Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
MachinaOs - Visual Workflow Automation Platform
trohitg2ff55bc71a50
diff --git a/.env.template b/.env.templatenew file mode 100644index 00000000..1c1347dd--- /dev/null+++ b/.env.template@@ -0,0 +1,4 @@+# Port Configuration+VITE_CLIENT_PORT=3000+PYTHON_BACKEND_PORT=3010+WHATSAPP_RPC_PORT=9400diff --git a/.github/workflows/npm-publish-github-packages.yml b/.github/workflows/npm-publish-github-packages.ymlnew file mode 100644index 00000000..ea2d329f--- /dev/null+++ b/.github/workflows/npm-publish-github-packages.yml@@ -0,0 +1,36 @@+# This workflow will run tests using node and then publish a package to GitHub Packages when a release is created+# For more information see: https://docs.github.com/en/actions/publishing-packages/publishing-nodejs-packages++name: Node.js Package++on:+ release:+ types: [created]++jobs:+ build:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: 20+ - run: npm ci+ - run: npm test++ publish-gpr:+ needs: build+ runs-on: ubuntu-latest+ permissions:+ contents: read+ packages: write+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: 20+ registry-url: https://npm.pkg.github.com/+ - run: npm ci+ - run: npm publish+ env:+ NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}}diff --git a/.gitignore b/.gitignorenew file mode 100644index 00000000..16008366--- /dev/null+++ b/.gitignore@@ -0,0 +1,126 @@+# Logs+logs+*.log+npm-debug.log*+yarn-debug.log*+yarn-error.log*+pnpm-debug.log*+lerna-debug.log*++node_modules+dist+dist-ssr+*.local++# =============================================================================+# SECURITY - Credentials and Secrets (NEVER COMMIT)+# =============================================================================+# Environment variables (contain API keys, secrets)+.env+.env.*+!.env.template+!.env.example+server/.env+server/.env.*+!server/.env.template+!server/.env.example++# API Keys and Credentials+**/credentials.json+**/secrets.json+**/apikeys.json+**/*.pem+**/*.key+**/*.crt+**/*.p12+**/*.pfx++# WhatsApp session data (contains auth tokens)+server/whatsapp-rpc/.wwebjs_*+server/whatsapp-rpc/.wwebjs_auth/+server/whatsapp-rpc/session/+server/whatsapp-rpc/*.db+server/whatsapp-rpc/data/+server/whatsapp-rpc/bin/+server/whatsapp-rpc/*.exe+server/whatsapp-rpc/qr_*.png++# =============================================================================+# Database files (may contain sensitive user data)+# =============================================================================+*.db+*.sqlite+*.sqlite3+*.db-journal+*.db-shm+*.db-wal+server/api/db/+server/*.db+server/data/++# =============================================================================+# Editor and IDE+# =============================================================================+.vscode/*+!.vscode/extensions.json+!.vscode/settings.json+.idea+*.suo+*.ntvs*+*.njsproj+*.sln+*.sw?++# =============================================================================+# OS and System files+# =============================================================================+.DS_Store+Thumbs.db+*.pyc+__pycache__/++# Backup files+*.bak+*.backup+*~++# Windows reserved files+nul+NUL++# =============================================================================+# Build artifacts+# =============================================================================+build/+*.exe+*.dll+*.so+*.dylib++# =============================================================================+# Python+# =============================================================================+.venv/+venv/+*.egg-info/+.eggs/++# =============================================================================+# Temporary and cache files+# =============================================================================+*.tmp+*.temp+.cache/+*.cache++# =============================================================================+# Claude Code configuration+# =============================================================================+.claude/+CLAUDE.md+**/CLAUDE.md++# =============================================================================+# Documentation (keep local only)+# =============================================================================+docs/diff --git a/LICENSE b/LICENSEnew file mode 100644index 00000000..61d58c50--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2025 MachinaOs++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.md b/README.mdnew file mode 100644index 00000000..997c2789--- /dev/null+++ b/README.md@@ -0,0 +1,84 @@+# MachinaOs++Visual workflow automation platform. Build workflows by connecting nodes - like n8n or Zapier.++## Quick Start++**Prerequisites:** Node.js 18+, Python 3.10+++```bash+# 1. Clone and install+git clone https://github.com/user/MachinaOs.git+cd MachinaOs+npm run build++# 2. Setup config+cp server/.env.template server/.env++# 3. Run+npm run dev+```++Open http://localhost:3000 and register your account.++---++## What You Can Build++- **AI Workflows** - Connect OpenAI, Claude, Gemini models+- **Android Automation** - Control your phone (battery, WiFi, apps, sensors)+- **WhatsApp Bots** - Send/receive messages, auto-replies+- **HTTP/Webhooks** - API integrations, triggers++## How It Works++1. Drag nodes onto canvas+2. Connect them together+3. Configure each node+4. Click Run++## Commands++| Command | Description |+|---------|-------------|+| `npm run dev` | Start development server |+| `npm run build` | Install all dependencies |+| `npm run stop` | Stop all services |++## Project Structure++```+MachinaOs/+├── client/ # React frontend (localhost:3000)+├── server/ # Python backend (localhost:3010)+│ └── whatsapp-rpc/ # WhatsApp service+└── package.json+```++## Configuration++Edit `server/.env` for:+- API keys (OpenAI, Google Maps, etc.)+- Authentication settings+- Database location++API keys can also be added through the UI (click the key icon).++---++## Docker Deployment++```bash+npm run docker:build+npm run docker:up+```++## Tech Stack++- **Frontend:** React, TypeScript, React Flow+- **Backend:** Python, FastAPI, SQLite+- **Services:** WhatsApp (Go), WebSocket relay++## License++MITdiff --git a/client/.dockerignore b/client/.dockerignorenew file mode 100644index 00000000..620e8ff0--- /dev/null+++ b/client/.dockerignore@@ -0,0 +1,45 @@+# Dependencies+node_modules/++# Build output+dist/+build/++# IDE+.vscode/+.idea/+*.swp+*.swo++# Logs+*.log+npm-debug.log*+yarn-debug.log*+yarn-error.log*++# Environment+.env+.env.*+!.env.example++# Git+.git/+.gitignore++# Documentation+*.md+!README.md++# Test+coverage/+__tests__/+*.test.ts+*.test.tsx+*.spec.ts+*.spec.tsx++# TypeScript cache+*.tsbuildinfo++# ESLint cache+.eslintcachediff --git a/client/Dockerfile b/client/Dockerfilenew file mode 100644index 00000000..cd2d8570--- /dev/null+++ b/client/Dockerfile@@ -0,0 +1,53 @@+# React Frontend (Vite)+# Development stage+FROM node:22-alpine AS development++WORKDIR /app++# Copy package files+COPY package.json package-lock.json* ./++# Install dependencies+RUN npm install++# Copy application code+COPY . .++# Expose port+EXPOSE 3001++# Run development server with host binding+CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0", "--port", "3001"]++# Build stage+FROM node:22-alpine AS builder++WORKDIR /app++# Copy package files+COPY package.json package-lock.json* ./++# Install dependencies+RUN npm install++# Copy application code+COPY . .++# Increase Node.js memory limit for large builds (GCP e2-micro has limited RAM)+ENV NODE_OPTIONS="--max-old-space-size=2048"++# Build for production+RUN npm run build++# Production stage+FROM nginx:alpine AS production++# Copy built assets+COPY --from=builder /app/dist /usr/share/nginx/html++# Copy nginx config+COPY nginx.conf /etc/nginx/conf.d/default.conf++EXPOSE 80++CMD ["nginx", "-g", "daemon off;"]diff --git a/client/eslint.config.js b/client/eslint.config.jsnew file mode 100644index 00000000..cee1e2c7--- /dev/null+++ b/client/eslint.config.js@@ -0,0 +1,29 @@+import js from '@eslint/js'+import globals from 'globals'+import reactHooks from 'eslint-plugin-react-hooks'+import reactRefresh from 'eslint-plugin-react-refresh'+import { defineConfig, globalIgnores } from 'eslint/config'++export default defineConfig([+ globalIgnores(['dist']),+ {+ files: ['**/*.{js,jsx}'],+ extends: [+ js.configs.recommended,+ reactHooks.configs['recommended-latest'],+ reactRefresh.configs.vite,+ ],+ languageOptions: {+ ecmaVersion: 2020,+ globals: globals.browser,+ parserOptions: {+ ecmaVersion: 'latest',+ ecmaFeatures: { jsx: true },+ sourceType: 'module',+ },+ },+ rules: {+ 'no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]' }],+ },+ },+])diff --git a/client/index.html b/client/index.htmlnew file mode 100644index 00000000..e55c9690--- /dev/null+++ b/client/index.html@@ -0,0 +1,13 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <link rel="icon" type="image/svg+xml" href="/vite.svg" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>React Flow Project</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/src/main.tsx"></script>+ </body>+</html>diff --git a/client/nginx.conf b/client/nginx.confnew file mode 100644index 00000000..f98b87db--- /dev/null+++ b/client/nginx.conf@@ -0,0 +1,66 @@+server {+ listen 80;+ server_name localhost;+ root /usr/share/nginx/html;+ index index.html;++ # Gzip compression+ gzip on;+ gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;++ # Security headers+ add_header X-Content-Type-Options "nosniff" always;+ add_header X-Frame-Options "SAMEORIGIN" always;++ # Handle SPA routing+ location / {+ try_files $uri $uri/ /index.html;+ }++ # Proxy API requests to backend+ location /api/ {+ proxy_pass http://backend:3010/api/;+ proxy_http_version 1.1;+ proxy_set_header Upgrade $http_upgrade;+ proxy_set_header Connection 'upgrade';+ proxy_set_header Host $host;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_cache_bypass $http_upgrade;+ }++ # Proxy webhook requests to backend+ location /webhook/ {+ proxy_pass http://backend:3010/webhook/;+ proxy_http_version 1.1;+ proxy_set_header Host $host;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme;+ }++ # Proxy WebSocket requests+ location /ws/ {+ proxy_pass http://backend:3010/ws/;+ proxy_http_version 1.1;+ proxy_set_header Upgrade $http_upgrade;+ proxy_set_header Connection "Upgrade";+ proxy_set_header Host $host;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_read_timeout 86400;+ }++ # Health check endpoint+ location /health {+ proxy_pass http://backend:3010/health;+ proxy_http_version 1.1;+ proxy_set_header Host $host;+ }++ # Cache static assets+ location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {+ expires 1y;+ add_header Cache-Control "public, immutable";+ }+}diff --git a/client/package.json b/client/package.jsonnew file mode 100644index 00000000..f1a95bb5--- /dev/null+++ b/client/package.json@@ -0,0 +1,53 @@+{+ "name": "react-flow-client",+ "private": true,+ "version": "0.0.0",+ "type": "module",+ "scripts": {+ "dev": "vite",+ "build": "vite build",+ "lint": "eslint .",+ "preview": "vite preview"+ },+ "dependencies": {+ "@ant-design/icons": "^6.0.2",+ "@langchain/anthropic": "^0.3.28",+ "@langchain/google-genai": "^0.1.0",+ "@langchain/openai": "^0.6.12",+ "@lobehub/icons": "^2.45.0",+ "@radix-ui/react-collapsible": "^1.1.12",+ "@radix-ui/react-dialog": "^1.1.15",+ "@types/styled-components": "^5.1.34",+ "ai": "^5.0.35",+ "antd": "^5.27.4",+ "dexie": "^4.2.0",+ "openai": "^5.19.1",+ "prismjs": "^1.30.0",+ "react": "^19.1.1",+ "react-dom": "^19.1.1",+ "react-js-cron": "^5.2.0",+ "react-simple-code-editor": "^0.14.1",+ "react-use": "^17.6.0",+ "reactflow": "^11.11.4",+ "styled-components": "^6.1.19",+ "zustand": "^5.0.8"+ },+ "devDependencies": {+ "@eslint/js": "^9.33.0",+ "@types/google.maps": "^3.58.1",+ "@types/node": "^24.3.1",+ "@types/prismjs": "^1.26.5",+ "@types/react": "^19.1.10",+ "@types/react-dom": "^19.1.7",+ "@vitejs/plugin-react": "^5.0.0",+ "autoprefixer": "^10.4.21",+ "eslint": "^9.33.0",+ "eslint-plugin-react-hooks": "^7.0.1",+ "eslint-plugin-react-refresh": "^0.4.20",+ "globals": "^16.3.0",+ "postcss": "^8.5.6",+ "tailwindcss": "^4.1.13",+ "typescript": "^5.9.2",+ "vite": "^7.1.2"+ }+}diff --git a/client/src/App.tsx b/client/src/App.tsxnew file mode 100644index 00000000..353c3895--- /dev/null+++ b/client/src/App.tsx@@ -0,0 +1,27 @@+import React from 'react';+import { ConfigProvider, theme as antdThemeAlgorithm } from 'antd';+import Dashboard from './Dashboard';+import ProtectedRoute from './components/auth/ProtectedRoute';+import { lightTheme, darkTheme } from './config/antdTheme';+import { useTheme } from './contexts/ThemeContext';++const App: React.FC = () => {+ const { isDarkMode } = useTheme();++ const currentTheme = isDarkMode ? {+ ...darkTheme,+ algorithm: antdThemeAlgorithm.darkAlgorithm,+ } : lightTheme;++ return (+ <ConfigProvider theme={currentTheme}>+ <ProtectedRoute>+ <div style={{ width: '100vw', height: '100vh', display: 'flex' }}>+ <Dashboard />+ </div>+ </ProtectedRoute>+ </ConfigProvider>+ );+}++export default Appdiff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsxnew file mode 100644index 00000000..fa98316b--- /dev/null+++ b/client/src/Dashboard.tsx@@ -0,0 +1,1103 @@+import React, { useEffect } from 'react';+import {+ ReactFlow,+ ReactFlowProvider,+ Controls,+ useNodesState,+ useEdgesState,+ useReactFlow,+ ConnectionMode,+ ConnectionLineType,+ SelectionMode,+ Node,+ Edge,+} from 'reactflow';+import GenericNode from './components/GenericNode';+import AIAgentNode from './components/AIAgentNode';+import ModelNode from './components/ModelNode';+import SquareNode from './components/SquareNode';+import TriggerNode from './components/TriggerNode';+import ConditionalEdge from './components/ConditionalEdge';+import NodeContextMenu from './components/ui/NodeContextMenu';+import { nodeDefinitions } from './nodeDefinitions';+import { ANDROID_SERVICE_NODE_TYPES } from './nodeDefinitions/androidServiceNodes';+import { ANDROID_DEVICE_NODE_TYPES } from './nodeDefinitions/androidDeviceNodes';+import { SCHEDULER_NODE_TYPES } from './nodeDefinitions/schedulerNodes';+import { CHAT_NODE_TYPES } from './nodeDefinitions/chatNodes';+import { CODE_NODE_TYPES } from './nodeDefinitions/codeNodes';+import { UTILITY_NODE_TYPES } from './nodeDefinitions/utilityNodes';+import ParameterPanel from './ParameterPanel';+import LocationParameterPanel from './components/LocationParameterPanel';+import { useAppStore } from './store/useAppStore';+import ComponentPalette from './components/ui/ComponentPalette';+import TopToolbar from './components/ui/TopToolbar';+import WorkflowSidebar from './components/ui/WorkflowSidebar';+import SettingsPanel, { WorkflowSettings, defaultSettings } from './components/ui/SettingsPanel';+import WhatsAppSettingsPanel from './components/ui/WhatsAppSettingsPanel';+import AndroidSettingsPanel from './components/ui/AndroidSettingsPanel';+import AIResultModal from './components/ui/AIResultModal';+import CredentialsModal from './components/CredentialsModal';+import ErrorBoundary from './components/ui/ErrorBoundary';+import { useAppTheme } from './hooks/useAppTheme';+import { useWorkflowManagement } from './hooks/useWorkflowManagement';+import { useDragAndDrop } from './hooks/useDragAndDrop';+import { useComponentPalette } from './hooks/useComponentPalette';+import { useReactFlowNodes } from './hooks/useReactFlowNodes';+import { useCopyPaste } from './hooks/useCopyPaste';+import { useWebSocket } from './contexts/WebSocketContext';+import { useTheme } from './contexts/ThemeContext';+import {+ sanitizeNodesForComparison,+ sanitizeEdgesForComparison+} from './utils/workflow';++import 'reactflow/dist/style.css';++// Node types configuration - defined outside component to prevent recreation on re-renders+// This is required by React Flow to avoid performance issues+const createNodeTypes = (): Record<string, React.ComponentType<any>> => {+ const types: Record<string, React.ComponentType<any>> = {};++ // Trigger nodes (no input handles) - check by group or specific types+ const TRIGGER_NODE_TYPES = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive'];++ Object.keys(nodeDefinitions).forEach(type => {+ const definition = nodeDefinitions[type];++ // Trigger nodes - no input connections (start workflows)+ if (TRIGGER_NODE_TYPES.includes(type)) {+ types[type] = TriggerNode;+ } else if (type === 'openaiChatModel' || type === 'anthropicChatModel' || type === 'geminiChatModel') {+ // AI chat model nodes use square design+ types[type] = SquareNode;+ } else if (type === 'aiAgent') {+ types[type] = AIAgentNode;+ } else if (type === 'simpleMemory') {+ // Simple Memory node for AI conversation history - uses circular ModelNode design+ types[type] = ModelNode;+ } else if (type === 'whatsappConnect' || type === 'whatsappSend') {+ // WhatsApp action nodes use SquareNode (whatsappReceive is a trigger)+ types[type] = SquareNode;+ } else if (ANDROID_SERVICE_NODE_TYPES.includes(type) || ANDROID_DEVICE_NODE_TYPES.includes(type)) {+ // Android service and device nodes use SquareNode component+ types[type] = SquareNode;+ } else if (SCHEDULER_NODE_TYPES.includes(type)) {+ // Timer uses SquareNode (has input), cronScheduler already handled as trigger above+ types[type] = SquareNode;+ } else if (CHAT_NODE_TYPES.includes(type)) {+ // Chat nodes use SquareNode component+ types[type] = SquareNode;+ } else if (CODE_NODE_TYPES.includes(type)) {+ // Code execution nodes use SquareNode component+ types[type] = SquareNode;+ } else if (UTILITY_NODE_TYPES.includes(type)) {+ // Utility nodes (HTTP, Webhooks) use SquareNode component+ // Note: webhookTrigger is already handled as trigger above+ types[type] = SquareNode;+ } else if (definition?.group?.includes('model')) {+ // Fallback for other model nodes+ types[type] = ModelNode;+ } else if (definition?.group?.includes('service')) {+ // Any node with 'service' group uses SquareNode component+ types[type] = SquareNode;+ } else {+ types[type] = GenericNode;+ }+ });++ return types;+};++// Create node types once at module load time+const moduleNodeTypes = createNodeTypes();++// Edge types configuration - enables conditional edge rendering+const moduleEdgeTypes = {+ conditional: ConditionalEdge,+};++// Edge styles generator using theme colors - supports light and dark modes+const getEdgeStyles = (colors: {+ edgeDefault: string;+ edgeSelected: string;+ edgeExecuting: string;+ edgeCompleted: string;+ edgeError: string;+}, isDark: boolean) => `+ /* Base style for ALL edges */+ .react-flow__edge path {+ stroke: ${colors.edgeDefault} !important;+ stroke-width: 2px;+ }++ .react-flow__edge.selected path {+ stroke: ${colors.edgeSelected} !important;+ stroke-width: 4px !important;+ }++ /* Executing edge - subtle blue in light mode, cyan in dark mode */+ .react-flow__edge.executing path {+ stroke: ${isDark ? colors.edgeExecuting : '#2563eb'} !important;+ stroke-width: 3px !important;+ stroke-dasharray: 8 4;+ animation: dashFlow 0.5s linear infinite;+ }++ /* Completed edge - subtle green in both modes */+ .react-flow__edge.completed path {+ stroke: ${isDark ? colors.edgeCompleted : '#16a34a'} !important;+ stroke-width: 2px !important;+ }++ /* Error edge - keep red for visibility */+ .react-flow__edge.error path {+ stroke: ${colors.edgeError} !important;+ stroke-width: 3px !important;+ }++ /* Pending edge - animated dash in both modes */+ .react-flow__edge.pending path {+ stroke: ${isDark ? colors.edgeDefault : '#6b7280'} !important;+ stroke-width: 2px !important;+ stroke-dasharray: 8 4;+ animation: dashFlow 0.5s linear infinite;+ }++ /* Memory connection active */+ .react-flow__edge.memory-active path {+ stroke: ${isDark ? '#ff79c6' : '#db2777'} !important;+ stroke-width: 3px !important;+ }++ /* Tool connection active */+ .react-flow__edge.tool-active path {+ stroke: ${isDark ? '#ffb86c' : '#ea580c'} !important;+ stroke-width: 3px !important;+ }++ @keyframes dashFlow {+ 0% { stroke-dashoffset: 24; }+ 100% { stroke-dashoffset: 0; }+ }++ /* Executing node - visible glow in both modes */+ .react-flow__node.executing {+ filter: ${isDark+ ? `drop-shadow(0 0 8px ${colors.edgeExecuting}) drop-shadow(0 0 16px ${colors.edgeExecuting}80)`+ : 'drop-shadow(0 0 10px rgba(37, 99, 235, 0.8)) drop-shadow(0 0 20px rgba(37, 99, 235, 0.6))'};+ animation: ${isDark ? 'nodeGlowDark' : 'nodeGlowLight'} 1.2s ease-in-out infinite;+ }++ @keyframes nodeGlowDark {+ 0%, 100% {+ filter: drop-shadow(0 0 8px ${colors.edgeExecuting}) drop-shadow(0 0 16px ${colors.edgeExecuting}80);+ }+ 50% {+ filter: drop-shadow(0 0 14px ${colors.edgeExecuting}) drop-shadow(0 0 24px ${colors.edgeExecuting});+ }+ }++ @keyframes nodeGlowLight {+ 0%, 100% {+ filter: drop-shadow(0 0 10px rgba(37, 99, 235, 0.8)) drop-shadow(0 0 20px rgba(37, 99, 235, 0.6));+ }+ 50% {+ filter: drop-shadow(0 0 16px rgba(37, 99, 235, 1)) drop-shadow(0 0 30px rgba(37, 99, 235, 0.8));+ }+ }+`;++const initialNodes: Node[] = [];+const initialEdges: Edge[] = [];++// Inner component that uses useReactFlow() - must be inside ReactFlowProvider+const DashboardContent: React.FC = () => {+ const theme = useAppTheme();+ const { isDarkMode } = useTheme();+ const {+ currentWorkflow,+ hasUnsavedChanges,+ savedWorkflows,+ sidebarVisible,+ componentPaletteVisible,+ updateWorkflow,+ loadSavedWorkflows,+ createNewWorkflow,+ deleteWorkflow,+ migrateCurrentWorkflow,+ toggleSidebar,+ toggleComponentPalette,+ exportWorkflowToJSON,+ exportWorkflowToFile,+ setCurrentWorkflow,+ whatsappSettingsOpen,+ setWhatsAppSettingsOpen,+ androidSettingsOpen,+ setAndroidSettingsOpen,+ selectedNode,+ setSelectedNode,+ renamingNodeId,+ setRenamingNodeId,+ // Per-workflow UI state (n8n pattern)+ setWorkflowExecuting,+ setWorkflowExecutionOrder,+ setWorkflowViewport,+ clearWorkflowExecutionState,+ } = useAppStore();++ // ReactFlow state management (local state for performance)+ const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);+ const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);++ // ReactFlow instance for viewport control (n8n pattern - per-workflow viewport)+ const reactFlowInstance = useReactFlow();++ // AI execution state - result and modal are local, execution tracking is per-workflow+ const [executionResult, setExecutionResult] = React.useState<any>(null);+ const [showResult, setShowResult] = React.useState(false);++ // Get per-workflow execution state (n8n pattern - isolated per workflow)+ // Subscribe to workflowUIStates directly so Zustand triggers re-renders when it changes+ const workflowUIStates = useAppStore(state => state.workflowUIStates);+ const workflowUIState = React.useMemo(() => {+ if (!currentWorkflow?.id) return null;+ return workflowUIStates[currentWorkflow.id] || { isExecuting: false, executedNodes: [], executionOrder: [], selectedNodeId: null };+ }, [workflowUIStates, currentWorkflow?.id]);+ const isExecuting = workflowUIState?.isExecuting || false;+ const executedNodes = React.useMemo(() => new Set(workflowUIState?.executedNodes || []), [workflowUIState?.executedNodes]);+ const executionOrder = workflowUIState?.executionOrder || [];+ // Custom hooks for different concerns+ const {+ handleWorkflowNameChange,+ handleSave,+ handleNew,+ handleOpen,+ handleSelectWorkflow,+ } = useWorkflowManagement();++ const { collapsedSections, searchQuery, setSearchQuery, toggleSection } = useComponentPalette();+ const { saveNodeParameters, getAllNodeParameters, executeWorkflow, deployWorkflow, cancelDeployment, nodeStatuses, deploymentStatus, workflowLock, isConnected } = useWebSocket();++ // Scope deployment and lock to current workflow (n8n pattern)+ // Only show as "running" or "locked" if it applies to the currently viewed workflow+ const isCurrentWorkflowDeployed = deploymentStatus.isRunning &&+ deploymentStatus.workflow_id === currentWorkflow?.id;+ const isCurrentWorkflowLocked = workflowLock.locked &&+ workflowLock.workflow_id === currentWorkflow?.id;+ const { onDragOver, onDrop, handleComponentDragStart } = useDragAndDrop({ nodes, setNodes, saveNodeParameters });+ const { onConnect, onNodesDelete, onEdgesDelete } = useReactFlowNodes({ setNodes, setEdges });+ const { copySelectedNodes, pasteNodes } = useCopyPaste({ nodes, edges, setNodes, setEdges, saveNodeParameters });++ // Toggle disabled state on selected nodes+ const toggleDisableSelected = React.useCallback(() => {+ setNodes(nds => nds.map(node => {+ if (node.selected) {+ return {+ ...node,+ data: {+ ...node.data,+ disabled: !node.data?.disabled,+ },+ };+ }+ return node;+ }));+ }, [setNodes]);++ // Note: executedNodes and executionOrder are now derived from per-workflow state above++ // Settings state with localStorage persistence+ const [settings, setSettings] = React.useState<WorkflowSettings>(() => {+ try {+ const saved = localStorage.getItem('workflow_settings');+ return saved ? { ...defaultSettings, ...JSON.parse(saved) } : defaultSettings;+ } catch {+ return defaultSettings;+ }+ });+ const [settingsOpen, setSettingsOpen] = React.useState(false);+ const [credentialsOpen, setCredentialsOpen] = React.useState(false);++ // Context menu state for node right-click+ const [contextMenu, setContextMenu] = React.useState<{+ nodeId: string;+ x: number;+ y: number;+ } | null>(null);++ // Persist settings to localStorage+ React.useEffect(() => {+ localStorage.setItem('workflow_settings', JSON.stringify(settings));+ }, [settings]);++ // Update nodes with execution status classes+ const styledNodes = React.useMemo(() => {+ return nodes.map(node => {+ const nodeStatus = nodeStatuses[node.id];+ let className = '';++ if (nodeStatus?.status === 'executing' || nodeStatus?.status === 'waiting') {+ className = 'executing';+ } else if (nodeStatus?.status === 'success') {+ className = 'completed';+ } else if (nodeStatus?.status === 'error') {+ className = 'error';+ } else if (isExecuting && executionOrder.includes(node.id) && !executedNodes.has(node.id)) {+ className = 'pending';+ }++ return {+ ...node,+ className+ };+ });+ }, [nodes, nodeStatuses, isExecuting, executionOrder, executedNodes]);++ // Update edges with execution status classes+ const styledEdges = React.useMemo(() => {+ return edges.map(edge => {+ const sourceStatus = nodeStatuses[edge.source];+ const targetStatus = nodeStatuses[edge.target];+ const targetNode = nodes.find(n => n.id === edge.target);++ let className = '';++ // Check if this edge connects to an AI Agent's memory or tools handle+ const isMemoryConnection = edge.targetHandle === 'input-memory';+ const isToolConnection = edge.targetHandle === 'input-tools';+ const isAIAgentTarget = targetNode?.type === 'aiAgent';++ // Highlight memory/tool connections when AI Agent is executing and using them+ if (isAIAgentTarget && targetStatus?.status === 'executing') {+ const phase = targetStatus?.data?.phase as string | undefined;+ const hasMemory = targetStatus?.data?.has_memory;++ // Memory connection highlights during memory phases+ if (isMemoryConnection && hasMemory) {+ if (phase === 'loading_memory' || phase === 'memory_loaded' || phase === 'saving_memory') {+ className = 'memory-active';+ } else if (phase === 'invoking_llm') {+ // Keep memory edge highlighted during LLM invocation to show context is being used+ className = 'memory-active';+ }+ }+ // Tool connection highlights during tool-related phases+ else if (isToolConnection) {+ if (phase === 'invoking_llm' || phase === 'building_graph') {+ className = 'tool-active';+ }+ }+ }++ // Standard edge status classes - ONLY apply during active execution or deployment+ // When not executing/deploying, all edges should have the same default cyan color+ const isActiveExecution = isExecuting || isCurrentWorkflowDeployed;+ if (!className && isActiveExecution) {+ const srcStatus = sourceStatus?.status;+ const tgtStatus = targetStatus?.status;++ // Edge is executing if target is currently executing (data flowing into it)+ if (tgtStatus === 'executing') {+ className = 'executing';+ }+ // Edge is completed if both source and target are successful during this execution+ else if (srcStatus === 'success' && tgtStatus === 'success') {+ className = 'completed';+ }+ // Edge has error if target has error+ else if (tgtStatus === 'error') {+ className = 'error';+ }+ // Edge shows data flowing when source completed and target is waiting for inputs+ // This indicates data has been produced and is available to the target+ else if (srcStatus === 'success' && tgtStatus === 'waiting') {+ className = 'executing';+ }+ // Edge is pending if source completed but target hasn't started+ else if (srcStatus === 'success' && !tgtStatus) {+ className = 'pending';+ }+ // Edge is pending if source is waiting (hasn't produced output yet)+ // This keeps downstream edges from glowing until source completes+ else if (srcStatus === 'waiting') {+ className = 'pending';+ }+ }++ return {+ ...edge,+ className+ };+ });+ }, [edges, nodeStatuses, isExecuting, isCurrentWorkflowDeployed, nodes]);++ // Memoize ReactFlow options to prevent unnecessary re-renders+ const defaultEdgeOptions = React.useMemo(() => ({+ type: 'smoothstep',+ animated: true,+ style: { stroke: theme.dracula.cyan, strokeWidth: 3 },+ }), [theme.dracula.cyan]);++ const connectionLineStyle = React.useMemo(() => ({+ stroke: theme.dracula.cyan,+ strokeWidth: 2+ }), [theme.dracula.cyan]);++ const reactFlowStyle = React.useMemo(() => ({+ width: '100%',+ height: '100%',+ backgroundColor: theme.colors.background,+ }), [theme.colors.background]);++ const snapGrid: [number, number] = React.useMemo(() => [20, 20], []);++ const proOptions = React.useMemo(() => ({ hideAttribution: true }), []);++ // Use useRef for nodeTypes to guarantee the same object reference across all renders+ // including React.StrictMode's double-render cycle. useMemo can't guarantee this+ // because it may run during both render cycles.+ const nodeTypesRef = React.useRef(moduleNodeTypes);+ const edgeTypesRef = React.useRef(moduleEdgeTypes);++ // Execute entire workflow from start node to end+ const handleRun = async () => {+ if (!currentWorkflow) return;+ const workflowId = currentWorkflow.id;++ // Use per-workflow state setters (n8n pattern)+ setWorkflowExecuting(workflowId, true);+ setExecutionResult(null);+ clearWorkflowExecutionState(workflowId);+ setWorkflowExecuting(workflowId, true); // Re-set after clear++ try {+ // Check if there's a start node+ const startNode = nodes.find(node => node.type === 'start');+ if (!startNode) {+ alert('No Start node found in workflow.\n\nAdd a Start node to begin workflow execution.');+ setWorkflowExecuting(workflowId, false);+ return;+ }++ // Build execution order for visual feedback (BFS from start node)+ const buildOrder = () => {+ const order: string[] = [];+ const visited = new Set<string>();+ const queue = [startNode.id];+ const adjacencyMap = new Map<string, string[]>();++ edges.forEach(edge => {+ const sources = adjacencyMap.get(edge.source) || [];+ sources.push(edge.target);+ adjacencyMap.set(edge.source, sources);+ });++ while (queue.length > 0) {+ const currentId = queue.shift()!;+ if (visited.has(currentId)) continue;+ visited.add(currentId);+ order.push(currentId);++ const connected = adjacencyMap.get(currentId) || [];+ connected.forEach(id => {+ if (!visited.has(id)) queue.push(id);+ });+ }+ return order;+ };++ const order = buildOrder();+ setWorkflowExecutionOrder(workflowId, order);++ console.log('[Workflow Run] Starting workflow execution with', nodes.length, 'nodes and', edges.length, 'edges');+ console.log('[Workflow Run] Execution order:', order);++ // Execute the entire workflow via WebSocket+ const workflowResult = await executeWorkflow(nodes, edges);++ console.log('[Workflow Run] Execution complete:', workflowResult);++ // Build result for display+ const result = {+ success: workflowResult.success,+ nodeId: 'workflow',+ nodeName: currentWorkflow.name || 'Workflow',+ timestamp: new Date().toISOString(),+ executionTime: workflowResult.execution_time || 0,+ outputs: workflowResult.node_results || {},+ data: workflowResult,+ error: workflowResult.error || (workflowResult.errors?.length > 0 ? workflowResult.errors[0].error : undefined),+ nodeData: workflowResult,+ // Workflow-specific display data+ nodesExecuted: workflowResult.nodes_executed || [],+ executionOrder: workflowResult.execution_order || [],+ totalNodes: workflowResult.total_nodes || 0,+ completedNodes: workflowResult.completed_nodes || 0,+ nodeResults: workflowResult.node_results || {},+ errors: workflowResult.errors || [],+ // For backwards compatibility with AI result modal+ response: workflowResult.success+ ? `Workflow executed successfully. ${workflowResult.completed_nodes}/${workflowResult.total_nodes} nodes completed.`+ : `Workflow failed: ${workflowResult.error || 'Unknown error'}`,+ model: 'workflow'+ };++ // Set result and show modal+ setExecutionResult(result);+ setShowResult(true);++ } catch (error: any) {+ console.error('Workflow execution error:', error);++ // Create error result for modal display+ const errorResult = {+ success: false,+ nodeId: 'workflow',+ nodeName: currentWorkflow?.name || 'Workflow',+ timestamp: new Date().toISOString(),+ executionTime: 0,+ error: error.message || 'Unknown execution error',+ response: `Error: ${error.message}`,+ model: 'workflow'+ };++ setExecutionResult(errorResult);+ setShowResult(true);+ } finally {+ setWorkflowExecuting(workflowId, false);+ }+ };++ // Deploy workflow - runs continuously until cancelled+ const handleDeploy = async () => {+ if (!currentWorkflow) return;++ // Check if there's at least one trigger node (workflow entry points)+ // Trigger types: start, cronScheduler, webhookTrigger, whatsappReceive, workflowTrigger+ const triggerTypes = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive', 'workflowTrigger'];+ const hasTriggerNode = nodes.some(node => triggerTypes.includes(node.type || ''));+ if (!hasTriggerNode) {+ alert('No trigger node found in workflow.\n\nAdd a trigger node (Cron Scheduler, WhatsApp Receive, Webhook, etc.) to begin deployment.');+ return;+ }++ try {+ console.log('[Dashboard] Starting deployment (using backend stored settings)');++ // Settings are already synced to backend via WebSocket from SettingsPanel+ // Backend will use the stored settings+ const result = await deployWorkflow(currentWorkflow.id, nodes, edges, 'default');++ if (!result.success) {+ console.error('[Dashboard] Deployment failed to start:', result.error);+ alert(`Failed to start deployment: ${result.error}`);+ } else {+ console.log('[Dashboard] Deployment started successfully');+ }+ } catch (error: any) {+ console.error('[Dashboard] Deployment error:', error);+ alert(`Deployment error: ${error.message}`);+ }+ };++ // Cancel running deployment for current workflow+ const handleCancelDeployment = async () => {+ try {+ const workflowId = currentWorkflow?.id;+ console.log('[Dashboard] Cancelling deployment for workflow:', workflowId);+ const result = await cancelDeployment(workflowId);++ if (result.success) {+ console.log('[Dashboard] Deployment cancelled:', result);+ } else {+ console.error('[Dashboard] Failed to cancel deployment:', result.message);+ }+ } catch (error: any) {+ console.error('[Dashboard] Cancel deployment error:', error);+ }+ };++ const handleExportJSON = async () => {+ try {+ const jsonString = exportWorkflowToJSON();+ await navigator.clipboard.writeText(jsonString);+ alert('Workflow JSON copied to clipboard');+ } catch (error) {+ console.error('Export JSON error:', error);+ alert('Failed to export workflow JSON');+ }+ };++ const handleExportFile = () => {+ try {+ exportWorkflowToFile();+ } catch (error) {+ console.error('Export file error:', error);+ alert('Failed to export workflow file');+ }+ };++ const handleImportJSON = () => {+ const fileInput = document.createElement('input');+ fileInput.type = 'file';+ fileInput.accept = '.json';+ fileInput.onchange = async (e) => {+ try {+ const file = (e.target as HTMLInputElement).files?.[0];+ if (!file) return;++ const { importWorkflowFromFile } = await import('./utils/workflowExport');+ const { generateWorkflowId } = await import('./utils/workflow');+ const importedWorkflow = await importWorkflowFromFile(file);++ const workflow = {+ ...importedWorkflow,+ id: generateWorkflowId(),+ createdAt: new Date(),+ lastModified: new Date()+ };++ console.log('Importing workflow:', workflow);++ for (const node of workflow.nodes) {+ if (node.data && Object.keys(node.data).length > 0) {+ try {+ await saveNodeParameters(node.id, node.data);+ console.log(`Saved parameters for node ${node.id}:`, node.data);+ } catch (error) {+ console.error(`Failed to save parameters for node ${node.id}:`, error);+ }+ }+ }++ setCurrentWorkflow(workflow);++ console.log('Workflow imported successfully');+ alert(`Workflow "${workflow.name}" imported with ${workflow.nodes.length} nodes and ${workflow.edges.length} connections`);+ } catch (error: any) {+ console.error('Import error:', error);+ alert(`Failed to import workflow: ${error.message}`);+ }+ };+ fileInput.click();+ };+ // Load saved workflows on mount and create default workflow if needed+ const hasMigrated = React.useRef(false);+ useEffect(() => {+ console.log('[Dashboard] Mount effect - loading workflows', {+ hasCurrentWorkflow: !!currentWorkflow,+ currentWorkflowId: currentWorkflow?.id,+ });+ loadSavedWorkflows();+ if (!currentWorkflow) {+ console.log('[Dashboard] No current workflow, creating new one');+ createNewWorkflow();+ } else if (!hasMigrated.current) {+ console.log('[Dashboard] Migrating current workflow');+ migrateCurrentWorkflow();+ hasMigrated.current = true;+ }+ }, [loadSavedWorkflows, currentWorkflow, createNewWorkflow, migrateCurrentWorkflow]);++ // Sync workflow state → ReactFlow state (when loading workflows or data changes)+ // Note: Database is the source of truth for parameters - node.data should NOT store parameters+ // Parameters are loaded from database when parameter panel opens (useParameterPanel hook)+ // and when backend executes nodes (NodeExecutor._prepare_parameters)+ useEffect(() => {+ if (currentWorkflow && currentWorkflow.id) {+ const workflowNodes = currentWorkflow.nodes || [];+ setNodes(workflowNodes);+ setEdges(currentWorkflow.edges || []);+ // Do NOT sync database parameters to node.data+ // Database is the single source of truth for parameters+ // This prevents dual storage issues where node.data could diverge from database+ }+ }, [currentWorkflow?.id, currentWorkflow?.lastModified, setNodes, setEdges]);++ // Sync ReactFlow state → workflow state (debounced for performance)+ useEffect(() => {+ if (!currentWorkflow || !currentWorkflow.id) return;++ const timeoutId = setTimeout(() => {+ try {+ const currentNodesStr = JSON.stringify(sanitizeNodesForComparison(nodes));+ const currentEdgesStr = JSON.stringify(sanitizeEdgesForComparison(edges));+ const workflowNodesStr = JSON.stringify(sanitizeNodesForComparison(currentWorkflow.nodes || []));+ const workflowEdgesStr = JSON.stringify(sanitizeEdgesForComparison(currentWorkflow.edges || []));++ if (currentNodesStr !== workflowNodesStr || currentEdgesStr !== workflowEdgesStr) {+ updateWorkflow({ nodes, edges });+ }+ } catch (error) {+ console.warn('Failed to sync workflow state:', error);+ }+ }, theme.constants.debounceDelay.workflowUpdate);++ return () => clearTimeout(timeoutId);+ }, [nodes, edges, currentWorkflow?.id, updateWorkflow]);++ // Track previous workflow ID for viewport save/restore (n8n pattern)+ const prevWorkflowIdRef = React.useRef<string | null>(null);+ // Track if we've already restored viewport for current workflow (prevent duplicate restores)+ const viewportRestoredForRef = React.useRef<string | null>(null);++ // Save viewport when switching workflows, restore after nodes load (n8n pattern)+ useEffect(() => {+ const currentId = currentWorkflow?.id;+ const prevId = prevWorkflowIdRef.current;++ // Save viewport of previous workflow before switching+ if (prevId && prevId !== currentId) {+ try {+ const viewport = reactFlowInstance.getViewport();+ setWorkflowViewport(prevId, viewport);+ } catch {+ // Failed to save viewport - ignore+ }+ // Reset the restored flag when switching to new workflow+ viewportRestoredForRef.current = null;+ }++ prevWorkflowIdRef.current = currentId || null;+ }, [currentWorkflow?.id, reactFlowInstance, setWorkflowViewport]);++ // Restore viewport AFTER nodes are loaded and rendered+ // Only restores saved viewport - never auto-centers+ useEffect(() => {+ const currentId = currentWorkflow?.id;+ if (!currentId) return;++ // Skip if we already restored viewport for this workflow+ if (viewportRestoredForRef.current === currentId) {+ return;+ }++ // Get saved viewport from store+ const uiState = workflowUIStates[currentId];+ const savedViewport = uiState?.viewport;++ // Only restore if we have a saved viewport+ if (!savedViewport) {+ viewportRestoredForRef.current = currentId;+ return;+ }++ // Use delay to ensure ReactFlow has finished rendering nodes+ const timeoutId = setTimeout(() => {+ try {+ reactFlowInstance.setViewport(savedViewport, { duration: 0 });+ viewportRestoredForRef.current = currentId;+ } catch {+ // Viewport restore failed - ignore silently+ }+ }, 100);++ return () => clearTimeout(timeoutId);+ }, [currentWorkflow?.id, nodes.length, workflowUIStates, reactFlowInstance]);++ // Node context menu handler (right-click)+ const onNodeContextMenu = React.useCallback(+ (event: React.MouseEvent, node: Node) => {+ event.preventDefault();+ // Select the node when right-clicking+ setSelectedNode(node);+ setContextMenu({+ nodeId: node.id,+ x: event.clientX,+ y: event.clientY,+ });+ },+ [setSelectedNode]+ );++ // Close context menu+ const closeContextMenu = React.useCallback(() => {+ setContextMenu(null);+ }, []);++ // Context menu actions+ const handleContextMenuRename = React.useCallback(() => {+ if (contextMenu) {+ setRenamingNodeId(contextMenu.nodeId);+ }+ closeContextMenu();+ }, [contextMenu, setRenamingNodeId, closeContextMenu]);++ const handleContextMenuCopy = React.useCallback(() => {+ if (contextMenu) {+ // Select the node first, then copy+ const node = nodes.find(n => n.id === contextMenu.nodeId);+ if (node) {+ setNodes(nds => nds.map(n => ({ ...n, selected: n.id === contextMenu.nodeId })));+ // Small delay to ensure selection is applied before copy+ setTimeout(() => copySelectedNodes(), 0);+ }+ }+ closeContextMenu();+ }, [contextMenu, nodes, setNodes, copySelectedNodes, closeContextMenu]);++ const handleContextMenuDelete = React.useCallback(() => {+ if (contextMenu) {+ onNodesDelete([nodes.find(n => n.id === contextMenu.nodeId)].filter(Boolean) as Node[]);+ }+ closeContextMenu();+ }, [contextMenu, nodes, onNodesDelete, closeContextMenu]);++ // Keyboard shortcut handler for workflow operations+ useEffect(() => {+ const handleKeyDown = (event: KeyboardEvent) => {+ // Ignore shortcuts when typing in input/textarea+ if (event.target instanceof HTMLInputElement ||+ event.target instanceof HTMLTextAreaElement) {+ return;+ }++ // Ignore shortcuts when renaming a node+ if (renamingNodeId) {+ return;+ }++ // F2 to rename selected node+ if (event.key === 'F2' && selectedNode) {+ event.preventDefault();+ setRenamingNodeId(selectedNode.id);+ return;+ }++ // Check for Ctrl/Cmd key shortcuts+ if (event.ctrlKey || event.metaKey) {+ switch (event.key.toLowerCase()) {+ case 's':+ event.preventDefault();+ handleSave();+ break;+ case 'c':+ event.preventDefault();+ copySelectedNodes();+ break;+ case 'v':+ event.preventDefault();+ pasteNodes();+ break;+ }+ } else {+ // Non-modifier shortcuts+ switch (event.key.toLowerCase()) {+ case 'd':+ // Toggle disable on selected nodes+ event.preventDefault();+ toggleDisableSelected();+ break;+ }+ }+ };++ document.addEventListener('keydown', handleKeyDown);++ return () => {+ document.removeEventListener('keydown', handleKeyDown);+ };+ }, [handleSave, copySelectedNodes, pasteNodes, toggleDisableSelected, selectedNode, renamingNodeId, setRenamingNodeId]);++ return (+ <>+ <style>{getEdgeStyles(theme.colors, isDarkMode)}</style>+ <div style={{+ width: '100%',+ height: '100vh',+ display: 'flex',+ flexDirection: 'column',+ backgroundColor: theme.colors.background,+ fontFamily: 'system-ui, sans-serif',+ }}>+ {/* Top Toolbar */}+ <TopToolbar+ workflowName={currentWorkflow?.name || 'Untitled Workflow'}+ onWorkflowNameChange={handleWorkflowNameChange}+ onSave={handleSave}+ onNew={handleNew}+ onOpen={handleOpen}+ onRun={handleRun}+ isRunning={isExecuting}+ onDeploy={handleDeploy}+ onCancelDeployment={handleCancelDeployment}+ isDeploying={isCurrentWorkflowDeployed}+ hasUnsavedChanges={hasUnsavedChanges}+ sidebarVisible={sidebarVisible}+ onToggleSidebar={toggleSidebar}+ componentPaletteVisible={componentPaletteVisible}+ onToggleComponentPalette={toggleComponentPalette}+ onOpenSettings={() => setSettingsOpen(true)}+ onOpenCredentials={() => setCredentialsOpen(true)}+ onExportJSON={handleExportJSON}+ onExportFile={handleExportFile}+ onImportJSON={handleImportJSON}+ />++ {/* Main Content Area */}+ <div style={{+ flex: 1,+ display: 'flex',+ overflow: 'hidden',+ }}>+ {/* Left Workflow Sidebar */}+ <div style={{+ width: sidebarVisible ? '280px' : '0px',+ overflow: 'hidden',+ transition: 'width 0.3s ease',+ borderRight: sidebarVisible ? `1px solid ${theme.colors.border}` : 'none',+ display: 'flex',+ flexDirection: 'column',+ }}>+ {sidebarVisible && (+ <WorkflowSidebar+ workflows={savedWorkflows}+ currentWorkflowId={currentWorkflow?.id}+ onSelectWorkflow={handleSelectWorkflow}+ onDeleteWorkflow={deleteWorkflow}+ />+ )}+ </div>++ {/* Canvas Area */}+ <div style={{+ flex: 1,+ display: 'flex',+ position: 'relative',+ }}>+ <div style={{+ flex: 1,+ backgroundColor: theme.colors.backgroundAlt,+ }}>+ <ErrorBoundary>+ <ReactFlow+ nodes={styledNodes}+ edges={styledEdges}+ onNodesChange={onNodesChange}+ onEdgesChange={onEdgesChange}+ onNodesDelete={onNodesDelete}+ onEdgesDelete={onEdgesDelete}+ onConnect={onConnect}+ onDragOver={onDragOver}+ onDrop={onDrop}+ onNodeContextMenu={onNodeContextMenu}+ nodeTypes={nodeTypesRef.current}+ edgeTypes={edgeTypesRef.current}+ connectionMode={ConnectionMode.Loose}+ deleteKeyCode={isCurrentWorkflowLocked ? [] : ['Delete', 'Backspace']}+ edgesFocusable={!isCurrentWorkflowLocked}+ edgesUpdatable={!isCurrentWorkflowLocked}+ nodesDraggable={!isCurrentWorkflowLocked}+ nodesConnectable={!isCurrentWorkflowLocked}+ nodesFocusable={!isCurrentWorkflowLocked}+ elementsSelectable={!isCurrentWorkflowLocked}+ selectNodesOnDrag={false}+ selectionOnDrag={true}+ selectionMode={SelectionMode.Partial}+ selectionKeyCode="Control"+ panOnDrag={true}+ panOnScroll={false}+ zoomOnScroll={true}+ preventScrolling={true}+ proOptions={proOptions}+ defaultEdgeOptions={defaultEdgeOptions}+ connectionLineStyle={connectionLineStyle}+ connectionLineType={ConnectionLineType.SmoothStep}+ snapToGrid={true}+ snapGrid={snapGrid}+ style={reactFlowStyle}+ >+ <Controls />+ </ReactFlow>+ </ErrorBoundary>+ </div>++ {/* Right Component Palette */}+ <div style={{+ width: componentPaletteVisible ? theme.layout.sidebarWidth : '0px',+ overflow: 'hidden',+ transition: 'width 0.3s ease',+ borderLeft: componentPaletteVisible ? `1px solid ${theme.colors.border}` : 'none',+ display: 'flex',+ flexDirection: 'column',+ }}>+ {componentPaletteVisible && (+ <ComponentPalette+ nodeDefinitions={nodeDefinitions}+ searchQuery={searchQuery}+ onSearchChange={setSearchQuery}+ collapsedSections={collapsedSections}+ onToggleSection={toggleSection}+ onDragStart={handleComponentDragStart}+ />+ )}+ </div>+ </div>+ </div>++ {/* Parameter Panels */}+ <ErrorBoundary>+ <ParameterPanel />+ <LocationParameterPanel />+ </ErrorBoundary>++ {/* AI Result Modal */}+ <AIResultModal+ isOpen={showResult}+ onClose={() => setShowResult(false)}+ result={executionResult}+ />++ {/* Settings Panel Modal */}+ <SettingsPanel+ isOpen={settingsOpen}+ onClose={() => setSettingsOpen(false)}+ settings={settings}+ onSettingsChange={setSettings}+ />++ {/* WhatsApp Settings Panel Modal */}+ <WhatsAppSettingsPanel+ isOpen={whatsappSettingsOpen}+ onClose={() => setWhatsAppSettingsOpen(false)}+ />++ {/* Android Settings Panel Modal */}+ <AndroidSettingsPanel+ isOpen={androidSettingsOpen}+ onClose={() => setAndroidSettingsOpen(false)}+ />++ {/* Credentials Modal */}+ <CredentialsModal+ visible={credentialsOpen}+ onClose={() => setCredentialsOpen(false)}+ />++ {/* Node Context Menu (right-click) */}+ {contextMenu && (+ <NodeContextMenu+ nodeId={contextMenu.nodeId}+ x={contextMenu.x}+ y={contextMenu.y}+ onClose={closeContextMenu}+ onRename={handleContextMenuRename}+ onCopy={handleContextMenuCopy}+ onDelete={handleContextMenuDelete}+ />+ )}+ </div>+ </>+ );+};++// Outer wrapper component that provides ReactFlowProvider context+const Dashboard: React.FC = () => {+ return (+ <ReactFlowProvider>+ <DashboardContent />+ </ReactFlowProvider>+ );+};++export default Dashboard;\ No newline at end of filediff --git a/client/src/ParameterPanel.tsx b/client/src/ParameterPanel.tsxnew file mode 100644index 00000000..f5eb307b--- /dev/null+++ b/client/src/ParameterPanel.tsx@@ -0,0 +1,301 @@+import React from 'react';+import Modal from './components/ui/Modal';+import ParameterPanelLayout from './components/parameterPanel/ParameterPanelLayout';+import { useParameterPanel } from './hooks/useParameterPanel';+import { useAppStore } from './store/useAppStore';+import { useWebSocket } from './contexts/WebSocketContext';+import { ExecutionService, ExecutionResult } from './services/executionService';+import { useAppTheme } from './hooks/useAppTheme';+import { ScheduleOutlined, PlayCircleFilled } from '@ant-design/icons';++const ParameterPanel: React.FC = () => {+ const theme = useAppTheme();+ const {+ selectedNode,+ nodeDefinition,+ parameters,+ hasUnsavedChanges,+ handleParameterChange,+ handleSave,+ handleCancel,+ isLoading,+ } = useParameterPanel();++ const { currentWorkflow } = useAppStore();+ const { executeNode, getNodeParameters, clearNodeStatus, cancelEventWait, getNodeStatus } = useWebSocket();++ // Get current node status to check if waiting+ const nodeStatus = selectedNode ? getNodeStatus(selectedNode.id) : null;+ const isWaiting = nodeStatus?.status === 'waiting';++ // Execution state+ const [isExecuting, setIsExecuting] = React.useState(false);+ const [executionResults, setExecutionResults] = React.useState<ExecutionResult[]>([]);+++ const handleModalClose = () => {+ handleCancel();+ };++ // Execute the current node+ const handleRun = async () => {+ if (!selectedNode || !nodeDefinition) return;++ // Save parameters first if there are unsaved changes+ if (hasUnsavedChanges) {+ await handleSave();+ }++ setIsExecuting(true);++ try {++ // Get current workflow nodes and edges from app store+ const nodes = currentWorkflow?.nodes || [];+ const edges = currentWorkflow?.edges || [];++ // Execute node via WebSocket+ const result: ExecutionResult = await ExecutionService.executeNodeViaWebSocket(+ selectedNode.id,+ nodeDefinition.name,+ executeNode,+ getNodeParameters,+ nodes,+ edges+ );++ // Debug logging+ console.log('[ParameterPanel] Execution result:', result);+ console.log('[ParameterPanel] Result nodeId:', result.nodeId);+ console.log('[ParameterPanel] Result outputs:', result.outputs);+ console.log('[ParameterPanel] Selected node id:', selectedNode.id);++ // Add result to the beginning of the array (newest first)+ setExecutionResults(prev => [result, ...prev]);++ } catch (error: any) {+ console.error('Execution failed:', error);++ // Add error result+ const errorResult: ExecutionResult = {+ success: false,+ nodeId: selectedNode.id,+ nodeType: nodeDefinition.name,+ nodeName: nodeDefinition.displayName,+ timestamp: new Date().toISOString(),+ executionTime: 0,+ error: error.message || 'Unknown execution error',+ nodeData: [[{+ json: {+ error: error.message || 'Unknown execution error',+ nodeId: selectedNode.id,+ success: false,+ timestamp: new Date().toISOString()+ }+ }]]+ };++ setExecutionResults(prev => [errorResult, ...prev]);+ } finally {+ setIsExecuting(false);+ }+ };++ // Clear execution results (both local state and WebSocket nodeStatuses)+ const handleClearResults = () => {+ setExecutionResults([]);+ // Also clear the node status from WebSocket context+ if (selectedNode) {+ clearNodeStatus(selectedNode.id);+ }+ };+++ // Check if node can be executed+ const canExecute = selectedNode && nodeDefinition &&+ ExecutionService.isNodeTypeSupported(nodeDefinition.name);++ // Check if this is a Start node (only show middle section)+ const isStartNode = nodeDefinition?.name === 'start';++ if (!selectedNode || !nodeDefinition) {+ return null;+ }++++ // Helper to render icon (handles image URLs, Ant Design icons, and emoji/text)+ const renderIcon = (icon: string) => {+ // Handle Ant Design icon names+ if (icon === 'schedule') {+ return <ScheduleOutlined style={{ fontSize: 20, color: theme.colors.actionDeploy }} />;+ }+ if (icon === 'play' || nodeDefinition?.name === 'start') {+ return <PlayCircleFilled style={{ fontSize: 20, color: theme.dracula.cyan }} />;+ }+ // Handle image URLs+ if (icon.startsWith('data:') || icon.startsWith('http') || icon.startsWith('/')) {+ return (+ <img+ src={icon}+ alt="icon"+ style={{ width: 20, height: 20, objectFit: 'contain' }}+ />+ );+ }+ return <span>{icon}</span>;+ };++ // Action button style helper - Dracula theme for visibility+ const actionButtonStyle = (color: string, isDisabled = false): React.CSSProperties => ({+ height: '32px',+ padding: '0 14px',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ backgroundColor: isDisabled ? `${theme.colors.primary}15` : `${color}25`,+ color: isDisabled ? theme.colors.primary : color,+ border: `1px solid ${isDisabled ? `${theme.colors.primary}40` : `${color}60`}`,+ borderRadius: theme.borderRadius.sm,+ fontSize: '13px',+ fontWeight: 600,+ cursor: isDisabled ? 'not-allowed' : 'pointer',+ transition: `all ${theme.transitions.fast}`,+ fontFamily: 'system-ui, sans-serif',+ });++ // Header actions with node name and buttons in middle area+ const headerActions = (+ <div style={{+ display: 'flex',+ gap: '16px',+ alignItems: 'center'+ }}>+ {/* Node Name */}+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ fontSize: '15px',+ fontWeight: 600,+ color: theme.colors.text,+ fontFamily: 'system-ui, sans-serif'+ }}>+ {renderIcon(nodeDefinition.icon)}+ <span>{nodeDefinition.displayName}</span>+ {hasUnsavedChanges && <span style={{ color: theme.accent.orange }}>*</span>}+ </div>++ {/* Buttons: Run, Save, Cancel */}+ <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>+ {/* Run Button */}+ {canExecute && (+ <button+ style={actionButtonStyle(theme.dracula.green, isExecuting)}+ onClick={handleRun}+ disabled={isExecuting}+ title={isExecuting ? 'Execution in progress...' : 'Execute this node'}+ onMouseEnter={(e) => {+ if (!isExecuting) {+ e.currentTarget.style.backgroundColor = `${theme.dracula.green}40`;+ }+ }}+ onMouseLeave={(e) => {+ if (!isExecuting) {+ e.currentTarget.style.backgroundColor = `${theme.dracula.green}25`;+ }+ }}+ >+ <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">+ <path d="M8 5v14l11-7z"/>+ </svg>+ {isExecuting ? 'Running...' : 'Run'}+ </button>+ )}++ {/* Save Button */}+ <button+ style={actionButtonStyle(theme.dracula.purple, !hasUnsavedChanges)}+ onClick={handleSave}+ disabled={!hasUnsavedChanges}+ onMouseEnter={(e) => {+ if (hasUnsavedChanges) {+ e.currentTarget.style.backgroundColor = `${theme.dracula.purple}40`;+ }+ }}+ onMouseLeave={(e) => {+ if (hasUnsavedChanges) {+ e.currentTarget.style.backgroundColor = `${theme.dracula.purple}25`;+ }+ }}+ >+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">+ <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/>+ <polyline points="17 21 17 13 7 13 7 21"/>+ <polyline points="7 3 7 8 15 8"/>+ </svg>+ Save+ </button>++ {/* Cancel/Stop Button */}+ <button+ style={actionButtonStyle(theme.dracula.pink, false)}+ onClick={async () => {+ if (isWaiting && selectedNode) {+ // Cancel the event wait for trigger nodes - don't close modal, let execution complete+ console.log('[ParameterPanel] Cancelling event wait:', {+ nodeId: selectedNode.id,+ waiterId: nodeStatus?.data?.waiter_id,+ nodeStatus+ });+ const result = await cancelEventWait(selectedNode.id, nodeStatus?.data?.waiter_id);+ console.log('[ParameterPanel] Cancel result:', result);+ // Don't call handleCancel() - let the execution complete with cancelled state+ return;+ }+ handleCancel();+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = `${theme.dracula.pink}40`;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = `${theme.dracula.pink}25`;+ }}+ >+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">+ <line x1="18" y1="6" x2="6" y2="18"/>+ <line x1="6" y1="6" x2="18" y2="18"/>+ </svg>+ {isWaiting ? 'Stop' : 'Cancel'}+ </button>+ </div>+ </div>+ );++ return (+ <Modal+ isOpen={!!selectedNode}+ onClose={handleModalClose}+ title="Node Configuration"+ maxWidth="95vw"+ maxHeight="95vh"+ headerActions={headerActions}+ >+ {/* Modular Three Panel Layout */}+ <ParameterPanelLayout+ selectedNode={selectedNode}+ nodeDefinition={nodeDefinition}+ parameters={parameters}+ hasUnsavedChanges={hasUnsavedChanges}+ onParameterChange={handleParameterChange}+ executionResults={executionResults}+ onClearResults={handleClearResults}+ showInputSection={!isStartNode}+ showOutputSection={!isStartNode}+ isLoadingParameters={isLoading}+ />+ </Modal>+ );+};++export default ParameterPanel;\ No newline at end of filediff --git a/client/src/components/AIAgentNode.tsx b/client/src/components/AIAgentNode.tsxnew file mode 100644index 00000000..5806b2f9--- /dev/null+++ b/client/src/components/AIAgentNode.tsx@@ -0,0 +1,319 @@+import React, { useState, useEffect } from 'react';+import { Handle, Position, NodeProps } from 'reactflow';+import { NodeData } from '../types/NodeTypes';+import { useAppStore } from '../store/useAppStore';+import AIAgentExecutionService from '../services/execution/aiAgentExecutionService';+import { useAppTheme } from '../hooks/useAppTheme';+import { useNodeStatus } from '../contexts/WebSocketContext';++// LangGraph phase icons and labels+const PHASE_CONFIG: Record<string, { icon: string; label: string; color: string }> = {+ initializing: { icon: '⚡', label: 'Initializing', color: '#8be9fd' },+ loading_memory: { icon: '💾', label: 'Loading Memory', color: '#bd93f9' },+ memory_loaded: { icon: '✓', label: 'Memory Ready', color: '#50fa7b' },+ building_graph: { icon: '🔗', label: 'Building Graph', color: '#ffb86c' },+ invoking_llm: { icon: '🧠', label: 'Thinking...', color: '#ff79c6' },+ saving_memory: { icon: '💾', label: 'Saving Memory', color: '#bd93f9' },+};++const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectable, selected }) => {+ const theme = useAppTheme();+ const { setSelectedNode } = useAppStore();+ const [_configValid, setConfigValid] = useState(true);+ const [_configErrors, setConfigErrors] = useState<string[]>([]);++ // Get real-time node status from WebSocket+ const nodeStatus = useNodeStatus(id);+ const isExecuting = nodeStatus?.status === 'executing';+ const currentPhase = nodeStatus?.data?.phase as string | undefined;+ const phaseConfig = currentPhase ? PHASE_CONFIG[currentPhase] : null;++ // Validate AI Agent configuration whenever data changes+ useEffect(() => {+ try {+ const validation = AIAgentExecutionService.validateConfiguration(data || {});+ setConfigValid(validation.valid);+ setConfigErrors(validation.errors);++ if (!validation.valid) {+ console.warn(`AI Agent ${id} configuration issues:`, validation.errors);+ }+ } catch (error) {+ console.error('Configuration validation error:', error);+ setConfigValid(false);+ setConfigErrors(['Configuration validation failed']);+ }+ }, [data, id]);++ const handleParametersClick = (e: React.MouseEvent) => {+ e.stopPropagation();+ setSelectedNode({ id, type, data, position: { x: 0, y: 0 } });+ };++ // Determine border and glow based on execution state+ const getBorderColor = () => {+ if (isExecuting) {+ if (theme.isDarkMode && phaseConfig) return phaseConfig.color;+ // Light mode - use consistent blue+ return '#2563eb';+ }+ if (selected) return theme.colors.focus;+ return theme.colors.border;+ };++ const getBoxShadow = () => {+ if (isExecuting) {+ if (theme.isDarkMode && phaseConfig) {+ return `0 0 20px ${phaseConfig.color}80, 0 0 40px ${phaseConfig.color}40`;+ }+ // Light mode - use consistent blue+ return `0 0 0 3px rgba(37, 99, 235, 0.5), 0 4px 16px rgba(37, 99, 235, 0.35)`;+ }+ if (selected) {+ return `0 4px 12px ${theme.colors.focusRing}, 0 0 0 1px ${theme.colors.focusRing}`;+ }+ return `0 2px 4px ${theme.colors.shadow}`;+ };++ return (+ <div+ style={{+ position: 'relative',+ padding: theme.spacing.lg,+ minWidth: '180px',+ minHeight: '120px',+ borderRadius: theme.borderRadius.lg,+ background: theme.colors.background,+ border: `2px solid ${getBorderColor()}`,+ color: theme.colors.text,+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,+ textAlign: 'center',+ cursor: 'pointer',+ transition: 'all 0.3s ease',+ boxShadow: getBoxShadow(),+ overflow: 'visible',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ gap: theme.spacing.sm,+ animation: isExecuting ? 'pulse 1.5s ease-in-out infinite' : 'none'+ }}+ >++ {/* Input Handle */}+ <Handle+ id="input-main"+ type="target"+ position={Position.Left}+ isConnectable={isConnectable}+ style={{+ position: 'absolute',+ left: '-6px',+ top: '50%',+ transform: 'translateY(-50%)',+ width: theme.nodeSize.handle,+ height: theme.nodeSize.handle,+ backgroundColor: theme.colors.background,+ border: `2px solid ${theme.colors.textSecondary}`,+ borderRadius: '50%'+ }}+ title="Main Input"+ />++ {/* Parameters Button */}+ <button+ onClick={handleParametersClick}+ style={{+ position: 'absolute',+ top: theme.spacing.xs,+ right: theme.spacing.xs,+ width: theme.nodeSize.paramButton,+ height: theme.nodeSize.paramButton,+ borderRadius: theme.borderRadius.sm,+ backgroundColor: theme.colors.backgroundAlt,+ border: `1px solid ${theme.colors.border}`,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ fontSize: theme.fontSize.xs,+ color: theme.colors.textSecondary,+ fontWeight: theme.fontWeight.normal,+ transition: theme.transitions.fast,+ zIndex: 20+ }}+ title="Edit Parameters"+ >+ ⚙️+ </button>++ {/* Status Indicator - Top Left */}+ <div+ style={{+ position: 'absolute',+ top: theme.spacing.xs,+ left: theme.spacing.xs,+ width: '10px',+ height: '10px',+ borderRadius: '50%',+ backgroundColor: isExecuting+ ? (theme.isDarkMode ? (phaseConfig?.color || theme.dracula.cyan) : theme.dracula.cyan)+ : (nodeStatus?.status === 'success' ? theme.dracula.green+ : nodeStatus?.status === 'error' ? theme.dracula.red+ : theme.colors.textSecondary),+ boxShadow: isExecuting+ ? (theme.isDarkMode+ ? `0 0 8px ${phaseConfig?.color || theme.dracula.cyan}`+ : '0 0 4px rgba(37, 99, 235, 0.5)')+ : 'none',+ animation: isExecuting ? 'pulse 1s ease-in-out infinite' : 'none',+ zIndex: 20+ }}+ title={isExecuting ? (phaseConfig?.label || 'Executing') : (nodeStatus?.status || 'Idle')}+ />++ {/* Robot Icon */}+ <div style={{+ fontSize: theme.iconSize.xl,+ lineHeight: '1',+ marginBottom: theme.spacing.xs+ }}>+ 🤖+ </div>++ {/* AI Agent Text */}+ <div style={{+ fontSize: theme.fontSize.base,+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.text,+ lineHeight: '1.2',+ marginBottom: theme.spacing.xs+ }}>+ AI Agent+ </div>++ {/* Subtitle - shows execution phase or default */}+ <div style={{+ fontSize: theme.fontSize.xs,+ fontWeight: theme.fontWeight.normal,+ color: isExecuting && phaseConfig ? phaseConfig.color : theme.colors.focus,+ lineHeight: '1.2',+ marginBottom: theme.spacing.lg,+ transition: 'color 0.3s ease'+ }}>+ {isExecuting && phaseConfig ? phaseConfig.label : 'LangGraph Agent'}+ </div>++ {/* Memory Info Badge - shows when loading/using memory */}+ {isExecuting && nodeStatus?.data?.has_memory && (+ <div style={{+ position: 'absolute',+ top: '-8px',+ left: '50%',+ transform: 'translateX(-50%)',+ backgroundColor: theme.dracula.purple,+ color: '#fff',+ fontSize: '10px',+ padding: '2px 8px',+ borderRadius: '10px',+ whiteSpace: 'nowrap',+ boxShadow: `0 0 8px ${theme.dracula.purple}80`,+ animation: 'pulse 1s ease-in-out infinite',+ zIndex: 30+ }}>+ {nodeStatus?.data?.history_count !== undefined+ ? `Memory: ${nodeStatus.data.history_count} msgs`+ : 'Using Memory'}+ </div>+ )}++ {/* Parameter Labels */}+ <div style={{+ position: 'absolute',+ bottom: theme.spacing.lg,+ left: '0',+ right: '0',+ display: 'flex',+ justifyContent: 'space-around',+ fontSize: theme.fontSize.xs,+ color: theme.colors.textSecondary,+ fontWeight: theme.fontWeight.normal+ }}>+ <span>Memory</span>+ <span>Tool</span>+ </div>++ {/* Parameter Handles */}+ <Handle+ id="input-memory"+ type="target"+ position={Position.Bottom}+ isConnectable={isConnectable}+ style={{+ position: 'absolute',+ bottom: '-6px',+ left: '35%',+ width: theme.nodeSize.handle,+ height: theme.nodeSize.handle,+ backgroundColor: isExecuting && nodeStatus?.data?.has_memory+ ? theme.dracula.purple+ : theme.colors.background,+ border: `2px solid ${isExecuting && nodeStatus?.data?.has_memory+ ? theme.dracula.purple+ : theme.colors.textSecondary}`,+ borderRadius: '0',+ transform: 'translateX(-50%) rotate(45deg)',+ boxShadow: isExecuting && nodeStatus?.data?.has_memory+ ? `0 0 10px ${theme.dracula.purple}`+ : 'none',+ transition: 'all 0.3s ease'+ }}+ title="Memory"+ />++ <Handle+ id="input-tools"+ type="target"+ position={Position.Bottom}+ isConnectable={isConnectable}+ style={{+ position: 'absolute',+ bottom: '-6px',+ left: '65%',+ width: theme.nodeSize.handle,+ height: theme.nodeSize.handle,+ backgroundColor: theme.colors.background,+ border: `2px solid ${theme.colors.textSecondary}`,+ borderRadius: '0',+ transform: 'translateX(-50%) rotate(45deg)'+ }}+ title="Tools"+ />++ {/* Output Handles */}+ <Handle+ id="output-main"+ type="source"+ position={Position.Right}+ isConnectable={isConnectable}+ style={{+ position: 'absolute',+ right: '-6px',+ top: '50%',+ transform: 'translateY(-50%)',+ width: theme.nodeSize.handle,+ height: theme.nodeSize.handle,+ backgroundColor: theme.colors.background,+ border: `2px solid ${theme.colors.textSecondary}`,+ borderRadius: '50%'+ }}+ title="Main Output"+ />++ </div>+ );+};++export default AIAgentNode;diff --git a/client/src/components/APIKeyValidator.tsx b/client/src/components/APIKeyValidator.tsxnew file mode 100644index 00000000..0dbbe7d5--- /dev/null+++ b/client/src/components/APIKeyValidator.tsx@@ -0,0 +1,118 @@+import React, { useEffect } from 'react';+import { Input, Button, Space, Tag, Tooltip } from 'antd';+import { CheckCircleOutlined, CloseCircleOutlined, LoadingOutlined, DeleteOutlined } from '@ant-design/icons';+import { useApiKeyValidation } from '../hooks/useApiKeyValidation';++interface APIKeyValidatorProps {+ value: string;+ onChange: (value: string) => void;+ placeholder?: string;+ validationConfig: {+ provider?: string;+ showValidateButton?: boolean;+ };+ onValidationSuccess?: (models: string[]) => void;+ isDragOver?: boolean;+ onDragOver?: (e: React.DragEvent) => void;+ onDragLeave?: (e: React.DragEvent) => void;+ onDrop?: (e: React.DragEvent) => void;+}++const APIKeyValidator: React.FC<APIKeyValidatorProps> = ({+ value,+ onChange,+ placeholder,+ validationConfig,+ onValidationSuccess,+ isDragOver = false,+ onDragOver,+ onDragLeave,+ onDrop+}) => {+ const { status, hasStoredKey, validate, clear, getStoredKey, isValidating, isValid } = useApiKeyValidation({+ provider: validationConfig.provider,+ onSuccess: onValidationSuccess+ });++ // Auto-load stored key on mount+ useEffect(() => {+ if (hasStoredKey && !value) {+ getStoredKey().then(storedKey => {+ if (storedKey) onChange(storedKey);+ });+ }+ }, [hasStoredKey, value, onChange, getStoredKey]);++ const handleValidate = () => validate(value);++ const handleClear = async () => {+ await clear();+ onChange('');+ };++ const getStatusIcon = () => {+ if (isValidating) return <LoadingOutlined />;+ if (isValid) return <CheckCircleOutlined style={{ color: '#52c41a' }} />;+ if (status === 'invalid') return <CloseCircleOutlined style={{ color: '#ff4d4f' }} />;+ return null;+ };++ const getStatusTag = () => {+ if (hasStoredKey && isValid) {+ return (+ <Tag color="success" icon={<CheckCircleOutlined />}>+ Validated+ </Tag>+ );+ }+ return null;+ };++ return (+ <Space direction="vertical" style={{ width: '100%' }} size="small">+ <Space.Compact style={{ width: '100%' }}>+ <Input.Password+ value={value}+ onChange={(e) => onChange(e.target.value)}+ placeholder={placeholder || 'Enter API key...'}+ onDragOver={onDragOver}+ onDragLeave={onDragLeave}+ onDrop={onDrop}+ suffix={getStatusIcon()}+ status={status === 'invalid' ? 'error' : undefined}+ style={{+ fontFamily: 'monospace',+ borderColor: isDragOver ? '#1890ff' : undefined,+ backgroundColor: isDragOver ? '#e6f7ff' : undefined+ }}+ />++ {validationConfig.showValidateButton && (+ <Button+ type={isValid ? 'primary' : 'default'}+ loading={isValidating}+ disabled={!value?.trim() || isValidating}+ onClick={handleValidate}+ >+ {isValidating ? 'Validating' : isValid ? 'Valid' : 'Validate'}+ </Button>+ )}++ {hasStoredKey && (+ <Tooltip title="Clear stored API key">+ <Button+ icon={<DeleteOutlined />}+ onClick={handleClear}+ type="text"+ size="small"+ />+ </Tooltip>+ )}+ </Space.Compact>++ {getStatusTag()}+ </Space>+ );+};++export default APIKeyValidator;\ No newline at end of filediff --git a/client/src/components/ClaudeChatModelNode.tsx b/client/src/components/ClaudeChatModelNode.tsxnew file mode 100644index 00000000..6220e061--- /dev/null+++ b/client/src/components/ClaudeChatModelNode.tsx@@ -0,0 +1,18 @@+import React from 'react';+import { NodeProps } from 'reactflow';+import { NodeData } from '../types/NodeTypes';+import BaseChatModelNode from './base/BaseChatModelNode';++const ClaudeChatModelNode: React.FC<NodeProps<NodeData>> = (props) => {+ return (+ <BaseChatModelNode+ {...props}+ providerId="anthropic"+ displayName="Claude"+ icon="🧠"+ color="#FF6B35"+ />+ );+};++export default ClaudeChatModelNode;\ No newline at end of filediff --git a/client/src/components/ConditionalEdge.tsx b/client/src/components/ConditionalEdge.tsxnew file mode 100644index 00000000..8d2b7cea--- /dev/null+++ b/client/src/components/ConditionalEdge.tsx@@ -0,0 +1,189 @@+/**+ * ConditionalEdge - Custom React Flow edge with condition label display+ *+ * Renders edges with visual indicators for conditional branching:+ * - Displays condition label as a badge on the edge+ * - Different styling for conditional vs unconditional edges+ * - Click-to-edit condition support+ */+import React, { useState, useCallback, memo } from 'react';+import {+ EdgeProps,+ getSmoothStepPath,+ EdgeLabelRenderer,+ BaseEdge,+} from 'reactflow';+import { useAppTheme } from '../hooks/useAppTheme';+import { ConditionalEdgeData, formatConditionLabel } from '../types/EdgeCondition';+import EdgeConditionEditor from './EdgeConditionEditor';++interface ConditionalEdgeProps extends EdgeProps<ConditionalEdgeData> {+ /** Callback when condition is updated */+ onConditionUpdate?: (+ edgeId: string,+ condition: ConditionalEdgeData['condition'],+ label: string | undefined+ ) => void;+}++const ConditionalEdge: React.FC<ConditionalEdgeProps> = ({+ id,+ sourceX,+ sourceY,+ targetX,+ targetY,+ sourcePosition,+ targetPosition,+ style = {},+ markerEnd,+ data,+ selected,+ onConditionUpdate,+}) => {+ const theme = useAppTheme();+ const [isEditorOpen, setIsEditorOpen] = useState(false);++ // Calculate edge path+ const [edgePath, labelX, labelY] = getSmoothStepPath({+ sourceX,+ sourceY,+ sourcePosition,+ targetX,+ targetY,+ targetPosition,+ borderRadius: 10,+ });++ const hasCondition = !!data?.condition;+ const displayLabel = data?.label || (hasCondition && data?.condition ? formatConditionLabel(data.condition) : null);++ const handleLabelClick = useCallback((e: React.MouseEvent) => {+ e.stopPropagation();+ setIsEditorOpen(true);+ }, []);++ const handleEditorClose = useCallback(() => {+ setIsEditorOpen(false);+ }, []);++ const handleConditionSave = useCallback(+ (condition: ConditionalEdgeData['condition'], label: string | undefined) => {+ if (onConditionUpdate) {+ onConditionUpdate(id, condition, label);+ }+ },+ [id, onConditionUpdate]+ );++ // Label badge style+ const labelBadgeStyle: React.CSSProperties = {+ position: 'absolute',+ transform: 'translate(-50%, -50%)',+ pointerEvents: 'all',+ cursor: 'pointer',+ padding: `${theme.spacing.xs} ${theme.spacing.sm}`,+ borderRadius: theme.borderRadius.sm,+ fontSize: theme.fontSize.xs,+ fontWeight: theme.fontWeight.medium,+ fontFamily: 'system-ui, sans-serif',+ backgroundColor: hasCondition+ ? `${theme.dracula.cyan}20`+ : theme.colors.backgroundPanel,+ border: `1px solid ${hasCondition ? `${theme.dracula.cyan}60` : theme.colors.border}`,+ color: hasCondition ? theme.dracula.cyan : theme.colors.textSecondary,+ whiteSpace: 'nowrap',+ maxWidth: '150px',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ boxShadow: selected ? `0 0 6px ${theme.dracula.purple}` : 'none',+ transition: theme.transitions.fast,+ };++ // Add condition button (shown when no condition)+ const addButtonStyle: React.CSSProperties = {+ position: 'absolute',+ transform: 'translate(-50%, -50%)',+ pointerEvents: 'all',+ cursor: 'pointer',+ width: '20px',+ height: '20px',+ borderRadius: '50%',+ backgroundColor: theme.colors.backgroundPanel,+ border: `1px dashed ${theme.colors.border}`,+ color: theme.colors.textMuted,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ fontSize: '14px',+ opacity: selected ? 1 : 0,+ transition: theme.transitions.fast,+ };++ return (+ <>+ <BaseEdge+ id={id}+ path={edgePath}+ markerEnd={markerEnd}+ style={{+ ...style,+ stroke: hasCondition ? theme.dracula.cyan : undefined,+ strokeWidth: hasCondition ? 2 : undefined,+ strokeDasharray: hasCondition ? '5 3' : undefined,+ }}+ />++ <EdgeLabelRenderer>+ {/* Condition label or add button */}+ {displayLabel ? (+ <div+ style={{+ ...labelBadgeStyle,+ left: labelX,+ top: labelY,+ }}+ onClick={handleLabelClick}+ title={`Click to edit condition: ${displayLabel}`}+ >+ <span style={{ marginRight: '4px' }}>+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <path d="M16 3h5v5"/>+ <path d="M8 3H3v5"/>+ <path d="M21 3l-7 7"/>+ <path d="M3 3l7 7"/>+ <path d="M3 21l7-7"/>+ <path d="M21 21l-7-7"/>+ <path d="M16 21h5v-5"/>+ <path d="M8 21H3v-5"/>+ </svg>+ </span>+ {displayLabel}+ </div>+ ) : (+ <div+ style={{+ ...addButtonStyle,+ left: labelX,+ top: labelY,+ }}+ onClick={handleLabelClick}+ title="Click to add condition"+ >+ ++ </div>+ )}+ </EdgeLabelRenderer>++ {/* Condition Editor Modal */}+ <EdgeConditionEditor+ isOpen={isEditorOpen}+ onClose={handleEditorClose}+ condition={data?.condition}+ label={data?.label}+ onSave={handleConditionSave}+ />+ </>+ );+};++export default memo(ConditionalEdge);diff --git a/client/src/components/CredentialsModal.tsx b/client/src/components/CredentialsModal.tsxnew file mode 100644index 00000000..eb505acf--- /dev/null+++ b/client/src/components/CredentialsModal.tsx@@ -0,0 +1,166 @@+/**+ * CredentialsModal - Manage API credentials globally+ */++import React, { useState, useEffect, useCallback } from 'react';+import { Form, Input, Button, Card, Tag, Space, message, Row, Col, Typography } from 'antd';+import { CheckCircleOutlined, DeleteOutlined, SafetyOutlined } from '@ant-design/icons';+import Modal from './ui/Modal';+import { useApiKeys } from '../hooks/useApiKeys';++const { Text } = Typography;++const PROVIDERS = [+ { id: 'openai', name: 'OpenAI', placeholder: 'sk-...', color: '#10a37f', desc: 'GPT-4o, GPT-4 Turbo, GPT-3.5' },+ { id: 'anthropic', name: 'Anthropic', placeholder: 'sk-ant-...', color: '#d97706', desc: 'Claude 3.5 Sonnet, Claude 3 Opus' },+ { id: 'gemini', name: 'Gemini', placeholder: 'AIza...', color: '#4285f4', desc: 'Gemini 1.5 Pro, Gemini Flash' },+ { id: 'google_maps', name: 'Google Maps', placeholder: 'AIza...', color: '#34a853', desc: 'Geocoding, Places API' },+ { id: 'android_remote', name: 'Android Remote', placeholder: 'your-api-key...', color: '#3ddc84', desc: 'Remote Android device via WebSocket' },+];++interface Props {+ visible: boolean;+ onClose: () => void;+}++const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {+ const { validateApiKey, saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey, validateGoogleMapsKey } = useApiKeys();+ const [form] = Form.useForm();+ const [validKeys, setValidKeys] = useState<Record<string, boolean>>({});+ const [loading, setLoading] = useState<Record<string, boolean>>({});+ const [models, setModels] = useState<Record<string, string[]>>({});++ const loadStoredKeys = useCallback(async () => {+ const fieldValues: Record<string, string> = {};+ const validResults: Record<string, boolean> = {};++ for (const p of PROVIDERS) {+ const has = await hasStoredKey(p.id);+ if (has) {+ const key = await getStoredApiKey(p.id);+ if (key) {+ fieldValues[p.id] = key;+ validResults[p.id] = true;+ }+ }+ }++ if (Object.keys(fieldValues).length > 0) {+ form.setFieldsValue(fieldValues);+ setValidKeys(validResults);+ }+ }, [form, hasStoredKey, getStoredApiKey]);++ useEffect(() => {+ if (visible) {+ loadStoredKeys();+ }+ }, [visible, loadStoredKeys]);++ const handleValidate = async (id: string) => {+ const key = form.getFieldValue(id);+ if (!key?.trim()) return message.warning('Enter an API key first');++ setLoading(l => ({ ...l, [id]: true }));++ let result;+ if (id === 'google_maps') {+ result = await validateGoogleMapsKey(key);+ } else if (id === 'android_remote') {+ // Android Remote key - save without validation (validated on connection)+ result = await saveApiKey(id, key);+ } else {+ result = await validateApiKey(id, key);+ }+ setLoading(l => ({ ...l, [id]: false }));++ if (result.isValid) {+ setValidKeys(v => ({ ...v, [id]: true }));+ if (result.models) setModels(m => ({ ...m, [id]: result.models! }));+ message.success(`${PROVIDERS.find(p => p.id === id)?.name} key saved${id === 'android_remote' ? '' : ' and validated'}`);+ } else {+ message.error(result.error || 'Invalid key');+ }+ };++ const handleRemove = async (id: string) => {+ await removeApiKey(id);+ form.setFieldValue(id, '');+ setValidKeys(v => ({ ...v, [id]: false }));+ setModels(m => ({ ...m, [id]: [] }));+ message.success('Key removed');+ };++ return (+ <Modal+ isOpen={visible}+ onClose={onClose}+ title="API Credentials"+ maxWidth="95vw"+ maxHeight="95vh"+ >+ <div style={{ padding: '24px' }}>+ <div style={{ marginBottom: 24 }}>+ <Space>+ <SafetyOutlined style={{ color: '#52c41a' }} />+ <Text type="secondary">+ API keys are validated and stored securely. They will be used automatically by AI nodes in your workflows.+ </Text>+ </Space>+ </div>++ <Form form={form} layout="vertical">+ <Row gutter={[24, 24]}>+ {PROVIDERS.map(p => (+ <Col xs={24} lg={12} key={p.id}>+ <Card+ title={+ <Space>+ <span style={{ color: p.color, fontWeight: 600 }}>{p.name}</span>+ {validKeys[p.id] && <Tag color="success" icon={<CheckCircleOutlined />}>Valid</Tag>}+ </Space>+ }+ extra={validKeys[p.id] && (+ <Button size="small" danger icon={<DeleteOutlined />} onClick={() => handleRemove(p.id)}>+ Remove+ </Button>+ )}+ >+ <Text type="secondary" style={{ fontSize: 13, display: 'block', marginBottom: 16 }}>{p.desc}</Text>+ <Space.Compact style={{ width: '100%' }}>+ <Form.Item name={p.id} noStyle>+ <Input.Password+ placeholder={p.placeholder}+ style={{ fontFamily: 'monospace', fontSize: 14 }}+ onChange={() => setValidKeys(v => ({ ...v, [p.id]: false }))}+ />+ </Form.Item>+ <Button+ loading={loading[p.id]}+ onClick={() => handleValidate(p.id)}+ type={validKeys[p.id] ? 'primary' : 'default'}+ style={validKeys[p.id] ? { backgroundColor: p.color, borderColor: p.color } : {}}+ >+ {validKeys[p.id] ? 'Valid' : 'Validate'}+ </Button>+ </Space.Compact>+ {models[p.id]?.length > 0 && (+ <Text type="secondary" style={{ fontSize: 12, marginTop: 12, display: 'block' }}>+ Models: {models[p.id].slice(0, 4).join(', ')}{models[p.id].length > 4 && ` +${models[p.id].length - 4} more`}+ </Text>+ )}+ </Card>+ </Col>+ ))}+ </Row>+ </Form>++ <div style={{ marginTop: 24, textAlign: 'right' }}>+ <Button type="primary" onClick={onClose}>Done</Button>+ </div>+ </div>+ </Modal>+ );+};++export default CredentialsModal;diff --git a/client/src/components/EdgeConditionEditor.tsx b/client/src/components/EdgeConditionEditor.tsxnew file mode 100644index 00000000..f905875f--- /dev/null+++ b/client/src/components/EdgeConditionEditor.tsx@@ -0,0 +1,443 @@+/**+ * EdgeConditionEditor - Modal for configuring edge conditions+ *+ * Allows users to set up runtime conditional branching on workflow edges.+ * Conditions are evaluated against the source node's output at runtime.+ */+import React, { useState, useEffect, useCallback } from 'react';+import * as Dialog from '@radix-ui/react-dialog';+import { useAppTheme } from '../hooks/useAppTheme';+import {+ EdgeCondition,+ ConditionOperator,+ OPERATORS,+ getOperatorsByCategory,+ formatConditionLabel,+ validateCondition,+} from '../types/EdgeCondition';++interface EdgeConditionEditorProps {+ isOpen: boolean;+ onClose: () => void;+ /** Current condition (if editing existing) */+ condition?: EdgeCondition;+ /** Current edge label */+ label?: string;+ /** Callback when condition is saved */+ onSave: (condition: EdgeCondition | undefined, label: string | undefined) => void;+ /** Available fields from source node output (for autocomplete) */+ availableFields?: string[];+ /** Source node name for display */+ sourceNodeName?: string;+}++const EdgeConditionEditor: React.FC<EdgeConditionEditorProps> = ({+ isOpen,+ onClose,+ condition,+ label,+ onSave,+ availableFields = [],+ sourceNodeName,+}) => {+ const theme = useAppTheme();++ // Form state+ const [field, setField] = useState(condition?.field || '');+ const [operator, setOperator] = useState<ConditionOperator>(condition?.operator || 'eq');+ const [value, setValue] = useState<string>(+ condition?.value !== undefined ? String(condition.value) : ''+ );+ const [edgeLabel, setEdgeLabel] = useState(label || '');+ const [error, setError] = useState<string | null>(null);++ // Reset form when modal opens with new condition+ useEffect(() => {+ if (isOpen) {+ setField(condition?.field || '');+ setOperator(condition?.operator || 'eq');+ setValue(condition?.value !== undefined ? String(condition.value) : '');+ setEdgeLabel(label || '');+ setError(null);+ }+ }, [isOpen, condition, label]);++ const operatorMeta = OPERATORS[operator];+ const operatorsByCategory = getOperatorsByCategory();++ const handleSave = useCallback(() => {+ // If no field specified, remove condition+ if (!field.trim()) {+ onSave(undefined, edgeLabel.trim() || undefined);+ onClose();+ return;+ }++ const newCondition: EdgeCondition = {+ field: field.trim(),+ operator,+ value: operatorMeta.requiresValue ? parseValue(value, operatorMeta.valueType) : undefined,+ };++ const validation = validateCondition(newCondition);+ if (!validation.valid) {+ setError(validation.error || 'Invalid condition');+ return;+ }++ onSave(newCondition, edgeLabel.trim() || formatConditionLabel(newCondition));+ onClose();+ }, [field, operator, value, edgeLabel, operatorMeta, onSave, onClose]);++ const handleRemoveCondition = useCallback(() => {+ onSave(undefined, undefined);+ onClose();+ }, [onSave, onClose]);++ // Parse value based on expected type+ const parseValue = (val: string, type?: string): any => {+ if (type === 'number') {+ const num = parseFloat(val);+ return isNaN(num) ? val : num;+ }+ if (type === 'boolean') {+ return val.toLowerCase() === 'true';+ }+ if (type === 'array') {+ try {+ return JSON.parse(val);+ } catch {+ return val.split(',').map(s => s.trim());+ }+ }+ return val;+ };++ const inputStyle: React.CSSProperties = {+ width: '100%',+ padding: `${theme.spacing.sm} ${theme.spacing.md}`,+ fontSize: theme.fontSize.base,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.md,+ backgroundColor: theme.colors.background,+ color: theme.colors.text,+ fontFamily: 'system-ui, sans-serif',+ outline: 'none',+ };++ const selectStyle: React.CSSProperties = {+ ...inputStyle,+ cursor: 'pointer',+ };++ const labelStyle: React.CSSProperties = {+ display: 'block',+ marginBottom: theme.spacing.xs,+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.textSecondary,+ };++ const sectionStyle: React.CSSProperties = {+ marginBottom: theme.spacing.lg,+ };++ const buttonBaseStyle: React.CSSProperties = {+ padding: `${theme.spacing.sm} ${theme.spacing.lg}`,+ borderRadius: theme.borderRadius.md,+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,+ cursor: 'pointer',+ border: 'none',+ transition: theme.transitions.fast,+ };++ return (+ <Dialog.Root open={isOpen}>+ <Dialog.Portal>+ <Dialog.Overlay+ style={{+ position: 'fixed',+ inset: 0,+ backgroundColor: 'rgba(0, 0, 0, 0.5)',+ backdropFilter: 'blur(2px)',+ zIndex: 1100,+ }}+ />+ <Dialog.Content+ style={{+ position: 'fixed',+ top: '50%',+ left: '50%',+ transform: 'translate(-50%, -50%)',+ backgroundColor: theme.colors.background,+ borderRadius: theme.borderRadius.lg,+ boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.25)',+ width: '420px',+ maxHeight: '85vh',+ display: 'flex',+ flexDirection: 'column',+ fontFamily: 'system-ui, sans-serif',+ overflow: 'hidden',+ zIndex: 1101,+ }}+ >+ {/* Header */}+ <div+ style={{+ padding: `${theme.spacing.lg} ${theme.spacing.xl}`,+ borderBottom: `1px solid ${theme.colors.border}`,+ backgroundColor: theme.colors.backgroundPanel,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}+ >+ <Dialog.Title+ style={{+ margin: 0,+ fontSize: theme.fontSize.lg,+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.text,+ display: 'flex',+ alignItems: 'center',+ gap: theme.spacing.sm,+ }}+ >+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={theme.dracula.cyan} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <path d="M16 3h5v5"/>+ <path d="M21 3l-7 7"/>+ <path d="M8 21H3v-5"/>+ <path d="M3 21l7-7"/>+ </svg>+ Edge Condition+ </Dialog.Title>+ <Dialog.Close+ onClick={onClose}+ style={{+ background: 'transparent',+ border: 'none',+ fontSize: '20px',+ cursor: 'pointer',+ color: theme.colors.textSecondary,+ padding: theme.spacing.xs,+ borderRadius: theme.borderRadius.sm,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ width: '32px',+ height: '32px',+ }}+ >+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <line x1="18" y1="6" x2="6" y2="18"/>+ <line x1="6" y1="6" x2="18" y2="18"/>+ </svg>+ </Dialog.Close>+ </div>++ <Dialog.Description style={{ display: 'none' }}>+ Configure condition for edge branching+ </Dialog.Description>++ {/* Content */}+ <div style={{ padding: theme.spacing.xl, overflowY: 'auto' }}>+ {/* Source node info */}+ {sourceNodeName && (+ <div+ style={{+ marginBottom: theme.spacing.lg,+ padding: theme.spacing.md,+ backgroundColor: theme.colors.backgroundPanel,+ borderRadius: theme.borderRadius.md,+ fontSize: theme.fontSize.sm,+ color: theme.colors.textSecondary,+ }}+ >+ Condition evaluates output from: <strong style={{ color: theme.colors.text }}>{sourceNodeName}</strong>+ </div>+ )}++ {/* Field input */}+ <div style={sectionStyle}>+ <label style={labelStyle}>Field Path</label>+ <input+ type="text"+ value={field}+ onChange={(e) => setField(e.target.value)}+ placeholder="e.g., result.status, items.0.name"+ style={inputStyle}+ list="available-fields"+ />+ {availableFields.length > 0 && (+ <datalist id="available-fields">+ {availableFields.map((f) => (+ <option key={f} value={f} />+ ))}+ </datalist>+ )}+ <div style={{ marginTop: theme.spacing.xs, fontSize: theme.fontSize.xs, color: theme.colors.textMuted }}>+ Use dot notation for nested fields (e.g., result.data.value)+ </div>+ </div>++ {/* Operator select */}+ <div style={sectionStyle}>+ <label style={labelStyle}>Operator</label>+ <select+ value={operator}+ onChange={(e) => setOperator(e.target.value as ConditionOperator)}+ style={selectStyle}+ >+ {Object.entries(operatorsByCategory).map(([category, ops]) => (+ <optgroup key={category} label={category}>+ {ops.map((op) => (+ <option key={op} value={op}>+ {OPERATORS[op].label}+ </option>+ ))}+ </optgroup>+ ))}+ </select>+ <div style={{ marginTop: theme.spacing.xs, fontSize: theme.fontSize.xs, color: theme.colors.textMuted }}>+ {operatorMeta.description}+ </div>+ </div>++ {/* Value input (conditional) */}+ {operatorMeta.requiresValue && (+ <div style={sectionStyle}>+ <label style={labelStyle}>+ Value+ {operatorMeta.valueType === 'array' && (+ <span style={{ fontWeight: 'normal', marginLeft: theme.spacing.sm }}>+ (comma-separated or JSON array)+ </span>+ )}+ </label>+ <input+ type={operatorMeta.valueType === 'number' ? 'number' : 'text'}+ value={value}+ onChange={(e) => setValue(e.target.value)}+ placeholder={+ operatorMeta.valueType === 'array'+ ? 'e.g., value1, value2 or ["a", "b"]'+ : 'Enter comparison value'+ }+ style={inputStyle}+ />+ </div>+ )}++ {/* Edge label */}+ <div style={sectionStyle}>+ <label style={labelStyle}>Edge Label (optional)</label>+ <input+ type="text"+ value={edgeLabel}+ onChange={(e) => setEdgeLabel(e.target.value)}+ placeholder="Auto-generated from condition"+ style={inputStyle}+ />+ <div style={{ marginTop: theme.spacing.xs, fontSize: theme.fontSize.xs, color: theme.colors.textMuted }}>+ Displayed on the workflow canvas+ </div>+ </div>++ {/* Error message */}+ {error && (+ <div+ style={{+ padding: theme.spacing.md,+ backgroundColor: `${theme.colors.error}20`,+ border: `1px solid ${theme.colors.error}40`,+ borderRadius: theme.borderRadius.md,+ color: theme.colors.error,+ fontSize: theme.fontSize.sm,+ marginBottom: theme.spacing.lg,+ }}+ >+ {error}+ </div>+ )}++ {/* Preview */}+ {field && (+ <div+ style={{+ padding: theme.spacing.md,+ backgroundColor: theme.colors.backgroundPanel,+ borderRadius: theme.borderRadius.md,+ marginBottom: theme.spacing.lg,+ }}+ >+ <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textMuted, marginBottom: theme.spacing.xs }}>+ Preview:+ </div>+ <div style={{ fontSize: theme.fontSize.sm, color: theme.dracula.cyan, fontFamily: 'monospace' }}>+ if output.{field} {OPERATORS[operator].label.toLowerCase()}+ {operatorMeta.requiresValue && value && ` "${value}"`}+ </div>+ </div>+ )}+ </div>++ {/* Footer */}+ <div+ style={{+ padding: theme.spacing.lg,+ borderTop: `1px solid ${theme.colors.border}`,+ backgroundColor: theme.colors.backgroundPanel,+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ }}+ >+ {/* Remove condition button (left side) */}+ {condition && (+ <button+ onClick={handleRemoveCondition}+ style={{+ ...buttonBaseStyle,+ backgroundColor: `${theme.colors.error}20`,+ color: theme.colors.error,+ border: `1px solid ${theme.colors.error}40`,+ }}+ >+ Remove Condition+ </button>+ )}+ {!condition && <div />}++ {/* Save/Cancel buttons (right side) */}+ <div style={{ display: 'flex', gap: theme.spacing.sm }}>+ <button+ onClick={onClose}+ style={{+ ...buttonBaseStyle,+ backgroundColor: 'transparent',+ color: theme.colors.textSecondary,+ border: `1px solid ${theme.colors.border}`,+ }}+ >+ Cancel+ </button>+ <button+ onClick={handleSave}+ style={{+ ...buttonBaseStyle,+ backgroundColor: theme.dracula.cyan,+ color: theme.dracula.background,+ }}+ >+ Save Condition+ </button>+ </div>+ </div>+ </Dialog.Content>+ </Dialog.Portal>+ </Dialog.Root>+ );+};++export default EdgeConditionEditor;diff --git a/client/src/components/GeminiChatModelNode.tsx b/client/src/components/GeminiChatModelNode.tsxnew file mode 100644index 00000000..40e32a83--- /dev/null+++ b/client/src/components/GeminiChatModelNode.tsx@@ -0,0 +1,18 @@+import React from 'react';+import { NodeProps } from 'reactflow';+import { NodeData } from '../types/NodeTypes';+import BaseChatModelNode from './base/BaseChatModelNode';++const GeminiChatModelNode: React.FC<NodeProps<NodeData>> = (props) => {+ return (+ <BaseChatModelNode+ {...props}+ providerId="gemini"+ displayName="Gemini"+ icon="⭐"+ color="#4285F4"+ />+ );+};++export default GeminiChatModelNode;\ No newline at end of filediff --git a/client/src/components/GenericNode.tsx b/client/src/components/GenericNode.tsxnew file mode 100644index 00000000..183df1fd--- /dev/null+++ b/client/src/components/GenericNode.tsx@@ -0,0 +1,357 @@+import React, { useState, useEffect, useRef, useCallback } from 'react';+import { Handle, Position, NodeProps } from 'reactflow';+import { nodeDefinitions } from '../nodeDefinitions';+import { NodeData } from '../types/NodeTypes';+import { INodeInputDefinition, INodeOutputDefinition, NodeConnectionType } from '../types/INodeProperties';+import { useAppStore } from '../store/useAppStore';+import { useAppTheme } from '../hooks/useAppTheme';+import { useWebSocket } from '../contexts/WebSocketContext';++const GenericNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectable, selected }) => {+ const theme = useAppTheme();+ const { setSelectedNode, renamingNodeId, setRenamingNodeId, updateNodeData } = useAppStore();+ const { getNodeStatus } = useWebSocket();+ const isDisabled = data?.disabled === true;++ // Get execution status from WebSocket+ const nodeStatus = getNodeStatus(id);+ const executionStatus = nodeStatus?.status || 'idle';+ const isExecuting = executionStatus === 'executing' || executionStatus === 'waiting';++ // Get definition early for use in hooks+ const definition = type && nodeDefinitions[type] ? nodeDefinitions[type] : null;++ // Inline rename state+ const [isRenaming, setIsRenaming] = useState(false);+ const [editLabel, setEditLabel] = useState('');+ const inputRef = useRef<HTMLInputElement>(null);++ // Sync with global renaming state+ useEffect(() => {+ if (renamingNodeId === id) {+ setIsRenaming(true);+ setEditLabel(data?.label || definition?.displayName || type || '');+ } else {+ setIsRenaming(false);+ }+ }, [renamingNodeId, id, data?.label, definition?.displayName, type]);++ // Focus and select input when entering rename mode+ useEffect(() => {+ if (isRenaming && inputRef.current) {+ inputRef.current.focus();+ inputRef.current.select();+ }+ }, [isRenaming]);++ // Handle save rename+ const handleSaveRename = useCallback(() => {+ const newLabel = editLabel.trim();+ const originalLabel = data?.label || definition?.displayName || type || '';++ // Only save if label changed and is not empty+ if (newLabel && newLabel !== originalLabel) {+ updateNodeData(id, { ...data, label: newLabel });+ }++ setIsRenaming(false);+ setRenamingNodeId(null);+ }, [editLabel, data, definition?.displayName, type, id, updateNodeData, setRenamingNodeId]);++ // Handle cancel rename+ const handleCancelRename = useCallback(() => {+ setIsRenaming(false);+ setRenamingNodeId(null);+ }, [setRenamingNodeId]);++ // Handle double-click to rename+ const handleLabelDoubleClick = useCallback((e: React.MouseEvent) => {+ e.stopPropagation();+ setRenamingNodeId(id);+ }, [id, setRenamingNodeId]);++ const handleParametersClick = (e: React.MouseEvent) => {+ e.stopPropagation();+ setSelectedNode({ id, type, data, position: { x: 0, y: 0 } });+ };++ if (!type || !definition) {+ return (+ <div style={{+ padding: '8px 12px',+ backgroundColor: '#ef4444',+ color: 'white',+ borderRadius: '8px',+ fontSize: '12px',+ minWidth: '120px',+ textAlign: 'center'+ }}>+ Unknown node type+ </div>+ );+ }++ // Helper functions to get inputs/outputs for both enhanced and legacy nodes+ const getNodeInputs = (): INodeInputDefinition[] => {+ if (!definition.inputs) return [];++ // Enhanced nodes: array of input objects+ if (definition.inputs.length > 0 && typeof definition.inputs[0] === 'object') {+ return definition.inputs as INodeInputDefinition[];+ }++ // Legacy nodes: array of strings - convert to input objects+ return (definition.inputs as string[]).map((input, index) => ({+ name: `input_${index}`,+ displayName: 'Input',+ type: (input as NodeConnectionType) || 'main',+ description: 'Node input connection'+ }));+ };++ const getNodeOutputs = (): INodeOutputDefinition[] => {+ if (!definition.outputs) return [];++ // Enhanced nodes: array of output objects+ if (definition.outputs.length > 0 && typeof definition.outputs[0] === 'object') {+ return definition.outputs as INodeOutputDefinition[];+ }++ // Legacy nodes: array of strings - convert to output objects+ return (definition.outputs as string[]).map((output, index) => ({+ name: `output_${index}`,+ displayName: 'Output',+ type: (output as NodeConnectionType) || 'main',+ description: 'Node output connection'+ }));+ };++ const nodeInputs = getNodeInputs();+ const nodeOutputs = getNodeOutputs();++ // Helper functions for color management+ const getNodeColor = () => definition.defaults.color || '#9E9E9E';+ const getBorderColor = () => {+ const color = getNodeColor();+ if (color.startsWith('#')) {+ const hex = color.substring(1);+ const r = Math.max(0, parseInt(hex.substring(0, 2), 16) - 40);+ const g = Math.max(0, parseInt(hex.substring(2, 4), 16) - 40);+ const b = Math.max(0, parseInt(hex.substring(4, 6), 16) - 40);+ return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`;+ }+ return color;+ };++ return (+ <div+ style={{+ position: 'relative',+ padding: '12px 32px 12px 16px',+ minWidth: '160px',+ minHeight: '60px',+ borderRadius: '12px',+ background: `linear-gradient(135deg, ${getNodeColor()} 0%, ${getBorderColor()} 100%)`,+ border: `2px solid ${isExecuting+ ? (theme.isDarkMode ? theme.dracula.cyan : '#2563eb')+ : selected+ ? '#3b82f6'+ : getBorderColor()}`,+ color: 'white',+ fontFamily: 'system-ui, -apple-system, sans-serif',+ fontSize: '14px',+ fontWeight: '600',+ textAlign: 'center',+ cursor: 'pointer',+ transition: 'all 0.2s ease',+ boxShadow: isExecuting+ ? theme.isDarkMode+ ? `0 4px 12px ${theme.dracula.cyan}66, 0 0 0 3px ${theme.dracula.cyan}4D`+ : `0 0 0 3px rgba(37, 99, 235, 0.5), 0 4px 16px rgba(37, 99, 235, 0.35)`+ : selected+ ? `0 8px 25px ${getNodeColor()}40, 0 0 0 2px ${theme.colors.focus}`+ : theme.isDarkMode+ ? `0 4px 12px ${getNodeColor()}40`+ : `0 2px 8px ${getNodeColor()}25, 0 4px 16px rgba(0, 0, 0, 0.08)`,+ overflow: 'visible',+ opacity: isDisabled ? 0.5 : 1,+ animation: isExecuting ? 'pulse 1.5s ease-in-out infinite' : 'none',+ }}+ >+ {/* Disabled Overlay */}+ {isDisabled && (+ <div style={{+ position: 'absolute',+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ backgroundColor: 'rgba(128, 128, 128, 0.4)',+ borderRadius: 'inherit',+ zIndex: 25,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ pointerEvents: 'none',+ }}>+ <span style={{ fontSize: '24px', opacity: 0.8 }}>||</span>+ </div>+ )}+ {/* Input Handles - Multiple handles based on node definition */}+ {nodeInputs.map((input, index) => {+ const totalInputs = nodeInputs.length;+ const topPosition = totalInputs === 1 ? '50%' :+ `${20 + (60 * index) / Math.max(totalInputs - 1, 1)}%`;++ return (+ <Handle+ key={`input-${input.name}-${index}`}+ id={`input-${input.name}`}+ type="target"+ position={Position.Left}+ isConnectable={isConnectable}+ style={{+ position: 'absolute',+ left: '-6px',+ top: topPosition,+ transform: 'translateY(-50%)',+ width: '12px',+ height: '12px',+ backgroundColor: 'rgba(255,255,255,0.9)',+ border: `2px solid ${getBorderColor()}`,+ borderRadius: '50%'+ }}+ title={`${input.displayName}: ${input.description}`}+ />+ );+ })}+++ {/* Parameters Button */}+ <button+ onClick={handleParametersClick}+ style={{+ position: 'absolute',+ top: '8px',+ right: '8px',+ width: '20px',+ height: '20px',+ borderRadius: '50%',+ backgroundColor: 'rgba(255, 255, 255, 0.95)',+ border: 'none',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ fontSize: '10px',+ color: getNodeColor(),+ fontWeight: '600',+ transition: 'all 0.2s ease',+ boxShadow: '0 1px 3px rgba(0, 0, 0, 0.2)',+ zIndex: 20+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = 'white';+ e.currentTarget.style.transform = 'scale(1.15)';+ e.currentTarget.style.boxShadow = '0 2px 6px rgba(0, 0, 0, 0.3)';+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = 'rgba(255, 255, 255, 0.95)';+ e.currentTarget.style.transform = 'scale(1)';+ e.currentTarget.style.boxShadow = '0 1px 3px rgba(0, 0, 0, 0.2)';+ }}+ title="Edit Parameters"+ >+ ⚙️+ </button>++ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '8px',+ position: 'relative',+ zIndex: 10,+ paddingRight: '4px'+ }}>+ <span style={{ fontSize: type === 'aiAgent' ? '18px' : '24px' }}>{definition.icon}</span>+ {isRenaming ? (+ <input+ ref={inputRef}+ type="text"+ value={editLabel}+ onChange={(e) => setEditLabel(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ handleSaveRename();+ } else if (e.key === 'Escape') {+ handleCancelRename();+ }+ e.stopPropagation();+ }}+ onBlur={handleSaveRename}+ onClick={(e) => e.stopPropagation()}+ style={{+ padding: '2px 4px',+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.text,+ backgroundColor: theme.colors.backgroundElevated,+ border: `1px solid ${theme.dracula.purple}`,+ borderRadius: theme.borderRadius.sm,+ outline: 'none',+ minWidth: '60px',+ maxWidth: '120px',+ }}+ />+ ) : (+ <span+ onDoubleClick={handleLabelDoubleClick}+ style={{+ whiteSpace: 'nowrap',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ maxWidth: '100%',+ cursor: 'text',+ }}+ title="Double-click to rename"+ >+ {data?.label || definition.displayName}+ </span>+ )}+ </div>+++ {/* Output Handles - Multiple handles based on node definition */}+ {nodeOutputs.map((output, index) => {+ const totalOutputs = nodeOutputs.length;+ const topPosition = totalOutputs === 1 ? '50%' :+ `${20 + (60 * index) / Math.max(totalOutputs - 1, 1)}%`;++ return (+ <Handle+ key={`output-${output.name}-${index}`}+ id={`output-${output.name}`}+ type="source"+ position={Position.Right}+ isConnectable={isConnectable}+ style={{+ position: 'absolute',+ right: '-6px',+ top: topPosition,+ transform: 'translateY(-50%)',+ width: '12px',+ height: '12px',+ backgroundColor: 'rgba(255,255,255,0.9)',+ border: `2px solid ${getBorderColor()}`,+ borderRadius: '50%'+ }}+ title={`${output.displayName}: ${output.description}`}+ />+ );+ })}+ </div>+ );+};++export default GenericNode;\ No newline at end of filediff --git a/client/src/components/LocationParameterPanel.tsx b/client/src/components/LocationParameterPanel.tsxnew file mode 100644index 00000000..3e8eb8d2--- /dev/null+++ b/client/src/components/LocationParameterPanel.tsx@@ -0,0 +1,170 @@+import React, { useState } from 'react';+import Modal from './ui/Modal';+import LocationPanelLayout from './parameterPanel/LocationPanelLayout';+import { useParameterPanel } from '../hooks/useParameterPanel';+import { ExecutionService } from '../services/executionService';++const LocationParameterPanel: React.FC = () => {+ const {+ selectedNode,+ nodeDefinition,+ parameters,+ hasUnsavedChanges,+ handleParameterChange,+ handleSave,+ handleCancel,+ } = useParameterPanel();+++ // Execution state (kept for potential future location node execution)+ const [isExecuting, setIsExecuting] = useState(false);++ const handleModalClose = () => {+ handleCancel();+ };++ // Execute the current node (simplified - location nodes typically don't execute)+ const handleRun = async () => {+ if (!selectedNode || !nodeDefinition) return;++ if (hasUnsavedChanges) {+ await handleSave();+ }++ setIsExecuting(true);+ try {+ // Location nodes like createMap typically don't need backend execution+ // They're configuration nodes that output map instances+ } catch (error: any) {+ console.error('Location node execution failed:', error);+ } finally {+ setIsExecuting(false);+ }+ };++ // Check if node can be executed+ const canExecute = selectedNode && nodeDefinition &&+ ExecutionService.isNodeTypeSupported(nodeDefinition.name);++ if (!selectedNode || !nodeDefinition) {+ return null;+ }++ // Only show LocationParameterPanel for createMap node+ if (nodeDefinition.name !== 'createMap') {+ return null;+ }++ // Header actions with node name and buttons in middle area+ const headerActions = (+ <div style={{+ display: 'flex',+ gap: '12px',+ alignItems: 'center'+ }}>+ {/* Node Name */}+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ fontSize: '16px',+ fontWeight: '600',+ color: '#1f2937',+ fontFamily: 'system-ui, sans-serif'+ }}>+ <span>{nodeDefinition.icon}</span>+ <span>{nodeDefinition.displayName}</span>+ {hasUnsavedChanges && <span style={{ color: '#f59e0b' }}>*</span>}+ </div>++ {/* Buttons: Run, Save, Cancel */}+ <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>+ {/* Run Button */}+ {canExecute && (+ <button+ style={{+ padding: '8px 16px',+ backgroundColor: '#ff6d5a',+ color: 'white',+ border: 'none',+ borderRadius: '4px',+ fontSize: '14px',+ fontWeight: '500',+ cursor: isExecuting ? 'not-allowed' : 'pointer',+ opacity: isExecuting ? 0.7 : 1,+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ fontFamily: 'system-ui, sans-serif'+ }}+ onClick={handleRun}+ disabled={isExecuting}+ title={isExecuting ? 'Execution in progress...' : 'Execute this node'}+ >+ {isExecuting ? 'Running...' : 'Run'}+ </button>+ )}++ {/* Save Button */}+ <button+ style={{+ padding: '8px 16px',+ backgroundColor: hasUnsavedChanges ? '#3b82f6' : '#9ca3af',+ color: 'white',+ border: 'none',+ borderRadius: '4px',+ fontSize: '14px',+ fontWeight: '500',+ cursor: hasUnsavedChanges ? 'pointer' : 'not-allowed',+ fontFamily: 'system-ui, sans-serif'+ }}+ onClick={handleSave}+ disabled={!hasUnsavedChanges}+ >+ Save+ </button>++ {/* Cancel Button */}+ <button+ style={{+ padding: '8px 16px',+ backgroundColor: '#6b7280',+ color: 'white',+ border: 'none',+ borderRadius: '4px',+ fontSize: '14px',+ fontWeight: '500',+ cursor: 'pointer',+ fontFamily: 'system-ui, sans-serif'+ }}+ onClick={handleCancel}+ >+ Cancel+ </button>+ </div>+ </div>+ );++ return (+ <Modal+ isOpen={!!selectedNode}+ onClose={handleModalClose}+ title="Node Configuration"+ maxWidth="95vw"+ maxHeight="95vh"+ headerActions={headerActions}+ >+ {/* Modular Location Panel Layout */}+ <LocationPanelLayout+ selectedNode={selectedNode}+ nodeDefinition={nodeDefinition}+ parameters={parameters}+ hasUnsavedChanges={hasUnsavedChanges}+ onParameterChange={handleParameterChange}+ showInputSection={true}+ />+ </Modal>+ );+};++export default LocationParameterPanel;\ No newline at end of filediff --git a/client/src/components/ModelNode.tsx b/client/src/components/ModelNode.tsxnew file mode 100644index 00000000..f91aae66--- /dev/null+++ b/client/src/components/ModelNode.tsx@@ -0,0 +1,270 @@+import React, { useMemo } from 'react';+import { Handle, Position, NodeProps } from 'reactflow';+import { NodeData } from '../types/NodeTypes';+import { useAppStore } from '../store/useAppStore';+import { nodeDefinitions } from '../nodeDefinitions';+import { useWebSocket, useNodeStatus } from '../contexts/WebSocketContext';+import { useAppTheme } from '../hooks/useAppTheme';++// Map credential names to provider keys+const CREDENTIAL_TO_PROVIDER: Record<string, string> = {+ 'openaiApi': 'openai',+ 'anthropicApi': 'anthropic',+ 'googleAiApi': 'gemini',+ 'azureOpenaiApi': 'azure_openai',+ 'cohereApi': 'cohere',+ 'ollamaApi': 'ollama',+ 'mistralApi': 'mistral'+};++const ModelNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectable, selected }) => {+ const theme = useAppTheme();+ const { setSelectedNode } = useAppStore();+ const { apiKeyStatuses } = useWebSocket();++ // Get execution status from WebSocket+ const nodeStatus = useNodeStatus(id);+ const executionStatus = nodeStatus?.status || 'idle';+ const isExecuting = executionStatus === 'executing' || executionStatus === 'waiting';++ const definition = nodeDefinitions[type as keyof typeof nodeDefinitions];++ // Determine provider from node definition or type+ const provider = useMemo(() => {+ const credentials = definition?.credentials?.[0];+ if (credentials?.name && CREDENTIAL_TO_PROVIDER[credentials.name]) {+ return CREDENTIAL_TO_PROVIDER[credentials.name];+ }++ // Fallback: extract provider from node type+ if (type?.includes('openai')) return 'openai';+ if (type?.includes('claude')) return 'anthropic';+ if (type?.includes('gemini')) return 'gemini';+ if (type?.includes('azure')) return 'azure_openai';+ if (type?.includes('cohere')) return 'cohere';+ if (type?.includes('ollama')) return 'ollama';+ if (type?.includes('mistral')) return 'mistral';++ return '';+ }, [type, definition?.credentials]);++ // Reactive API key status from WebSocket context+ const hasApiKey = useMemo(() => {+ if (!provider) return false;+ const status = apiKeyStatuses[provider];+ return status?.hasKey || false;+ }, [provider, apiKeyStatuses]);++ // Memory nodes are always "configured" (they don't need API keys)+ const isMemoryNode = type === 'simpleMemory';++ // Get the output handle ID based on node type+ // Memory nodes use 'output-memory' to match their node definition output name+ // Other nodes use 'output-model' for AI model configuration output+ const outputHandleId = isMemoryNode ? 'output-memory' : 'output-model';++ // Check if model is configured+ const isConfigured = useMemo(() => {+ // Memory nodes are always ready+ if (isMemoryNode) return true;+ const hasModel = data?.model && data.model.trim() !== '';+ return hasModel && hasApiKey;+ }, [data?.model, hasApiKey, isMemoryNode]);++ const handleParametersClick = (e: React.MouseEvent) => {+ e.stopPropagation();+ setSelectedNode({ id, type, data, position: { x: 0, y: 0 } });+ };++ const nodeColor = definition?.defaults?.color || '#6b7280';++ // Get provider icon/text for circular display+ const getProviderDisplay = () => {+ // Use the icon from the node definition if available+ if (definition?.icon) {+ return definition.icon;+ }++ // Fallback logic based on node type+ if (type?.includes('openai')) return '🤖';+ if (type?.includes('claude')) return '🧠';+ if (type?.includes('gemini')) return '⭐';+ if (type?.includes('azure')) return '☁️';+ if (type?.includes('cohere')) return '🌊';+ if (type?.includes('ollama')) return '🦙';+ if (type?.includes('mistral')) return '🌪️';++ return 'AI';+ };++ return (+ <div+ style={{+ position: 'relative',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ fontFamily: 'system-ui, -apple-system, sans-serif',+ fontSize: theme.fontSize.xs,+ cursor: 'pointer',+ }}+ >+ {/* Main Circular Node */}+ <div+ style={{+ position: 'relative',+ width: theme.nodeSize.square,+ height: theme.nodeSize.square,+ borderRadius: '50%',+ background: theme.isDarkMode+ ? `linear-gradient(135deg, ${nodeColor}20 0%, ${theme.colors.backgroundAlt} 100%)`+ : `linear-gradient(145deg, #ffffff 0%, ${nodeColor}10 100%)`,+ border: `2px solid ${isExecuting+ ? (theme.isDarkMode ? theme.dracula.cyan : '#2563eb')+ : selected+ ? theme.colors.focus+ : isConfigured+ ? (theme.isDarkMode ? `${nodeColor}60` : `${nodeColor}50`)+ : theme.dracula.red}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ color: theme.colors.text,+ fontSize: type === 'aiAgent' ? theme.fontSize.lg : theme.iconSize.xl,+ fontWeight: theme.fontWeight.semibold,+ transition: theme.transitions.fast,+ boxShadow: isExecuting+ ? theme.isDarkMode+ ? `0 4px 12px ${theme.dracula.cyan}66, 0 0 0 3px ${theme.dracula.cyan}4D`+ : `0 0 0 3px rgba(37, 99, 235, 0.5), 0 4px 16px rgba(37, 99, 235, 0.35)`+ : selected+ ? `0 4px 12px ${theme.colors.focusRing}, 0 0 0 2px ${theme.colors.focusRing}`+ : isConfigured+ ? (theme.isDarkMode+ ? `0 2px 8px ${nodeColor}30`+ : `0 2px 8px ${nodeColor}25, 0 4px 12px rgba(0,0,0,0.06)`)+ : `0 2px 8px ${theme.dracula.red}4D`,+ animation: isExecuting ? 'pulse 1.5s ease-in-out infinite' : 'none',+ }}+ >+ {/* AI Text */}+ {getProviderDisplay()}++ {/* Parameters Button */}+ <button+ onClick={handleParametersClick}+ style={{+ position: 'absolute',+ top: '-8px',+ right: '-8px',+ width: theme.nodeSize.paramButton,+ height: theme.nodeSize.paramButton,+ borderRadius: '50%',+ backgroundColor: theme.isDarkMode ? theme.colors.backgroundAlt : '#ffffff',+ border: `1px solid ${theme.isDarkMode ? theme.colors.border : `${nodeColor}40`}`,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ fontSize: theme.fontSize.xs,+ color: theme.colors.textSecondary,+ fontWeight: '400',+ transition: theme.transitions.fast,+ zIndex: 30,+ boxShadow: theme.isDarkMode+ ? `0 1px 3px ${theme.colors.shadow}`+ : `0 1px 4px ${nodeColor}20`+ }}+ title="Edit Model Parameters"+ >+ ⚙️+ </button>++ {/* Configuration Status Indicator */}+ <div+ style={{+ position: 'absolute',+ top: '-4px',+ left: '-4px',+ width: theme.nodeSize.statusIndicator,+ height: theme.nodeSize.statusIndicator,+ borderRadius: '50%',+ backgroundColor: isExecuting+ ? theme.dracula.cyan+ : executionStatus === 'success'+ ? theme.dracula.green+ : executionStatus === 'error'+ ? theme.dracula.red+ : isConfigured+ ? theme.dracula.green+ : hasApiKey+ ? theme.dracula.orange+ : theme.dracula.red,+ border: `2px solid ${theme.isDarkMode ? theme.colors.background : '#ffffff'}`,+ boxShadow: isExecuting+ ? theme.isDarkMode+ ? `0 0 6px ${theme.dracula.cyan}80`+ : '0 0 4px rgba(37, 99, 235, 0.5)'+ : theme.isDarkMode+ ? `0 1px 3px ${theme.colors.shadow}`+ : '0 1px 3px rgba(0,0,0,0.15)',+ zIndex: 30,+ animation: isExecuting ? 'pulse 1s ease-in-out infinite' : 'none',+ }}+ title={+ isExecuting+ ? 'Executing...'+ : isMemoryNode+ ? 'Memory node ready'+ : isConfigured+ ? 'Model configured and ready'+ : hasApiKey+ ? 'API key found, model needs configuration'+ : 'API key required'+ }+ />++ {/* Diamond Output Handle */}+ <Handle+ id={outputHandleId}+ type="source"+ position={Position.Top}+ isConnectable={isConnectable && isConfigured}+ style={{+ position: 'absolute',+ top: '-6px',+ left: '50%',+ transform: 'translateX(-50%) rotate(45deg)',+ width: theme.nodeSize.statusIndicator,+ height: theme.nodeSize.statusIndicator,+ backgroundColor: isConfigured ? theme.dracula.cyan : theme.colors.textMuted,+ border: `2px solid ${theme.isDarkMode ? theme.colors.backgroundAlt : '#ffffff'}`,+ borderRadius: '0',+ opacity: isConfigured ? 1 : 0.6,+ zIndex: 20,+ boxShadow: theme.isDarkMode ? 'none' : '0 1px 2px rgba(0,0,0,0.1)'+ }}+ title={isMemoryNode ? 'Memory Output' : isConfigured ? 'Model Configuration Output' : 'Configure model to enable connection'}+ />+ </div>++ {/* Model Name Below Circle */}+ <div+ style={{+ marginTop: theme.spacing.sm,+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.text,+ lineHeight: '1.2',+ textAlign: 'center',+ maxWidth: '120px'+ }}+ >+ {data?.label || definition?.displayName}+ </div>++ </div>+ );+};++export default ModelNode;\ No newline at end of filediff --git a/client/src/components/OpenAIChatModelNode.tsx b/client/src/components/OpenAIChatModelNode.tsxnew file mode 100644index 00000000..40c61c42--- /dev/null+++ b/client/src/components/OpenAIChatModelNode.tsx@@ -0,0 +1,18 @@+import React from 'react';+import { NodeProps } from 'reactflow';+import { NodeData } from '../types/NodeTypes';+import BaseChatModelNode from './base/BaseChatModelNode';++const OpenAIChatModelNode: React.FC<NodeProps<NodeData>> = (props) => {+ return (+ <BaseChatModelNode+ {...props}+ providerId="openai"+ displayName="OpenAI"+ icon="🤖"+ color="#00A67E"+ />+ );+};++export default OpenAIChatModelNode;\ No newline at end of filediff --git a/client/src/components/OutputPanel.tsx b/client/src/components/OutputPanel.tsxnew file mode 100644index 00000000..6bf394e0--- /dev/null+++ b/client/src/components/OutputPanel.tsx@@ -0,0 +1,471 @@+import React, { useState } from 'react';+import { useAppTheme } from '../hooks/useAppTheme';+import { useAppStore } from '../store/useAppStore';+import { nodeDefinitions } from '../nodeDefinitions';+import { INodeOutputDefinition, NodeConnectionType } from '../types/INodeProperties';+import { useDragVariable } from '../hooks/useDragVariable';++interface OutputPanelProps {+ nodeId: string;+}++interface ConnectedNodeData {+ nodeId: string;+ nodeName: string;+ outputs: INodeOutputDefinition[];+}++// Android node output schemas - matches the flattened output structure from backend+// These are shown as draggable outputs for template variable creation+const ANDROID_OUTPUT_SCHEMAS: Record<string, Record<string, string>> = {+ batteryMonitor: {+ battery_level: 'number',+ is_charging: 'boolean',+ temperature_celsius: 'number',+ health: 'string',+ voltage: 'number'+ },+ systemInfo: {+ device_model: 'string',+ android_version: 'string',+ api_level: 'number',+ manufacturer: 'string',+ total_memory: 'number',+ available_memory: 'number'+ },+ networkMonitor: {+ connected: 'boolean',+ type: 'string',+ ssid: 'string',+ ip_address: 'string',+ signal_strength: 'number'+ },+ wifiAutomation: {+ enabled: 'boolean',+ connected: 'boolean',+ ssid: 'string',+ networks: 'array'+ },+ bluetoothAutomation: {+ enabled: 'boolean',+ connected: 'boolean',+ paired_devices: 'array'+ },+ audioAutomation: {+ media_volume: 'number',+ ring_volume: 'number',+ muted: 'boolean'+ },+ location: {+ latitude: 'number',+ longitude: 'number',+ accuracy: 'number',+ provider: 'string',+ altitude: 'number',+ speed: 'number',+ bearing: 'number'+ },+ appLauncher: {+ package_name: 'string',+ launched: 'boolean',+ app_name: 'string'+ },+ appList: {+ apps: 'array',+ count: 'number'+ },+ deviceStateAutomation: {+ airplane_mode: 'boolean',+ screen_on: 'boolean',+ brightness: 'number'+ },+ screenControlAutomation: {+ brightness: 'number',+ auto_brightness: 'boolean',+ screen_timeout: 'number'+ },+ motionDetection: {+ acceleration_x: 'number',+ acceleration_y: 'number',+ acceleration_z: 'number',+ is_moving: 'boolean'+ },+ environmentalSensors: {+ temperature: 'number',+ humidity: 'number',+ pressure: 'number',+ light: 'number'+ },+ cameraControl: {+ cameras: 'array',+ photo_path: 'string'+ },+ mediaControl: {+ playing: 'boolean',+ volume: 'number',+ track: 'string'+ },+ airplaneModeControl: {+ enabled: 'boolean'+ }+};++// List of Android service node types+const ANDROID_NODE_TYPES = [+ 'batteryMonitor', 'systemInfo', 'networkMonitor', 'location',+ 'wifiAutomation', 'bluetoothAutomation', 'audioAutomation',+ 'deviceStateAutomation', 'screenControlAutomation', 'airplaneModeControl',+ 'motionDetection', 'environmentalSensors', 'cameraControl', 'mediaControl',+ 'appLauncher', 'appList'+];++const OutputPanel: React.FC<OutputPanelProps> = ({ nodeId }) => {+ const theme = useAppTheme();+ const { currentWorkflow } = useAppStore();+ const [expandedNode, setExpandedNode] = useState<string | null>(null);+ const [isDragging, setIsDragging] = useState(false);+ const [draggedParam, setDraggedParam] = useState<{ nodeId: string; output: string } | null>(null);++ // Use the same template variable naming as InputSection for consistency+ const { getTemplateVariableName } = useDragVariable(nodeId);++ // Helper to get outputs from a node definition+ const getNodeOutputs = (nodeType: string): INodeOutputDefinition[] => {+ // For Android nodes, use the detailed schema to show individual draggable properties+ if (ANDROID_NODE_TYPES.includes(nodeType)) {+ const schema = ANDROID_OUTPUT_SCHEMAS[nodeType];+ if (schema) {+ return Object.entries(schema).map(([name, type]) => ({+ name,+ displayName: name.split('_').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' '),+ type: type as NodeConnectionType,+ description: `${type} value`+ }));+ }+ }++ const definition = nodeDefinitions[nodeType];+ if (!definition) return [];++ if (!definition.outputs) {+ return [{+ name: 'output',+ displayName: 'Output',+ type: 'main' as NodeConnectionType,+ description: 'Node output'+ }];+ } else if (Array.isArray(definition.outputs)) {+ if (typeof definition.outputs[0] === 'string') {+ return (definition.outputs as string[]).map(outputName => ({+ name: outputName,+ displayName: outputName.charAt(0).toUpperCase() + outputName.slice(1),+ type: 'main' as NodeConnectionType,+ description: `${outputName} output`+ }));+ } else {+ return definition.outputs as INodeOutputDefinition[];+ }+ }+ return [{+ name: 'output',+ displayName: 'Output',+ type: 'main' as NodeConnectionType,+ description: 'Node output'+ }];+ };++ // Helper to check if a handle is a config/auxiliary handle (not main data flow)+ const isConfigHandle = (handle: string | null | undefined): boolean => {+ if (!handle) return false;+ // Config handles follow pattern: input-<type> where type is not 'main'+ // Examples: input-memory, input-tools, input-model+ if (handle.startsWith('input-') && handle !== 'input-main') {+ return true;+ }+ return false;+ };++ // Helper to check if a node is a config/auxiliary node (connects to config handles)+ const isConfigNode = (nodeType: string | undefined): boolean => {+ if (!nodeType) return false;+ const definition = nodeDefinitions[nodeType];+ if (!definition) return false;+ // Config nodes typically have 'memory' or 'tool' in their group, or have no main input+ const groups = definition.group || [];+ return groups.includes('memory') || groups.includes('tool');+ };++ // Get connected nodes with their outputs+ const getConnectedNodes = (): ConnectedNodeData[] => {+ if (!currentWorkflow || !nodeId) return [];++ const connectedNodes: ConnectedNodeData[] = [];+ const addedNodeIds = new Set<string>();++ // Helper to add a node to connected list+ const addConnectedNode = (sourceNodeId: string, label?: string) => {+ if (addedNodeIds.has(sourceNodeId)) return;++ const sourceNode = currentWorkflow.nodes.find(n => n.id === sourceNodeId);+ if (!sourceNode?.type) return;++ const sourceDefinition = nodeDefinitions[sourceNode.type];+ if (!sourceDefinition) return;++ addedNodeIds.add(sourceNodeId);+ connectedNodes.push({+ nodeId: sourceNode.id,+ nodeName: label ? `${sourceDefinition.displayName} (${label})` : sourceDefinition.displayName,+ outputs: getNodeOutputs(sourceNode.type)+ });+ };++ // Find all edges that connect TO the current node+ const incomingEdges = currentWorkflow.edges.filter(edge => edge.target === nodeId);++ // Get current node info+ const currentNode = currentWorkflow.nodes.find(n => n.id === nodeId);+ const currentNodeType = currentNode?.type;++ for (const edge of incomingEdges) {+ // Skip config handle connections - they're for auxiliary nodes, not main data flow+ if (isConfigHandle(edge.targetHandle)) {+ continue;+ }+ addConnectedNode(edge.source);+ }++ // If current node is a config node (memory, tool), inherit parent node's main inputs+ if (isConfigNode(currentNodeType)) {+ // Find which parent node this config node is connected to+ const outgoingEdges = currentWorkflow.edges.filter(edge => edge.source === nodeId);++ for (const edge of outgoingEdges) {+ // Check if connected to a config handle on the target+ if (isConfigHandle(edge.targetHandle)) {+ const targetNode = currentWorkflow.nodes.find(n => n.id === edge.target);+ if (!targetNode) continue;++ const targetDef = nodeDefinitions[targetNode.type || ''];+ const targetName = targetDef?.displayName || targetNode.type;++ // Find nodes connected to the parent's main input (non-config handles)+ const parentInputEdges = currentWorkflow.edges.filter(+ e => e.target === targetNode.id && !isConfigHandle(e.targetHandle)+ );++ for (const parentEdge of parentInputEdges) {+ addConnectedNode(parentEdge.source, `via ${targetName}`);+ }+ }+ }+ }++ return connectedNodes;+ };++ const connectedNodes = getConnectedNodes();++ const handleDragStart = (e: React.DragEvent, sourceNodeId: string, outputName: string) => {+ setIsDragging(true);+ setDraggedParam({ nodeId: sourceNodeId, output: outputName });+ e.dataTransfer.effectAllowed = 'copy';++ // Use the same template naming as InputSection for consistency+ // This ensures Android nodes and all other nodes work properly with template variables+ const templateName = getTemplateVariableName(sourceNodeId);++ e.dataTransfer.setData('text/plain', `{{${templateName}.${outputName}}}`);+ };++ const handleDragEnd = () => {+ setIsDragging(false);+ setDraggedParam(null);+ };++ if (connectedNodes.length === 0) {+ return (+ <div style={{+ width: '300px',+ height: '100%',+ padding: theme.spacing.md,+ backgroundColor: theme.colors.backgroundAlt,+ borderRight: `1px solid ${theme.colors.border}`,+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center'+ }}>+ <p style={{+ margin: 0,+ fontSize: theme.fontSize.sm,+ color: theme.colors.textSecondary,+ fontStyle: 'italic',+ textAlign: 'center'+ }}>+ No connected nodes.+ <br />+ Connect nodes to see their outputs here.+ </p>+ </div>+ );+ }++ return (+ <div style={{+ width: '300px',+ height: '100%',+ backgroundColor: theme.colors.backgroundAlt,+ borderRight: `1px solid ${theme.colors.border}`,+ display: 'flex',+ flexDirection: 'column'+ }}>+ {/* Header */}+ <div style={{+ padding: theme.spacing.md,+ backgroundColor: theme.colors.backgroundPanel,+ borderBottom: `1px solid ${theme.colors.border}`,+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.textSecondary,+ textTransform: 'uppercase',+ letterSpacing: '0.1em'+ }}>+ 🔗 Connected Outputs+ </div>++ {/* Scrollable content */}+ <div style={{+ flex: 1,+ overflowY: 'auto',+ padding: theme.spacing.sm+ }}>+ {connectedNodes.map((node) => (+ <div key={node.nodeId} style={{+ marginBottom: theme.spacing.xs,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.sm,+ backgroundColor: theme.colors.background,+ overflow: 'hidden'+ }}>+ <div+ onClick={() => setExpandedNode(expandedNode === node.nodeId ? null : node.nodeId)}+ style={{+ padding: theme.spacing.sm,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ backgroundColor: theme.colors.backgroundAlt,+ transition: theme.transitions.fast+ }}+ >+ <span style={{+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.text+ }}>+ 📦 {node.nodeName}+ </span>+ <span style={{+ fontSize: theme.fontSize.xs,+ color: theme.colors.textSecondary,+ transform: expandedNode === node.nodeId ? 'rotate(180deg)' : 'rotate(0deg)',+ transition: 'transform 0.2s ease'+ }}>+ ▼+ </span>+ </div>++ {expandedNode === node.nodeId && (+ <div style={{+ padding: theme.spacing.sm,+ borderTop: `1px solid ${theme.colors.border}`+ }}>+ {node.outputs.length === 0 ? (+ <p style={{+ margin: 0,+ fontSize: theme.fontSize.xs,+ color: theme.colors.textSecondary,+ fontStyle: 'italic',+ padding: theme.spacing.xs+ }}>+ No output parameters available+ </p>+ ) : (+ node.outputs.map((output) => (+ <div+ key={output.name}+ draggable+ onDragStart={(e) => handleDragStart(e, node.nodeId, output.name)}+ onDragEnd={handleDragEnd}+ style={{+ padding: theme.spacing.xs,+ marginBottom: theme.spacing.xs,+ backgroundColor: isDragging && draggedParam?.nodeId === node.nodeId && draggedParam?.output === output.name+ ? theme.colors.focusRing+ : theme.colors.backgroundAlt,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.sm,+ cursor: 'grab',+ transition: theme.transitions.fast+ }}+ >+ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between'+ }}>+ <div>+ <div style={{+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.text,+ marginBottom: '2px'+ }}>+ {output.displayName}+ </div>+ <div style={{+ fontSize: theme.fontSize.xs,+ color: theme.colors.textSecondary+ }}>+ {output.type} • {output.description}+ </div>+ </div>+ <div style={{+ fontSize: theme.fontSize.xs,+ color: theme.colors.textSecondary,+ fontFamily: 'monospace',+ padding: `2px ${theme.spacing.xs}`,+ backgroundColor: theme.colors.background,+ borderRadius: theme.borderRadius.sm,+ border: `1px solid ${theme.colors.border}`+ }}>+ {output.name}+ </div>+ </div>+ </div>+ ))+ )}+ </div>+ )}+ </div>+ ))}+ </div>++ {/* Footer */}+ <div style={{+ padding: theme.spacing.sm,+ backgroundColor: theme.colors.backgroundPanel,+ borderTop: `1px solid ${theme.colors.border}`,+ fontSize: theme.fontSize.xs,+ color: theme.colors.textSecondary,+ textAlign: 'center'+ }}>+ 💡 Drag outputs to parameter fields+ </div>+ </div>+ );+};++export default OutputPanel;\ No newline at end of filediff --git a/client/src/components/ParameterRenderer.tsx b/client/src/components/ParameterRenderer.tsxnew file mode 100644index 00000000..1f65da75--- /dev/null+++ b/client/src/components/ParameterRenderer.tsx@@ -0,0 +1,1807 @@+import React, { useState, useEffect } from 'react';+import { NodeParameter } from '../types/NodeTypes';+import { INodeProperties, INodePropertyOption } from '../types/INodeProperties';+import APIKeyValidator from './APIKeyValidator';+import CodeEditor from './ui/CodeEditor';+import DynamicParameterService from '../services/dynamicParameterService';+import { useAppStore } from '../store/useAppStore';+import { ANDROID_SERVICE_NODE_TYPES } from '../nodeDefinitions/androidServiceNodes';+import { useAppTheme } from '../hooks/useAppTheme';+import { API_CONFIG } from '../config/api';+import { useWebSocket } from '../contexts/WebSocketContext';+import { useApiKeys } from '../hooks/useApiKeys';++// Map node types to provider keys for AI model nodes+const NODE_TYPE_TO_PROVIDER: Record<string, string> = {+ 'openaiChatModel': 'openai',+ 'anthropicChatModel': 'anthropic',+ 'claudeChatModel': 'anthropic',+ 'googleChatModel': 'gemini',+ 'geminiChatModel': 'gemini',+ 'azureChatModel': 'azure_openai',+ 'cohereChatModel': 'cohere',+ 'ollamaChatModel': 'ollama',+ 'mistralChatModel': 'mistral'+};++// Collection Renderer - n8n official style+const CollectionRenderer: React.FC<{+ parameter: any;+ value: any;+ onChange: (value: any) => void;+ allParameters?: Record<string, any>;+ theme: ReturnType<typeof useAppTheme>;+}> = ({ parameter, value, onChange, allParameters, theme }) => {+ const [showAddOption, setShowAddOption] = useState(false);+ const currentValue = value || {};+ const addedOptions = Object.keys(currentValue).filter(key => currentValue[key] !== undefined);+ const availableOptions = parameter.options?.filter((opt: any) => !addedOptions.includes(opt.name)) || [];++ const addOption = (optionName: string) => {+ const option = parameter.options?.find((opt: any) => opt.name === optionName);+ if (option) {+ onChange({+ ...currentValue,+ [optionName]: option.default+ });+ setShowAddOption(false);+ }+ };++ const removeOption = (optionName: string) => {+ const newValue = { ...currentValue };+ delete newValue[optionName];+ onChange(newValue);+ };++ const updateOption = (optionName: string, optionValue: any) => {+ onChange({+ ...currentValue,+ [optionName]: optionValue+ });+ };++ return (+ <div>+ {addedOptions.length === 0 && (+ <div style={{+ fontSize: '14px',+ color: theme.colors.textSecondary,+ marginBottom: '12px',+ padding: '8px 0'+ }}>+ No properties+ </div>+ )}++ {addedOptions.map((optionName) => {+ const option = parameter.options?.find((opt: any) => opt.name === optionName);+ if (!option) return null;++ return (+ <div key={optionName} style={{+ marginBottom: '16px',+ padding: '12px',+ border: `1px solid ${theme.colors.border}`,+ borderRadius: '4px',+ backgroundColor: theme.colors.backgroundAlt,+ position: 'relative'+ }}>+ <button+ onClick={() => removeOption(optionName)}+ style={{+ position: 'absolute',+ top: '6px',+ right: '6px',+ background: 'none',+ border: 'none',+ color: theme.colors.textSecondary,+ cursor: 'pointer',+ fontSize: '14px',+ padding: '2px 4px',+ borderRadius: '2px'+ }}+ onMouseEnter={(e) => e.currentTarget.style.backgroundColor = theme.colors.border}+ onMouseLeave={(e) => e.currentTarget.style.backgroundColor = 'transparent'}+ title="Remove"+ >+ ✕+ </button>+ <ParameterRenderer+ parameter={option}+ value={currentValue[optionName]}+ onChange={(newValue) => updateOption(optionName, newValue)}+ allParameters={allParameters}+ />+ </div>+ );+ })}++ {availableOptions.length > 0 && (+ <div style={{ position: 'relative' }}>+ <button+ onClick={() => setShowAddOption(!showAddOption)}+ style={{+ width: '100%',+ padding: '10px 12px',+ border: `1px solid ${theme.colors.border}`,+ borderRadius: '4px',+ backgroundColor: theme.colors.backgroundAlt,+ color: theme.colors.textSecondary,+ cursor: 'pointer',+ fontSize: '14px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ transition: 'all 0.2s ease'+ }}+ onMouseEnter={(e) => e.currentTarget.style.backgroundColor = theme.colors.borderHover}+ onMouseLeave={(e) => e.currentTarget.style.backgroundColor = theme.colors.backgroundAlt}+ >+ {parameter.placeholder || 'Add Option'}+ <span style={{+ transform: showAddOption ? 'rotate(180deg)' : 'rotate(0deg)',+ transition: 'transform 0.2s ease'+ }}>+ ▼+ </span>+ </button>++ {showAddOption && (+ <div style={{+ position: 'absolute',+ top: '100%',+ left: 0,+ right: 0,+ zIndex: 1000,+ backgroundColor: theme.colors.background,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: '4px',+ marginTop: '2px',+ boxShadow: `0 4px 6px -1px ${theme.colors.shadow}`,+ maxHeight: '200px',+ overflowY: 'auto'+ }}>+ {availableOptions.map((option: any, index: number) => (+ <button+ key={option.name}+ onClick={() => addOption(option.name)}+ style={{+ width: '100%',+ padding: '10px 12px',+ border: 'none',+ backgroundColor: 'transparent',+ color: theme.colors.text,+ cursor: 'pointer',+ fontSize: '14px',+ textAlign: 'left',+ borderBottom: index < availableOptions.length - 1 ? `1px solid ${theme.colors.border}` : 'none'+ }}+ onMouseEnter={(e) => e.currentTarget.style.backgroundColor = theme.colors.backgroundAlt}+ onMouseLeave={(e) => e.currentTarget.style.backgroundColor = 'transparent'}+ >+ <div style={{ fontWeight: '500' }}>+ {option.displayName}+ </div>+ {option.description && (+ <div style={{+ fontSize: '12px',+ color: theme.colors.textSecondary,+ marginTop: '2px'+ }}>+ {option.description}+ </div>+ )}+ </button>+ ))}+ </div>+ )}+ </div>+ )}+ </div>+ );+};++// Group ID Selector - with Load Groups button and dropdown+const GroupIdSelector: React.FC<{+ value: string;+ onChange: (value: string) => void;+ onNameChange?: (name: string) => void;+ storedName?: string;+ placeholder?: string;+ theme: ReturnType<typeof useAppTheme>;+ isDragOver: boolean;+ onDragOver: (e: React.DragEvent) => void;+ onDragLeave: (e: React.DragEvent) => void;+ onDrop: (e: React.DragEvent) => void;+}> = ({ value, onChange, onNameChange, storedName, placeholder, theme, isDragOver, onDragOver, onDragLeave, onDrop }) => {+ const [groups, setGroups] = useState<Array<{ jid: string; name: string; topic?: string; size?: number }>>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [showDropdown, setShowDropdown] = useState(false);+ const [error, setError] = useState<string | null>(null);+ // Use stored name if available, otherwise local state+ const [localGroupName, setLocalGroupName] = useState<string | null>(null);+ const selectedGroupName = storedName || localGroupName;+ const { getWhatsAppGroups } = useWebSocket();++ // Sync local state with stored name+ useEffect(() => {+ if (storedName) {+ setLocalGroupName(storedName);+ }+ }, [storedName]);++ const handleLoadGroups = async () => {+ setIsLoading(true);+ setError(null);+ try {+ const result = await getWhatsAppGroups();+ if (result.success && result.groups.length > 0) {+ setGroups(result.groups);+ setShowDropdown(true);+ // If we already have a value, try to find its name and update storage+ if (value) {+ const matchingGroup = result.groups.find(g => g.jid === value);+ if (matchingGroup && matchingGroup.name !== storedName) {+ setLocalGroupName(matchingGroup.name);+ onNameChange?.(matchingGroup.name);+ }+ }+ } else if (result.error) {+ setError(result.error);+ } else {+ setError('No groups found');+ }+ } catch (err: any) {+ setError(err.message || 'Failed to load groups');+ } finally {+ setIsLoading(false);+ }+ };++ const handleSelectGroup = (group: { jid: string; name: string }) => {+ onChange(group.jid);+ setLocalGroupName(group.name);+ onNameChange?.(group.name);+ setShowDropdown(false);+ };++ const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {+ onChange(e.target.value);+ // Clear group name when user types manually+ setLocalGroupName(null);+ onNameChange?.('');+ };++ // Display value: show group name if selected, otherwise show JID+ const displayValue = selectedGroupName || value;+ const isGroupSelected = selectedGroupName !== null && value;++ return (+ <div style={{ position: 'relative' }}>+ <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>+ <input+ type="text"+ value={displayValue}+ onChange={handleInputChange}+ placeholder={placeholder || '[email protected]'}+ onDragOver={onDragOver}+ onDragLeave={onDragLeave}+ onDrop={onDrop}+ style={{+ flex: 1,+ padding: '8px 12px',+ border: isDragOver ? `2px solid ${theme.colors.focus}` : `1px solid ${theme.colors.border}`,+ borderRadius: '6px',+ fontSize: '14px',+ backgroundColor: isGroupSelected ? theme.colors.backgroundAlt : (isDragOver ? theme.colors.focusRing : theme.colors.background),+ color: isGroupSelected ? theme.colors.success : (value && value.includes('{{') ? theme.colors.templateVariable : theme.colors.text),+ outline: 'none',+ transition: 'all 0.2s ease',+ fontFamily: value && value.includes('{{') ? 'monospace' : 'system-ui, sans-serif',+ fontWeight: isGroupSelected ? '500' : 'normal'+ }}+ onFocus={(e) => e.target.style.borderColor = theme.colors.focus}+ onBlur={(e) => e.target.style.borderColor = theme.colors.border}+ />+ <button+ onClick={handleLoadGroups}+ disabled={isLoading}+ style={{+ padding: '8px 12px',+ border: `1px solid ${isLoading ? theme.colors.border : `${theme.colors.focus}40`}`,+ borderRadius: '6px',+ backgroundColor: isLoading ? 'transparent' : `${theme.colors.focus}18`,+ color: isLoading ? theme.colors.textMuted : theme.colors.focus,+ cursor: isLoading ? 'wait' : 'pointer',+ fontSize: '13px',+ fontWeight: 600,+ transition: 'all 0.2s ease',+ whiteSpace: 'nowrap',+ opacity: isLoading ? 0.7 : 1+ }}+ onMouseEnter={(e) => {+ if (!isLoading) {+ e.currentTarget.style.backgroundColor = `${theme.colors.focus}30`;+ }+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = isLoading ? 'transparent' : `${theme.colors.focus}18`;+ }}+ title="Load WhatsApp groups"+ >+ {isLoading ? 'Loading...' : 'Load'}+ </button>+ </div>+ {/* Show JID below when group name is displayed */}+ {isGroupSelected && (+ <div style={{+ fontSize: '11px',+ color: theme.colors.textSecondary,+ marginTop: '4px',+ fontFamily: 'monospace'+ }}>+ {value}+ </div>+ )}++ {error && (+ <div style={{+ fontSize: '12px',+ color: theme.colors.error,+ marginTop: '4px'+ }}>+ {error}+ </div>+ )}++ {showDropdown && groups.length > 0 && (+ <div style={{+ position: 'absolute',+ top: '100%',+ left: 0,+ right: 0,+ marginTop: '4px',+ backgroundColor: theme.colors.background,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: '6px',+ boxShadow: `0 4px 12px ${theme.colors.shadow}`,+ maxHeight: '200px',+ overflowY: 'auto',+ zIndex: 1000+ }}>+ {groups.map((group, index) => (+ <button+ key={group.jid}+ onClick={() => handleSelectGroup(group)}+ style={{+ width: '100%',+ padding: '10px 12px',+ border: 'none',+ backgroundColor: 'transparent',+ color: theme.colors.text,+ cursor: 'pointer',+ fontSize: '13px',+ textAlign: 'left',+ borderBottom: index < groups.length - 1 ? `1px solid ${theme.colors.border}` : 'none'+ }}+ onMouseEnter={(e) => e.currentTarget.style.backgroundColor = theme.colors.backgroundAlt}+ onMouseLeave={(e) => e.currentTarget.style.backgroundColor = 'transparent'}+ >+ <div style={{ fontWeight: '500' }}>{group.name}</div>+ <div style={{+ fontSize: '11px',+ color: theme.colors.textSecondary,+ marginTop: '2px',+ fontFamily: 'monospace'+ }}>+ {group.jid}+ {group.size && <span style={{ marginLeft: '8px' }}>({group.size} members)</span>}+ </div>+ </button>+ ))}+ <button+ onClick={() => setShowDropdown(false)}+ style={{+ width: '100%',+ padding: '8px 12px',+ border: 'none',+ borderTop: `1px solid ${theme.colors.border}`,+ backgroundColor: theme.colors.backgroundAlt,+ color: theme.colors.textSecondary,+ cursor: 'pointer',+ fontSize: '12px',+ textAlign: 'center'+ }}+ onMouseEnter={(e) => e.currentTarget.style.color = theme.colors.text}+ onMouseLeave={(e) => e.currentTarget.style.color = theme.colors.textSecondary}+ >+ Close+ </button>+ </div>+ )}+ </div>+ );+};++// Sender Number Selector - with Load Members button and dropdown (loads from selected group)+const SenderNumberSelector: React.FC<{+ value: string;+ onChange: (value: string) => void;+ onNameChange?: (name: string) => void;+ storedName?: string;+ placeholder?: string;+ theme: ReturnType<typeof useAppTheme>;+ isDragOver: boolean;+ onDragOver: (e: React.DragEvent) => void;+ onDragLeave: (e: React.DragEvent) => void;+ onDrop: (e: React.DragEvent) => void;+ groupId: string; // The selected group to load members from+}> = ({ value, onChange, onNameChange, storedName, placeholder, theme, isDragOver, onDragOver, onDragLeave, onDrop, groupId }) => {+ const [members, setMembers] = useState<Array<{ phone: string; name: string; jid: string; is_admin?: boolean }>>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [showDropdown, setShowDropdown] = useState(false);+ const [error, setError] = useState<string | null>(null);+ // Use stored name if available, otherwise local state+ const [localMemberName, setLocalMemberName] = useState<string | null>(null);+ const selectedMemberName = storedName || localMemberName;+ const { getWhatsAppGroupInfo } = useWebSocket();++ // Sync local state with stored name+ useEffect(() => {+ if (storedName) {+ setLocalMemberName(storedName);+ }+ }, [storedName]);++ const handleLoadMembers = async () => {+ if (!groupId) {+ setError('Select a group first');+ return;+ }++ setIsLoading(true);+ setError(null);+ try {+ const result = await getWhatsAppGroupInfo(groupId);+ if (result.success && result.participants && result.participants.length > 0) {+ setMembers(result.participants);+ setShowDropdown(true);+ // If we already have a value, try to find its name and update storage+ if (value) {+ const matchingMember = result.participants.find((m: any) => m.phone === value);+ if (matchingMember) {+ const name = matchingMember.name || matchingMember.phone;+ if (name !== storedName) {+ setLocalMemberName(name);+ onNameChange?.(name);+ }+ }+ }+ } else if (result.error) {+ setError(result.error);+ } else {+ setError('No members found');+ }+ } catch (err: any) {+ setError(err.message || 'Failed to load members');+ } finally {+ setIsLoading(false);+ }+ };++ const handleSelectMember = (member: { phone: string; name: string }) => {+ const name = member.name || member.phone;+ onChange(member.phone);+ setLocalMemberName(name);+ onNameChange?.(name);+ setShowDropdown(false);+ };++ const handleClearSelection = () => {+ onChange('');+ setLocalMemberName(null);+ onNameChange?.('');+ setShowDropdown(false);+ };++ const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {+ onChange(e.target.value);+ // Clear member name when user types manually+ setLocalMemberName(null);+ onNameChange?.('');+ };++ // Display value: show member name if selected, otherwise show phone+ const displayValue = selectedMemberName || value;+ const isMemberSelected = selectedMemberName !== null && value;++ return (+ <div style={{ position: 'relative' }}>+ <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>+ <input+ type="text"+ value={displayValue}+ onChange={handleInputChange}+ placeholder={placeholder || 'All members (leave empty)'}+ onDragOver={onDragOver}+ onDragLeave={onDragLeave}+ onDrop={onDrop}+ style={{+ flex: 1,+ padding: '8px 12px',+ border: isDragOver ? `2px solid ${theme.colors.focus}` : `1px solid ${theme.colors.border}`,+ borderRadius: '6px',+ fontSize: '14px',+ backgroundColor: isMemberSelected ? theme.colors.backgroundAlt : (isDragOver ? theme.colors.focusRing : theme.colors.background),+ color: isMemberSelected ? theme.colors.success : (value && value.includes('{{') ? theme.colors.templateVariable : theme.colors.text),+ outline: 'none',+ transition: 'all 0.2s ease',+ fontFamily: value && value.includes('{{') ? 'monospace' : 'system-ui, sans-serif',+ fontWeight: isMemberSelected ? '500' : 'normal'+ }}+ onFocus={(e) => e.target.style.borderColor = theme.colors.focus}+ onBlur={(e) => e.target.style.borderColor = theme.colors.border}+ />+ <button+ onClick={handleLoadMembers}+ disabled={isLoading || !groupId}+ style={{+ padding: '8px 12px',+ border: `1px solid ${(isLoading || !groupId) ? theme.colors.border : `${theme.colors.focus}40`}`,+ borderRadius: '6px',+ backgroundColor: (isLoading || !groupId) ? 'transparent' : `${theme.colors.focus}18`,+ color: (isLoading || !groupId) ? theme.colors.textMuted : theme.colors.focus,+ cursor: (isLoading || !groupId) ? 'not-allowed' : 'pointer',+ fontSize: '13px',+ fontWeight: 600,+ transition: 'all 0.2s ease',+ whiteSpace: 'nowrap',+ opacity: (isLoading || !groupId) ? 0.7 : 1+ }}+ onMouseEnter={(e) => {+ if (!isLoading && groupId) {+ e.currentTarget.style.backgroundColor = `${theme.colors.focus}30`;+ }+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = (isLoading || !groupId) ? 'transparent' : `${theme.colors.focus}18`;+ }}+ title={groupId ? "Load group members" : "Select a group first"}+ >+ {isLoading ? 'Loading...' : 'Load'}+ </button>+ </div>+ {/* Show phone below when member name is displayed */}+ {isMemberSelected && (+ <div style={{+ fontSize: '11px',+ color: theme.colors.textSecondary,+ marginTop: '4px',+ fontFamily: 'monospace'+ }}>+ {value}+ </div>+ )}++ {error && (+ <div style={{+ fontSize: '12px',+ color: theme.colors.error,+ marginTop: '4px'+ }}>+ {error}+ </div>+ )}++ {showDropdown && members.length > 0 && (+ <div style={{+ position: 'absolute',+ top: '100%',+ left: 0,+ right: 0,+ marginTop: '4px',+ backgroundColor: theme.colors.background,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: '6px',+ boxShadow: `0 4px 12px ${theme.colors.shadow}`,+ maxHeight: '250px',+ overflowY: 'auto',+ zIndex: 1000+ }}>+ {/* All Members option */}+ <button+ onClick={handleClearSelection}+ style={{+ width: '100%',+ padding: '10px 12px',+ border: 'none',+ backgroundColor: !value ? theme.colors.backgroundAlt : 'transparent',+ color: theme.colors.text,+ cursor: 'pointer',+ fontSize: '13px',+ textAlign: 'left',+ borderBottom: `1px solid ${theme.colors.border}`+ }}+ onMouseEnter={(e) => e.currentTarget.style.backgroundColor = theme.colors.backgroundAlt}+ onMouseLeave={(e) => e.currentTarget.style.backgroundColor = !value ? theme.colors.backgroundAlt : 'transparent'}+ >+ <div style={{ fontWeight: '500', color: theme.colors.textSecondary }}>All Members</div>+ <div style={{ fontSize: '11px', color: theme.colors.textMuted, marginTop: '2px' }}>+ Receive from anyone in group+ </div>+ </button>+ {members.map((member, index) => (+ <button+ key={member.jid || member.phone}+ onClick={() => handleSelectMember(member)}+ style={{+ width: '100%',+ padding: '10px 12px',+ border: 'none',+ backgroundColor: value === member.phone ? theme.colors.backgroundAlt : 'transparent',+ color: theme.colors.text,+ cursor: 'pointer',+ fontSize: '13px',+ textAlign: 'left',+ borderBottom: index < members.length - 1 ? `1px solid ${theme.colors.border}` : 'none'+ }}+ onMouseEnter={(e) => e.currentTarget.style.backgroundColor = theme.colors.backgroundAlt}+ onMouseLeave={(e) => e.currentTarget.style.backgroundColor = value === member.phone ? theme.colors.backgroundAlt : 'transparent'}+ >+ <div style={{ fontWeight: '500' }}>+ {member.name || member.phone}+ {member.is_admin && <span style={{ marginLeft: '8px', fontSize: '10px', color: theme.colors.warning }}>(Admin)</span>}+ </div>+ <div style={{+ fontSize: '11px',+ color: theme.colors.textSecondary,+ marginTop: '2px',+ fontFamily: 'monospace'+ }}>+ {member.phone}+ </div>+ </button>+ ))}+ <button+ onClick={() => setShowDropdown(false)}+ style={{+ width: '100%',+ padding: '8px 12px',+ border: 'none',+ borderTop: `1px solid ${theme.colors.border}`,+ backgroundColor: theme.colors.backgroundAlt,+ color: theme.colors.textSecondary,+ cursor: 'pointer',+ fontSize: '12px',+ textAlign: 'center'+ }}+ onMouseEnter={(e) => e.currentTarget.style.color = theme.colors.text}+ onMouseLeave={(e) => e.currentTarget.style.color = theme.colors.textSecondary}+ >+ Close+ </button>+ </div>+ )}+ </div>+ );+};++// Fixed Collection Renderer - n8n style fixed collection+const FixedCollectionRenderer: React.FC<{+ parameter: any;+ value: any;+ onChange: (value: any) => void;+ allParameters?: Record<string, any>;+ theme: ReturnType<typeof useAppTheme>;+}> = ({ parameter, value, onChange, allParameters, theme }) => {+ const currentValue = value || {};++ return (+ <div style={{+ border: `1px solid ${theme.colors.border}`,+ borderRadius: '6px',+ backgroundColor: theme.colors.backgroundAlt,+ padding: '12px'+ }}>+ {parameter.options?.map((option: any) => {+ const optionValue = currentValue[option.name] || {};++ return (+ <div key={option.name} style={{ marginBottom: '16px' }}>+ <div style={{+ fontSize: '14px',+ fontWeight: '500',+ color: theme.colors.text,+ marginBottom: '8px'+ }}>+ {option.displayName}+ </div>+ <div style={{+ border: `1px solid ${theme.colors.border}`,+ borderRadius: '6px',+ backgroundColor: theme.colors.background,+ padding: '12px'+ }}>+ {option.values?.map((valueParam: any) => (+ <ParameterRenderer+ key={valueParam.name}+ parameter={valueParam}+ value={optionValue[valueParam.name]}+ onChange={(newValue) => {+ onChange({+ ...currentValue,+ [option.name]: {+ ...optionValue,+ [valueParam.name]: newValue+ }+ });+ }}+ allParameters={allParameters}+ />+ ))}+ </div>+ </div>+ );+ })}+ </div>+ );+};++interface ParameterRendererProps {+ parameter: NodeParameter | INodeProperties;+ value: any;+ onChange: (value: any) => void;+ allParameters?: Record<string, any>;+ onParameterChange?: (paramName: string, value: any) => void;+ onClosePanel?: () => void;+ isLoadingParameters?: boolean;+}++// Type guard to check if parameter is INodeProperties+const isINodeProperties = (param: NodeParameter | INodeProperties): param is INodeProperties => {+ return 'typeOptions' in param;+};++const ParameterRenderer: React.FC<ParameterRendererProps> = ({+ parameter,+ value,+ onChange,+ allParameters,+ onParameterChange,+ isLoadingParameters = false,+}) => {+ const theme = useAppTheme();+ // Don't use default while loading - wait for actual saved value to load+ // This prevents showing template code briefly before saved code appears+ const currentValue = isLoadingParameters ? (value ?? '') : (value !== undefined ? value : parameter.default);+ const [isDragOver, setIsDragOver] = useState(false);+ const [dynamicOptions, setDynamicOptions] = useState<INodePropertyOption[]>([]);+ const [nodeParameters, setNodeParameters] = useState<Record<string, any>>({});++ const { selectedNode } = useAppStore();+ const { getNodeParameters } = useWebSocket();+ const { getStoredApiKey, hasStoredKey, getStoredModels } = useApiKeys();++ // Don't render hidden parameters+ if (parameter.type === 'hidden') {+ return null;+ }++ // Load node parameters for expression resolution+ useEffect(() => {+ const loadParameters = async () => {+ if (selectedNode?.id) {+ const result = await getNodeParameters(selectedNode.id);+ if (result?.parameters) setNodeParameters(result.parameters);+ }+ };+ loadParameters();+ }, [selectedNode?.id, getNodeParameters]);++ // Auto-load stored API key and models when provider changes+ // Use ref to track previous provider to prevent infinite loops+ const prevProviderRef = React.useRef<string | null>(null);+ // Track if we've done initial auto-select after parameters loaded+ const hasAutoSelectedRef = React.useRef(false);++ // Reset auto-select tracking when node changes+ useEffect(() => {+ hasAutoSelectedRef.current = false;+ prevProviderRef.current = null;+ }, [selectedNode?.id]);++ useEffect(() => {+ const loadStoredKeyForProvider = async () => {+ // Only run for apiKey or model parameters+ if (parameter.name !== 'apiKey' && parameter.name !== 'model') return;++ // Don't run while parameters are still loading from database+ if (isLoadingParameters) return;++ // Get provider from allParameters or derive from node type+ let provider = allParameters?.provider;+ if (!provider && selectedNode) {+ const nodeType = selectedNode.type || selectedNode.data?.nodeType;+ if (nodeType) {+ provider = NODE_TYPE_TO_PROVIDER[nodeType];+ }+ }+ if (!provider) return;++ // Distinguish between initial load (prevProvider was null) and actual user-initiated provider change+ // On initial load: respect saved model if it exists+ // On provider change: reset to first model to prevent mismatched provider/model+ const isInitialLoad = prevProviderRef.current === null;+ const isActualProviderChange = !isInitialLoad && prevProviderRef.current !== provider;+ const shouldAutoSelectModel = parameter.name === 'model' &&+ (isActualProviderChange || isInitialLoad || !hasAutoSelectedRef.current);++ // Skip if provider hasn't changed (except for initial model load)+ if (!isActualProviderChange && !isInitialLoad && parameter.name !== 'model') return;+ if (!isActualProviderChange && !isInitialLoad && hasAutoSelectedRef.current) return;++ prevProviderRef.current = provider;++ try {+ const hasKey = await hasStoredKey(provider);++ if (hasKey) {+ // Auto-load API key for apiKey parameter - always update when provider changes+ if (parameter.name === 'apiKey' && isActualProviderChange) {+ const storedKey = await getStoredApiKey(provider);+ if (storedKey) {+ onChange(storedKey);+ }+ }++ // Auto-load models for model parameter+ if (shouldAutoSelectModel && selectedNode) {+ const models = await getStoredModels(provider);+ if (models?.length) {+ const modelOptions = DynamicParameterService.createModelOptions(models);+ DynamicParameterService.updateParameterOptions(selectedNode.id, 'model', modelOptions);++ // When user actively changes provider, reset to first model+ // to prevent mismatched provider/model combinations (e.g., OpenAI model with Anthropic provider)+ if (isActualProviderChange) {+ onChange(models[0]);+ } else {+ // Initial load or no provider change - only auto-select if no saved model exists+ const savedModel = value || allParameters?.model;+ if (!savedModel || savedModel === '') {+ onChange(models[0]);+ }+ // If saved model exists, keep it (don't call onChange)+ }+ hasAutoSelectedRef.current = true;+ }+ }+ } else {+ // No stored key for this provider - clear the fields+ if (parameter.name === 'apiKey') {+ onChange('');+ }+ if (parameter.name === 'model') {+ onChange('');+ hasAutoSelectedRef.current = true;+ }+ }+ } catch (error) {+ console.warn('Error loading stored key info:', error);+ }+ };++ loadStoredKeyForProvider();+ }, [allParameters?.provider, parameter.name, hasStoredKey, getStoredApiKey, getStoredModels, selectedNode?.id, selectedNode?.type, onChange, isLoadingParameters, value, allParameters?.model]);++ // Merge database params with current form params (current takes precedence)+ const resolvedParameters = { ...nodeParameters, ...allParameters };++ // Helper functions to get values from both interface types+ const getMin = () => (parameter as any).min || (parameter as any).typeOptions?.minValue || 0;+ const getMax = () => (parameter as any).max || (parameter as any).typeOptions?.maxValue || 100;+ const getStep = () => (parameter as any).step || (parameter as any).typeOptions?.numberStepSize || 1;++ // Load dynamic options based on loadOptionsMethod+ useEffect(() => {+ const loadDynamicOptions = async () => {+ if (!selectedNode || !isINodeProperties(parameter) || !parameter.typeOptions?.loadOptionsMethod) return;++ const dependsOn = parameter.typeOptions.loadOptionsDependsOn || [];+ const allParamsResolved = { ...nodeParameters, ...allParameters };++ // Check if all dependencies are satisfied+ const hasAllDependencies = dependsOn.every((dep: string) => allParamsResolved[dep]);+ if (dependsOn.length > 0 && !hasAllDependencies) return;++ try {+ // Get the node definition to access methods+ const { nodeDefinitions } = await import('../nodeDefinitions');+ const nodeType = selectedNode.data?.nodeType || selectedNode.type;+ const nodeDef = nodeType ? nodeDefinitions[nodeType] : null;++ if (nodeDef?.methods?.loadOptions?.[parameter.typeOptions.loadOptionsMethod]) {+ const loadMethod = nodeDef.methods.loadOptions[parameter.typeOptions.loadOptionsMethod];++ // Create context for the load method+ const context = {+ getCurrentNodeParameter: (paramName: string) => allParamsResolved[paramName]+ };++ // Call the load method with context+ const options = await loadMethod.call(context);+ setDynamicOptions(options);++ // Also update the DynamicParameterService for consistency+ DynamicParameterService.updateParameterOptions(selectedNode.id, parameter.name, options);++ // Auto-select first option if current value is empty and options are available+ if (options.length > 0 && (!currentValue || currentValue === '')) {+ console.log(`[ParameterRenderer] Auto-selecting first option for ${parameter.name}:`, options[0].value);+ onChange(options[0].value);+ }+ }+ } catch (error) {+ console.error('Error loading dynamic options:', error);+ }+ };++ loadDynamicOptions();+ }, [selectedNode?.id, isINodeProperties(parameter) && parameter.typeOptions?.loadOptionsMethod, nodeParameters, allParameters, parameter.name]);++ // Load default parameters for Android service nodes when service_id or action changes+ useEffect(() => {+ const loadDefaultParameters = async () => {+ if (!selectedNode || parameter.name !== 'parameters') return;++ const nodeType = selectedNode.data?.nodeType || selectedNode.type;+ if (!ANDROID_SERVICE_NODE_TYPES.includes(nodeType)) return;++ // Merge database params with current form params (current takes precedence)+ const allParamsResolved = { ...nodeParameters, ...allParameters };+ const serviceId = allParamsResolved.service_id;+ const action = allParamsResolved.action;++ if (!serviceId || !action) {+ console.log('[AndroidService] Skipping - missing serviceId or action:', { serviceId, action });+ return;+ }++ try {+ console.log('[AndroidService] Fetching default parameters for:', { serviceId, action });+ const response = await fetch(`${API_CONFIG.PYTHON_BASE_URL}/api/android/services/${serviceId}/actions/${action}/parameters`, {+ credentials: 'include'+ });+ const data = await response.json();+ console.log('[AndroidService] Default parameters response:', data);++ if (data.success && data.default_parameters) {+ // Always update with new defaults when service/action changes+ console.log('[AndroidService] Setting parameters to:', data.default_parameters);+ onChange(data.default_parameters);+ }+ } catch (error) {+ console.error('[AndroidService] Error loading default parameters:', error);+ }+ };++ loadDefaultParameters();+ }, [+ selectedNode?.id,+ parameter.name,+ allParameters?.service_id,+ allParameters?.action,+ nodeParameters?.service_id,+ nodeParameters?.action+ ]);++ // Subscribe to dynamic parameter updates+ useEffect(() => {+ if (!selectedNode) return;+++ const unsubscribe = DynamicParameterService.subscribe((nodeId, parameterName, options) => {++ if (nodeId === selectedNode.id && parameterName === parameter.name) {+ setDynamicOptions(options);+ }+ });++ // Check for existing dynamic options+ const existingOptions = DynamicParameterService.getParameterOptions(selectedNode.id, parameter.name);++ if (existingOptions) {+ setDynamicOptions(existingOptions);+ }++ return unsubscribe;+ }, [selectedNode?.id, parameter.name]);++ // Handle API key validation success+ const handleApiKeyValidationSuccess = (models: string[]) => {++ if (!selectedNode) {+ console.warn('ParameterRenderer: No selected node for dynamic options update');+ return;+ }++ // Always update the 'model' parameter with dynamic options when API key validation succeeds+ // This callback can be triggered from any parameter (usually the apiKey parameter)+ const modelOptions = DynamicParameterService.createModelOptions(models);+ DynamicParameterService.updateParameterOptions(selectedNode.id, 'model', modelOptions);++ // If this callback is triggered from the model parameter itself and it's empty, auto-select first model+ if (parameter.name === 'model' && !currentValue && models.length > 0) {+ onChange(models[0]);+ }+ };++ const handleDragOver = (e: React.DragEvent) => {+ e.preventDefault();+ e.dataTransfer.dropEffect = 'copy';+ setIsDragOver(true);+ };++ const handleDragLeave = (e: React.DragEvent) => {+ e.preventDefault();+ setIsDragOver(false);+ };++ const handleDrop = (e: React.DragEvent) => {+ e.preventDefault();+ setIsDragOver(false);++ // Check if this is a coordinate parameter (lat/lng) for special handling+ const paramName = parameter.name.toLowerCase();+ const isCoordinate = paramName.includes('lat') || paramName.includes('lng') ||+ paramName.includes('lon') || paramName === 'latitude' ||+ paramName === 'longitude';++ // Try to get JSON data first (from connected node outputs)+ const jsonData = e.dataTransfer.getData('application/json');+ if (jsonData) {+ try {+ const parsedData = JSON.parse(jsonData);+ if (parsedData.type === 'nodeVariable') {+ // For coordinate parameters, try to extract actual numeric value from connected node data+ if (isCoordinate && typeof parsedData.dataType === 'string' && parsedData.dataType === 'number') {+ // Look for actual coordinate values in global execution data+ // This is a simplified approach - in production you'd want more robust data access++ // For now, use template string but mark it for coordinate processing+ const existingValue = currentValue || '';+ const needsSpace = existingValue && !existingValue.endsWith(' ') && existingValue.length > 0;+ const newValue = existingValue + (needsSpace ? ' ' : '') + parsedData.variableTemplate;+ onChange(newValue);+ return;+ }++ // Handle variable template data - use the template string+ const existingValue = currentValue || '';+ // Add smart spacing - add space if existing content doesn't end with space+ const needsSpace = existingValue && !existingValue.endsWith(' ') && existingValue.length > 0;+ const newValue = existingValue + (needsSpace ? ' ' : '') + parsedData.variableTemplate;+ onChange(newValue);+ return;+ }+ if (parsedData.type === 'nodeOutput') {+ // Handle node output data - use the actual value for direct mapping+ onChange(parsedData.value);+ return;+ }+ } catch (err) {+ console.warn('Failed to parse JSON drag data:', err);+ }+ }++ // Fallback to existing text/plain format (OutputPanel drag-drop)+ const data = e.dataTransfer.getData('text/plain');+ if (data && data.startsWith('{{') && data.endsWith('}}')) {+ // For coordinate parameters, allow template strings but process them appropriately+ if (isCoordinate) {+ onChange(data); // Set the template directly for coordinate resolution+ return;+ }++ // Append to existing content instead of replacing+ const existingValue = currentValue || '';+ // Add smart spacing - add space if existing content doesn't end with space+ const needsSpace = existingValue && !existingValue.endsWith(' ') && existingValue.length > 0;+ const newValue = existingValue + (needsSpace ? ' ' : '') + data;+ onChange(newValue);+ }+ };++ const renderInput = () => {+ switch (parameter.type) {+ case 'string':+ // Check if this should be a textarea based on typeOptions.rows+ const shouldUseTextarea = (parameter as any).typeOptions?.rows > 1;+ // Check if this should be a password field+ const isPassword = (parameter as any).typeOptions?.password;+ // Check if this is a code editor+ const isCodeEditor = (parameter as any).typeOptions?.editor === 'code';++ if (shouldUseTextarea) {+ // Use CodeEditor for code editing+ if (isCodeEditor) {+ // Show loading state while parameters are being fetched+ if (isLoadingParameters) {+ return (+ <div style={{+ height: '100%',+ minHeight: '200px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: theme.colors.backgroundAlt,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.md,+ color: theme.colors.textMuted,+ fontSize: '14px'+ }}>+ Loading code...+ </div>+ );+ }+ // Get language from typeOptions or default to python+ const codeLanguage = (parameter as any).typeOptions?.editorLanguage || 'python';+ return (+ <CodeEditor+ value={currentValue || ''}+ onChange={onChange}+ language={codeLanguage}+ placeholder={parameter.placeholder}+ />+ );+ }++ // Regular textarea for non-code+ return (+ <textarea+ value={currentValue || ''}+ onChange={(e) => onChange(e.target.value)}+ placeholder={parameter.placeholder}+ rows={(parameter as any).typeOptions?.rows || 3}+ spellCheck={true}+ onDragOver={handleDragOver}+ onDragLeave={handleDragLeave}+ onDrop={handleDrop}+ style={{+ width: '100%',+ padding: '10px 12px',+ border: isDragOver ? `2px solid ${theme.accent.cyan}` : `1px solid ${theme.colors.border}`,+ borderRadius: '6px',+ fontSize: '14px',+ backgroundColor: isDragOver ? `${theme.accent.cyan}10` : theme.colors.backgroundAlt,+ color: currentValue && currentValue.includes('{{') ? theme.accent.yellow : theme.colors.text,+ outline: 'none',+ transition: 'all 0.2s ease',+ fontFamily: currentValue && currentValue.includes('{{') ? 'monospace' : 'system-ui, sans-serif',+ resize: 'vertical',+ minHeight: '80px',+ boxShadow: 'inset 0 1px 2px rgba(0,0,0,0.05)',+ lineHeight: '1.5'+ }}+ onFocus={(e) => {+ e.target.style.borderColor = theme.accent.cyan;+ e.target.style.boxShadow = `0 0 0 3px ${theme.accent.cyan}20, inset 0 1px 2px rgba(0,0,0,0.05)`;+ }}+ onBlur={(e) => {+ e.target.style.borderColor = theme.colors.border;+ e.target.style.boxShadow = 'inset 0 1px 2px rgba(0,0,0,0.05)';+ }}+ />+ );+ }++ // Check if this parameter has API key validation+ const validationArray = (parameter as any).validation;+ const apiKeyValidation = validationArray?.find((v: any) => v.type === 'apiKey' && v.showValidateButton);++ if (apiKeyValidation) {+ // Resolve provider expression if it's a template like {{ $parameter["provider"] }}+ let resolvedProvider = apiKeyValidation.provider;+ if (typeof resolvedProvider === 'string' && resolvedProvider.includes('$parameter[')) {+ // Extract parameter name from expression like {{ $parameter["provider"] }}+ const match = resolvedProvider.match(/\$parameter\["([^"]+)"\]|\$parameter\['([^']+)'\]/);+ if (match) {+ const paramName = match[1] || match[2];+ resolvedProvider = resolvedParameters[paramName] || resolvedProvider;+ }+ }++ const resolvedValidationConfig = {+ ...apiKeyValidation,+ provider: resolvedProvider+ };++ return (+ <APIKeyValidator+ value={currentValue || ''}+ onChange={onChange}+ placeholder={parameter.placeholder}+ validationConfig={resolvedValidationConfig}+ onValidationSuccess={handleApiKeyValidationSuccess}+ isDragOver={isDragOver}+ onDragOver={handleDragOver}+ onDragLeave={handleDragLeave}+ onDrop={handleDrop}+ />+ );+ }++ // Check if this parameter has dynamic options (like models after API key validation)++ if (dynamicOptions.length > 0 && parameter.type === 'string') {+ return (+ <select+ value={currentValue || ''}+ onChange={(e) => onChange(e.target.value)}+ style={{+ width: '100%',+ padding: '8px 12px',+ border: `1px solid ${theme.colors.border}`,+ borderRadius: '6px',+ fontSize: '14px',+ outline: 'none',+ transition: 'border-color 0.2s ease',+ cursor: 'pointer',+ backgroundColor: theme.colors.background,+ color: theme.colors.text,+ fontFamily: 'system-ui, sans-serif'+ }}+ onFocus={(e) => e.target.style.borderColor = theme.colors.focus}+ onBlur={(e) => e.target.style.borderColor = theme.colors.border}+ >+ {!currentValue && (+ <option value="" disabled>+ Select a model...+ </option>+ )}+ {dynamicOptions.map((option) => (+ <option key={String(option.value)} value={String(option.value)}>+ {option.label || option.name || String(option.value)}+ </option>+ ))}+ </select>+ );+ }++ // Log why we're not using dynamic options for this parameter+ if (parameter.type === 'string' && parameter.name === 'model') {+ }++ // Special case for group_id parameter - add Load Groups button+ if (parameter.name === 'group_id') {+ const storedGroupName = allParameters?.group_name || '';+ return (+ <GroupIdSelector+ value={currentValue || ''}+ onChange={onChange}+ onNameChange={(name) => onParameterChange?.('group_name', name)}+ storedName={storedGroupName}+ placeholder={parameter.placeholder}+ theme={theme}+ isDragOver={isDragOver}+ onDragOver={handleDragOver}+ onDragLeave={handleDragLeave}+ onDrop={handleDrop}+ />+ );+ }++ // Special case for senderNumber parameter - add Load Members button (uses group_id)+ if (parameter.name === 'senderNumber') {+ const groupId = resolvedParameters?.group_id || allParameters?.group_id || '';+ const storedSenderName = allParameters?.sender_name || '';+ return (+ <SenderNumberSelector+ value={currentValue || ''}+ onChange={onChange}+ onNameChange={(name) => onParameterChange?.('sender_name', name)}+ storedName={storedSenderName}+ placeholder={parameter.placeholder}+ theme={theme}+ isDragOver={isDragOver}+ onDragOver={handleDragOver}+ onDragLeave={handleDragLeave}+ onDrop={handleDrop}+ groupId={groupId}+ />+ );+ }++ return (+ <input+ type={isPassword ? "password" : "text"}+ value={currentValue || ''}+ onChange={(e) => onChange(e.target.value)}+ placeholder={parameter.placeholder}+ onDragOver={handleDragOver}+ onDragLeave={handleDragLeave}+ onDrop={handleDrop}+ style={{+ width: '100%',+ padding: '10px 12px',+ border: isDragOver ? `2px solid ${theme.accent.cyan}` : `1px solid ${theme.colors.border}`,+ borderRadius: '6px',+ fontSize: '14px',+ backgroundColor: isDragOver ? `${theme.accent.cyan}10` : theme.colors.backgroundAlt,+ color: currentValue && currentValue.includes('{{') ? theme.accent.yellow : theme.colors.text,+ outline: 'none',+ transition: 'all 0.2s ease',+ fontFamily: currentValue && currentValue.includes('{{') ? 'monospace' : 'system-ui, sans-serif',+ boxShadow: 'inset 0 1px 2px rgba(0,0,0,0.05)'+ }}+ onFocus={(e) => {+ e.target.style.borderColor = theme.accent.cyan;+ e.target.style.boxShadow = `0 0 0 3px ${theme.accent.cyan}20, inset 0 1px 2px rgba(0,0,0,0.05)`;+ }}+ onBlur={(e) => {+ e.target.style.borderColor = theme.colors.border;+ e.target.style.boxShadow = 'inset 0 1px 2px rgba(0,0,0,0.05)';+ }}+ />+ );++ case 'number':++ return (+ <input+ type="number"+ value={currentValue !== undefined ? currentValue : (parameter.default || 0)}+ onChange={(e) => onChange(Number(e.target.value))}+ min={getMin()}+ max={getMax()}+ step={getStep()}+ onDragOver={handleDragOver}+ onDragLeave={handleDragLeave}+ onDrop={handleDrop}+ style={{+ width: '100%',+ padding: '8px 12px',+ border: isDragOver ? `2px solid ${theme.colors.focus}` : `1px solid ${theme.colors.border}`,+ borderRadius: '6px',+ fontSize: '14px',+ backgroundColor: isDragOver ? theme.colors.focusRing : theme.colors.background,+ color: theme.colors.text,+ outline: 'none',+ transition: 'all 0.2s ease',+ fontFamily: 'system-ui, sans-serif'+ }}+ onFocus={(e) => e.target.style.borderColor = theme.colors.focus}+ onBlur={(e) => e.target.style.borderColor = theme.colors.border}+ />+ );++ case 'boolean':+ return (+ <label style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ cursor: 'pointer',+ fontSize: '14px',+ fontFamily: 'system-ui, sans-serif',+ color: theme.colors.text+ }}>+ <input+ type="checkbox"+ checked={currentValue || false}+ onChange={(e) => onChange(e.target.checked)}+ style={{ width: '16px', height: '16px', accentColor: theme.colors.focus }}+ />+ {parameter.displayName}+ </label>+ );++ case 'select':+ case 'options':+ // Use dynamic options if available, otherwise use static options+ const optionsToRender = dynamicOptions.length > 0 ? dynamicOptions : (parameter.options || []);+ const selectOptions = optionsToRender.filter((option): option is import('../types/INodeProperties').INodePropertyOption =>+ 'value' in option+ );++ return (+ <select+ value={currentValue || parameter.default}+ onChange={(e) => onChange(e.target.value)}+ style={{+ width: '100%',+ padding: '10px 12px',+ border: `1px solid ${theme.colors.border}`,+ borderRadius: '6px',+ fontSize: '14px',+ outline: 'none',+ transition: 'all 0.2s ease',+ cursor: 'pointer',+ backgroundColor: theme.colors.backgroundAlt,+ color: theme.colors.text,+ fontFamily: 'system-ui, sans-serif',+ boxShadow: 'inset 0 1px 2px rgba(0,0,0,0.05)',+ appearance: 'none',+ backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23657b83' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E")`,+ backgroundRepeat: 'no-repeat',+ backgroundPosition: 'right 12px center',+ paddingRight: '36px'+ }}+ onFocus={(e) => {+ e.target.style.borderColor = theme.accent.cyan;+ e.target.style.boxShadow = `0 0 0 3px ${theme.accent.cyan}20, inset 0 1px 2px rgba(0,0,0,0.05)`;+ }}+ onBlur={(e) => {+ e.target.style.borderColor = theme.colors.border;+ e.target.style.boxShadow = 'inset 0 1px 2px rgba(0,0,0,0.05)';+ }}+ >+ {selectOptions.map((option) => (+ <option key={String(option.value)} value={String(option.value)}>+ {option.label || option.name || String(option.value)}+ </option>+ ))}+ </select>+ );++ case 'slider':+ return (+ <div>+ <input+ type="range"+ min={getMin()}+ max={getMax()}+ step={getStep()}+ value={currentValue !== undefined ? currentValue : (parameter.default || 0)}+ onChange={(e) => onChange(Number(e.target.value))}+ style={{+ width: '100%',+ height: '8px',+ backgroundColor: theme.colors.backgroundAlt,+ borderRadius: '8px',+ outline: 'none',+ accentColor: theme.colors.focus+ }}+ />+ <div style={{+ textAlign: 'center',+ fontSize: '12px',+ color: theme.colors.textSecondary,+ marginTop: '4px',+ fontFamily: 'system-ui, sans-serif'+ }}>+ {currentValue !== undefined ? currentValue : (parameter.default || 0)}+ {parameter.type === 'slider' ? '%' : ''}+ </div>+ </div>+ );++ case 'percentage':+ return (+ <div>+ <input+ type="range"+ min={getMin()}+ max={getMax()}+ step={getStep()}+ value={currentValue !== undefined ? currentValue : (parameter.default || 0)}+ onChange={(e) => onChange(Number(e.target.value))}+ style={{+ width: '100%',+ height: '8px',+ backgroundColor: theme.colors.backgroundAlt,+ borderRadius: '8px',+ outline: 'none',+ accentColor: theme.colors.success+ }}+ />+ <div style={{+ textAlign: 'center',+ fontSize: '12px',+ color: theme.colors.textSecondary,+ marginTop: '4px',+ fontFamily: 'system-ui, sans-serif'+ }}>+ {currentValue !== undefined ? currentValue : (parameter.default || 0)}%+ </div>+ </div>+ );++ case 'text':+ return (+ <input+ type="text"+ value={currentValue || ''}+ onChange={(e) => onChange(e.target.value)}+ placeholder={parameter.placeholder}+ onDragOver={handleDragOver}+ onDragLeave={handleDragLeave}+ onDrop={handleDrop}+ style={{+ width: '100%',+ padding: '8px 12px',+ border: isDragOver ? `2px solid ${theme.colors.focus}` : `1px solid ${theme.colors.border}`,+ borderRadius: '6px',+ fontSize: '14px',+ backgroundColor: isDragOver ? theme.colors.focusRing : theme.colors.background,+ color: currentValue && currentValue.includes('{{') ? theme.colors.templateVariable : theme.colors.text,+ outline: 'none',+ transition: 'all 0.2s ease',+ fontFamily: currentValue && currentValue.includes('{{') ? 'monospace' : 'system-ui, sans-serif'+ }}+ onFocus={(e) => e.target.style.borderColor = theme.colors.focus}+ onBlur={(e) => e.target.style.borderColor = theme.colors.border}+ />+ );++ case 'file':+ const fileInputRef = React.useRef<HTMLInputElement>(null);++ const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {+ const file = e.target.files?.[0];+ if (!file) return;++ const reader = new FileReader();+ reader.onload = () => {+ const base64 = (reader.result as string).split(',')[1]; // Remove data:mime;base64, prefix+ // Store as object with base64 data, filename, and mime type+ onChange({+ type: 'upload',+ data: base64,+ filename: file.name,+ mimeType: file.type || 'application/octet-stream'+ });+ };+ reader.readAsDataURL(file);+ };++ const isUploadedFile = currentValue && typeof currentValue === 'object' && currentValue.type === 'upload';++ // Determine file accept type based on context (e.g., messageType for WhatsApp)+ const getFileAcceptType = () => {+ const messageType = allParameters?.messageType;+ if (messageType) {+ switch (messageType) {+ case 'image':+ return 'image/*';+ case 'video':+ return 'video/*';+ case 'audio':+ return 'audio/*,.ogg,.opus,.mp3,.wav,.m4a';+ case 'document':+ return '.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.csv,.zip,.rar';+ case 'sticker':+ return 'image/webp,.webp';+ default:+ return (parameter as any).typeOptions?.accept || '*/*';+ }+ }+ return (parameter as any).typeOptions?.accept || '*/*';+ };++ return (+ <div>+ <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>+ <input+ type="text"+ value={isUploadedFile ? `[Uploaded] ${currentValue.filename}` : (currentValue || '')}+ onChange={(e) => onChange(e.target.value)}+ placeholder={parameter.placeholder || 'Enter file path or upload'}+ onDragOver={handleDragOver}+ onDragLeave={handleDragLeave}+ onDrop={handleDrop}+ readOnly={isUploadedFile}+ style={{+ flex: 1,+ padding: '8px 12px',+ border: isDragOver ? `2px solid ${theme.colors.focus}` : `1px solid ${theme.colors.border}`,+ borderRadius: '6px',+ fontSize: '13px',+ backgroundColor: isUploadedFile ? theme.colors.backgroundAlt : (isDragOver ? theme.colors.focusRing : theme.colors.background),+ color: isUploadedFile ? theme.colors.success : (currentValue && currentValue.includes?.('{{') ? theme.colors.templateVariable : theme.colors.text),+ outline: 'none',+ transition: 'all 0.2s ease',+ fontFamily: 'monospace'+ }}+ onFocus={(e) => e.target.style.borderColor = theme.colors.focus}+ onBlur={(e) => e.target.style.borderColor = theme.colors.border}+ />+ <input+ key={`file-input-${allParameters?.messageType || 'default'}`}+ ref={fileInputRef}+ type="file"+ onChange={handleFileUpload}+ style={{ display: 'none' }}+ accept={getFileAcceptType()}+ />+ <button+ onClick={() => fileInputRef.current?.click()}+ style={{+ padding: '8px 12px',+ border: `1px solid ${theme.colors.focus}40`,+ borderRadius: '6px',+ backgroundColor: `${theme.colors.focus}18`,+ color: theme.colors.focus,+ cursor: 'pointer',+ fontSize: '13px',+ fontWeight: 600,+ transition: 'all 0.2s ease',+ whiteSpace: 'nowrap'+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = `${theme.colors.focus}30`;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = `${theme.colors.focus}18`;+ }}+ title="Upload file"+ >+ Upload+ </button>+ {isUploadedFile && (+ <button+ onClick={() => {+ onChange('');+ if (fileInputRef.current) fileInputRef.current.value = '';+ }}+ style={{+ padding: '8px 10px',+ border: `1px solid ${theme.colors.error}40`,+ borderRadius: '6px',+ backgroundColor: `${theme.colors.error}18`,+ color: theme.colors.error,+ cursor: 'pointer',+ fontSize: '13px',+ fontWeight: 600,+ transition: 'all 0.2s ease'+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = `${theme.colors.error}30`;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = `${theme.colors.error}18`;+ }}+ title="Clear uploaded file"+ >+ X+ </button>+ )}+ </div>+ <div style={{+ fontSize: '11px',+ color: theme.colors.textSecondary,+ marginTop: '4px',+ fontStyle: 'italic'+ }}>+ {isUploadedFile+ ? `Size: ${(currentValue.data.length * 0.75 / 1024).toFixed(1)} KB | Type: ${currentValue.mimeType}`+ : 'Enter server path or click Upload to select a file'}+ </div>+ </div>+ );++ case 'array':+ const arrayValue = Array.isArray(currentValue) ? currentValue : [];+ return (+ <div>+ <div style={{+ border: `1px solid ${theme.colors.border}`,+ borderRadius: '6px',+ backgroundColor: theme.colors.background,+ maxHeight: '120px',+ overflowY: 'auto'+ }}>+ {parameter.options?.map((option) => (+ <label key={option.value} style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ padding: '8px 12px',+ cursor: 'pointer',+ fontSize: '14px',+ fontFamily: 'system-ui, sans-serif',+ color: theme.colors.text,+ borderBottom: `1px solid ${theme.colors.border}`+ }}>+ <input+ type="checkbox"+ checked={arrayValue.includes(option.value)}+ onChange={(e) => {+ if (e.target.checked) {+ onChange([...arrayValue, option.value]);+ } else {+ onChange(arrayValue.filter((v: any) => v !== option.value));+ }+ }}+ style={{ width: '16px', height: '16px', accentColor: theme.colors.focus }}+ />+ {option.label}+ </label>+ ))}+ </div>+ <div style={{+ fontSize: '11px',+ color: theme.colors.textSecondary,+ marginTop: '4px'+ }}>+ Selected: {arrayValue.length} item{arrayValue.length !== 1 ? 's' : ''}+ </div>+ </div>+ );++ case 'collection':+ return <CollectionRenderer parameter={parameter} value={currentValue} onChange={onChange} allParameters={allParameters} theme={theme} />;++ case 'fixedCollection':+ return <FixedCollectionRenderer parameter={parameter} value={currentValue} onChange={onChange} allParameters={allParameters} theme={theme} />;++ case 'notice':+ // Info/notice display - shows informational text without input+ return (+ <div style={{+ padding: '10px 12px',+ backgroundColor: theme.colors.backgroundAlt,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: '6px',+ fontSize: '13px',+ color: theme.colors.textSecondary,+ lineHeight: '1.5'+ }}>+ {parameter.default || parameter.description || ''}+ </div>+ );++ default:+ return <div style={{ color: theme.colors.error, fontSize: '14px', padding: '8px 12px', backgroundColor: `${theme.colors.error}15`, border: `1px solid ${theme.colors.error}30`, borderRadius: '6px' }}>Unsupported parameter type: {parameter.type}</div>;+ }+ };++ return (+ <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>+ {parameter.type !== 'boolean' && (+ <label style={{+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ marginBottom: '8px',+ fontSize: '13px',+ fontWeight: 600,+ color: theme.colors.text,+ fontFamily: 'system-ui, sans-serif',+ flexShrink: 0+ }}>+ <span>{parameter.displayName}</span>+ {parameter.required && (+ <span style={{+ color: theme.accent.red,+ fontSize: '14px',+ fontWeight: 700+ }}>*</span>+ )}+ </label>+ )}++ <div style={{ flex: 1, minHeight: 0 }}>+ {renderInput()}+ </div>++ {parameter.description && (+ <div style={{+ fontSize: '12px',+ color: theme.colors.textSecondary,+ marginTop: '6px',+ lineHeight: '1.5',+ fontFamily: 'system-ui, sans-serif',+ paddingLeft: '2px',+ flexShrink: 0+ }}>+ {parameter.description}+ </div>+ )}++ </div>+ );+};++export default ParameterRenderer;\ No newline at end of filediff --git a/client/src/components/SquareNode.tsx b/client/src/components/SquareNode.tsxnew file mode 100644index 00000000..0af1657c--- /dev/null+++ b/client/src/components/SquareNode.tsx@@ -0,0 +1,753 @@+import React, { useState, useEffect, useRef, useCallback } from 'react';+import { Handle, Position, NodeProps } from 'reactflow';+import { NodeData } from '../types/NodeTypes';+import { useAppStore } from '../store/useAppStore';+import { nodeDefinitions } from '../nodeDefinitions';+import { useAppTheme } from '../hooks/useAppTheme';+import { ANDROID_SERVICE_NODE_TYPES } from '../nodeDefinitions/androidServiceNodes';+import { ANDROID_DEVICE_NODE_TYPES } from '../nodeDefinitions/androidDeviceNodes';+import { useWebSocket, useWhatsAppStatus } from '../contexts/WebSocketContext';+import { useApiKeys } from '../hooks/useApiKeys';+import { getAIProviderIcon } from './icons/AIProviderIcons';+import { PlayCircleFilled, ScheduleOutlined } from '@ant-design/icons';++// All Android node types combined+const ALL_ANDROID_NODE_TYPES = [...ANDROID_SERVICE_NODE_TYPES, ...ANDROID_DEVICE_NODE_TYPES];++// Google Maps node types+const GOOGLE_MAPS_NODE_TYPES = ['createMap', 'addLocations', 'showNearbyPlaces'];++// WhatsApp node types+const WHATSAPP_NODE_TYPES = ['whatsappConnect', 'whatsappSend', 'whatsappReceive'];++// AI Model node types with their provider IDs+const AI_MODEL_NODE_TYPES: Record<string, string> = {+ 'openaiChatModel': 'openai',+ 'anthropicChatModel': 'anthropic',+ 'geminiChatModel': 'gemini',+};++const SquareNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectable, selected }) => {+ const theme = useAppTheme();+ const { setSelectedNode, renamingNodeId, setRenamingNodeId, updateNodeData } = useAppStore();+ const [hasApiKey, setHasApiKey] = useState(false);+ const [isConfigured, setIsConfigured] = useState(false);+ const isDisabled = data?.disabled === true;++ // Inline rename state+ const [isRenaming, setIsRenaming] = useState(false);+ const [editLabel, setEditLabel] = useState('');+ const inputRef = useRef<HTMLInputElement>(null);++ // Get Android status, node status, and API key status from WebSocket context+ const { androidStatus, getNodeStatus, getApiKeyStatus } = useWebSocket();+ const { getStoredApiKey, validateGoogleMapsKey } = useApiKeys();+ const nodeStatus = getNodeStatus(id);+ const executionStatus = nodeStatus?.status || 'idle';++ // Check if this is a Google Maps node+ const isGoogleMapsNode = type ? GOOGLE_MAPS_NODE_TYPES.includes(type) : false;+ const googleMapsKeyStatus = isGoogleMapsNode ? getApiKeyStatus('google_maps') : undefined;++ // Check if this is an AI model node and get reactive API key status+ const isAIModelNode = type ? type in AI_MODEL_NODE_TYPES : false;+ const aiProviderId = type && AI_MODEL_NODE_TYPES[type] ? AI_MODEL_NODE_TYPES[type] : null;+ const aiKeyStatus = aiProviderId ? getApiKeyStatus(aiProviderId) : undefined;++ const definition = nodeDefinitions[type as keyof typeof nodeDefinitions];++ // Check if this is an Android node+ const isAndroidNode = type ? ALL_ANDROID_NODE_TYPES.includes(type) : false;++ // Android connection status from WebSocket (real-time updates)+ // Service nodes need a paired device to execute, not just relay connection+ const isAndroidConnected = isAndroidNode && androidStatus.paired;++ // Check if this is a WhatsApp node+ const isWhatsAppNode = type ? WHATSAPP_NODE_TYPES.includes(type) : false;++ // WhatsApp connection status from WebSocket (real-time updates)+ const whatsappStatus = useWhatsAppStatus();++ // Execution state - waiting is treated identically to executing+ const isExecuting = executionStatus === 'executing' || executionStatus === 'waiting';+++ // Sync with global renaming state+ useEffect(() => {+ if (renamingNodeId === id) {+ setIsRenaming(true);+ setEditLabel(data?.label || definition?.displayName || type || '');+ } else {+ setIsRenaming(false);+ }+ }, [renamingNodeId, id, data?.label, definition?.displayName, type]);++ // Focus and select input when entering rename mode+ useEffect(() => {+ if (isRenaming && inputRef.current) {+ inputRef.current.focus();+ inputRef.current.select();+ }+ }, [isRenaming]);++ // Handle save rename+ const handleSaveRename = useCallback(() => {+ const newLabel = editLabel.trim();+ const originalLabel = data?.label || definition?.displayName || type || '';++ // Only save if label changed and is not empty+ if (newLabel && newLabel !== originalLabel) {+ updateNodeData(id, { ...data, label: newLabel });+ }++ setIsRenaming(false);+ setRenamingNodeId(null);+ }, [editLabel, data, definition?.displayName, type, id, updateNodeData, setRenamingNodeId]);++ // Handle cancel rename+ const handleCancelRename = useCallback(() => {+ setIsRenaming(false);+ setRenamingNodeId(null);+ }, [setRenamingNodeId]);++ // Handle double-click to rename+ const handleLabelDoubleClick = useCallback(() => {+ setRenamingNodeId(id);+ }, [id, setRenamingNodeId]);++ // Check API key and configuration status+ useEffect(() => {+ const checkConfiguration = async () => {+ try {+ // Determine provider from node definition credentials+ let provider = '';+ const credentials = definition?.credentials?.[0];+ if (credentials?.name) {+ // Map credential names to provider keys+ const credentialToProvider: Record<string, string> = {+ 'googleMapsApi': 'google_maps',+ 'openaiApi': 'openai',+ 'anthropicApi': 'anthropic',+ 'googleAiApi': 'gemini'+ };+ provider = credentialToProvider[credentials.name] || '';+ }++ // Fallback: extract provider from node type if not found in credentials+ if (!provider) {+ if (type?.includes('map') || type?.includes('location')) provider = 'google_maps';+ }++ // Check if API key exists via WebSocket+ const apiKey = provider ? await getStoredApiKey(provider) : null;+ setHasApiKey(!!apiKey);++ // Check if service is configured (has required parameters)+ const hasRequiredParams = data && Object.keys(data).length > 0;+ setIsConfigured(hasRequiredParams && !!apiKey);++ // For Google Maps nodes, trigger validation via WebSocket+ if (isGoogleMapsNode && apiKey) {+ await validateGoogleMapsKey(apiKey);+ }++ if (!apiKey && provider) {+ console.warn(`[SquareNode] ${definition?.displayName} ${id}: No API key configured for ${provider}`);+ }+ } catch (error) {+ console.error('Configuration check error:', error);+ setHasApiKey(false);+ setIsConfigured(false);+ }+ };++ checkConfiguration();+ }, [data, id, type, definition?.displayName, definition?.credentials, isGoogleMapsNode, getStoredApiKey, validateGoogleMapsKey]);++ // Get settings panel controls from store+ const { setWhatsAppSettingsOpen, setAndroidSettingsOpen } = useAppStore();++ const handleParametersClick = (e: React.MouseEvent) => {+ e.stopPropagation();+ // For whatsappConnect, open the WhatsApp settings panel instead+ if (type === 'whatsappConnect') {+ setWhatsAppSettingsOpen(true);+ } else if (type === 'androidDeviceSetup') {+ // For androidDeviceSetup, open the Android settings panel+ setAndroidSettingsOpen(true);+ } else {+ setSelectedNode({ id, type, data, position: { x: 0, y: 0 } });+ }+ };++ // Get status indicator color based on execution state+ const getStatusIndicatorColor = () => {+ // For executing or waiting state, show blue/cyan+ if (executionStatus === 'executing' || executionStatus === 'waiting') {+ return theme.dracula.cyan;+ }+ if (executionStatus === 'success') {+ return theme.dracula.green;+ }+ if (executionStatus === 'error') {+ return theme.dracula.red;+ }++ // Idle state - use Android or configuration status+ if (isAndroidNode) {+ return isAndroidConnected ? theme.dracula.green : theme.dracula.red;+ }++ // WhatsApp nodes - use WebSocket connection status+ if (isWhatsAppNode) {+ if (whatsappStatus.connected) return theme.dracula.green;+ if (whatsappStatus.pairing) return theme.dracula.orange;+ return theme.dracula.red;+ }++ // Google Maps nodes - use WebSocket API key validation status+ if (isGoogleMapsNode && googleMapsKeyStatus) {+ return googleMapsKeyStatus.valid ? theme.dracula.green : theme.dracula.red;+ }++ // AI Model nodes - use reactive WebSocket API key status+ if (isAIModelNode) {+ if (aiKeyStatus?.valid && aiKeyStatus?.hasKey) return theme.dracula.green;+ if (aiKeyStatus?.hasKey) return theme.dracula.orange;+ return theme.dracula.red;+ }++ return isConfigured ? theme.dracula.green : hasApiKey ? theme.dracula.orange : theme.dracula.red;+ };++ const getStatusTitle = () => {+ switch (executionStatus) {+ case 'executing':+ return 'Executing...';+ case 'waiting':+ return nodeStatus?.message || 'Waiting for event...';+ case 'success':+ return 'Execution successful';+ case 'error':+ return `Error: ${nodeStatus?.data?.error || 'Unknown error'}`;+ default:+ if (isAndroidNode) {+ return isAndroidConnected ? 'Android device connected' : 'Android device not connected';+ }+ // WhatsApp nodes - use WebSocket connection status+ if (isWhatsAppNode) {+ if (whatsappStatus.connected) return 'WhatsApp connected';+ if (whatsappStatus.pairing) return 'Pairing in progress...';+ if (whatsappStatus.running) return 'WhatsApp service running';+ return 'WhatsApp not connected';+ }+ // Google Maps nodes - use WebSocket API key validation status+ if (isGoogleMapsNode && googleMapsKeyStatus) {+ return googleMapsKeyStatus.valid+ ? 'Google Maps API key validated'+ : `API key invalid: ${googleMapsKeyStatus.message || 'Validation failed'}`;+ }+ // AI Model nodes - use reactive WebSocket API key status+ if (isAIModelNode) {+ if (aiKeyStatus?.valid && aiKeyStatus?.hasKey) {+ return `${aiProviderId?.charAt(0).toUpperCase()}${aiProviderId?.slice(1)} API key validated`;+ }+ if (aiKeyStatus?.hasKey) {+ return 'API key found, validation pending';+ }+ return 'API key required - configure in Credentials';+ }+ return isConfigured+ ? 'Service configured and ready'+ : hasApiKey+ ? 'API key found, service needs configuration'+ : 'API key required';+ }+ };++ // Common icon name to emoji mapping for fallback+ const iconNameToEmoji: Record<string, string> = {+ brain: '🧠',+ memory: '🧠',+ robot: '🤖',+ ai: '🤖',+ agent: '🤖',+ chat: '💬',+ message: '💬',+ whatsapp: '📱',+ phone: '📱',+ email: '📧',+ mail: '📧',+ webhook: '🔗',+ http: '🌐',+ api: '🔌',+ database: '🗄️',+ file: '📄',+ folder: '📁',+ code: '💻',+ python: '🐍',+ javascript: '📜',+ settings: '⚙️',+ config: '⚙️',+ clock: '⏰',+ schedule: '📅',+ location: '📍',+ map: '🗺️',+ search: '🔍',+ filter: '🔍',+ play: '▶️',+ start: '▶️',+ stop: '⏹️',+ pause: '⏸️',+ send: '📤',+ receive: '📥',+ upload: '⬆️',+ download: '⬇️',+ sync: '🔄',+ refresh: '🔄',+ warning: '⚠️',+ error: '❌',+ success: '✅',+ info: '💡',+ help: '❓',+ user: '👤',+ users: '👥',+ key: '🔑',+ lock: '🔒',+ unlock: '🔓',+ star: '⭐',+ heart: '❤️',+ thunder: '⚡',+ lightning: '⚡',+ fire: '🔥',+ water: '💧',+ cloud: '☁️',+ sun: '☀️',+ moon: '🌙',+ camera: '📷',+ image: '🖼️',+ video: '🎬',+ audio: '🔊',+ music: '🎵',+ bell: '🔔',+ notification: '🔔',+ link: '🔗',+ chain: '🔗',+ tool: '🔧',+ wrench: '🔧',+ hammer: '🔨',+ gear: '⚙️',+ cog: '⚙️',+ bug: '🐛',+ debug: '🐛',+ test: '🧪',+ experiment: '🧪',+ lab: '🧪',+ book: '📖',+ docs: '📚',+ note: '📝',+ edit: '✏️',+ pencil: '✏️',+ trash: '🗑️',+ delete: '🗑️',+ copy: '📋',+ paste: '📋',+ cut: '✂️',+ scissors: '✂️',+ tag: '🏷️',+ label: '🏷️',+ flag: '🚩',+ bookmark: '🔖',+ pin: '📌',+ target: '🎯',+ goal: '🎯',+ trophy: '🏆',+ medal: '🏅',+ gift: '🎁',+ package: '📦',+ box: '📦',+ truck: '🚚',+ shipping: '🚚',+ cart: '🛒',+ shop: '🛍️',+ store: '🏪',+ money: '💰',+ dollar: '💵',+ credit: '💳',+ payment: '💳',+ chart: '📊',+ graph: '📈',+ analytics: '📊',+ stats: '📊',+ dashboard: '📊',+ terminal: '💻',+ console: '💻',+ server: '🖥️',+ computer: '💻',+ mobile: '📱',+ tablet: '📱',+ battery: '🔋',+ wifi: '📶',+ bluetooth: '📶',+ antenna: '📡',+ satellite: '🛰️',+ rocket: '🚀',+ plane: '✈️',+ car: '🚗',+ bike: '🚲',+ train: '🚂',+ ship: '🚢',+ home: '🏠',+ house: '🏠',+ building: '🏢',+ office: '🏢',+ factory: '🏭',+ hospital: '🏥',+ school: '🏫',+ university: '🎓',+ graduation: '🎓',+ world: '🌍',+ globe: '🌐',+ earth: '🌍',+ android: '🤖',+ apple: '🍎',+ windows: '🪟',+ linux: '🐧',+ };++ // Check if string is likely an emoji (contains emoji characters)+ const isEmoji = (str: string): boolean => {+ // Emoji regex pattern - matches most common emojis+ const emojiRegex = /[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]|[\u{1F600}-\u{1F64F}]|[\u{1F680}-\u{1F6FF}]|[\u{1F1E0}-\u{1F1FF}]|[\u{2300}-\u{23FF}]|[\u{2B50}]|[\u{231A}-\u{231B}]|[\u{25AA}-\u{25AB}]|[\u{25B6}]|[\u{25C0}]|[\u{25FB}-\u{25FE}]|[\u{2614}-\u{2615}]|[\u{2648}-\u{2653}]|[\u{267F}]|[\u{2693}]|[\u{26A1}]|[\u{26AA}-\u{26AB}]|[\u{26BD}-\u{26BE}]|[\u{26C4}-\u{26C5}]|[\u{26CE}]|[\u{26D4}]|[\u{26EA}]|[\u{26F2}-\u{26F3}]|[\u{26F5}]|[\u{26FA}]|[\u{26FD}]|[\u{2702}]|[\u{2705}]|[\u{2708}-\u{270D}]|[\u{270F}]|[\u{2712}]|[\u{2714}]|[\u{2716}]|[\u{271D}]|[\u{2721}]|[\u{2728}]|[\u{2733}-\u{2734}]|[\u{2744}]|[\u{2747}]|[\u{274C}]|[\u{274E}]|[\u{2753}-\u{2755}]|[\u{2757}]|[\u{2763}-\u{2764}]|[\u{2795}-\u{2797}]|[\u{27A1}]|[\u{27B0}]|[\u{27BF}]|[\u{E000}-\u{F8FF}]/u;+ return emojiRegex.test(str);+ };++ // Helper to render icon (handles URLs, emojis, and icon names)+ const renderIcon = (icon: string) => {+ // Handle image URLs+ if (icon.startsWith('http') || icon.startsWith('data:') || icon.startsWith('/')) {+ return (+ <img+ src={icon}+ alt="icon"+ style={{+ width: '28px',+ height: '28px',+ objectFit: 'contain',+ borderRadius: '4px'+ }}+ />+ );+ }++ // If it's already an emoji, return it directly+ if (isEmoji(icon)) {+ return icon;+ }++ // Check if it's a known icon name and convert to emoji+ const lowerIcon = icon.toLowerCase().trim();+ if (iconNameToEmoji[lowerIcon]) {+ return iconNameToEmoji[lowerIcon];+ }++ // Fallback: return a generic icon instead of plain text+ console.warn(`[SquareNode] Unknown icon name "${icon}" - using fallback. Add emoji directly or update iconNameToEmoji mapping.`);+ return '📦';+ };++ // Get service icon for display+ const getServiceIcon = () => {+ // Priority 0: Start node - use PlayCircleFilled icon with cyan color (neutral "begin" color)+ if (type === 'start') {+ return <PlayCircleFilled style={{ fontSize: 28, color: theme.dracula.cyan }} />;+ }++ // Cron Scheduler node - use ScheduleOutlined with node definition color+ if (type === 'cronScheduler') {+ return <ScheduleOutlined style={{ fontSize: 28, color: definition?.defaults?.color || nodeColor }} />;+ }++ // Priority 1: Check if this is an AI model node - use official provider icons+ if (type && AI_MODEL_NODE_TYPES[type]) {+ const providerId = AI_MODEL_NODE_TYPES[type];+ const IconComponent = getAIProviderIcon(providerId);+ if (IconComponent) {+ return <IconComponent size={28} />;+ }+ }++ // Priority 2: Custom icon set on the node instance (via data.customIcon)+ if (data?.customIcon && typeof data.customIcon === 'string') {+ return renderIcon(data.customIcon);+ }++ // Priority 3: Use the icon from the node definition if available+ if (definition?.icon && typeof definition.icon === 'string') {+ return renderIcon(definition.icon);+ }++ // Fallback logic based on node type+ if (type?.includes('createMap')) return '🗺️';+ if (type?.includes('addLocations')) return '🌍';+ if (type?.includes('showNearbyPlaces')) return '🔍';++ return '📍';+ };++ // Get the node color from definition or use default+ const nodeColor = definition?.defaults?.color || '#1A73E8';++ return (+ <div+ style={{+ position: 'relative',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ fontFamily: 'system-ui, -apple-system, sans-serif',+ fontSize: '11px',+ cursor: 'pointer',+ }}+ >+ {/* Main Square Node */}+ <div+ style={{+ position: 'relative',+ width: theme.nodeSize.square,+ height: theme.nodeSize.square,+ borderRadius: theme.borderRadius.lg,+ background: theme.isDarkMode+ ? `linear-gradient(135deg, ${nodeColor}25 0%, ${theme.colors.background} 100%)`+ : `linear-gradient(145deg, #ffffff 0%, ${nodeColor}08 100%)`,+ border: `2px solid ${isExecuting+ ? (theme.isDarkMode ? theme.dracula.cyan : '#2563eb')+ : selected+ ? theme.colors.focus+ : theme.isDarkMode ? nodeColor + '80' : `${nodeColor}40`}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ color: theme.colors.text,+ fontSize: theme.nodeSize.squareIcon,+ fontWeight: '600',+ transition: 'all 0.2s ease',+ boxShadow: isExecuting+ ? theme.isDarkMode+ ? `0 4px 12px ${theme.dracula.cyan}66, 0 0 0 3px ${theme.dracula.cyan}4D`+ : `0 0 0 3px rgba(37, 99, 235, 0.5), 0 4px 16px rgba(37, 99, 235, 0.35)`+ : selected+ ? `0 4px 12px ${theme.colors.focusRing}, 0 0 0 1px ${theme.colors.focusRing}`+ : theme.isDarkMode+ ? `0 2px 8px ${nodeColor}40`+ : `0 2px 8px ${nodeColor}20, 0 4px 12px rgba(0,0,0,0.06)`,+ animation: isExecuting ? 'pulse 1.5s ease-in-out infinite' : 'none',+ opacity: isDisabled ? 0.5 : 1,+ }}+ >+ {/* Disabled Overlay */}+ {isDisabled && (+ <div style={{+ position: 'absolute',+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ backgroundColor: 'rgba(128, 128, 128, 0.4)',+ borderRadius: 'inherit',+ zIndex: 35,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ pointerEvents: 'none',+ }}>+ <span style={{ fontSize: '20px', opacity: 0.8, color: theme.colors.textSecondary }}>||</span>+ </div>+ )}++ {/* Service Icon */}+ {getServiceIcon()}++ {/* Parameters Button */}+ <button+ onClick={handleParametersClick}+ style={{+ position: 'absolute',+ top: '-8px',+ right: '-8px',+ width: theme.nodeSize.paramButton,+ height: theme.nodeSize.paramButton,+ borderRadius: theme.borderRadius.sm,+ backgroundColor: theme.isDarkMode ? theme.colors.backgroundAlt : '#ffffff',+ border: `1px solid ${theme.isDarkMode ? theme.colors.border : '#d1d5db'}`,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ fontSize: theme.fontSize.xs,+ color: theme.colors.textSecondary,+ fontWeight: '400',+ transition: theme.transitions.fast,+ zIndex: 30,+ boxShadow: theme.isDarkMode+ ? `0 1px 3px ${theme.colors.shadow}`+ : '0 1px 4px rgba(0,0,0,0.1)'+ }}+ title="Edit Service Parameters"+ >+ ⚙️+ </button>++ {/* Configuration/Execution Status Indicator */}+ <div+ style={{+ position: 'absolute',+ top: '-4px',+ left: '-4px',+ width: theme.nodeSize.statusIndicator,+ height: theme.nodeSize.statusIndicator,+ borderRadius: '50%',+ backgroundColor: getStatusIndicatorColor(),+ border: `2px solid ${theme.isDarkMode ? theme.colors.background : '#ffffff'}`,+ boxShadow: isExecuting+ ? theme.isDarkMode+ ? `0 0 6px ${theme.dracula.cyan}80`+ : '0 0 4px rgba(37, 99, 235, 0.5)'+ : theme.isDarkMode+ ? `0 1px 2px ${theme.colors.shadow}`+ : '0 1px 3px rgba(0,0,0,0.15)',+ zIndex: 30,+ animation: isExecuting ? 'pulse 1s ease-in-out infinite' : 'none',+ }}+ title={getStatusTitle()}+ />++ {/* Square Input Handle */}+ <Handle+ id="input-main"+ type="target"+ position={Position.Left}+ isConnectable={isConnectable}+ style={{+ position: 'absolute',+ left: '-6px',+ top: '50%',+ transform: 'translateY(-50%)',+ width: theme.nodeSize.handle,+ height: theme.nodeSize.handle,+ backgroundColor: theme.isDarkMode ? theme.colors.background : '#ffffff',+ border: `2px solid ${theme.isDarkMode ? theme.colors.textSecondary : '#6b7280'}`,+ borderRadius: '50%',+ zIndex: 20+ }}+ title="Service Input"+ />++ {/* Square Output Handle */}+ <Handle+ id="output-main"+ type="source"+ position={Position.Right}+ isConnectable={isConnectable}+ style={{+ position: 'absolute',+ right: '-6px',+ top: '50%',+ transform: 'translateY(-50%)',+ width: theme.nodeSize.handle,+ height: theme.nodeSize.handle,+ backgroundColor: isConfigured ? nodeColor : theme.colors.textSecondary,+ border: `2px solid ${theme.isDarkMode ? theme.colors.background : '#ffffff'}`,+ borderRadius: '50%',+ zIndex: 20+ }}+ title="Service Output"+ />++ {/* Output Data Indicator - shows when node has execution output */}+ {executionStatus === 'success' && nodeStatus?.data && (+ <div+ style={{+ position: 'absolute',+ bottom: '-4px',+ right: '-4px',+ width: theme.nodeSize.outputBadge,+ height: theme.nodeSize.outputBadge,+ borderRadius: theme.borderRadius.sm,+ backgroundColor: theme.dracula.green,+ border: `1px solid ${theme.isDarkMode ? theme.colors.background : '#ffffff'}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ fontSize: theme.fontSize.xs,+ color: 'white',+ fontWeight: 'bold',+ zIndex: 30,+ boxShadow: theme.isDarkMode+ ? '0 1px 3px rgba(0,0,0,0.2)'+ : '0 1px 3px rgba(0,0,0,0.15)',+ }}+ title="Output data available - click node to view"+ >+ <span style={{ lineHeight: 1 }}>D</span>+ </div>+ )}+ </div>++ {/* Service Name Below Square */}+ {isRenaming ? (+ <input+ ref={inputRef}+ type="text"+ value={editLabel}+ onChange={(e) => setEditLabel(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ handleSaveRename();+ } else if (e.key === 'Escape') {+ handleCancelRename();+ }+ e.stopPropagation();+ }}+ onBlur={handleSaveRename}+ onClick={(e) => e.stopPropagation()}+ style={{+ marginTop: theme.spacing.sm,+ width: '100%',+ maxWidth: '120px',+ padding: '2px 4px',+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.text,+ backgroundColor: theme.colors.backgroundElevated,+ border: `1px solid ${theme.dracula.purple}`,+ borderRadius: theme.borderRadius.sm,+ outline: 'none',+ textAlign: 'center',+ }}+ />+ ) : (+ <div+ onDoubleClick={handleLabelDoubleClick}+ style={{+ marginTop: theme.spacing.sm,+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.text,+ lineHeight: '1.2',+ textAlign: 'center',+ maxWidth: '120px',+ cursor: 'text',+ }}+ title="Double-click to rename"+ >+ {data?.label || definition?.displayName}+ </div>+ )}++ </div>+ );+};++export default SquareNode;\ No newline at end of filediff --git a/client/src/components/StartNode.tsx b/client/src/components/StartNode.tsxnew file mode 100644index 00000000..8645ac66--- /dev/null+++ b/client/src/components/StartNode.tsx@@ -0,0 +1,250 @@+import React, { useState, useEffect, useRef, useCallback } from 'react';+import { Handle, Position, NodeProps } from 'reactflow';+import { NodeData } from '../types/NodeTypes';+import { useAppStore } from '../store/useAppStore';+import { useAppTheme } from '../hooks/useAppTheme';+import { PlayCircleFilled } from '@ant-design/icons';++const StartNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectable, selected }) => {+ const { setSelectedNode, renamingNodeId, setRenamingNodeId, updateNodeData } = useAppStore();+ const theme = useAppTheme();++ // Inline rename state+ const [isRenaming, setIsRenaming] = useState(false);+ const [editLabel, setEditLabel] = useState('');+ const inputRef = useRef<HTMLInputElement>(null);++ const defaultLabel = 'Start';++ // Sync with global renaming state+ useEffect(() => {+ if (renamingNodeId === id) {+ setIsRenaming(true);+ setEditLabel(data?.label || defaultLabel);+ } else {+ setIsRenaming(false);+ }+ }, [renamingNodeId, id, data?.label]);++ // Focus and select input when entering rename mode+ useEffect(() => {+ if (isRenaming && inputRef.current) {+ inputRef.current.focus();+ inputRef.current.select();+ }+ }, [isRenaming]);++ // Handle save rename+ const handleSaveRename = useCallback(() => {+ const newLabel = editLabel.trim();+ const originalLabel = data?.label || defaultLabel;++ // Only save if label changed and is not empty+ if (newLabel && newLabel !== originalLabel) {+ updateNodeData(id, { ...data, label: newLabel });+ }++ setIsRenaming(false);+ setRenamingNodeId(null);+ }, [editLabel, data, id, updateNodeData, setRenamingNodeId]);++ // Handle cancel rename+ const handleCancelRename = useCallback(() => {+ setIsRenaming(false);+ setRenamingNodeId(null);+ }, [setRenamingNodeId]);++ // Handle double-click to rename+ const handleLabelDoubleClick = useCallback(() => {+ setRenamingNodeId(id);+ }, [id, setRenamingNodeId]);++ const handleParametersClick = (e: React.MouseEvent) => {+ e.stopPropagation();+ setSelectedNode({ id, type, data, position: { x: 0, y: 0 } });+ };++ const nodeColor = theme.dracula.cyan; // Cyan color for start node (neutral "begin" color)++ return (+ <div+ style={{+ position: 'relative',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ fontFamily: 'system-ui, -apple-system, sans-serif',+ fontSize: '11px',+ cursor: 'pointer',+ }}+ >+ {/* Main Square Node */}+ <div+ style={{+ position: 'relative',+ width: '60px',+ height: '60px',+ borderRadius: '8px',+ background: theme.isDarkMode+ ? `linear-gradient(135deg, ${nodeColor}20 0%, ${theme.colors.background} 100%)`+ : `linear-gradient(145deg, #ffffff 0%, ${nodeColor}10 100%)`,+ border: `2px solid ${selected+ ? theme.colors.focus+ : theme.isDarkMode ? `${nodeColor}60` : `${nodeColor}50`}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ color: theme.colors.text,+ fontSize: '28px',+ fontWeight: '600',+ transition: 'all 0.2s ease',+ boxShadow: selected+ ? `0 4px 12px ${theme.colors.focusRing}, 0 0 0 1px ${theme.colors.focusRing}`+ : theme.isDarkMode+ ? `0 2px 8px ${nodeColor}30`+ : `0 2px 8px ${nodeColor}25, 0 4px 12px rgba(0,0,0,0.06)`,+ }}+ >+ {/* Play Icon */}+ <PlayCircleFilled style={{ fontSize: 28, color: nodeColor }} />++ {/* Parameters Button */}+ <button+ onClick={handleParametersClick}+ style={{+ position: 'absolute',+ top: '-8px',+ right: '-8px',+ width: '16px',+ height: '16px',+ borderRadius: '3px',+ backgroundColor: theme.isDarkMode ? theme.colors.backgroundAlt : '#ffffff',+ border: `1px solid ${theme.isDarkMode ? theme.colors.border : `${nodeColor}40`}`,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ fontSize: '8px',+ color: theme.colors.textSecondary,+ fontWeight: '400',+ transition: 'all 0.2s ease',+ zIndex: 30,+ boxShadow: theme.isDarkMode+ ? `0 1px 3px ${theme.colors.shadow}`+ : `0 1px 4px ${nodeColor}20`+ }}+ title="Edit Parameters"+ >+ {'\u2699\uFE0F'}+ </button>++ {/* Status Indicator - always green for start */}+ <div+ style={{+ position: 'absolute',+ top: '-4px',+ left: '-4px',+ width: '10px',+ height: '10px',+ borderRadius: '50%',+ backgroundColor: nodeColor,+ border: `2px solid ${theme.isDarkMode ? theme.colors.background : '#ffffff'}`,+ boxShadow: theme.isDarkMode+ ? `0 1px 2px ${theme.colors.shadow}`+ : '0 1px 3px rgba(0,0,0,0.15)',+ zIndex: 30,+ }}+ title="Workflow start point"+ />++ {/* Input Handle - hidden but present for consistency */}+ <Handle+ id="input-main"+ type="target"+ position={Position.Left}+ isConnectable={false}+ style={{+ visibility: 'hidden',+ width: '1px',+ height: '1px',+ }}+ />++ {/* Output Handle */}+ <Handle+ id="output-main"+ type="source"+ position={Position.Right}+ isConnectable={isConnectable}+ style={{+ position: 'absolute',+ right: '-6px',+ top: '50%',+ transform: 'translateY(-50%)',+ width: '8px',+ height: '8px',+ backgroundColor: nodeColor,+ border: `2px solid ${theme.isDarkMode ? theme.colors.background : '#ffffff'}`,+ borderRadius: '50%',+ zIndex: 20+ }}+ title="Workflow Output"+ />+ </div>++ {/* Name Below Square */}+ {isRenaming ? (+ <input+ ref={inputRef}+ type="text"+ value={editLabel}+ onChange={(e) => setEditLabel(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ handleSaveRename();+ } else if (e.key === 'Escape') {+ handleCancelRename();+ }+ e.stopPropagation();+ }}+ onBlur={handleSaveRename}+ onClick={(e) => e.stopPropagation()}+ style={{+ marginTop: '8px',+ width: '100%',+ maxWidth: '120px',+ padding: '2px 4px',+ fontSize: '12px',+ fontWeight: '500',+ color: theme.colors.text,+ backgroundColor: theme.colors.backgroundElevated,+ border: `1px solid ${theme.dracula.purple}`,+ borderRadius: theme.borderRadius.sm,+ outline: 'none',+ textAlign: 'center',+ }}+ />+ ) : (+ <div+ onDoubleClick={handleLabelDoubleClick}+ style={{+ marginTop: '8px',+ fontSize: '12px',+ fontWeight: '500',+ color: theme.colors.text,+ lineHeight: '1.2',+ textAlign: 'center',+ maxWidth: '120px',+ cursor: 'text',+ }}+ title="Double-click to rename"+ >+ {data?.label || defaultLabel}+ </div>+ )}++ </div>+ );+};++export default StartNode;diff --git a/client/src/components/TriggerNode.tsx b/client/src/components/TriggerNode.tsxnew file mode 100644index 00000000..62055537--- /dev/null+++ b/client/src/components/TriggerNode.tsx@@ -0,0 +1,467 @@+/**+ * TriggerNode - Visual component for trigger nodes (no input connections)+ *+ * Trigger nodes start workflows and have only output handles.+ * Based on SquareNode design but without input handles.+ *+ * Used for: cronScheduler, webhookTrigger, whatsappReceive, start+ */+import React, { useState, useEffect, useRef, useCallback } from 'react';+import { Handle, Position, NodeProps } from 'reactflow';+import { NodeData } from '../types/NodeTypes';+import { useAppStore } from '../store/useAppStore';+import { nodeDefinitions } from '../nodeDefinitions';+import { useAppTheme } from '../hooks/useAppTheme';+import { useWebSocket, useWhatsAppStatus } from '../contexts/WebSocketContext';+import { PlayCircleFilled, ScheduleOutlined } from '@ant-design/icons';++const TriggerNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectable, selected }) => {+ const theme = useAppTheme();+ const { setSelectedNode, renamingNodeId, setRenamingNodeId, updateNodeData } = useAppStore();+ const [isConfigured, setIsConfigured] = useState(false);+ const isDisabled = data?.disabled === true;++ // Inline rename state+ const [isRenaming, setIsRenaming] = useState(false);+ const [editLabel, setEditLabel] = useState('');+ const inputRef = useRef<HTMLInputElement>(null);++ // Get node status from WebSocket context+ const { getNodeStatus } = useWebSocket();+ const nodeStatus = getNodeStatus(id);+ const executionStatus = nodeStatus?.status || 'idle';++ // Check if this is a WhatsApp trigger+ const isWhatsAppTrigger = type === 'whatsappReceive';+ const whatsappStatus = useWhatsAppStatus();++ // n8n Pattern: Distinguish between waiting (listening) and executing states+ // - waiting: Trigger is listening for events (shows subtle cyan indicator, no glow/animation)+ // - executing: Only used when trigger itself is being executed (rare, used for manual runs)+ const isWaiting = executionStatus === 'waiting';+ const isExecuting = executionStatus === 'executing';++ const definition = nodeDefinitions[type as keyof typeof nodeDefinitions];++ // Check configuration status+ useEffect(() => {+ const hasRequiredParams = data && Object.keys(data).length > 0;+ setIsConfigured(hasRequiredParams);+ }, [data]);++ // Sync with global renaming state+ useEffect(() => {+ if (renamingNodeId === id) {+ setIsRenaming(true);+ setEditLabel(data?.label || definition?.displayName || type || '');+ } else {+ setIsRenaming(false);+ }+ }, [renamingNodeId, id, data?.label, definition?.displayName, type]);++ // Focus and select input when entering rename mode+ useEffect(() => {+ if (isRenaming && inputRef.current) {+ inputRef.current.focus();+ inputRef.current.select();+ }+ }, [isRenaming]);++ // Handle save rename+ const handleSaveRename = useCallback(() => {+ const newLabel = editLabel.trim();+ const originalLabel = data?.label || definition?.displayName || type || '';++ // Only save if label changed and is not empty+ if (newLabel && newLabel !== originalLabel) {+ updateNodeData(id, { ...data, label: newLabel });+ }++ setIsRenaming(false);+ setRenamingNodeId(null);+ }, [editLabel, data, definition?.displayName, type, id, updateNodeData, setRenamingNodeId]);++ // Handle cancel rename+ const handleCancelRename = useCallback(() => {+ setIsRenaming(false);+ setRenamingNodeId(null);+ }, [setRenamingNodeId]);++ // Handle double-click to rename+ const handleLabelDoubleClick = useCallback(() => {+ setRenamingNodeId(id);+ }, [id, setRenamingNodeId]);++ const handleParametersClick = (e: React.MouseEvent) => {+ e.stopPropagation();+ setSelectedNode({ id, type, data, position: { x: 0, y: 0 } });+ };++ // Get status indicator color based on execution state+ const getStatusIndicatorColor = () => {+ // n8n Pattern: Different colors for different trigger states+ if (isExecuting) {+ return theme.dracula.purple; // Actually executing (manual run)+ }+ if (isWaiting) {+ // Waiting/listening for events - show cyan (active listener)+ return theme.dracula.cyan;+ }+ if (executionStatus === 'success') {+ return theme.dracula.green;+ }+ if (executionStatus === 'error') {+ return theme.dracula.red;+ }++ // WhatsApp trigger - use connection status when idle+ if (isWhatsAppTrigger) {+ if (whatsappStatus.connected) return theme.dracula.green;+ if (whatsappStatus.pairing) return theme.dracula.orange;+ return theme.dracula.red;+ }++ // Idle state - show configured status+ return isConfigured ? theme.dracula.green : theme.dracula.orange;+ };++ const getStatusTitle = () => {+ switch (executionStatus) {+ case 'executing':+ return 'Executing...';+ case 'waiting':+ return nodeStatus?.message || 'Waiting for trigger event...';+ case 'success':+ return 'Trigger fired successfully';+ case 'error':+ return `Error: ${nodeStatus?.data?.error || 'Unknown error'}`;+ default:+ // WhatsApp trigger status+ if (isWhatsAppTrigger) {+ if (whatsappStatus.connected) return 'WhatsApp connected - ready to receive';+ if (whatsappStatus.pairing) return 'Pairing in progress...';+ return 'WhatsApp not connected';+ }+ return isConfigured ? 'Trigger configured and ready' : 'Click to configure trigger';+ }+ };++ // Check if string is likely an emoji+ const isEmoji = (str: string): boolean => {+ const emojiRegex = /[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]|[\u{1F600}-\u{1F64F}]|[\u{1F680}-\u{1F6FF}]|[\u{1F1E0}-\u{1F1FF}]|[\u{2300}-\u{23FF}]|[\u{2B50}]|[\u{231A}-\u{231B}]|[\u{25AA}-\u{25AB}]|[\u{25B6}]|[\u{25C0}]|[\u{25FB}-\u{25FE}]|[\u{2614}-\u{2615}]|[\u{2648}-\u{2653}]|[\u{267F}]|[\u{2693}]|[\u{26A1}]|[\u{26AA}-\u{26AB}]|[\u{26BD}-\u{26BE}]|[\u{26C4}-\u{26C5}]|[\u{26CE}]|[\u{26D4}]|[\u{26EA}]|[\u{26F2}-\u{26F3}]|[\u{26F5}]|[\u{26FA}]|[\u{26FD}]|[\u{2702}]|[\u{2705}]|[\u{2708}-\u{270D}]|[\u{270F}]|[\u{2712}]|[\u{2714}]|[\u{2716}]|[\u{271D}]|[\u{2721}]|[\u{2728}]|[\u{2733}-\u{2734}]|[\u{2744}]|[\u{2747}]|[\u{274C}]|[\u{274E}]|[\u{2753}-\u{2755}]|[\u{2757}]|[\u{2763}-\u{2764}]|[\u{2795}-\u{2797}]|[\u{27A1}]|[\u{27B0}]|[\u{27BF}]|[\u{E000}-\u{F8FF}]/u;+ return emojiRegex.test(str);+ };++ // Helper to render icon+ const renderIcon = (icon: string) => {+ if (icon.startsWith('http') || icon.startsWith('data:') || icon.startsWith('/')) {+ return (+ <img+ src={icon}+ alt="icon"+ style={{+ width: '28px',+ height: '28px',+ objectFit: 'contain',+ borderRadius: '4px'+ }}+ />+ );+ }++ if (isEmoji(icon)) {+ return icon;+ }++ // Fallback+ return '⚡';+ };++ // Get trigger icon for display+ const getTriggerIcon = () => {+ // Start node - use PlayCircleFilled icon+ if (type === 'start') {+ return <PlayCircleFilled style={{ fontSize: 28, color: theme.dracula.cyan }} />;+ }++ // Cron Scheduler - use ScheduleOutlined+ if (type === 'cronScheduler') {+ return <ScheduleOutlined style={{ fontSize: 28, color: definition?.defaults?.color || nodeColor }} />;+ }++ // Use the icon from the node definition if available+ if (definition?.icon && typeof definition.icon === 'string') {+ return renderIcon(definition.icon);+ }++ // Fallback to lightning bolt for triggers+ return '⚡';+ };++ // Get the node color from definition or use default trigger color+ const nodeColor = definition?.defaults?.color || '#f59e0b';++ return (+ <div+ style={{+ position: 'relative',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ fontFamily: 'system-ui, -apple-system, sans-serif',+ fontSize: '11px',+ cursor: 'pointer',+ }}+ >+ {/* Main Trigger Node */}+ {/* n8n Pattern: Only show glow/animation for actual executing state, not for waiting */}+ <div+ style={{+ position: 'relative',+ width: theme.nodeSize.square,+ height: theme.nodeSize.square,+ borderRadius: theme.borderRadius.lg,+ background: theme.isDarkMode+ ? `linear-gradient(135deg, ${nodeColor}25 0%, ${theme.colors.background} 100%)`+ : `linear-gradient(145deg, #ffffff 0%, ${nodeColor}08 100%)`,+ border: `2px solid ${+ isExecuting+ ? (theme.isDarkMode ? theme.dracula.purple : '#2563eb')+ : selected+ ? theme.colors.focus+ : theme.isDarkMode ? nodeColor + '80' : `${nodeColor}40`+ }`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ color: theme.colors.text,+ fontSize: theme.nodeSize.squareIcon,+ fontWeight: '600',+ transition: 'all 0.2s ease',+ boxShadow: isExecuting+ ? theme.isDarkMode+ ? `0 4px 12px ${theme.dracula.purple}66, 0 0 0 3px ${theme.dracula.purple}4D`+ : `0 0 0 3px rgba(37, 99, 235, 0.5), 0 4px 16px rgba(37, 99, 235, 0.35)`+ : selected+ ? `0 4px 12px ${theme.colors.focusRing}, 0 0 0 1px ${theme.colors.focusRing}`+ : theme.isDarkMode+ ? `0 2px 8px ${nodeColor}40`+ : `0 2px 8px ${nodeColor}20, 0 4px 12px rgba(0,0,0,0.06)`,+ // Subtle animation for both modes+ animation: isExecuting ? 'pulse 1.5s ease-in-out infinite' : 'none',+ opacity: isDisabled ? 0.5 : 1,+ }}+ >+ {/* Disabled Overlay */}+ {isDisabled && (+ <div style={{+ position: 'absolute',+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ backgroundColor: 'rgba(128, 128, 128, 0.4)',+ borderRadius: 'inherit',+ zIndex: 35,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ pointerEvents: 'none',+ }}>+ <span style={{ fontSize: '20px', opacity: 0.8, color: theme.colors.textSecondary }}>||</span>+ </div>+ )}++ {/* Trigger Icon */}+ {getTriggerIcon()}++ {/* Parameters Button */}+ <button+ onClick={handleParametersClick}+ style={{+ position: 'absolute',+ top: '-8px',+ right: '-8px',+ width: theme.nodeSize.paramButton,+ height: theme.nodeSize.paramButton,+ borderRadius: theme.borderRadius.sm,+ backgroundColor: theme.isDarkMode ? theme.colors.backgroundAlt : '#ffffff',+ border: `1px solid ${theme.isDarkMode ? theme.colors.border : '#d1d5db'}`,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ fontSize: theme.fontSize.xs,+ color: theme.colors.textSecondary,+ fontWeight: '400',+ transition: theme.transitions.fast,+ zIndex: 30,+ boxShadow: theme.isDarkMode+ ? `0 1px 3px ${theme.colors.shadow}`+ : '0 1px 4px rgba(0,0,0,0.1)'+ }}+ title="Configure Trigger"+ >+ ⚙️+ </button>++ {/* Execution Status Indicator */}+ {/* n8n Pattern: No glow for waiting, only for actual execution */}+ <div+ style={{+ position: 'absolute',+ top: '-4px',+ left: '-4px',+ width: theme.nodeSize.statusIndicator,+ height: theme.nodeSize.statusIndicator,+ borderRadius: '50%',+ backgroundColor: getStatusIndicatorColor(),+ border: `2px solid ${theme.isDarkMode ? theme.colors.background : '#ffffff'}`,+ boxShadow: isExecuting+ ? theme.isDarkMode+ ? `0 0 6px ${theme.dracula.purple}80`+ : '0 0 4px rgba(37, 99, 235, 0.5)'+ : theme.isDarkMode+ ? `0 1px 2px ${theme.colors.shadow}`+ : '0 1px 3px rgba(0,0,0,0.15)',+ zIndex: 30,+ // Subtle pulse animation for both modes+ animation: isExecuting ? 'pulse 1s ease-in-out infinite' : 'none',+ }}+ title={getStatusTitle()}+ />++ {/* NO INPUT HANDLE - Trigger nodes don't have inputs */}++ {/* Trigger Badge - Lightning bolt indicator on bottom-left */}+ <div+ style={{+ position: 'absolute',+ bottom: '-4px',+ left: '-4px',+ width: theme.nodeSize.outputBadge,+ height: theme.nodeSize.outputBadge,+ borderRadius: theme.borderRadius.sm,+ backgroundColor: theme.dracula.yellow,+ border: `1px solid ${theme.isDarkMode ? theme.colors.background : '#ffffff'}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ fontSize: theme.fontSize.xs,+ zIndex: 30,+ boxShadow: theme.isDarkMode+ ? `0 1px 3px ${theme.colors.shadow}`+ : '0 1px 3px rgba(0,0,0,0.15)',+ }}+ title="Trigger Node - Starts workflow execution"+ >+ <span style={{ lineHeight: 1, color: theme.isDarkMode ? theme.colors.background : '#1a1d21' }}>⚡</span>+ </div>++ {/* Output Handle (right side) */}+ <Handle+ id="output-main"+ type="source"+ position={Position.Right}+ isConnectable={isConnectable}+ style={{+ position: 'absolute',+ right: '-6px',+ top: '50%',+ transform: 'translateY(-50%)',+ width: theme.nodeSize.handle,+ height: theme.nodeSize.handle,+ backgroundColor: isConfigured ? nodeColor : theme.colors.textSecondary,+ border: `2px solid ${theme.isDarkMode ? theme.colors.background : '#ffffff'}`,+ borderRadius: '50%',+ zIndex: 20+ }}+ title="Trigger Output"+ />++ {/* Output Data Indicator */}+ {executionStatus === 'success' && nodeStatus?.data && (+ <div+ style={{+ position: 'absolute',+ bottom: '-4px',+ right: '-4px',+ width: theme.nodeSize.outputBadge,+ height: theme.nodeSize.outputBadge,+ borderRadius: theme.borderRadius.sm,+ backgroundColor: theme.dracula.green,+ border: `1px solid ${theme.isDarkMode ? theme.colors.background : '#ffffff'}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ fontSize: theme.fontSize.xs,+ color: 'white',+ fontWeight: 'bold',+ zIndex: 30,+ boxShadow: theme.isDarkMode+ ? '0 1px 3px rgba(0,0,0,0.2)'+ : '0 1px 3px rgba(0,0,0,0.15)',+ }}+ title="Output data available - click node to view"+ >+ <span style={{ lineHeight: 1 }}>D</span>+ </div>+ )}+ </div>++ {/* Trigger Name Below Node */}+ {isRenaming ? (+ <input+ ref={inputRef}+ type="text"+ value={editLabel}+ onChange={(e) => setEditLabel(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ handleSaveRename();+ } else if (e.key === 'Escape') {+ handleCancelRename();+ }+ e.stopPropagation();+ }}+ onBlur={handleSaveRename}+ onClick={(e) => e.stopPropagation()}+ style={{+ marginTop: theme.spacing.sm,+ width: '100%',+ maxWidth: '120px',+ padding: '2px 4px',+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.text,+ backgroundColor: theme.colors.backgroundElevated,+ border: `1px solid ${theme.dracula.purple}`,+ borderRadius: theme.borderRadius.sm,+ outline: 'none',+ textAlign: 'center',+ }}+ />+ ) : (+ <div+ onDoubleClick={handleLabelDoubleClick}+ style={{+ marginTop: theme.spacing.sm,+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.text,+ lineHeight: '1.2',+ textAlign: 'center',+ maxWidth: '120px',+ cursor: 'text',+ }}+ title="Double-click to rename"+ >+ {data?.label || definition?.displayName}+ </div>+ )}++ </div>+ );+};++export default TriggerNode;diff --git a/client/src/components/auth/LoginPage.tsx b/client/src/components/auth/LoginPage.tsxnew file mode 100644index 00000000..694d32ac--- /dev/null+++ b/client/src/components/auth/LoginPage.tsx@@ -0,0 +1,247 @@+/**+ * Login/Register Page with Dracula theme.+ * Shows login form, or register form if registration is available.+ */++import React, { useState } from 'react';+import { useAuth } from '../../contexts/AuthContext';+import { dracula } from '../../styles/theme';++const LoginPage: React.FC = () => {+ const { login, register, canRegister, error, isLoading } = useAuth();++ const [isRegistering, setIsRegistering] = useState(false);+ const [email, setEmail] = useState('');+ const [password, setPassword] = useState('');+ const [displayName, setDisplayName] = useState('');+ const [localError, setLocalError] = useState<string | null>(null);++ const handleSubmit = async (e: React.FormEvent) => {+ e.preventDefault();+ setLocalError(null);++ if (!email || !password) {+ setLocalError('Email and password are required');+ return;+ }++ if (isRegistering) {+ if (!displayName) {+ setLocalError('Display name is required');+ return;+ }+ if (password.length < 8) {+ setLocalError('Password must be at least 8 characters');+ return;+ }+ await register(email, password, displayName);+ } else {+ await login(email, password);+ }+ };++ const toggleMode = () => {+ setIsRegistering(!isRegistering);+ setLocalError(null);+ };++ const displayError = localError || error;++ return (+ <div style={styles.container}>+ <div style={styles.card}>+ {/* Logo/Title */}+ <div style={styles.header}>+ <h1 style={styles.title}>MachinaOs</h1>+ <p style={styles.subtitle}>+ {isRegistering ? 'Create your account' : 'Sign in to continue'}+ </p>+ </div>++ {/* Error Message */}+ {displayError && (+ <div style={styles.errorBox}>+ {displayError}+ </div>+ )}++ {/* Form */}+ <form onSubmit={handleSubmit} style={styles.form}>+ {isRegistering && (+ <div style={styles.inputGroup}>+ <label style={styles.label}>Display Name</label>+ <input+ type="text"+ value={displayName}+ onChange={(e) => setDisplayName(e.target.value)}+ style={styles.input}+ placeholder="Your name"+ disabled={isLoading}+ />+ </div>+ )}++ <div style={styles.inputGroup}>+ <label style={styles.label}>Email</label>+ <input+ type="email"+ value={email}+ onChange={(e) => setEmail(e.target.value)}+ style={styles.input}+ placeholder="[email protected]"+ disabled={isLoading}+ autoComplete="email"+ />+ </div>++ <div style={styles.inputGroup}>+ <label style={styles.label}>Password</label>+ <input+ type="password"+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ style={styles.input}+ placeholder={isRegistering ? 'At least 8 characters' : 'Your password'}+ disabled={isLoading}+ autoComplete={isRegistering ? 'new-password' : 'current-password'}+ />+ </div>++ <button+ type="submit"+ style={{+ ...styles.submitButton,+ opacity: isLoading ? 0.7 : 1,+ cursor: isLoading ? 'not-allowed' : 'pointer'+ }}+ disabled={isLoading}+ >+ {isLoading+ ? 'Please wait...'+ : isRegistering+ ? 'Create Account'+ : 'Sign In'}+ </button>+ </form>++ {/* Toggle Login/Register */}+ {canRegister && (+ <div style={styles.toggleSection}>+ <span style={styles.toggleText}>+ {isRegistering ? 'Already have an account?' : "Don't have an account?"}+ </span>+ <button+ onClick={toggleMode}+ style={styles.toggleButton}+ disabled={isLoading}+ >+ {isRegistering ? 'Sign In' : 'Register'}+ </button>+ </div>+ )}+ </div>+ </div>+ );+};++const styles: Record<string, React.CSSProperties> = {+ container: {+ display: 'flex',+ justifyContent: 'center',+ alignItems: 'center',+ minHeight: '100vh',+ backgroundColor: dracula.background,+ padding: 20,+ },+ card: {+ backgroundColor: dracula.currentLine,+ borderRadius: 12,+ padding: 40,+ width: '100%',+ maxWidth: 400,+ boxShadow: '0 8px 32px rgba(0, 0, 0, 0.4)',+ },+ header: {+ textAlign: 'center',+ marginBottom: 24,+ },+ title: {+ color: dracula.purple,+ fontSize: 32,+ fontWeight: 700,+ margin: 0,+ marginBottom: 8,+ },+ subtitle: {+ color: dracula.comment,+ fontSize: 14,+ margin: 0,+ },+ errorBox: {+ backgroundColor: `${dracula.red}20`,+ border: `1px solid ${dracula.red}`,+ borderRadius: 6,+ padding: '12px 16px',+ marginBottom: 20,+ color: dracula.red,+ fontSize: 13,+ },+ form: {+ display: 'flex',+ flexDirection: 'column',+ gap: 16,+ },+ inputGroup: {+ display: 'flex',+ flexDirection: 'column',+ gap: 6,+ },+ label: {+ color: dracula.foreground,+ fontSize: 13,+ fontWeight: 500,+ },+ input: {+ backgroundColor: dracula.background,+ border: `1px solid ${dracula.comment}50`,+ borderRadius: 6,+ padding: '12px 14px',+ fontSize: 14,+ color: dracula.foreground,+ outline: 'none',+ transition: 'border-color 0.2s, box-shadow 0.2s',+ },+ submitButton: {+ backgroundColor: dracula.purple,+ color: dracula.background,+ border: 'none',+ borderRadius: 6,+ padding: '14px 20px',+ fontSize: 15,+ fontWeight: 600,+ marginTop: 8,+ transition: 'opacity 0.2s, transform 0.1s',+ },+ toggleSection: {+ textAlign: 'center',+ marginTop: 24,+ paddingTop: 20,+ borderTop: `1px solid ${dracula.comment}30`,+ },+ toggleText: {+ color: dracula.comment,+ fontSize: 13,+ marginRight: 8,+ },+ toggleButton: {+ background: 'none',+ border: 'none',+ color: dracula.cyan,+ fontSize: 13,+ fontWeight: 500,+ cursor: 'pointer',+ padding: 0,+ },+};++export default LoginPage;diff --git a/client/src/components/auth/ProtectedRoute.tsx b/client/src/components/auth/ProtectedRoute.tsxnew file mode 100644index 00000000..3a423982--- /dev/null+++ b/client/src/components/auth/ProtectedRoute.tsx@@ -0,0 +1,59 @@+/**+ * Protected Route component.+ * Wraps content that requires authentication.+ * Shows LoginPage if user is not authenticated.+ */++import React from 'react';+import { useAuth } from '../../contexts/AuthContext';+import LoginPage from './LoginPage';++interface ProtectedRouteProps {+ children: React.ReactNode;+}++const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ children }) => {+ const { isAuthenticated, isLoading } = useAuth();++ // Show loading spinner while checking auth+ if (isLoading) {+ return (+ <div style={{+ display: 'flex',+ justifyContent: 'center',+ alignItems: 'center',+ height: '100vh',+ backgroundColor: '#0d1117',+ color: '#c9d1d9'+ }}>+ <div style={{ textAlign: 'center' }}>+ <div style={{+ width: 40,+ height: 40,+ border: '3px solid #30363d',+ borderTopColor: '#bd93f9',+ borderRadius: '50%',+ animation: 'spin 1s linear infinite',+ margin: '0 auto 16px'+ }} />+ <style>{`+ @keyframes spin {+ to { transform: rotate(360deg); }+ }+ `}</style>+ <p>Loading...</p>+ </div>+ </div>+ );+ }++ // Show login page if not authenticated+ if (!isAuthenticated) {+ return <LoginPage />;+ }++ // Render protected content+ return <>{children}</>;+};++export default ProtectedRoute;diff --git a/client/src/components/base/BaseChatModelNode.tsx b/client/src/components/base/BaseChatModelNode.tsxnew file mode 100644index 00000000..a0c6d246--- /dev/null+++ b/client/src/components/base/BaseChatModelNode.tsx@@ -0,0 +1,271 @@+import React, { useState, useEffect } from 'react';+import { Handle, Position, NodeProps } from 'reactflow';+import { NodeData } from '../../types/NodeTypes';+import { useAppStore } from '../../store/useAppStore';+import { useWebSocket } from '../../contexts/WebSocketContext';+import { useApiKeys } from '../../hooks/useApiKeys';+import { useAppTheme } from '../../hooks/useAppTheme';++interface BaseChatModelNodeProps extends NodeProps<NodeData> {+ providerId: string;+ displayName: string;+ icon: string;+ color: string;+}++const BaseChatModelNode: React.FC<BaseChatModelNodeProps> = ({+ id,+ type,+ data,+ isConnectable,+ selected,+ providerId,+ displayName,+ icon,+ color+}) => {+ const theme = useAppTheme();+ const { setSelectedNode } = useAppStore();+ const [hasApiKey, setHasApiKey] = useState(false);+ const [isConfigured, setIsConfigured] = useState(false);+ const isDisabled = data?.disabled === true;++ // Get node status from WebSocket context+ const { getNodeStatus } = useWebSocket();+ const { getStoredApiKey } = useApiKeys();+ const nodeStatus = getNodeStatus(id);+ const executionStatus = nodeStatus?.status || 'idle';++ useEffect(() => {+ const checkConfiguration = async () => {+ try {+ const apiKey = await getStoredApiKey(providerId);+ const hasApiKeyStored = !!apiKey;+ setHasApiKey(hasApiKeyStored);++ const hasModel = data?.model && data.model.trim() !== '';+ const configured = hasModel && hasApiKeyStored;++ setIsConfigured(configured);+ } catch (error) {+ console.error(`[BaseChatModelNode] ${displayName} ${id}: Configuration check error:`, error);+ setHasApiKey(false);+ setIsConfigured(false);+ }+ };++ checkConfiguration();+ }, [data?.model, id, providerId, displayName, getStoredApiKey]);++ const handleParametersClick = (e: React.MouseEvent) => {+ e.stopPropagation();+ setSelectedNode({ id, type, data, position: { x: 0, y: 0 } });+ };++ // Get status indicator color based on execution state+ const getStatusIndicatorColor = () => {+ switch (executionStatus) {+ case 'executing':+ return theme.dracula.cyan; // Executing+ case 'success':+ return theme.dracula.green; // Success+ case 'error':+ return theme.dracula.red; // Error+ default:+ // Idle - use configuration status+ return isConfigured ? theme.dracula.green : hasApiKey ? theme.dracula.orange : theme.dracula.red;+ }+ };++ const getStatusTitle = () => {+ switch (executionStatus) {+ case 'executing':+ return 'Executing...';+ case 'success':+ return 'Execution successful';+ case 'error':+ return `Error: ${nodeStatus?.data?.error || 'Unknown error'}`;+ default:+ return isConfigured+ ? 'Model configured and ready'+ : hasApiKey+ ? 'API key found, model needs configuration'+ : 'API key required';+ }+ };++ const isExecuting = executionStatus === 'executing';++ return (+ <div+ style={{+ position: 'relative',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ fontFamily: 'system-ui, -apple-system, sans-serif',+ fontSize: theme.fontSize.xs,+ cursor: 'pointer',+ }}+ >+ {/* Main Circular Node */}+ <div+ style={{+ position: 'relative',+ width: theme.nodeSize.square,+ height: theme.nodeSize.square,+ borderRadius: '50%',+ background: isConfigured ? color : theme.colors.textMuted,+ border: `2px solid ${selected ? theme.colors.focus : isExecuting ? theme.dracula.cyan : isConfigured ? color : theme.dracula.red}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ color: 'white',+ fontSize: type === 'aiAgent' ? theme.fontSize.lg : theme.nodeSize.squareIcon,+ fontWeight: theme.fontWeight.semibold,+ transition: theme.transitions.fast,+ boxShadow: selected+ ? `0 4px 12px ${theme.colors.focusRing}, 0 0 0 2px ${theme.colors.focusRing}`+ : isExecuting+ ? `0 4px 12px ${theme.dracula.cyan}66, 0 0 0 3px ${theme.dracula.cyan}4D`+ : isConfigured+ ? `0 2px 8px ${theme.colors.shadow}`+ : `0 2px 8px ${theme.dracula.red}4D`,+ animation: isExecuting ? 'pulse 1.5s ease-in-out infinite' : 'none',+ opacity: isDisabled ? 0.5 : 1,+ }}+ >+ {/* Disabled Overlay */}+ {isDisabled && (+ <div style={{+ position: 'absolute',+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ backgroundColor: 'rgba(128, 128, 128, 0.4)',+ borderRadius: 'inherit',+ zIndex: 35,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ pointerEvents: 'none',+ }}>+ <span style={{ fontSize: '20px', opacity: 0.8, color: theme.colors.textSecondary }}>||</span>+ </div>+ )}++ {/* Provider Icon */}+ {icon}++ {/* Parameters Button */}+ <button+ onClick={handleParametersClick}+ style={{+ position: 'absolute',+ top: '-8px',+ right: '-8px',+ width: theme.nodeSize.paramButton,+ height: theme.nodeSize.paramButton,+ borderRadius: '50%',+ backgroundColor: theme.colors.backgroundAlt,+ border: `1px solid ${theme.colors.border}`,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ fontSize: theme.fontSize.xs,+ color: theme.colors.textSecondary,+ fontWeight: '400',+ transition: theme.transitions.fast,+ zIndex: 30,+ boxShadow: `0 1px 3px ${theme.colors.shadow}`+ }}+ title="Edit Model Parameters"+ >+ ⚙️+ </button>++ {/* Configuration/Execution Status Indicator */}+ <div+ style={{+ position: 'absolute',+ top: '-4px',+ left: '-4px',+ width: theme.nodeSize.statusIndicator,+ height: theme.nodeSize.statusIndicator,+ borderRadius: '50%',+ backgroundColor: getStatusIndicatorColor(),+ border: `2px solid ${theme.colors.background}`,+ boxShadow: isExecuting+ ? `0 0 8px ${theme.dracula.cyan}99`+ : `0 1px 3px ${theme.colors.shadow}`,+ zIndex: 30,+ animation: isExecuting ? 'pulse 1s ease-in-out infinite' : 'none',+ }}+ title={getStatusTitle()}+ />++ {/* Diamond Output Handle */}+ <Handle+ id="output-model"+ type="source"+ position={Position.Top}+ isConnectable={isConnectable}+ style={{+ position: 'absolute',+ top: '-6px',+ left: '50%',+ transform: 'translateX(-50%) rotate(45deg)',+ width: theme.nodeSize.statusIndicator,+ height: theme.nodeSize.statusIndicator,+ backgroundColor: isConfigured ? color : theme.colors.textMuted,+ border: `2px solid ${theme.colors.background}`,+ borderRadius: '0',+ opacity: isConfigured ? 1 : 0.6,+ zIndex: 20+ }}+ title={isConfigured ? 'Model Configuration Output - Connect to AI Agent' : 'Connect to AI Agent (configure API key and model before running)'}+ />++ {/* Diamond Input Handle for Prompt */}+ <Handle+ id="input-prompt"+ type="target"+ position={Position.Bottom}+ isConnectable={isConnectable}+ style={{+ position: 'absolute',+ bottom: '-6px',+ left: '50%',+ transform: 'translateX(-50%) rotate(45deg)',+ width: theme.nodeSize.statusIndicator,+ height: theme.nodeSize.statusIndicator,+ backgroundColor: theme.colors.background,+ border: `2px solid ${theme.colors.textMuted}`,+ borderRadius: '0',+ zIndex: 20+ }}+ title="Prompt Input (optional)"+ />+ </div>++ {/* Model Name Below Circle */}+ <div+ style={{+ marginTop: theme.spacing.sm,+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.text,+ lineHeight: '1.2',+ textAlign: 'center',+ maxWidth: '120px'+ }}+ >+ {data?.label || displayName}+ </div>+ </div>+ );+};++export default BaseChatModelNode;\ No newline at end of filediff --git a/client/src/components/icons/AIProviderIcons.tsx b/client/src/components/icons/AIProviderIcons.tsxnew file mode 100644index 00000000..6ffa6e41--- /dev/null+++ b/client/src/components/icons/AIProviderIcons.tsx@@ -0,0 +1,32 @@+// AI Provider Icons - Using @lobehub/icons for official brand logos+import React from 'react';+import { OpenAI, Claude, Gemini } from '@lobehub/icons';++// Icon size constant for consistency+const ICON_SIZE = 28;++// Export icon components with consistent sizing+// OpenAI uses Avatar (no Color variant), Claude and Gemini use Color variant+export const OpenAIIcon: React.FC<{ size?: number }> = ({ size = ICON_SIZE }) => (+ <OpenAI.Avatar size={size} />+);++export const ClaudeIcon: React.FC<{ size?: number }> = ({ size = ICON_SIZE }) => (+ <Claude.Color size={size} />+);++export const GeminiIcon: React.FC<{ size?: number }> = ({ size = ICON_SIZE }) => (+ <Gemini.Color size={size} />+);++// Map provider IDs to their icon components+export const AI_PROVIDER_ICONS: Record<string, React.FC<{ size?: number }>> = {+ openai: OpenAIIcon,+ anthropic: ClaudeIcon,+ gemini: GeminiIcon,+};++// Get icon component by provider ID+export const getAIProviderIcon = (providerId: string): React.FC<{ size?: number }> | null => {+ return AI_PROVIDER_ICONS[providerId] || null;+};diff --git a/client/src/components/maps/GoogleMapsPicker.tsx b/client/src/components/maps/GoogleMapsPicker.tsxnew file mode 100644index 00000000..bc002d5c--- /dev/null+++ b/client/src/components/maps/GoogleMapsPicker.tsx@@ -0,0 +1,136 @@+import React, { useEffect, useRef } from 'react';+import { theme } from '../../styles/theme';+import { loadGoogleMaps } from '../../utils/googleMapsLoader';++interface GoogleMapsPickerProps {+ lat: number;+ lng: number;+ onLocationClick: (lat: number, lng: number) => void;+ apiKey?: string;+ zoom?: number;+ mapTypeId?: string;+ height?: string;+ width?: string;+}++const GoogleMapsPicker: React.FC<GoogleMapsPickerProps> = ({+ lat,+ lng,+ onLocationClick,+ apiKey,+ zoom = 13,+ mapTypeId = 'ROADMAP',+ height = '100%',+ width = '100%'+}) => {+ const mapRef = useRef<HTMLDivElement>(null);+ const mapInstanceRef = useRef<google.maps.Map | null>(null);+ const markerRef = useRef<google.maps.Marker | null>(null);++ useEffect(() => {+ if (!mapRef.current || !apiKey) return;++ // Load Google Maps API using centralized loader+ const loadAndInitialize = async () => {+ try {+ await loadGoogleMaps({+ apiKey,+ libraries: ['geometry']+ });+ initializeMap();+ } catch (error) {+ console.error('Failed to load Google Maps API:', error);+ }+ };++ loadAndInitialize();++ function initializeMap() {+ if (!mapRef.current || !window.google?.maps) return;++ const mapOptions: google.maps.MapOptions = {+ center: { lat, lng },+ zoom,+ mapTypeId: window.google.maps.MapTypeId[mapTypeId as keyof typeof google.maps.MapTypeId] || google.maps.MapTypeId.ROADMAP,+ clickableIcons: false,+ disableDefaultUI: false,+ zoomControl: true,+ mapTypeControl: true,+ streetViewControl: true,+ fullscreenControl: true+ };++ mapInstanceRef.current = new google.maps.Map(mapRef.current, mapOptions);++ // Create marker+ markerRef.current = new google.maps.Marker({+ position: { lat, lng },+ map: mapInstanceRef.current,+ draggable: true,+ title: 'Selected Location - Click or drag to change'+ });++ // Add click listeners+ mapInstanceRef.current.addListener('click', (e: google.maps.MapMouseEvent) => {+ if (e.latLng) {+ const newLat = e.latLng.lat();+ const newLng = e.latLng.lng();+ onLocationClick(newLat, newLng);+ }+ });++ // Add marker drag listener+ markerRef.current.addListener('dragend', (e: google.maps.MapMouseEvent) => {+ if (e.latLng) {+ const newLat = e.latLng.lat();+ const newLng = e.latLng.lng();+ onLocationClick(newLat, newLng);+ }+ });+ }+ }, [apiKey, lat, lng, zoom, mapTypeId]);++ // Update marker position when coordinates change+ useEffect(() => {+ if (markerRef.current && mapInstanceRef.current) {+ const newPosition = { lat, lng };+ markerRef.current.setPosition(newPosition);+ mapInstanceRef.current.setCenter(newPosition);+ }+ }, [lat, lng]);++ if (!apiKey) {+ return (+ <div style={{+ height,+ width,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: '#f5f5f5',+ color: theme.colors.textSecondary,+ fontSize: theme.fontSize.sm,+ textAlign: 'center',+ padding: theme.spacing.lg,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.sm+ }}>+ Google Maps API key required for map display+ </div>+ );+ }++ return (+ <div+ ref={mapRef}+ style={{+ height,+ width,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.sm+ }}+ />+ );+};++export default GoogleMapsPicker;\ No newline at end of filediff --git a/client/src/components/maps/MapsPreviewPanel.tsx b/client/src/components/maps/MapsPreviewPanel.tsxnew file mode 100644index 00000000..abcd7e76--- /dev/null+++ b/client/src/components/maps/MapsPreviewPanel.tsx@@ -0,0 +1,107 @@+import React from 'react';+import GoogleMapsPicker from './GoogleMapsPicker';+import { theme } from '../../styles/theme';++interface MapsPreviewPanelProps {+ lat: number;+ lng: number;+ zoom?: number;+ mapTypeId?: string;+ apiKey?: string;+ onLocationClick: (lat: number, lng: number) => void;+ title?: string;+ description?: string;+}++const MapsPreviewPanel: React.FC<MapsPreviewPanelProps> = ({+ lat,+ lng,+ zoom = 13,+ mapTypeId = 'ROADMAP',+ apiKey,+ onLocationClick,+ title = 'Maps Preview',+ description = 'Interactive map based on current parameters'+}) => {+ return (+ <div style={{+ width: '100%',+ height: '100%',+ display: 'flex',+ flexDirection: 'column',+ backgroundColor: theme.colors.backgroundPanel+ }}>+ {/* Maps Header */}+ <div style={{+ padding: theme.spacing.lg,+ borderBottom: `1px solid ${theme.colors.border}`,+ backgroundColor: theme.colors.backgroundAlt,+ flexShrink: 0+ }}>+ <h3 style={{+ margin: 0,+ fontSize: theme.fontSize.lg,+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.text,+ display: 'flex',+ alignItems: 'center',+ gap: theme.spacing.sm+ }}>+ 🗺️ {title}+ </h3>+ <p style={{+ margin: `${theme.spacing.xs} 0 0 0`,+ fontSize: theme.fontSize.sm,+ color: theme.colors.textSecondary+ }}>+ {description}+ </p>+ </div>++ {/* Maps Content */}+ <div style={{+ flex: 1,+ padding: theme.spacing.md,+ display: 'flex',+ flexDirection: 'column'+ }}>+ <GoogleMapsPicker+ lat={lat}+ lng={lng}+ onLocationClick={onLocationClick}+ apiKey={apiKey}+ zoom={zoom}+ mapTypeId={mapTypeId}+ height="100%"+ width="100%"+ />+ </div>++ {/* Coordinates Display */}+ <div style={{+ padding: theme.spacing.md,+ borderTop: `1px solid ${theme.colors.border}`,+ backgroundColor: theme.colors.backgroundAlt,+ fontSize: theme.fontSize.xs,+ color: theme.colors.textSecondary,+ fontFamily: 'monospace',+ flexShrink: 0+ }}>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span>Lat: {lat.toFixed(6)}</span>+ <span>Lng: {lng.toFixed(6)}</span>+ </div>+ <div style={{+ marginTop: theme.spacing.xs,+ textAlign: 'center',+ fontSize: theme.fontSize.xs,+ opacity: 0.7+ }}>+ Click or drag marker to update coordinates+ </div>+ </div>+ </div>+ );+};++export default MapsPreviewPanel;\ No newline at end of filediff --git a/client/src/components/maps/index.ts b/client/src/components/maps/index.tsnew file mode 100644index 00000000..8e2e3fd6--- /dev/null+++ b/client/src/components/maps/index.ts@@ -0,0 +1,26 @@+// Maps Components+export { default as GoogleMapsPicker } from './GoogleMapsPicker';+export { default as MapsPreviewPanel } from './MapsPreviewPanel';++// Re-export types for convenience+export interface GoogleMapsPickerProps {+ lat: number;+ lng: number;+ onLocationClick: (lat: number, lng: number) => void;+ apiKey?: string;+ zoom?: number;+ mapTypeId?: string;+ height?: string;+ width?: string;+}++export interface MapsPreviewPanelProps {+ lat: number;+ lng: number;+ zoom?: number;+ mapTypeId?: string;+ apiKey?: string;+ onLocationClick: (lat: number, lng: number) => void;+ title?: string;+ description?: string;+}\ No newline at end of filediff --git a/client/src/components/parameterPanel/InputSection.tsx b/client/src/components/parameterPanel/InputSection.tsxnew file mode 100644index 00000000..fe8f84cc--- /dev/null+++ b/client/src/components/parameterPanel/InputSection.tsx@@ -0,0 +1,797 @@+import React, { useState, useEffect } from 'react';+import { useAppStore } from '../../store/useAppStore';+import { nodeDefinitions } from '../../nodeDefinitions';+import { useWebSocket } from '../../contexts/WebSocketContext';+import { Node, Edge } from 'reactflow';+import { useDragVariable } from '../../hooks/useDragVariable';+import { useAppTheme } from '../../hooks/useAppTheme';++interface InputSectionProps {+ nodeId: string;+ visible?: boolean;+}++interface NodeData {+ id: string;+ name: string;+ type: string;+ icon: string;+ inputData?: any;+ outputSchema: Record<string, any>;+ hasExecutionData: boolean;+}++// Helper to render icon (handles both image URLs and emoji/text)+const renderNodeIcon = (icon: string, size: number = 16) => {+ if (icon.startsWith('data:') || icon.startsWith('http') || icon.startsWith('/')) {+ return (+ <img+ src={icon}+ alt="icon"+ style={{ width: size, height: size, objectFit: 'contain' }}+ />+ );+ }+ return <span style={{ fontSize: size - 2 }}>{icon}</span>;+};++const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) => {+ const theme = useAppTheme();+ const { currentWorkflow } = useAppStore();+ const { getNodeOutput } = useWebSocket();+ const [expandedNodes, setExpandedNodes] = useState<Set<string>>(new Set());+ const [connectedNodes, setConnectedNodes] = useState<NodeData[]>([]);+ const [loading, setLoading] = useState(false);+ const { handleVariableDragStart, getTemplateVariableName } = useDragVariable(nodeId);++ // Fetch connected node data with execution results from backend+ useEffect(() => {+ const fetchConnectedNodes = async () => {+ if (!currentWorkflow || !nodeId) {+ setConnectedNodes([]);+ return;+ }++ setLoading(true);+ const nodes = currentWorkflow.nodes || [];+ const edges = currentWorkflow.edges || [];++ // Helper to check if a handle is a config/auxiliary handle (not main data flow)+ const isConfigHandle = (handle: string | null | undefined): boolean => {+ if (!handle) return false;+ // Config handles follow pattern: input-<type> where type is not 'main'+ // Examples: input-memory, input-tools, input-model+ if (handle.startsWith('input-') && handle !== 'input-main') {+ return true;+ }+ return false;+ };++ // Helper to check if a node is a config/auxiliary node (connects to config handles)+ const isConfigNode = (nodeType: string | undefined): boolean => {+ if (!nodeType) return false;+ const definition = nodeDefinitions[nodeType];+ if (!definition) return false;+ // Config nodes typically have 'memory' or 'tool' in their group+ const groups = definition.group || [];+ return groups.includes('memory') || groups.includes('tool');+ };++ // Get current node info+ const currentNode = nodes.find((node: Node) => node.id === nodeId);+ const currentNodeType = currentNode?.type;++ // Collect all edges to process (direct + inherited from parent for config nodes)+ interface EdgeWithLabel { edge: Edge; label?: string }+ const edgesToProcess: EdgeWithLabel[] = [];++ // 1. Add direct incoming edges (excluding config handle connections)+ const directEdges = edges.filter((edge: Edge) => {+ if (edge.target !== nodeId) return false;+ if (isConfigHandle(edge.targetHandle)) return false;+ return true;+ });+ directEdges.forEach(edge => edgesToProcess.push({ edge }));++ // 2. If current node is a config node (memory, tool), inherit parent node's main inputs+ if (isConfigNode(currentNodeType)) {+ const outgoingEdges = edges.filter((edge: Edge) => edge.source === nodeId);++ for (const outEdge of outgoingEdges) {+ // Check if connected to a config handle on the target+ if (isConfigHandle(outEdge.targetHandle)) {+ const targetNode = nodes.find((node: Node) => node.id === outEdge.target);+ if (!targetNode) continue;++ const targetDef = nodeDefinitions[targetNode.type || ''];+ const targetName = targetDef?.displayName || targetNode.type;++ // Find nodes connected to the parent's main input (non-config handles)+ const parentInputEdges = edges.filter(+ (e: Edge) => e.target === targetNode.id && !isConfigHandle(e.targetHandle)+ );++ for (const parentEdge of parentInputEdges) {+ edgesToProcess.push({ edge: parentEdge, label: `via ${targetName}` });+ }+ }+ }+ }++ const nodeDataPromises = edgesToProcess.map(async ({ edge, label }) => {+ const sourceNode = nodes.find((node: Node) => node.id === edge.source);+ const nodeType = sourceNode?.type || '';+ const nodeDef = nodeDefinitions[nodeType];++ const executionData = await getNodeOutput(edge.source, 'output_0');+ let inputData: any = null;+ let outputSchema: Record<string, any>;+ let hasExecutionData = false;++ if (executionData && executionData[0] && executionData[0][0]) {+ const rawData = executionData[0][0].json || executionData[0][0];+ if (typeof rawData === 'object' && rawData !== null) {+ inputData = rawData;+ outputSchema = rawData;+ hasExecutionData = true;+ } else {+ inputData = { value: rawData };+ outputSchema = { value: typeof rawData };+ hasExecutionData = true;+ }+ } else {+ hasExecutionData = false;++ if (nodeType === 'start') {+ try {+ const initialData = sourceNode?.data?.initialData || '{}';+ outputSchema = typeof initialData === 'string' ? JSON.parse(initialData) : initialData;+ } catch (e) {+ outputSchema = {};+ }+ } else {+ const sampleSchemas: Record<string, Record<string, any>> = {+ location: { latitude: 'number', longitude: 'number', accuracy: 'number', provider: 'string', altitude: 'number' },+ ai: { response: 'string', model: 'string', usage: { tokens: 'number' } },+ file: { fileName: 'string', fileSize: 'number' },+ whatsapp: {+ message_id: 'string',+ sender: 'string',+ sender_phone: 'string',+ chat_id: 'string',+ message_type: 'string',+ text: 'string',+ timestamp: 'string',+ is_group: 'boolean',+ is_from_me: 'boolean',+ push_name: 'string',+ media: 'object',+ group_info: {+ group_jid: 'string',+ sender_jid: 'string',+ sender_phone: 'string',+ sender_name: 'string'+ }+ },+ webhook: {+ method: 'string',+ path: 'string',+ headers: 'object',+ query: 'object',+ body: 'string',+ json: 'object'+ },+ httpRequest: {+ status: 'number',+ data: 'any',+ headers: 'object',+ url: 'string',+ method: 'string'+ },+ python: { output: 'any' },+ javascript: { output: 'any' },+ memory: {+ session_id: 'string',+ messages: 'array',+ message_count: 'number',+ memory_type: 'string',+ window_size: 'number'+ },+ cronScheduler: {+ timestamp: 'string',+ iteration: 'number',+ start_mode: 'string',+ frequency: 'string',+ timezone: 'string',+ schedule: 'string',+ scheduled_time: 'string',+ triggered_at: 'string',+ waited_seconds: 'number',+ message: 'string'+ },+ // Android service schemas+ android: {+ service_id: 'string',+ action: 'string',+ data: 'object',+ success: 'boolean'+ },+ batteryMonitor: {+ battery_level: 'number',+ is_charging: 'boolean',+ temperature_celsius: 'number',+ health: 'string',+ voltage: 'number'+ },+ systemInfo: {+ device_model: 'string',+ android_version: 'string',+ api_level: 'number',+ manufacturer: 'string',+ total_memory: 'number',+ available_memory: 'number'+ },+ networkMonitor: {+ connected: 'boolean',+ type: 'string',+ wifi_ssid: 'string',+ ip_address: 'string'+ },+ wifiAutomation: {+ wifi_enabled: 'boolean',+ ssid: 'string',+ ip_address: 'string',+ signal_strength: 'number'+ },+ bluetoothAutomation: {+ bluetooth_enabled: 'boolean',+ paired_devices: 'array',+ connected_devices: 'array'+ },+ audioAutomation: {+ music_volume: 'number',+ ring_volume: 'number',+ muted: 'boolean'+ },+ androidLocation: {+ latitude: 'number',+ longitude: 'number',+ accuracy: 'number',+ provider: 'string',+ altitude: 'number',+ speed: 'number',+ bearing: 'number'+ },+ appLauncher: {+ package_name: 'string',+ launched: 'boolean',+ app_name: 'string'+ },+ appList: {+ apps: 'array',+ count: 'number'+ },+ deviceStateAutomation: {+ airplane_mode: 'boolean',+ screen_on: 'boolean',+ brightness: 'number'+ },+ screenControlAutomation: {+ brightness: 'number',+ auto_brightness: 'boolean',+ screen_timeout: 'number'+ },+ airplaneModeControl: {+ airplane_mode_enabled: 'boolean'+ },+ motionDetection: {+ accelerometer: { x: 'number', y: 'number', z: 'number' },+ gyroscope: { x: 'number', y: 'number', z: 'number' },+ motion_detected: 'boolean'+ },+ environmentalSensors: {+ temperature: 'number',+ humidity: 'number',+ pressure: 'number',+ light_level: 'number'+ },+ cameraControl: {+ cameras: 'array',+ photo_path: 'string',+ success: 'boolean'+ },+ mediaControl: {+ volume: 'number',+ is_playing: 'boolean',+ current_track: 'string'+ }+ };++ // Node type detection+ const isMemory = nodeType === 'simpleMemory';+ const isAI = !isMemory && (nodeType.includes('ai') || nodeType.includes('chat'));+ const isFile = nodeType.includes('file');+ const isWhatsApp = nodeType.includes('whatsapp') || nodeType.includes('Whatsapp');+ const isWebhook = nodeType === 'webhookTrigger';+ const isHttpRequest = nodeType === 'httpRequest';+ const isPython = nodeType.includes('python') || nodeType.includes('Python');+ const isJavaScript = nodeType.includes('javascript') || nodeType.includes('Javascript');+ const isCodeExecutor = isPython || isJavaScript;+ const isCronScheduler = nodeType === 'cronScheduler';++ // Android service node detection - check for specific Android node types+ const androidNodeTypes = [+ 'batteryMonitor', 'systemInfo', 'networkMonitor',+ 'wifiAutomation', 'bluetoothAutomation', 'audioAutomation',+ 'deviceStateAutomation', 'screenControlAutomation', 'airplaneModeControl',+ 'motionDetection', 'environmentalSensors', 'cameraControl', 'mediaControl',+ 'appLauncher', 'appList'+ ];+ const isAndroidNode = androidNodeTypes.includes(nodeType);+ const isAndroidLocation = nodeType === 'location';++ // Location nodes (Google Maps, not Android location)+ const isLocationNode = nodeType.includes('location') && !isAndroidLocation;+ const isGoogleMaps = nodeType === 'createMap' || nodeType === 'addLocations' || nodeType === 'showNearbyPlaces';++ // Select appropriate schema+ if (isAndroidLocation) {+ outputSchema = sampleSchemas.androidLocation;+ } else if (isAndroidNode && sampleSchemas[nodeType as keyof typeof sampleSchemas]) {+ outputSchema = sampleSchemas[nodeType as keyof typeof sampleSchemas];+ } else {+ outputSchema = isLocationNode || isGoogleMaps ? sampleSchemas.location :+ isMemory ? sampleSchemas.memory :+ isAI ? sampleSchemas.ai :+ isFile ? sampleSchemas.file :+ isWhatsApp ? sampleSchemas.whatsapp :+ isWebhook ? sampleSchemas.webhook :+ isHttpRequest ? sampleSchemas.httpRequest :+ isCodeExecutor ? sampleSchemas.python :+ isCronScheduler ? sampleSchemas.cronScheduler :+ { data: 'any' };+ }+ }+ }++ const baseName = sourceNode?.data?.label || nodeDef?.displayName || nodeType;+ return {+ id: edge.source,+ name: label ? `${baseName} (${label})` : baseName,+ type: nodeType,+ icon: nodeDef?.icon || '',+ inputData,+ outputSchema,+ hasExecutionData+ };+ });++ const nodeDataResults = await Promise.all(nodeDataPromises);+ setConnectedNodes(nodeDataResults);+ // Auto-expand all nodes initially+ setExpandedNodes(new Set(nodeDataResults.map(n => n.id)));+ setLoading(false);+ };++ fetchConnectedNodes();+ }, [nodeId, currentWorkflow, getNodeOutput]);++ const toggleNode = (nodeId: string) => {+ setExpandedNodes(prev => {+ const next = new Set(prev);+ if (next.has(nodeId)) {+ next.delete(nodeId);+ } else {+ next.add(nodeId);+ }+ return next;+ });+ };++ // Render draggable property+ // NOTE: sourceNodeId is the unique node ID, used for template variable resolution+ const renderDraggableProperty = (key: string, value: any, sourceNodeId: string, path: string = '', depth: number = 0) => {+ const currentPath = path ? `${path}.${key}` : key;+ const isObject = typeof value === 'object' && value !== null && !Array.isArray(value);++ if (isObject) {+ return (+ <div key={currentPath} style={{ marginLeft: depth > 0 ? 16 : 0, marginBottom: 8 }}>+ <div style={{+ fontSize: theme.fontSize.xs,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.textMuted,+ marginBottom: 4,+ }}>+ {key}:+ </div>+ <div>+ {Object.entries(value as Record<string, any>).map(([subKey, subValue]) =>+ renderDraggableProperty(subKey, subValue, sourceNodeId, currentPath, depth + 1)+ )}+ </div>+ </div>+ );+ }++ const templateName = getTemplateVariableName(sourceNodeId);+ return (+ <div+ key={currentPath}+ draggable+ onDragStart={(e) => handleVariableDragStart(e, sourceNodeId, currentPath, value)}+ style={{+ marginBottom: 8,+ marginLeft: depth > 0 ? 16 : 0,+ padding: theme.spacing.sm,+ backgroundColor: theme.colors.backgroundAlt,+ border: `1px solid ${theme.colors.focus}`,+ borderRadius: theme.borderRadius.md,+ cursor: 'grab',+ transition: theme.transitions.fast,+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = theme.colors.focusRing;+ e.currentTarget.style.borderColor = theme.dracula.cyan;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = theme.colors.backgroundAlt;+ e.currentTarget.style.borderColor = theme.colors.focus;+ }}+ >+ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <div>+ <div style={{+ fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.templateVariable,+ marginBottom: 2,+ }}>+ {`{{${templateName}.${currentPath}}}`}+ </div>+ <div style={{+ fontSize: theme.fontSize.xs,+ color: theme.colors.textSecondary,+ }}>+ {key}: {typeof value}+ </div>+ </div>+ {/* Drag icon */}+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={theme.colors.templateVariable} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <line x1="12" y1="5" x2="12" y2="19"/>+ <polyline points="19 12 12 19 5 12"/>+ </svg>+ </div>+ </div>+ );+ };++ if (!visible) {+ return null;+ }++ // Loading state+ if (loading) {+ return (+ <div style={{+ width: '100%',+ height: '100%',+ backgroundColor: theme.colors.backgroundPanel,+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ padding: theme.spacing.xxl,+ }}>+ <div style={{+ width: 32,+ height: 32,+ border: `3px solid ${theme.colors.border}`,+ borderTopColor: theme.dracula.cyan,+ borderRadius: '50%',+ animation: 'spin 1s linear infinite',+ marginBottom: theme.spacing.lg,+ }} />+ <style>+ {`@keyframes spin { to { transform: rotate(360deg); } }`}+ </style>+ <div style={{+ fontSize: theme.fontSize.sm,+ color: theme.colors.textSecondary,+ }}>+ Loading input data...+ </div>+ </div>+ );+ }++ // Empty state+ if (connectedNodes.length === 0) {+ return (+ <div style={{+ width: '100%',+ height: '100%',+ backgroundColor: theme.colors.backgroundPanel,+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ padding: theme.spacing.xxl,+ }}>+ {/* Link icon */}+ <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke={theme.colors.textMuted} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{ marginBottom: theme.spacing.lg }}>+ <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/>+ <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>+ </svg>+ <div style={{+ fontSize: theme.fontSize.base,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.textSecondary,+ marginBottom: theme.spacing.xs,+ }}>+ No connected inputs+ </div>+ <div style={{+ fontSize: theme.fontSize.sm,+ color: theme.colors.textMuted,+ textAlign: 'center',+ }}>+ Connect nodes to see input data and available variables+ </div>+ </div>+ );+ }++ return (+ <div style={{+ width: '100%',+ height: '100%',+ backgroundColor: theme.colors.backgroundPanel,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden',+ }}>+ {/* Header */}+ <div style={{+ padding: `${theme.spacing.md} ${theme.spacing.lg}`,+ borderBottom: `1px solid ${theme.colors.border}`,+ backgroundColor: theme.colors.background,+ display: 'flex',+ alignItems: 'center',+ gap: theme.spacing.sm,+ flexShrink: 0,+ }}>+ {/* Database icon */}+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={theme.colors.textSecondary} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <ellipse cx="12" cy="5" rx="9" ry="3"/>+ <path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"/>+ <path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/>+ </svg>+ <span style={{+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.text,+ }}>+ Input Data & Variables+ </span>+ <span style={{+ fontSize: theme.fontSize.xs,+ fontWeight: theme.fontWeight.medium,+ color: theme.dracula.cyan,+ padding: `2px ${theme.spacing.sm}`,+ backgroundColor: theme.dracula.cyan + '20',+ borderRadius: theme.borderRadius.sm,+ }}>+ {connectedNodes.length}+ </span>+ </div>++ {/* Content */}+ <div style={{+ flex: 1,+ overflow: 'auto',+ padding: theme.spacing.md,+ }}>+ {connectedNodes.map((node) => {+ const isExpanded = expandedNodes.has(node.id);++ return (+ <div key={node.id} style={{+ marginBottom: theme.spacing.md,+ backgroundColor: theme.colors.background,+ border: `1px solid ${theme.colors.border}`,+ borderLeft: `3px solid ${node.hasExecutionData ? theme.dracula.green : theme.dracula.orange}`,+ borderRadius: theme.borderRadius.md,+ overflow: 'hidden',+ }}>+ {/* Node Header */}+ <div+ onClick={() => toggleNode(node.id)}+ style={{+ padding: `${theme.spacing.sm} ${theme.spacing.md}`,+ backgroundColor: theme.colors.backgroundAlt,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ transition: theme.transitions.fast,+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', gap: theme.spacing.sm }}>+ {renderNodeIcon(node.icon, 18)}+ <span style={{+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.text,+ }}>+ {node.name}+ </span>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: theme.spacing.sm }}>+ {/* Status badge */}+ <span style={{+ fontSize: '10px',+ fontWeight: theme.fontWeight.medium,+ color: node.hasExecutionData ? theme.dracula.green : theme.dracula.orange,+ padding: `2px ${theme.spacing.xs}`,+ backgroundColor: node.hasExecutionData ? theme.dracula.green + '20' : theme.dracula.orange + '20',+ borderRadius: theme.borderRadius.sm,+ display: 'flex',+ alignItems: 'center',+ gap: 4,+ }}>+ {node.hasExecutionData ? (+ <svg width="10" height="10" viewBox="0 0 24 24" fill={theme.dracula.green} stroke="none">+ <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>+ </svg>+ ) : (+ <svg width="10" height="10" viewBox="0 0 24 24" fill={theme.dracula.orange} stroke="none">+ <path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/>+ </svg>+ )}+ {node.hasExecutionData ? 'LIVE' : 'SCHEMA'}+ </span>+ {/* Expand arrow */}+ <svg+ width="12"+ height="12"+ viewBox="0 0 24 24"+ fill="none"+ stroke={theme.colors.textSecondary}+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ style={{+ transform: isExpanded ? 'rotate(180deg)' : 'rotate(0deg)',+ transition: 'transform 0.2s ease',+ }}+ >+ <polyline points="6 9 12 15 18 9"/>+ </svg>+ </div>+ </div>++ {/* Node Content */}+ {isExpanded && (+ <div style={{+ padding: theme.spacing.md,+ borderTop: `1px solid ${theme.colors.border}`,+ }}>+ {/* Schema info banner */}+ {!node.hasExecutionData && (+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: theme.spacing.sm,+ padding: `${theme.spacing.xs} ${theme.spacing.sm}`,+ marginBottom: theme.spacing.md,+ backgroundColor: theme.dracula.cyan + '10',+ border: `1px solid ${theme.dracula.cyan}40`,+ borderRadius: theme.borderRadius.sm,+ fontSize: theme.fontSize.xs,+ color: theme.dracula.cyan,+ }}>+ <svg width="12" height="12" viewBox="0 0 24 24" fill={theme.dracula.cyan} stroke="none">+ <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/>+ </svg>+ Schema view - Execute this node to see actual input data+ </div>+ )}++ {/* Live data preview */}+ {node.hasExecutionData && (+ <div style={{ marginBottom: theme.spacing.md }}>+ <div style={{+ fontSize: theme.fontSize.xs,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.textMuted,+ marginBottom: theme.spacing.xs,+ textTransform: 'uppercase',+ letterSpacing: '0.05em',+ }}>+ Received Data+ </div>+ <pre style={{+ margin: 0,+ padding: theme.spacing.sm,+ fontSize: theme.fontSize.xs,+ fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',+ backgroundColor: theme.colors.backgroundElevated,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.sm,+ overflow: 'auto',+ maxHeight: '120px',+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ color: theme.dracula.foreground,+ }}>+ {JSON.stringify(node.inputData, null, 2)}+ </pre>+ </div>+ )}++ {/* Draggable variables */}+ <div style={{+ fontSize: theme.fontSize.xs,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.textMuted,+ marginBottom: theme.spacing.sm,+ textTransform: 'uppercase',+ letterSpacing: '0.05em',+ }}>+ Drag Variables to Parameters+ </div>+ <div>+ {typeof node.outputSchema === 'object' && node.outputSchema !== null+ ? Object.entries(node.outputSchema).map(([key, value]) =>+ renderDraggableProperty(key, value, node.id)+ )+ : (+ <div style={{+ fontSize: theme.fontSize.sm,+ color: theme.colors.textMuted,+ fontStyle: 'italic',+ }}>+ No variables available+ </div>+ )+ }+ </div>+ </div>+ )}+ </div>+ );+ })}+ </div>++ {/* Footer hint */}+ <div style={{+ padding: `${theme.spacing.sm} ${theme.spacing.lg}`,+ borderTop: `1px solid ${theme.colors.border}`,+ backgroundColor: theme.colors.background,+ fontSize: theme.fontSize.xs,+ color: theme.colors.textMuted,+ textAlign: 'center',+ flexShrink: 0,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: theme.spacing.xs,+ }}>+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <circle cx="12" cy="12" r="10"/>+ <line x1="12" y1="16" x2="12" y2="12"/>+ <line x1="12" y1="8" x2="12.01" y2="8"/>+ </svg>+ Drag variables into parameter fields to use them+ </div>+ </div>+ );+};++export default InputSection;diff --git a/client/src/components/parameterPanel/LocationPanelLayout.tsx b/client/src/components/parameterPanel/LocationPanelLayout.tsxnew file mode 100644index 00000000..ca1359e3--- /dev/null+++ b/client/src/components/parameterPanel/LocationPanelLayout.tsx@@ -0,0 +1,64 @@+import React from 'react';+import { Node } from 'reactflow';+import InputSection from './InputSection';+import MiddleSection from './MiddleSection';+import MapsSection from './MapsSection';+import { INodeTypeDescription } from '../../types/INodeProperties';++interface LocationPanelLayoutProps {+ // Node data+ selectedNode: Node;+ nodeDefinition: INodeTypeDescription;+ parameters: Record<string, any>;+ hasUnsavedChanges: boolean;++ // Parameter handling+ onParameterChange: (paramName: string, value: any) => void;++ // Layout configuration+ showInputSection?: boolean;+}++const LocationPanelLayout: React.FC<LocationPanelLayoutProps> = ({+ selectedNode,+ nodeDefinition,+ parameters,+ hasUnsavedChanges: _hasUnsavedChanges,+ onParameterChange,+ showInputSection = true+}) => {+ return (+ <div style={{ display: 'flex', height: '100%', minHeight: 0 }}>+ {/* Left: Input Nodes JSON Data */}+ {showInputSection && (+ <div style={{ flex: 1, height: '100%', overflow: 'hidden' }}>+ <InputSection+ nodeId={selectedNode.id}+ visible={showInputSection}+ />+ </div>+ )}++ {/* Middle: Parameter Content */}+ <div style={{ flex: 1, height: '100%', overflow: 'hidden' }}>+ <MiddleSection+ nodeDefinition={nodeDefinition}+ parameters={parameters}+ onParameterChange={onParameterChange}+ />+ </div>++ {/* Right: Maps Section */}+ <div style={{ flex: 1, height: '100%', overflow: 'hidden' }}>+ <MapsSection+ selectedNode={selectedNode}+ nodeDefinition={nodeDefinition}+ parameters={parameters}+ onParameterChange={onParameterChange}+ />+ </div>+ </div>+ );+};++export default LocationPanelLayout;\ No newline at end of filediff --git a/client/src/components/parameterPanel/MapsSection.tsx b/client/src/components/parameterPanel/MapsSection.tsxnew file mode 100644index 00000000..ca907968--- /dev/null+++ b/client/src/components/parameterPanel/MapsSection.tsx@@ -0,0 +1,92 @@+import React, { useState, useEffect, useRef } from 'react';+import MapsPreviewPanel from '../maps/MapsPreviewPanel';+import { useAppTheme } from '../../hooks/useAppTheme';+import { Node } from 'reactflow';+import { INodeTypeDescription } from '../../types/INodeProperties';+import {+ getCoordinateParams,+ getCurrentCoordinates,+ getMapDisplayParams,+ getGoogleMapsApiKey,+ createLocationUpdateHandler+} from '../../utils/locationUtils';+import { useApiKeys } from '../../hooks/useApiKeys';++interface MapsSectionProps {+ selectedNode: Node;+ nodeDefinition: INodeTypeDescription;+ parameters: Record<string, any>;+ onParameterChange: (paramName: string, value: any) => void;+ visible?: boolean;+}++const MapsSection: React.FC<MapsSectionProps> = ({+ nodeDefinition,+ parameters,+ onParameterChange,+ visible = true+}) => {+ const theme = useAppTheme();+ const { getStoredApiKey, isConnected } = useApiKeys();+ const [apiKey, setApiKey] = useState<string | undefined>(() => {+ // Initialize with env variable if available+ return getGoogleMapsApiKey();+ });+ const hasFetchedRef = useRef(false);++ // Fetch stored API key from backend when WebSocket is connected+ useEffect(() => {+ if (!isConnected || hasFetchedRef.current) {+ return;+ }++ const fetchApiKey = async () => {+ hasFetchedRef.current = true;+ try {+ const storedKey = await getStoredApiKey('google_maps');+ if (storedKey) {+ setApiKey(storedKey);+ }+ } catch {+ // Keep env key if fetch fails+ }+ };++ fetchApiKey();+ }, [isConnected, getStoredApiKey]);++ if (!visible) {+ return null;+ }++ // Get coordinate parameters and current values+ const locationParams = getCoordinateParams(nodeDefinition);+ const { lat, lng } = getCurrentCoordinates(parameters, locationParams);+ const { zoom, mapTypeId } = getMapDisplayParams(parameters);++ // Create location update handler+ const handleLocationUpdate = createLocationUpdateHandler(locationParams, onParameterChange);++ return (+ <div style={{+ backgroundColor: theme.colors.backgroundPanel,+ display: 'flex',+ flexDirection: 'column',+ width: '100%',+ height: '100%'+ }}>+ <MapsPreviewPanel+ lat={lat}+ lng={lng}+ zoom={zoom}+ mapTypeId={mapTypeId}+ apiKey={apiKey}+ onLocationClick={handleLocationUpdate}+ title="Maps Preview"+ description="Interactive map based on current parameters"+ />+ </div>+ );+};++export default MapsSection;\ No newline at end of filediff --git a/client/src/components/parameterPanel/MiddleSection.tsx b/client/src/components/parameterPanel/MiddleSection.tsxnew file mode 100644index 00000000..ba38e104--- /dev/null+++ b/client/src/components/parameterPanel/MiddleSection.tsx@@ -0,0 +1,307 @@+import React, { useState } from 'react';+import ParameterRenderer from '../ParameterRenderer';+import { useAppTheme } from '../../hooks/useAppTheme';+import { INodeTypeDescription, INodeProperties } from '../../types/INodeProperties';+import { ExecutionResult } from '../../services/executionService';++interface MiddleSectionProps {+ nodeDefinition: INodeTypeDescription;+ parameters: Record<string, any>;+ onParameterChange: (paramName: string, value: any) => void;+ isLoadingParameters?: boolean;+ executionResults?: ExecutionResult[];+}++const shouldShowParameter = (param: INodeProperties, allParameters: Record<string, any>): boolean => {+ if (!param.displayOptions?.show) {+ return true;+ }++ const showConditions = param.displayOptions.show;++ for (const [paramName, allowedValues] of Object.entries(showConditions)) {+ const currentValue = allParameters[paramName];++ if (Array.isArray(allowedValues)) {+ if (!allowedValues.includes(currentValue)) {+ return false;+ }+ } else {+ if (currentValue !== allowedValues) {+ return false;+ }+ }+ }++ return true;+};++const MiddleSection: React.FC<MiddleSectionProps> = ({+ nodeDefinition,+ parameters,+ onParameterChange,+ isLoadingParameters = false,+ executionResults = []+}) => {+ const theme = useAppTheme();+ const [isConsoleExpanded, setIsConsoleExpanded] = useState(true);++ const visibleParams = (nodeDefinition.properties || [])+ .filter((param: INodeProperties) => shouldShowParameter(param, parameters));++ // Check if this is a code executor node (Python or JavaScript)+ const isCodeExecutorNode = nodeDefinition.name === 'pythonExecutor' || nodeDefinition.name === 'javascriptExecutor';++ // Extract console output from execution results+ const getConsoleOutput = (): string => {+ if (executionResults.length === 0) return '';++ const latestResult = executionResults[0];+ const outputs = latestResult.outputs || latestResult.data || latestResult.nodeData?.[0]?.[0]?.json;++ if (!outputs) return '';++ // Check for console_output or stdout in the result+ if (outputs.console_output) return outputs.console_output;+ if (outputs.stdout) return outputs.stdout;+ if (outputs.result?.console_output) return outputs.result.console_output;+ if (outputs.result?.stdout) return outputs.result.stdout;++ // Check for error output+ if (latestResult.error) return `Error: ${latestResult.error}`;+ if (outputs.error) return `Error: ${outputs.error}`;+ if (outputs.stderr) return `Error: ${outputs.stderr}`;++ return '';+ };++ const consoleOutput = isCodeExecutorNode ? getConsoleOutput() : '';++ return (+ <div style={{+ flex: 1,+ display: 'flex',+ flexDirection: 'column',+ height: '100%',+ overflow: 'hidden',+ position: 'relative'+ }}>+ {/* Description - hide for Python nodes */}+ {!isCodeExecutorNode && (+ <div style={{+ padding: `${theme.spacing.lg} ${theme.spacing.xl} ${theme.spacing.sm}`,+ borderBottom: `1px solid ${theme.colors.border}`,+ backgroundColor: theme.colors.backgroundAlt,+ flexShrink: 0+ }}>+ <p style={{+ margin: 0,+ fontSize: theme.fontSize.base,+ color: theme.colors.textSecondary,+ lineHeight: '1.5',+ }}>+ {nodeDefinition.description}+ </p>+ </div>+ )}++ {/* Main Content Area - Flexible */}+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0, overflow: 'hidden' }}>+ {/* Parameters */}+ <div style={{+ padding: theme.spacing.xl,+ flex: isCodeExecutorNode ? '3' : 1,+ overflowY: isCodeExecutorNode ? 'hidden' : 'auto',+ overflowX: 'hidden',+ width: '100%',+ boxSizing: 'border-box',+ minHeight: 0,+ display: isCodeExecutorNode ? 'flex' : 'block',+ flexDirection: 'column'+ }}>+ {/* Parameters Container */}+ <div style={{+ backgroundColor: theme.colors.background,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.md,+ padding: theme.spacing.lg,+ boxShadow: `0 1px 3px ${theme.colors.shadowLight}`,+ height: isCodeExecutorNode ? '100%' : 'auto',+ display: isCodeExecutorNode ? 'flex' : 'block',+ flexDirection: 'column',+ boxSizing: 'border-box'+ }}>+ {/* All Parameters - standard n8n style */}+ {visibleParams.map((param: INodeProperties, index: number) => (+ <div+ key={param.name}+ style={{+ paddingBottom: index < visibleParams.length - 1 ? theme.spacing.md : 0,+ marginBottom: index < visibleParams.length - 1 ? theme.spacing.md : 0,+ borderBottom: index < visibleParams.length - 1 ? `1px solid ${theme.colors.border}` : 'none',+ flex: isCodeExecutorNode ? 1 : 'none',+ display: isCodeExecutorNode ? 'flex' : 'block',+ flexDirection: 'column',+ minHeight: 0+ }}+ >+ <ParameterRenderer+ parameter={param}+ value={parameters[param.name]}+ onChange={(value) => onParameterChange(param.name, value)}+ allParameters={parameters}+ onParameterChange={onParameterChange}+ onClosePanel={() => {}}+ isLoadingParameters={isLoadingParameters}+ />+ </div>+ ))}+ </div>+ </div>++ {/* Console Output Section - Only for Python nodes */}+ {isCodeExecutorNode && (+ <div style={{+ padding: `0 ${theme.spacing.xl} ${theme.spacing.xl}`,+ flex: '1',+ minHeight: 0,+ display: 'flex',+ flexDirection: 'column'+ }}>+ <div style={{+ backgroundColor: theme.colors.background,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.md,+ boxShadow: `0 1px 3px ${theme.colors.shadowLight}`,+ overflow: 'hidden',+ flex: 1,+ display: 'flex',+ flexDirection: 'column',+ minHeight: 0+ }}>+ {/* Console Header */}+ <div+ onClick={() => setIsConsoleExpanded(!isConsoleExpanded)}+ style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ padding: `${theme.spacing.sm} ${theme.spacing.md}`,+ backgroundColor: theme.colors.backgroundAlt,+ borderBottom: isConsoleExpanded ? `1px solid ${theme.colors.border}` : 'none',+ cursor: 'pointer',+ userSelect: 'none'+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', gap: theme.spacing.sm }}>+ <svg+ width="14"+ height="14"+ viewBox="0 0 24 24"+ fill="none"+ stroke={theme.colors.textSecondary}+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ style={{+ transform: isConsoleExpanded ? 'rotate(90deg)' : 'rotate(0deg)',+ transition: 'transform 0.2s ease'+ }}+ >+ <polyline points="9 18 15 12 9 6" />+ </svg>+ <svg+ width="14"+ height="14"+ viewBox="0 0 24 24"+ fill="none"+ stroke={theme.dracula.cyan}+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <polyline points="4 17 10 11 4 5" />+ <line x1="12" y1="19" x2="20" y2="19" />+ </svg>+ <span style={{+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.text+ }}>+ Console+ </span>+ </div>+ {consoleOutput && (+ <span style={{+ fontSize: theme.fontSize.xs,+ color: theme.dracula.green,+ padding: `2px ${theme.spacing.sm}`,+ backgroundColor: theme.dracula.green + '20',+ borderRadius: theme.borderRadius.sm+ }}>+ Output+ </span>+ )}+ </div>++ {/* Console Content */}+ {isConsoleExpanded && (+ <div style={{+ padding: theme.spacing.sm,+ backgroundColor: '#1a1a2e',+ flex: 1,+ minHeight: 0,+ overflowY: 'auto',+ fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',+ fontSize: theme.fontSize.sm,+ lineHeight: '1.4'+ }}>+ {consoleOutput ? (+ <pre style={{+ margin: 0,+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ color: consoleOutput.startsWith('Error') ? theme.dracula.red : theme.dracula.green+ }}>+ {consoleOutput}+ </pre>+ ) : (+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ height: '100%',+ minHeight: '40px',+ color: theme.colors.textMuted+ }}>+ <svg+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke={theme.colors.textMuted}+ strokeWidth="1.5"+ strokeLinecap="round"+ strokeLinejoin="round"+ style={{ marginBottom: theme.spacing.sm, opacity: 0.5 }}+ >+ <polyline points="4 17 10 11 4 5" />+ <line x1="12" y1="19" x2="20" y2="19" />+ </svg>+ <span style={{ fontSize: theme.fontSize.xs }}>+ Run the code to see console output+ </span>+ </div>+ )}+ </div>+ )}+ </div>+ </div>+ )}+ </div>+ </div>+ );+};++export default MiddleSection;diff --git a/client/src/components/parameterPanel/OutputSection.tsx b/client/src/components/parameterPanel/OutputSection.tsxnew file mode 100644index 00000000..5398113f--- /dev/null+++ b/client/src/components/parameterPanel/OutputSection.tsx@@ -0,0 +1,81 @@+import React from 'react';+import NodeOutputPanel from '../ui/NodeOutputPanel';+import { useAppTheme } from '../../hooks/useAppTheme';+import { ExecutionResult } from '../../services/executionService';+import { Node } from 'reactflow';+import { useWebSocket } from '../../contexts/WebSocketContext';++interface OutputSectionProps {+ selectedNode: Node;+ executionResults: ExecutionResult[];+ onClearResults: () => void;+ visible?: boolean;+}++const OutputSection: React.FC<OutputSectionProps> = ({+ selectedNode,+ executionResults,+ onClearResults,+ visible = true+}) => {+ const theme = useAppTheme();+ const { nodeStatuses } = useWebSocket();++ if (!visible) {+ return null;+ }++ // Combine local execution results with WebSocket nodeStatuses from workflow execution+ const combinedResults = React.useMemo(() => {+ const results = [...executionResults];++ // Check if there's output from workflow execution in nodeStatuses+ const nodeStatus = nodeStatuses[selectedNode.id];+ if (nodeStatus && nodeStatus.data && (nodeStatus.status === 'success' || nodeStatus.status === 'error')) {+ // Check if this output is already in executionResults+ const alreadyExists = results.some(r =>+ r.nodeId === selectedNode.id &&+ JSON.stringify(r.outputs) === JSON.stringify(nodeStatus.data)+ );++ if (!alreadyExists) {+ // Create ExecutionResult from nodeStatus (from workflow execution)+ const wsResult: ExecutionResult = {+ success: nodeStatus.status === 'success',+ nodeId: selectedNode.id,+ nodeType: selectedNode.type || 'unknown',+ nodeName: selectedNode.type || 'Node',+ timestamp: new Date().toISOString(),+ executionTime: 0,+ outputs: nodeStatus.data,+ nodeData: [[{ json: nodeStatus.data }]],+ error: nodeStatus.status === 'error' ? nodeStatus.data?.error : undefined+ };+ // Add WebSocket result to the beginning (most recent)+ results.unshift(wsResult);+ }+ }++ return results;+ }, [executionResults, nodeStatuses, selectedNode.id, selectedNode.type]);++ return (+ <div style={{+ backgroundColor: theme.colors.backgroundPanel,+ display: 'flex',+ flexDirection: 'column',+ width: '100%',+ height: '100%',+ overflow: 'hidden',+ position: 'relative'+ }}>+ <NodeOutputPanel+ results={combinedResults}+ onClear={onClearResults}+ selectedNode={selectedNode}+ />+ </div>+ );+};++export default OutputSection;\ No newline at end of filediff --git a/client/src/components/parameterPanel/ParameterPanelLayout.tsx b/client/src/components/parameterPanel/ParameterPanelLayout.tsxnew file mode 100644index 00000000..3b84cde8--- /dev/null+++ b/client/src/components/parameterPanel/ParameterPanelLayout.tsx@@ -0,0 +1,81 @@+import React from 'react';+import { Node } from 'reactflow';+import InputSection from './InputSection';+import MiddleSection from './MiddleSection';+import OutputSection from './OutputSection';+import { INodeTypeDescription } from '../../types/INodeProperties';+import { ExecutionResult } from '../../services/executionService';++interface ParameterPanelLayoutProps {+ // Node data+ selectedNode: Node;+ nodeDefinition: INodeTypeDescription;+ parameters: Record<string, any>;+ hasUnsavedChanges: boolean;++ // Parameter handling+ onParameterChange: (paramName: string, value: any) => void;++ // Execution data+ executionResults: ExecutionResult[];+ onClearResults: () => void;++ // Layout configuration+ showInputSection?: boolean;+ showOutputSection?: boolean;++ // Loading state+ isLoadingParameters?: boolean;+}++const ParameterPanelLayout: React.FC<ParameterPanelLayoutProps> = ({+ selectedNode,+ nodeDefinition,+ parameters,+ hasUnsavedChanges: _hasUnsavedChanges,+ onParameterChange,+ executionResults,+ onClearResults,+ showInputSection = true,+ showOutputSection = true,+ isLoadingParameters = false+}) => {+ return (+ <div style={{ display: 'flex', height: '100%', minHeight: 0 }}>+ {/* Left: Input Nodes JSON Data */}+ {showInputSection && (+ <div style={{ flex: 0.7, height: '100%', overflow: 'hidden' }}>+ <InputSection+ nodeId={selectedNode.id}+ visible={showInputSection}+ />+ </div>+ )}++ {/* Middle: Parameter Content */}+ <div style={{ flex: 1.6, height: '100%', overflow: 'hidden', minWidth: 0 }}>+ <MiddleSection+ nodeDefinition={nodeDefinition}+ parameters={parameters}+ onParameterChange={onParameterChange}+ isLoadingParameters={isLoadingParameters}+ executionResults={executionResults}+ />+ </div>++ {/* Right: Current Node Output */}+ {showOutputSection && (+ <div style={{ flex: 0.7, height: '100%', overflow: 'hidden' }}>+ <OutputSection+ selectedNode={selectedNode}+ executionResults={executionResults}+ onClearResults={onClearResults}+ visible={showOutputSection}+ />+ </div>+ )}+ </div>+ );+};++export default ParameterPanelLayout;\ No newline at end of filediff --git a/client/src/components/parameterPanel/index.ts b/client/src/components/parameterPanel/index.tsnew file mode 100644index 00000000..52943e1e--- /dev/null+++ b/client/src/components/parameterPanel/index.ts@@ -0,0 +1,42 @@+// Modular Parameter Panel Components+export { default as InputSection } from './InputSection';+export { default as MiddleSection } from './MiddleSection';+export { default as OutputSection } from './OutputSection';+export { default as MapsSection } from './MapsSection';+export { default as ParameterPanelLayout } from './ParameterPanelLayout';+export { default as LocationPanelLayout } from './LocationPanelLayout';++// Types defined inline for convenience++// Export interface definitions+export interface InputSectionProps {+ nodeId: string;+ visible?: boolean;+}++export interface MiddleSectionProps {+ nodeDefinition: any;+ parameters: Record<string, any>;+ onParameterChange: (paramName: string, value: any) => void;+}++export interface OutputSectionProps {+ selectedNode: any;+ executionResults: any[];+ onClearResults: () => void;+ visible?: boolean;+}++export interface ParameterPanelLayoutProps {+ selectedNode: any;+ nodeDefinition: any;+ parameters: Record<string, any>;+ hasUnsavedChanges: boolean;+ onParameterChange: (paramName: string, value: any) => void;+ onSave: () => void;+ onCancel: () => void;+ executionResults: any[];+ onClearResults: () => void;+ showInputSection?: boolean;+ showOutputSection?: boolean;+}\ No newline at end of filediff --git a/client/src/components/shared/DataPanel.tsx b/client/src/components/shared/DataPanel.tsxnew file mode 100644index 00000000..54b08183--- /dev/null+++ b/client/src/components/shared/DataPanel.tsx@@ -0,0 +1,142 @@+import React, { ReactNode } from 'react';+import { Card, Space, Empty, Typography } from 'antd';+import { useAppTheme } from '../../hooks/useAppTheme';++const { Text } = Typography;++// Compound Component Pattern+interface DataPanelProps {+ children: ReactNode;+}++interface HeaderProps {+ title: ReactNode;+ extra?: ReactNode;+ children?: ReactNode;+}++interface ContentProps {+ children: ReactNode;+}++interface FooterProps {+ children: ReactNode;+}++interface EmptyStateProps {+ icon: ReactNode;+ title: string;+ description: string;+}++const DataPanelRoot: React.FC<DataPanelProps> = ({ children }) => {+ const theme = useAppTheme();+ return (+ <div style={{+ width: '350px',+ height: '100%',+ backgroundColor: theme.colors.backgroundPanel,+ borderLeft: `1px solid ${theme.colors.border}`,+ display: 'flex',+ flexDirection: 'column'+ }}>+ {children}+ </div>+ );+};++const DataPanelHeader: React.FC<HeaderProps> = ({ title, extra, children }) => {+ const theme = useAppTheme();+ return (+ <Card+ size="small"+ title={title}+ extra={extra}+ headStyle={{+ borderBottom: `1px solid ${theme.colors.border}`,+ padding: 8,+ backgroundColor: theme.colors.backgroundPanel+ }}+ bodyStyle={{ padding: children ? 8 : 0 }}+ style={{+ borderRadius: 0,+ border: 'none',+ borderBottom: `1px solid ${theme.colors.border}`,+ backgroundColor: theme.colors.backgroundPanel+ }}+ >+ {children}+ </Card>+ );+};++const DataPanelContent: React.FC<ContentProps> = ({ children }) => (+ <div style={{+ flex: 1,+ overflowY: 'auto',+ padding: '8px'+ }}>+ {children}+ </div>+);++const DataPanelFooter: React.FC<FooterProps> = ({ children }) => {+ const theme = useAppTheme();+ return (+ <Card+ size="small"+ bodyStyle={{ padding: 8, textAlign: 'center' }}+ style={{+ borderRadius: 0,+ border: 'none',+ borderTop: `1px solid ${theme.colors.border}`,+ backgroundColor: theme.colors.backgroundPanel+ }}+ >+ {children}+ </Card>+ );+};++const DataPanelEmpty: React.FC<EmptyStateProps> = ({ icon, title, description }) => {+ const theme = useAppTheme();+ return (+ <div style={{+ width: '350px',+ height: '100%',+ backgroundColor: theme.colors.backgroundPanel,+ borderLeft: `1px solid ${theme.colors.border}`,+ display: 'flex',+ flexDirection: 'column'+ }}>+ <Empty+ image={icon}+ description={+ <Space direction="vertical" size="small">+ <Text style={{ color: theme.colors.textSecondary }}>{title}</Text>+ <Text style={{ fontSize: 12, color: theme.colors.textSecondary }}>+ {description}+ </Text>+ </Space>+ }+ style={{+ height: '100%',+ display: 'flex',+ flexDirection: 'column',+ justifyContent: 'center'+ }}+ />+ </div>+ );+};++// Compound Component Export+const DataPanel = {+ Root: DataPanelRoot,+ Header: DataPanelHeader,+ Content: DataPanelContent,+ Footer: DataPanelFooter,+ Empty: DataPanelEmpty+};++export default DataPanel;diff --git a/client/src/components/shared/JSONTreeRenderer.tsx b/client/src/components/shared/JSONTreeRenderer.tsxnew file mode 100644index 00000000..9469fe3f--- /dev/null+++ b/client/src/components/shared/JSONTreeRenderer.tsx@@ -0,0 +1,106 @@+import React from 'react';+import { Tree, Card, Space, Typography } from 'antd';+import { DragOutlined } from '@ant-design/icons';+import type { DataNode } from 'antd/es/tree';+import styled from 'styled-components';++const { Text } = Typography;++const DraggableTreeNode = styled(Card)<{ $isDraggable: boolean }>`+ cursor: ${props => props.$isDraggable ? 'grab' : 'default'};+ background-color: #f0f9ff;+ border-color: #0ea5e9;+ margin-bottom: 4px;+ transition: all 0.2s ease;++ &:hover {+ background-color: ${props => props.$isDraggable ? '#e0f2fe' : '#f0f9ff'};+ transform: ${props => props.$isDraggable ? 'translateY(-1px)' : 'none'};+ }+`;++interface JSONTreeProps {+ data: Record<string, any>;+ nodeName: string;+ onDragStart: (e: React.DragEvent, nodeName: string, propertyPath: string, value: any) => void;+ templateName: string;+}++interface TreeNodeData extends DataNode {+ path: string;+ value: any;+ isDraggable: boolean;+}++const JSONTreeRenderer: React.FC<JSONTreeProps> = ({+ data,+ nodeName,+ onDragStart,+ templateName+}) => {+ const convertToTreeData = (+ obj: any,+ path: string = '',+ _parentKey: string = ''+ ): TreeNodeData[] => {+ return Object.entries(obj).map(([key, value]) => {+ const currentPath = path ? `${path}.${key}` : key;+ const isObject = typeof value === 'object' && value !== null && !Array.isArray(value);+ const isDraggable = !isObject;++ const node: TreeNodeData = {+ title: (+ <DraggableTreeNode+ size="small"+ $isDraggable={isDraggable}+ draggable={isDraggable}+ onDragStart={(e) => isDraggable && onDragStart(e, nodeName, currentPath, value)}+ bodyStyle={{ padding: 8 }}+ >+ <Space style={{ width: '100%', justifyContent: 'space-between' }}>+ <Space direction="vertical" size={0}>+ <Text code style={{ color: '#7c3aed', fontSize: 11 }}>+ {`{{${templateName}.${currentPath}}}`}+ </Text>+ <Space size={4}>+ <Text strong style={{ color: '#059669', fontSize: 10 }}>+ "{key}"+ </Text>+ <Text type="secondary" style={{ fontSize: 10 }}>:</Text>+ <Text style={{+ color: isObject ? '#7c2d12' : (typeof value === 'string' ? '#dc2626' : '#7c2d12'),+ fontSize: 10+ }}>+ {isObject ? '{object}' : JSON.stringify(value)}+ </Text>+ </Space>+ </Space>+ {isDraggable && <DragOutlined style={{ color: '#7c3aed', fontSize: 12 }} />}+ </Space>+ </DraggableTreeNode>+ ),+ key: currentPath,+ path: currentPath,+ value,+ isDraggable,+ children: isObject ? convertToTreeData(value, currentPath, key) : undefined+ };++ return node;+ });+ };++ const treeData = convertToTreeData(data);++ return (+ <Tree+ treeData={treeData}+ defaultExpandAll+ showLine+ blockNode+ style={{ background: 'transparent' }}+ />+ );+};++export default JSONTreeRenderer;\ No newline at end of filediff --git a/client/src/components/ui/AIResultModal.tsx b/client/src/components/ui/AIResultModal.tsxnew file mode 100644index 00000000..21f0a6dc--- /dev/null+++ b/client/src/components/ui/AIResultModal.tsx@@ -0,0 +1,204 @@+import React from 'react';+import Modal from './Modal';+import { useAppTheme } from '../../hooks/useAppTheme';+import { copyToClipboard, formatTimestamp } from '../../utils/formatters';++interface AIResultModalProps {+ isOpen: boolean;+ onClose: () => void;+ result: {+ response: string;+ usage?: {+ promptTokens: number;+ completionTokens: number;+ totalTokens: number;+ };+ model: string;+ finishReason?: string;+ nodeId: string;+ nodeName: string;+ timestamp: string;+ } | null;+}++const AIResultModal: React.FC<AIResultModalProps> = ({ isOpen, onClose, result }) => {+ const theme = useAppTheme();+ if (!result) return null;++ return (+ <Modal+ isOpen={isOpen}+ onClose={onClose}+ title="🤖 AI Execution Result"+ maxWidth="800px"+ maxHeight="90vh"+ >+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>+ {/* Header Info */}+ <div style={{+ padding: theme.spacing.lg,+ borderBottom: `1px solid ${theme.colors.border}`,+ backgroundColor: theme.colors.backgroundAlt,+ }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: theme.spacing.sm }}>+ <div>+ <h3 style={{+ margin: 0,+ fontSize: theme.fontSize.lg,+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.text+ }}>+ {result.nodeName} Result+ </h3>+ <p style={{+ margin: `${theme.spacing.xs} 0 0 0`,+ fontSize: theme.fontSize.sm,+ color: theme.colors.textSecondary+ }}>+ Model: {result.model} | {formatTimestamp(result.timestamp)}+ </p>+ </div>+ <button+ onClick={() => copyToClipboard(result.response, 'Response copied to clipboard!')}+ style={{+ padding: `${theme.spacing.xs} ${theme.spacing.sm}`,+ backgroundColor: theme.colors.focus,+ color: 'white',+ border: 'none',+ borderRadius: theme.borderRadius.sm,+ fontSize: theme.fontSize.sm,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: theme.spacing.xs+ }}+ onMouseEnter={(e) => e.currentTarget.style.backgroundColor = '#2563eb'}+ onMouseLeave={(e) => e.currentTarget.style.backgroundColor = theme.colors.focus}+ >+ 📋 Copy Response+ </button>+ </div>++ {/* Usage Stats */}+ {result.usage && (+ <div style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))',+ gap: theme.spacing.sm,+ marginTop: theme.spacing.sm,+ }}>+ <div style={{+ padding: theme.spacing.sm,+ backgroundColor: theme.colors.background,+ borderRadius: theme.borderRadius.sm,+ textAlign: 'center'+ }}>+ <div style={{ fontSize: theme.fontSize.lg, fontWeight: theme.fontWeight.semibold, color: theme.colors.text }}>+ {result.usage.promptTokens}+ </div>+ <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary }}>+ Prompt Tokens+ </div>+ </div>+ <div style={{+ padding: theme.spacing.sm,+ backgroundColor: theme.colors.background,+ borderRadius: theme.borderRadius.sm,+ textAlign: 'center'+ }}>+ <div style={{ fontSize: theme.fontSize.lg, fontWeight: theme.fontWeight.semibold, color: theme.colors.text }}>+ {result.usage.completionTokens}+ </div>+ <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary }}>+ Completion Tokens+ </div>+ </div>+ <div style={{+ padding: theme.spacing.sm,+ backgroundColor: theme.colors.background,+ borderRadius: theme.borderRadius.sm,+ textAlign: 'center'+ }}>+ <div style={{ fontSize: theme.fontSize.lg, fontWeight: theme.fontWeight.semibold, color: theme.colors.text }}>+ {result.usage.totalTokens}+ </div>+ <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary }}>+ Total Tokens+ </div>+ </div>+ </div>+ )}+ </div>++ {/* Response Content */}+ <div style={{+ flex: 1,+ padding: theme.spacing.lg,+ overflowY: 'auto'+ }}>+ <h4 style={{+ margin: `0 0 ${theme.spacing.md} 0`,+ fontSize: theme.fontSize.base,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.text+ }}>+ Response:+ </h4>+ <div style={{+ padding: theme.spacing.lg,+ backgroundColor: theme.colors.backgroundAlt,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.md,+ fontSize: theme.fontSize.base,+ lineHeight: '1.6',+ color: theme.colors.text,+ whiteSpace: 'pre-wrap',+ fontFamily: 'system-ui, -apple-system, sans-serif',+ maxHeight: '400px',+ overflowY: 'auto'+ }}>+ {result.response}+ </div>+ </div>++ {/* Footer */}+ <div style={{+ padding: theme.spacing.lg,+ borderTop: `1px solid ${theme.colors.border}`,+ backgroundColor: theme.colors.backgroundAlt,+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center'+ }}>+ <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary }}>+ {result.finishReason && `Finish reason: ${result.finishReason}`}+ </div>+ <button+ onClick={onClose}+ style={{+ padding: `${theme.spacing.sm} ${theme.spacing.lg}`,+ backgroundColor: theme.colors.background,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.sm,+ fontSize: theme.fontSize.sm,+ cursor: 'pointer',+ transition: 'all 0.2s ease'+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = theme.colors.backgroundAlt;+ e.currentTarget.style.borderColor = theme.colors.borderHover;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = theme.colors.background;+ e.currentTarget.style.borderColor = theme.colors.border;+ }}+ >+ Close+ </button>+ </div>+ </div>+ </Modal>+ );+};++export default AIResultModal;\ No newline at end of filediff --git a/client/src/components/ui/AndroidSettingsPanel.tsx b/client/src/components/ui/AndroidSettingsPanel.tsxnew file mode 100644index 00000000..0a96238c--- /dev/null+++ b/client/src/components/ui/AndroidSettingsPanel.tsx@@ -0,0 +1,401 @@+import React, { useState, useEffect } from 'react';+import { useAndroidStatus, useWebSocket } from '../../contexts/WebSocketContext';+import { useAppTheme } from '../../hooks/useAppTheme';+import { useApiKeys } from '../../hooks/useApiKeys';++interface AndroidSettingsPanelProps {+ isOpen: boolean;+ onClose: () => void;+}++const AndroidSettingsPanel: React.FC<AndroidSettingsPanelProps> = ({ isOpen, onClose }) => {+ const theme = useAppTheme();+ const androidStatus = useAndroidStatus();+ const { sendRequest } = useWebSocket();+ const { getStoredApiKey, hasStoredKey } = useApiKeys();++ const [errorMessage, setErrorMessage] = useState<string | null>(null);+ const [actionLoading, setActionLoading] = useState<'connect' | 'disconnect' | 'reconnect' | null>(null);+ const [hasApiKey, setHasApiKey] = useState<boolean | null>(null);++ // Derive status from WebSocket state+ const isConnected = androidStatus.connected;+ const isPaired = androidStatus.paired;+ const qrData = androidStatus.qr_data;++ // Check if API key is configured when panel opens+ useEffect(() => {+ if (isOpen) {+ hasStoredKey('android_remote').then(setHasApiKey);+ setErrorMessage(null);+ }+ }, [isOpen, hasStoredKey]);++ const handleConnect = async () => {+ setActionLoading('connect');+ setErrorMessage(null);++ try {+ // Get stored API key+ const apiKey = await getStoredApiKey('android_remote');++ if (!apiKey) {+ setErrorMessage('No API key configured. Go to Credentials (key icon) to add your Android Remote API key.');+ setActionLoading(null);+ return;+ }++ // Send connect request via WebSocket with stored API key+ const response = await sendRequest('android_relay_connect', {+ url: import.meta.env.VITE_ANDROID_RELAY_URL || '',+ api_key: apiKey+ });+ if (!response.success) {+ setErrorMessage(response.error || 'Failed to connect');+ }+ } catch (error: any) {+ setErrorMessage(error.message || 'Failed to connect to relay');+ } finally {+ setActionLoading(null);+ }+ };++ const handleDisconnect = async () => {+ setActionLoading('disconnect');+ setErrorMessage(null);+ try {+ // Send disconnect request via WebSocket+ const response = await sendRequest('android_relay_disconnect', {});+ if (!response.success) {+ setErrorMessage(response.error || 'Failed to disconnect');+ }+ } catch (error: any) {+ setErrorMessage(error.message || 'Failed to disconnect');+ } finally {+ setActionLoading(null);+ }+ };++ const handleReconnect = async () => {+ setActionLoading('reconnect');+ setErrorMessage(null);++ try {+ // Get stored API key+ const apiKey = await getStoredApiKey('android_remote');++ if (!apiKey) {+ setErrorMessage('No API key configured. Go to Credentials (key icon) to add your Android Remote API key.');+ setActionLoading(null);+ return;+ }++ // Send reconnect request via WebSocket - forces new session token+ const response = await sendRequest('android_relay_reconnect', {+ url: import.meta.env.VITE_ANDROID_RELAY_URL || '',+ api_key: apiKey+ });+ if (!response.success) {+ setErrorMessage(response.error || 'Failed to reconnect');+ }+ } catch (error: any) {+ setErrorMessage(error.message || 'Failed to reconnect to relay');+ } finally {+ setActionLoading(null);+ }+ };++ if (!isOpen) return null;++ const needsApiKey = hasApiKey === false && !isConnected;++ return (+ <div+ style={{+ position: 'fixed',+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ backgroundColor: 'rgba(0, 0, 0, 0.5)',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ zIndex: 1000,+ }}+ onClick={onClose}+ >+ <div+ style={{+ background: theme.colors.background,+ borderRadius: '12px',+ padding: '24px',+ boxShadow: '0 10px 40px rgba(0, 0, 0, 0.4)',+ minWidth: '400px',+ maxWidth: '500px',+ border: `1px solid ${theme.colors.border}`,+ }}+ onClick={(e) => e.stopPropagation()}+ >+ {/* Header */}+ <div+ style={{+ marginBottom: '20px',+ paddingBottom: '16px',+ borderBottom: `2px solid ${theme.colors.border}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <span style={{ fontSize: '24px' }}>+ <svg width="24" height="24" viewBox="0 0 24 24" fill="#3DDC84">+ <path d="M17.523 2.24a.75.75 0 0 0-1.046 1.046l1.5 1.5a.75.75 0 1 0 1.046-1.046l-1.5-1.5zM6.477 2.24a.75.75 0 0 1 1.046 1.046l-1.5 1.5a.75.75 0 0 1-1.046-1.046l1.5-1.5zM6.75 6h10.5a2.25 2.25 0 0 1 2.25 2.25v9a2.25 2.25 0 0 1-2.25 2.25H6.75A2.25 2.25 0 0 1 4.5 17.25v-9A2.25 2.25 0 0 1 6.75 6zm0 1.5a.75.75 0 0 0-.75.75v9c0 .414.336.75.75.75h10.5a.75.75 0 0 0 .75-.75v-9a.75.75 0 0 0-.75-.75H6.75zM12 20.25a.75.75 0 0 1 .75.75v1.5a.75.75 0 0 1-1.5 0V21a.75.75 0 0 1 .75-.75zM9 10.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm8 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0z"/>+ </svg>+ </span>+ <span style={{ fontWeight: '600', color: theme.colors.text, fontSize: '18px' }}>+ Android Relay Settings+ </span>+ </div>+ <button+ onClick={onClose}+ style={{+ background: 'none',+ border: 'none',+ fontSize: '20px',+ cursor: 'pointer',+ color: theme.colors.textSecondary,+ padding: '4px 8px',+ }}+ >+ x+ </button>+ </div>++ {/* API Key Warning */}+ {needsApiKey && (+ <div style={{+ background: '#fef3c7',+ border: '1px solid #fcd34d',+ padding: '12px',+ borderRadius: '8px',+ fontSize: '12px',+ color: '#92400e',+ lineHeight: '1.5',+ marginBottom: '16px'+ }}>+ <div style={{ fontWeight: '600', marginBottom: '4px' }}>API Key Required</div>+ <div>+ No Android Remote API key configured. Click the <strong>key icon</strong> in the toolbar to open Credentials and add your API key.+ </div>+ </div>+ )}++ {/* Connection Details */}+ <div style={{+ background: theme.colors.backgroundAlt,+ padding: '16px',+ borderRadius: '8px',+ fontSize: '13px',+ marginBottom: '16px'+ }}>+ <div style={{ fontWeight: '600', marginBottom: '12px', color: theme.colors.text, fontSize: '14px' }}>+ Connection Status+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: theme.colors.textSecondary }}>API Key:</span>+ <span style={{ color: hasApiKey ? '#3DDC84' : '#ef4444', fontWeight: '500' }}>+ {hasApiKey === null ? 'Checking...' : hasApiKey ? 'Configured' : 'Not configured'}+ </span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: theme.colors.textSecondary }}>Relay:</span>+ <span style={{ color: isConnected ? '#3DDC84' : '#ef4444', fontWeight: '500' }}>+ {isConnected ? 'Connected' : 'Disconnected'}+ </span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: theme.colors.textSecondary }}>Device:</span>+ <span style={{ color: isPaired ? '#3DDC84' : '#f59e0b', fontWeight: '500' }}>+ {isPaired ? 'Paired' : 'Waiting for pairing'}+ </span>+ </div>+ {androidStatus.device_id && (+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: theme.colors.textSecondary }}>Device ID:</span>+ <span style={{ color: theme.colors.text, fontWeight: '500', fontSize: '11px', maxWidth: '200px', overflow: 'hidden', textOverflow: 'ellipsis' }}>+ {androidStatus.device_id}+ </span>+ </div>+ )}+ {androidStatus.device_name && (+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: theme.colors.textSecondary }}>Device Name:</span>+ <span style={{ color: theme.colors.text, fontWeight: '500' }}>+ {androidStatus.device_name}+ </span>+ </div>+ )}+ </div>+ </div>++ {/* QR Code Section */}+ <div style={{+ background: theme.colors.backgroundAlt,+ padding: '16px',+ borderRadius: '8px',+ marginBottom: '16px'+ }}>+ <div style={{ fontWeight: '600', marginBottom: '12px', color: theme.colors.text, fontSize: '14px', textAlign: 'center' }}>+ QR Code Pairing+ </div>+ <div style={{+ background: theme.colors.background,+ padding: '20px',+ borderRadius: '8px',+ textAlign: 'center',+ minHeight: '220px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ flexDirection: 'column',+ gap: '12px'+ }}>+ {isPaired ? (+ <div style={{ color: '#3DDC84', fontSize: '14px' }}>+ <div style={{ fontSize: '56px', marginBottom: '12px' }}>OK</div>+ <div style={{ fontWeight: '600' }}>Device Paired!</div>+ <div style={{ color: theme.colors.textSecondary, fontSize: '12px', marginTop: '4px' }}>+ {androidStatus.device_name || androidStatus.device_id || 'Android Device'}+ </div>+ </div>+ ) : qrData ? (+ <div style={{ width: '100%' }}>+ <img+ src={`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(qrData)}`}+ alt="Android Pairing QR Code"+ style={{ maxWidth: '200px', margin: '0 auto', display: 'block', borderRadius: '8px' }}+ />+ <div style={{ color: theme.colors.textSecondary, fontSize: '12px', marginTop: '12px' }}>+ Scan with Android companion app to pair+ </div>+ </div>+ ) : isConnected ? (+ <div style={{ color: theme.colors.textSecondary, fontSize: '14px' }}>+ <div style={{ fontSize: '40px', marginBottom: '12px' }}>...</div>+ <div>Waiting for QR code...</div>+ <div style={{ fontSize: '12px', marginTop: '8px' }}>+ QR code will appear when relay server sends it+ </div>+ </div>+ ) : (+ <div style={{ color: theme.colors.textSecondary, fontSize: '14px' }}>+ <div style={{ fontSize: '40px', marginBottom: '12px' }}>[]</div>+ <div>Not connected to relay</div>+ <div style={{ fontSize: '12px', marginTop: '8px' }}>+ {hasApiKey ? 'Click Connect to start' : 'Add API key in Credentials first'}+ </div>+ </div>+ )}+ </div>+ </div>++ {/* Error Message */}+ {errorMessage && (+ <div style={{+ background: '#fef2f2',+ border: '1px solid #fecaca',+ padding: '12px',+ borderRadius: '8px',+ fontSize: '12px',+ color: '#991b1b',+ lineHeight: '1.5',+ marginBottom: '16px'+ }}>+ <div style={{ fontWeight: '600', marginBottom: '4px' }}>Error:</div>+ <div>{errorMessage}</div>+ </div>+ )}++ {/* Action Buttons */}+ <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>+ <button+ onClick={handleConnect}+ disabled={actionLoading !== null || isConnected || !hasApiKey}+ style={{+ flex: 1,+ minWidth: '100px',+ padding: '12px 16px',+ background: actionLoading === 'connect' ? '#9ca3af' : (isConnected || !hasApiKey) ? '#6b7280' : '#3DDC84',+ color: 'white',+ border: 'none',+ borderRadius: '8px',+ cursor: actionLoading !== null || isConnected || !hasApiKey ? 'not-allowed' : 'pointer',+ fontSize: '14px',+ fontWeight: '500',+ transition: 'background 0.2s ease',+ }}+ >+ {actionLoading === 'connect' ? 'Connecting...' : 'Connect'}+ </button>++ <button+ onClick={handleReconnect}+ disabled={actionLoading !== null || !isConnected || !hasApiKey}+ style={{+ flex: 1,+ minWidth: '100px',+ padding: '12px 16px',+ background: actionLoading === 'reconnect' ? '#9ca3af' : (!isConnected || !hasApiKey) ? '#6b7280' : '#f59e0b',+ color: 'white',+ border: 'none',+ borderRadius: '8px',+ cursor: actionLoading !== null || !isConnected || !hasApiKey ? 'not-allowed' : 'pointer',+ fontSize: '14px',+ fontWeight: '500',+ transition: 'background 0.2s ease',+ }}+ >+ {actionLoading === 'reconnect' ? 'Reconnecting...' : 'Reconnect'}+ </button>++ <button+ onClick={handleDisconnect}+ disabled={actionLoading !== null || !isConnected}+ style={{+ flex: 1,+ minWidth: '100px',+ padding: '12px 16px',+ background: actionLoading === 'disconnect' ? '#9ca3af' : !isConnected ? '#6b7280' : '#ef4444',+ color: 'white',+ border: 'none',+ borderRadius: '8px',+ cursor: actionLoading !== null || !isConnected ? 'not-allowed' : 'pointer',+ fontSize: '14px',+ fontWeight: '500',+ transition: 'background 0.2s ease',+ }}+ >+ {actionLoading === 'disconnect' ? 'Disconnecting...' : 'Disconnect'}+ </button>+ </div>++ {/* Reconnect Help Text */}+ {isConnected && (+ <div style={{+ marginTop: '12px',+ fontSize: '11px',+ color: theme.colors.textMuted,+ textAlign: 'center'+ }}>+ Use Reconnect to get a new QR code if pairing fails or device needs to re-pair+ </div>+ )}+ </div>+ </div>+ );+};++export default AndroidSettingsPanel;diff --git a/client/src/components/ui/CodeEditor.tsx b/client/src/components/ui/CodeEditor.tsxnew file mode 100644index 00000000..2d1c8ea6--- /dev/null+++ b/client/src/components/ui/CodeEditor.tsx@@ -0,0 +1,80 @@+import React from 'react';+import Editor from 'react-simple-code-editor';+import Prism from 'prismjs';+import 'prismjs/components/prism-python';+import 'prismjs/components/prism-javascript';+import 'prismjs/components/prism-typescript';+import { useAppTheme } from '../../hooks/useAppTheme';++interface CodeEditorProps {+ value: string;+ onChange: (value: string) => void;+ language?: string;+ placeholder?: string;+}++const CodeEditor: React.FC<CodeEditorProps> = ({+ value,+ onChange,+ language = 'python',+ placeholder+}) => {+ const theme = useAppTheme();++ const handleChange = (newValue: string) => {+ console.log('[CodeEditor] Value changed, length:', newValue.length);+ onChange(newValue);+ };++ const highlight = (code: string) => {+ const grammar = Prism.languages[language] || Prism.languages.python;+ return Prism.highlight(code, grammar, language);+ };++ return (+ <div style={{+ height: '100%',+ borderRadius: theme.borderRadius.md,+ overflow: 'hidden',+ border: `1px solid ${theme.colors.border}`+ }}>+ <style>{`+ .code-editor-container .token.comment { color: ${theme.dracula.comment}; }+ .code-editor-container .token.string { color: ${theme.dracula.yellow}; }+ .code-editor-container .token.keyword { color: ${theme.dracula.pink}; }+ .code-editor-container .token.function { color: ${theme.dracula.green}; }+ .code-editor-container .token.number { color: ${theme.dracula.purple}; }+ .code-editor-container .token.operator { color: ${theme.dracula.pink}; }+ .code-editor-container .token.class-name { color: ${theme.dracula.cyan}; }+ .code-editor-container .token.builtin { color: ${theme.dracula.cyan}; }+ .code-editor-container .token.boolean { color: ${theme.dracula.purple}; }+ .code-editor-container .token.punctuation { color: ${theme.colors.text}; }+ .code-editor-container textarea { outline: none !important; caret-color: ${theme.colors.text}; }+ .code-editor-container textarea::placeholder { color: ${theme.colors.textMuted}; }+ `}</style>+ <div className="code-editor-container" style={{ height: '100%' }}>+ <Editor+ value={value || ''}+ onValueChange={handleChange}+ highlight={highlight}+ placeholder={placeholder}+ padding={12}+ tabSize={4}+ insertSpaces={true}+ style={{+ fontFamily: "'Consolas', 'Monaco', 'Fira Code', monospace",+ fontSize: 13,+ lineHeight: 1.5,+ backgroundColor: theme.colors.backgroundAlt,+ color: theme.colors.text,+ minHeight: '100%',+ height: '100%',+ overflow: 'auto'+ }}+ />+ </div>+ </div>+ );+};++export default CodeEditor;diff --git a/client/src/components/ui/CollapsibleSection.tsx b/client/src/components/ui/CollapsibleSection.tsxnew file mode 100644index 00000000..3fba8ed5--- /dev/null+++ b/client/src/components/ui/CollapsibleSection.tsx@@ -0,0 +1,88 @@+import React from 'react';+import * as Collapsible from '@radix-ui/react-collapsible';+import { useAppTheme } from '../../hooks/useAppTheme';++interface CollapsibleSectionProps {+ title: string | React.ReactNode;+ isCollapsed: boolean;+ onToggle: () => void;+ children: React.ReactNode;+}++const CollapsibleSection: React.FC<CollapsibleSectionProps> = ({+ title,+ isCollapsed,+ onToggle,+ children+}) => {+ const theme = useAppTheme();+ return (+ <Collapsible.Root open={!isCollapsed} onOpenChange={() => onToggle()}>+ <div style={{+ backgroundColor: theme.colors.background,+ borderRadius: theme.borderRadius.lg,+ overflow: 'hidden',+ border: `1px solid ${theme.colors.border}`,+ }}>+ <Collapsible.Trigger+ style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ width: '100%',+ padding: `${theme.spacing.md} ${theme.spacing.lg}`,+ backgroundColor: theme.colors.backgroundAlt,+ border: 'none',+ cursor: 'pointer',+ fontFamily: 'system-ui, sans-serif',+ fontSize: theme.fontSize.base,+ color: theme.colors.text,+ transition: `all ${theme.transitions.fast}`,+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = theme.colors.backgroundPanel;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = theme.colors.backgroundAlt;+ }}+ >+ {typeof title === 'string' ? (+ <>+ <span style={{ fontWeight: theme.fontWeight.medium }}>{title}</span>+ <span style={{+ transform: isCollapsed ? 'rotate(-90deg)' : 'rotate(0deg)',+ transition: `transform ${theme.transitions.fast}`,+ fontSize: '12px',+ color: theme.colors.textSecondary,+ }}>+ ▼+ </span>+ </>+ ) : (+ <>+ {title}+ <span style={{+ transform: isCollapsed ? 'rotate(-90deg)' : 'rotate(0deg)',+ transition: `transform ${theme.transitions.fast}`,+ fontSize: '12px',+ color: theme.colors.textSecondary,+ marginLeft: 'auto',+ }}>+ ▼+ </span>+ </>+ )}+ </Collapsible.Trigger>++ <Collapsible.Content style={{+ padding: isCollapsed ? 0 : theme.spacing.md,+ transition: `padding ${theme.transitions.fast}`,+ }}>+ {children}+ </Collapsible.Content>+ </div>+ </Collapsible.Root>+ );+};++export default CollapsibleSection;\ No newline at end of filediff --git a/client/src/components/ui/ComponentItem.tsx b/client/src/components/ui/ComponentItem.tsxnew file mode 100644index 00000000..8d2cc7d8--- /dev/null+++ b/client/src/components/ui/ComponentItem.tsx@@ -0,0 +1,154 @@+import React, { useState } from 'react';+import { useAppTheme } from '../../hooks/useAppTheme';+import { INodeTypeDescription } from '../../types/INodeProperties';++interface ComponentItemProps {+ definition: INodeTypeDescription;+ onDragStart: (event: React.DragEvent, definition: INodeTypeDescription) => void;+}++const ComponentItem: React.FC<ComponentItemProps> = ({ definition, onDragStart }) => {+ const theme = useAppTheme();+ const [isDragging, setIsDragging] = useState(false);+ const [isHovered, setIsHovered] = useState(false);++ // Helper to get colors from new interface format+ const getNodeColor = () => definition.defaults.color || '#9E9E9E';+ const isImageIcon = () => {+ const icon = definition.icon;+ return icon && (icon.startsWith('data:') || icon.startsWith('http') || icon.startsWith('/'));+ };+ const getIconBackground = () => isImageIcon() ? theme.colors.backgroundAlt : getNodeColor();+ const getBorderColor = () => {+ // Create a darker shade for border+ const color = getNodeColor();+ // Simple color darkening - could be enhanced+ if (color.startsWith('#')) {+ const hex = color.substring(1);+ const r = Math.max(0, parseInt(hex.substring(0, 2), 16) - 40);+ const g = Math.max(0, parseInt(hex.substring(2, 4), 16) - 40);+ const b = Math.max(0, parseInt(hex.substring(4, 6), 16) - 40);+ return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`;+ }+ return color;+ };++ return (+ <div+ draggable+ onDragStart={(e) => {+ setIsDragging(true);+ onDragStart(e, definition);+ }}+ onDragEnd={() => setIsDragging(false)}+ onMouseEnter={() => setIsHovered(true)}+ onMouseLeave={() => setIsHovered(false)}+ style={{+ padding: '12px',+ backgroundColor: theme.colors.background,+ border: `2px solid ${isHovered ? getBorderColor() : theme.colors.border}`,+ borderRadius: theme.borderRadius.lg,+ cursor: 'grab',+ transition: `all ${theme.transitions.fast}`,+ display: 'flex',+ alignItems: 'center',+ gap: '12px',+ boxShadow: isHovered+ ? theme.isDarkMode+ ? `0 4px 12px ${getNodeColor()}25, 0 0 0 1px ${getNodeColor()}15`+ : `0 4px 12px ${getNodeColor()}30, 0 0 0 1px ${getNodeColor()}20`+ : theme.isDarkMode+ ? `0 1px 3px ${theme.colors.shadowLight}`+ : `0 1px 4px rgba(0,0,0,0.08)`,+ transform: isHovered ? 'translateY(-2px) scale(1.02)' : 'translateY(0)',+ opacity: isDragging ? 0.5 : 1,+ fontFamily: 'system-ui, sans-serif',+ position: 'relative',+ overflow: 'hidden',+ }}+ >+ {/* Gradient Background on Hover */}+ <div style={{+ position: 'absolute',+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ background: theme.isDarkMode+ ? `linear-gradient(135deg, ${getNodeColor()}08 0%, ${getNodeColor()}12 100%)`+ : `linear-gradient(135deg, ${getNodeColor()}06 0%, ${getNodeColor()}12 100%)`,+ opacity: isHovered ? 1 : 0,+ transition: `opacity ${theme.transitions.fast}`,+ pointerEvents: 'none',+ }} />++ {/* Icon */}+ <div+ style={{+ fontSize: '18px',+ width: '36px',+ height: '36px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ borderRadius: theme.borderRadius.md,+ backgroundColor: getIconBackground(),+ boxShadow: `0 2px 4px ${getNodeColor()}30`,+ flexShrink: 0,+ position: 'relative',+ zIndex: 1,+ }}+ >+ {definition.icon && (definition.icon.startsWith('data:') || definition.icon.startsWith('http') || definition.icon.startsWith('/')) ? (+ <img src={definition.icon} alt="" style={{ width: '20px', height: '20px', objectFit: 'contain' }} />+ ) : (+ definition.icon || '📦'+ )}+ </div>++ {/* Content */}+ <div style={{+ flex: 1,+ overflow: 'hidden',+ position: 'relative',+ zIndex: 1,+ }}>+ <div style={{+ fontWeight: theme.fontWeight.medium,+ fontSize: theme.fontSize.base,+ color: theme.colors.text,+ marginBottom: '2px',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ }}>+ {definition.displayName}+ </div>+ <div style={{+ fontSize: theme.fontSize.xs,+ color: theme.colors.textSecondary,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ lineHeight: '1.3',+ }}>+ {definition.description}+ </div>+ </div>++ {/* Drag Indicator */}+ <div style={{+ fontSize: '14px',+ color: theme.colors.textSecondary,+ opacity: isHovered ? 0.6 : 0.3,+ transition: `opacity ${theme.transitions.fast}`,+ position: 'relative',+ zIndex: 1,+ }}>+ ⋮⋮+ </div>+ </div>+ );+};++export default ComponentItem;\ No newline at end of filediff --git a/client/src/components/ui/ComponentPalette.tsx b/client/src/components/ui/ComponentPalette.tsxnew file mode 100644index 00000000..fd7d49c6--- /dev/null+++ b/client/src/components/ui/ComponentPalette.tsx@@ -0,0 +1,293 @@+import React from 'react';+import { useAppTheme } from '../../hooks/useAppTheme';+import { ComponentPaletteProps } from '../../types/ComponentTypes';+import { INodeTypeDescription } from '../../types/INodeProperties';+import ComponentItem from './ComponentItem';+import CollapsibleSection from './CollapsibleSection';++// Category emoji icons+const CATEGORY_EMOJIS: Record<string, string> = {+ workflow: '⚡',+ trigger: '🕐',+ ai: '🤖',+ location: '📍',+ whatsapp: '💬',+ android: '📱',+ chat: '💭',+ code: '💻',+ data: '🗄️',+ util: '🔧',+};++const ComponentPalette: React.FC<ComponentPaletteProps> = ({+ nodeDefinitions,+ searchQuery,+ onSearchChange,+ collapsedSections,+ onToggleSection,+ onDragStart,+}) => {+ const theme = useAppTheme();++ const getCategoryConfig = (category: string) => {+ const key = category.toLowerCase();+ // Use theme-specific category colors (darker for light mode, vibrant for dark mode)+ const colors = theme.colors as Record<string, string>;+ const colorMap: Record<string, string> = {+ workflow: colors.categoryWorkflow || theme.dracula.orange,+ trigger: colors.categoryTrigger || theme.dracula.pink,+ ai: colors.categoryAI || theme.dracula.purple,+ location: colors.categoryLocation || theme.dracula.red,+ whatsapp: colors.categoryWhatsapp || theme.dracula.green,+ android: colors.categoryAndroid || theme.dracula.cyan,+ chat: colors.categoryChat || theme.dracula.yellow,+ code: colors.categoryCode || theme.dracula.orange,+ data: colors.categoryTrigger || theme.dracula.pink,+ util: colors.categoryUtil || theme.dracula.purple,+ };+ const labelMap: Record<string, string> = {+ workflow: 'Workflow',+ trigger: 'Triggers',+ ai: 'AI',+ location: 'Google Maps',+ whatsapp: 'WhatsApp',+ android: 'Android',+ chat: 'Chat',+ code: 'Code Executors',+ data: 'Data',+ util: 'Utilities',+ };+ return {+ icon: CATEGORY_EMOJIS[key] || '📦',+ color: colorMap[key] || theme.colors.textSecondary,+ label: labelMap[key] || category+ };+ };++ const categorizedComponents = React.useMemo(() => {+ const categories: Record<string, INodeTypeDescription[]> = {};++ const filteredDefinitions = Object.values(nodeDefinitions).filter((definition) => {+ if (!searchQuery.trim()) return true;++ try {+ const query = searchQuery.toLowerCase();+ return (+ (definition.displayName || '').toLowerCase().includes(query) ||+ (definition.description || '').toLowerCase().includes(query) ||+ (definition.group?.[0] || '').toLowerCase().includes(query)+ );+ } catch (error) {+ return false;+ }+ });++ filteredDefinitions.forEach((definition) => {+ try {+ const categoryKey = definition.group?.[0] || 'Uncategorized';+ if (!categories[categoryKey]) {+ categories[categoryKey] = [];+ }+ categories[categoryKey].push(definition);+ } catch (error) {+ // Skip invalid definitions+ }+ });++ return categories;+ }, [nodeDefinitions, searchQuery]);++ const totalComponents = Object.values(categorizedComponents).reduce(+ (acc, components) => acc + components.length,+ 0+ );++ return (+ <div style={{+ width: '100%',+ height: '100%',+ overflowY: 'auto',+ backgroundColor: theme.colors.backgroundPanel,+ display: 'flex',+ flexDirection: 'column',+ }}>+ {/* Header Section */}+ <div style={{+ padding: theme.spacing.lg,+ borderBottom: `1px solid ${theme.colors.border}`,+ background: theme.colors.background,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: theme.spacing.md }}>+ <h2 style={{+ margin: 0,+ fontSize: theme.fontSize.lg,+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.text,+ fontFamily: 'system-ui, sans-serif',+ }}>+ Components+ </h2>+ <span style={{+ fontSize: theme.fontSize.xs,+ padding: '4px 10px',+ backgroundColor: theme.colors.backgroundAlt,+ borderRadius: '12px',+ color: theme.colors.textSecondary,+ fontWeight: theme.fontWeight.medium,+ }}>+ {totalComponents}+ </span>+ </div>++ {/* Search Input */}+ <div style={{ position: 'relative' }}>+ <input+ type="text"+ placeholder="Search..."+ value={searchQuery}+ onChange={(e) => onSearchChange(e.target.value)}+ style={{+ width: '100%',+ padding: '10px 12px',+ paddingLeft: '36px',+ fontSize: theme.fontSize.sm,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.md,+ backgroundColor: theme.colors.backgroundAlt,+ color: theme.colors.text,+ fontFamily: 'system-ui, sans-serif',+ outline: 'none',+ transition: `all ${theme.transitions.fast}`,+ }}+ onFocus={(e) => {+ e.currentTarget.style.borderColor = theme.colors.focus;+ e.currentTarget.style.backgroundColor = theme.colors.background;+ }}+ onBlur={(e) => {+ e.currentTarget.style.borderColor = theme.colors.border;+ e.currentTarget.style.backgroundColor = theme.colors.backgroundAlt;+ }}+ />+ <svg+ style={{+ position: 'absolute',+ left: '12px',+ top: '50%',+ transform: 'translateY(-50%)',+ width: '16px',+ height: '16px',+ color: theme.colors.textSecondary,+ pointerEvents: 'none',+ }}+ fill="none"+ stroke="currentColor"+ viewBox="0 0 24 24"+ >+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />+ </svg>+ </div>+ </div>++ {/* Categories */}+ <div style={{+ padding: theme.spacing.md,+ flex: 1,+ overflowY: 'auto',+ }}>+ {Object.keys(categorizedComponents).length === 0 ? (+ <div style={{+ textAlign: 'center',+ padding: theme.spacing.xxl,+ color: theme.colors.textSecondary,+ }}>+ <svg+ style={{ width: '48px', height: '48px', marginBottom: theme.spacing.md, opacity: 0.5 }}+ fill="none"+ stroke="currentColor"+ viewBox="0 0 24 24"+ >+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />+ </svg>+ <p style={{ margin: 0, fontSize: theme.fontSize.sm }}>+ No components found matching "{searchQuery}"+ </p>+ </div>+ ) : (+ Object.entries(categorizedComponents).map(([category, components]) => {+ try {+ const isCollapsed = collapsedSections[category];+ const config = getCategoryConfig(category);++ return (+ <div key={category || 'unknown'} style={{ marginBottom: theme.spacing.md }}>+ <CollapsibleSection+ title={+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>+ <span style={{+ width: '28px',+ height: '28px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: `${config.color}20`,+ borderRadius: '6px',+ fontSize: '16px',+ }}>+ {config.icon}+ </span>+ <span style={{+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.text,+ }}>+ {config.label}+ </span>+ </div>+ <span style={{+ fontSize: theme.fontSize.xs,+ padding: '3px 10px',+ backgroundColor: `${config.color}15`,+ borderRadius: '12px',+ color: theme.colors.textSecondary,+ fontWeight: theme.fontWeight.medium,+ }}>+ {components?.length || 0}+ </span>+ </div>+ }+ isCollapsed={isCollapsed}+ onToggle={() => onToggleSection(category)}+ >+ <div style={{+ display: 'grid',+ gap: theme.spacing.sm,+ paddingTop: theme.spacing.sm,+ }}>+ {(components || []).map((definition, idx) => {+ try {+ return (+ <ComponentItem+ key={definition?.name || `item-${idx}`}+ definition={definition}+ onDragStart={onDragStart}+ />+ );+ } catch (error) {+ return null;+ }+ })}+ </div>+ </CollapsibleSection>+ </div>+ );+ } catch (error) {+ return null;+ }+ })+ )}+ </div>+ </div>+ );+};++export default ComponentPalette;\ No newline at end of filediff --git a/client/src/components/ui/ErrorBoundary.tsx b/client/src/components/ui/ErrorBoundary.tsxnew file mode 100644index 00000000..458ba565--- /dev/null+++ b/client/src/components/ui/ErrorBoundary.tsx@@ -0,0 +1,196 @@+import { Component, ErrorInfo, ReactNode } from 'react';+import { theme } from '../../styles/theme';++interface Props {+ children: ReactNode;+ fallback?: ReactNode;+}++interface State {+ hasError: boolean;+ error?: Error;+ errorInfo?: ErrorInfo;+}++class ErrorBoundary extends Component<Props, State> {+ public state: State = {+ hasError: false+ };++ public static getDerivedStateFromError(error: Error): State {+ // Update state so the next render will show the fallback UI+ return { hasError: true, error };+ }++ public componentDidCatch(error: Error, errorInfo: ErrorInfo) {+ console.error('ErrorBoundary caught an error:', error, errorInfo);++ this.setState({+ error,+ errorInfo+ });+ }++ private handleReset = () => {+ this.setState({+ hasError: false,+ error: undefined,+ errorInfo: undefined+ });+ };++ private handleReload = () => {+ window.location.reload();+ };++ public render() {+ if (this.state.hasError) {+ // Custom fallback UI+ if (this.props.fallback) {+ return this.props.fallback;+ }++ // Default fallback UI+ return (+ <div style={{+ width: '100%',+ height: '100%',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: theme.colors.background,+ padding: theme.spacing.xl+ }}>+ <div style={{+ maxWidth: '600px',+ textAlign: 'center',+ backgroundColor: theme.colors.backgroundAlt,+ padding: theme.spacing.xl,+ borderRadius: theme.borderRadius.lg,+ border: `1px solid ${theme.colors.border}`+ }}>+ <div style={{+ fontSize: '64px',+ marginBottom: theme.spacing.lg+ }}>+ ⚠️+ </div>++ <h2 style={{+ margin: 0,+ marginBottom: theme.spacing.md,+ fontSize: theme.fontSize.xl,+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.text+ }}>+ Canvas Error Detected+ </h2>++ <p style={{+ margin: 0,+ marginBottom: theme.spacing.lg,+ fontSize: theme.fontSize.base,+ color: theme.colors.textSecondary,+ lineHeight: '1.6'+ }}>+ The workflow canvas encountered an error and needs to be reset.+ Your workflow data is safe and will be restored.+ </p>++ <div style={{+ display: 'flex',+ gap: theme.spacing.md,+ justifyContent: 'center',+ flexWrap: 'wrap'+ }}>+ <button+ onClick={this.handleReset}+ style={{+ padding: `${theme.spacing.sm} ${theme.spacing.lg}`,+ backgroundColor: theme.colors.focus,+ color: 'white',+ border: 'none',+ borderRadius: theme.borderRadius.sm,+ fontSize: theme.fontSize.base,+ fontWeight: theme.fontWeight.medium,+ cursor: 'pointer',+ transition: 'all 0.2s ease'+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = '#2563eb';+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = theme.colors.focus;+ }}+ >+ 🔄 Reset Canvas+ </button>++ <button+ onClick={this.handleReload}+ style={{+ padding: `${theme.spacing.sm} ${theme.spacing.lg}`,+ backgroundColor: 'transparent',+ color: theme.colors.text,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.sm,+ fontSize: theme.fontSize.base,+ fontWeight: theme.fontWeight.medium,+ cursor: 'pointer',+ transition: 'all 0.2s ease'+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = theme.colors.backgroundAlt;+ e.currentTarget.style.borderColor = theme.colors.borderHover;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = 'transparent';+ e.currentTarget.style.borderColor = theme.colors.border;+ }}+ >+ 🔃 Reload Page+ </button>+ </div>++ {process.env.NODE_ENV === 'development' && this.state.error && (+ <details style={{+ marginTop: theme.spacing.lg,+ textAlign: 'left',+ backgroundColor: theme.colors.backgroundPanel,+ padding: theme.spacing.md,+ borderRadius: theme.borderRadius.sm,+ border: `1px solid ${theme.colors.border}`+ }}>+ <summary style={{+ cursor: 'pointer',+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.text,+ marginBottom: theme.spacing.sm+ }}>+ 🐛 Debug Information+ </summary>+ <pre style={{+ margin: 0,+ fontSize: theme.fontSize.xs,+ color: theme.colors.textSecondary,+ fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ maxHeight: '200px',+ overflowY: 'auto'+ }}>+ {this.state.error.toString()}+ {this.state.errorInfo && this.state.errorInfo.componentStack}+ </pre>+ </details>+ )}+ </div>+ </div>+ );+ }++ return this.props.children;+ }+}++export default ErrorBoundary;\ No newline at end of filediff --git a/client/src/components/ui/InputNodesPanel.tsx b/client/src/components/ui/InputNodesPanel.tsxnew file mode 100644index 00000000..36190d47--- /dev/null+++ b/client/src/components/ui/InputNodesPanel.tsx@@ -0,0 +1,204 @@+import React, { useState, useEffect } from 'react';+import { Card, Button, Space, Typography, List, Tag, Spin } from 'antd';+import {+ LinkOutlined,+ ReloadOutlined,+ CopyOutlined,+ DatabaseOutlined+} from '@ant-design/icons';+import { useAppStore } from '../../store/useAppStore';+import { useWebSocket } from '../../contexts/WebSocketContext';+import DataPanel from '../shared/DataPanel';+import { copyToClipboard } from '../../utils/formatters';++const { Text } = Typography;++interface InputNodesPanelProps {+ nodeId: string;+}++interface InputDataItem {+ index: number;+ data: any;+ source: string; // Which node this data came from+}++const InputNodesPanel: React.FC<InputNodesPanelProps> = ({ nodeId }) => {+ const { currentWorkflow } = useAppStore();+ const { getNodeOutput } = useWebSocket();+ const [inputData, setInputData] = useState<InputDataItem[]>([]);+ const [loading, setLoading] = useState(false);++ // Fetch actual input data from backend (async)+ useEffect(() => {+ const fetchInputData = async () => {+ if (!currentWorkflow || !nodeId) {+ setInputData([]);+ return;+ }++ setLoading(true);+ const nodes = currentWorkflow.nodes || [];+ const edges = currentWorkflow.edges || [];++ // Find edges that connect TO the current node (incoming connections)+ const incomingEdges = edges.filter((edge: any) => edge.target === nodeId);++ const inputItems: InputDataItem[] = [];++ // Fetch data from backend for each connected node+ for (const edge of incomingEdges) {+ const sourceNode = nodes.find((node: any) => node.id === edge.source);+ const sourceName = sourceNode?.data?.label || sourceNode?.type || 'Unknown';++ // Get the actual output data from backend via WebSocket+ const outputData = await getNodeOutput(edge.source, 'output_0');++ if (outputData && outputData[0] && outputData[0][0]) {+ // Real execution data exists+ const actualData = outputData[0][0].json || outputData[0][0];+ inputItems.push({+ index: inputItems.length,+ data: actualData,+ source: sourceName+ });+ }+ }++ setInputData(inputItems);+ setLoading(false);+ };++ fetchInputData();+ }, [nodeId, currentWorkflow, getNodeOutput]);++ const hasExecutionData = inputData.length > 0;++ if (loading) {+ return (+ <DataPanel.Empty+ icon={<Spin size="large" />}+ title="Loading input data..."+ description="Fetching execution data from backend"+ />+ );+ }++ if (!hasExecutionData) {+ return (+ <DataPanel.Empty+ icon={<DatabaseOutlined style={{ fontSize: 48, color: '#94a3b8' }} />}+ title="No input data"+ description="Execute connected nodes to see the input data received by this node"+ />+ );+ }++ return (+ <DataPanel.Root>+ <DataPanel.Header+ title={+ <Space>+ <LinkOutlined />+ <Text strong style={{ fontSize: 13 }}>Input Data ({inputData.length} item{inputData.length !== 1 ? 's' : ''})</Text>+ </Space>+ }+ extra={+ <Button+ size="small"+ icon={<ReloadOutlined />}+ onClick={() => {+ // Trigger re-fetch by updating a dummy state+ setInputData([]);+ setLoading(true);+ }}+ type="text"+ title="Refresh input data from backend"+ loading={loading}+ >+ Refresh+ </Button>+ }+ />++ <DataPanel.Content>+ <List+ size="small"+ dataSource={inputData}+ renderItem={(inputItem) => (+ <List.Item key={inputItem.index}>+ <Card+ size="small"+ style={{+ width: '100%',+ marginBottom: 8,+ borderLeft: '4px solid #10b981'+ }}+ >+ {/* Input Item Header */}+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ marginBottom: 12+ }}>+ <Space>+ <DatabaseOutlined style={{ color: '#10b981', fontSize: 16 }} />+ <Text strong style={{ fontSize: 14 }}>+ Item {inputItem.index + 1}+ </Text>+ <Tag color="green" style={{ margin: 0 }}>+ from {inputItem.source}+ </Tag>+ </Space>+ <Button+ size="small"+ icon={<CopyOutlined />}+ onClick={() => copyToClipboard(inputItem.data, 'Input data copied to clipboard!')}+ type="text"+ title="Copy input data"+ >+ Copy+ </Button>+ </div>++ {/* JSON Input Data */}+ <Card+ size="small"+ title={<Text strong style={{ fontSize: 12 }}>Received Data</Text>}+ headStyle={{ backgroundColor: '#f0fdf4', minHeight: 'auto', padding: '8px 12px' }}+ bodyStyle={{ padding: 12 }}+ >+ <pre style={{+ margin: 0,+ fontSize: 12,+ fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',+ lineHeight: 1.4,+ overflow: 'auto',+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ maxHeight: 300,+ backgroundColor: '#f8fafc',+ padding: 12,+ borderRadius: 4,+ border: '1px solid #d1d5db'+ }}>+ {JSON.stringify(inputItem.data, null, 2)}+ </pre>+ </Card>+ </Card>+ </List.Item>+ )}+ />+ </DataPanel.Content>++ <DataPanel.Footer>+ <Text type="secondary" style={{ fontSize: 11 }}>+ 💡 Shows actual data received by this node during execution+ </Text>+ </DataPanel.Footer>+ </DataPanel.Root>+ );+};++export default InputNodesPanel;\ No newline at end of filediff --git a/client/src/components/ui/MapSelector.tsx b/client/src/components/ui/MapSelector.tsxnew file mode 100644index 00000000..8715fdd5--- /dev/null+++ b/client/src/components/ui/MapSelector.tsx@@ -0,0 +1,282 @@+import React, { useState, useCallback, useEffect, useRef } from 'react';+import { theme } from '../../styles/theme';+import { loadGoogleMaps } from '../../utils/googleMapsLoader';++// Google Maps API Key from environment variable+const GOOGLE_MAPS_API_KEY = (import.meta as any).env?.VITE_GOOGLE_MAPS_API_KEY || 'YOUR_API_KEY_HERE';++interface MapSelectorProps {+ initialLatitude?: number;+ initialLongitude?: number;+ onLocationSelect: (latitude: number, longitude: number) => void;+ onClose: () => void;+ apiKey?: string;+}++// Google Maps Component for Location Selection+const GoogleMapsLocationPicker: React.FC<{+ lat: number;+ lng: number;+ onLocationClick: (lat: number, lng: number) => void;+ apiKey?: string;+}> = ({ lat, lng, onLocationClick, apiKey }) => {+ const mapRef = useRef<HTMLDivElement>(null);+ const mapInstanceRef = useRef<google.maps.Map | null>(null);+ const markerRef = useRef<google.maps.Marker | null>(null);++ useEffect(() => {+ if (!mapRef.current || !apiKey || apiKey === 'YOUR_API_KEY_HERE') return;++ // Load Google Maps API using centralized loader+ const loadAndInitialize = async () => {+ try {+ await loadGoogleMaps({+ apiKey,+ libraries: ['geometry']+ });+ initializeMap();+ } catch (error) {+ console.error('Failed to load Google Maps API:', error);+ }+ };++ loadAndInitialize();++ function initializeMap() {+ if (!mapRef.current) return;++ const mapOptions: google.maps.MapOptions = {+ center: { lat, lng },+ zoom: 15,+ mapTypeId: google.maps.MapTypeId.ROADMAP,+ clickableIcons: false,+ disableDefaultUI: false,+ zoomControl: true,+ mapTypeControl: true,+ streetViewControl: true,+ fullscreenControl: true+ };++ mapInstanceRef.current = new google.maps.Map(mapRef.current, mapOptions);++ // Create marker+ markerRef.current = new google.maps.Marker({+ position: { lat, lng },+ map: mapInstanceRef.current,+ draggable: true,+ title: 'Selected Location - Click or drag to change'+ });++ // Add click listeners+ mapInstanceRef.current.addListener('click', (e: google.maps.MapMouseEvent) => {+ if (e.latLng) {+ const newLat = e.latLng.lat();+ const newLng = e.latLng.lng();+ onLocationClick(newLat, newLng);+ }+ });++ // Add marker drag listener+ markerRef.current.addListener('dragend', (e: google.maps.MapMouseEvent) => {+ if (e.latLng) {+ const newLat = e.latLng.lat();+ const newLng = e.latLng.lng();+ onLocationClick(newLat, newLng);+ }+ });+ }+ }, [apiKey]);++ // Update marker position when coordinates change+ useEffect(() => {+ if (markerRef.current && mapInstanceRef.current) {+ const newPosition = { lat, lng };+ markerRef.current.setPosition(newPosition);+ mapInstanceRef.current.setCenter(newPosition);+ }+ }, [lat, lng]);++ if (!apiKey || apiKey === 'YOUR_API_KEY_HERE') {+ return (+ <div style={{+ height: '100%',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: '#f5f5f5',+ color: theme.colors.textSecondary,+ fontSize: theme.fontSize.sm,+ textAlign: 'center',+ padding: theme.spacing.lg+ }}>+ Google Maps API key required for map display+ </div>+ );+ }++ return (+ <div+ ref={mapRef}+ style={{+ height: '100%',+ width: '100%'+ }}+ />+ );+};++const MapSelector: React.FC<MapSelectorProps> = ({+ initialLatitude = 37.7749,+ initialLongitude = -122.4194,+ onLocationSelect,+ onClose,+ apiKey = GOOGLE_MAPS_API_KEY+}) => {+ const [selectedPosition, setSelectedPosition] = useState<[number, number]>([+ initialLatitude,+ initialLongitude+ ]);++ const handleMapClick = useCallback((lat: number, lng: number) => {+ setSelectedPosition([lat, lng]);+ onLocationSelect(lat, lng);+ }, [onLocationSelect]);++ return (+ <>+ {/* Backdrop */}+ <div+ style={{+ position: 'fixed',+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ backgroundColor: 'rgba(0, 0, 0, 0.5)',+ zIndex: 2000,+ pointerEvents: 'none',+ }}+ />++ {/* Close Button */}+ <button+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ onClose();+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = '#dc2626';+ e.currentTarget.style.transform = 'scale(1.1)';+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = '#ef4444';+ e.currentTarget.style.transform = 'scale(1)';+ }}+ style={{+ position: 'fixed',+ top: 'calc(50% - 40vh + 10px)',+ right: '60px',+ width: '44px',+ height: '44px',+ borderRadius: '50%',+ backgroundColor: '#ef4444',+ color: 'white',+ border: 'none',+ fontSize: '20px',+ fontWeight: 'bold',+ cursor: 'pointer',+ boxShadow: '0 6px 16px rgba(239, 68, 68, 0.4)',+ zIndex: 2002,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ transition: 'all 0.2s ease',+ }}+ title="Close Map Selector"+ >+ ✕+ </button>++ {/* Map Window */}+ <div+ style={{+ position: 'fixed',+ top: '50%',+ left: '490px',+ right: '50px',+ transform: 'translateY(-50%)',+ height: '80vh',+ backgroundColor: 'white',+ borderRadius: theme.borderRadius.lg,+ boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.4)',+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden',+ zIndex: 2001,+ }}+ >+ {/* Header */}+ <div style={{+ padding: theme.spacing.md,+ borderBottom: `1px solid ${theme.colors.border}`,+ backgroundColor: theme.colors.backgroundPanel,+ }}>+ <h3 style={{+ margin: 0,+ fontSize: theme.fontSize.lg,+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.text+ }}>+ 📍 Select Location+ </h3>+ <p style={{+ margin: `${theme.spacing.xs} 0 0 0`,+ fontSize: theme.fontSize.sm,+ color: theme.colors.textSecondary+ }}>+ Click on the map or drag the marker to select coordinates+ </p>+ </div>++ {/* Coordinates Display */}+ <div style={{+ padding: theme.spacing.sm,+ backgroundColor: theme.colors.background,+ borderBottom: `1px solid ${theme.colors.border}`,+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center'+ }}>+ <div style={{+ fontSize: theme.fontSize.sm,+ fontFamily: 'monospace',+ color: theme.colors.text,+ fontWeight: theme.fontWeight.medium+ }}>+ 📌 {selectedPosition[0].toFixed(6)}, {selectedPosition[1].toFixed(6)}+ </div>+ <div style={{+ fontSize: theme.fontSize.xs,+ color: theme.colors.textSecondary,+ fontStyle: 'italic'+ }}>+ Google Maps+ </div>+ </div>++ {/* Map */}+ <div style={{ flex: 1, position: 'relative' }}>+ <GoogleMapsLocationPicker+ lat={selectedPosition[0]}+ lng={selectedPosition[1]}+ onLocationClick={handleMapClick}+ apiKey={apiKey}+ />+ </div>+ </div>+ </>+ );+};++export default MapSelector;\ No newline at end of filediff --git a/client/src/components/ui/Modal.tsx b/client/src/components/ui/Modal.tsxnew file mode 100644index 00000000..c35eeac8--- /dev/null+++ b/client/src/components/ui/Modal.tsx@@ -0,0 +1,150 @@+import React from 'react';+import * as Dialog from '@radix-ui/react-dialog';+import { useAppTheme } from '../../hooks/useAppTheme';++interface ModalProps {+ isOpen: boolean;+ onClose: () => void;+ children: React.ReactNode;+ title?: string;+ maxWidth?: string;+ maxHeight?: string;+ headerActions?: React.ReactNode;+}++const Modal: React.FC<ModalProps> = ({+ isOpen,+ onClose,+ children,+ title,+ maxWidth = '500px',+ maxHeight = '80vh',+ headerActions,+}) => {+ const theme = useAppTheme();+ return (+ <Dialog.Root open={isOpen}>+ <Dialog.Portal>+ <Dialog.Overlay+ style={{+ position: 'fixed',+ inset: 0,+ backgroundColor: 'rgba(0, 0, 0, 0.5)',+ backdropFilter: 'blur(2px)',+ zIndex: 1000,+ }}+ />+ <Dialog.Content+ style={{+ position: 'fixed',+ top: '2.5vh',+ left: '2.5vw',+ backgroundColor: theme.colors.background,+ borderRadius: theme.borderRadius.lg,+ boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.25)',+ width: maxWidth,+ height: maxHeight,+ display: 'flex',+ flexDirection: 'column',+ fontFamily: 'system-ui, sans-serif',+ overflow: 'hidden',+ zIndex: 1001,+ }}+ >+ {title && (+ <div+ style={{+ padding: `${theme.spacing.lg} ${theme.spacing.xl}`,+ borderBottom: `1px solid ${theme.colors.border}`,+ backgroundColor: theme.colors.backgroundPanel,+ display: 'flex',+ alignItems: 'center',+ position: 'relative',+ width: '100%'+ }}+ >+ <Dialog.Title+ style={{+ margin: 0,+ fontSize: theme.fontSize.lg,+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.textSecondary,+ position: 'absolute',+ left: theme.spacing.xl,+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ }}+ >+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ opacity: 0.7 }}>+ <circle cx="12" cy="12" r="3"/>+ <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/>+ </svg>+ {title}+ </Dialog.Title>++ {/* Centered header actions */}+ <div style={{+ flex: 1,+ display: 'flex',+ justifyContent: 'center',+ alignItems: 'center'+ }}>+ {headerActions}+ </div>++ <Dialog.Close+ onClick={onClose}+ style={{+ background: 'transparent',+ border: 'none',+ fontSize: '20px',+ cursor: 'pointer',+ color: theme.colors.textSecondary,+ padding: theme.spacing.xs,+ borderRadius: theme.borderRadius.sm,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ width: '32px',+ height: '32px',+ position: 'absolute',+ right: theme.spacing.xl,+ transition: `all ${theme.transitions.fast}`,+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = theme.colors.backgroundHover;+ e.currentTarget.style.color = theme.colors.text;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = 'transparent';+ e.currentTarget.style.color = theme.colors.textSecondary;+ }}+ >+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <line x1="18" y1="6" x2="6" y2="18"/>+ <line x1="6" y1="6" x2="18" y2="18"/>+ </svg>+ </Dialog.Close>+ </div>+ )}+ <Dialog.Description style={{ display: 'none' }}>+ {title || 'Modal dialog'}+ </Dialog.Description>+ <div+ style={{+ flex: 1,+ height: '100%',+ overflowY: 'auto',+ padding: 0,+ }}+ >+ {children}+ </div>+ </Dialog.Content>+ </Dialog.Portal>+ </Dialog.Root>+ );+};++export default Modal;\ No newline at end of filediff --git a/client/src/components/ui/NodeContextMenu.tsx b/client/src/components/ui/NodeContextMenu.tsxnew file mode 100644index 00000000..0fdabc47--- /dev/null+++ b/client/src/components/ui/NodeContextMenu.tsx@@ -0,0 +1,192 @@+/**+ * NodeContextMenu - Right-click context menu for nodes+ *+ * Provides actions: Rename, Copy, Delete+ * Follows n8n-style UX patterns with keyboard shortcuts displayed+ */+import React, { useEffect, useRef, useCallback } from 'react';+import { useAppTheme } from '../../hooks/useAppTheme';++interface NodeContextMenuProps {+ nodeId: string;+ x: number;+ y: number;+ onClose: () => void;+ onRename: () => void;+ onCopy: () => void;+ onDelete: () => void;+}++interface MenuItem {+ label: string;+ shortcut: string;+ action: () => void;+ icon: string;+ danger?: boolean;+}++const NodeContextMenu: React.FC<NodeContextMenuProps> = ({+ nodeId: _nodeId,+ x,+ y,+ onClose,+ onRename,+ onCopy,+ onDelete,+}) => {+ const theme = useAppTheme();+ const menuRef = useRef<HTMLDivElement>(null);+ const [focusedIndex, setFocusedIndex] = React.useState(0);++ const menuItems: MenuItem[] = [+ { label: 'Rename', shortcut: 'F2', action: onRename, icon: '✏️' },+ { label: 'Copy', shortcut: 'Ctrl+C', action: onCopy, icon: '📋' },+ { label: 'Delete', shortcut: 'Del', action: onDelete, icon: '🗑️', danger: true },+ ];++ // Calculate menu position to avoid overflow+ const getMenuPosition = useCallback(() => {+ const menuWidth = 180;+ const menuHeight = menuItems.length * 36 + 16; // items + padding+ const viewportWidth = window.innerWidth;+ const viewportHeight = window.innerHeight;++ let left = x;+ let top = y;++ // Prevent overflow on right+ if (x + menuWidth > viewportWidth) {+ left = viewportWidth - menuWidth - 8;+ }++ // Prevent overflow on bottom+ if (y + menuHeight > viewportHeight) {+ top = viewportHeight - menuHeight - 8;+ }++ return { left, top };+ }, [x, y, menuItems.length]);++ const position = getMenuPosition();++ // Handle click outside to close+ useEffect(() => {+ const handleClickOutside = (event: MouseEvent) => {+ if (menuRef.current && !menuRef.current.contains(event.target as Node)) {+ onClose();+ }+ };++ const handleEscape = (event: KeyboardEvent) => {+ if (event.key === 'Escape') {+ onClose();+ }+ };++ // Add listeners with small delay to avoid immediate close+ const timeoutId = setTimeout(() => {+ document.addEventListener('mousedown', handleClickOutside);+ document.addEventListener('keydown', handleEscape);+ }, 0);++ return () => {+ clearTimeout(timeoutId);+ document.removeEventListener('mousedown', handleClickOutside);+ document.removeEventListener('keydown', handleEscape);+ };+ }, [onClose]);++ // Handle keyboard navigation+ useEffect(() => {+ const handleKeyDown = (event: KeyboardEvent) => {+ switch (event.key) {+ case 'ArrowDown':+ event.preventDefault();+ setFocusedIndex((prev) => (prev + 1) % menuItems.length);+ break;+ case 'ArrowUp':+ event.preventDefault();+ setFocusedIndex((prev) => (prev - 1 + menuItems.length) % menuItems.length);+ break;+ case 'Enter':+ event.preventDefault();+ menuItems[focusedIndex].action();+ onClose();+ break;+ }+ };++ document.addEventListener('keydown', handleKeyDown);+ return () => document.removeEventListener('keydown', handleKeyDown);+ }, [focusedIndex, menuItems, onClose]);++ // Focus the menu on mount+ useEffect(() => {+ menuRef.current?.focus();+ }, []);++ const handleItemClick = (item: MenuItem) => {+ item.action();+ onClose();+ };++ return (+ <div+ ref={menuRef}+ tabIndex={-1}+ style={{+ position: 'fixed',+ left: position.left,+ top: position.top,+ backgroundColor: theme.colors.backgroundElevated,+ border: `1px solid ${theme.isDarkMode ? theme.colors.border : '#d1d5db'}`,+ borderRadius: theme.borderRadius.lg,+ boxShadow: theme.isDarkMode+ ? `0 4px 12px ${theme.colors.shadow}`+ : '0 4px 16px rgba(0,0,0,0.12), 0 2px 8px rgba(0,0,0,0.08)',+ padding: theme.spacing.xs,+ zIndex: 10000,+ minWidth: '160px',+ outline: 'none',+ }}+ >+ {menuItems.map((item, index) => (+ <div+ key={item.label}+ onClick={() => handleItemClick(item)}+ onMouseEnter={() => setFocusedIndex(index)}+ style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ padding: `${theme.spacing.sm} ${theme.spacing.md}`,+ borderRadius: theme.borderRadius.md,+ cursor: 'pointer',+ backgroundColor: focusedIndex === index+ ? theme.colors.backgroundHover+ : 'transparent',+ color: item.danger ? theme.dracula.red : theme.colors.text,+ fontSize: theme.fontSize.sm,+ transition: theme.transitions.fast,+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', gap: theme.spacing.sm }}>+ <span style={{ fontSize: theme.fontSize.sm }}>{item.icon}</span>+ <span style={{ fontWeight: theme.fontWeight.medium }}>{item.label}</span>+ </div>+ <span+ style={{+ fontSize: theme.fontSize.xs,+ color: theme.colors.textMuted,+ fontFamily: 'monospace',+ }}+ >+ {item.shortcut}+ </span>+ </div>+ ))}+ </div>+ );+};++export default NodeContextMenu;diff --git a/client/src/components/ui/NodeOutputPanel.tsx b/client/src/components/ui/NodeOutputPanel.tsxnew file mode 100644index 00000000..e02d8451--- /dev/null+++ b/client/src/components/ui/NodeOutputPanel.tsx@@ -0,0 +1,512 @@+import React, { useState } from 'react';+import { useAppTheme } from '../../hooks/useAppTheme';+import { ExecutionResult } from '../../services/executionService';+import { Node } from 'reactflow';+import { copyToClipboard } from '../../utils/formatters';++// Simple JSON syntax highlighter using Dracula colors+const highlightJSON = (json: string, dracula: any): React.ReactNode => {+ const lines = json.split('\n');+ return lines.map((line, i) => {+ // Highlight different parts of JSON+ const highlighted = line+ .replace(/"([^"]+)":/g, `<span style="color: ${dracula.cyan}">"$1"</span>:`)+ .replace(/: "([^"]+)"/g, `: <span style="color: ${dracula.yellow}">"$1"</span>`)+ .replace(/: (\d+\.?\d*)/g, `: <span style="color: ${dracula.purple}">$1</span>`)+ .replace(/: (true|false)/g, `: <span style="color: ${dracula.purple}">$1</span>`)+ .replace(/: (null)/g, `: <span style="color: ${dracula.orange}">$1</span>`);+ return (+ <div key={i} dangerouslySetInnerHTML={{ __html: highlighted }} />+ );+ });+};++interface NodeOutputPanelProps {+ results: ExecutionResult[];+ onClear?: () => void;+ selectedNode?: Node | null;+}++const NodeOutputPanel: React.FC<NodeOutputPanelProps> = ({+ results,+ onClear,+ selectedNode+}) => {+ const theme = useAppTheme();+ const [showRawJson, setShowRawJson] = useState(false);++ // Filter results to only show current node's output+ const nodeResults = selectedNode ? results.filter(result => result.nodeId === selectedNode.id) : results;++ // Get output data with fallbacks+ const getOutputData = (result: ExecutionResult) => {+ if (result.outputs && Object.keys(result.outputs).length > 0) {+ return result.outputs;+ }+ if (result.data && Object.keys(result.data).length > 0) {+ return result.data;+ }+ if (result.nodeData && result.nodeData.length > 0 && result.nodeData[0].length > 0) {+ return result.nodeData[0][0].json;+ }+ return {+ success: result.success,+ message: 'Execution completed'+ };+ };++ // Helper to parse nested JSON strings in Android responses+ const parseAndroidData = (data: any): any => {+ if (typeof data !== 'object' || data === null) return data;++ const parsed: any = Array.isArray(data) ? [] : {};+ for (const key in data) {+ const value = data[key];+ // Try to parse string values that look like JSON arrays or objects+ if (typeof value === 'string' && (value.startsWith('[') || value.startsWith('{'))) {+ try {+ parsed[key] = JSON.parse(value);+ } catch {+ parsed[key] = value;+ }+ } else if (typeof value === 'object' && value !== null) {+ parsed[key] = parseAndroidData(value);+ } else {+ parsed[key] = value;+ }+ }+ return parsed;+ };++ // Extract the main response text from execution results+ const getMainResponse = (result: ExecutionResult): string | { type: string; data: any; service: string; action: string } | null => {+ const data = getOutputData(result);+ // Python node output+ if (data?.output !== undefined) {+ return typeof data.output === 'string' ? data.output : JSON.stringify(data.output, null, 2);+ }+ if (data?.result?.response) return data.result.response;+ if (data?.response) return data.response;+ if (data?.result?.text) return data.result.text;+ if (data?.text) return data.text;+ if (data?.result?.content) return data.result.content;+ if (data?.content) return data.content;+ if (data?.result?.message) return data.result.message;+ if (data?.message && typeof data.message === 'string' && data.message !== 'Execution completed') return data.message;+ // WhatsApp message preview+ if (data?.result?.preview) return data.result.preview;+ if (data?.preview) return data.preview;+ // Webhook trigger output+ if (data?.method && data?.path !== undefined) {+ let bodyData = data.json || (data.body ? (() => { try { return JSON.parse(data.body); } catch { return data.body; } })() : null);+ const bodyStr = bodyData ? JSON.stringify(bodyData) : '';+ return `${data.method} /${data.path}${bodyStr ? ` - ${bodyStr}` : ''}`;+ }+ // HTTP Request output - format status and data+ if (data?.status !== undefined && data?.data !== undefined) {+ const statusText = data.status >= 200 && data.status < 300 ? 'OK' : data.status >= 400 ? 'Error' : '';+ const isHtml = typeof data.data === 'string' && data.data.trim().startsWith('<');+ const isLong = typeof data.data === 'string' && data.data.length > 200;++ if (isHtml) {+ return `${data.status} ${statusText} - HTML response (${data.data.length} chars)`;+ } else if (isLong) {+ return `${data.status} ${statusText} - ${data.data.substring(0, 150)}...`;+ } else if (typeof data.data === 'string') {+ return `${data.status} ${statusText} - ${data.data}`;+ } else {+ return `${data.status} ${statusText}\n${JSON.stringify(data.data, null, 2)}`;+ }+ }+ // Android service output - show received data with parsed nested JSON+ if (data?.service_id && data?.data) {+ const parsedData = parseAndroidData(data.data);+ return { type: 'android', data: parsedData, service: data.service_id, action: data.action };+ }+ return null;+ };++ // Get the most recent result+ const latestResult = nodeResults[0];++ if (nodeResults.length === 0) {+ const hasOtherResults = results.length > 0;++ return (+ <div style={{+ width: '100%',+ height: '100%',+ backgroundColor: theme.colors.backgroundPanel,+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ padding: theme.spacing.xxl,+ }}>+ <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke={theme.colors.textMuted} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{ marginBottom: theme.spacing.lg }}>+ <polygon points="5 3 19 12 5 21 5 3"/>+ </svg>+ <div style={{+ fontSize: theme.fontSize.base,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.textSecondary,+ marginBottom: theme.spacing.xs+ }}>+ No output yet+ </div>+ <div style={{+ fontSize: theme.fontSize.sm,+ color: theme.colors.textMuted,+ textAlign: 'center'+ }}>+ Run the node to see results+ </div>+ {hasOtherResults && (+ <div style={{+ marginTop: theme.spacing.md,+ fontSize: theme.fontSize.xs,+ color: theme.dracula.orange,+ padding: `${theme.spacing.xs} ${theme.spacing.md}`,+ backgroundColor: theme.dracula.orange + '15',+ borderRadius: theme.borderRadius.sm,+ }}>+ {results.length} result(s) from other nodes+ </div>+ )}+ </div>+ );+ }++ const outputData = getOutputData(latestResult);+ const mainResponse = getMainResponse(latestResult);++ return (+ <div style={{+ width: '100%',+ height: '100%',+ backgroundColor: theme.colors.backgroundPanel,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden',+ }}>+ {/* Header */}+ <div style={{+ padding: `${theme.spacing.md} ${theme.spacing.lg}`,+ borderBottom: `1px solid ${theme.colors.border}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ backgroundColor: theme.colors.backgroundElevated,+ flexShrink: 0,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: theme.spacing.md }}>+ {latestResult.success ? (+ <svg width="20" height="20" viewBox="0 0 24 24" fill={theme.dracula.green} stroke="none">+ <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>+ </svg>+ ) : (+ <svg width="20" height="20" viewBox="0 0 24 24" fill={theme.dracula.red} stroke="none">+ <path d="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z"/>+ </svg>+ )}+ <span style={{+ fontSize: theme.fontSize.base,+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.text,+ }}>+ Output+ </span>+ <span style={{+ fontSize: theme.fontSize.xs,+ fontWeight: theme.fontWeight.semibold,+ color: latestResult.success ? theme.dracula.green : theme.dracula.red,+ padding: `4px ${theme.spacing.md}`,+ backgroundColor: latestResult.success ? theme.dracula.green + '25' : theme.dracula.red + '25',+ borderRadius: theme.borderRadius.sm,+ border: `1px solid ${latestResult.success ? theme.dracula.green : theme.dracula.red}50`,+ letterSpacing: '0.05em',+ }}>+ {latestResult.success ? 'SUCCESS' : 'FAILED'}+ </span>+ {latestResult.executionTime > 0 && (+ <span style={{+ fontSize: theme.fontSize.sm,+ color: theme.colors.textSecondary,+ fontFamily: 'Monaco, Menlo, monospace',+ }}>+ {latestResult.executionTime.toFixed(2)}ms+ </span>+ )}+ </div>+ {onClear && (+ <button+ onClick={onClear}+ style={{+ padding: `${theme.spacing.xs} ${theme.spacing.md}`,+ fontSize: theme.fontSize.xs,+ color: theme.colors.textSecondary,+ backgroundColor: 'transparent',+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.sm,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: theme.spacing.xs,+ transition: theme.transitions.fast,+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = theme.colors.backgroundAlt;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = 'transparent';+ }}+ >+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <polyline points="3 6 5 6 21 6"/>+ <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>+ </svg>+ Clear+ </button>+ )}+ </div>++ {/* Content */}+ <div style={{+ flex: 1,+ overflow: 'auto',+ padding: theme.spacing.md,+ }}>+ {/* Error Display */}+ {latestResult.error && (+ <div style={{+ padding: theme.spacing.md,+ marginBottom: theme.spacing.md,+ backgroundColor: theme.dracula.red + '10',+ border: `1px solid ${theme.dracula.red}40`,+ borderRadius: theme.borderRadius.md,+ }}>+ <div style={{+ fontSize: theme.fontSize.xs,+ fontWeight: theme.fontWeight.medium,+ color: theme.dracula.red,+ marginBottom: theme.spacing.sm,+ textTransform: 'uppercase',+ letterSpacing: '0.05em',+ }}>+ Error+ </div>+ <pre style={{+ margin: 0,+ fontSize: theme.fontSize.sm,+ fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',+ color: theme.dracula.red,+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ }}>+ {latestResult.error}+ </pre>+ </div>+ )}++ {/* Main Response */}+ {mainResponse && typeof mainResponse === 'object' && (mainResponse as any).type === 'android' ? (+ /* Android Service Response */+ <div style={{+ padding: theme.spacing.lg,+ marginBottom: theme.spacing.md,+ backgroundColor: theme.colors.backgroundElevated,+ border: `1px solid ${theme.dracula.green}40`,+ borderRadius: theme.borderRadius.md,+ borderLeft: `3px solid ${theme.dracula.green}`,+ }}>+ <div style={{+ fontSize: theme.fontSize.xs,+ fontWeight: theme.fontWeight.semibold,+ color: theme.dracula.green,+ marginBottom: theme.spacing.md,+ textTransform: 'uppercase',+ letterSpacing: '0.1em',+ display: 'flex',+ alignItems: 'center',+ gap: theme.spacing.sm,+ }}>+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <rect x="5" y="2" width="14" height="20" rx="2" ry="2"/>+ <line x1="12" y1="18" x2="12" y2="18"/>+ </svg>+ {(mainResponse as any).service?.replace(/_/g, ' ')} - {(mainResponse as any).action}+ </div>+ <pre style={{+ margin: 0,+ fontSize: theme.fontSize.sm,+ fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',+ color: theme.colors.text,+ lineHeight: 1.6,+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ }}>+ {highlightJSON(JSON.stringify((mainResponse as any).data, null, 2), theme.dracula)}+ </pre>+ </div>+ ) : mainResponse && (+ /* Standard Response (AI, etc) */+ <div style={{+ padding: theme.spacing.lg,+ marginBottom: theme.spacing.md,+ backgroundColor: theme.colors.backgroundElevated,+ border: `1px solid ${theme.dracula.cyan}40`,+ borderRadius: theme.borderRadius.md,+ borderLeft: `3px solid ${theme.dracula.cyan}`,+ }}>+ <div style={{+ fontSize: theme.fontSize.xs,+ fontWeight: theme.fontWeight.semibold,+ color: theme.dracula.cyan,+ marginBottom: theme.spacing.md,+ textTransform: 'uppercase',+ letterSpacing: '0.1em',+ display: 'flex',+ alignItems: 'center',+ gap: theme.spacing.sm,+ }}>+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>+ </svg>+ Response+ </div>+ <div style={{+ fontSize: theme.fontSize.base,+ color: theme.colors.text,+ lineHeight: 1.7,+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ fontWeight: theme.fontWeight.normal,+ }}>+ {mainResponse as string}+ </div>+ </div>+ )}++ {/* JSON Output Toggle */}+ <div style={{+ backgroundColor: theme.colors.backgroundElevated,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.md,+ overflow: 'hidden',+ }}>+ <div+ onClick={() => setShowRawJson(!showRawJson)}+ style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ padding: `${theme.spacing.sm} ${theme.spacing.md}`,+ backgroundColor: theme.colors.backgroundAlt,+ cursor: 'pointer',+ transition: theme.transitions.fast,+ borderBottom: showRawJson ? `1px solid ${theme.colors.border}` : 'none',+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', gap: theme.spacing.sm }}>+ <svg+ width="12"+ height="12"+ viewBox="0 0 24 24"+ fill="none"+ stroke={theme.dracula.purple}+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ style={{+ transform: showRawJson ? 'rotate(90deg)' : 'rotate(0deg)',+ transition: 'transform 0.2s ease',+ }}+ >+ <polyline points="9 18 15 12 9 6"/>+ </svg>+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={theme.dracula.purple} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>+ <polyline points="14 2 14 8 20 8"/>+ <line x1="16" y1="13" x2="8" y2="13"/>+ <line x1="16" y1="17" x2="8" y2="17"/>+ </svg>+ <span style={{+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.text,+ }}>+ {showRawJson ? 'Hide' : 'Show'} Raw JSON+ </span>+ </div>+ <button+ onClick={(e) => {+ e.stopPropagation();+ copyToClipboard(outputData, 'JSON copied to clipboard!');+ }}+ style={{+ padding: `${theme.spacing.xs} ${theme.spacing.md}`,+ fontSize: theme.fontSize.xs,+ color: theme.dracula.cyan,+ backgroundColor: `${theme.dracula.cyan}15`,+ border: `1px solid ${theme.dracula.cyan}40`,+ borderRadius: theme.borderRadius.sm,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: theme.spacing.xs,+ transition: theme.transitions.fast,+ fontWeight: theme.fontWeight.medium,+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = `${theme.dracula.cyan}25`;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = `${theme.dracula.cyan}15`;+ }}+ >+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>+ <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>+ </svg>+ Copy+ </button>+ </div>++ {/* Expanded JSON with syntax highlighting */}+ {showRawJson && (+ <div style={{+ margin: 0,+ padding: theme.spacing.md,+ fontSize: theme.fontSize.sm,+ fontFamily: '"Fira Code", Monaco, Menlo, "Ubuntu Mono", monospace',+ lineHeight: 1.6,+ overflow: 'auto',+ maxHeight: '400px',+ backgroundColor: '#1a1a2e',+ color: theme.dracula.foreground,+ }}>+ {highlightJSON(JSON.stringify(outputData, null, 2), theme.dracula)}+ </div>+ )}+ </div>+ </div>++ {/* Footer */}+ {nodeResults.length > 1 && (+ <div style={{+ padding: `${theme.spacing.sm} ${theme.spacing.lg}`,+ borderTop: `1px solid ${theme.colors.border}`,+ backgroundColor: theme.colors.background,+ fontSize: theme.fontSize.xs,+ color: theme.colors.textMuted,+ textAlign: 'center',+ flexShrink: 0,+ }}>+ Showing latest of {nodeResults.length} results+ </div>+ )}+ </div>+ );+};++export default NodeOutputPanel;diff --git a/client/src/components/ui/OutputDisplayPanel.tsx b/client/src/components/ui/OutputDisplayPanel.tsxnew file mode 100644index 00000000..684b0a70--- /dev/null+++ b/client/src/components/ui/OutputDisplayPanel.tsx@@ -0,0 +1,381 @@+import React, { useState } from 'react';+import { ExecutionResult } from '../../services/executionService';+import { copyToClipboard, formatTimestamp } from '../../utils/formatters';+import { useAppTheme } from '../../hooks/useAppTheme';++interface OutputDisplayPanelProps {+ results: ExecutionResult[];+ onClear?: () => void;+ selectedNode?: any;+ currentWorkflow?: any;+}++const OutputDisplayPanel: React.FC<OutputDisplayPanelProps> = ({ results, onClear }) => {+ const theme = useAppTheme();+ const [expandedResults, setExpandedResults] = useState<Set<string>>(new Set());++ const toggleExpand = (key: string) => {+ setExpandedResults(prev => {+ const next = new Set(prev);+ if (next.has(key)) {+ next.delete(key);+ } else {+ next.add(key);+ }+ return next;+ });+ };++ const getExecutionData = (result: ExecutionResult) => {+ if (result.outputs) return result.outputs;+ if (result.data?.data) return result.data.data;+ return { message: 'No output data' };+ };++ // Extract the main response text from AI results+ const getMainResponse = (result: ExecutionResult): string | null => {+ const data = getExecutionData(result);+ // Handle nested response structure+ if (data?.result?.response) return data.result.response;+ if (data?.response) return data.response;+ if (data?.result?.text) return data.result.text;+ if (data?.text) return data.text;+ if (data?.result?.content) return data.result.content;+ if (data?.content) return data.content;+ if (data?.result?.message) return data.result.message;+ if (data?.message && typeof data.message === 'string') return data.message;+ return null;+ };++ if (results.length === 0) {+ return (+ <div style={{+ height: '100%',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ padding: theme.spacing.xxl,+ color: theme.colors.textMuted,+ backgroundColor: theme.colors.backgroundPanel,+ }}>+ <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke={theme.colors.textMuted} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{ marginBottom: theme.spacing.lg }}>+ <polygon points="5 3 19 12 5 21 5 3"/>+ </svg>+ <div style={{ fontSize: theme.fontSize.base, fontWeight: theme.fontWeight.medium, color: theme.colors.textSecondary, marginBottom: theme.spacing.xs }}>+ No executions yet+ </div>+ <div style={{ fontSize: theme.fontSize.sm, color: theme.colors.textMuted, textAlign: 'center' }}>+ Run nodes to see their<br />execution results here+ </div>+ </div>+ );+ }++ return (+ <div style={{+ height: '100%',+ display: 'flex',+ flexDirection: 'column',+ backgroundColor: theme.colors.backgroundPanel,+ }}>+ {/* Header */}+ <div style={{+ padding: `${theme.spacing.md} ${theme.spacing.lg}`,+ borderBottom: `1px solid ${theme.colors.border}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ backgroundColor: theme.colors.background,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: theme.spacing.sm }}>+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={theme.dracula.green} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <polygon points="5 3 19 12 5 21 5 3"/>+ </svg>+ <span style={{+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.text,+ }}>+ Execution Results+ </span>+ <span style={{+ fontSize: theme.fontSize.xs,+ color: theme.colors.textMuted,+ backgroundColor: theme.colors.backgroundAlt,+ padding: `2px ${theme.spacing.sm}`,+ borderRadius: theme.borderRadius.sm,+ }}>+ {results.length}+ </span>+ </div>+ {onClear && (+ <button+ onClick={onClear}+ style={{+ padding: `${theme.spacing.xs} ${theme.spacing.md}`,+ fontSize: theme.fontSize.xs,+ color: theme.colors.textSecondary,+ backgroundColor: 'transparent',+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.sm,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: theme.spacing.xs,+ transition: theme.transitions.fast,+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = theme.colors.backgroundAlt;+ e.currentTarget.style.borderColor = theme.colors.textMuted;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = 'transparent';+ e.currentTarget.style.borderColor = theme.colors.border;+ }}+ >+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <polyline points="3 6 5 6 21 6"/>+ <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>+ </svg>+ Clear+ </button>+ )}+ </div>++ {/* Results List */}+ <div style={{+ flex: 1,+ overflowY: 'auto',+ padding: theme.spacing.md,+ }}>+ {results.map((result, index) => {+ const resultKey = `${result.nodeId}-${result.timestamp}-${index}`;+ const isExpanded = expandedResults.has(resultKey);+ const mainResponse = getMainResponse(result);+ const executionData = getExecutionData(result);++ return (+ <div+ key={resultKey}+ style={{+ marginBottom: theme.spacing.md,+ borderRadius: theme.borderRadius.md,+ border: `1px solid ${result.success ? theme.dracula.green + '40' : theme.dracula.red + '40'}`,+ backgroundColor: theme.colors.background,+ overflow: 'hidden',+ }}+ >+ {/* Result Header */}+ <div style={{+ padding: `${theme.spacing.sm} ${theme.spacing.md}`,+ backgroundColor: result.success ? theme.dracula.green + '10' : theme.dracula.red + '10',+ borderBottom: `1px solid ${result.success ? theme.dracula.green + '30' : theme.dracula.red + '30'}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: theme.spacing.sm }}>+ {result.success ? (+ <svg width="16" height="16" viewBox="0 0 24 24" fill={theme.dracula.green} stroke="none">+ <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>+ </svg>+ ) : (+ <svg width="16" height="16" viewBox="0 0 24 24" fill={theme.dracula.red} stroke="none">+ <path d="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z"/>+ </svg>+ )}+ <span style={{+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.text,+ }}>+ {result.nodeName}+ </span>+ <span style={{+ fontSize: theme.fontSize.xs,+ fontWeight: theme.fontWeight.medium,+ color: result.success ? theme.dracula.green : theme.dracula.red,+ padding: `2px ${theme.spacing.sm}`,+ backgroundColor: result.success ? theme.dracula.green + '20' : theme.dracula.red + '20',+ borderRadius: theme.borderRadius.sm,+ }}>+ {result.success ? 'SUCCESS' : 'FAILED'}+ </span>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: theme.spacing.md }}>+ <span style={{ fontSize: theme.fontSize.xs, color: theme.colors.textMuted }}>+ {result.executionTime.toFixed(2)}ms+ </span>+ <span style={{ fontSize: theme.fontSize.xs, color: theme.colors.textMuted }}>+ {formatTimestamp(result.timestamp)}+ </span>+ </div>+ </div>++ {/* Error Display */}+ {result.error && (+ <div style={{+ padding: theme.spacing.md,+ backgroundColor: theme.dracula.red + '10',+ borderBottom: `1px solid ${theme.dracula.red}30`,+ }}>+ <pre style={{+ margin: 0,+ fontSize: theme.fontSize.sm,+ fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',+ color: theme.dracula.red,+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ }}>+ {result.error}+ </pre>+ </div>+ )}++ {/* Main Response (for AI results) */}+ {mainResponse && (+ <div style={{+ padding: theme.spacing.md,+ borderBottom: `1px solid ${theme.colors.border}`,+ }}>+ <div style={{+ fontSize: theme.fontSize.xs,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.textMuted,+ marginBottom: theme.spacing.sm,+ textTransform: 'uppercase',+ letterSpacing: '0.05em',+ }}>+ Response+ </div>+ <div style={{+ fontSize: theme.fontSize.sm,+ color: theme.colors.text,+ lineHeight: 1.6,+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ }}>+ {mainResponse}+ </div>+ </div>+ )}++ {/* JSON Output Toggle */}+ <div style={{ padding: theme.spacing.md }}>+ <div+ onClick={() => toggleExpand(resultKey)}+ style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ padding: `${theme.spacing.sm} ${theme.spacing.md}`,+ backgroundColor: theme.colors.backgroundAlt,+ borderRadius: theme.borderRadius.sm,+ cursor: 'pointer',+ transition: theme.transitions.fast,+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', gap: theme.spacing.sm }}>+ <svg+ width="12"+ height="12"+ viewBox="0 0 24 24"+ fill="none"+ stroke={theme.colors.textSecondary}+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ style={{+ transform: isExpanded ? 'rotate(90deg)' : 'rotate(0deg)',+ transition: 'transform 0.2s ease',+ }}+ >+ <polyline points="9 18 15 12 9 6"/>+ </svg>+ <span style={{+ fontSize: theme.fontSize.xs,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.textSecondary,+ }}>+ {isExpanded ? 'Hide' : 'Show'} Raw JSON+ </span>+ </div>+ <button+ onClick={(e) => {+ e.stopPropagation();+ copyToClipboard(executionData, 'JSON copied to clipboard!');+ }}+ style={{+ padding: `${theme.spacing.xs} ${theme.spacing.sm}`,+ fontSize: theme.fontSize.xs,+ color: theme.colors.textMuted,+ backgroundColor: 'transparent',+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.sm,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: theme.spacing.xs,+ transition: theme.transitions.fast,+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = theme.colors.background;+ e.currentTarget.style.color = theme.colors.text;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = 'transparent';+ e.currentTarget.style.color = theme.colors.textMuted;+ }}+ >+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>+ <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>+ </svg>+ Copy+ </button>+ </div>++ {/* Expanded JSON */}+ {isExpanded && (+ <pre style={{+ margin: 0,+ marginTop: theme.spacing.sm,+ padding: theme.spacing.md,+ fontSize: theme.fontSize.xs,+ fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',+ lineHeight: 1.5,+ overflow: 'auto',+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ maxHeight: '300px',+ backgroundColor: theme.colors.backgroundElevated,+ color: theme.dracula.foreground,+ borderRadius: theme.borderRadius.sm,+ border: `1px solid ${theme.colors.border}`,+ }}>+ {JSON.stringify(executionData, null, 2)}+ </pre>+ )}+ </div>+ </div>+ );+ })}+ </div>++ {/* Footer */}+ <div style={{+ padding: `${theme.spacing.sm} ${theme.spacing.lg}`,+ borderTop: `1px solid ${theme.colors.border}`,+ backgroundColor: theme.colors.background,+ fontSize: theme.fontSize.xs,+ color: theme.colors.textMuted,+ textAlign: 'center',+ }}>+ Results displayed in execution order+ </div>+ </div>+ );+};++export default OutputDisplayPanel;diff --git a/client/src/components/ui/SettingsPanel.tsx b/client/src/components/ui/SettingsPanel.tsxnew file mode 100644index 00000000..8b7b41a8--- /dev/null+++ b/client/src/components/ui/SettingsPanel.tsx@@ -0,0 +1,243 @@+import React from 'react';+import Modal from './Modal';+import { useAppTheme } from '../../hooks/useAppTheme';++export interface WorkflowSettings {+ autoSave: boolean;+ autoSaveInterval: number;+}++export const defaultSettings: WorkflowSettings = {+ autoSave: true,+ autoSaveInterval: 30,+};++interface SettingsPanelProps {+ isOpen: boolean;+ onClose: () => void;+ settings: WorkflowSettings;+ onSettingsChange: (settings: WorkflowSettings) => void;+}++const SettingsPanel: React.FC<SettingsPanelProps> = ({+ isOpen,+ onClose,+ settings,+ onSettingsChange,+}) => {+ const theme = useAppTheme();++ const handleChange = (key: keyof WorkflowSettings, value: number | boolean) => {+ onSettingsChange({+ ...settings,+ [key]: value,+ });+ };++ const handleReset = () => {+ onSettingsChange(defaultSettings);+ };++ const handleSave = () => {+ // Settings are already persisted to localStorage via onSettingsChange+ console.log('[SettingsPanel] Settings saved');+ onClose();+ };++ const inputStyle: React.CSSProperties = {+ width: '100%',+ padding: `${theme.spacing.sm} ${theme.spacing.md}`,+ backgroundColor: theme.colors.background,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.sm,+ color: theme.colors.text,+ fontSize: theme.fontSize.sm,+ outline: 'none',+ };++ const labelStyle: React.CSSProperties = {+ display: 'block',+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.text,+ marginBottom: theme.spacing.xs,+ };++ const descriptionStyle: React.CSSProperties = {+ fontSize: theme.fontSize.xs,+ color: theme.colors.textSecondary,+ marginTop: theme.spacing.xs,+ };++ const fieldStyle: React.CSSProperties = {+ marginBottom: theme.spacing.lg,+ };++ const checkboxContainerStyle: React.CSSProperties = {+ display: 'flex',+ alignItems: 'flex-start',+ gap: theme.spacing.sm,+ marginBottom: theme.spacing.lg,+ };++ const sectionStyle: React.CSSProperties = {+ marginBottom: theme.spacing.xl,+ padding: theme.spacing.lg,+ backgroundColor: theme.colors.backgroundPanel,+ borderRadius: theme.borderRadius.md,+ border: `1px solid ${theme.colors.border}`,+ };++ const sectionTitleStyle: React.CSSProperties = {+ fontSize: theme.fontSize.base,+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.text,+ marginBottom: theme.spacing.lg,+ display: 'flex',+ alignItems: 'center',+ gap: theme.spacing.sm,+ };++ // Header actions+ const headerActions = (+ <div style={{+ display: 'flex',+ gap: '12px',+ alignItems: 'center'+ }}>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ fontSize: '16px',+ fontWeight: '600',+ color: theme.colors.text,+ fontFamily: 'system-ui, sans-serif'+ }}>+ <span style={{ fontSize: '20px' }}>{'\u2699'}</span>+ <span>Workflow Settings</span>+ </div>++ <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>+ <button+ style={{+ padding: '8px 16px',+ backgroundColor: theme.colors.textSecondary,+ color: 'white',+ border: 'none',+ borderRadius: '4px',+ fontSize: '14px',+ fontWeight: '500',+ cursor: 'pointer',+ fontFamily: 'system-ui, sans-serif'+ }}+ onClick={handleReset}+ >+ Reset to Defaults+ </button>++ <button+ style={{+ padding: '8px 16px',+ backgroundColor: theme.colors.focus,+ color: 'white',+ border: 'none',+ borderRadius: '4px',+ fontSize: '14px',+ fontWeight: '500',+ cursor: 'pointer',+ fontFamily: 'system-ui, sans-serif'+ }}+ onClick={handleSave}+ >+ Save+ </button>+ </div>+ </div>+ );++ return (+ <Modal+ isOpen={isOpen}+ onClose={onClose}+ title="Settings"+ maxWidth="600px"+ maxHeight="95vh"+ headerActions={headerActions}+ >+ <div style={{+ padding: theme.spacing.xl,+ height: '100%',+ }}>+ {/* Auto-save Settings */}+ <div style={sectionStyle}>+ <div style={sectionTitleStyle}>+ <span>{'\uD83D\uDCBE'}</span>+ Auto-save Settings+ </div>++ <div style={checkboxContainerStyle}>+ <input+ type="checkbox"+ id="autoSave"+ checked={settings.autoSave}+ onChange={(e) => handleChange('autoSave', e.target.checked)}+ style={{ cursor: 'pointer', marginTop: '2px' }}+ />+ <div>+ <label+ htmlFor="autoSave"+ style={{+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.text,+ cursor: 'pointer',+ }}+ >+ Enable auto-save+ </label>+ <p style={descriptionStyle}>+ Automatically save the workflow at regular intervals+ </p>+ </div>+ </div>++ {settings.autoSave && (+ <div style={fieldStyle}>+ <label style={labelStyle}>Auto-save Interval (seconds)</label>+ <input+ type="number"+ min="10"+ max="300"+ step="5"+ value={settings.autoSaveInterval}+ onChange={(e) => handleChange('autoSaveInterval', parseInt(e.target.value) || 30)}+ style={inputStyle}+ />+ <p style={descriptionStyle}>+ How often to auto-save the workflow (10-300 seconds)+ </p>+ </div>+ )}++ {/* Current Settings Summary */}+ <div style={{+ marginTop: theme.spacing.lg,+ padding: theme.spacing.md,+ backgroundColor: theme.colors.backgroundAlt,+ borderRadius: theme.borderRadius.sm,+ fontSize: theme.fontSize.xs,+ color: theme.colors.textSecondary,+ }}>+ <strong>Current Configuration:</strong>+ <ul style={{ margin: `${theme.spacing.sm} 0 0 ${theme.spacing.md}`, paddingLeft: theme.spacing.md }}>+ <li>Auto-save: {settings.autoSave ? `Every ${settings.autoSaveInterval}s` : 'Disabled'}</li>+ </ul>+ </div>+ </div>+ </div>+ </Modal>+ );+};++export default SettingsPanel;diff --git a/client/src/components/ui/TopToolbar.tsx b/client/src/components/ui/TopToolbar.tsxnew file mode 100644index 00000000..7c6c4a1a--- /dev/null+++ b/client/src/components/ui/TopToolbar.tsx@@ -0,0 +1,658 @@+import React, { useState } from 'react';+import { useTheme } from '../../contexts/ThemeContext';+import { useAuth } from '../../contexts/AuthContext';+import { useAppTheme } from '../../hooks/useAppTheme';++interface TopToolbarProps {+ workflowName: string;+ onWorkflowNameChange: (name: string) => void;+ onSave: () => void;+ onNew: () => void;+ onOpen: () => void;+ onRun: () => void;+ isRunning?: boolean;+ onDeploy: () => void;+ onCancelDeployment: () => void;+ isDeploying?: boolean;+ hasUnsavedChanges: boolean;+ sidebarVisible: boolean;+ onToggleSidebar: () => void;+ componentPaletteVisible: boolean;+ onToggleComponentPalette: () => void;+ onOpenSettings: () => void;+ onOpenCredentials: () => void;+ onExportJSON: () => void;+ onExportFile: () => void;+ onImportJSON: () => void;+}++const TopToolbar: React.FC<TopToolbarProps> = ({+ workflowName,+ onWorkflowNameChange,+ onSave,+ onNew,+ onOpen,+ onRun,+ isRunning = false,+ onDeploy,+ onCancelDeployment,+ isDeploying = false,+ hasUnsavedChanges,+ sidebarVisible,+ onToggleSidebar,+ componentPaletteVisible,+ onToggleComponentPalette,+ onOpenSettings,+ onOpenCredentials,+ onExportJSON,+ onExportFile,+ onImportJSON,+}) => {+ const [isEditing, setIsEditing] = useState(false);+ const [tempName, setTempName] = useState(workflowName);+ const [fileMenuOpen, setFileMenuOpen] = useState(false);+ const { isDarkMode, toggleTheme } = useTheme();+ const { user, logout } = useAuth();+ const theme = useAppTheme();++ const handleNameClick = () => {+ setTempName(workflowName);+ setIsEditing(true);+ };++ const handleNameSubmit = () => {+ onWorkflowNameChange(tempName.trim() || 'Untitled Workflow');+ setIsEditing(false);+ };++ const handleNameKeyDown = (e: React.KeyboardEvent) => {+ if (e.key === 'Enter') {+ handleNameSubmit();+ } else if (e.key === 'Escape') {+ setTempName(workflowName);+ setIsEditing(false);+ }+ };++ // Icon-only button style - subtle with colored icon+ const iconButtonStyle: React.CSSProperties = {+ width: theme.buttonSize.lg,+ height: theme.buttonSize.lg,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: 'transparent',+ color: theme.colors.textSecondary,+ border: 'none',+ borderRadius: theme.borderRadius.md,+ cursor: 'pointer',+ transition: `all ${theme.transitions.fast}`,+ };++ // Text button style - cleaner with subtle border and Dracula accent+ const textButtonStyle: React.CSSProperties = {+ height: theme.buttonSize.md,+ padding: `0 ${theme.spacing.md}`,+ display: 'flex',+ alignItems: 'center',+ gap: theme.spacing.sm,+ backgroundColor: 'transparent',+ color: theme.dracula.green,+ border: `1px solid ${theme.dracula.green}40`,+ borderRadius: theme.borderRadius.sm,+ fontSize: theme.fontSize.base,+ fontWeight: theme.fontWeight.semibold,+ cursor: 'pointer',+ transition: `all ${theme.transitions.fast}`,+ fontFamily: 'system-ui, sans-serif',+ };++ // Action button style - Dracula theme for visibility+ const actionButtonStyle = (color: string, isDisabled = false): React.CSSProperties => ({+ height: theme.buttonSize.md,+ padding: `0 ${theme.spacing.lg}`,+ display: 'flex',+ alignItems: 'center',+ gap: theme.spacing.sm,+ backgroundColor: isDisabled ? `${theme.colors.primary}15` : `${color}25`,+ color: isDisabled ? theme.colors.primary : color,+ border: `1px solid ${isDisabled ? `${theme.colors.primary}40` : `${color}60`}`,+ borderRadius: theme.borderRadius.sm,+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.semibold,+ cursor: isDisabled ? 'not-allowed' : 'pointer',+ transition: `all ${theme.transitions.fast}`,+ fontFamily: 'system-ui, sans-serif',+ letterSpacing: '0.3px',+ });++ return (+ <div+ style={{+ height: theme.layout.toolbarHeight,+ backgroundColor: theme.colors.backgroundPanel,+ borderBottom: `1px solid ${theme.colors.border}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ padding: `0 ${theme.spacing.md}`,+ gap: theme.spacing.md,+ }}+ >+ {/* Left Section */}+ <div style={{ display: 'flex', alignItems: 'center', gap: theme.spacing.sm }}>+ {/* Sidebar Toggle */}+ <button+ onClick={onToggleSidebar}+ style={{+ ...iconButtonStyle,+ backgroundColor: sidebarVisible ? `${theme.colors.actionSidebar}30` : `${theme.colors.actionSidebar}15`,+ color: theme.colors.actionSidebar,+ border: `1px solid ${sidebarVisible ? `${theme.colors.actionSidebar}60` : `${theme.colors.actionSidebar}40`}`,+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = `${theme.colors.actionSidebar}40`;+ e.currentTarget.style.borderColor = `${theme.colors.actionSidebar}80`;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = sidebarVisible ? `${theme.colors.actionSidebar}30` : `${theme.colors.actionSidebar}15`;+ e.currentTarget.style.borderColor = sidebarVisible ? `${theme.colors.actionSidebar}60` : `${theme.colors.actionSidebar}40`;+ }}+ title={sidebarVisible ? 'Hide sidebar' : 'Show sidebar'}+ >+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ {sidebarVisible ? (+ <>+ <rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>+ <line x1="9" y1="3" x2="9" y2="21"/>+ </>+ ) : (+ <>+ <line x1="3" y1="12" x2="21" y2="12"/>+ <line x1="3" y1="6" x2="21" y2="6"/>+ <line x1="3" y1="18" x2="21" y2="18"/>+ </>+ )}+ </svg>+ </button>++ {/* Divider */}+ <div style={{ width: '1px', height: theme.spacing.xl, backgroundColor: theme.colors.border, margin: `0 ${theme.spacing.xs}` }} />++ {/* File Menu */}+ <div style={{ position: 'relative', marginLeft: sidebarVisible ? `calc(${theme.layout.workflowSidebarWidth} - ${theme.spacing.xxl} - ${theme.spacing.xxl})` : 0 }}>+ <button+ onClick={() => setFileMenuOpen(!fileMenuOpen)}+ style={{+ ...textButtonStyle,+ backgroundColor: fileMenuOpen ? theme.colors.backgroundHover : 'transparent',+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = theme.colors.backgroundHover;+ }}+ onMouseLeave={(e) => {+ if (!fileMenuOpen) {+ e.currentTarget.style.backgroundColor = 'transparent';+ }+ }}+ >+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>+ <polyline points="14 2 14 8 20 8"/>+ </svg>+ File+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <path d="M6 9l6 6 6-6"/>+ </svg>+ </button>++ {fileMenuOpen && (+ <>+ <div+ style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, zIndex: 999 }}+ onClick={() => setFileMenuOpen(false)}+ />+ <div+ style={{+ position: 'absolute',+ top: 'calc(100% + 4px)',+ left: 0,+ background: `linear-gradient(135deg, ${theme.colors.backgroundPanel} 0%, ${theme.colors.background} 100%)`,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.lg,+ boxShadow: `0 8px 24px ${theme.colors.shadow}, 0 2px 8px ${theme.colors.shadowLight}`,+ minWidth: '200px',+ zIndex: 1000,+ overflow: 'hidden',+ padding: theme.spacing.sm,+ backdropFilter: 'blur(8px)',+ }}+ >+ {/* Menu Header */}+ <div+ style={{+ padding: `${theme.spacing.sm} ${theme.spacing.md}`,+ marginBottom: theme.spacing.xs,+ borderBottom: `1px solid ${theme.colors.border}`,+ }}+ >+ <span+ style={{+ fontSize: theme.fontSize.xs,+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.textMuted,+ textTransform: 'uppercase',+ letterSpacing: '0.5px',+ fontFamily: 'system-ui, sans-serif',+ }}+ >+ File Operations+ </span>+ </div>+ {[+ { label: 'New Workflow', icon: 'M12 5v14M5 12h14', action: onNew, color: theme.dracula.green },+ { label: 'Open', icon: 'M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z', action: onOpen, color: theme.accent.blue },+ { divider: true },+ { label: 'Export', icon: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12', action: onExportFile, color: theme.accent.cyan },+ { label: 'Import', icon: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3', action: onImportJSON, color: theme.accent.cyan },+ { divider: true },+ { label: 'Copy as JSON', icon: 'M8 17.929H6a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v0M18 9h-8a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V11a2 2 0 0 0-2-2z', action: onExportJSON, color: theme.dracula.purple },+ ].map((item, index) =>+ item.divider ? (+ <div key={index} style={{ height: '1px', backgroundColor: theme.colors.border, margin: `${theme.spacing.xs} 0` }} />+ ) : (+ <button+ key={index}+ onClick={() => { item.action?.(); setFileMenuOpen(false); }}+ style={{+ width: '100%',+ padding: `${theme.spacing.sm} ${theme.spacing.md}`,+ backgroundColor: 'transparent',+ border: 'none',+ borderRadius: theme.borderRadius.md,+ color: theme.colors.textSecondary,+ fontSize: theme.fontSize.sm,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: theme.spacing.md,+ textAlign: 'left',+ fontFamily: 'system-ui, sans-serif',+ transition: `all ${theme.transitions.fast}`,+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = `${item.color}15`;+ e.currentTarget.style.color = item.color || theme.colors.text;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = 'transparent';+ e.currentTarget.style.color = theme.colors.textSecondary;+ }}+ >+ <div+ style={{+ width: theme.iconSize.lg,+ height: theme.iconSize.lg,+ borderRadius: theme.borderRadius.sm,+ backgroundColor: `${item.color}15`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ flexShrink: 0,+ }}+ >+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={item.color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <path d={item.icon} />+ </svg>+ </div>+ <span style={{ fontWeight: theme.fontWeight.medium }}>{item.label}</span>+ </button>+ )+ )}+ </div>+ </>+ )}+ </div>+ </div>++ {/* Center Section - Workflow Name */}+ <div style={{ flex: 1, display: 'flex', justifyContent: 'center' }}>+ {isEditing ? (+ <input+ type="text"+ value={tempName}+ onChange={(e) => setTempName(e.target.value)}+ onBlur={handleNameSubmit}+ onKeyDown={handleNameKeyDown}+ autoFocus+ style={{+ fontSize: '14px',+ fontWeight: 500,+ color: theme.colors.textSecondary,+ backgroundColor: theme.colors.backgroundAlt,+ border: `1px solid ${theme.accent.cyan}`,+ borderRadius: theme.borderRadius.sm,+ padding: '6px 12px',+ outline: 'none',+ fontFamily: 'system-ui, sans-serif',+ minWidth: '200px',+ textAlign: 'center',+ }}+ />+ ) : (+ <button+ onClick={handleNameClick}+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ padding: '6px 12px',+ backgroundColor: 'transparent',+ border: 'none',+ borderRadius: theme.borderRadius.sm,+ cursor: 'pointer',+ transition: `all ${theme.transitions.fast}`,+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = theme.colors.backgroundHover;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = 'transparent';+ }}+ title="Click to rename"+ >+ <span style={{+ fontSize: '14px',+ fontWeight: 500,+ color: theme.dracula.purple,+ fontFamily: 'system-ui, sans-serif',+ }}>+ {workflowName}+ </span>+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={theme.colors.textMuted} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>+ <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>+ </svg>+ </button>+ )}+ </div>++ {/* Right Section */}+ <div style={{ display: 'flex', alignItems: 'center', gap: theme.spacing.sm }}>+ {/* Settings Button */}+ <button+ onClick={onOpenSettings}+ style={{+ ...iconButtonStyle,+ backgroundColor: `${theme.colors.actionSettings}15`,+ color: theme.colors.actionSettings,+ border: `1px solid ${theme.colors.actionSettings}40`,+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = `${theme.colors.actionSettings}30`;+ e.currentTarget.style.borderColor = `${theme.colors.actionSettings}60`;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = `${theme.colors.actionSettings}15`;+ e.currentTarget.style.borderColor = `${theme.colors.actionSettings}40`;+ }}+ title="Settings"+ >+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <circle cx="12" cy="12" r="3"/>+ <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/>+ </svg>+ </button>++ {/* Credentials Button */}+ <button+ onClick={onOpenCredentials}+ style={{+ ...iconButtonStyle,+ backgroundColor: `${theme.colors.actionCredentials}15`,+ color: theme.colors.actionCredentials,+ border: `1px solid ${theme.colors.actionCredentials}40`,+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = `${theme.colors.actionCredentials}30`;+ e.currentTarget.style.borderColor = `${theme.colors.actionCredentials}60`;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = `${theme.colors.actionCredentials}15`;+ e.currentTarget.style.borderColor = `${theme.colors.actionCredentials}40`;+ }}+ title="API Credentials"+ >+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/>+ </svg>+ </button>++ {/* Theme Toggle Button */}+ <button+ onClick={toggleTheme}+ style={{+ ...iconButtonStyle,+ backgroundColor: `${theme.colors.actionTheme}15`,+ color: theme.colors.actionTheme,+ border: `1px solid ${theme.colors.actionTheme}40`,+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = `${theme.colors.actionTheme}30`;+ e.currentTarget.style.borderColor = `${theme.colors.actionTheme}60`;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = `${theme.colors.actionTheme}15`;+ e.currentTarget.style.borderColor = `${theme.colors.actionTheme}40`;+ }}+ title={isDarkMode ? 'Switch to Light mode' : 'Switch to Dark mode'}+ >+ {isDarkMode ? (+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <circle cx="12" cy="12" r="5"/>+ <line x1="12" y1="1" x2="12" y2="3"/>+ <line x1="12" y1="21" x2="12" y2="23"/>+ <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/>+ <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/>+ <line x1="1" y1="12" x2="3" y2="12"/>+ <line x1="21" y1="12" x2="23" y2="12"/>+ <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/>+ <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>+ </svg>+ ) : (+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>+ </svg>+ )}+ </button>++ {/* User & Logout */}+ {user && (+ <button+ onClick={logout}+ style={{+ ...iconButtonStyle,+ backgroundColor: `${theme.dracula.pink}15`,+ color: theme.dracula.pink,+ border: `1px solid ${theme.dracula.pink}40`,+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = `${theme.dracula.pink}30`;+ e.currentTarget.style.borderColor = `${theme.dracula.pink}60`;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = `${theme.dracula.pink}15`;+ e.currentTarget.style.borderColor = `${theme.dracula.pink}40`;+ }}+ title={`Logout ${user.display_name}`}+ >+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>+ <polyline points="16 17 21 12 16 7"/>+ <line x1="21" y1="12" x2="9" y2="12"/>+ </svg>+ </button>+ )}++ {/* Divider */}+ <div style={{ width: '1px', height: theme.spacing.xl, backgroundColor: theme.colors.border, margin: `0 ${theme.spacing.sm}` }} />++ {/* Action Buttons */}+ <button+ onClick={onRun}+ disabled={isRunning || isDeploying}+ style={actionButtonStyle(theme.colors.actionRun, isRunning || isDeploying)}+ onMouseEnter={(e) => {+ if (!isRunning && !isDeploying) {+ e.currentTarget.style.backgroundColor = `${theme.colors.actionRun}40`;+ }+ }}+ onMouseLeave={(e) => {+ if (!isRunning && !isDeploying) {+ e.currentTarget.style.backgroundColor = `${theme.colors.actionRun}25`;+ }+ }}+ title={isRunning ? 'Running...' : isDeploying ? 'Cannot run while deploying' : 'Run workflow once'}+ >+ <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">+ <path d="M8 5v14l11-7z"/>+ </svg>+ {isRunning ? 'Running' : 'Run'}+ </button>++ {!isDeploying ? (+ <button+ onClick={onDeploy}+ disabled={isRunning}+ style={actionButtonStyle(theme.colors.actionDeploy, isRunning)}+ onMouseEnter={(e) => {+ if (!isRunning) {+ e.currentTarget.style.backgroundColor = `${theme.colors.actionDeploy}40`;+ }+ }}+ onMouseLeave={(e) => {+ if (!isRunning) {+ e.currentTarget.style.backgroundColor = `${theme.colors.actionDeploy}25`;+ }+ }}+ title="Deploy workflow continuously"+ >+ <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">+ <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>+ </svg>+ Deploy+ </button>+ ) : (+ <button+ onClick={onCancelDeployment}+ style={actionButtonStyle(theme.colors.actionStop, false)}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = `${theme.colors.actionStop}40`;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = `${theme.colors.actionStop}25`;+ }}+ title="Stop deployment"+ >+ <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">+ <rect x="6" y="6" width="12" height="12" rx="1"/>+ </svg>+ Stop+ </button>+ )}++ <button+ onClick={() => {+ if (typeof onSave === 'function') {+ onSave();+ }+ }}+ style={actionButtonStyle(theme.colors.actionSave, !hasUnsavedChanges)}+ onMouseEnter={(e) => {+ if (hasUnsavedChanges) {+ e.currentTarget.style.backgroundColor = `${theme.colors.actionSave}40`;+ }+ }}+ onMouseLeave={(e) => {+ if (hasUnsavedChanges) {+ e.currentTarget.style.backgroundColor = `${theme.colors.actionSave}25`;+ }+ }}+ title={hasUnsavedChanges ? 'Save changes' : 'No changes to save'}+ >+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">+ <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/>+ <polyline points="17 21 17 13 7 13 7 21"/>+ <polyline points="7 3 7 8 15 8"/>+ </svg>+ Save+ </button>++ {/* Status Indicator */}+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: theme.spacing.sm,+ padding: `${theme.spacing.xs} ${theme.spacing.md}`,+ backgroundColor: 'transparent',+ borderRadius: theme.borderRadius.sm,+ fontSize: theme.fontSize.xs,+ fontWeight: theme.fontWeight.medium,+ color: hasUnsavedChanges ? theme.colors.statusModified : theme.colors.statusSaved,+ fontFamily: 'system-ui, sans-serif',+ }}+ >+ <div style={{+ width: theme.spacing.sm,+ height: theme.spacing.sm,+ borderRadius: '50%',+ backgroundColor: hasUnsavedChanges ? theme.colors.statusModified : theme.colors.statusSaved,+ }} />+ {hasUnsavedChanges ? 'Modified' : 'Saved'}+ </div>++ {/* Divider */}+ <div style={{ width: '1px', height: theme.spacing.xl, backgroundColor: theme.colors.border, margin: `0 ${theme.spacing.sm}` }} />++ {/* Component Palette Toggle */}+ <button+ onClick={onToggleComponentPalette}+ style={{+ ...iconButtonStyle,+ backgroundColor: componentPaletteVisible ? `${theme.colors.actionPalette}30` : `${theme.colors.actionPalette}15`,+ color: theme.colors.actionPalette,+ border: `1px solid ${componentPaletteVisible ? `${theme.colors.actionPalette}60` : `${theme.colors.actionPalette}40`}`,+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = `${theme.colors.actionPalette}40`;+ e.currentTarget.style.borderColor = `${theme.colors.actionPalette}80`;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = componentPaletteVisible ? `${theme.colors.actionPalette}30` : `${theme.colors.actionPalette}15`;+ e.currentTarget.style.borderColor = componentPaletteVisible ? `${theme.colors.actionPalette}60` : `${theme.colors.actionPalette}40`;+ }}+ title={componentPaletteVisible ? 'Hide components' : 'Show components'}+ >+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ {componentPaletteVisible ? (+ <>+ <rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>+ <line x1="15" y1="3" x2="15" y2="21"/>+ </>+ ) : (+ <>+ <rect x="3" y="3" width="7" height="7"/>+ <rect x="14" y="3" width="7" height="7"/>+ <rect x="14" y="14" width="7" height="7"/>+ <rect x="3" y="14" width="7" height="7"/>+ </>+ )}+ </svg>+ </button>+ </div>+ </div>+ );+};++export default TopToolbar;diff --git a/client/src/components/ui/WhatsAppSettingsPanel.tsx b/client/src/components/ui/WhatsAppSettingsPanel.tsxnew file mode 100644index 00000000..c295b007--- /dev/null+++ b/client/src/components/ui/WhatsAppSettingsPanel.tsx@@ -0,0 +1,345 @@+import React, { useState, useEffect } from 'react';+import { useWhatsApp } from '../../hooks/useWhatsApp';+import { useWhatsAppStatus } from '../../contexts/WebSocketContext';+import { useAppTheme } from '../../hooks/useAppTheme';++interface WhatsAppSettingsPanelProps {+ isOpen: boolean;+ onClose: () => void;+}++const WhatsAppSettingsPanel: React.FC<WhatsAppSettingsPanelProps> = ({ isOpen, onClose }) => {+ const theme = useAppTheme();+ const { getStatus, startConnection, restartConnection } = useWhatsApp();+ const whatsappStatus = useWhatsAppStatus();++ const [errorMessage, setErrorMessage] = useState<string | null>(null);+ const [actionLoading, setActionLoading] = useState<'restart' | 'start' | 'refresh' | null>(null);++ // Derive status from reactive WebSocket state+ const status = whatsappStatus.connected ? 'connected' : 'disconnected';++ // QR data comes from WebSocket status when pairing+ const qrData = whatsappStatus.qr+ ? { qr: whatsappStatus.qr, connected: false }+ : whatsappStatus.connected+ ? { connected: true }+ : { connected: false, message: whatsappStatus.running ? 'Waiting for QR code...' : 'Service not running' };++ // Fetch initial status when panel opens+ useEffect(() => {+ if (isOpen) {+ setErrorMessage(null);+ getStatus().catch(err => console.error('[WhatsAppSettings] Initial status failed:', err));+ }+ }, [isOpen, getStatus]);++ const handleRefreshStatus = async () => {+ console.log('[WhatsAppSettings] Refresh status clicked');+ setActionLoading('refresh');+ setErrorMessage(null);+ try {+ await getStatus();+ console.log('[WhatsAppSettings] Refresh status complete');+ } catch (error: any) {+ console.error('[WhatsAppSettings] Refresh status failed:', error);+ setErrorMessage(error.message || 'Failed to refresh status');+ } finally {+ setActionLoading(null);+ }+ };++ const handleRestart = async () => {+ setActionLoading('restart');+ setErrorMessage(null);++ try {+ const result = await restartConnection();+ if (!result.success && result.message) {+ setErrorMessage(result.message);+ }+ } catch (error: any) {+ setErrorMessage(error.message || 'Failed to restart service');+ } finally {+ setActionLoading(null);+ }+ };++ const handleStart = async () => {+ setActionLoading('start');+ setErrorMessage(null);++ try {+ const result = await startConnection();+ if (!result.success && result.message) {+ setErrorMessage(result.message);+ }+ } catch (error: any) {+ setErrorMessage(error.message || 'Failed to start service');+ } finally {+ setActionLoading(null);+ }+ };++ if (!isOpen) return null;++ return (+ <div+ style={{+ position: 'fixed',+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ backgroundColor: 'rgba(0, 0, 0, 0.5)',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ zIndex: 1000,+ }}+ onClick={onClose}+ >+ <div+ style={{+ background: theme.colors.background,+ borderRadius: '12px',+ padding: '24px',+ boxShadow: '0 10px 40px rgba(0, 0, 0, 0.4)',+ minWidth: '400px',+ maxWidth: '500px',+ border: `1px solid ${theme.colors.border}`,+ }}+ onClick={(e) => e.stopPropagation()}+ >+ {/* Header */}+ <div+ style={{+ marginBottom: '20px',+ paddingBottom: '16px',+ borderBottom: `2px solid ${theme.colors.border}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <span style={{ fontSize: '24px' }}>+ <svg width="24" height="24" viewBox="0 0 24 24" fill="#25D366">+ <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/>+ </svg>+ </span>+ <span style={{ fontWeight: '600', color: theme.colors.text, fontSize: '18px' }}>+ WhatsApp Settings+ </span>+ </div>+ <button+ onClick={onClose}+ style={{+ background: 'none',+ border: 'none',+ fontSize: '20px',+ cursor: 'pointer',+ color: theme.colors.textSecondary,+ padding: '4px 8px',+ }}+ >+ x+ </button>+ </div>++ {/* Connection Details */}+ <div style={{+ background: theme.colors.backgroundAlt,+ padding: '16px',+ borderRadius: '8px',+ fontSize: '13px',+ marginBottom: '16px'+ }}>+ <div style={{ fontWeight: '600', marginBottom: '12px', color: theme.colors.text, fontSize: '14px' }}>+ Connection Status+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>+ {whatsappStatus.device_id && (+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: theme.colors.textSecondary }}>Device ID:</span>+ <span style={{ color: theme.colors.text, fontWeight: '500', fontSize: '11px', maxWidth: '200px', overflow: 'hidden', textOverflow: 'ellipsis' }}>+ {whatsappStatus.device_id}+ </span>+ </div>+ )}+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: theme.colors.textSecondary }}>Status:</span>+ <span style={{ color: status === 'connected' ? '#25D366' : '#ef4444', fontWeight: '500' }}>+ {status === 'connected' ? 'Connected' : 'Disconnected'}+ </span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: theme.colors.textSecondary }}>Session:</span>+ <span style={{ color: whatsappStatus.has_session ? '#25D366' : '#ef4444', fontWeight: '500' }}>+ {whatsappStatus.has_session ? 'Active' : 'Inactive'}+ </span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: theme.colors.textSecondary }}>Service:</span>+ <span style={{ color: whatsappStatus.running ? '#25D366' : '#ef4444', fontWeight: '500' }}>+ {whatsappStatus.running ? 'Running' : 'Stopped'}+ </span>+ </div>+ {whatsappStatus.pairing !== undefined && (+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: theme.colors.textSecondary }}>Pairing:</span>+ <span style={{ color: whatsappStatus.pairing ? '#f59e0b' : theme.colors.textSecondary, fontWeight: '500' }}>+ {whatsappStatus.pairing ? 'In Progress' : 'Complete'}+ </span>+ </div>+ )}+ </div>+ </div>++ {/* QR Code Section */}+ <div style={{+ background: theme.colors.backgroundAlt,+ padding: '16px',+ borderRadius: '8px',+ marginBottom: '16px'+ }}>+ <div style={{ fontWeight: '600', marginBottom: '12px', color: theme.colors.text, fontSize: '14px', textAlign: 'center' }}>+ QR Code Authentication+ </div>+ <div style={{+ background: theme.colors.background,+ padding: '20px',+ borderRadius: '8px',+ textAlign: 'center',+ minHeight: '220px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ flexDirection: 'column',+ gap: '12px'+ }}>+ {qrData.connected ? (+ <div style={{ color: '#25D366', fontSize: '14px' }}>+ <div style={{ fontSize: '56px', marginBottom: '12px' }}>OK</div>+ <div style={{ fontWeight: '600' }}>Already Connected!</div>+ <div style={{ color: theme.colors.textSecondary, fontSize: '12px', marginTop: '4px' }}>No QR code needed</div>+ </div>+ ) : qrData.qr ? (+ <div style={{ width: '100%' }}>+ <img+ src={`data:image/png;base64,${qrData.qr}`}+ alt="WhatsApp QR Code"+ style={{ maxWidth: '200px', margin: '0 auto', display: 'block' }}+ />+ <div style={{ color: theme.colors.textSecondary, fontSize: '12px', marginTop: '12px' }}>+ Scan with WhatsApp mobile app+ </div>+ </div>+ ) : (+ <div style={{ color: theme.colors.textSecondary, fontSize: '14px' }}>+ <div style={{ fontSize: '40px', marginBottom: '12px' }}>[]</div>+ <div>{qrData.message || 'QR code not available'}</div>+ <a+ href="http://localhost:5000"+ target="_blank"+ rel="noopener noreferrer"+ style={{+ color: '#3b82f6',+ textDecoration: 'underline',+ fontSize: '12px',+ marginTop: '8px',+ display: 'block'+ }}+ >+ Open WhatsApp Dashboard+ </a>+ </div>+ )}+ </div>+ </div>++ {/* Error Message */}+ {errorMessage && (+ <div style={{+ background: '#fef2f2',+ border: '1px solid #fecaca',+ padding: '12px',+ borderRadius: '8px',+ fontSize: '12px',+ color: '#991b1b',+ lineHeight: '1.5',+ marginBottom: '16px'+ }}>+ <div style={{ fontWeight: '600', marginBottom: '4px' }}>Error:</div>+ <div>{errorMessage}</div>+ </div>+ )}++ {/* Action Buttons */}+ <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>+ <div style={{ display: 'flex', gap: '10px' }}>+ <button+ onClick={handleStart}+ disabled={actionLoading !== null}+ style={{+ flex: 1,+ padding: '12px 16px',+ background: actionLoading === 'start' ? '#9ca3af' : '#16a34a',+ color: 'white',+ border: 'none',+ borderRadius: '8px',+ cursor: actionLoading !== null ? 'wait' : 'pointer',+ fontSize: '14px',+ fontWeight: '500',+ transition: 'background 0.2s ease',+ }}+ >+ {actionLoading === 'start' ? 'Starting...' : 'Start'}+ </button>++ <button+ onClick={handleRestart}+ disabled={actionLoading !== null}+ style={{+ flex: 1,+ padding: '12px 16px',+ background: actionLoading === 'restart' ? '#9ca3af' : '#f59e0b',+ color: 'white',+ border: 'none',+ borderRadius: '8px',+ cursor: actionLoading !== null ? 'wait' : 'pointer',+ fontSize: '14px',+ fontWeight: '500',+ transition: 'background 0.2s ease',+ }}+ >+ {actionLoading === 'restart' ? 'Restarting...' : 'Restart'}+ </button>+ </div>++ <button+ onClick={handleRefreshStatus}+ disabled={actionLoading !== null}+ style={{+ width: '100%',+ padding: '12px 16px',+ background: actionLoading === 'refresh' ? '#60a5fa' : actionLoading !== null ? '#9ca3af' : '#3b82f6',+ color: 'white',+ border: 'none',+ borderRadius: '8px',+ cursor: actionLoading !== null ? 'wait' : 'pointer',+ fontSize: '14px',+ fontWeight: '500',+ transition: 'background 0.2s ease',+ pointerEvents: 'auto',+ }}+ >+ {actionLoading === 'refresh' ? 'Refreshing...' : 'Refresh Status'}+ </button>+ </div>+ </div>+ </div>+ );+};++export default WhatsAppSettingsPanel;diff --git a/client/src/components/ui/WorkflowSidebar.tsx b/client/src/components/ui/WorkflowSidebar.tsxnew file mode 100644index 00000000..1a6bf4a5--- /dev/null+++ b/client/src/components/ui/WorkflowSidebar.tsx@@ -0,0 +1,294 @@+import React, { useState } from 'react';+import { useAppTheme } from '../../hooks/useAppTheme';++export interface SavedWorkflow {+ id: string;+ name: string;+ createdAt: Date;+ lastModified: Date;+ nodeCount: number;+}++interface WorkflowSidebarProps {+ workflows: SavedWorkflow[];+ currentWorkflowId?: string;+ onSelectWorkflow: (workflow: SavedWorkflow) => void;+ onDeleteWorkflow?: (id: string) => void;+}++const WorkflowSidebar: React.FC<WorkflowSidebarProps> = ({+ workflows,+ currentWorkflowId,+ onSelectWorkflow,+ onDeleteWorkflow,+}) => {+ const theme = useAppTheme();+ const [hoveredId, setHoveredId] = useState<string | null>(null);++ const formatDate = (date: Date) => {+ return new Intl.DateTimeFormat('en-US', {+ month: 'short',+ day: 'numeric',+ hour: '2-digit',+ minute: '2-digit',+ }).format(date);+ };++ // Debug: Force component update when workflows change+ const [, forceUpdate] = React.useReducer(x => x + 1, 0);++ React.useEffect(() => {+ forceUpdate();+ }, [workflows]);++ return (+ <div+ style={{+ width: theme.layout.workflowSidebarWidth,+ height: '100%',+ backgroundColor: theme.colors.backgroundPanel,+ borderRight: `1px solid ${theme.colors.border}`,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden',+ }}+ >+ {/* Header */}+ <div+ style={{+ padding: theme.spacing.xl,+ borderBottom: `1px solid ${theme.colors.border}`,+ background: `linear-gradient(135deg, ${theme.colors.background} 0%, ${theme.colors.backgroundAlt} 100%)`,+ }}+ >+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: theme.spacing.sm,+ }}+ >+ <div+ style={{+ width: theme.spacing.xxl,+ height: theme.spacing.xxl,+ borderRadius: theme.borderRadius.md,+ background: `linear-gradient(135deg, ${theme.accent.blue}30 0%, ${theme.accent.cyan}30 100%)`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ fontSize: theme.fontSize.lg,+ }}+ >+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={theme.accent.cyan} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>+ </svg>+ </div>+ <div>+ <h3+ style={{+ margin: 0,+ fontSize: theme.fontSize.lg,+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.text,+ fontFamily: 'system-ui, sans-serif',+ }}+ >+ Workflows+ </h3>+ <p+ style={{+ margin: 0,+ fontSize: theme.fontSize.xs,+ color: theme.colors.textSecondary,+ fontFamily: 'system-ui, sans-serif',+ }}+ >+ {workflows.length} saved+ </p>+ </div>+ </div>+ </div>++ {/* Workflows List */}+ <div+ style={{+ flex: 1,+ overflowY: 'auto',+ padding: theme.spacing.md,+ }}+ >+ {workflows.length === 0 ? (+ <div+ style={{+ textAlign: 'center',+ padding: `${theme.spacing.xxl} ${theme.spacing.lg}`,+ color: theme.colors.textSecondary,+ fontSize: theme.fontSize.sm,+ fontFamily: 'system-ui, sans-serif',+ }}+ >+ <div+ style={{+ width: '64px',+ height: '64px',+ margin: `0 auto ${theme.spacing.lg}`,+ borderRadius: theme.borderRadius.lg,+ background: `linear-gradient(135deg, ${theme.colors.backgroundAlt} 0%, ${theme.colors.background} 100%)`,+ border: `2px dashed ${theme.colors.border}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ }}+ >+ <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={theme.colors.textMuted} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">+ <circle cx="12" cy="12" r="10"/>+ <line x1="12" y1="8" x2="12" y2="16"/>+ <line x1="8" y1="12" x2="16" y2="12"/>+ </svg>+ </div>+ <p style={{ margin: 0, fontWeight: theme.fontWeight.medium, color: theme.colors.text }}>No workflows yet</p>+ <p style={{ margin: `${theme.spacing.sm} 0 0`, fontSize: theme.fontSize.xs, lineHeight: '1.5' }}>+ Create your first workflow<br />to get started+ </p>+ </div>+ ) : (+ workflows.map((workflow) => {+ const isSelected = currentWorkflowId === workflow.id;+ const isHovered = hoveredId === workflow.id;+ const accentColor = theme.accent.cyan;++ return (+ <div+ key={workflow.id}+ style={{+ position: 'relative',+ padding: theme.spacing.lg,+ marginBottom: theme.spacing.sm,+ backgroundColor: isSelected+ ? `${accentColor}20`+ : isHovered+ ? theme.colors.backgroundAlt+ : theme.colors.background,+ border: `1px solid ${isSelected ? `${accentColor}50` : theme.colors.border}`,+ borderLeft: isSelected ? `3px solid ${accentColor}` : `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.md,+ cursor: 'pointer',+ transition: `all ${theme.transitions.fast}`,+ boxShadow: isSelected+ ? `0 2px 8px ${accentColor}25`+ : `0 1px 3px ${theme.colors.shadowLight}`,+ }}+ onClick={() => {+ onSelectWorkflow(workflow);+ }}+ onMouseEnter={() => setHoveredId(workflow.id)}+ onMouseLeave={() => setHoveredId(null)}+ >+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: theme.spacing.sm,+ marginBottom: theme.spacing.xs,+ }}+ >+ <div+ style={{+ width: '24px',+ height: '24px',+ borderRadius: theme.borderRadius.sm,+ background: isSelected+ ? `linear-gradient(135deg, ${accentColor}40 0%, ${accentColor}20 100%)`+ : `linear-gradient(135deg, ${theme.colors.backgroundAlt} 0%, ${theme.colors.background} 100%)`,+ border: `1px solid ${isSelected ? `${accentColor}50` : theme.colors.border}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ flexShrink: 0,+ transition: `all ${theme.transitions.fast}`,+ }}+ >+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={isSelected ? accentColor : theme.colors.textSecondary} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <polyline points="16 18 22 12 16 6"/>+ <polyline points="8 6 2 12 8 18"/>+ </svg>+ </div>+ <h4+ style={{+ margin: 0,+ fontSize: theme.fontSize.base,+ fontWeight: theme.fontWeight.medium,+ color: isSelected ? accentColor : theme.colors.text,+ fontFamily: 'system-ui, sans-serif',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ flex: 1,+ }}+ >+ {workflow.name}+ </h4>+ </div>++ <div+ style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ fontSize: theme.fontSize.xs,+ color: isSelected ? theme.colors.text : theme.colors.textSecondary,+ fontFamily: 'system-ui, sans-serif',+ }}+ >+ <span>{workflow.nodeCount} nodes</span>+ <span>{formatDate(workflow.lastModified)}</span>+ </div>++ {/* Delete button - show on hover */}+ {isHovered && onDeleteWorkflow && (+ <button+ onClick={(e) => {+ e.stopPropagation();+ if (window.confirm(`Delete "${workflow.name}"?`)) {+ onDeleteWorkflow(workflow.id);+ }+ }}+ style={{+ position: 'absolute',+ top: theme.spacing.sm,+ right: theme.spacing.sm,+ width: '24px',+ height: '24px',+ borderRadius: '4px',+ border: 'none',+ backgroundColor: theme.dracula.red + '20',+ color: theme.dracula.red,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ fontSize: '14px',+ transition: `all ${theme.transitions.fast}`,+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = theme.dracula.red + '40';+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = theme.dracula.red + '20';+ }}+ title="Delete workflow"+ >+ x+ </button>+ )}+ </div>+ );+ })+ )}+ </div>+ </div>+ );+};++export default WorkflowSidebar;\ No newline at end of filediff --git a/client/src/config/antdTheme.ts b/client/src/config/antdTheme.tsnew file mode 100644index 00000000..c4ac3339--- /dev/null+++ b/client/src/config/antdTheme.ts@@ -0,0 +1,186 @@+import { ThemeConfig } from 'antd';+import { solarized, lightColors, darkColors } from '../styles/theme';++export const lightTheme: ThemeConfig = {+ token: {+ // Primary colors - using Solarized palette+ colorPrimary: solarized.blue,+ colorSuccess: lightColors.success,+ colorWarning: solarized.yellow,+ colorError: solarized.red,+ colorInfo: solarized.cyan,++ // Background colors+ colorBgBase: lightColors.background,+ colorBgContainer: lightColors.background,+ colorBgElevated: lightColors.backgroundElevated,+ colorBgLayout: lightColors.backgroundPanel,++ // Text colors+ colorText: lightColors.text,+ colorTextSecondary: lightColors.textSecondary,+ colorTextTertiary: lightColors.textMuted,++ // Border colors+ colorBorder: lightColors.border,+ colorBorderSecondary: lightColors.backgroundAlt,++ // Border and layout+ borderRadius: 6,+ borderRadiusLG: 8,+ borderRadiusOuter: 4,++ // Typography+ fontSize: 14,+ fontSizeLG: 16,+ fontSizeSM: 12,+ fontFamily: 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',++ // Spacing+ padding: 12,+ paddingLG: 16,+ paddingSM: 8,+ paddingXS: 6,++ // Component specific+ controlHeight: 32,+ controlHeightSM: 24,+ controlHeightLG: 40,++ // Box shadow+ boxShadowSecondary: '0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)',+ },+ components: {+ Card: {+ borderRadius: 6,+ paddingLG: 12,+ },+ Collapse: {+ borderRadius: 6,+ headerBg: lightColors.backgroundPanel,+ },+ Button: {+ borderRadius: 6,+ },+ Input: {+ borderRadius: 6,+ },+ Select: {+ borderRadius: 6,+ },+ Form: {+ itemMarginBottom: 16,+ verticalLabelPadding: '0 0 4px',+ },+ Typography: {+ fontSize: 14,+ },+ Tag: {+ borderRadius: 4,+ fontSize: 11,+ },+ Badge: {+ fontSize: 11,+ },+ },+};++export const darkTheme: ThemeConfig = {+ token: {+ // Primary colors - using Solarized palette+ colorPrimary: solarized.blue,+ colorSuccess: solarized.green,+ colorWarning: solarized.yellow,+ colorError: solarized.red,+ colorInfo: solarized.cyan,++ // Background colors - using Solarized dark+ colorBgBase: darkColors.background,+ colorBgContainer: darkColors.backgroundAlt,+ colorBgElevated: darkColors.backgroundElevated,+ colorBgLayout: darkColors.background,++ // Text colors+ colorText: darkColors.text,+ colorTextSecondary: darkColors.textSecondary,+ colorTextTertiary: darkColors.textMuted,++ // Border colors+ colorBorder: darkColors.border,+ colorBorderSecondary: darkColors.borderHover,++ // Border and layout+ borderRadius: 6,+ borderRadiusLG: 8,+ borderRadiusOuter: 4,++ // Typography+ fontSize: 14,+ fontSizeLG: 16,+ fontSizeSM: 12,+ fontFamily: 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',++ // Spacing+ padding: 12,+ paddingLG: 16,+ paddingSM: 8,+ paddingXS: 6,++ // Component specific+ controlHeight: 32,+ controlHeightSM: 24,+ controlHeightLG: 40,++ // Box shadow+ boxShadowSecondary: '0 4px 12px 0 rgba(0, 0, 0, 0.4)',+ },+ components: {+ Card: {+ borderRadius: 6,+ paddingLG: 12,+ colorBgContainer: darkColors.backgroundAlt,+ },+ Collapse: {+ borderRadius: 6,+ headerBg: darkColors.backgroundAlt,+ contentBg: darkColors.background,+ },+ Button: {+ borderRadius: 6,+ },+ Input: {+ borderRadius: 6,+ colorBgContainer: darkColors.backgroundAlt,+ colorBorder: darkColors.border,+ },+ Select: {+ borderRadius: 6,+ colorBgContainer: darkColors.backgroundAlt,+ colorBorder: darkColors.border,+ },+ Form: {+ itemMarginBottom: 16,+ verticalLabelPadding: '0 0 4px',+ },+ Typography: {+ fontSize: 14,+ },+ Tag: {+ borderRadius: 4,+ fontSize: 11,+ },+ Badge: {+ fontSize: 11,+ },+ Modal: {+ contentBg: darkColors.backgroundAlt,+ headerBg: darkColors.backgroundAlt,+ },+ Tooltip: {+ colorBgSpotlight: darkColors.backgroundElevated,+ },+ },+};++// Legacy export for backwards compatibility+export const antdTheme = lightTheme;diff --git a/client/src/config/api.ts b/client/src/config/api.tsnew file mode 100644index 00000000..0ca6698e--- /dev/null+++ b/client/src/config/api.ts@@ -0,0 +1,50 @@+/**+ * Centralized API Configuration+ * Single source of truth for all backend service URLs+ */++interface ApiConfig {+ readonly PYTHON_BASE_URL: string;+ readonly WHATSAPP_BASE_URL: string;+}++/**+ * Get API configuration from environment variables with fallback defaults+ */+function getApiConfig(): ApiConfig {+ const viteEnv = (import.meta as any).env || {};++ // In production (non-localhost), use relative URLs (same origin)+ const isProduction = typeof window !== 'undefined' &&+ !window.location.hostname.includes('localhost') &&+ !window.location.hostname.includes('127.0.0.1');++ return {+ // Python FastAPI backend (port 3010 in dev, same origin in prod)+ PYTHON_BASE_URL: viteEnv.VITE_PYTHON_SERVICE_URL || (isProduction ? '' : 'http://localhost:3010'),++ // WhatsApp Go service (port 3012) - typically not called directly from frontend+ WHATSAPP_BASE_URL: viteEnv.VITE_WHATSAPP_SERVICE_URL || (isProduction ? '' : 'http://localhost:3012'),+ };+}++/**+ * API Configuration singleton+ * Import this in services instead of hardcoding URLs+ *+ * @example+ * import { API_CONFIG } from '../config/api';+ * fetch(`${API_CONFIG.PYTHON_BASE_URL}/api/workflow/execute-node`);+ */+export const API_CONFIG = getApiConfig();++/**+ * Helper to build API endpoint URLs+ */+export const buildApiUrl = (path: string, baseUrl: string = API_CONFIG.PYTHON_BASE_URL): string => {+ // Ensure path starts with /+ const normalizedPath = path.startsWith('/') ? path : `/${path}`;+ // Remove trailing slash from baseUrl+ const normalizedBase = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;+ return `${normalizedBase}${normalizedPath}`;+};diff --git a/client/src/contexts/AuthContext.tsx b/client/src/contexts/AuthContext.tsxnew file mode 100644index 00000000..3b83d655--- /dev/null+++ b/client/src/contexts/AuthContext.tsx@@ -0,0 +1,202 @@+/**+ * Authentication Context for user session management.+ *+ * Provides:+ * - Login/logout/register functions+ * - Current user state+ * - Authentication status+ * - Auth mode (single-owner vs multi-user)+ */++import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';+import { API_CONFIG } from '../config/api';++export interface User {+ id: number;+ email: string;+ display_name: string;+ is_owner: boolean;+}++export interface AuthStatus {+ auth_mode: 'single' | 'multi';+ authenticated: boolean;+ user: User | null;+ can_register: boolean;+}++interface AuthContextType {+ user: User | null;+ isAuthenticated: boolean;+ isLoading: boolean;+ authMode: 'single' | 'multi';+ canRegister: boolean;+ error: string | null;+ login: (email: string, password: string) => Promise<boolean>;+ register: (email: string, password: string, displayName: string) => Promise<boolean>;+ logout: () => Promise<void>;+ checkAuth: () => Promise<void>;+}++const AuthContext = createContext<AuthContextType | undefined>(undefined);++const getApiBase = () => `${API_CONFIG.PYTHON_BASE_URL}/api/auth`;++export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {+ const [user, setUser] = useState<User | null>(null);+ const [isLoading, setIsLoading] = useState(true);+ const [authMode, setAuthMode] = useState<'single' | 'multi'>('single');+ const [canRegister, setCanRegister] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const checkAuth = useCallback(async () => {+ try {+ const response = await fetch(`${getApiBase()}/status`, {+ credentials: 'include'+ });+ const data: AuthStatus = await response.json();++ setAuthMode(data.auth_mode);+ setCanRegister(data.can_register);++ if (data.authenticated && data.user) {+ setUser(data.user);+ } else {+ setUser(null);+ }+ setError(null);+ } catch (err) {+ console.error('Failed to check auth status:', err);+ setUser(null);+ setError('Failed to connect to server');+ } finally {+ setIsLoading(false);+ }+ }, []);++ // Check auth status on mount+ useEffect(() => {+ checkAuth();+ }, [checkAuth]);++ const login = useCallback(async (email: string, password: string): Promise<boolean> => {+ setError(null);+ setIsLoading(true);++ try {+ const response = await fetch(`${getApiBase()}/login`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ email, password })+ });++ const data = await response.json();++ if (!response.ok) {+ setError(data.detail || 'Login failed');+ setIsLoading(false);+ return false;+ }++ if (data.success && data.user) {+ setUser(data.user);+ setIsLoading(false);+ return true;+ }++ setError('Login failed');+ setIsLoading(false);+ return false;+ } catch (err) {+ console.error('Login error:', err);+ setError('Failed to connect to server');+ setIsLoading(false);+ return false;+ }+ }, []);++ const register = useCallback(async (+ email: string,+ password: string,+ displayName: string+ ): Promise<boolean> => {+ setError(null);+ setIsLoading(true);++ try {+ const response = await fetch(`${getApiBase()}/register`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ email, password, display_name: displayName })+ });++ const data = await response.json();++ if (!response.ok) {+ setError(data.detail || 'Registration failed');+ setIsLoading(false);+ return false;+ }++ if (data.success && data.user) {+ setUser(data.user);+ setCanRegister(false); // After successful registration in single-owner mode+ setIsLoading(false);+ return true;+ }++ setError('Registration failed');+ setIsLoading(false);+ return false;+ } catch (err) {+ console.error('Register error:', err);+ setError('Failed to connect to server');+ setIsLoading(false);+ return false;+ }+ }, []);++ const logout = useCallback(async () => {+ try {+ await fetch(`${getApiBase()}/logout`, {+ method: 'POST',+ credentials: 'include'+ });+ } catch (err) {+ console.error('Logout error:', err);+ } finally {+ setUser(null);+ // Re-check auth status to update canRegister+ await checkAuth();+ }+ }, [checkAuth]);++ const value: AuthContextType = {+ user,+ isAuthenticated: user !== null,+ isLoading,+ authMode,+ canRegister,+ error,+ login,+ register,+ logout,+ checkAuth+ };++ return (+ <AuthContext.Provider value={value}>+ {children}+ </AuthContext.Provider>+ );+};++export const useAuth = (): AuthContextType => {+ const context = useContext(AuthContext);+ if (context === undefined) {+ throw new Error('useAuth must be used within an AuthProvider');+ }+ return context;+};diff --git a/client/src/contexts/ThemeContext.tsx b/client/src/contexts/ThemeContext.tsxnew file mode 100644index 00000000..b35e7262--- /dev/null+++ b/client/src/contexts/ThemeContext.tsx@@ -0,0 +1,42 @@+import React, { createContext, useContext, useState, useEffect } from 'react';++interface ThemeContextType {+ isDarkMode: boolean;+ toggleTheme: () => void;+}++const ThemeContext = createContext<ThemeContextType | undefined>(undefined);++export const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {+ const [isDarkMode, setIsDarkMode] = useState(() => {+ const saved = localStorage.getItem('darkMode');+ return saved === null ? true : saved === 'true';+ });++ useEffect(() => {+ localStorage.setItem('darkMode', isDarkMode.toString());+ if (isDarkMode) {+ document.documentElement.classList.add('dark');+ } else {+ document.documentElement.classList.remove('dark');+ }+ }, [isDarkMode]);++ const toggleTheme = () => {+ setIsDarkMode(prev => !prev);+ };++ return (+ <ThemeContext.Provider value={{ isDarkMode, toggleTheme }}>+ {children}+ </ThemeContext.Provider>+ );+};++export const useTheme = () => {+ const context = useContext(ThemeContext);+ if (context === undefined) {+ throw new Error('useTheme must be used within a ThemeProvider');+ }+ return context;+};diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsxnew file mode 100644index 00000000..a1bf8f61--- /dev/null+++ b/client/src/contexts/WebSocketContext.tsx@@ -0,0 +1,1706 @@+/**+ * WebSocket Context for real-time communication with Python backend.+ *+ * Provides WebSocket connection for:+ * - Request/response operations (parameters, execution, API keys)+ * - Real-time broadcasts (status updates, multi-client sync)+ * - Android device connection status+ * - Node execution status (scoped by workflow_id - n8n pattern)+ * - Variable/parameter updates+ * - Workflow state changes+ */++import React, { createContext, useContext, useEffect, useState, useCallback, useRef, useMemo } from 'react';+import { API_CONFIG } from '../config/api';+import { useAppStore } from '../store/useAppStore';+import { useAuth } from './AuthContext';++// Generate unique request ID+const generateRequestId = (): string => {+ return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;+};++// Pending request tracking+interface PendingRequest {+ resolve: (value: any) => void;+ reject: (reason: any) => void;+ timeout: NodeJS.Timeout | null; // null for no timeout (trigger nodes)+}++// Request timeout (30 seconds)+const REQUEST_TIMEOUT = 30000;++// Trigger node types that wait indefinitely for events+const TRIGGER_NODE_TYPES = ['whatsappReceive', 'webhookTrigger', 'cronScheduler'];++// Status types+export interface AndroidStatus {+ connected: boolean;+ paired: boolean;+ device_id: string | null;+ device_name: string | null;+ connected_devices: string[];+ connection_type: string | null;+ qr_data: string | null;+ session_token: string | null;+}++export interface NodeStatus {+ status: 'idle' | 'executing' | 'success' | 'error' | 'waiting';+ data?: Record<string, any>;+ output?: any;+ timestamp?: number;+ // Per-workflow scoping (n8n pattern)+ workflow_id?: string;+ // Waiting state data+ message?: string;+ waiter_id?: string;+ timeout?: number;+}++export interface WorkflowStatus {+ executing: boolean;+ current_node: string | null;+ progress?: number;+}++export interface DeploymentStatus {+ isRunning: boolean;+ activeRuns: number;+ status: 'idle' | 'starting' | 'running' | 'stopped' | 'cancelled' | 'error';+ workflow_id?: string | null; // Which workflow is deployed (for scoping)+ totalTime?: number;+ error?: string;+}++export interface WorkflowLock {+ locked: boolean;+ workflow_id: string | null;+ locked_at: number | null;+ reason: string | null;+}++export interface WhatsAppStatus {+ connected: boolean;+ has_session: boolean;+ running: boolean;+ pairing: boolean;+ device_id?: string;+ qr?: string;+ timestamp?: number;+}++export interface ApiKeyStatus {+ valid: boolean;+ hasKey?: boolean;+ message?: string;+ models?: string[];+ timestamp?: number;+}++// WhatsApp received message structure (from Go service via whatsapp_message_received event)+export interface WhatsAppMessage {+ message_id: string;+ sender: string;+ chat_id: string;+ type: 'text' | 'image' | 'video' | 'audio' | 'document' | 'location' | 'contact' | 'sticker';+ text?: string;+ timestamp: number;+ is_group: boolean;+ push_name?: string;+ media_url?: string;+ media_data?: string; // Base64 if includeMediaData is enabled+ caption?: string;+ // Location message fields+ latitude?: number;+ longitude?: number;+ // Contact message fields+ contact_name?: string;+ vcard?: string;+}++export interface NodeParameters {+ parameters: Record<string, any>;+ version: number;+ timestamp?: number;+}++export interface FullStatus {+ android: AndroidStatus;+ api_keys: Record<string, ApiKeyStatus>;+ nodes: Record<string, NodeStatus>;+ node_parameters: Record<string, NodeParameters>;+ variables: Record<string, any>;+ workflow: WorkflowStatus;+}++// Context value type+interface WebSocketContextValue {+ // Connection state+ isConnected: boolean;+ reconnecting: boolean;++ // Status data+ androidStatus: AndroidStatus;+ whatsappStatus: WhatsAppStatus;+ whatsappMessages: WhatsAppMessage[]; // History of received messages+ lastWhatsAppMessage: WhatsAppMessage | null; // Most recent message+ apiKeyStatuses: Record<string, ApiKeyStatus>;+ nodeStatuses: Record<string, NodeStatus>; // Current workflow's node statuses+ nodeParameters: Record<string, NodeParameters>;+ variables: Record<string, any>;+ workflowStatus: WorkflowStatus;+ deploymentStatus: DeploymentStatus;+ workflowLock: WorkflowLock;++ // Status getters+ getNodeStatus: (nodeId: string) => NodeStatus | undefined;+ getApiKeyStatus: (provider: string) => ApiKeyStatus | undefined;+ getVariable: (name: string) => any;+ requestStatus: () => void;+ clearNodeStatus: (nodeId: string) => Promise<void>;+ clearWhatsAppMessages: () => void;++ // Generic request method+ sendRequest: <T = any>(type: string, data?: Record<string, any>) => Promise<T>;++ // Node Parameters+ getNodeParameters: (nodeId: string) => Promise<NodeParameters | null>;+ getAllNodeParameters: (nodeIds: string[]) => Promise<Record<string, NodeParameters>>;+ saveNodeParameters: (nodeId: string, parameters: Record<string, any>, version?: number) => Promise<boolean>;+ deleteNodeParameters: (nodeId: string) => Promise<boolean>;++ // Node Execution+ executeNode: (nodeId: string, nodeType: string, parameters: Record<string, any>, nodes?: any[], edges?: any[]) => Promise<any>;+ executeWorkflow: (nodes: any[], edges: any[], sessionId?: string) => Promise<any>;+ getNodeOutput: (nodeId: string, outputName?: string) => Promise<any>;++ // Trigger/Event Waiting+ cancelEventWait: (nodeId: string, waiterId?: string) => Promise<{ success: boolean; cancelled_count?: number }>;++ // Deployment Operations+ deployWorkflow: (workflowId: string, nodes: any[], edges: any[], sessionId?: string) => Promise<any>;+ cancelDeployment: (workflowId?: string) => Promise<any>;+ getDeploymentStatus: (workflowId?: string) => Promise<{ isRunning: boolean; activeRuns: number; settings?: any; workflow_id?: string }>;++ // AI Operations+ executeAiNode: (nodeId: string, nodeType: string, parameters: Record<string, any>, model: string) => Promise<any>;+ getAiModels: (provider: string, apiKey: string) => Promise<string[]>;++ // API Key Operations+ validateApiKey: (provider: string, apiKey: string) => Promise<{ valid: boolean; message?: string; models?: string[] }>;+ getStoredApiKey: (provider: string) => Promise<{ hasKey: boolean; apiKey?: string; models?: string[] }>;+ saveApiKey: (provider: string, apiKey: string, models?: string[]) => Promise<boolean>;+ deleteApiKey: (provider: string) => Promise<boolean>;++ // Android Operations+ getAndroidDevices: () => Promise<string[]>;+ executeAndroidAction: (serviceId: string, action: string, parameters: Record<string, any>, deviceId?: string) => Promise<any>;+ setupAndroidDevice: (connectionType: string, deviceId?: string, websocketUrl?: string) => Promise<any>;++ // Maps Operations+ validateMapsKey: (apiKey: string) => Promise<{ valid: boolean; message?: string }>;++ // WhatsApp Operations+ getWhatsAppStatus: () => Promise<{ connected: boolean; deviceId?: string; data?: any }>;+ getWhatsAppQR: () => Promise<{ connected: boolean; qr?: string; message?: string }>;+ sendWhatsAppMessage: (phone: string, message: string) => Promise<{ success: boolean; messageId?: string; error?: string }>;+ startWhatsAppConnection: () => Promise<{ success: boolean; message?: string }>;+ restartWhatsAppConnection: () => Promise<{ success: boolean; message?: string }>;+ getWhatsAppGroups: () => Promise<{ success: boolean; groups: Array<{ jid: string; name: string; topic?: string; size?: number }>; error?: string }>;+ getWhatsAppGroupInfo: (groupId: string) => Promise<{ success: boolean; participants: Array<{ phone: string; name: string; jid: string; is_admin?: boolean }>; name?: string; error?: string }>;+}++// Default values+const defaultAndroidStatus: AndroidStatus = {+ connected: false,+ paired: false,+ device_id: null,+ device_name: null,+ connected_devices: [],+ connection_type: null,+ qr_data: null,+ session_token: null+};++const defaultWorkflowStatus: WorkflowStatus = {+ executing: false,+ current_node: null+};++const defaultDeploymentStatus: DeploymentStatus = {+ isRunning: false,+ activeRuns: 0,+ status: 'idle'+};++const defaultWorkflowLock: WorkflowLock = {+ locked: false,+ workflow_id: null,+ locked_at: null,+ reason: null+};++const defaultWhatsAppStatus: WhatsAppStatus = {+ connected: false,+ has_session: false,+ running: false,+ pairing: false+};++const WebSocketContext = createContext<WebSocketContextValue | null>(null);++// WebSocket URL (convert http to ws)+const getWebSocketUrl = () => {+ const baseUrl = API_CONFIG.PYTHON_BASE_URL;++ // Production: empty base URL means use current origin+ if (!baseUrl) {+ const wsProtocol = window.location.protocol === 'https:' ? 'wss' : 'ws';+ return `${wsProtocol}://${window.location.host}/ws/status`;+ }++ // Development: convert http(s) to ws(s)+ const wsProtocol = baseUrl.startsWith('https') ? 'wss' : 'ws';+ const wsUrl = baseUrl.replace(/^https?/, wsProtocol);+ return `${wsUrl}/ws/status`;+};++// Max number of WhatsApp messages to keep in history+const MAX_WHATSAPP_MESSAGE_HISTORY = 100;++export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {+ // Get authentication state - only connect WebSocket when authenticated+ const { isAuthenticated, isLoading: authLoading } = useAuth();++ // Get current workflow ID for filtering node status updates (n8n pattern)+ const currentWorkflow = useAppStore(state => state.currentWorkflow);+ const currentWorkflowId = currentWorkflow?.id;++ const [isConnected, setIsConnected] = useState(false);+ const [reconnecting, setReconnecting] = useState(false);+ const [androidStatus, setAndroidStatus] = useState<AndroidStatus>(defaultAndroidStatus);+ const [whatsappStatus, setWhatsappStatus] = useState<WhatsAppStatus>(defaultWhatsAppStatus);+ const [whatsappMessages, setWhatsappMessages] = useState<WhatsAppMessage[]>([]);+ const [lastWhatsAppMessage, setLastWhatsAppMessage] = useState<WhatsAppMessage | null>(null);+ const [apiKeyStatuses, setApiKeyStatuses] = useState<Record<string, ApiKeyStatus>>({});+ // Per-workflow node statuses: workflow_id -> node_id -> NodeStatus (n8n pattern)+ const [allNodeStatuses, setAllNodeStatuses] = useState<Record<string, Record<string, NodeStatus>>>({});+ const [nodeParameters, setNodeParameters] = useState<Record<string, NodeParameters>>({});+ // Per-workflow variables: workflow_id -> variable_name -> value (n8n pattern)+ const [allVariables, setAllVariables] = useState<Record<string, Record<string, any>>>({});+ const [workflowStatus, setWorkflowStatus] = useState<WorkflowStatus>(defaultWorkflowStatus);+ const [deploymentStatus, setDeploymentStatus] = useState<DeploymentStatus>(defaultDeploymentStatus);+ const [workflowLock, setWorkflowLock] = useState<WorkflowLock>(defaultWorkflowLock);++ const wsRef = useRef<WebSocket | null>(null);+ const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);+ const pingIntervalRef = useRef<NodeJS.Timeout | null>(null);+ const pendingRequestsRef = useRef<Map<string, PendingRequest>>(new Map());+ // Ref for current workflow ID - allows message handler to access latest value+ // without recreating the WebSocket connection (n8n pattern)+ const currentWorkflowIdRef = useRef<string | undefined>(currentWorkflowId);++ // Keep the ref in sync with the state and clear node statuses on workflow switch (n8n pattern)+ useEffect(() => {+ const previousWorkflowId = currentWorkflowIdRef.current;+ currentWorkflowIdRef.current = currentWorkflowId;++ // No need to clear node statuses - they are now stored per-workflow (n8n pattern)+ // Each workflow's statuses are isolated in allNodeStatuses[workflow_id]+ if (previousWorkflowId && currentWorkflowId && previousWorkflowId !== currentWorkflowId) {++ // Fetch deployment status for the new workflow (n8n pattern)+ // This ensures the deploy button shows correct state when switching workflows+ if (wsRef.current?.readyState === WebSocket.OPEN) {+ const fetchDeploymentStatus = async () => {+ try {+ const requestId = generateRequestId();+ const response = await new Promise<any>((resolve, reject) => {+ const timeout = setTimeout(() => reject(new Error('Timeout')), 5000);++ const handler = (event: MessageEvent) => {+ try {+ const msg = JSON.parse(event.data);+ if (msg.request_id === requestId) {+ clearTimeout(timeout);+ wsRef.current?.removeEventListener('message', handler);+ resolve(msg);+ }+ } catch {}+ };++ wsRef.current?.addEventListener('message', handler);+ wsRef.current?.send(JSON.stringify({+ type: 'get_deployment_status',+ request_id: requestId,+ workflow_id: currentWorkflowId+ }));+ });++ // Update deployment status based on response+ const isRunning = response.is_running || false;+ setDeploymentStatus({+ isRunning,+ activeRuns: response.active_runs || 0,+ status: isRunning ? 'running' : 'idle',+ workflow_id: response.workflow_id || null+ });++ // Sync with Zustand store's per-workflow isExecuting state (n8n pattern)+ // This ensures Dashboard's isExecuting reflects the actual backend state+ const { setWorkflowExecuting } = useAppStore.getState();+ setWorkflowExecuting(currentWorkflowId, isRunning);++ // Also update workflow lock based on deployment status (n8n pattern)+ // A running workflow should be locked+ setWorkflowLock({+ locked: isRunning,+ workflow_id: isRunning ? currentWorkflowId : null,+ locked_at: isRunning ? Date.now() : null,+ reason: isRunning ? 'Workflow is running' : null+ });+ } catch (err) {+ console.error('[WebSocket] Failed to fetch deployment status:', err);+ }+ };+ fetchDeploymentStatus();+ }+ }+ }, [currentWorkflowId]);++ // Handle incoming messages+ const handleMessage = useCallback((event: MessageEvent) => {+ try {+ const message = JSON.parse(event.data);+ const { type, data, node_id, name, value, output, variables: varsUpdate, request_id } = message;++ // Handle request/response pattern - resolve pending requests+ if (request_id && pendingRequestsRef.current.has(request_id)) {+ const pending = pendingRequestsRef.current.get(request_id)!;+ if (pending.timeout) {+ clearTimeout(pending.timeout);+ }+ pendingRequestsRef.current.delete(request_id);+ pending.resolve(message);+ return; // Response handled, don't process as broadcast+ }++ switch (type) {+ case 'initial_status':+ case 'full_status':+ if (data) {+ if (data.android) setAndroidStatus(data.android);+ if (data.whatsapp) setWhatsappStatus(data.whatsapp);+ if (data.api_keys) setApiKeyStatuses(data.api_keys);+ // Node statuses from initial_status - group by workflow_id (n8n pattern)+ if (data.nodes) {+ const groupedStatuses: Record<string, Record<string, NodeStatus>> = {};+ for (const [nodeId, status] of Object.entries(data.nodes)) {+ const nodeStatus = status as NodeStatus;+ const wfId = nodeStatus?.workflow_id || 'unknown';+ if (!groupedStatuses[wfId]) groupedStatuses[wfId] = {};+ groupedStatuses[wfId][nodeId] = nodeStatus;+ }+ setAllNodeStatuses(prev => ({ ...prev, ...groupedStatuses }));+ }+ if (data.node_parameters) setNodeParameters(data.node_parameters);+ // Variables from initial_status - group by workflow_id (n8n pattern)+ if (data.variables) {+ // Variables may come with workflow_id or need grouping+ const groupedVars: Record<string, Record<string, any>> = {};+ for (const [varName, varData] of Object.entries(data.variables)) {+ const wfId = (varData as any)?.workflow_id || 'unknown';+ if (!groupedVars[wfId]) groupedVars[wfId] = {};+ groupedVars[wfId][varName] = varData;+ }+ setAllVariables(prev => ({ ...prev, ...groupedVars }));+ }+ if (data.workflow) setWorkflowStatus(data.workflow);+ if (data.workflow_lock) setWorkflowLock(data.workflow_lock);+ // Handle deployment status from initial_status (n8n/Conductor pattern)+ if (data.deployment) {+ setDeploymentStatus({+ isRunning: data.deployment.isRunning || false,+ activeRuns: data.deployment.activeRuns || 0,+ status: data.deployment.status || 'idle'+ });+ }+ }+ break;++ case 'api_key_status':+ if (message.provider) {+ setApiKeyStatuses(prev => ({+ ...prev,+ [message.provider]: data+ }));+ }+ break;++ case 'android_status':+ setAndroidStatus(data || defaultAndroidStatus);+ break;++ case 'whatsapp_status':+ setWhatsappStatus(data || defaultWhatsAppStatus);+ break;++ case 'whatsapp_message_received':+ // Handle incoming WhatsApp message from Go service+ if (data) {+ const message: WhatsAppMessage = {+ message_id: data.message_id || data.id || '',+ sender: data.sender || data.from || '',+ chat_id: data.chat_id || data.chat || '',+ type: data.type || 'text',+ text: data.text || data.message || data.body || '',+ timestamp: data.timestamp || Date.now(),+ is_group: data.is_group || data.isGroup || false,+ push_name: data.push_name || data.pushName || data.name,+ media_url: data.media_url || data.mediaUrl,+ media_data: data.media_data || data.mediaData,+ caption: data.caption,+ latitude: data.latitude,+ longitude: data.longitude,+ contact_name: data.contact_name || data.contactName,+ vcard: data.vcard+ };++ // Update last message+ setLastWhatsAppMessage(message);++ // Add to message history (newest first, limit size)+ setWhatsappMessages(prev => {+ const updated = [message, ...prev];+ return updated.slice(0, MAX_WHATSAPP_MESSAGE_HISTORY);+ });++ }+ break;++ case 'node_status':+ // Per-workflow node status storage (n8n pattern)+ // Store status under workflow_id -> node_id structure+ if (node_id) {+ const statusWorkflowId = message.workflow_id || 'unknown';+ setAllNodeStatuses((prev: Record<string, Record<string, NodeStatus>>) => ({+ ...prev,+ [statusWorkflowId]: {+ ...(prev[statusWorkflowId] || {}),+ [node_id]: { ...data, workflow_id: statusWorkflowId }+ }+ }));+ }+ break;++ case 'node_output':+ // Per-workflow node output storage (n8n pattern)+ if (node_id) {+ const outputWorkflowId = message.workflow_id || 'unknown';+ setAllNodeStatuses((prev: Record<string, Record<string, NodeStatus>>) => ({+ ...prev,+ [outputWorkflowId]: {+ ...(prev[outputWorkflowId] || {}),+ [node_id]: {+ ...(prev[outputWorkflowId]?.[node_id] || {}),+ output,+ workflow_id: outputWorkflowId+ }+ }+ }));+ }+ break;++ case 'node_status_cleared':+ // Handle broadcast from server when node status is cleared+ if (node_id || message.node_id) {+ const clearedNodeId = node_id || message.node_id;+ const clearWorkflowId = message.workflow_id;+ setAllNodeStatuses((prev: Record<string, Record<string, NodeStatus>>) => {+ // If workflow_id specified, only clear from that workflow+ if (clearWorkflowId && prev[clearWorkflowId]) {+ const workflowStatuses = { ...prev[clearWorkflowId] };+ delete workflowStatuses[clearedNodeId];+ return { ...prev, [clearWorkflowId]: workflowStatuses };+ }+ // Otherwise clear from all workflows+ const newStatuses: Record<string, Record<string, NodeStatus>> = {};+ for (const [wfId, nodes] of Object.entries(prev)) {+ const filteredNodes = { ...nodes };+ delete filteredNodes[clearedNodeId];+ newStatuses[wfId] = filteredNodes;+ }+ return newStatuses;+ });+ }+ break;++ // Node parameters broadcasts (from other clients)+ case 'node_parameters_updated':+ if (node_id) {+ setNodeParameters(prev => ({+ ...prev,+ [node_id]: {+ parameters: message.parameters,+ version: message.version,+ timestamp: message.timestamp+ }+ }));+ }+ break;++ case 'node_parameters_deleted':+ if (node_id) {+ setNodeParameters(prev => {+ const updated = { ...prev };+ delete updated[node_id];+ return updated;+ });+ }+ break;++ case 'variable_update':+ // Per-workflow variable storage (n8n pattern)+ if (name !== undefined) {+ const varWorkflowId = message.workflow_id || 'unknown';+ setAllVariables((prev: Record<string, Record<string, any>>) => ({+ ...prev,+ [varWorkflowId]: {+ ...(prev[varWorkflowId] || {}),+ [name]: value+ }+ }));+ }+ break;++ case 'variables_update':+ // Per-workflow batch variable update (n8n pattern)+ if (varsUpdate) {+ const batchWorkflowId = message.workflow_id || 'unknown';+ setAllVariables((prev: Record<string, Record<string, any>>) => ({+ ...prev,+ [batchWorkflowId]: {+ ...(prev[batchWorkflowId] || {}),+ ...varsUpdate+ }+ }));+ }+ break;++ case 'workflow_status':+ setWorkflowStatus(data || defaultWorkflowStatus);+ break;++ case 'deployment_status':+ // Handle deployment status updates (event-driven, no iterations)+ // Per-workflow scoping (n8n pattern): Only apply updates for current workflow+ if (message.status) {+ const deploymentWorkflowId = message.workflow_id;+ const activeWorkflowId = currentWorkflowIdRef.current;++ // Apply deployment update if:+ // 1. It's for the current workflow, OR+ // 2. It's a stop/cancel/error (affects any workflow that was running), OR+ // 3. No specific workflow context (backward compatibility)+ const isTerminalStatus = ['stopped', 'cancelled', 'error'].includes(message.status);+ const shouldApplyDeployment = !deploymentWorkflowId ||+ deploymentWorkflowId === activeWorkflowId ||+ isTerminalStatus;++ if (shouldApplyDeployment) {+ setDeploymentStatus(prev => {+ const newStatus: DeploymentStatus = { ...prev };+ // Capture workflow_id from message+ if (message.workflow_id) {+ newStatus.workflow_id = message.workflow_id;+ }++ switch (message.status) {+ case 'starting':+ newStatus.isRunning = true;+ newStatus.status = 'starting';+ newStatus.activeRuns = 0;+ break;+ case 'running':+ case 'started':+ newStatus.isRunning = true;+ newStatus.status = 'running';+ newStatus.activeRuns = message.data?.active_runs ?? prev.activeRuns;+ break;+ case 'run_started':+ newStatus.isRunning = true;+ newStatus.status = 'running';+ newStatus.activeRuns = message.data?.active_runs || prev.activeRuns + 1;+ break;+ case 'run_complete':+ newStatus.activeRuns = Math.max(0, message.data?.active_runs || prev.activeRuns - 1);+ break;+ case 'stopped':+ // Only clear if this was our workflow or no workflow was tracked+ if (!prev.workflow_id || prev.workflow_id === deploymentWorkflowId) {+ newStatus.isRunning = false;+ newStatus.status = 'stopped';+ newStatus.totalTime = message.data?.total_time;+ newStatus.activeRuns = 0;+ newStatus.workflow_id = null;+ }+ break;+ case 'cancelled':+ // Only clear if this was our workflow or no workflow was tracked+ if (!prev.workflow_id || prev.workflow_id === deploymentWorkflowId) {+ newStatus.isRunning = false;+ newStatus.status = 'cancelled';+ newStatus.activeRuns = 0;+ newStatus.workflow_id = null;+ }+ break;+ case 'error':+ // Only clear if this was our workflow or no workflow was tracked+ if (!prev.workflow_id || prev.workflow_id === deploymentWorkflowId) {+ newStatus.isRunning = false;+ newStatus.status = 'error';+ newStatus.error = message.error;+ newStatus.workflow_id = null;+ }+ break;+ }++ return newStatus;+ });+ // Sync with Zustand store's per-workflow isExecuting state (n8n pattern)+ if (deploymentWorkflowId) {+ const { setWorkflowExecuting } = useAppStore.getState();+ const isRunning = ['starting', 'running', 'started', 'run_started'].includes(message.status);+ const isStopped = ['stopped', 'cancelled', 'error'].includes(message.status);+ if (isRunning || isStopped) {+ setWorkflowExecuting(deploymentWorkflowId, isRunning);+ }+ }+ }+ }+ break;++ case 'pong':+ // Keep-alive response, no action needed+ break;++ case 'workflow_lock':+ // Handle workflow lock status updates (per-workflow locking - n8n pattern)+ // Only update lock state if it's for the current workflow or if unlocking+ if (data) {+ const lockWorkflowId = message.workflow_id || data.workflow_id;+ const activeWorkflowId = currentWorkflowIdRef.current;++ // Apply lock update if:+ // 1. It's for the current workflow, OR+ // 2. We're unlocking (locked=false), OR+ // 3. No specific workflow context (backward compatibility)+ const shouldApplyLock = !lockWorkflowId ||+ lockWorkflowId === activeWorkflowId ||+ !data.locked;++ if (shouldApplyLock) {+ setWorkflowLock({+ locked: data.locked || false,+ workflow_id: data.workflow_id || null,+ locked_at: data.locked_at || null,+ reason: data.reason || null+ });+ }+ }+ break;++ case 'error':+ console.error('[WebSocket] Server error:', message.code, message.message);+ break;++ default:+ break;+ }+ } catch (error) {+ console.error('[WebSocket] Failed to parse message:', error);+ }+ }, []); // Empty deps - uses ref for currentWorkflowId to avoid reconnecting WebSocket++ // Connect to WebSocket+ const connect = useCallback(() => {+ if (wsRef.current?.readyState === WebSocket.OPEN) {+ return;+ }++ const wsUrl = getWebSocketUrl();++ try {+ const ws = new WebSocket(wsUrl);++ ws.onopen = async () => {+ setIsConnected(true);+ setReconnecting(false);++ // Start ping interval+ pingIntervalRef.current = setInterval(() => {+ if (ws.readyState === WebSocket.OPEN) {+ ws.send(JSON.stringify({ type: 'ping' }));+ }+ }, 30000);++ // Load initial API key statuses for known providers+ const providers = ['openai', 'anthropic', 'gemini', 'google_maps', 'android_remote'];+ for (const provider of providers) {+ try {+ const response = await new Promise<any>((resolve, reject) => {+ const requestId = `init_${provider}_${Date.now()}`;+ const timeout = setTimeout(() => reject(new Error('Timeout')), 5000);++ const handler = (event: MessageEvent) => {+ try {+ const msg = JSON.parse(event.data);+ if (msg.request_id === requestId) {+ clearTimeout(timeout);+ ws.removeEventListener('message', handler);+ resolve(msg);+ }+ } catch {}+ };++ ws.addEventListener('message', handler);+ ws.send(JSON.stringify({ type: 'get_stored_api_key', provider, request_id: requestId }));+ });++ if (response.has_key) {+ setApiKeyStatuses(prev => ({+ ...prev,+ [provider]: { hasKey: true, valid: true }+ }));+ }+ } catch {+ // Ignore errors during initial check+ }+ }+ };++ ws.onmessage = handleMessage;++ ws.onclose = (event) => {+ console.log('[WebSocket] Disconnected:', event.code, event.reason);+ setIsConnected(false);+ wsRef.current = null;++ // Clear ping interval+ if (pingIntervalRef.current) {+ clearInterval(pingIntervalRef.current);+ pingIntervalRef.current = null;+ }++ // Reconnect after delay (unless intentional close)+ if (event.code !== 1000) {+ setReconnecting(true);+ reconnectTimeoutRef.current = setTimeout(() => {+ connect();+ }, 3000);+ }+ };++ ws.onerror = (error) => {+ console.error('[WebSocket] Error:', error);+ };++ wsRef.current = ws;+ } catch (error) {+ console.error('[WebSocket] Failed to create connection:', error);+ setReconnecting(true);+ reconnectTimeoutRef.current = setTimeout(connect, 3000);+ }+ }, [handleMessage]);++ // Request current status+ const requestStatus = useCallback(() => {+ if (wsRef.current?.readyState === WebSocket.OPEN) {+ wsRef.current.send(JSON.stringify({ type: 'get_status' }));+ }+ }, []);++ // Get node status for current workflow (n8n pattern)+ // IMPORTANT: Use currentWorkflowId state directly (not ref) to ensure reactivity on workflow switch+ const getNodeStatus = useCallback((nodeId: string) => {+ if (!currentWorkflowId) {+ return undefined;+ }+ return allNodeStatuses[currentWorkflowId]?.[nodeId];+ }, [allNodeStatuses, currentWorkflowId]);++ // Get API key status+ const getApiKeyStatus = useCallback((provider: string) => {+ return apiKeyStatuses[provider];+ }, [apiKeyStatuses]);++ // Get variable value for current workflow (n8n pattern)+ // IMPORTANT: Use currentWorkflowId state directly (not ref) to ensure reactivity on workflow switch+ const getVariable = useCallback((name: string) => {+ if (!currentWorkflowId) return undefined;+ return allVariables[currentWorkflowId]?.[name];+ }, [allVariables, currentWorkflowId]);++ // Clear node status (used when clearing execution results)+ // Also clears the backend node_outputs storage+ const clearNodeStatus = useCallback(async (nodeId: string) => {+ const workflowId = currentWorkflowIdRef.current;+ // Clear local state for current workflow+ setAllNodeStatuses((prev: Record<string, Record<string, NodeStatus>>) => {+ if (!workflowId || !prev[workflowId]) return prev;+ const workflowStatuses = { ...prev[workflowId] };+ delete workflowStatuses[nodeId];+ return { ...prev, [workflowId]: workflowStatuses };+ });+ // Clear backend storage+ try {+ if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {+ wsRef.current.send(JSON.stringify({+ type: 'clear_node_output',+ node_id: nodeId,+ workflow_id: workflowId+ }));+ }+ } catch (err) {+ console.error('[WebSocket] Failed to clear backend node output:', err);+ }+ }, []);++ // Clear WhatsApp message history+ const clearWhatsAppMessages = useCallback(() => {+ setWhatsappMessages([]);+ setLastWhatsAppMessage(null);+ }, []);++ // Derive current workflow's node statuses (n8n pattern)+ // This provides a flat Record<nodeId, NodeStatus> for the current workflow+ // IMPORTANT: Use currentWorkflowId state directly, not ref, to ensure re-render on workflow switch+ const nodeStatuses = useMemo(() => {+ if (!currentWorkflowId) return {};+ return allNodeStatuses[currentWorkflowId] || {};+ }, [allNodeStatuses, currentWorkflowId]);++ // Derive current workflow's variables (n8n pattern)+ // This provides a flat Record<varName, value> for the current workflow+ // IMPORTANT: Use currentWorkflowId state directly, not ref, to ensure re-render on workflow switch+ const variables = useMemo(() => {+ if (!currentWorkflowId) return {};+ return allVariables[currentWorkflowId] || {};+ }, [allVariables, currentWorkflowId]);++ // =========================================================================+ // Core Request/Response Pattern+ // =========================================================================++ // Send a request and wait for response+ // timeoutMs: undefined/0 = use default, negative = no timeout (for trigger nodes)+ const sendRequest = useCallback(async <T = any>(+ type: string,+ data?: Record<string, any>,+ timeoutMs?: number+ ): Promise<T> => {+ return new Promise((resolve, reject) => {+ if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {+ reject(new Error('WebSocket not connected'));+ return;+ }++ const requestId = generateRequestId();+ const useTimeout = timeoutMs === undefined || timeoutMs >= 0;+ const actualTimeout = timeoutMs && timeoutMs > 0 ? timeoutMs : REQUEST_TIMEOUT;++ let timeout: NodeJS.Timeout | null = null;+ if (useTimeout && timeoutMs !== -1) {+ timeout = setTimeout(() => {+ pendingRequestsRef.current.delete(requestId);+ reject(new Error(`Request timeout: ${type}`));+ }, actualTimeout);+ }++ pendingRequestsRef.current.set(requestId, { resolve, reject, timeout });++ wsRef.current.send(JSON.stringify({+ type,+ request_id: requestId,+ ...data+ }));+ });+ }, []);++ // =========================================================================+ // Node Parameters Operations+ // =========================================================================++ const getNodeParametersAsync = useCallback(async (nodeId: string): Promise<NodeParameters | null> => {+ try {+ const response = await sendRequest<any>('get_node_parameters', { node_id: nodeId });+ if (response.parameters) {+ const params: NodeParameters = {+ parameters: response.parameters,+ version: response.version || 0,+ timestamp: response.timestamp+ };+ // Update local cache+ setNodeParameters(prev => ({ ...prev, [nodeId]: params }));+ return params;+ }+ return null;+ } catch (error) {+ console.error('[WebSocket] Failed to get node parameters:', error);+ return null;+ }+ }, [sendRequest]);++ const getAllNodeParametersAsync = useCallback(async (nodeIds: string[]): Promise<Record<string, NodeParameters>> => {+ if (!nodeIds.length) return {};+ try {+ const response = await sendRequest<any>('get_all_node_parameters', { node_ids: nodeIds });+ const result: Record<string, NodeParameters> = {};++ if (response.parameters) {+ for (const [nodeId, data] of Object.entries(response.parameters as Record<string, any>)) {+ result[nodeId] = {+ parameters: data.parameters || {},+ version: data.version || 0,+ timestamp: response.timestamp+ };+ }+ // Update local cache with all parameters+ setNodeParameters(prev => ({ ...prev, ...result }));+ }+ return result;+ } catch (error) {+ console.error('[WebSocket] Failed to get all node parameters:', error);+ return {};+ }+ }, [sendRequest]);++ const saveNodeParametersAsync = useCallback(async (+ nodeId: string,+ parameters: Record<string, any>,+ version?: number+ ): Promise<boolean> => {+ try {+ const currentVersion = nodeParameters[nodeId]?.version || version || 0;+ const response = await sendRequest<any>('save_node_parameters', {+ node_id: nodeId,+ parameters,+ version: currentVersion+ });+ if (response.success !== false) {+ // Update local cache+ setNodeParameters(prev => ({+ ...prev,+ [nodeId]: {+ parameters: response.parameters || parameters,+ version: response.version || currentVersion + 1,+ timestamp: response.timestamp+ }+ }));+ return true;+ }+ return false;+ } catch (error) {+ console.error('[WebSocket] Failed to save node parameters:', error);+ return false;+ }+ }, [sendRequest, nodeParameters]);++ const deleteNodeParametersAsync = useCallback(async (nodeId: string): Promise<boolean> => {+ try {+ await sendRequest<any>('delete_node_parameters', { node_id: nodeId });+ setNodeParameters(prev => {+ const updated = { ...prev };+ delete updated[nodeId];+ return updated;+ });+ return true;+ } catch (error) {+ console.error('[WebSocket] Failed to delete node parameters:', error);+ return false;+ }+ }, [sendRequest]);++ // =========================================================================+ // Node Execution Operations+ // =========================================================================++ const executeNodeAsync = useCallback(async (+ nodeId: string,+ nodeType: string,+ parameters: Record<string, any>,+ nodes?: any[],+ edges?: any[]+ ): Promise<any> => {+ try {+ // Trigger nodes wait indefinitely for events - no timeout+ const isTriggerNode = TRIGGER_NODE_TYPES.includes(nodeType);+ const timeoutMs = isTriggerNode ? -1 : undefined; // -1 = no timeout++ const response = await sendRequest<any>('execute_node', {+ node_id: nodeId,+ node_type: nodeType,+ parameters,+ nodes,+ edges+ }, timeoutMs);+ return response;+ } catch (error) {+ console.error('[WebSocket] Failed to execute node:', error);+ throw error;+ }+ }, [sendRequest]);++ const getNodeOutputAsync = useCallback(async (+ nodeId: string,+ outputName?: string+ ): Promise<any> => {+ try {+ const response = await sendRequest<any>('get_node_output', {+ node_id: nodeId,+ output_name: outputName || 'output_0'+ });+ if (response.success) {+ return response.data;+ }+ return null;+ } catch (error) {+ console.error('[WebSocket] Failed to get node output:', error);+ return null;+ }+ }, [sendRequest]);++ // Cancel event wait (for trigger nodes)+ const cancelEventWaitAsync = useCallback(async (+ nodeId: string,+ waiterId?: string+ ): Promise<{ success: boolean; cancelled_count?: number }> => {+ try {+ const response = await sendRequest<{ success: boolean; cancelled_count?: number }>('cancel_event_wait', {+ node_id: nodeId,+ waiter_id: waiterId+ });+ return response;+ } catch (error) {+ console.error('[WebSocket] Failed to cancel event wait:', error);+ return { success: false };+ }+ }, [sendRequest]);++ const executeWorkflowAsync = useCallback(async (+ nodes: any[],+ edges: any[],+ sessionId?: string+ ): Promise<any> => {+ try {+ const response = await sendRequest<any>('execute_workflow', {+ nodes: nodes.map(node => ({+ id: node.id,+ type: node.type || '',+ data: node.data || {}+ })),+ edges: edges.map(edge => ({+ id: edge.id,+ source: edge.source,+ target: edge.target,+ sourceHandle: edge.sourceHandle || undefined,+ targetHandle: edge.targetHandle || undefined+ })),+ session_id: sessionId || 'default'+ });++ return response;+ } catch (error) {+ console.error('[WebSocket] Failed to execute workflow:', error);+ throw error;+ }+ }, [sendRequest]);++ // =========================================================================+ // Deployment Operations+ // =========================================================================++ const deployWorkflowAsync = useCallback(async (+ workflowId: string,+ nodes: any[],+ edges: any[],+ sessionId?: string+ ): Promise<any> => {+ try {+ const response = await sendRequest<any>('deploy_workflow', {+ workflow_id: workflowId,+ nodes: nodes.map(node => ({+ id: node.id,+ type: node.type || '',+ data: node.data || {}+ })),+ edges: edges.map(edge => ({+ id: edge.id,+ source: edge.source,+ target: edge.target,+ sourceHandle: edge.sourceHandle || undefined,+ targetHandle: edge.targetHandle || undefined+ })),+ session_id: sessionId || 'default'+ });++ return response;+ } catch (error) {+ console.error('[WebSocket] Failed to start deployment:', error);+ throw error;+ }+ }, [sendRequest]);++ const cancelDeploymentAsync = useCallback(async (workflowId?: string): Promise<any> => {+ try {+ const response = await sendRequest<any>('cancel_deployment', {+ workflow_id: workflowId+ });++ // Reset deployment status only if the cancelled workflow matches current+ if (!workflowId || workflowId === deploymentStatus.workflow_id) {+ setDeploymentStatus(defaultDeploymentStatus);+ }++ return response;+ } catch (error) {+ console.error('[WebSocket] Failed to cancel deployment:', error);+ throw error;+ }+ }, [sendRequest, deploymentStatus.workflow_id]);++ const getDeploymentStatusAsync = useCallback(async (workflowId?: string): Promise<{ isRunning: boolean; activeRuns: number; settings?: any; workflow_id?: string }> => {+ try {+ const response = await sendRequest<any>('get_deployment_status', { workflow_id: workflowId });+ return {+ isRunning: response.is_running || false,+ activeRuns: response.active_runs || 0,+ settings: response.settings,+ workflow_id: response.workflow_id+ };+ } catch (error) {+ console.error('[WebSocket] Failed to get deployment status:', error);+ return { isRunning: false, activeRuns: 0 };+ }+ }, [sendRequest]);++ // =========================================================================+ // AI Operations+ // =========================================================================++ const executeAiNodeAsync = useCallback(async (+ nodeId: string,+ nodeType: string,+ parameters: Record<string, any>,+ model: string+ ): Promise<any> => {+ try {+ const response = await sendRequest<any>('execute_ai_node', {+ node_id: nodeId,+ node_type: nodeType,+ parameters,+ model+ });+ return response;+ } catch (error) {+ console.error('[WebSocket] Failed to execute AI node:', error);+ throw error;+ }+ }, [sendRequest]);++ const getAiModelsAsync = useCallback(async (provider: string, apiKey: string): Promise<string[]> => {+ try {+ const response = await sendRequest<any>('get_ai_models', {+ provider,+ api_key: apiKey+ });+ return response.models || [];+ } catch (error) {+ console.error('[WebSocket] Failed to get AI models:', error);+ return [];+ }+ }, [sendRequest]);++ // =========================================================================+ // API Key Operations+ // =========================================================================++ const validateApiKeyAsync = useCallback(async (+ provider: string,+ apiKey: string+ ): Promise<{ valid: boolean; message?: string; models?: string[] }> => {+ try {+ const response = await sendRequest<any>('validate_api_key', {+ provider,+ api_key: apiKey+ });+ const result = {+ valid: response.valid || false,+ message: response.message,+ models: response.models+ };++ // Update apiKeyStatuses on successful validation+ if (result.valid) {+ setApiKeyStatuses(prev => ({+ ...prev,+ [provider]: { hasKey: true, valid: true, models: result.models }+ }));+ }++ return result;+ } catch (error) {+ console.error('[WebSocket] Failed to validate API key:', error);+ return { valid: false, message: 'Validation failed' };+ }+ }, [sendRequest]);++ const getStoredApiKeyAsync = useCallback(async (+ provider: string+ ): Promise<{ hasKey: boolean; apiKey?: string; models?: string[] }> => {+ try {+ const response = await sendRequest<any>('get_stored_api_key', { provider });+ const result = {+ hasKey: response.has_key || false,+ apiKey: response.api_key,+ models: response.models+ };++ // Update apiKeyStatuses with stored models+ if (result.hasKey) {+ setApiKeyStatuses(prev => ({+ ...prev,+ [provider]: { hasKey: true, valid: true, models: result.models }+ }));+ }++ return result;+ } catch (error) {+ console.error('[WebSocket] Failed to get stored API key:', error);+ return { hasKey: false };+ }+ }, [sendRequest]);++ const saveApiKeyAsync = useCallback(async (+ provider: string,+ apiKey: string,+ models?: string[]+ ): Promise<boolean> => {+ try {+ const response = await sendRequest<any>('save_api_key', {+ provider,+ api_key: apiKey,+ models+ });+ const success = response.success !== false;++ // Update apiKeyStatuses on successful save+ if (success) {+ setApiKeyStatuses(prev => ({+ ...prev,+ [provider]: { hasKey: true, valid: true, models }+ }));+ }++ return success;+ } catch (error) {+ console.error('[WebSocket] Failed to save API key:', error);+ return false;+ }+ }, [sendRequest]);++ const deleteApiKeyAsync = useCallback(async (provider: string): Promise<boolean> => {+ try {+ await sendRequest<any>('delete_api_key', { provider });++ // Remove from apiKeyStatuses on successful delete+ setApiKeyStatuses(prev => {+ const newStatuses = { ...prev };+ delete newStatuses[provider];+ return newStatuses;+ });++ return true;+ } catch (error) {+ console.error('[WebSocket] Failed to delete API key:', error);+ return false;+ }+ }, [sendRequest]);++ // =========================================================================+ // Android Operations+ // =========================================================================++ const getAndroidDevicesAsync = useCallback(async (): Promise<string[]> => {+ try {+ const response = await sendRequest<any>('get_android_devices', {});+ return response.devices || [];+ } catch (error) {+ console.error('[WebSocket] Failed to get Android devices:', error);+ return [];+ }+ }, [sendRequest]);++ const executeAndroidActionAsync = useCallback(async (+ serviceId: string,+ action: string,+ parameters: Record<string, any>,+ deviceId?: string+ ): Promise<any> => {+ try {+ const response = await sendRequest<any>('execute_android_action', {+ service_id: serviceId,+ action,+ parameters,+ device_id: deviceId+ });+ return response;+ } catch (error) {+ console.error('[WebSocket] Failed to execute Android action:', error);+ throw error;+ }+ }, [sendRequest]);++ const setupAndroidDeviceAsync = useCallback(async (+ connectionType: string,+ deviceId?: string,+ websocketUrl?: string+ ): Promise<any> => {+ try {+ const response = await sendRequest<any>('setup_android_device', {+ connection_type: connectionType,+ device_id: deviceId,+ websocket_url: websocketUrl+ });+ return response;+ } catch (error) {+ console.error('[WebSocket] Failed to setup Android device:', error);+ throw error;+ }+ }, [sendRequest]);++ // =========================================================================+ // Maps Operations+ // =========================================================================++ const validateMapsKeyAsync = useCallback(async (+ apiKey: string+ ): Promise<{ valid: boolean; message?: string }> => {+ try {+ const response = await sendRequest<any>('validate_maps_key', { api_key: apiKey });+ return {+ valid: response.valid || false,+ message: response.message+ };+ } catch (error) {+ console.error('[WebSocket] Failed to validate Maps key:', error);+ return { valid: false, message: 'Validation failed' };+ }+ }, [sendRequest]);++ // =========================================================================+ // WhatsApp Operations+ // =========================================================================++ const getWhatsAppStatusAsync = useCallback(async (): Promise<{ connected: boolean; deviceId?: string; data?: any }> => {+ try {+ const response = await sendRequest<any>('whatsapp_status', {});+ return {+ connected: response.connected || false,+ deviceId: response.device_id,+ data: response.data+ };+ } catch (error) {+ console.error('[WebSocket] Failed to get WhatsApp status:', error);+ return { connected: false };+ }+ }, [sendRequest]);++ const getWhatsAppQRAsync = useCallback(async (): Promise<{ connected: boolean; qr?: string; message?: string }> => {+ try {+ const response = await sendRequest<any>('whatsapp_qr', {});+ return {+ connected: response.connected || false,+ qr: response.qr,+ message: response.message+ };+ } catch (error) {+ console.error('[WebSocket] Failed to get WhatsApp QR:', error);+ return { connected: false, message: 'Failed to get QR code' };+ }+ }, [sendRequest]);++ const sendWhatsAppMessageAsync = useCallback(async (+ phone: string,+ message: string+ ): Promise<{ success: boolean; messageId?: string; error?: string }> => {+ try {+ const response = await sendRequest<any>('whatsapp_send', { phone, message });+ return {+ success: response.success || false,+ messageId: response.messageId,+ error: response.error+ };+ } catch (error: any) {+ console.error('[WebSocket] Failed to send WhatsApp message:', error);+ return { success: false, error: error.message || 'Send failed' };+ }+ }, [sendRequest]);++ const startWhatsAppConnectionAsync = useCallback(async (): Promise<{ success: boolean; message?: string }> => {+ try {+ const response = await sendRequest<any>('whatsapp_start', {});+ return {+ success: response.success !== false,+ message: response.message+ };+ } catch (error: any) {+ console.error('[WebSocket] Failed to start WhatsApp connection:', error);+ return { success: false, message: error.message || 'Failed to start' };+ }+ }, [sendRequest]);++ const restartWhatsAppConnectionAsync = useCallback(async (): Promise<{ success: boolean; message?: string }> => {+ try {+ const response = await sendRequest<any>('whatsapp_restart', {});+ return {+ success: response.success !== false,+ message: response.message+ };+ } catch (error: any) {+ console.error('[WebSocket] Failed to restart WhatsApp connection:', error);+ return { success: false, message: error.message || 'Failed to restart' };+ }+ }, [sendRequest]);++ const getWhatsAppGroupsAsync = useCallback(async (): Promise<{ success: boolean; groups: Array<{ jid: string; name: string; topic?: string; size?: number }>; error?: string }> => {+ try {+ const response = await sendRequest<any>('whatsapp_groups', {});+ return {+ success: response.success !== false,+ groups: response.groups || [],+ error: response.error+ };+ } catch (error: any) {+ console.error('[WebSocket] Failed to get WhatsApp groups:', error);+ return { success: false, groups: [], error: error.message || 'Failed to get groups' };+ }+ }, [sendRequest]);++ const getWhatsAppGroupInfoAsync = useCallback(async (groupId: string): Promise<{ success: boolean; participants: Array<{ phone: string; name: string; jid: string; is_admin?: boolean }>; name?: string; error?: string }> => {+ try {+ const response = await sendRequest<any>('whatsapp_group_info', { group_id: groupId });+ return {+ success: response.success !== false,+ participants: response.participants || [],+ name: response.name,+ error: response.error+ };+ } catch (error: any) {+ console.error('[WebSocket] Failed to get WhatsApp group info:', error);+ return { success: false, participants: [], error: error.message || 'Failed to get group info' };+ }+ }, [sendRequest]);++ // Track if component is mounted to prevent state updates after unmount+ const isMountedRef = useRef(true);++ // Connect only when authenticated (not during auth loading)+ useEffect(() => {+ isMountedRef.current = true;++ // Don't connect if still loading auth or not authenticated+ if (authLoading || !isAuthenticated) {+ // If we were connected and user logs out, disconnect+ if (wsRef.current) {+ if (wsRef.current.readyState === WebSocket.OPEN ||+ wsRef.current.readyState === WebSocket.CONNECTING) {+ wsRef.current.close(1000, 'User logged out');+ }+ wsRef.current = null;+ setIsConnected(false);+ }+ return;+ }++ // Small delay to avoid React Strict Mode double-connection issues+ const connectTimeout = setTimeout(() => {+ if (isMountedRef.current && isAuthenticated) {+ connect();+ }+ }, 100);++ return () => {+ isMountedRef.current = false;+ clearTimeout(connectTimeout);++ // Cleanup on unmount+ if (reconnectTimeoutRef.current) {+ clearTimeout(reconnectTimeoutRef.current);+ }+ if (pingIntervalRef.current) {+ clearInterval(pingIntervalRef.current);+ }+ if (wsRef.current) {+ // Only close if WebSocket is open or connecting+ if (wsRef.current.readyState === WebSocket.OPEN ||+ wsRef.current.readyState === WebSocket.CONNECTING) {+ wsRef.current.close(1000, 'Component unmounted');+ }+ }+ };+ }, [connect, isAuthenticated, authLoading]);++ const value: WebSocketContextValue = {+ // Connection state+ isConnected,+ reconnecting,++ // Status data+ androidStatus,+ whatsappStatus,+ whatsappMessages,+ lastWhatsAppMessage,+ apiKeyStatuses,+ nodeStatuses,+ nodeParameters,+ variables,+ workflowStatus,+ deploymentStatus,+ workflowLock,++ // Status getters+ getNodeStatus,+ getApiKeyStatus,+ getVariable,+ requestStatus,+ clearNodeStatus,+ clearWhatsAppMessages,++ // Generic request method+ sendRequest,++ // Node Parameters+ getNodeParameters: getNodeParametersAsync,+ getAllNodeParameters: getAllNodeParametersAsync,+ saveNodeParameters: saveNodeParametersAsync,+ deleteNodeParameters: deleteNodeParametersAsync,++ // Node Execution+ executeNode: executeNodeAsync,+ executeWorkflow: executeWorkflowAsync,+ getNodeOutput: getNodeOutputAsync,++ // Trigger/Event Waiting+ cancelEventWait: cancelEventWaitAsync,++ // Deployment Operations+ deployWorkflow: deployWorkflowAsync,+ cancelDeployment: cancelDeploymentAsync,+ getDeploymentStatus: getDeploymentStatusAsync,++ // AI Operations+ executeAiNode: executeAiNodeAsync,+ getAiModels: getAiModelsAsync,++ // API Key Operations+ validateApiKey: validateApiKeyAsync,+ getStoredApiKey: getStoredApiKeyAsync,+ saveApiKey: saveApiKeyAsync,+ deleteApiKey: deleteApiKeyAsync,++ // Android Operations+ getAndroidDevices: getAndroidDevicesAsync,+ executeAndroidAction: executeAndroidActionAsync,+ setupAndroidDevice: setupAndroidDeviceAsync,++ // Maps Operations+ validateMapsKey: validateMapsKeyAsync,++ // WhatsApp Operations+ getWhatsAppStatus: getWhatsAppStatusAsync,+ getWhatsAppQR: getWhatsAppQRAsync,+ sendWhatsAppMessage: sendWhatsAppMessageAsync,+ startWhatsAppConnection: startWhatsAppConnectionAsync,+ restartWhatsAppConnection: restartWhatsAppConnectionAsync,+ getWhatsAppGroups: getWhatsAppGroupsAsync,+ getWhatsAppGroupInfo: getWhatsAppGroupInfoAsync+ };++ return (+ <WebSocketContext.Provider value={value}>+ {children}+ </WebSocketContext.Provider>+ );+};++// Hook to use WebSocket context+export const useWebSocket = (): WebSocketContextValue => {+ const context = useContext(WebSocketContext);+ if (!context) {+ throw new Error('useWebSocket must be used within a WebSocketProvider');+ }+ return context;+};++// Hook specifically for Android status+export const useAndroidStatus = (): AndroidStatus & { isConnected: boolean } => {+ const { androidStatus, isConnected } = useWebSocket();+ return {+ ...androidStatus,+ isConnected+ };+};++// Hook specifically for node status+export const useNodeStatus = (nodeId: string): NodeStatus | undefined => {+ const { getNodeStatus } = useWebSocket();+ return getNodeStatus(nodeId);+};++// Hook specifically for workflow status+export const useWorkflowStatus = (): WorkflowStatus => {+ const { workflowStatus } = useWebSocket();+ return workflowStatus;+};++// Hook specifically for API key status+export const useApiKeyStatus = (provider: string): ApiKeyStatus | undefined => {+ const { getApiKeyStatus } = useWebSocket();+ return getApiKeyStatus(provider);+};++// Hook specifically for WhatsApp status+export const useWhatsAppStatus = (): WhatsAppStatus => {+ const { whatsappStatus } = useWebSocket();+ return whatsappStatus;+};++// Hook specifically for deployment status+export const useDeploymentStatus = (): DeploymentStatus => {+ const { deploymentStatus } = useWebSocket();+ return deploymentStatus;+};++// Hook specifically for workflow lock status+export const useWorkflowLock = (): WorkflowLock => {+ const { workflowLock } = useWebSocket();+ return workflowLock;+};++// Hook specifically for WhatsApp messages (for trigger nodes)+export const useWhatsAppMessages = (): {+ messages: WhatsAppMessage[];+ lastMessage: WhatsAppMessage | null;+ clearMessages: () => void;+} => {+ const { whatsappMessages, lastWhatsAppMessage, clearWhatsAppMessages } = useWebSocket();+ return {+ messages: whatsappMessages,+ lastMessage: lastWhatsAppMessage,+ clearMessages: clearWhatsAppMessages+ };+};++export default WebSocketContext;diff --git a/client/src/factories/baseChatModelFactory.ts b/client/src/factories/baseChatModelFactory.tsnew file mode 100644index 00000000..457d3cdb--- /dev/null+++ b/client/src/factories/baseChatModelFactory.ts@@ -0,0 +1,195 @@+// Base Chat Model Factory - Standardized node definition generator+import {+ INodeTypeDescription,+ NodeConnectionType,+ INodeProperties+} from '../types/INodeProperties';++// ============================================================================+// BASE CHAT MODEL CONFIGURATION INTERFACE+// ============================================================================++export interface ChatModelConfig {+ providerId: string;+ displayName: string;+ icon: string;+ color: string;+ description: string;+ nodeName?: string;+ models: Array<{+ name: string;+ value: string;+ maxTokens?: number;+ }>;+ parameters: INodeProperties[];+}++// ============================================================================+// BASE CHAT MODEL FACTORY FUNCTION+// ============================================================================++export function createBaseChatModel(config: ChatModelConfig): INodeTypeDescription {+ return {+ displayName: `${config.displayName} Chat Model`,+ name: config.nodeName || `${config.providerId}ChatModel`,+ icon: config.icon,+ group: ['ai', 'model'],+ version: 1,+ subtitle: '={{$parameter["model"]}}',+ description: config.description,+ defaults: {+ name: `${config.displayName} Chat Model`,+ color: config.color+ },+ inputs: [{+ name: 'prompt',+ displayName: 'Prompt',+ type: 'string' as NodeConnectionType,+ description: 'Input prompt or message for the AI model',+ required: false+ }],+ outputs: [{+ name: 'model',+ displayName: 'Model',+ type: 'ai' as NodeConnectionType,+ description: `${config.displayName} configuration for AI agents`,+ dataStructure: {+ properties: {+ provider: {+ type: 'string',+ description: `Model provider (${config.providerId})`,+ required: true+ },+ model: {+ type: 'string',+ description: 'Model name',+ required: true+ },+ apiKey: {+ type: 'string',+ description: `${config.displayName} API key`,+ required: true+ },+ temperature: {+ type: 'number',+ description: 'Sampling temperature'+ },+ maxTokens: {+ type: 'number',+ description: 'Maximum response tokens'+ },+ topP: {+ type: 'number',+ description: 'Top-p sampling parameter'+ }+ }+ }+ }],+ properties: [+ {+ displayName: 'Model',+ name: 'model',+ type: 'string',+ default: '',+ required: true,+ placeholder: `Select a ${config.displayName} model...`,+ description: `${config.displayName} model to use (configure API key in Credentials)`,+ typeOptions: {+ dynamicOptions: true+ }+ },+ {+ displayName: 'Prompt',+ name: 'prompt',+ type: 'string',+ default: '{{ $json.message }}',+ required: true,+ typeOptions: {+ rows: 4+ },+ description: 'The message to send to the AI model',+ placeholder: 'Enter your prompt or use template variables...'+ },+ {+ displayName: 'Options',+ name: 'options',+ type: 'collection',+ placeholder: 'Add Option',+ default: {},+ options: [+ {+ displayName: 'System Message',+ name: 'systemMessage',+ type: 'string',+ default: '',+ typeOptions: {+ rows: 3+ },+ description: 'System message to define AI behavior and personality'+ },+ ...config.parameters+ ] as any+ }+ ]+ };+}++// ============================================================================+// STANDARD PARAMETER SETS+// ============================================================================++export const STANDARD_PARAMETERS = {+ temperature: {+ displayName: 'Temperature',+ name: 'temperature',+ type: 'number' as const,+ default: 0.7,+ typeOptions: { minValue: 0, maxValue: 2, numberStepSize: 0.1 },+ description: 'Controls randomness in responses'+ },++ maxTokens: {+ displayName: 'Maximum Tokens',+ name: 'maxTokens',+ type: 'number' as const,+ default: 1000,+ typeOptions: { minValue: 1, maxValue: 8192 },+ description: 'Maximum number of tokens to generate'+ },++ topP: {+ displayName: 'Top P',+ name: 'topP',+ type: 'number' as const,+ default: 1,+ typeOptions: { minValue: 0, maxValue: 1, numberStepSize: 0.1 },+ description: 'Controls diversity via nucleus sampling'+ },++ topK: {+ displayName: 'Top K',+ name: 'topK',+ type: 'number' as const,+ default: 40,+ typeOptions: { minValue: 1, maxValue: 100 },+ description: 'Limits token selection to top K candidates'+ },++ frequencyPenalty: {+ displayName: 'Frequency Penalty',+ name: 'frequencyPenalty',+ type: 'number' as const,+ default: 0,+ typeOptions: { minValue: -2, maxValue: 2, numberStepSize: 0.1 },+ description: 'Penalty for frequency of token usage'+ },++ presencePenalty: {+ displayName: 'Presence Penalty',+ name: 'presencePenalty',+ type: 'number' as const,+ default: 0,+ typeOptions: { minValue: -2, maxValue: 2, numberStepSize: 0.1 },+ description: 'Penalty for presence of tokens'+ }+};\ No newline at end of filediff --git a/client/src/hooks/useAndroidOperations.ts b/client/src/hooks/useAndroidOperations.tsnew file mode 100644index 00000000..c9cd99b1--- /dev/null+++ b/client/src/hooks/useAndroidOperations.ts@@ -0,0 +1,164 @@+/**+ * useAndroidOperations Hook - WebSocket-based Android device operations+ *+ * Provides Android device management and service execution via WebSocket.+ * This replaces REST-based Android API calls for real-time operations.+ */++import { useCallback, useState } from 'react';+import { useWebSocket } from '../contexts/WebSocketContext';++export interface AndroidDevice {+ id: string;+ model?: string;+ state?: string;+}++export interface AndroidActionResult {+ success: boolean;+ result?: any;+ error?: string;+}++export interface UseAndroidOperationsResult {+ // Get list of connected devices+ getDevices: () => Promise<AndroidDevice[]>;++ // Setup Android device connection+ setupDevice: (+ connectionType: 'local' | 'remote',+ deviceId?: string,+ websocketUrl?: string,+ port?: number+ ) => Promise<AndroidActionResult>;++ // Execute Android service action+ executeAction: (+ serviceId: string,+ action: string,+ parameters: Record<string, any>,+ deviceId?: string+ ) => Promise<AndroidActionResult>;++ // State+ isExecuting: boolean;+ lastError: string | null;+ isConnected: boolean;++ // Android status from WebSocket+ androidStatus: {+ connected: boolean;+ device_id: string | null;+ connected_devices: string[];+ connection_type: string | null;+ };+}++export const useAndroidOperations = (): UseAndroidOperationsResult => {+ const {+ getAndroidDevices: wsGetDevices,+ setupAndroidDevice: wsSetupDevice,+ executeAndroidAction: wsExecuteAction,+ androidStatus,+ isConnected+ } = useWebSocket();++ const [isExecuting, setIsExecuting] = useState(false);+ const [lastError, setLastError] = useState<string | null>(null);++ /**+ * Get list of connected Android devices+ */+ const getDevices = useCallback(async (): Promise<AndroidDevice[]> => {+ try {+ const devices = await wsGetDevices();+ return devices.map((id: string) => ({ id }));+ } catch (error: any) {+ console.warn('Failed to get Android devices:', error);+ setLastError(error.message);+ return [];+ }+ }, [wsGetDevices]);++ /**+ * Setup Android device connection+ */+ const setupDevice = useCallback(async (+ connectionType: 'local' | 'remote',+ deviceId?: string,+ websocketUrl?: string,+ _port: number = 8888 // Port passed to backend via wsSetupDevice+ ): Promise<AndroidActionResult> => {+ setIsExecuting(true);+ setLastError(null);++ try {+ const result = await wsSetupDevice(connectionType, deviceId, websocketUrl);++ if (!result.success) {+ setLastError(result.error || 'Setup failed');+ }++ return {+ success: result.success,+ result: result.result,+ error: result.error+ };+ } catch (error: any) {+ const errorMsg = error.message || 'Device setup failed';+ setLastError(errorMsg);+ return {+ success: false,+ error: errorMsg+ };+ } finally {+ setIsExecuting(false);+ }+ }, [wsSetupDevice]);++ /**+ * Execute Android service action+ */+ const executeAction = useCallback(async (+ serviceId: string,+ action: string,+ parameters: Record<string, any>,+ deviceId?: string+ ): Promise<AndroidActionResult> => {+ setIsExecuting(true);+ setLastError(null);++ try {+ const result = await wsExecuteAction(serviceId, action, parameters, deviceId);++ if (!result.success) {+ setLastError(result.error || 'Action failed');+ }++ return {+ success: result.success,+ result: result.result,+ error: result.error+ };+ } catch (error: any) {+ const errorMsg = error.message || 'Action execution failed';+ setLastError(errorMsg);+ return {+ success: false,+ error: errorMsg+ };+ } finally {+ setIsExecuting(false);+ }+ }, [wsExecuteAction]);++ return {+ getDevices,+ setupDevice,+ executeAction,+ isExecuting,+ lastError,+ isConnected,+ androidStatus+ };+};diff --git a/client/src/hooks/useApiKeyValidation.ts b/client/src/hooks/useApiKeyValidation.tsnew file mode 100644index 00000000..175454ba--- /dev/null+++ b/client/src/hooks/useApiKeyValidation.ts@@ -0,0 +1,107 @@+import { useState, useEffect, useCallback } from 'react';+import { notification } from 'antd';+import { useApiKeys } from './useApiKeys';++export type ValidationStatus = 'idle' | 'validating' | 'valid' | 'invalid';++interface UseApiKeyValidationProps {+ provider?: string;+ onSuccess?: (models: string[]) => void;+}++export const useApiKeyValidation = ({ provider, onSuccess }: UseApiKeyValidationProps) => {+ const [status, setStatus] = useState<ValidationStatus>('idle');+ const [hasStoredKeyState, setHasStoredKeyState] = useState(false);++ // Use WebSocket-based API key management+ const {+ validateApiKey: wsValidateApiKey,+ getStoredApiKey: wsGetStoredApiKey,+ hasStoredKey: wsHasStoredKey,+ removeApiKey: wsRemoveApiKey,+ getStoredModels: wsGetStoredModels+ } = useApiKeys();++ // Check for existing key on mount+ useEffect(() => {+ if (!provider) return;++ const checkStoredKey = async () => {+ try {+ const hasKey = await wsHasStoredKey(provider);+ if (hasKey) {+ setHasStoredKeyState(true);+ setStatus('valid');++ // Try to get models if there's a stored key+ const models = await wsGetStoredModels(provider);+ if (models?.length && onSuccess) {+ onSuccess(models);+ }+ }+ } catch (error) {+ console.warn('Error checking stored key:', error);+ }+ };++ checkStoredKey();+ }, [provider, onSuccess, wsHasStoredKey, wsGetStoredModels]);++ const validate = useCallback(async (apiKey: string) => {+ if (!provider || !apiKey.trim()) {+ notification.error({ message: 'Please enter an API key' });+ return;+ }++ setStatus('validating');++ try {+ const result = await wsValidateApiKey(provider, apiKey.trim());++ if (result.isValid) {+ setStatus('valid');+ setHasStoredKeyState(true);+ notification.success({ message: 'API key validated successfully!' });++ if (result.models?.length && onSuccess) {+ onSuccess(result.models);+ }+ } else {+ setStatus('invalid');+ notification.error({ message: result.error || 'Invalid API key' });+ }+ } catch (error: any) {+ setStatus('invalid');+ notification.error({ message: error.message || 'Validation failed' });+ }+ }, [provider, onSuccess, wsValidateApiKey]);++ const clear = useCallback(async () => {+ if (!provider) return;++ try {+ await wsRemoveApiKey(provider);+ setHasStoredKeyState(false);+ setStatus('idle');+ notification.success({ message: 'API key cleared' });+ } catch (error) {+ notification.error({ message: 'Failed to clear API key' });+ }+ }, [provider, wsRemoveApiKey]);++ const getStoredKey = useCallback(async () => {+ if (!provider) return null;+ return await wsGetStoredApiKey(provider);+ }, [provider, wsGetStoredApiKey]);++ return {+ status,+ hasStoredKey: hasStoredKeyState,+ validate,+ clear,+ getStoredKey,+ isValidating: status === 'validating',+ isValid: status === 'valid',+ isInvalid: status === 'invalid'+ };+};\ No newline at end of filediff --git a/client/src/hooks/useApiKeys.ts b/client/src/hooks/useApiKeys.tsnew file mode 100644index 00000000..897cfa36--- /dev/null+++ b/client/src/hooks/useApiKeys.ts@@ -0,0 +1,238 @@+/**+ * useApiKeys Hook - WebSocket-based API key management+ *+ * Provides API key validation, storage, and retrieval via WebSocket.+ * This replaces the REST-based ApiKeyManagerService for real-time operations.+ */++import { useCallback, useState } from 'react';+import { useWebSocket } from '../contexts/WebSocketContext';++export interface ApiKeyValidationResult {+ isValid: boolean;+ error?: string;+ models?: string[];+}++export interface UseApiKeysResult {+ // Validate and store API key+ validateApiKey: (provider: string, apiKey: string) => Promise<ApiKeyValidationResult>;++ // Save API key without validation+ saveApiKey: (provider: string, apiKey: string) => Promise<ApiKeyValidationResult>;++ // Get stored API key+ getStoredApiKey: (provider: string) => Promise<string | null>;++ // Check if API key exists+ hasStoredKey: (provider: string) => Promise<boolean>;++ // Get stored models for a provider+ getStoredModels: (provider: string) => Promise<string[] | null>;++ // Remove stored API key+ removeApiKey: (provider: string) => Promise<void>;++ // Validate Google Maps API key+ validateGoogleMapsKey: (apiKey: string) => Promise<ApiKeyValidationResult>;++ // Get AI models for a provider+ getAiModels: (provider: string, apiKey: string) => Promise<string[]>;++ // State+ isValidating: boolean;+ validationError: string | null;+ isConnected: boolean;+}++export const useApiKeys = (): UseApiKeysResult => {+ const {+ validateApiKey: wsValidateApiKey,+ getStoredApiKey: wsGetStoredApiKey,+ saveApiKey: wsSaveApiKey,+ deleteApiKey: wsDeleteApiKey,+ validateMapsKey: wsValidateMapsKey,+ getAiModels: wsGetAiModels,+ isConnected+ } = useWebSocket();++ const [isValidating, setIsValidating] = useState(false);+ const [validationError, setValidationError] = useState<string | null>(null);++ /**+ * Validate API key and store if valid+ */+ const validateApiKey = useCallback(async (+ provider: string,+ apiKey: string+ ): Promise<ApiKeyValidationResult> => {+ setIsValidating(true);+ setValidationError(null);++ try {+ const result = await wsValidateApiKey(provider, apiKey);++ if (!result.valid) {+ setValidationError(result.message || 'Validation failed');+ }++ return {+ isValid: result.valid,+ error: result.message,+ models: result.models+ };+ } catch (error: any) {+ const errorMsg = error.message || 'Validation failed';+ setValidationError(errorMsg);+ return {+ isValid: false,+ error: errorMsg+ };+ } finally {+ setIsValidating(false);+ }+ }, [wsValidateApiKey]);++ /**+ * Save API key without validation (for keys that can't be validated beforehand)+ */+ const saveApiKey = useCallback(async (+ provider: string,+ apiKey: string+ ): Promise<ApiKeyValidationResult> => {+ try {+ const success = await wsSaveApiKey(provider, apiKey);+ return {+ isValid: success,+ error: success ? undefined : 'Failed to save API key'+ };+ } catch (error: any) {+ return {+ isValid: false,+ error: error.message || 'Failed to save API key'+ };+ }+ }, [wsSaveApiKey]);++ /**+ * Get stored API key for a provider+ */+ const getStoredApiKey = useCallback(async (+ provider: string+ ): Promise<string | null> => {+ try {+ const result = await wsGetStoredApiKey(provider);+ return result.hasKey ? (result.apiKey || null) : null;+ } catch (error) {+ console.warn(`Error retrieving API key for ${provider}:`, error);+ return null;+ }+ }, [wsGetStoredApiKey]);++ /**+ * Check if a stored key exists for a provider+ */+ const hasStoredKey = useCallback(async (+ provider: string+ ): Promise<boolean> => {+ try {+ const result = await wsGetStoredApiKey(provider);+ return result.hasKey;+ } catch (error) {+ return false;+ }+ }, [wsGetStoredApiKey]);++ /**+ * Get stored models for a provider+ */+ const getStoredModels = useCallback(async (+ provider: string+ ): Promise<string[] | null> => {+ try {+ // Get models directly from stored API key response (includes models from DB)+ const result = await wsGetStoredApiKey(provider);+ if (result.hasKey && result.models && result.models.length > 0) {+ return result.models;+ }+ return null;+ } catch (error) {+ console.warn(`Error retrieving models for ${provider}:`, error);+ return null;+ }+ }, [wsGetStoredApiKey]);++ /**+ * Remove stored API key+ */+ const removeApiKey = useCallback(async (+ provider: string+ ): Promise<void> => {+ try {+ await wsDeleteApiKey(provider);+ } catch (error) {+ console.warn(`Error removing API key for ${provider}:`, error);+ }+ }, [wsDeleteApiKey]);++ /**+ * Validate Google Maps API key+ */+ const validateGoogleMapsKey = useCallback(async (+ apiKey: string+ ): Promise<ApiKeyValidationResult> => {+ setIsValidating(true);+ setValidationError(null);++ try {+ const result = await wsValidateMapsKey(apiKey);++ if (!result.valid) {+ setValidationError(result.message || 'Validation failed');+ }++ return {+ isValid: result.valid,+ error: result.message+ };+ } catch (error: any) {+ const errorMsg = error.message || 'Validation failed';+ setValidationError(errorMsg);+ return {+ isValid: false,+ error: errorMsg+ };+ } finally {+ setIsValidating(false);+ }+ }, [wsValidateMapsKey]);++ /**+ * Get available AI models for a provider+ */+ const getAiModels = useCallback(async (+ provider: string,+ apiKey: string+ ): Promise<string[]> => {+ try {+ return await wsGetAiModels(provider, apiKey);+ } catch (error) {+ console.warn(`Error fetching AI models for ${provider}:`, error);+ return [];+ }+ }, [wsGetAiModels]);++ return {+ validateApiKey,+ saveApiKey,+ getStoredApiKey,+ hasStoredKey,+ getStoredModels,+ removeApiKey,+ validateGoogleMapsKey,+ getAiModels,+ isValidating,+ validationError,+ isConnected+ };+};diff --git a/client/src/hooks/useAppTheme.ts b/client/src/hooks/useAppTheme.tsnew file mode 100644index 00000000..c3a354ec--- /dev/null+++ b/client/src/hooks/useAppTheme.ts@@ -0,0 +1,17 @@+import { useMemo } from 'react';+import { useTheme } from '../contexts/ThemeContext';+import { theme as baseTheme, lightColors, darkColors } from '../styles/theme';++export const useAppTheme = () => {+ const { isDarkMode } = useTheme();++ const dynamicTheme = useMemo(() => {+ return {+ ...baseTheme,+ colors: isDarkMode ? darkColors : lightColors,+ isDarkMode,+ };+ }, [isDarkMode]);++ return dynamicTheme;+};diff --git a/client/src/hooks/useComponentPalette.ts b/client/src/hooks/useComponentPalette.tsnew file mode 100644index 00000000..979fe322--- /dev/null+++ b/client/src/hooks/useComponentPalette.ts@@ -0,0 +1,51 @@+import { useState, useCallback, useEffect } from 'react';+import { nodeDefinitions } from '../nodeDefinitions';++const STORAGE_KEY = 'component_palette_collapsed_sections';++export const useComponentPalette = () => {+ const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>(() => {+ // Try to load from localStorage first+ try {+ const saved = localStorage.getItem(STORAGE_KEY);+ if (saved) {+ return JSON.parse(saved);+ }+ } catch {+ // Ignore parsing errors+ }++ // Default: all sections collapsed+ const initialCollapsed: Record<string, boolean> = {};+ const categories = new Set(Object.values(nodeDefinitions).flatMap(def => def.group || []));+ categories.forEach(category => {+ initialCollapsed[category] = true;+ });+ return initialCollapsed;+ });++ const [searchQuery, setSearchQuery] = useState<string>('');++ // Persist collapsed sections to localStorage+ useEffect(() => {+ try {+ localStorage.setItem(STORAGE_KEY, JSON.stringify(collapsedSections));+ } catch {+ // Ignore storage errors+ }+ }, [collapsedSections]);++ const toggleSection = useCallback((sectionId: string) => {+ setCollapsedSections(prev => ({+ ...prev,+ [sectionId]: !prev[sectionId]+ }));+ }, []);++ return {+ collapsedSections,+ searchQuery,+ setSearchQuery,+ toggleSection,+ };+};\ No newline at end of filediff --git a/client/src/hooks/useCopyPaste.ts b/client/src/hooks/useCopyPaste.tsnew file mode 100644index 00000000..c9418e98--- /dev/null+++ b/client/src/hooks/useCopyPaste.ts@@ -0,0 +1,155 @@+import { useCallback, useRef } from 'react';+import { Node, Edge } from 'reactflow';+import { generateUniqueLabel } from './useDragAndDrop';+import { nodeDefinitions } from '../nodeDefinitions';++interface UseCopyPasteProps {+ nodes: Node[];+ edges: Edge[];+ setNodes: (nodes: Node[] | ((nodes: Node[]) => Node[])) => void;+ setEdges: (edges: Edge[] | ((edges: Edge[]) => Edge[])) => void;+ saveNodeParameters?: (nodeId: string, parameters: Record<string, any>) => Promise<boolean>;+}++interface ClipboardData {+ nodes: Node[];+ edges: Edge[];+}++/**+ * Hook for copy/paste functionality with n8n-style auto-labeling.+ *+ * Features:+ * - Copy selected nodes and their connecting edges+ * - Paste with offset position and unique labels+ * - Persist node parameters to database+ */+export const useCopyPaste = ({+ nodes,+ edges,+ setNodes,+ setEdges,+ saveNodeParameters+}: UseCopyPasteProps) => {+ // In-memory clipboard (simpler than browser clipboard API)+ const clipboardRef = useRef<ClipboardData | null>(null);++ /**+ * Copy selected nodes and their connecting edges to clipboard.+ */+ const copySelectedNodes = useCallback(() => {+ const selectedNodes = nodes.filter(n => n.selected);+ if (selectedNodes.length === 0) {+ console.log('[CopyPaste] No nodes selected to copy');+ return;+ }++ // Get edges that connect selected nodes (both ends must be selected)+ const selectedNodeIds = new Set(selectedNodes.map(n => n.id));+ const selectedEdges = edges.filter(+ e => selectedNodeIds.has(e.source) && selectedNodeIds.has(e.target)+ );++ clipboardRef.current = {+ nodes: selectedNodes,+ edges: selectedEdges,+ };++ console.log(`[CopyPaste] Copied ${selectedNodes.length} nodes and ${selectedEdges.length} edges`);+ }, [nodes, edges]);++ /**+ * Paste nodes from clipboard with offset and unique labels.+ */+ const pasteNodes = useCallback(async () => {+ if (!clipboardRef.current) {+ console.log('[CopyPaste] Nothing in clipboard to paste');+ return;+ }++ const { nodes: copiedNodes, edges: copiedEdges } = clipboardRef.current;++ // Generate ID mapping (old ID -> new ID)+ const idMap = new Map<string, string>();+ const now = Date.now();++ copiedNodes.forEach((node, index) => {+ // Use timestamp + index to ensure unique IDs+ idMap.set(node.id, `${node.type}-${now + index}`);+ });++ // Offset for pasted nodes to avoid stacking on original+ const PASTE_OFFSET = 50;++ // Create new nodes with offset, new IDs, and unique labels+ const newNodes: Node[] = [];++ for (let i = 0; i < copiedNodes.length; i++) {+ const node = copiedNodes[i];+ const newId = idMap.get(node.id)!;++ // Always use the original display name from node definition as base+ // This ensures "WhatsApp Receive 2" copies become "WhatsApp Receive 3", not "WhatsApp Receive 2 1"+ const baseDisplayName = nodeDefinitions[node.type!]?.displayName || node.type!;++ // Generate unique label considering existing nodes AND nodes we're about to add+ const allNodes = [...nodes, ...newNodes];+ const uniqueLabel = generateUniqueLabel(baseDisplayName, node.type!, allNodes);++ const newNode: Node = {+ ...node,+ id: newId,+ position: {+ x: node.position.x + PASTE_OFFSET,+ y: node.position.y + PASTE_OFFSET,+ },+ selected: true,+ data: {+ ...node.data,+ label: uniqueLabel,+ },+ };++ // Save parameters for new node to database+ if (saveNodeParameters && newNode.data) {+ try {+ await saveNodeParameters(newId, newNode.data);+ } catch (error) {+ console.error(`[CopyPaste] Failed to save parameters for ${newId}:`, error);+ }+ }++ newNodes.push(newNode);+ }++ // Create new edges with updated source/target IDs+ const newEdges: Edge[] = copiedEdges.map(edge => ({+ ...edge,+ id: `e-${idMap.get(edge.source)}-${idMap.get(edge.target)}-${Date.now()}`,+ source: idMap.get(edge.source)!,+ target: idMap.get(edge.target)!,+ selected: false,+ }));++ // Deselect existing nodes and add new ones as selected+ setNodes(nds => [+ ...nds.map(n => ({ ...n, selected: false })),+ ...newNodes,+ ]);++ setEdges(eds => [...eds, ...newEdges]);++ console.log(`[CopyPaste] Pasted ${newNodes.length} nodes and ${newEdges.length} edges`);+ }, [nodes, setNodes, setEdges, saveNodeParameters]);++ /**+ * Check if clipboard has content.+ */+ const hasClipboard = clipboardRef.current !== null && clipboardRef.current.nodes.length > 0;++ return {+ copySelectedNodes,+ pasteNodes,+ hasClipboard,+ };+};diff --git a/client/src/hooks/useDragAndDrop.ts b/client/src/hooks/useDragAndDrop.tsnew file mode 100644index 00000000..84c8647f--- /dev/null+++ b/client/src/hooks/useDragAndDrop.ts@@ -0,0 +1,124 @@+import { useCallback } from 'react';+import { Node } from 'reactflow';+import { snapToGrid, getDefaultNodePosition } from '../utils/workflow';+import { theme } from '../styles/theme';+import { nodeDefinitions } from '../nodeDefinitions';++interface UseDragAndDropProps {+ nodes: Node[];+ setNodes: (nodes: Node[] | ((nodes: Node[]) => Node[])) => void;+ saveNodeParameters?: (nodeId: string, parameters: Record<string, any>) => Promise<boolean>;+}++/**+ * Generate a unique label for a new node (n8n pattern).+ * First node of type: "Cron Scheduler"+ * Second node of type: "Cron Scheduler 1"+ * Third node of type: "Cron Scheduler 2"+ */+export const generateUniqueLabel = (displayName: string, nodeType: string, existingNodes: Node[]): string => {+ // Collect all labels from nodes of the same type+ const existingLabels = existingNodes+ .filter(n => n.type === nodeType)+ .map(n => n.data?.label as string | undefined)+ .filter((label): label is string => !!label);++ // If no nodes have this base displayName, use it as-is+ if (!existingLabels.includes(displayName)) {+ return displayName;+ }++ // Find next available suffix+ let suffix = 1;+ while (existingLabels.includes(`${displayName} ${suffix}`)) {+ suffix++;+ }+ return `${displayName} ${suffix}`;+};++export const useDragAndDrop = ({ nodes, setNodes, saveNodeParameters }: UseDragAndDropProps) => {+ const onDragOver = useCallback((event: React.DragEvent) => {+ event.preventDefault();+ event.dataTransfer.dropEffect = 'move';+ }, []);++ const onDrop = useCallback(+ async (event: React.DragEvent) => {+ event.preventDefault();++ try {+ const nodeData = JSON.parse(event.dataTransfer.getData('application/reactflow'));+ if (!nodeData || !nodeData.type) {+ return;+ }++ const reactFlowBounds = (event.target as Element).getBoundingClientRect();++ let position = {+ x: event.clientX - reactFlowBounds.left - theme.constants.dragOffset.x,+ y: event.clientY - reactFlowBounds.top - theme.constants.dragOffset.y,+ };++ // Snap to grid for better alignment+ position = snapToGrid(position);++ // If no nodes exist, use default position+ if (nodes.length === 0) {+ position = getDefaultNodePosition(nodes.length);+ }++ // Get node definition to access displayName+ const nodeDef = nodeDefinitions[nodeData.type];+ const displayName = nodeDef?.displayName || nodeData.type;++ // Generate unique label for template variable resolution (n8n pattern)+ const uniqueLabel = generateUniqueLabel(displayName, nodeData.type, nodes);++ const newNode: Node = {+ id: `${nodeData.type}-${Date.now()}`,+ type: nodeData.type,+ position,+ data: {+ ...(nodeData.data || {}),+ label: uniqueLabel, // Add unique label for template resolution+ },+ };++ // Save node parameters to database immediately via WebSocket (including hidden parameters)+ if (newNode.data && Object.keys(newNode.data).length > 0 && saveNodeParameters) {+ try {+ await saveNodeParameters(newNode.id, newNode.data);+ console.log(`[DragAndDrop] Saved default parameters for node ${newNode.id}:`, newNode.data);+ } catch (error) {+ console.error(`[DragAndDrop] Failed to save parameters for node ${newNode.id}:`, error);+ }+ }++ setNodes((nds) => nds.concat(newNode));+ } catch (error) {+ console.error('Error dropping node:', error);+ }+ },+ [setNodes, nodes, saveNodeParameters]+ );++ const handleComponentDragStart = useCallback((event: React.DragEvent, definition: any) => {+ const defaults: any = {};+ // Handle both old (parameters) and new (properties) interface formats+ const properties = definition.properties || definition.parameters || [];+ properties.forEach((param: any) => {+ defaults[param.name] = param.default;+ });+ event.dataTransfer.setData('application/reactflow', JSON.stringify({+ type: definition.name || definition.type, // Handle both new (name) and old (type) formats+ data: defaults+ }));+ event.dataTransfer.effectAllowed = 'move';+ }, []);++ return {+ onDragOver,+ onDrop,+ handleComponentDragStart,+ };+};\ No newline at end of filediff --git a/client/src/hooks/useDragVariable.ts b/client/src/hooks/useDragVariable.tsnew file mode 100644index 00000000..701e957c--- /dev/null+++ b/client/src/hooks/useDragVariable.ts@@ -0,0 +1,88 @@+import { useCallback } from 'react';+import { useAppStore } from '../store/useAppStore';+import { nodeDefinitions } from '../nodeDefinitions';+import { Node } from 'reactflow';++interface DragVariableHookReturn {+ handleVariableDragStart: (+ e: React.DragEvent,+ sourceNodeId: string,+ propertyPath: string,+ value: any+ ) => void;+ getTemplateVariableName: (sourceNodeId: string) => string;+}++/**+ * Hook for handling drag-and-drop of template variables from connected nodes.+ *+ * Template variables use the SOURCE NODE LABEL as the key to ensure uniqueness+ * when multiple nodes of the same type are connected to the same target.+ * This follows the n8n pattern where each node has a unique label.+ *+ * Format: {{normalizedLabel.propertyPath}}+ * Example: {{cronscheduler.data}} or {{cronscheduler1.data}}+ *+ * @param targetNodeId - The ID of the node receiving the drag (target of edge)+ */+export const useDragVariable = (_targetNodeId: string): DragVariableHookReturn => {+ const { currentWorkflow } = useAppStore();++ /**+ * Get template variable name for a source node.+ * Uses node label (n8n pattern) for uniqueness when multiple same-type nodes connect.+ * Falls back to displayName -> nodeType -> nodeId for backward compatibility.+ */+ const getTemplateVariableName = useCallback((sourceNodeId: string): string => {+ if (!currentWorkflow) return sourceNodeId;++ // Find the source node by ID+ const sourceNode = (currentWorkflow.nodes || []).find(+ (node: Node) => node.id === sourceNodeId+ );++ if (!sourceNode) return sourceNodeId;++ // Priority: node.data.label > displayName > nodeType > nodeId+ const label = sourceNode.data?.label;+ if (label && typeof label === 'string') {+ // Normalize label: lowercase, remove spaces+ return label.toLowerCase().replace(/\s+/g, '');+ }++ // Fallback to displayName from node definition+ const nodeDef = nodeDefinitions[sourceNode.type || ''];+ if (nodeDef?.displayName) {+ return nodeDef.displayName.toLowerCase().replace(/\s+/g, '');+ }++ // Ultimate fallback: node type or ID+ return (sourceNode.type || sourceNodeId).toLowerCase().replace(/\s+/g, '');+ }, [currentWorkflow]);++ const handleVariableDragStart = useCallback((+ e: React.DragEvent,+ sourceNodeId: string,+ propertyPath: string,+ value: any+ ) => {+ const templateName = getTemplateVariableName(sourceNodeId);+ const variableTemplate = `{{${templateName}.${propertyPath}}}`;++ e.dataTransfer.setData('text/plain', variableTemplate);+ e.dataTransfer.setData('application/json', JSON.stringify({+ type: 'nodeVariable',+ nodeId: sourceNodeId, // Include source node ID for reference+ nodeName: templateName,+ key: propertyPath,+ variableTemplate,+ dataType: typeof value+ }));+ e.dataTransfer.effectAllowed = 'copy';+ }, [getTemplateVariableName]);++ return {+ handleVariableDragStart,+ getTemplateVariableName+ };+};diff --git a/client/src/hooks/useExecution.ts b/client/src/hooks/useExecution.tsnew file mode 100644index 00000000..f55150e9--- /dev/null+++ b/client/src/hooks/useExecution.ts@@ -0,0 +1,313 @@+/**+ * useExecution Hook - WebSocket-based node execution+ *+ * Provides node execution functionality via WebSocket instead of REST API.+ * This replaces the REST-based ExecutionService for real-time execution.+ */++import { useCallback, useState } from 'react';+import { Node, Edge } from 'reactflow';+import { useWebSocket } from '../contexts/WebSocketContext';+import { nodeDefinitions } from '../nodeDefinitions';+import { INodeExecutionData } from '../types/INodeProperties';++// Execution result interface (compatible with ExecutionService)+export interface ExecutionResult {+ success: boolean;+ nodeId: string;+ nodeType: string;+ nodeName: string;+ timestamp: string;+ executionTime: number;+ outputs?: Record<string, any>;+ error?: string;+ data?: any;+ nodeData: INodeExecutionData[][];+}++export interface UseExecutionResult {+ // Execute a node via WebSocket+ executeNode: (+ nodeId: string,+ nodeType: string,+ nodes?: Node[],+ edges?: Edge[]+ ) => Promise<ExecutionResult>;++ // Execute AI node via WebSocket+ executeAiNode: (+ nodeId: string,+ nodeType: string,+ parameters: Record<string, any>,+ model: string+ ) => Promise<ExecutionResult>;++ // Execution state+ isExecuting: boolean;+ executingNodeId: string | null;+ lastError: string | null;++ // Connection status+ isConnected: boolean;+}++export const useExecution = (): UseExecutionResult => {+ const {+ executeNode: wsExecuteNode,+ executeAiNode: wsExecuteAiNode,+ getNodeParameters,+ isConnected+ } = useWebSocket();++ const [isExecuting, setIsExecuting] = useState(false);+ const [executingNodeId, setExecutingNodeId] = useState<string | null>(null);+ const [lastError, setLastError] = useState<string | null>(null);++ /**+ * Execute a workflow node via WebSocket+ */+ const executeNode = useCallback(async (+ nodeId: string,+ nodeType: string,+ nodes?: Node[],+ edges?: Edge[]+ ): Promise<ExecutionResult> => {+ const startTime = Date.now();++ try {+ console.log(`[WebSocket Execution] Starting: ${nodeId} (type: ${nodeType})`);++ setIsExecuting(true);+ setExecutingNodeId(nodeId);+ setLastError(null);++ // Load parameters from WebSocket/backend+ const paramsResult = await getNodeParameters(nodeId);+ const parameters = paramsResult?.parameters || {};++ console.log(`[WebSocket Execution] Parameters for ${nodeId}:`, parameters);++ // Prepare nodes and edges for execution+ const nodeData = nodes?.map(node => ({+ id: node.id,+ type: node.type || '',+ data: node.data || {}+ })) || [];++ const edgeData = edges?.map(edge => ({+ id: edge.id,+ source: edge.source,+ target: edge.target,+ sourceHandle: edge.sourceHandle || undefined,+ targetHandle: edge.targetHandle || undefined+ })) || [];++ // Execute via WebSocket+ const result = await wsExecuteNode(nodeId, nodeType, parameters, nodeData, edgeData);++ console.log(`[WebSocket Execution] Result:`, result);++ const executionTime = Date.now() - startTime;++ if (result.success) {+ // Extract output data+ const outputData = result.result || {+ nodeId,+ success: true,+ message: 'Execution completed successfully',+ timestamp: result.timestamp || new Date().toISOString()+ };++ const nodeExecutionData: INodeExecutionData[][] = [[{+ json: outputData+ }]];++ return {+ success: true,+ nodeId,+ nodeType,+ nodeName: nodeDefinitions[nodeType]?.displayName || nodeType,+ timestamp: result.timestamp || new Date().toISOString(),+ executionTime: result.execution_time || executionTime,+ outputs: outputData,+ data: outputData,+ nodeData: nodeExecutionData+ };+ } else {+ // Handle error+ const errorOutputData = result.result || {+ error: result.error,+ nodeId,+ success: false,+ timestamp: result.timestamp || new Date().toISOString()+ };++ const errorData: INodeExecutionData[][] = [[{+ json: errorOutputData+ }]];++ setLastError(result.error || 'Execution failed');++ return {+ success: false,+ nodeId,+ nodeType,+ nodeName: nodeDefinitions[nodeType]?.displayName || nodeType,+ timestamp: result.timestamp || new Date().toISOString(),+ executionTime: result.execution_time || executionTime,+ error: result.error,+ outputs: errorOutputData,+ data: errorOutputData,+ nodeData: errorData+ };+ }++ } catch (error: any) {+ console.error(`[WebSocket Execution] Failed for node ${nodeId}:`, error);++ const errorMessage = error.message || 'WebSocket execution failed';+ setLastError(errorMessage);++ const catchErrorData = {+ error: errorMessage,+ nodeId,+ success: false,+ timestamp: new Date().toISOString()+ };++ return {+ success: false,+ nodeId,+ nodeType,+ nodeName: nodeDefinitions[nodeType]?.displayName || nodeType,+ timestamp: new Date().toISOString(),+ executionTime: Date.now() - startTime,+ error: errorMessage,+ outputs: catchErrorData,+ data: catchErrorData,+ nodeData: [[{ json: catchErrorData }]]+ };++ } finally {+ setIsExecuting(false);+ setExecutingNodeId(null);+ }+ }, [wsExecuteNode, getNodeParameters]);++ /**+ * Execute an AI node via WebSocket+ */+ const executeAiNode = useCallback(async (+ nodeId: string,+ nodeType: string,+ parameters: Record<string, any>,+ model: string+ ): Promise<ExecutionResult> => {+ const startTime = Date.now();++ try {+ console.log(`[WebSocket AI Execution] Starting: ${nodeId} (type: ${nodeType})`);++ setIsExecuting(true);+ setExecutingNodeId(nodeId);+ setLastError(null);++ // Execute AI node via WebSocket+ const result = await wsExecuteAiNode(nodeId, nodeType, parameters, model);++ console.log(`[WebSocket AI Execution] Result:`, result);++ const executionTime = Date.now() - startTime;++ if (result.success) {+ const outputData = result.result || {+ nodeId,+ success: true,+ message: 'AI execution completed successfully',+ timestamp: result.timestamp || new Date().toISOString()+ };++ const nodeExecutionData: INodeExecutionData[][] = [[{+ json: outputData+ }]];++ return {+ success: true,+ nodeId,+ nodeType,+ nodeName: nodeDefinitions[nodeType]?.displayName || nodeType,+ timestamp: result.timestamp || new Date().toISOString(),+ executionTime: result.execution_time || executionTime,+ outputs: outputData,+ data: outputData,+ nodeData: nodeExecutionData+ };+ } else {+ const errorOutputData = result.result || {+ error: result.error,+ nodeId,+ success: false,+ timestamp: result.timestamp || new Date().toISOString()+ };++ const errorData: INodeExecutionData[][] = [[{+ json: errorOutputData+ }]];++ setLastError(result.error || 'AI execution failed');++ return {+ success: false,+ nodeId,+ nodeType,+ nodeName: nodeDefinitions[nodeType]?.displayName || nodeType,+ timestamp: result.timestamp || new Date().toISOString(),+ executionTime: result.execution_time || executionTime,+ error: result.error,+ outputs: errorOutputData,+ data: errorOutputData,+ nodeData: errorData+ };+ }++ } catch (error: any) {+ console.error(`[WebSocket AI Execution] Failed for node ${nodeId}:`, error);++ const errorMessage = error.message || 'WebSocket AI execution failed';+ setLastError(errorMessage);++ const catchErrorData = {+ error: errorMessage,+ nodeId,+ success: false,+ timestamp: new Date().toISOString()+ };++ return {+ success: false,+ nodeId,+ nodeType,+ nodeName: nodeDefinitions[nodeType]?.displayName || nodeType,+ timestamp: new Date().toISOString(),+ executionTime: Date.now() - startTime,+ error: errorMessage,+ outputs: catchErrorData,+ data: catchErrorData,+ nodeData: [[{ json: catchErrorData }]]+ };++ } finally {+ setIsExecuting(false);+ setExecutingNodeId(null);+ }+ }, [wsExecuteAiNode]);++ return {+ executeNode,+ executeAiNode,+ isExecuting,+ executingNodeId,+ lastError,+ isConnected+ };+};diff --git a/client/src/hooks/useParameterPanel.ts b/client/src/hooks/useParameterPanel.tsnew file mode 100644index 00000000..11f02fa7--- /dev/null+++ b/client/src/hooks/useParameterPanel.ts@@ -0,0 +1,130 @@+import { useState, useEffect, useMemo, useCallback } from 'react';+import { useAppStore } from '../store/useAppStore';+import { nodeDefinitions } from '../nodeDefinitions';+import { useWebSocket } from '../contexts/WebSocketContext';++export const useParameterPanel = () => {+ const { selectedNode, setSelectedNode, updateNodeData } = useAppStore();+ const [parameters, setParameters] = useState<any>({});+ const [originalParameters, setOriginalParameters] = useState<any>({});+ const [isLoading, setIsLoading] = useState(false);+ const [isSaving, setIsSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);++ // Use WebSocket for parameter operations+ const { getNodeParameters, saveNodeParameters, isConnected } = useWebSocket();++ // Use stable references to prevent multiple effect runs+ const nodeId = selectedNode?.id;+ const nodeType = selectedNode?.type;++ useEffect(() => {+ if (!nodeType || !nodeId) {+ setParameters({});+ setOriginalParameters({});+ setError(null);+ return;+ }++ const loadParameters = async () => {+ const nodeDefinition = nodeDefinitions[nodeType];+ if (!nodeDefinition) return;++ const defaults: any = {};++ // Set parameter defaults+ if (nodeDefinition.properties) {+ nodeDefinition.properties.forEach((param: any) => {+ defaults[param.name] = param.default !== undefined ? param.default : null;+ });+ }++ setIsLoading(true);+ setError(null);++ try {+ // Load saved parameters via WebSocket+ const result = await getNodeParameters(nodeId);+ // Extract parameters from NodeParameters response+ const savedParams = result?.parameters || {};+ const initialParams = { ...defaults, ...savedParams };++ console.log('[useParameterPanel] Loading params for node:', nodeId, nodeType);+ console.log('[useParameterPanel] Defaults:', defaults);+ console.log('[useParameterPanel] Saved from backend:', savedParams);+ console.log('[useParameterPanel] Merged initial:', initialParams);++ setParameters(initialParams);+ setOriginalParameters(initialParams);+ } catch (err) {+ console.error('Failed to load parameters via WebSocket:', err);+ // Use defaults if WebSocket fails+ setParameters(defaults);+ setOriginalParameters(defaults);+ setError('Failed to load saved parameters');+ } finally {+ setIsLoading(false);+ }+ };++ loadParameters();+ }, [nodeId, nodeType, getNodeParameters]);++ const hasUnsavedChanges = useMemo(() => {+ return JSON.stringify(parameters) !== JSON.stringify(originalParameters);+ }, [parameters, originalParameters]);++ const handleParameterChange = useCallback((paramName: string, value: any) => {+ setParameters((prevParams: any) => ({+ ...prevParams,+ [paramName]: value+ }));+ }, []);++ const handleSave = useCallback(async () => {+ if (selectedNode) {+ setIsSaving(true);+ setError(null);++ try {+ // Save parameters to database via WebSocket+ const success = await saveNodeParameters(selectedNode.id, parameters);++ if (success) {+ // Also update the node data in store for faster loading+ updateNodeData(selectedNode.id, parameters);+ setOriginalParameters({ ...parameters });+ } else {+ setError('Failed to save parameters');+ }+ } catch (err) {+ console.error('Failed to save parameters via WebSocket:', err);+ setError('Failed to save parameters');+ } finally {+ setIsSaving(false);+ }+ }+ }, [selectedNode, parameters, updateNodeData, saveNodeParameters]);++ const handleCancel = useCallback(() => {+ setParameters({ ...originalParameters });+ setSelectedNode(null);+ }, [originalParameters, setSelectedNode]);++ const nodeDefinition = selectedNode?.type ? nodeDefinitions[selectedNode.type] : null;++ return {+ selectedNode,+ nodeDefinition,+ parameters,+ hasUnsavedChanges,+ handleParameterChange,+ handleSave,+ handleCancel,+ // New state for loading/saving status+ isLoading,+ isSaving,+ error,+ isConnected,+ };+};diff --git a/client/src/hooks/useReactFlowNodes.ts b/client/src/hooks/useReactFlowNodes.tsnew file mode 100644index 00000000..06cf96d1--- /dev/null+++ b/client/src/hooks/useReactFlowNodes.ts@@ -0,0 +1,180 @@+import { useCallback } from 'react';+import { Node, Edge, addEdge, Connection } from 'reactflow';+import { useAppStore } from '../store/useAppStore';+import { nodeDefinitions } from '../nodeDefinitions';+import { INodeInputDefinition, INodeOutputDefinition, NodeConnectionType } from '../types/INodeProperties';++interface UseReactFlowNodesProps {+ setNodes: (nodes: Node[] | ((nodes: Node[]) => Node[])) => void;+ setEdges: (edges: Edge[] | ((edges: Edge[]) => Edge[])) => void;+}++export const useReactFlowNodes = ({ setNodes, setEdges }: UseReactFlowNodesProps) => {+ const { selectedNode, setSelectedNode } = useAppStore();++ // Helper function to get node inputs/outputs for both enhanced and legacy nodes+ const getNodeInputs = (nodeType: string): INodeInputDefinition[] => {+ const definition = nodeDefinitions[nodeType];+ if (!definition?.inputs) return [];++ // Enhanced nodes: array of input objects+ if (definition.inputs.length > 0 && typeof definition.inputs[0] === 'object') {+ return definition.inputs as INodeInputDefinition[];+ }++ // Legacy nodes: array of strings - convert to input objects+ return (definition.inputs as string[]).map((input, index) => ({+ name: `input_${index}`,+ displayName: 'Input',+ type: (input as NodeConnectionType) || 'main',+ description: 'Node input connection'+ }));+ };++ const getNodeOutputs = (nodeType: string): INodeOutputDefinition[] => {+ const definition = nodeDefinitions[nodeType];+ if (!definition?.outputs) return [];++ // Enhanced nodes: array of output objects+ if (definition.outputs.length > 0 && typeof definition.outputs[0] === 'object') {+ return definition.outputs as INodeOutputDefinition[];+ }++ // Legacy nodes: array of strings - convert to output objects+ return (definition.outputs as string[]).map((output, index) => ({+ name: `output_${index}`,+ displayName: 'Output',+ type: (output as NodeConnectionType) || 'main',+ description: 'Node output connection'+ }));+ };++ // Validate connection compatibility+ const isValidConnection = (connection: Connection, nodes: Node[]): boolean => {+ const sourceNode = nodes.find(n => n.id === connection.source);+ const targetNode = nodes.find(n => n.id === connection.target);++ if (!sourceNode || !targetNode) {+ console.warn('Connection validation: Source or target node not found');+ return false;+ }++ const sourceOutputs = getNodeOutputs(sourceNode.type || '');+ const targetInputs = getNodeInputs(targetNode.type || '');++ // Find the specific output and input being connected+ const sourceHandle = connection.sourceHandle || 'output_0';+ const targetHandle = connection.targetHandle || 'input_0';++ const sourceOutput = sourceOutputs.find(output =>+ `output-${output.name}` === sourceHandle || output.name === sourceHandle+ );+ const targetInput = targetInputs.find(input =>+ `input-${input.name}` === targetHandle || input.name === targetHandle+ );++ if (!sourceOutput || !targetInput) {+ console.log('[Connection Debug]', {+ sourceType: sourceNode.type,+ targetType: targetNode.type,+ sourceHandle,+ targetHandle,+ sourceOutputs: sourceOutputs.map(o => ({ name: o.name, computed: `output-${o.name}` })),+ targetInputs: targetInputs.map(i => ({ name: i.name, computed: `input-${i.name}` })),+ sourceOutput: sourceOutput ? 'found' : 'NOT FOUND',+ targetInput: targetInput ? 'found' : 'NOT FOUND'+ });+ console.warn('Connection validation: Handle not found', { sourceHandle, targetHandle });+ // Allow connection if we can't find handle definitions (fallback for legacy nodes)+ return true;+ }++ // Check type compatibility+ const isCompatible = areTypesCompatible(sourceOutput.type, targetInput.type);++ if (!isCompatible) {+ console.warn(`Connection rejected: Incompatible types`, {+ source: `${sourceNode.type}.${sourceOutput.name} (${sourceOutput.type})`,+ target: `${targetNode.type}.${targetInput.name} (${targetInput.type})`+ });+ }++ return isCompatible;+ };++ // Check if two connection types are compatible+ const areTypesCompatible = (outputType: NodeConnectionType, inputType: NodeConnectionType): boolean => {+ // Same types are always compatible+ if (outputType === inputType) return true;++ // 'main' is compatible with most types (universal data format)+ if (outputType === 'main' || inputType === 'main') return true;++ // Specific compatibility rules+ const compatibilityMatrix: Record<NodeConnectionType, NodeConnectionType[]> = {+ 'main': ['main', 'trigger', 'ai', 'file', 'binary', 'webhook'], // Main accepts everything+ 'trigger': ['main', 'trigger'], // Triggers only connect to main or other triggers+ 'ai': ['main', 'ai'], // AI outputs connect to main or other AI inputs+ 'file': ['main', 'file', 'binary'], // Files can connect to binary+ 'binary': ['main', 'file', 'binary'], // Binary connects to file/binary+ 'webhook': ['main', 'webhook'] // Webhooks connect to main or other webhooks+ };++ return compatibilityMatrix[outputType]?.includes(inputType) ?? false;+ };++ const onConnect = useCallback(+ (params: Edge | Connection) => {+ const { currentWorkflow } = useAppStore.getState();+ const nodes = currentWorkflow?.nodes || [];++ // Convert Edge to Connection format for validation+ const connection: Connection = {+ source: params.source,+ target: params.target,+ sourceHandle: params.sourceHandle ?? null,+ targetHandle: params.targetHandle ?? null+ };++ // Validate connection before adding+ if (!isValidConnection(connection, nodes)) {+ // Show user feedback for rejected connection (non-blocking)+ console.warn('Connection rejected: Incompatible connection types', connection);+ // Could implement a toast notification system here instead of alert+ setTimeout(() => {+ alert('Connection not allowed: Incompatible connection types.\n\nTip: Connect outputs to compatible inputs (e.g., AI → Main, File → Binary).');+ }, 0);+ return;+ }++ // Add the connection+ setEdges((eds) => addEdge(params, eds));+ },+ [setEdges]+ );++ const onNodesDelete = useCallback(+ (deleted: Node[]) => {+ setNodes((nds) => nds.filter((node) => !deleted.find((d) => d.id === node.id)));++ // Clear selected node if it was deleted+ if (selectedNode && deleted.find((d) => d.id === selectedNode.id)) {+ setSelectedNode(null);+ }+ },+ [setNodes, selectedNode, setSelectedNode]+ );++ const onEdgesDelete = useCallback(+ (deleted: Edge[]) => {+ setEdges((eds) => eds.filter((edge) => !deleted.find((d) => d.id === edge.id)));+ },+ [setEdges]+ );++ return {+ onConnect,+ onNodesDelete,+ onEdgesDelete,+ };+};\ No newline at end of filediff --git a/client/src/hooks/useWhatsApp.ts b/client/src/hooks/useWhatsApp.tsnew file mode 100644index 00000000..464d27a6--- /dev/null+++ b/client/src/hooks/useWhatsApp.ts@@ -0,0 +1,196 @@+/**+ * useWhatsApp Hook - WebSocket-based WhatsApp operations+ *+ * Provides WhatsApp messaging and connection management via WebSocket.+ * This replaces REST-based WhatsApp API calls for real-time operations.+ */++import { useCallback, useState } from 'react';+import { useWebSocket } from '../contexts/WebSocketContext';++export interface WhatsAppStatus {+ connected: boolean;+ deviceId?: string;+ data?: any;+}++export interface WhatsAppQRResult {+ connected: boolean;+ qr?: string;+ message?: string;+}++export interface WhatsAppSendResult {+ success: boolean;+ messageId?: string;+ error?: string;+}++export interface UseWhatsAppResult {+ // Get WhatsApp connection status+ getStatus: () => Promise<WhatsAppStatus>;++ // Get QR code for authentication+ getQRCode: () => Promise<WhatsAppQRResult>;++ // Send a WhatsApp message+ sendMessage: (phone: string, message: string) => Promise<WhatsAppSendResult>;++ // Start WhatsApp connection+ startConnection: () => Promise<{ success: boolean; message?: string }>;++ // Restart WhatsApp connection (stops and starts the service)+ restartConnection: () => Promise<{ success: boolean; message?: string }>;++ // State+ isLoading: boolean;+ lastError: string | null;+ connectionStatus: WhatsAppStatus | null;+ isConnected: boolean;+}++export const useWhatsApp = (): UseWhatsAppResult => {+ const {+ getWhatsAppStatus: wsGetStatus,+ getWhatsAppQR: wsGetQR,+ sendWhatsAppMessage: wsSendMessage,+ startWhatsAppConnection: wsStartConnection,+ restartWhatsAppConnection: wsRestartConnection,+ isConnected+ } = useWebSocket();++ const [isLoading, setIsLoading] = useState(false);+ const [lastError, setLastError] = useState<string | null>(null);+ const [connectionStatus, setConnectionStatus] = useState<WhatsAppStatus | null>(null);++ /**+ * Get WhatsApp connection status+ */+ const getStatus = useCallback(async (): Promise<WhatsAppStatus> => {+ setIsLoading(true);+ setLastError(null);++ try {+ const result = await wsGetStatus();+ setConnectionStatus(result);+ return result;+ } catch (error: any) {+ const errorMsg = error.message || 'Failed to get status';+ setLastError(errorMsg);+ return { connected: false };+ } finally {+ setIsLoading(false);+ }+ }, [wsGetStatus]);++ /**+ * Get QR code for WhatsApp authentication+ */+ const getQRCode = useCallback(async (): Promise<WhatsAppQRResult> => {+ setIsLoading(true);+ setLastError(null);++ try {+ const result = await wsGetQR();++ if (result.connected) {+ setConnectionStatus({ connected: true });+ }++ return result;+ } catch (error: any) {+ const errorMsg = error.message || 'Failed to get QR code';+ setLastError(errorMsg);+ return { connected: false, message: errorMsg };+ } finally {+ setIsLoading(false);+ }+ }, [wsGetQR]);++ /**+ * Send a WhatsApp message+ */+ const sendMessage = useCallback(async (+ phone: string,+ message: string+ ): Promise<WhatsAppSendResult> => {+ setIsLoading(true);+ setLastError(null);++ try {+ const result = await wsSendMessage(phone, message);++ if (!result.success && result.error) {+ setLastError(result.error);+ }++ return result;+ } catch (error: any) {+ const errorMsg = error.message || 'Failed to send message';+ setLastError(errorMsg);+ return { success: false, error: errorMsg };+ } finally {+ setIsLoading(false);+ }+ }, [wsSendMessage]);++ /**+ * Start WhatsApp connection+ */+ const startConnection = useCallback(async (): Promise<{ success: boolean; message?: string }> => {+ setIsLoading(true);+ setLastError(null);++ try {+ const result = await wsStartConnection();++ if (!result.success && result.message) {+ setLastError(result.message);+ }++ return result;+ } catch (error: any) {+ const errorMsg = error.message || 'Failed to start connection';+ setLastError(errorMsg);+ return { success: false, message: errorMsg };+ } finally {+ setIsLoading(false);+ }+ }, [wsStartConnection]);++ /**+ * Restart WhatsApp connection (stops and starts the service)+ */+ const restartConnection = useCallback(async (): Promise<{ success: boolean; message?: string }> => {+ setIsLoading(true);+ setLastError(null);++ try {+ const result = await wsRestartConnection();++ if (!result.success && result.message) {+ setLastError(result.message);+ }++ return result;+ } catch (error: any) {+ const errorMsg = error.message || 'Failed to restart connection';+ setLastError(errorMsg);+ return { success: false, message: errorMsg };+ } finally {+ setIsLoading(false);+ }+ }, [wsRestartConnection]);++ return {+ getStatus,+ getQRCode,+ sendMessage,+ startConnection,+ restartConnection,+ isLoading,+ lastError,+ connectionStatus,+ isConnected+ };+};diff --git a/client/src/hooks/useWorkflowManagement.ts b/client/src/hooks/useWorkflowManagement.tsnew file mode 100644index 00000000..bccfbd51--- /dev/null+++ b/client/src/hooks/useWorkflowManagement.ts@@ -0,0 +1,46 @@+import { useCallback } from 'react';+import { useAppStore } from '../store/useAppStore';++export const useWorkflowManagement = () => {+ const {+ currentWorkflow,+ hasUnsavedChanges,+ savedWorkflows,+ updateWorkflow,+ saveWorkflow,+ loadWorkflow,+ createNewWorkflow,+ } = useAppStore();++ const handleWorkflowNameChange = useCallback((name: string) => {+ updateWorkflow({ name });+ }, [updateWorkflow]);++ const handleSave = useCallback(() => {+ saveWorkflow();+ }, [saveWorkflow]);++ const handleNew = useCallback(() => {+ createNewWorkflow();+ }, [createNewWorkflow]);++ const handleOpen = useCallback(() => {+ // Workflow selection is handled by sidebar+ }, []);++ const handleSelectWorkflow = useCallback((workflow: any) => {+ loadWorkflow(workflow.id);+ }, [loadWorkflow]);+++ return {+ currentWorkflow,+ hasUnsavedChanges,+ savedWorkflows,+ handleWorkflowNameChange,+ handleSave,+ handleNew,+ handleOpen,+ handleSelectWorkflow,+ };+};\ No newline at end of filediff --git a/client/src/index.css b/client/src/index.cssnew file mode 100644index 00000000..ee5d1d21--- /dev/null+++ b/client/src/index.css@@ -0,0 +1,315 @@+@tailwind base;+@tailwind components;+@tailwind utilities;++@layer base {+ :root {+ --background: 0 0% 100%;+ --foreground: 222.2 84% 4.9%;+ --card: 0 0% 100%;+ --card-foreground: 222.2 84% 4.9%;+ --popover: 0 0% 100%;+ --popover-foreground: 222.2 84% 4.9%;+ --primary: 221.2 83.2% 53.3%;+ --primary-foreground: 210 40% 98%;+ --secondary: 210 40% 96%;+ --secondary-foreground: 222.2 84% 4.9%;+ --muted: 210 40% 96%;+ --muted-foreground: 215.4 16.3% 46.9%;+ --accent: 210 40% 96%;+ --accent-foreground: 222.2 84% 4.9%;+ --destructive: 0 84.2% 60.2%;+ --destructive-foreground: 210 40% 98%;+ --border: 214.3 31.8% 91.4%;+ --input: 214.3 31.8% 91.4%;+ --ring: 221.2 83.2% 53.3%;+ --radius: 0.5rem;+ }++ .dark {+ --background: 222.2 84% 4.9%;+ --foreground: 210 40% 98%;+ --card: 222.2 84% 4.9%;+ --card-foreground: 210 40% 98%;+ --popover: 222.2 84% 4.9%;+ --popover-foreground: 210 40% 98%;+ --primary: 217.2 91.2% 59.8%;+ --primary-foreground: 222.2 84% 4.9%;+ --secondary: 217.2 32.6% 17.5%;+ --secondary-foreground: 210 40% 98%;+ --muted: 217.2 32.6% 17.5%;+ --muted-foreground: 215 20.2% 65.1%;+ --accent: 217.2 32.6% 17.5%;+ --accent-foreground: 210 40% 98%;+ --destructive: 0 62.8% 30.6%;+ --destructive-foreground: 210 40% 98%;+ --border: 217.2 32.6% 17.5%;+ --input: 217.2 32.6% 17.5%;+ --ring: 224.3 76.3% 94.1%;+ }+}++@layer base {+ * {+ @apply border-border;+ box-sizing: border-box;+ }++ html,+ body {+ height: 100vh;+ width: 100vw;+ margin: 0;+ padding: 0;+ @apply bg-background text-foreground;+ font-feature-settings: "rlig" 1, "calt" 1;+ font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;+ }++ #root {+ height: 100vh;+ width: 100vw;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ }+}++/* ============================================================================+ LIGHT MODE STYLES - Modern, clean design with proper contrast+ ============================================================================ */++/* Light mode React Flow canvas - cooler gray for better node contrast */+.react-flow {+ background-color: #e8ecf1 !important;+}++/* Light mode dot pattern for canvas - more visible */+.react-flow__background pattern circle {+ fill: #9ca3af !important;+}++/* Light mode controls - elevated card style */+.react-flow__controls {+ background: #ffffff;+ border: 1px solid #e2e8f0;+ border-radius: 8px;+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06), 0 1px 2px rgba(0, 0, 0, 0.04);+}++.react-flow__controls button,+.react-flow__controls-button {+ background: #ffffff;+ border: none;+ border-bottom: 1px solid #f1f5f9;+ color: #475569;+}++.react-flow__controls button:last-child,+.react-flow__controls-button:last-child {+ border-bottom: none;+}++.react-flow__controls button:hover,+.react-flow__controls-button:hover {+ background: #f8fafc;+}++.react-flow__controls button svg,+.react-flow__controls-button svg {+ fill: #475569 !important;+}++.react-flow__controls button svg path,+.react-flow__controls-button svg path {+ fill: #475569 !important;+}++/* Light mode minimap */+.react-flow__minimap {+ background: #ffffff;+ border: 1px solid #e2e8f0;+ border-radius: 8px;+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);+}++/* Light mode attribution */+.react-flow__attribution {+ background: rgba(255, 255, 255, 0.9);+ color: #94a3b8;+}++/* Light mode scrollbar */+::-webkit-scrollbar {+ width: 8px;+ height: 8px;+}++::-webkit-scrollbar-track {+ background: #f1f5f9;+ border-radius: 4px;+}++::-webkit-scrollbar-thumb {+ background: #cbd5e1;+ border-radius: 4px;+}++::-webkit-scrollbar-thumb:hover {+ background: #94a3b8;+}++::-webkit-scrollbar-corner {+ background: #f1f5f9;+}++/* Firefox scrollbar - light mode */+html {+ scrollbar-width: thin;+ scrollbar-color: #cbd5e1 #f1f5f9;+}++/* Light mode selection box */+.react-flow__selection {+ background: rgba(59, 130, 246, 0.08);+ border: 1px solid rgba(59, 130, 246, 0.4);+}++/* Light mode connection line */+.react-flow__connection-line {+ stroke: #94a3b8;+ stroke-width: 2;+}++/* ============================================================================+ DARK MODE STYLES - Solarized/Dracula inspired+ ============================================================================ */++.dark .react-flow {+ background-color: hsl(var(--background)) !important;+}++.dark .react-flow__node {+ color: hsl(var(--foreground));+}++.dark .react-flow__edge {+ stroke: hsl(var(--border));+}++.dark .react-flow__controls {+ background: #1f2937;+ border: 1px solid #374151;+ border-radius: 8px;+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);+}++.dark .react-flow__controls button,+.dark .react-flow__controls-button {+ background: #1f2937;+ border: none;+ border-bottom: 1px solid #374151;+ color: #e5e7eb;+}++.dark .react-flow__controls button:last-child,+.dark .react-flow__controls-button:last-child {+ border-bottom: none;+}++.dark .react-flow__controls button:hover,+.dark .react-flow__controls-button:hover {+ background: #374151;+}++.dark .react-flow__controls button svg,+.dark .react-flow__controls-button svg {+ fill: #e5e7eb !important;+}++.dark .react-flow__controls button svg path,+.dark .react-flow__controls-button svg path {+ fill: #e5e7eb !important;+}++.dark .react-flow__minimap {+ background: #1f2937;+ border: 1px solid #374151;+ border-radius: 8px;+}++.dark .react-flow__background {+ background-color: hsl(var(--background));+}++.dark .react-flow__attribution {+ background: hsl(var(--card));+ color: hsl(var(--muted-foreground));+}++/* Node execution status animations - enhanced for visibility */+@keyframes pulse {+ 0%, 100% {+ opacity: 1;+ transform: scale(1);+ }+ 50% {+ opacity: 0.9;+ transform: scale(1.03);+ }+}++/* Light mode specific pulse with stronger effect */+@keyframes pulseLight {+ 0%, 100% {+ opacity: 1;+ transform: scale(1);+ filter: brightness(1);+ }+ 50% {+ opacity: 0.95;+ transform: scale(1.04);+ filter: brightness(1.05);+ }+}++@keyframes spin {+ from {+ transform: rotate(0deg);+ }+ to {+ transform: rotate(360deg);+ }+}++/* Custom Scrollbar - Solarized Dark Theme */+.dark ::-webkit-scrollbar {+ width: 8px;+ height: 8px;+}++.dark ::-webkit-scrollbar-track {+ background: #073642;+ border-radius: 4px;+}++.dark ::-webkit-scrollbar-thumb {+ background: #586e75;+ border-radius: 4px;+ border: 1px solid #073642;+}++.dark ::-webkit-scrollbar-thumb:hover {+ background: #657b83;+}++.dark ::-webkit-scrollbar-corner {+ background: #073642;+}++/* Firefox scrollbar - dark mode */+.dark {+ scrollbar-width: thin;+ scrollbar-color: #586e75 #073642;+}\ No newline at end of filediff --git a/client/src/main.tsx b/client/src/main.tsxnew file mode 100644index 00000000..c1a59d73--- /dev/null+++ b/client/src/main.tsx@@ -0,0 +1,19 @@+import { StrictMode } from 'react'+import { createRoot } from 'react-dom/client'+import './index.css'+import App from './App'+import { ThemeProvider } from './contexts/ThemeContext'+import { AuthProvider } from './contexts/AuthContext'+import { WebSocketProvider } from './contexts/WebSocketContext'++createRoot(document.getElementById('root')!).render(+ <StrictMode>+ <ThemeProvider>+ <AuthProvider>+ <WebSocketProvider>+ <App />+ </WebSocketProvider>+ </AuthProvider>+ </ThemeProvider>+ </StrictMode>,+)diff --git a/client/src/nodeDefinitions.ts b/client/src/nodeDefinitions.tsnew file mode 100644index 00000000..6743c8ec--- /dev/null+++ b/client/src/nodeDefinitions.ts@@ -0,0 +1,86 @@+// Main Node Definitions - Central registry importing from modular files+import { INodeTypeDescription } from './types/INodeProperties';++// Import modular node definitions+import { aiModelNodes } from './nodeDefinitions/aiModelNodes';+import { aiAgentNodes, AI_NODE_TYPES } from './nodeDefinitions/aiAgentNodes';+import { locationNodes, LOCATION_NODE_TYPES } from './nodeDefinitions/locationNodes';+import { whatsappNodes, WHATSAPP_NODE_TYPES } from './nodeDefinitions/whatsappNodes';+import { workflowNodes } from './nodeDefinitions/workflowNodes';+import { schedulerNodes, SCHEDULER_NODE_TYPES } from './nodeDefinitions/schedulerNodes';+import { androidServiceNodes, ANDROID_SERVICE_NODE_TYPES } from './nodeDefinitions/androidServiceNodes';+import { androidDeviceNodes } from './nodeDefinitions/androidDeviceNodes';+import { chatNodes, CHAT_NODE_TYPES } from './nodeDefinitions/chatNodes';+import { codeNodes, CODE_NODE_TYPES } from './nodeDefinitions/codeNodes';+import { utilityNodes, UTILITY_NODE_TYPES } from './nodeDefinitions/utilityNodes';++// ============================================================================+// MAIN NODE REGISTRY - Combining all modular definitions+// ============================================================================++// Merge all node definitions from modular files+export const nodeDefinitions: Record<string, INodeTypeDescription> = {+ ...workflowNodes,+ ...schedulerNodes,+ ...aiModelNodes,+ ...aiAgentNodes,+ ...locationNodes,+ ...whatsappNodes,+ ...androidServiceNodes,+ ...androidDeviceNodes,+ ...chatNodes,+ ...codeNodes,+ ...utilityNodes+};++// ============================================================================+// HELPER FUNCTIONS AND EXPORTS+// ============================================================================++// Export helper function to get all node types+export const getNodeTypes = (): string[] => {+ return Object.keys(nodeDefinitions);+};++// Export helper function to get nodes by group+export const getNodesByGroup = (group: string): INodeTypeDescription[] => {+ return Object.values(nodeDefinitions).filter(node =>+ node.group?.includes(group)+ );+};++// Export AI and Location node lists for easy reference (updated with new nodes)+export const AI_NODES = [+ ...AI_NODE_TYPES+];++export const LOCATION_NODES = [+ ...LOCATION_NODE_TYPES+];++export const WHATSAPP_NODES = [+ ...WHATSAPP_NODE_TYPES+];++export const ANDROID_SERVICE_NODES = [+ ...ANDROID_SERVICE_NODE_TYPES+];++export const SCHEDULER_NODES = [+ ...SCHEDULER_NODE_TYPES+];++export const CHAT_NODES = [+ ...CHAT_NODE_TYPES+];++export const CODE_NODES = [+ ...CODE_NODE_TYPES+];++export const UTILITY_NODES = [+ ...UTILITY_NODE_TYPES+];++// Re-export types and utilities from modular files for external access+export { createBaseChatModel } from './nodeDefinitions/aiModelNodes';\ No newline at end of filediff --git a/client/src/nodeDefinitions/aiAgentNodes.ts b/client/src/nodeDefinitions/aiAgentNodes.tsnew file mode 100644index 00000000..fe6534e5--- /dev/null+++ b/client/src/nodeDefinitions/aiAgentNodes.ts@@ -0,0 +1,186 @@+// AI Agent Node Definitions - AI agents and AI processing components+import {+ INodeTypeDescription,+ NodeConnectionType+} from '../types/INodeProperties';++// ============================================================================+// AI AGENT AND CHAT NODES+// ============================================================================++export const aiAgentNodes: Record<string, INodeTypeDescription> = {+ // Simple Memory Node - conversation history storage for AI agents+ // No run button - memory is accessed automatically when AI Agent runs+ simpleMemory: {+ displayName: 'Simple Memory',+ name: 'simpleMemory',+ icon: '🧠',+ group: ['ai', 'memory'],+ version: 1,+ description: 'Store conversation history for AI agents',+ defaults: { name: 'Memory', color: '#8b5cf6' },+ inputs: [], // No input - memory node is passive+ outputs: [{+ name: 'memory',+ displayName: 'Memory',+ type: 'main' as NodeConnectionType,+ description: 'session_id, messages, message_count, memory_type'+ }],+ properties: [+ {+ displayName: 'Session ID',+ name: 'sessionId',+ type: 'string',+ default: 'default',+ required: true,+ description: 'Unique identifier for conversation session. Use different IDs for separate conversations.'+ },+ {+ displayName: 'Memory Type',+ name: 'memoryType',+ type: 'options',+ default: 'buffer',+ options: [+ { name: 'Buffer (All Messages)', value: 'buffer' },+ { name: 'Window (Last N)', value: 'window' }+ ],+ description: 'Buffer keeps all messages, Window keeps only the last N messages'+ },+ {+ displayName: 'Window Size',+ name: 'windowSize',+ type: 'number',+ default: 10,+ typeOptions: { minValue: 1, maxValue: 100 },+ description: 'Number of recent messages to keep (for Window type)',+ displayOptions: {+ show: {+ memoryType: ['window']+ }+ }+ }+ ]+ },++ // AI Agent Node - n8n official style implementation+ aiAgent: {+ displayName: 'AI Agent',+ name: 'aiAgent',+ icon: '🤖',+ group: ['ai'],+ version: 1,+ subtitle: 'Tools Agent',+ description: 'Advanced AI agent with tool calling capabilities, memory, and iterative reasoning',+ defaults: { name: 'AI Agent', color: '#9333EA' },+ inputs: [+ {+ name: 'main',+ displayName: 'Input',+ type: 'main' as NodeConnectionType,+ description: 'Agent input'+ },+ {+ name: 'memory',+ displayName: 'Memory',+ type: 'main' as NodeConnectionType,+ description: 'Memory node connection for conversation history'+ }+ ],+ outputs: [{+ name: 'main',+ displayName: 'Output',+ type: 'main' as NodeConnectionType,+ description: 'Agent output'+ }],+ properties: [+ {+ displayName: 'AI Provider',+ name: 'provider',+ type: 'options',+ options: [+ {+ name: 'OpenAI',+ value: 'openai'+ },+ {+ name: 'Anthropic (Claude)',+ value: 'anthropic'+ },+ {+ name: 'Google (Gemini)',+ value: 'gemini'+ }+ ],+ default: 'openai',+ description: 'The AI provider to use (configure API keys in Credentials)'+ },+ {+ displayName: 'Model',+ name: 'model',+ type: 'string',+ default: '',+ required: true,+ placeholder: 'Select a model...',+ description: 'AI model to use for the agent',+ typeOptions: {+ dynamicOptions: true,+ dependsOn: ['provider']+ }+ },+ {+ displayName: 'Prompt',+ name: 'prompt',+ type: 'string',+ default: '{{ $json.chatInput }}',+ required: true,+ typeOptions: {+ rows: 4+ },+ description: 'The prompt template for the AI agent',+ placeholder: 'Enter your prompt or use template variables...'+ },+ {+ displayName: 'System Message',+ name: 'systemMessage',+ type: 'string',+ default: 'You are a helpful assistant',+ typeOptions: {+ rows: 3+ },+ description: 'Define the behavior and personality of the AI agent'+ },+ {+ displayName: 'Options',+ name: 'options',+ type: 'collection',+ placeholder: 'Add Option',+ default: {},+ options: [+ {+ displayName: 'Temperature',+ name: 'temperature',+ type: 'number',+ default: 0.7,+ typeOptions: { minValue: 0, maxValue: 2, numberStepSize: 0.1 },+ description: 'Controls randomness in responses'+ },+ {+ displayName: 'Maximum Tokens',+ name: 'maxTokens',+ type: 'number',+ default: 1000,+ typeOptions: { minValue: 1, maxValue: 8192 },+ description: 'Maximum number of tokens to generate'+ }+ ] as any+ }+ ]+ }+};++// ============================================================================+// EXPORTS+// ============================================================================++// List of AI-related node types for easy identification (chat models removed - now in aiModelNodes.ts)+export const AI_NODE_TYPES = ['aiAgent', 'simpleMemory'];\ No newline at end of filediff --git a/client/src/nodeDefinitions/aiModelNodes.ts b/client/src/nodeDefinitions/aiModelNodes.tsnew file mode 100644index 00000000..37de66fa--- /dev/null+++ b/client/src/nodeDefinitions/aiModelNodes.ts@@ -0,0 +1,187 @@+// AI Model Node Definitions - Standardized chat model configurations using base factory+import { INodeTypeDescription } from '../types/INodeProperties';+import { createBaseChatModel, ChatModelConfig, STANDARD_PARAMETERS } from '../factories/baseChatModelFactory';++// ============================================================================+// CHAT MODEL CONFIGURATIONS+// ============================================================================++// OpenAI Chat Model Configuration+const openaiConfig: ChatModelConfig = {+ providerId: 'openai',+ displayName: 'OpenAI',+ icon: '🤖',+ color: '#00A67E',+ description: 'OpenAI GPT models for chat completion and generation',+ models: [], // Models fetched dynamically via API+ parameters: [+ STANDARD_PARAMETERS.frequencyPenalty,+ STANDARD_PARAMETERS.maxTokens,+ {+ displayName: 'Response Format',+ name: 'responseFormat',+ type: 'options',+ options: [+ {+ name: 'Text',+ value: 'text'+ },+ {+ name: 'JSON Object',+ value: 'json_object'+ }+ ],+ default: 'text',+ description: 'Format of the response'+ },+ STANDARD_PARAMETERS.presencePenalty,+ STANDARD_PARAMETERS.temperature,+ {+ displayName: 'Timeout',+ name: 'timeout',+ type: 'number',+ default: 60000,+ typeOptions: {+ minValue: 1000,+ maxValue: 180000+ },+ description: 'Timeout for the request in milliseconds'+ },+ {+ displayName: 'Max Retries',+ name: 'maxRetries',+ type: 'number',+ default: 2,+ typeOptions: {+ minValue: 0,+ maxValue: 5+ },+ description: 'Maximum number of retries'+ },+ STANDARD_PARAMETERS.topP+ ]+};++// Claude Chat Model Configuration+const claudeConfig: ChatModelConfig = {+ providerId: 'anthropic',+ displayName: 'Claude',+ icon: '🧠',+ color: '#FF6B35',+ description: 'Anthropic Claude models for conversation and analysis',+ models: [], // Models fetched dynamically via API+ parameters: [+ {+ ...STANDARD_PARAMETERS.maxTokens,+ typeOptions: { minValue: 1, maxValue: 8192 }+ },+ {+ ...STANDARD_PARAMETERS.temperature,+ typeOptions: { minValue: 0, maxValue: 1, numberStepSize: 0.1 }+ },+ STANDARD_PARAMETERS.topP,+ STANDARD_PARAMETERS.topK,+ {+ displayName: 'Timeout',+ name: 'timeout',+ type: 'number',+ default: 60000,+ typeOptions: {+ minValue: 1000,+ maxValue: 180000+ },+ description: 'Timeout for the request in milliseconds'+ },+ {+ displayName: 'Max Retries',+ name: 'maxRetries',+ type: 'number',+ default: 2,+ typeOptions: {+ minValue: 0,+ maxValue: 5+ },+ description: 'Maximum number of retries'+ }+ ]+};++// Gemini Chat Model Configuration+const geminiConfig: ChatModelConfig = {+ providerId: 'gemini',+ displayName: 'Gemini',+ icon: '⭐',+ color: '#4285F4',+ description: 'Google Gemini models for multimodal AI capabilities',+ models: [], // Models fetched dynamically via API+ parameters: [+ STANDARD_PARAMETERS.maxTokens,+ {+ ...STANDARD_PARAMETERS.temperature,+ default: 0.9,+ typeOptions: { minValue: 0, maxValue: 1, numberStepSize: 0.1 }+ },+ {+ ...STANDARD_PARAMETERS.topP,+ default: 0.95+ },+ STANDARD_PARAMETERS.topK,+ {+ displayName: 'Safety Settings',+ name: 'safetySettings',+ type: 'options',+ options: [+ {+ name: 'Default',+ value: 'default'+ },+ {+ name: 'Strict',+ value: 'strict'+ },+ {+ name: 'Permissive',+ value: 'permissive'+ }+ ],+ default: 'default',+ description: 'Content safety filtering level'+ },+ {+ displayName: 'Timeout',+ name: 'timeout',+ type: 'number',+ default: 60000,+ typeOptions: {+ minValue: 1000,+ maxValue: 180000+ },+ description: 'Timeout for the request in milliseconds'+ },+ {+ displayName: 'Max Retries',+ name: 'maxRetries',+ type: 'number',+ default: 2,+ typeOptions: {+ minValue: 0,+ maxValue: 5+ },+ description: 'Maximum number of retries'+ }+ ]+};++// ============================================================================+// GENERATED CHAT MODEL NODES+// ============================================================================++export const aiModelNodes: Record<string, INodeTypeDescription> = {+ openaiChatModel: createBaseChatModel(openaiConfig),+ anthropicChatModel: createBaseChatModel(claudeConfig),+ geminiChatModel: createBaseChatModel(geminiConfig)+};++// Export configurations and factory for external use+export { openaiConfig, claudeConfig, geminiConfig, createBaseChatModel };+diff --git a/client/src/nodeDefinitions/androidDeviceNodes.ts b/client/src/nodeDefinitions/androidDeviceNodes.tsnew file mode 100644index 00000000..1bb13a9a--- /dev/null+++ b/client/src/nodeDefinitions/androidDeviceNodes.ts@@ -0,0 +1,140 @@+// Android Device Management Nodes+import {+ INodeTypeDescription,+ NodeConnectionType+} from '../types/INodeProperties';+import { API_CONFIG } from '../config/api';++export const androidDeviceNodes: Record<string, INodeTypeDescription> = {+ androidDeviceSetup: {+ displayName: 'Android Device Setup',+ name: 'androidDeviceSetup',+ icon: '🔌',+ group: ['android', 'setup'],+ version: 1,+ subtitle: 'Connect Android Device',+ description: 'Setup Android device connection via local ADB or remote relay with QR code pairing',+ defaults: { name: 'Android Device Setup', color: '#3DDC84' },+ inputs: [{+ name: 'main',+ displayName: 'Input',+ type: 'main' as NodeConnectionType,+ description: 'Trigger device setup',+ required: false+ }],+ outputs: [{+ name: 'main',+ displayName: 'Output',+ type: 'main' as NodeConnectionType,+ description: 'Device connection status'+ }],+ properties: [+ {+ displayName: 'Connection Type',+ name: 'connection_type',+ type: 'options',+ options: [+ {+ name: 'Local ADB Device',+ value: 'local',+ description: 'Connect to Android device via USB/ADB with port forwarding'+ },+ {+ name: 'Remote Relay (QR Pairing)',+ value: 'remote',+ description: 'Connect via relay server with QR code pairing'+ }+ ],+ default: 'remote',+ required: true,+ description: 'Choose connection method: local ADB or remote relay'+ },+ // Local ADB options+ {+ displayName: 'Android Device',+ name: 'device_id',+ type: 'options',+ typeOptions: {+ loadOptionsMethod: 'getAndroidDevices'+ },+ displayOptions: {+ show: {+ connection_type: ['local']+ }+ },+ options: [],+ default: '',+ required: true,+ description: 'Select connected Android device (from adb devices)'+ },+ {+ displayName: 'Auto Setup Port Forwarding',+ name: 'auto_forward',+ type: 'boolean',+ displayOptions: {+ show: {+ connection_type: ['local']+ }+ },+ default: true,+ required: false,+ description: 'Automatically setup ADB port forwarding when node executes'+ },+ {+ displayName: 'Port',+ name: 'port',+ type: 'number',+ displayOptions: {+ show: {+ connection_type: ['local']+ }+ },+ default: 8888,+ required: true,+ description: 'Port number for local ADB port forwarding'+ },+ // Remote relay options+ {+ displayName: 'Relay URL',+ name: 'websocket_url',+ type: 'string',+ displayOptions: {+ show: {+ connection_type: ['remote']+ }+ },+ default: '',+ required: true,+ placeholder: 'wss://your-relay-server.com/ws',+ description: 'Relay server URL for QR code pairing with Android device'+ }+ ],+ methods: {+ loadOptions: {+ async getAndroidDevices(this: any): Promise<Array<{name: string, value: string, description?: string}>> {+ try {+ const response = await fetch(`${API_CONFIG.PYTHON_BASE_URL}/api/android/devices`, {+ credentials: 'include'+ });+ const data = await response.json();++ if (data.success && data.devices) {+ return data.devices.map((device: any) => ({+ name: `${device.model || device.id} (${device.id})`,+ value: device.id,+ description: `${device.state} - Android ${device.android_version || 'Unknown'}`+ }));+ }++ return [];+ } catch (error) {+ console.error('Failed to load Android devices:', error);+ return [];+ }+ }+ }+ }+ }+};++export const ANDROID_DEVICE_NODE_TYPES = ['androidDeviceSetup'];diff --git a/client/src/nodeDefinitions/androidServiceNodes.ts b/client/src/nodeDefinitions/androidServiceNodes.tsnew file mode 100644index 00000000..738f6ed3--- /dev/null+++ b/client/src/nodeDefinitions/androidServiceNodes.ts@@ -0,0 +1,375 @@+// Android Service Nodes - Individual nodes for each Android system service+import {+ INodeTypeDescription,+ NodeConnectionType+} from '../types/INodeProperties';+import { API_CONFIG } from '../config/api';++// ============================================================================+// ANDROID SERVICE NODES - Individual nodes for each Android system service+// ============================================================================++// Helper function to create Android service node definition+function createAndroidServiceNode(config: {+ name: string;+ displayName: string;+ serviceId: string;+ icon: string;+ color: string;+ group: string[];+ description: string;+ defaultAction: string;+ additionalProperties?: Array<{+ displayName: string;+ name: string;+ type: 'string' | 'number' | 'boolean' | 'options' | 'multiOptions' | 'collection' | 'fixedCollection' | 'color' | 'dateTime' | 'json' | 'notice' | 'hidden' | 'resourceLocator' | 'code' | 'file';+ default?: any;+ required?: boolean;+ description?: string;+ placeholder?: string;+ displayOptions?: {+ show?: Record<string, any[]>;+ };+ }>;+}): INodeTypeDescription {+ return {+ displayName: config.displayName,+ name: config.name,+ icon: config.icon,+ group: config.group,+ version: 1,+ subtitle: `Android ${config.group[1]} Service`,+ description: config.description,+ defaults: { name: config.displayName, color: config.color },+ inputs: [{+ name: 'main',+ displayName: 'Input',+ type: 'main' as NodeConnectionType,+ description: 'Service trigger',+ required: false+ }],+ outputs: [{+ name: 'main',+ displayName: 'Output',+ type: 'main' as NodeConnectionType,+ description: 'Service execution result'+ }],+ properties: [+ // Hidden service_id - automatically set based on node type+ {+ displayName: 'Service ID',+ name: 'service_id',+ type: 'hidden',+ default: config.serviceId,+ required: true+ },++ // Hidden Android device connection settings - use defaults+ {+ displayName: 'Android Host',+ name: 'android_host',+ type: 'hidden',+ default: 'localhost',+ required: true+ },++ {+ displayName: 'Android Port',+ name: 'android_port',+ type: 'hidden',+ default: 8888,+ required: true+ },++ // Display label for this service node+ {+ displayName: 'Label',+ name: 'label',+ type: 'string',+ default: config.displayName,+ required: false,+ description: 'Custom label for this node instance'+ },++ // Dynamic Action field - loads options based on node type+ {+ displayName: 'Action',+ name: 'action',+ type: 'options',+ typeOptions: {+ loadOptionsMethod: 'getAndroidServiceActions'+ },+ options: [],+ default: config.defaultAction,+ required: true,+ description: `Action to perform on ${config.displayName}`+ },+ // Add any additional properties for this specific node+ ...(config.additionalProperties || [])+ ],+ methods: {+ loadOptions: {+ async getAndroidServiceActions(this: any): Promise<Array<{name: string, value: string, description?: string}>> {+ try {+ const response = await fetch(`${API_CONFIG.PYTHON_BASE_URL}/api/android/services/${config.serviceId}/actions`, {+ credentials: 'include'+ });+ const data = await response.json();++ if (data.success && data.actions) {+ return data.actions.map((action: any) => ({+ name: action.name,+ value: action.value,+ description: action.description+ }));+ }++ return [];+ } catch (error) {+ console.error(`Failed to load ${config.displayName} actions:`, error);+ return [];+ }+ }+ }+ }+ };+}++export const androidServiceNodes: Record<string, INodeTypeDescription> = {+ // ============================================================================+ // SYSTEM MONITORING SERVICES+ // ============================================================================++ batteryMonitor: createAndroidServiceNode({+ name: 'batteryMonitor',+ displayName: 'Battery Monitor',+ serviceId: 'battery',+ icon: '🔋',+ color: '#4CAF50',+ group: ['android', 'monitoring'],+ description: 'Monitor battery status, level, charging state, temperature, and health',+ defaultAction: 'status'+ }),++ networkMonitor: createAndroidServiceNode({+ name: 'networkMonitor',+ displayName: 'Network Monitor',+ serviceId: 'network',+ icon: '📡',+ color: '#2196F3',+ group: ['android', 'monitoring'],+ description: 'Monitor network connectivity status, type, and internet availability',+ defaultAction: 'status'+ }),++ systemInfo: createAndroidServiceNode({+ name: 'systemInfo',+ displayName: 'System Info',+ serviceId: 'system_info',+ icon: '📱',+ color: '#9C27B0',+ group: ['android', 'monitoring'],+ description: 'Get device and OS information including Android version, API level, memory, and hardware details',+ defaultAction: 'info'+ }),++ location: createAndroidServiceNode({+ name: 'location',+ displayName: 'Location',+ serviceId: 'location',+ icon: '📍',+ color: '#F44336',+ group: ['android', 'monitoring'],+ description: 'GPS location tracking with latitude, longitude, accuracy, and provider information',+ defaultAction: 'current'+ }),++ // ============================================================================+ // APP MANAGEMENT SERVICES+ // ============================================================================++ appLauncher: createAndroidServiceNode({+ name: 'appLauncher',+ displayName: 'App Launcher',+ serviceId: 'app_launcher',+ icon: '🚀',+ color: '#FF9800',+ group: ['android', 'apps'],+ description: 'Launch applications by package name',+ defaultAction: 'launch',+ additionalProperties: [+ {+ displayName: 'Package Name',+ name: 'package_name',+ type: 'string',+ default: '',+ required: true,+ description: 'Package name of the app to launch (e.g., com.whatsapp)',+ placeholder: 'com.example.app',+ displayOptions: {+ show: {+ action: ['launch']+ }+ }+ }+ ]+ }),++ appList: createAndroidServiceNode({+ name: 'appList',+ displayName: 'App List',+ serviceId: 'app_list',+ icon: '📋',+ color: '#00BCD4',+ group: ['android', 'apps'],+ description: 'Get list of installed applications with package names, versions, and metadata',+ defaultAction: 'list'+ }),++ // ============================================================================+ // DEVICE AUTOMATION SERVICES+ // ============================================================================++ wifiAutomation: createAndroidServiceNode({+ name: 'wifiAutomation',+ displayName: 'WiFi Automation',+ serviceId: 'wifi_automation',+ icon: '📶',+ color: '#3F51B5',+ group: ['android', 'automation'],+ description: 'WiFi control and scanning - enable, disable, get status, scan for networks',+ defaultAction: 'status'+ }),++ bluetoothAutomation: createAndroidServiceNode({+ name: 'bluetoothAutomation',+ displayName: 'Bluetooth Automation',+ serviceId: 'bluetooth_automation',+ icon: '🔵',+ color: '#2196F3',+ group: ['android', 'automation'],+ description: 'Bluetooth control - enable, disable, get status, and paired devices',+ defaultAction: 'status'+ }),++ audioAutomation: createAndroidServiceNode({+ name: 'audioAutomation',+ displayName: 'Audio Automation',+ serviceId: 'audio_automation',+ icon: '🔊',+ color: '#E91E63',+ group: ['android', 'automation'],+ description: 'Volume and audio control - get/set volume, mute, unmute',+ defaultAction: 'get_volume'+ }),++ deviceStateAutomation: createAndroidServiceNode({+ name: 'deviceStateAutomation',+ displayName: 'Device State',+ serviceId: 'device_state_automation',+ icon: '⚙️',+ color: '#607D8B',+ group: ['android', 'automation'],+ description: 'Device state control - airplane mode, screen on/off, power save mode, brightness',+ defaultAction: 'status'+ }),++ screenControlAutomation: createAndroidServiceNode({+ name: 'screenControlAutomation',+ displayName: 'Screen Control',+ serviceId: 'screen_control_automation',+ icon: '💡',+ color: '#FFC107',+ group: ['android', 'automation'],+ description: 'Screen control - brightness adjustment, wake screen, auto-brightness, screen timeout',+ defaultAction: 'status'+ }),++ airplaneModeControl: createAndroidServiceNode({+ name: 'airplaneModeControl',+ displayName: 'Airplane Mode',+ serviceId: 'airplane_mode_control',+ icon: '✈️',+ color: '#795548',+ group: ['android', 'automation'],+ description: 'Airplane mode status monitoring and control',+ defaultAction: 'status'+ }),++ // ============================================================================+ // SENSOR SERVICES (Experimental)+ // ============================================================================++ motionDetection: createAndroidServiceNode({+ name: 'motionDetection',+ displayName: 'Motion Detection',+ serviceId: 'motion_detection',+ icon: '📳',+ color: '#FF5722',+ group: ['android', 'sensors'],+ description: 'Accelerometer and gyroscope data - detect motion, shake gestures, device orientation',+ defaultAction: 'current_motion'+ }),++ environmentalSensors: createAndroidServiceNode({+ name: 'environmentalSensors',+ displayName: 'Environmental Sensors',+ serviceId: 'environmental_sensors',+ icon: '🌡️',+ color: '#009688',+ group: ['android', 'sensors'],+ description: 'Environmental sensors - temperature, humidity, pressure, light level',+ defaultAction: 'ambient_conditions'+ }),++ // ============================================================================+ // MEDIA SERVICES (Experimental)+ // ============================================================================++ cameraControl: createAndroidServiceNode({+ name: 'cameraControl',+ displayName: 'Camera Control',+ serviceId: 'camera_control',+ icon: '📷',+ color: '#673AB7',+ group: ['android', 'media'],+ description: 'Camera control - get camera info, take photos, camera capabilities',+ defaultAction: 'camera_info'+ }),++ mediaControl: createAndroidServiceNode({+ name: 'mediaControl',+ displayName: 'Media Control',+ serviceId: 'media_control',+ icon: '🎵',+ color: '#E91E63',+ group: ['android', 'media'],+ description: 'Media playback control - volume control, playback control, play media files',+ defaultAction: 'volume_control'+ })+};++// Export node type identifiers+export const ANDROID_SERVICE_NODE_TYPES = [+ // System Monitoring+ 'batteryMonitor',+ 'networkMonitor',+ 'systemInfo',+ 'location',+ // App Management+ 'appLauncher',+ 'appList',+ // Device Automation+ 'wifiAutomation',+ 'bluetoothAutomation',+ 'audioAutomation',+ 'deviceStateAutomation',+ 'screenControlAutomation',+ 'airplaneModeControl',+ // Sensors+ 'motionDetection',+ 'environmentalSensors',+ // Media+ 'cameraControl',+ 'mediaControl'+];diff --git a/client/src/nodeDefinitions/chatNodes.ts b/client/src/nodeDefinitions/chatNodes.tsnew file mode 100644index 00000000..528b9a32--- /dev/null+++ b/client/src/nodeDefinitions/chatNodes.ts@@ -0,0 +1,135 @@+// Chat Node Definitions - JSON-RPC 2.0 WebSocket chat integration+import { INodeTypeDescription, NodeConnectionType } from '../types/INodeProperties';++// Chat icon (speech bubble)+const CHAT_ICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%234A90D9'%3E%3Cpath d='M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z'/%3E%3C/svg%3E";++export const chatNodes: Record<string, INodeTypeDescription> = {+ // Chat Send Message Node+ chatSend: {+ displayName: 'Chat Send',+ name: 'chatSend',+ icon: CHAT_ICON,+ group: ['chat'],+ version: 1,+ subtitle: 'Send Chat Message',+ description: 'Send a message to the chat backend via JSON-RPC 2.0 WebSocket',+ defaults: { name: 'Chat Send', color: '#4A90D9' },+ inputs: [{+ name: 'main',+ displayName: 'Input',+ type: 'main' as NodeConnectionType,+ description: 'Trigger input'+ }],+ outputs: [{+ name: 'main',+ displayName: 'Output',+ type: 'main' as NodeConnectionType,+ description: 'message_id, status, timestamp'+ }],+ properties: [+ // Connection settings+ {+ displayName: 'Host',+ name: 'host',+ type: 'string',+ default: 'localhost',+ description: 'Chat server host'+ },+ {+ displayName: 'Port',+ name: 'port',+ type: 'number',+ default: 8080,+ description: 'Chat server port'+ },+ {+ displayName: 'Session ID',+ name: 'session_id',+ type: 'string',+ default: 'default',+ description: 'Chat session identifier'+ },+ {+ displayName: 'API Key',+ name: 'api_key',+ type: 'string',+ default: '',+ description: 'API key for authentication'+ },+ // Message+ {+ displayName: 'Message',+ name: 'content',+ type: 'string',+ default: '',+ required: true,+ typeOptions: { rows: 3 },+ description: 'Message content to send'+ }+ ]+ },++ // Chat Get History Node+ chatHistory: {+ displayName: 'Chat History',+ name: 'chatHistory',+ icon: CHAT_ICON,+ group: ['chat'],+ version: 1,+ subtitle: 'Get Chat History',+ description: 'Retrieve chat message history from the backend',+ defaults: { name: 'Chat History', color: '#4A90D9' },+ inputs: [{+ name: 'main',+ displayName: 'Input',+ type: 'main' as NodeConnectionType,+ description: 'Trigger input'+ }],+ outputs: [{+ name: 'main',+ displayName: 'Output',+ type: 'main' as NodeConnectionType,+ description: 'messages array'+ }],+ properties: [+ {+ displayName: 'Host',+ name: 'host',+ type: 'string',+ default: 'localhost',+ description: 'Chat server host'+ },+ {+ displayName: 'Port',+ name: 'port',+ type: 'number',+ default: 8080,+ description: 'Chat server port'+ },+ {+ displayName: 'Session ID',+ name: 'session_id',+ type: 'string',+ default: 'default',+ description: 'Chat session identifier'+ },+ {+ displayName: 'API Key',+ name: 'api_key',+ type: 'string',+ default: '',+ description: 'API key for authentication'+ },+ {+ displayName: 'Limit',+ name: 'limit',+ type: 'number',+ default: 50,+ description: 'Maximum number of messages to retrieve'+ }+ ]+ }+};++export const CHAT_NODE_TYPES = ['chatSend', 'chatHistory'];diff --git a/client/src/nodeDefinitions/codeNodes.ts b/client/src/nodeDefinitions/codeNodes.tsnew file mode 100644index 00000000..f764ab10--- /dev/null+++ b/client/src/nodeDefinitions/codeNodes.ts@@ -0,0 +1,54 @@+// Code Execution Nodes+import { INodeTypeDescription, NodeConnectionType } from '../types/INodeProperties';++export const codeNodes: Record<string, INodeTypeDescription> = {+ pythonExecutor: {+ displayName: 'Python Executor',+ name: 'pythonExecutor',+ icon: 'https://cdn.jsdelivr.net/gh/devicons/devicon/icons/python/python-original.svg',+ group: ['code', 'transform'],+ version: 1,+ subtitle: 'Run Python Code',+ description: 'Execute Python code with input data access',+ defaults: { name: 'Python Executor', color: '#3776AB' },+ inputs: [{ name: 'main', displayName: 'Input', type: 'main' as NodeConnectionType, description: 'Input data as input_data variable' }],+ outputs: [{ name: 'main', displayName: 'Output', type: 'main' as NodeConnectionType, description: 'Python execution result' }],+ properties: [+ {+ displayName: 'Code',+ name: 'code',+ type: 'string',+ default: '# Python Executor - Transform and process data\n#\n# Available:\n# input_data - dict with connected node outputs\n# math, json - imported modules\n# print() - for debugging\n#\n# Set the "output" variable with your result\n\n# Example: Get data from connected node\ndata = input_data.get("start", {}) or input_data\n\n# Process data\nresult = {\n "message": "Hello from Python!",\n "input_received": data,\n "processed": True\n}\n\n# Set output (required)\noutput = result',+ required: true,+ typeOptions: { rows: 5, editor: 'code', editorLanguage: 'python' },+ placeholder: '# Write your Python code here...'+ }+ ]+ },++ javascriptExecutor: {+ displayName: 'JavaScript Executor',+ name: 'javascriptExecutor',+ icon: 'https://cdn.jsdelivr.net/gh/devicons/devicon/icons/javascript/javascript-original.svg',+ group: ['code', 'transform'],+ version: 1,+ subtitle: 'Run JavaScript Code',+ description: 'Execute JavaScript code with input data access',+ defaults: { name: 'JavaScript Executor', color: '#F7DF1E' },+ inputs: [{ name: 'main', displayName: 'Input', type: 'main' as NodeConnectionType, description: 'Input data as input_data variable' }],+ outputs: [{ name: 'main', displayName: 'Output', type: 'main' as NodeConnectionType, description: 'JavaScript execution result' }],+ properties: [+ {+ displayName: 'Code',+ name: 'code',+ type: 'string',+ default: '// JavaScript Executor - Transform and process data\n//\n// Available:\n// input_data - object with connected node outputs\n// console.log() - for debugging\n//\n// Set the "output" variable with your result\n\n// Example: Get data from connected node\nconst data = input_data?.start || input_data || {};\n\n// Process data\nconst result = {\n message: "Hello from JavaScript!",\n input_received: data,\n processed: true\n};\n\n// Set output (required)\noutput = result;',+ required: true,+ typeOptions: { rows: 5, editor: 'code', editorLanguage: 'javascript' },+ placeholder: '// Write your JavaScript code here...'+ }+ ]+ }+};++export const CODE_NODE_TYPES = ['pythonExecutor', 'javascriptExecutor'];diff --git a/client/src/nodeDefinitions/index.ts b/client/src/nodeDefinitions/index.tsnew file mode 100644index 00000000..50089ce5--- /dev/null+++ b/client/src/nodeDefinitions/index.ts@@ -0,0 +1,14 @@+// Central export file for all node definitions+export { aiModelNodes, openaiConfig, claudeConfig, geminiConfig, createBaseChatModel } from './aiModelNodes';+export { aiAgentNodes, AI_NODE_TYPES } from './aiAgentNodes';+export { locationNodes, LOCATION_NODE_TYPES } from './locationNodes';+export { workflowNodes, WORKFLOW_NODE_TYPES } from './workflowNodes';+export { schedulerNodes, SCHEDULER_NODE_TYPES } from './schedulerNodes';+export { chatNodes, CHAT_NODE_TYPES } from './chatNodes';++// Re-export types for convenience+export type {+ INodeTypeDescription,+ NodeConnectionType,+ INodeProperties+} from '../types/INodeProperties';\ No newline at end of filediff --git a/client/src/nodeDefinitions/locationNodes.ts b/client/src/nodeDefinitions/locationNodes.tsnew file mode 100644index 00000000..782b3c10--- /dev/null+++ b/client/src/nodeDefinitions/locationNodes.ts@@ -0,0 +1,463 @@+// Location Node Definitions - GPS, Maps, and Geolocation Services+import {+ INodeTypeDescription,+ NodeConnectionType+} from '../types/INodeProperties';++// ============================================================================+// LOCATION NODES - GPS, Maps, and Geolocation Services+// ============================================================================++export const locationNodes: Record<string, INodeTypeDescription> = {+ // ============================================================================+ // GOOGLE MAPS NODES - Map Creation and Places Integration+ // ============================================================================++ // Create Map - Initialize Google Maps JavaScript API with coordinates+ createMap: {+ displayName: 'Create Map',+ name: 'createMap',+ icon: '🗺️',+ group: ['location', 'service'],+ version: 1,+ subtitle: 'Initialize Google Map',+ description: 'Creates an interactive Google Map using the Maps JavaScript API with customizable center, zoom, and map type',+ defaults: { name: 'Create Map', color: '#1A73E8' },+ inputs: [{+ name: 'main',+ displayName: 'Map Configuration',+ type: 'main' as NodeConnectionType,+ description: 'Input configuration for map initialization',+ required: false+ }],+ outputs: [{+ name: 'main',+ displayName: 'Map Output',+ type: 'main' as NodeConnectionType,+ description: 'Map configuration and reference'+ }],+ credentials: [{+ name: 'googleMapsApi',+ required: true,+ displayName: 'Google Maps API Key'+ }],+ properties: [+ { displayName: 'Center Latitude', name: 'lat', type: 'number', typeOptions: { minValue: -90, maxValue: 90, numberStepSize: 0.000001 }, default: 40.7128, required: true, description: 'Latitude for map center (decimal degrees)' },+ { displayName: 'Center Longitude', name: 'lng', type: 'number', typeOptions: { minValue: -180, maxValue: 180, numberStepSize: 0.000001 }, default: -74.0060, required: true, description: 'Longitude for map center (decimal degrees)' },+ { displayName: 'Zoom Level', name: 'zoom', type: 'number', typeOptions: { minValue: 0, maxValue: 21 }, default: 13, description: 'Map zoom level (0-21, where 21 is building level)' },+ { displayName: 'Map Type', name: 'mapTypeId', type: 'options', options: [+ { name: 'Roadmap', value: 'ROADMAP' },+ { name: 'Satellite', value: 'SATELLITE' },+ { name: 'Hybrid', value: 'HYBRID' },+ { name: 'Terrain', value: 'TERRAIN' }+ ], default: 'ROADMAP', description: 'Google Maps display type' },+ {+ displayName: 'Options',+ name: 'options',+ type: 'collection',+ placeholder: 'Add Option',+ default: {},+ options: [+ {+ displayName: 'Disable Default UI',+ name: 'disableDefaultUI',+ type: 'boolean',+ default: false,+ description: 'Disable default Google Maps UI controls'+ },+ {+ displayName: 'Zoom Control',+ name: 'zoomControl',+ type: 'boolean',+ default: true,+ description: 'Enable zoom control buttons'+ },+ {+ displayName: 'Map Type Control',+ name: 'mapTypeControl',+ type: 'boolean',+ default: true,+ description: 'Enable map type selection control'+ },+ {+ displayName: 'Street View Control',+ name: 'streetViewControl',+ type: 'boolean',+ default: true,+ description: 'Enable street view control'+ },+ {+ displayName: 'Fullscreen Control',+ name: 'fullscreenControl',+ type: 'boolean',+ default: true,+ description: 'Enable fullscreen control'+ }+ ] as any+ }+ ]+ },++ // Add Locations - Google Maps Geocoding Service+ addLocations: {+ displayName: 'Add Locations',+ name: 'addLocations',+ icon: '🌍',+ group: ['location', 'service'],+ version: 1,+ subtitle: 'Geocoding Service',+ description: 'Use Google Maps Geocoding Service for address-to-coordinates conversion and reverse geocoding with detailed location information',+ defaults: { name: 'Add Locations', color: '#34A853' },+ inputs: [{+ name: 'main',+ displayName: 'Geocoding Input',+ type: 'main' as NodeConnectionType,+ description: 'Input address or coordinates for geocoding service',+ required: false+ }],+ outputs: [{+ name: 'main',+ displayName: 'Geocoding Results',+ type: 'main' as NodeConnectionType,+ description: 'Geocoding service results with detailed location data'+ }],+ credentials: [{+ name: 'googleMapsApi',+ required: true,+ displayName: 'Google Maps API Key'+ }],+ properties: [+ { displayName: 'Service Type', name: 'serviceType', type: 'options', options: [+ { name: 'Geocoding (Address → LatLng)', value: 'geocode' },+ { name: 'Reverse Geocoding (LatLng → Address)', value: 'reverse_geocode' }+ ], default: 'geocode', required: true, description: 'Google Maps Geocoding service operation' },++ // Geocoding Request Parameters+ { displayName: 'Address Query', name: 'address', type: 'string', default: '', placeholder: 'e.g., "1600 Amphitheatre Parkway, Mountain View, CA"', required: true, displayOptions: { show: { serviceType: ['geocode'] } }, description: 'The address to geocode' },++ // Reverse Geocoding Parameters+ { displayName: 'Location Latitude', name: 'lat', type: 'number', typeOptions: { minValue: -90, maxValue: 90, numberStepSize: 0.000001 }, default: 37.4224, required: true, displayOptions: { show: { serviceType: ['reverse_geocode'] } }, description: 'Latitude for reverse geocoding' },+ { displayName: 'Location Longitude', name: 'lng', type: 'number', typeOptions: { minValue: -180, maxValue: 180, numberStepSize: 0.000001 }, default: -122.0842, required: true, displayOptions: { show: { serviceType: ['reverse_geocode'] } }, description: 'Longitude for reverse geocoding' },++ {+ displayName: 'Options',+ name: 'options',+ type: 'collection',+ placeholder: 'Add Option',+ default: {},+ options: [+ {+ displayName: 'Result Types',+ name: 'resultTypes',+ type: 'multiOptions',+ options: [+ { name: 'Street Address', value: 'street_address' },+ { name: 'Route', value: 'route' },+ { name: 'Intersection', value: 'intersection' },+ { name: 'Political', value: 'political' },+ { name: 'Country', value: 'country' },+ { name: 'Administrative Area Level 1', value: 'administrative_area_level_1' },+ { name: 'Administrative Area Level 2', value: 'administrative_area_level_2' },+ { name: 'Locality', value: 'locality' },+ { name: 'Sublocality', value: 'sublocality' },+ { name: 'Postal Code', value: 'postal_code' }+ ],+ default: [],+ description: 'Filter results by address component types'+ },+ {+ displayName: 'Location Types',+ name: 'locationTypes',+ type: 'multiOptions',+ options: [+ { name: 'Rooftop', value: 'ROOFTOP' },+ { name: 'Range Interpolated', value: 'RANGE_INTERPOLATED' },+ { name: 'Geometric Center', value: 'GEOMETRIC_CENTER' },+ { name: 'Approximate', value: 'APPROXIMATE' }+ ],+ default: [],+ description: 'Filter by location precision type'+ },+ {+ displayName: 'Language',+ name: 'language',+ type: 'options',+ options: [+ { name: 'English', value: 'en' },+ { name: 'Spanish', value: 'es' },+ { name: 'French', value: 'fr' },+ { name: 'German', value: 'de' },+ { name: 'Italian', value: 'it' },+ { name: 'Portuguese', value: 'pt' },+ { name: 'Japanese', value: 'ja' },+ { name: 'Korean', value: 'ko' },+ { name: 'Chinese (Simplified)', value: 'zh-CN' },+ { name: 'Russian', value: 'ru' },+ { name: 'Arabic', value: 'ar' }+ ],+ default: 'en',+ description: 'Language for returned results'+ },+ {+ displayName: 'Region Bias',+ name: 'region',+ type: 'string',+ default: '',+ placeholder: 'e.g., "us", "uk", "jp"',+ description: 'Region code for biasing results (ccTLD format)'+ },+ {+ displayName: 'Component Restrictions',+ name: 'componentRestrictions',+ type: 'string',+ default: '',+ placeholder: 'e.g., "country:US|administrative_area:CA"',+ description: 'Component-based filtering (pipe-separated)'+ }+ ] as any+ }+ ]+ },++ // Show Nearby Places - Google Maps Places API nearbySearch+ showNearbyPlaces: {+ displayName: 'Show Nearby Places',+ name: 'showNearbyPlaces',+ icon: '🔍',+ group: ['location', 'service'],+ version: 1,+ subtitle: 'Places API nearbySearch',+ description: 'Search for places near a location using Google Maps Places API nearbySearch with detailed place information in JSON format',+ defaults: { name: 'Show Nearby Places', color: '#FF6D01' },+ inputs: [{+ name: 'main',+ displayName: 'Search Parameters',+ type: 'main' as NodeConnectionType,+ description: 'Input search parameters for nearby places',+ required: false+ }],+ outputs: [{+ name: 'main',+ displayName: 'Places Results',+ type: 'main' as NodeConnectionType,+ description: 'Places API nearbySearch results with place details JSON'+ }],+ credentials: [{+ name: 'googleMapsApi',+ required: true,+ displayName: 'Google Maps API Key'+ }],+ properties: [+ // Required Parameters (matching Places API nearbySearch)+ { displayName: 'Location Latitude', name: 'lat', type: 'number', typeOptions: { minValue: -90, maxValue: 90, numberStepSize: 0.000001 }, default: 40.7484, required: true, description: 'Center latitude for nearbySearch (required)' },+ { displayName: 'Location Longitude', name: 'lng', type: 'number', typeOptions: { minValue: -180, maxValue: 180, numberStepSize: 0.000001 }, default: -73.9857, required: true, description: 'Center longitude for nearbySearch (required)' },+ { displayName: 'Radius (meters)', name: 'radius', type: 'number', typeOptions: { minValue: 1, maxValue: 50000 }, default: 500, required: true, description: 'Search radius in meters (max 50,000m)' },++ // Place Types (official Google Places API types)+ { displayName: 'Place Type', name: 'type', type: 'options', options: [+ { name: 'Accounting', value: 'accounting' },+ { name: 'Airport', value: 'airport' },+ { name: 'Amusement Park', value: 'amusement_park' },+ { name: 'Aquarium', value: 'aquarium' },+ { name: 'Art Gallery', value: 'art_gallery' },+ { name: 'ATM', value: 'atm' },+ { name: 'Bakery', value: 'bakery' },+ { name: 'Bank', value: 'bank' },+ { name: 'Bar', value: 'bar' },+ { name: 'Beauty Salon', value: 'beauty_salon' },+ { name: 'Bicycle Store', value: 'bicycle_store' },+ { name: 'Book Store', value: 'book_store' },+ { name: 'Bowling Alley', value: 'bowling_alley' },+ { name: 'Bus Station', value: 'bus_station' },+ { name: 'Cafe', value: 'cafe' },+ { name: 'Campground', value: 'campground' },+ { name: 'Car Dealer', value: 'car_dealer' },+ { name: 'Car Rental', value: 'car_rental' },+ { name: 'Car Repair', value: 'car_repair' },+ { name: 'Car Wash', value: 'car_wash' },+ { name: 'Casino', value: 'casino' },+ { name: 'Cemetery', value: 'cemetery' },+ { name: 'Church', value: 'church' },+ { name: 'City Hall', value: 'city_hall' },+ { name: 'Clothing Store', value: 'clothing_store' },+ { name: 'Convenience Store', value: 'convenience_store' },+ { name: 'Courthouse', value: 'courthouse' },+ { name: 'Dentist', value: 'dentist' },+ { name: 'Department Store', value: 'department_store' },+ { name: 'Doctor', value: 'doctor' },+ { name: 'Drugstore', value: 'drugstore' },+ { name: 'Electrician', value: 'electrician' },+ { name: 'Electronics Store', value: 'electronics_store' },+ { name: 'Embassy', value: 'embassy' },+ { name: 'Fire Station', value: 'fire_station' },+ { name: 'Florist', value: 'florist' },+ { name: 'Funeral Home', value: 'funeral_home' },+ { name: 'Furniture Store', value: 'furniture_store' },+ { name: 'Gas Station', value: 'gas_station' },+ { name: 'Gym', value: 'gym' },+ { name: 'Hair Care', value: 'hair_care' },+ { name: 'Hardware Store', value: 'hardware_store' },+ { name: 'Hindu Temple', value: 'hindu_temple' },+ { name: 'Home Goods Store', value: 'home_goods_store' },+ { name: 'Hospital', value: 'hospital' },+ { name: 'Insurance Agency', value: 'insurance_agency' },+ { name: 'Jewelry Store', value: 'jewelry_store' },+ { name: 'Laundry', value: 'laundry' },+ { name: 'Lawyer', value: 'lawyer' },+ { name: 'Library', value: 'library' },+ { name: 'Light Rail Station', value: 'light_rail_station' },+ { name: 'Liquor Store', value: 'liquor_store' },+ { name: 'Local Government Office', value: 'local_government_office' },+ { name: 'Locksmith', value: 'locksmith' },+ { name: 'Lodging', value: 'lodging' },+ { name: 'Meal Delivery', value: 'meal_delivery' },+ { name: 'Meal Takeaway', value: 'meal_takeaway' },+ { name: 'Mosque', value: 'mosque' },+ { name: 'Movie Rental', value: 'movie_rental' },+ { name: 'Movie Theater', value: 'movie_theater' },+ { name: 'Moving Company', value: 'moving_company' },+ { name: 'Museum', value: 'museum' },+ { name: 'Night Club', value: 'night_club' },+ { name: 'Painter', value: 'painter' },+ { name: 'Park', value: 'park' },+ { name: 'Parking', value: 'parking' },+ { name: 'Pet Store', value: 'pet_store' },+ { name: 'Pharmacy', value: 'pharmacy' },+ { name: 'Physiotherapist', value: 'physiotherapist' },+ { name: 'Plumber', value: 'plumber' },+ { name: 'Police', value: 'police' },+ { name: 'Post Office', value: 'post_office' },+ { name: 'Primary School', value: 'primary_school' },+ { name: 'Real Estate Agency', value: 'real_estate_agency' },+ { name: 'Restaurant', value: 'restaurant' },+ { name: 'Roofing Contractor', value: 'roofing_contractor' },+ { name: 'RV Park', value: 'rv_park' },+ { name: 'School', value: 'school' },+ { name: 'Secondary School', value: 'secondary_school' },+ { name: 'Shoe Store', value: 'shoe_store' },+ { name: 'Shopping Mall', value: 'shopping_mall' },+ { name: 'Spa', value: 'spa' },+ { name: 'Stadium', value: 'stadium' },+ { name: 'Storage', value: 'storage' },+ { name: 'Store', value: 'store' },+ { name: 'Subway Station', value: 'subway_station' },+ { name: 'Supermarket', value: 'supermarket' },+ { name: 'Synagogue', value: 'synagogue' },+ { name: 'Taxi Stand', value: 'taxi_stand' },+ { name: 'Tourist Attraction', value: 'tourist_attraction' },+ { name: 'Train Station', value: 'train_station' },+ { name: 'Transit Station', value: 'transit_station' },+ { name: 'Travel Agency', value: 'travel_agency' },+ { name: 'University', value: 'university' },+ { name: 'Veterinary Care', value: 'veterinary_care' },+ { name: 'Zoo', value: 'zoo' }+ ], default: 'restaurant', description: 'Google Places API place type filter' },++ {+ displayName: 'Options',+ name: 'options',+ type: 'collection',+ placeholder: 'Add Option',+ default: {},+ options: [+ {+ displayName: 'Keyword',+ name: 'keyword',+ type: 'string',+ default: '',+ placeholder: 'e.g., "pizza", "italian", "24 hour"',+ description: 'Keyword to match against place names and types'+ },+ {+ displayName: 'Name Filter',+ name: 'name',+ type: 'string',+ default: '',+ placeholder: 'e.g., "Starbucks", "McDonald\'s"',+ description: 'Match places with this name (equivalent to keyword but for names only)'+ },+ {+ displayName: 'Min Price Level',+ name: 'minPrice',+ type: 'options',+ options: [+ { name: 'Any', value: '' },+ { name: 'Free (0)', value: 0 },+ { name: 'Inexpensive (1)', value: 1 },+ { name: 'Moderate (2)', value: 2 },+ { name: 'Expensive (3)', value: 3 },+ { name: 'Very Expensive (4)', value: 4 }+ ],+ default: '',+ description: 'Minimum price level (0-4)'+ },+ {+ displayName: 'Max Price Level',+ name: 'maxPrice',+ type: 'options',+ options: [+ { name: 'Any', value: '' },+ { name: 'Free (0)', value: 0 },+ { name: 'Inexpensive (1)', value: 1 },+ { name: 'Moderate (2)', value: 2 },+ { name: 'Expensive (3)', value: 3 },+ { name: 'Very Expensive (4)', value: 4 }+ ],+ default: '',+ description: 'Maximum price level (0-4)'+ },+ {+ displayName: 'Open Now',+ name: 'openNow',+ type: 'boolean',+ default: false,+ description: 'Only return places open at query time'+ },+ {+ displayName: 'Language',+ name: 'language',+ type: 'options',+ options: [+ { name: 'English', value: 'en' },+ { name: 'Spanish', value: 'es' },+ { name: 'French', value: 'fr' },+ { name: 'German', value: 'de' },+ { name: 'Italian', value: 'it' },+ { name: 'Portuguese', value: 'pt' },+ { name: 'Japanese', value: 'ja' },+ { name: 'Korean', value: 'ko' },+ { name: 'Chinese (Simplified)', value: 'zh-CN' },+ { name: 'Russian', value: 'ru' },+ { name: 'Arabic', value: 'ar' },+ { name: 'Hindi', value: 'hi' }+ ],+ default: 'en',+ description: 'Language for place names and information'+ },+ {+ displayName: 'Rank By',+ name: 'rankBy',+ type: 'options',+ options: [+ { name: 'Prominence (Default)', value: 'prominence' },+ { name: 'Distance', value: 'distance' }+ ],+ default: 'prominence',+ description: 'How to rank the results. When using distance, radius parameter is ignored.'+ },+ {+ displayName: 'Page Size',+ name: 'pageSize',+ type: 'number',+ typeOptions: { minValue: 1, maxValue: 20 },+ default: 20,+ description: 'Number of results per page (max 20)'+ }+ ] as any+ }+ ]+ }+};++// List of Google Maps node types for easy identification+export const LOCATION_NODE_TYPES = ['createMap', 'addLocations', 'showNearbyPlaces'];\ No newline at end of filediff --git a/client/src/nodeDefinitions/schedulerNodes.ts b/client/src/nodeDefinitions/schedulerNodes.tsnew file mode 100644index 00000000..c4748b19--- /dev/null+++ b/client/src/nodeDefinitions/schedulerNodes.ts@@ -0,0 +1,220 @@+// Scheduler Nodes - Time-based workflow triggers+import { INodeTypeDescription, NodeConnectionType } from '../types/INodeProperties';++export const schedulerNodes: Record<string, INodeTypeDescription> = {+ // Timer node - Simple delay/wait before proceeding+ timer: {+ displayName: 'Timer',+ name: 'timer',+ icon: '⏱️',+ group: ['utility', 'workflow'],+ version: 1,+ subtitle: '={{$parameter["duration"]}} {{$parameter["unit"]}}',+ description: 'Wait for a specified duration before continuing',+ defaults: { name: 'Timer', color: '#10b981' },+ inputs: [{+ name: 'main',+ displayName: 'Input',+ type: 'main' as NodeConnectionType,+ description: 'Trigger to start timer'+ }],+ outputs: [{+ name: 'main',+ displayName: 'Output',+ type: 'main' as NodeConnectionType,+ description: 'timestamp, elapsed_ms, duration, unit'+ }],+ properties: [+ {+ displayName: 'Duration',+ name: 'duration',+ type: 'number',+ default: 5,+ required: true,+ description: 'How long to wait',+ typeOptions: {+ minValue: 1,+ maxValue: 3600+ }+ },+ {+ displayName: 'Unit',+ name: 'unit',+ type: 'options',+ default: 'seconds',+ options: [+ { name: 'Seconds', value: 'seconds' },+ { name: 'Minutes', value: 'minutes' },+ { name: 'Hours', value: 'hours' }+ ],+ description: 'Time unit for duration'+ }+ ]+ },++ // Cron Scheduler - Recurring scheduled execution+ cronScheduler: {+ displayName: 'Cron Scheduler',+ name: 'cronScheduler',+ icon: '⏰',+ group: ['trigger', 'workflow'],+ version: 1,+ subtitle: '={{$parameter["frequency"]}}',+ description: 'Trigger workflow execution on a schedule',+ defaults: { name: 'Cron Scheduler', color: '#6366f1' },+ inputs: [],+ outputs: [{+ name: 'main',+ displayName: 'Trigger',+ type: 'main' as NodeConnectionType,+ description: 'timestamp, iteration, scheduled_time, next_run'+ }],+ properties: [+ // Duration Type+ {+ displayName: 'Duration',+ name: 'frequency',+ type: 'options',+ default: 'minutes',+ options: [+ { name: 'Seconds', value: 'seconds' },+ { name: 'Minutes', value: 'minutes' },+ { name: 'Hours', value: 'hours' },+ { name: 'Days', value: 'days' },+ { name: 'Weeks', value: 'weeks' },+ { name: 'Months', value: 'months' },+ { name: 'Once (No Repeat)', value: 'once' },+ ],+ description: 'Wait duration before triggering'+ },+ // Interval for seconds/minutes/hours+ {+ displayName: 'Interval',+ name: 'interval',+ type: 'number',+ default: 30,+ description: 'Run every X seconds (5-59)',+ displayOptions: { show: { frequency: ['seconds'] } }+ },+ {+ displayName: 'Interval',+ name: 'intervalMinutes',+ type: 'number',+ default: 5,+ description: 'Run every X minutes (1-59)',+ displayOptions: { show: { frequency: ['minutes'] } }+ },+ {+ displayName: 'Interval',+ name: 'intervalHours',+ type: 'number',+ default: 1,+ description: 'Run every X hours (1-23)',+ displayOptions: { show: { frequency: ['hours'] } }+ },+ // Time for daily+ {+ displayName: 'At Time',+ name: 'dailyTime',+ type: 'options',+ default: '09:00',+ options: [+ { name: '00:00 (Midnight)', value: '00:00' },+ { name: '06:00', value: '06:00' },+ { name: '08:00', value: '08:00' },+ { name: '09:00', value: '09:00' },+ { name: '10:00', value: '10:00' },+ { name: '12:00 (Noon)', value: '12:00' },+ { name: '14:00', value: '14:00' },+ { name: '16:00', value: '16:00' },+ { name: '18:00', value: '18:00' },+ { name: '20:00', value: '20:00' },+ { name: '22:00', value: '22:00' },+ ],+ description: 'Time to run daily',+ displayOptions: { show: { frequency: ['days'] } }+ },+ // Weekday + Time for weekly+ {+ displayName: 'On Day',+ name: 'weekday',+ type: 'options',+ default: '1',+ options: [+ { name: 'Sunday', value: '0' },+ { name: 'Monday', value: '1' },+ { name: 'Tuesday', value: '2' },+ { name: 'Wednesday', value: '3' },+ { name: 'Thursday', value: '4' },+ { name: 'Friday', value: '5' },+ { name: 'Saturday', value: '6' },+ ],+ description: 'Day of week',+ displayOptions: { show: { frequency: ['weeks'] } }+ },+ {+ displayName: 'At Time',+ name: 'weeklyTime',+ type: 'options',+ default: '09:00',+ options: [+ { name: '00:00 (Midnight)', value: '00:00' },+ { name: '06:00', value: '06:00' },+ { name: '08:00', value: '08:00' },+ { name: '09:00', value: '09:00' },+ { name: '12:00 (Noon)', value: '12:00' },+ { name: '18:00', value: '18:00' },+ ],+ description: 'Time to run',+ displayOptions: { show: { frequency: ['weeks'] } }+ },+ // Day of month + Time for monthly+ {+ displayName: 'On Day',+ name: 'monthDay',+ type: 'options',+ default: '1',+ options: [+ ...Array.from({ length: 28 }, (_, i) => ({ name: `${i + 1}`, value: String(i + 1) })),+ { name: 'Last day', value: 'L' },+ ],+ description: 'Day of month',+ displayOptions: { show: { frequency: ['months'] } }+ },+ {+ displayName: 'At Time',+ name: 'monthlyTime',+ type: 'options',+ default: '09:00',+ options: [+ { name: '00:00 (Midnight)', value: '00:00' },+ { name: '06:00', value: '06:00' },+ { name: '09:00', value: '09:00' },+ { name: '12:00 (Noon)', value: '12:00' },+ { name: '18:00', value: '18:00' },+ ],+ description: 'Time to run',+ displayOptions: { show: { frequency: ['months'] } }+ },+ // Timezone for schedule+ {+ displayName: 'Timezone',+ name: 'timezone',+ type: 'options',+ default: 'UTC',+ options: [+ { name: 'UTC', value: 'UTC' },+ { name: 'US Eastern', value: 'America/New_York' },+ { name: 'US Pacific', value: 'America/Los_Angeles' },+ { name: 'UK', value: 'Europe/London' },+ { name: 'Europe Central', value: 'Europe/Paris' },+ { name: 'Japan', value: 'Asia/Tokyo' },+ { name: 'India', value: 'Asia/Kolkata' },+ ],+ description: 'Timezone for schedule'+ }+ ]+ }+};++export const SCHEDULER_NODE_TYPES = ['timer', 'cronScheduler'];diff --git a/client/src/nodeDefinitions/utilityNodes.ts b/client/src/nodeDefinitions/utilityNodes.tsnew file mode 100644index 00000000..0335ebee--- /dev/null+++ b/client/src/nodeDefinitions/utilityNodes.ts@@ -0,0 +1,186 @@+// Utility Nodes - HTTP Request, Webhooks+import {+ INodeTypeDescription,+ NodeConnectionType+} from '../types/INodeProperties';++export const utilityNodes: Record<string, INodeTypeDescription> = {+ httpRequest: {+ displayName: 'HTTP Request',+ name: 'httpRequest',+ icon: '🌐',+ group: ['utility'],+ version: 1,+ description: 'Make HTTP requests to external APIs',+ defaults: { name: 'HTTP Request', color: '#6366f1' },+ inputs: [{ name: 'main', displayName: 'Input', type: 'main' as NodeConnectionType, description: 'Trigger input' }],+ outputs: [{+ name: 'main',+ displayName: 'Response',+ type: 'main' as NodeConnectionType,+ description: 'status, data, headers'+ }],+ properties: [+ {+ displayName: 'Method',+ name: 'method',+ type: 'options',+ default: 'GET',+ options: [+ { name: 'GET', value: 'GET' },+ { name: 'POST', value: 'POST' },+ { name: 'PUT', value: 'PUT' },+ { name: 'DELETE', value: 'DELETE' },+ { name: 'PATCH', value: 'PATCH' }+ ]+ },+ {+ displayName: 'URL',+ name: 'url',+ type: 'string',+ default: '',+ required: true,+ placeholder: 'https://api.example.com/endpoint'+ },+ {+ displayName: 'Headers',+ name: 'headers',+ type: 'string',+ default: '{}',+ typeOptions: { rows: 3 },+ placeholder: '{"Authorization": "Bearer token"}'+ },+ {+ displayName: 'Body',+ name: 'body',+ type: 'string',+ default: '',+ typeOptions: { rows: 4 },+ placeholder: '{"key": "value"}',+ displayOptions: { show: { method: ['POST', 'PUT', 'PATCH'] } }+ },+ {+ displayName: 'Timeout (seconds)',+ name: 'timeout',+ type: 'number',+ default: 30+ }+ ]+ },++ webhookTrigger: {+ displayName: 'Webhook Trigger',+ name: 'webhookTrigger',+ icon: '🪝',+ group: ['trigger'],+ version: 1,+ description: 'Start workflow when HTTP request is received',+ defaults: { name: 'Webhook', color: '#f59e0b' },+ inputs: [],+ outputs: [{+ name: 'main',+ displayName: 'Request',+ type: 'main' as NodeConnectionType,+ description: 'method, path, headers, query, body, json'+ }],+ properties: [+ {+ displayName: 'Path',+ name: 'path',+ type: 'string',+ default: '',+ required: true,+ placeholder: 'my-webhook',+ description: 'URL: http://localhost:3010/webhook/{path}'+ },+ {+ displayName: 'HTTP Method',+ name: 'method',+ type: 'options',+ default: 'POST',+ options: [+ { name: 'GET', value: 'GET' },+ { name: 'POST', value: 'POST' },+ { name: 'PUT', value: 'PUT' },+ { name: 'DELETE', value: 'DELETE' },+ { name: 'Any', value: 'ALL' }+ ]+ },+ {+ displayName: 'Response Mode',+ name: 'responseMode',+ type: 'options',+ default: 'immediate',+ options: [+ { name: 'Immediate (200 OK)', value: 'immediate' },+ { name: 'Wait for Response Node', value: 'responseNode' }+ ]+ },+ {+ displayName: 'Authentication',+ name: 'authentication',+ type: 'options',+ default: 'none',+ options: [+ { name: 'None', value: 'none' },+ { name: 'Header Auth', value: 'header' }+ ]+ },+ {+ displayName: 'Header Name',+ name: 'headerName',+ type: 'string',+ default: 'X-API-Key',+ displayOptions: { show: { authentication: ['header'] } }+ },+ {+ displayName: 'Header Value',+ name: 'headerValue',+ type: 'string',+ default: '',+ displayOptions: { show: { authentication: ['header'] } }+ }+ ]+ },++ webhookResponse: {+ displayName: 'Webhook Response',+ name: 'webhookResponse',+ icon: '↩️',+ group: ['utility'],+ version: 1,+ description: 'Send response back to webhook caller',+ defaults: { name: 'Response', color: '#10b981' },+ inputs: [{ name: 'main', displayName: 'Input', type: 'main' as NodeConnectionType, description: 'Trigger input' }],+ outputs: [],+ properties: [+ {+ displayName: 'Status Code',+ name: 'statusCode',+ type: 'number',+ default: 200+ },+ {+ displayName: 'Response Body',+ name: 'responseBody',+ type: 'string',+ default: '',+ typeOptions: { rows: 4 },+ placeholder: '{"success": true, "data": ...}'+ },+ {+ displayName: 'Content Type',+ name: 'contentType',+ type: 'options',+ default: 'application/json',+ options: [+ { name: 'JSON', value: 'application/json' },+ { name: 'Text', value: 'text/plain' },+ { name: 'HTML', value: 'text/html' }+ ]+ }+ ]+ }+};++export const UTILITY_NODE_TYPES = ['httpRequest', 'webhookTrigger', 'webhookResponse'];diff --git a/client/src/nodeDefinitions/whatsappNodes.ts b/client/src/nodeDefinitions/whatsappNodes.tsnew file mode 100644index 00000000..3573124d--- /dev/null+++ b/client/src/nodeDefinitions/whatsappNodes.ts@@ -0,0 +1,617 @@+// WhatsApp Node Definitions - Messaging integration via whatsmeow+import {+ INodeTypeDescription,+ NodeConnectionType+} from '../types/INodeProperties';+import { API_CONFIG } from '../config/api';++// Get WebSocket URL dynamically based on environment+const getWebSocketUrl = (): string => {+ const baseUrl = API_CONFIG.PYTHON_BASE_URL;++ // Production: empty base URL means use current origin+ if (!baseUrl) {+ const wsProtocol = window.location.protocol === 'https:' ? 'wss' : 'ws';+ return `${wsProtocol}://${window.location.host}/ws/status`;+ }++ // Development: convert http(s) to ws(s)+ const wsProtocol = baseUrl.startsWith('https') ? 'wss' : 'ws';+ const wsUrl = baseUrl.replace(/^https?/, wsProtocol);+ return `${wsUrl}/ws/status`;+};++// Helper to make WebSocket requests+async function wsRequest(type: string, data: Record<string, unknown> = {}): Promise<unknown> {+ return new Promise((resolve, reject) => {+ const ws = new WebSocket(getWebSocketUrl());+ const timeout = setTimeout(() => {+ ws.close();+ reject(new Error('WebSocket request timeout'));+ }, 10000);++ ws.onopen = () => {+ ws.send(JSON.stringify({ type, ...data }));+ };++ ws.onmessage = (event) => {+ clearTimeout(timeout);+ try {+ const response = JSON.parse(event.data);+ ws.close();+ resolve(response);+ } catch (e) {+ ws.close();+ reject(e);+ }+ };++ ws.onerror = (error) => {+ clearTimeout(timeout);+ ws.close();+ reject(error);+ };+ });+}++// ============================================================================+// WHATSAPP ICONS (SVG Data URIs)+// ============================================================================++// WhatsApp Send - Paper plane (send message)+const WHATSAPP_SEND_ICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%2325D366'%3E%3Cpath d='M2.01 21L23 12 2.01 3 2 10l15 2-15 2z'/%3E%3C/svg%3E";++// WhatsApp Connect - Official WhatsApp logo+const WHATSAPP_CONNECT_ICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%2325D366'%3E%3Cpath d='M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z'/%3E%3C/svg%3E";++// WhatsApp Receive - Notification bell with dot (trigger node)+const WHATSAPP_RECEIVE_ICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%2325D366'%3E%3Cpath d='M12 22c1.1 0 2-.9 2-2h-4c0 1.1.9 2 2 2zm6-6v-5c0-3.07-1.63-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.64 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2zm-2 1H8v-6c0-2.48 1.51-4.5 4-4.5s4 2.02 4 4.5v6z'/%3E%3Ccircle cx='18' cy='6' r='4'/%3E%3C/svg%3E";++// ============================================================================+// WHATSAPP NODES+// ============================================================================++export const whatsappNodes: Record<string, INodeTypeDescription> = {+ // WhatsApp Send Message Node - Enhanced with full schema support+ whatsappSend: {+ displayName: 'WhatsApp Send',+ name: 'whatsappSend',+ icon: WHATSAPP_SEND_ICON,+ group: ['whatsapp'],+ version: 1,+ subtitle: 'Send WhatsApp Message',+ description: 'Send text, media, location, or contact messages via WhatsApp',+ defaults: { name: 'WhatsApp Send', color: '#25D366' },+ inputs: [{+ name: 'main',+ displayName: 'Input',+ type: 'main' as NodeConnectionType,+ description: 'Message input'+ }],+ outputs: [{+ name: 'main',+ displayName: 'Output',+ type: 'main' as NodeConnectionType,+ description: 'Message output'+ }],+ properties: [+ // ===== RECIPIENT =====+ {+ displayName: 'Send To',+ name: 'recipientType',+ type: 'options',+ options: [+ { name: 'Phone Number', value: 'phone' },+ { name: 'Group', value: 'group' }+ ],+ default: 'phone',+ description: 'Send to individual or group'+ },+ {+ displayName: 'Phone Number',+ name: 'phone',+ type: 'string',+ default: '',+ required: true,+ placeholder: '1234567890',+ description: 'Recipient phone number (without + prefix)',+ displayOptions: {+ show: { recipientType: ['phone'] }+ }+ },+ {+ displayName: 'Group',+ name: 'group_id',+ type: 'string',+ default: '',+ required: true,+ placeholder: '[email protected]',+ description: 'Group JID to send message to (use Load button to select)',+ displayOptions: {+ show: { recipientType: ['group'] }+ }+ },++ // ===== MESSAGE TYPE =====+ {+ displayName: 'Message Type',+ name: 'messageType',+ type: 'options',+ options: [+ { name: 'Text', value: 'text' },+ { name: 'Image', value: 'image' },+ { name: 'Video', value: 'video' },+ { name: 'Audio', value: 'audio' },+ { name: 'Document', value: 'document' },+ { name: 'Sticker', value: 'sticker' },+ { name: 'Location', value: 'location' },+ { name: 'Contact', value: 'contact' }+ ],+ default: 'text',+ description: 'Type of message to send'+ },++ // ===== TEXT MESSAGE =====+ {+ displayName: 'Message',+ name: 'message',+ type: 'string',+ default: '',+ required: true,+ typeOptions: { rows: 4 },+ description: 'Text message content',+ placeholder: 'Enter your message...',+ displayOptions: {+ show: { messageType: ['text'] }+ }+ },++ // ===== MEDIA MESSAGES (image, video, audio, document, sticker) =====+ {+ displayName: 'Media Source',+ name: 'mediaSource',+ type: 'options',+ options: [+ { name: 'Base64 Data', value: 'base64' },+ { name: 'File Path', value: 'file' },+ { name: 'URL', value: 'url' }+ ],+ default: 'base64',+ description: 'Source of media data',+ displayOptions: {+ show: { messageType: ['image', 'video', 'audio', 'document', 'sticker'] }+ }+ },+ {+ displayName: 'Media Data (Base64)',+ name: 'mediaData',+ type: 'string',+ default: '',+ required: true,+ typeOptions: { rows: 3 },+ description: 'Base64-encoded media data',+ displayOptions: {+ show: { messageType: ['image', 'video', 'audio', 'document', 'sticker'], mediaSource: ['base64'] }+ }+ },+ {+ displayName: 'File',+ name: 'filePath',+ type: 'file',+ default: '',+ required: true,+ placeholder: '/path/to/file.jpg',+ description: 'Upload a file or enter server path',+ typeOptions: {+ accept: '*/*'+ },+ displayOptions: {+ show: { messageType: ['image', 'video', 'audio', 'document', 'sticker'], mediaSource: ['file'] }+ }+ },+ {+ displayName: 'Media URL',+ name: 'mediaUrl',+ type: 'string',+ default: '',+ required: true,+ placeholder: 'https://example.com/image.jpg',+ description: 'URL to download media from',+ displayOptions: {+ show: { messageType: ['image', 'video', 'audio', 'document', 'sticker'], mediaSource: ['url'] }+ }+ },+ {+ displayName: 'MIME Type',+ name: 'mimeType',+ type: 'string',+ default: '',+ placeholder: 'image/jpeg, video/mp4, audio/ogg',+ description: 'MIME type of the media (auto-detected if empty)',+ displayOptions: {+ show: { messageType: ['image', 'video', 'audio', 'document', 'sticker'] }+ }+ },+ {+ displayName: 'Caption',+ name: 'caption',+ type: 'string',+ default: '',+ typeOptions: { rows: 2 },+ description: 'Optional caption for media',+ displayOptions: {+ show: { messageType: ['image', 'video', 'document'] }+ }+ },+ {+ displayName: 'Filename',+ name: 'filename',+ type: 'string',+ default: '',+ placeholder: 'document.pdf',+ description: 'Filename for document',+ displayOptions: {+ show: { messageType: ['document'] }+ }+ },++ // ===== LOCATION MESSAGE =====+ {+ displayName: 'Latitude',+ name: 'latitude',+ type: 'number',+ default: 0,+ required: true,+ description: 'Location latitude',+ displayOptions: {+ show: { messageType: ['location'] }+ }+ },+ {+ displayName: 'Longitude',+ name: 'longitude',+ type: 'number',+ default: 0,+ required: true,+ description: 'Location longitude',+ displayOptions: {+ show: { messageType: ['location'] }+ }+ },+ {+ displayName: 'Location Name',+ name: 'locationName',+ type: 'string',+ default: '',+ placeholder: 'San Francisco',+ description: 'Display name for location',+ displayOptions: {+ show: { messageType: ['location'] }+ }+ },+ {+ displayName: 'Address',+ name: 'address',+ type: 'string',+ default: '',+ placeholder: 'California, USA',+ description: 'Address text',+ displayOptions: {+ show: { messageType: ['location'] }+ }+ },++ // ===== CONTACT MESSAGE =====+ {+ displayName: 'Contact Name',+ name: 'contactName',+ type: 'string',+ default: '',+ required: true,+ placeholder: 'John Doe',+ description: 'Display name for contact',+ displayOptions: {+ show: { messageType: ['contact'] }+ }+ },+ {+ displayName: 'Contact vCard',+ name: 'vcard',+ type: 'string',+ default: '',+ required: true,+ typeOptions: { rows: 4 },+ placeholder: 'BEGIN:VCARD\nVERSION:3.0\nFN:John Doe\nTEL:+1234567890\nEND:VCARD',+ description: 'vCard 3.0 format string',+ displayOptions: {+ show: { messageType: ['contact'] }+ }+ },++ // ===== REPLY (QUOTE) =====+ {+ displayName: 'Reply To Message',+ name: 'isReply',+ type: 'boolean',+ default: false,+ description: 'Quote an existing message'+ },+ {+ displayName: 'Reply Message ID',+ name: 'replyMessageId',+ type: 'string',+ default: '',+ required: true,+ placeholder: 'ABC123DEF456',+ description: 'ID of message to reply to',+ displayOptions: {+ show: { isReply: [true] }+ }+ },+ {+ displayName: 'Reply Sender',+ name: 'replySender',+ type: 'string',+ default: '',+ required: true,+ placeholder: '[email protected]',+ description: 'Sender JID of quoted message',+ displayOptions: {+ show: { isReply: [true] }+ }+ },+ {+ displayName: 'Reply Preview',+ name: 'replyContent',+ type: 'string',+ default: '',+ placeholder: 'Original message text...',+ description: 'Text preview of quoted message',+ displayOptions: {+ show: { isReply: [true] }+ }+ }+ ]+ },++ // WhatsApp Connection/Auth Node+ whatsappConnect: {+ displayName: 'WhatsApp Connect',+ name: 'whatsappConnect',+ icon: WHATSAPP_CONNECT_ICON,+ group: ['whatsapp'],+ version: 1,+ subtitle: 'WhatsApp Status',+ description: 'Check WhatsApp connection status (QR code authentication removed - use external WhatsApp service)',+ defaults: { name: 'WhatsApp Connect', color: '#128C7E' },+ inputs: [],+ outputs: [{+ name: 'main',+ displayName: 'Output',+ type: 'main' as NodeConnectionType,+ description: 'Connection output'+ }],+ properties: [+ {+ displayName: 'Connection Type',+ name: 'connectionType',+ type: 'options',+ options: [+ {+ name: 'Scan QR Code',+ value: 'qr_code'+ },+ {+ name: 'Use Existing Session',+ value: 'existing'+ }+ ],+ default: 'qr_code',+ description: 'How to connect to WhatsApp'+ },+ {+ displayName: 'Session Info',+ name: 'sessionInfo',+ type: 'notice',+ default: 'Session will persist across workflow runs. Re-authentication required approximately every 20 days.'+ }+ ]+ },++ // WhatsApp Receive Message - triggers workflow on incoming messages+ whatsappReceive: {+ displayName: 'WhatsApp Receive',+ name: 'whatsappReceive',+ icon: WHATSAPP_RECEIVE_ICON,+ group: ['whatsapp', 'trigger'],+ version: 1,+ subtitle: 'On Message Received',+ description: 'Trigger workflow when WhatsApp message is received. Outputs message data including sender, content, and metadata.',+ defaults: { name: 'WhatsApp Receive', color: '#075E54' },+ inputs: [],+ outputs: [{+ name: 'main',+ displayName: 'Message',+ type: 'main' as NodeConnectionType,+ description: 'Received message data (message_id, sender, sender_phone, chat_id, message_type, text, timestamp, is_group, is_from_me, group_info.sender_jid, group_info.sender_phone, group_info.sender_name)'+ }],+ properties: [+ // ===== MESSAGE TYPE FILTER =====+ {+ displayName: 'Message Type',+ name: 'messageTypeFilter',+ type: 'options',+ options: [+ { name: 'All Types', value: 'all' },+ { name: 'Text Only', value: 'text' },+ { name: 'Image Only', value: 'image' },+ { name: 'Video Only', value: 'video' },+ { name: 'Audio Only', value: 'audio' },+ { name: 'Document Only', value: 'document' },+ { name: 'Location Only', value: 'location' },+ { name: 'Contact Only', value: 'contact' }+ ],+ default: 'all',+ description: 'Filter by message content type'+ },++ // ===== SENDER FILTER =====+ {+ displayName: 'Sender Filter',+ name: 'filter',+ type: 'options',+ options: [+ { name: 'All Messages', value: 'all' },+ { name: 'From Any Contact (Non-Group)', value: 'any_contact' },+ { name: 'From Specific Contact', value: 'contact' },+ { name: 'From Specific Group', value: 'group' },+ { name: 'Contains Keywords', value: 'keywords' }+ ],+ default: 'all',+ description: 'Filter which messages trigger the workflow'+ },+ {+ displayName: 'Contact Phone',+ name: 'contactPhone',+ type: 'string',+ default: '',+ required: true,+ displayOptions: {+ show: { filter: ['contact'] }+ },+ placeholder: '1234567890',+ description: 'Phone number to filter messages from (without + prefix)'+ },+ {+ displayName: 'Group',+ name: 'group_id',+ type: 'string',+ default: '',+ required: true,+ displayOptions: {+ show: { filter: ['group'] }+ },+ placeholder: '[email protected]',+ description: 'Group JID to filter messages from (use Load button to select)'+ },+ {+ displayName: 'Sender Number',+ name: 'senderNumber',+ type: 'string',+ default: '',+ displayOptions: {+ show: { filter: ['group'] }+ },+ placeholder: '1234567890',+ description: 'Optional: Filter by sender phone number (use Load button to select from group members)'+ },+ {+ displayName: 'Keywords',+ name: 'keywords',+ type: 'string',+ default: '',+ required: true,+ displayOptions: {+ show: { filter: ['keywords'] }+ },+ placeholder: 'help, support, info',+ description: 'Comma-separated keywords to trigger on (case-insensitive)'+ },++ // ===== OPTIONS =====+ {+ displayName: 'Ignore Own Messages',+ name: 'ignoreOwnMessages',+ type: 'boolean',+ default: true,+ description: 'Do not trigger on messages sent by this device'+ },+ {+ displayName: 'Forwarded Messages',+ name: 'forwardedFilter',+ type: 'options',+ options: [+ { name: 'Include All', value: 'all' },+ { name: 'Only Forwarded', value: 'only_forwarded' },+ { name: 'Ignore Forwarded', value: 'ignore_forwarded' }+ ],+ default: 'all',+ description: 'Filter messages based on forwarded status'+ },+ {+ displayName: 'Include Media Data',+ name: 'includeMediaData',+ type: 'boolean',+ default: false,+ description: 'Include base64 media data in output (increases memory usage)'+ }+ ],+ methods: {+ loadOptions: {+ async getWhatsAppGroups(): Promise<Array<{name: string, value: string, description?: string}>> {+ try {+ const response = await wsRequest('whatsapp_groups') as { success: boolean; groups?: Array<{ jid: string; name: string; participant_count?: number }> };++ if (response.success && response.groups) {+ return response.groups.map((group) => ({+ name: group.name || group.jid,+ value: group.jid,+ description: group.participant_count ? `${group.participant_count} members` : undefined+ }));+ }+ return [{ name: 'No groups found', value: '', description: 'Connect WhatsApp first' }];+ } catch (error) {+ console.error('Error loading WhatsApp groups:', error);+ return [{ name: 'Error loading groups', value: '', description: 'Check WhatsApp connection' }];+ }+ },++ async getGroupMembers(this: { getCurrentNodeParameter: (name: string) => string }): Promise<Array<{name: string, value: string, description?: string}>> {+ try {+ const groupId = this.getCurrentNodeParameter('group_id');+ if (!groupId) {+ return [{ name: 'Select a group first', value: '', description: 'Choose a group above' }];+ }++ const response = await wsRequest('whatsapp_group_info', { group_id: groupId }) as {+ success: boolean;+ participants?: Array<{ phone: string; name: string; jid: string; is_admin?: boolean }>;+ name?: string;+ };++ if (response.success && response.participants && response.participants.length > 0) {+ // Add "All Members" option first+ const options: Array<{name: string, value: string, description?: string}> = [+ { name: 'All Members', value: '', description: 'Receive from anyone in group' }+ ];++ // Add each participant+ for (const p of response.participants) {+ const displayName = p.name || p.phone;+ const adminLabel = p.is_admin ? ' (Admin)' : '';+ options.push({+ name: `${displayName}${adminLabel}`,+ value: p.phone,+ description: p.phone+ });+ }++ return options;+ }++ return [{ name: 'No members found', value: '', description: 'Could not load group members' }];+ } catch (error) {+ console.error('Error loading group members:', error);+ return [{ name: 'Error loading members', value: '', description: 'Check WhatsApp connection' }];+ }+ }+ }+ }+ }+};++// ============================================================================+// EXPORTS+// ============================================================================++export const WHATSAPP_NODE_TYPES = ['whatsappSend', 'whatsappConnect', 'whatsappReceive'];diff --git a/client/src/nodeDefinitions/workflowNodes.ts b/client/src/nodeDefinitions/workflowNodes.tsnew file mode 100644index 00000000..5f050a06--- /dev/null+++ b/client/src/nodeDefinitions/workflowNodes.ts@@ -0,0 +1,41 @@+// Workflow Control Nodes - Start, triggers, and flow control+import {+ INodeTypeDescription,+ NodeConnectionType+} from '../types/INodeProperties';++export const workflowNodes: Record<string, INodeTypeDescription> = {+ // Start Node - Entry point for workflows+ start: {+ displayName: 'Start',+ name: 'start',+ icon: '▶',+ group: ['workflow'],+ version: 1,+ subtitle: 'Workflow Entry',+ description: 'Starting point for workflow execution. Provides initial data to connected nodes.',+ defaults: { name: 'Start', color: '#8be9fd' },+ inputs: [],+ outputs: [{+ name: 'main',+ displayName: 'Output',+ type: 'main' as NodeConnectionType,+ description: 'Workflow start output'+ }],+ properties: [+ {+ displayName: 'Initial Data',+ name: 'initialData',+ type: 'string',+ default: '{}',+ typeOptions: {+ rows: 6+ },+ description: 'JSON data to pass to connected nodes',+ placeholder: '{\n "message": "Hello World",\n "value": 123\n}'+ }+ ]+ }+};++export const WORKFLOW_NODE_TYPES = ['start'];diff --git a/client/src/schemas/workflowSchema.ts b/client/src/schemas/workflowSchema.tsnew file mode 100644index 00000000..554043ce--- /dev/null+++ b/client/src/schemas/workflowSchema.ts@@ -0,0 +1,264 @@+/**+ * JSON Schema for Workflow Definition+ * Defines the structure and validation rules for workflow data+ */++export const WorkflowJSONSchema = {+ $schema: "http://json-schema.org/draft-07/schema#",+ title: "Workflow",+ description: "A workflow automation definition containing nodes and connections",+ type: "object",+ required: ["id", "name", "nodes", "edges", "createdAt", "lastModified"],+ properties: {+ id: {+ type: "string",+ description: "Unique identifier for the workflow",+ pattern: "^workflow_[0-9]+$"+ },+ name: {+ type: "string",+ description: "Human-readable workflow name",+ minLength: 1,+ maxLength: 100+ },+ description: {+ type: "string",+ description: "Optional workflow description"+ },+ nodes: {+ type: "array",+ description: "Array of workflow nodes",+ items: {+ $ref: "#/definitions/node"+ }+ },+ edges: {+ type: "array",+ description: "Array of connections between nodes",+ items: {+ $ref: "#/definitions/edge"+ }+ },+ createdAt: {+ type: "string",+ format: "date-time",+ description: "ISO 8601 timestamp of workflow creation"+ },+ lastModified: {+ type: "string",+ format: "date-time",+ description: "ISO 8601 timestamp of last modification"+ },+ version: {+ type: "string",+ description: "Workflow schema version",+ default: "1.0.0"+ }+ },+ definitions: {+ node: {+ type: "object",+ required: ["id", "type", "position"],+ properties: {+ id: {+ type: "string",+ description: "Unique node identifier"+ },+ type: {+ type: "string",+ description: "Node type identifier",+ enum: [+ "start",+ "aiAgent",+ "openaiChatModel",+ "anthropicChatModel",+ "googleChatModel",+ "createMap",+ "addLocations",+ "showNearbyPlaces",+ "whatsappSendMessage",+ "whatsappReceiveMessage"+ ]+ },+ position: {+ type: "object",+ required: ["x", "y"],+ properties: {+ x: {+ type: "number",+ description: "X coordinate on canvas"+ },+ y: {+ type: "number",+ description: "Y coordinate on canvas"+ }+ }+ },+ data: {+ type: "object",+ description: "Node-specific parameters and configuration",+ properties: {+ label: {+ type: "string",+ description: "Display label for the node"+ }+ },+ additionalProperties: true+ },+ selected: {+ type: "boolean",+ description: "Whether node is currently selected"+ },+ dragging: {+ type: "boolean",+ description: "Whether node is being dragged"+ }+ },+ additionalProperties: true+ },+ edge: {+ type: "object",+ required: ["id", "source", "target"],+ properties: {+ id: {+ type: "string",+ description: "Unique edge identifier"+ },+ source: {+ type: "string",+ description: "Source node ID"+ },+ target: {+ type: "string",+ description: "Target node ID"+ },+ sourceHandle: {+ type: "string",+ description: "Source handle identifier",+ default: "output-main"+ },+ targetHandle: {+ type: "string",+ description: "Target handle identifier",+ default: "input-main"+ },+ type: {+ type: "string",+ description: "Edge rendering type",+ enum: ["default", "straight", "step", "smoothstep", "simplebezier"],+ default: "default"+ },+ animated: {+ type: "boolean",+ description: "Whether edge is animated"+ },+ style: {+ type: "object",+ description: "Custom edge styling"+ },+ label: {+ type: "string",+ description: "Edge label text"+ }+ },+ additionalProperties: true+ }+ }+};++/**+ * Validates a workflow object against the JSON schema+ */+export function validateWorkflow(workflow: any): { valid: boolean; errors: string[] } {+ const errors: string[] = [];++ if (!workflow.id || typeof workflow.id !== 'string') {+ errors.push('Workflow must have a valid id');+ }++ if (!workflow.name || typeof workflow.name !== 'string') {+ errors.push('Workflow must have a valid name');+ }++ if (!Array.isArray(workflow.nodes)) {+ errors.push('Workflow must have a nodes array');+ }++ if (!Array.isArray(workflow.edges)) {+ errors.push('Workflow must have an edges array');+ }++ if (!workflow.createdAt) {+ errors.push('Workflow must have a createdAt timestamp');+ }++ if (!workflow.lastModified) {+ errors.push('Workflow must have a lastModified timestamp');+ }++ workflow.nodes?.forEach((node: any, index: number) => {+ if (!node.id) {+ errors.push(`Node at index ${index} must have an id`);+ }+ if (!node.type) {+ errors.push(`Node at index ${index} must have a type`);+ }+ if (!node.position || typeof node.position.x !== 'number' || typeof node.position.y !== 'number') {+ errors.push(`Node at index ${index} must have a valid position with x and y coordinates`);+ }+ });++ workflow.edges?.forEach((edge: any, index: number) => {+ if (!edge.id) {+ errors.push(`Edge at index ${index} must have an id`);+ }+ if (!edge.source) {+ errors.push(`Edge at index ${index} must have a source node`);+ }+ if (!edge.target) {+ errors.push(`Edge at index ${index} must have a target node`);+ }++ const sourceExists = workflow.nodes?.some((n: any) => n.id === edge.source);+ const targetExists = workflow.nodes?.some((n: any) => n.id === edge.target);++ if (!sourceExists) {+ errors.push(`Edge ${edge.id} references non-existent source node: ${edge.source}`);+ }+ if (!targetExists) {+ errors.push(`Edge ${edge.id} references non-existent target node: ${edge.target}`);+ }+ });++ return {+ valid: errors.length === 0,+ errors+ };+}++/**+ * Serializes a workflow to JSON format+ */+export function serializeWorkflow(workflow: any): string {+ return JSON.stringify(workflow, null, 2);+}++/**+ * Deserializes a JSON string to workflow object+ */+export function deserializeWorkflow(json: string): any {+ try {+ const workflow = JSON.parse(json);++ if (workflow.createdAt) {+ workflow.createdAt = new Date(workflow.createdAt);+ }+ if (workflow.lastModified) {+ workflow.lastModified = new Date(workflow.lastModified);+ }++ return workflow;+ } catch (error) {+ throw new Error(`Failed to parse workflow JSON: ${error}`);+ }+}diff --git a/client/src/services/dynamicParameterService.ts b/client/src/services/dynamicParameterService.tsnew file mode 100644index 00000000..9995d01e--- /dev/null+++ b/client/src/services/dynamicParameterService.ts@@ -0,0 +1,91 @@+// Dynamic Parameter Service - Manages runtime parameter option updates+import { INodePropertyOption } from '../types/INodeProperties';++interface DynamicParameterOptions {+ [nodeId: string]: {+ [parameterName: string]: INodePropertyOption[];+ };+}++class DynamicParameterService {+ private static dynamicOptions: DynamicParameterOptions = {};+ private static listeners: ((nodeId: string, parameterName: string, options: INodePropertyOption[]) => void)[] = [];++ // Subscribe to dynamic option updates+ static subscribe(callback: (nodeId: string, parameterName: string, options: INodePropertyOption[]) => void) {+ this.listeners.push(callback);+ return () => {+ this.listeners = this.listeners.filter(listener => listener !== callback);+ };+ }++ // Update options for a specific parameter+ static updateParameterOptions(nodeId: string, parameterName: string, options: INodePropertyOption[]) {+ if (!this.dynamicOptions[nodeId]) {+ this.dynamicOptions[nodeId] = {};+ }++ this.dynamicOptions[nodeId][parameterName] = options;++ // Notify all listeners+ this.listeners.forEach((listener) => {+ listener(nodeId, parameterName, options);+ });+ }++ // Get options for a specific parameter+ static getParameterOptions(nodeId: string, parameterName: string): INodePropertyOption[] | null {+ return this.dynamicOptions[nodeId]?.[parameterName] || null;+ }++ // Clear options for a specific parameter+ static clearParameterOptions(nodeId: string, parameterName: string) {+ if (this.dynamicOptions[nodeId]) {+ delete this.dynamicOptions[nodeId][parameterName];++ // Notify listeners with empty array+ this.listeners.forEach(listener => {+ listener(nodeId, parameterName, []);+ });+ }+ }++ // Clear all options for a node+ static clearNodeOptions(nodeId: string) {+ if (this.dynamicOptions[nodeId]) {+ const parameterNames = Object.keys(this.dynamicOptions[nodeId]);+ delete this.dynamicOptions[nodeId];++ // Notify listeners for each parameter+ parameterNames.forEach(parameterName => {+ this.listeners.forEach(listener => {+ listener(nodeId, parameterName, []);+ });+ });+ }+ }++ // Convert model strings to INodePropertyOption format+ static createModelOptions(models: string[]): INodePropertyOption[] {+ return models.map(model => ({+ name: this.formatModelName(model),+ value: model,+ label: this.formatModelName(model),+ description: `Model: ${model}`+ }));+ }++ // Format model name for display+ private static formatModelName(modelId: string): string {+ return modelId+ .replace(/^gpt-/, 'GPT-')+ .replace(/^claude-/, 'Claude ')+ .replace(/^gemini-/, 'Gemini ')+ .replace(/turbo/i, 'Turbo')+ .replace(/^o1-/, 'O1-')+ .replace(/-/g, ' ')+ .replace(/\b\w/g, l => l.toUpperCase());+ }+}++export default DynamicParameterService;\ No newline at end of filediff --git a/client/src/services/execution/aiAgentExecutionService.ts b/client/src/services/execution/aiAgentExecutionService.tsnew file mode 100644index 00000000..8f4ce1a4--- /dev/null+++ b/client/src/services/execution/aiAgentExecutionService.ts@@ -0,0 +1,35 @@+import { ExecutionResult } from '../executionService';++// AI Agent execution result (simplified)+export interface AIAgentExecutionResult extends ExecutionResult {+ aiResponse?: string;+ toolCalls?: any[];+ iterations?: number;+ tokens?: {+ prompt: number;+ completion: number;+ total: number;+ };+}++export class AIAgentExecutionService {+ /**+ * Basic validation for UI feedback - backend handles full validation+ */+ static validateConfiguration(nodeData: any): { valid: boolean; errors: string[] } {+ const errors: string[] = [];++ // Basic required field checks for immediate UI feedback+ if (!nodeData.prompt || nodeData.prompt.trim() === '') {+ errors.push('Prompt is required');+ }++ // Backend handles all complex validation, API keys, etc.+ return {+ valid: errors.length === 0,+ errors+ };+ }+}++export default AIAgentExecutionService;\ No newline at end of filediff --git a/client/src/services/executionService.ts b/client/src/services/executionService.tsnew file mode 100644index 00000000..2e834117--- /dev/null+++ b/client/src/services/executionService.ts@@ -0,0 +1,224 @@+import { nodeDefinitions } from '../nodeDefinitions';+import { ANDROID_SERVICE_NODE_TYPES } from '../nodeDefinitions/androidServiceNodes';+import { ANDROID_DEVICE_NODE_TYPES } from '../nodeDefinitions/androidDeviceNodes';+import { SCHEDULER_NODE_TYPES } from '../nodeDefinitions/schedulerNodes';+import { CODE_NODE_TYPES } from '../nodeDefinitions/codeNodes';+import { UTILITY_NODE_TYPES } from '../nodeDefinitions/utilityNodes';+import { Node, Edge } from 'reactflow';+import { INodeExecutionData } from '../types/INodeProperties';+import { API_CONFIG } from '../config/api';++// Execution result with n8n-compatible data+export interface ExecutionResult {+ success: boolean;+ nodeId: string;+ nodeType: string;+ nodeName: string;+ timestamp: string;+ executionTime: number;+ outputs?: Record<string, any>;+ error?: string;+ data?: any;+ nodeData: INodeExecutionData[][];+}++// WebSocket execution function type (passed from components using useWebSocket)+export type WebSocketExecuteFn = (+ nodeId: string,+ nodeType: string,+ parameters: Record<string, any>,+ nodes?: any[],+ edges?: any[]+) => Promise<any>;++// WebSocket parameter getter type+export type WebSocketGetParametersFn = (nodeId: string) => Promise<{ parameters: Record<string, any> } | null>;++// No frontend cache - backend is single source of truth++// ============================================================================+// EXECUTION SERVICE - Migrated to Python backend+// ============================================================================++export class ExecutionService {+ // ============================================================================+ // WEBSOCKET-BASED EXECUTION - Primary execution method+ // ============================================================================++ /**+ * Execute node via WebSocket (preferred method)+ * Use this when you have access to WebSocket functions from useWebSocket hook+ */+ static async executeNodeViaWebSocket(+ nodeId: string,+ nodeType: string,+ wsExecute: WebSocketExecuteFn,+ wsGetParameters: WebSocketGetParametersFn,+ nodes?: Node[],+ edges?: Edge[]+ ): Promise<ExecutionResult> {+ try {+ console.log(`[WS Execution] Starting: ${nodeId} (type: ${nodeType})`);++ const startTime = Date.now();++ // Load parameters via WebSocket+ const paramsResult = await wsGetParameters(nodeId);+ const parameters = paramsResult?.parameters || {};+ console.log(`[WS Execution] Parameters for ${nodeId}:`, parameters);++ // Prepare nodes and edges+ const nodeData = nodes?.map(node => ({+ id: node.id,+ type: node.type || '',+ data: node.data || {}+ })) || [];++ const edgeData = edges?.map(edge => ({+ id: edge.id,+ source: edge.source,+ target: edge.target,+ sourceHandle: edge.sourceHandle || undefined,+ targetHandle: edge.targetHandle || undefined+ })) || [];++ // Execute via WebSocket+ const result = await wsExecute(nodeId, nodeType, parameters, nodeData, edgeData);++ console.log(`[WS Execution] Result:`, result);++ const executionTime = Date.now() - startTime;++ if (result.success) {+ const outputData = result.result || {+ nodeId,+ success: true,+ message: 'Execution completed successfully',+ timestamp: result.timestamp || new Date().toISOString()+ };++ const nodeExecutionData: INodeExecutionData[][] = [[{+ json: outputData+ }]];++ return {+ success: true,+ nodeId,+ nodeType,+ nodeName: nodeDefinitions[nodeType]?.displayName || nodeType,+ timestamp: result.timestamp || new Date().toISOString(),+ executionTime: result.execution_time || executionTime,+ outputs: outputData,+ data: outputData,+ nodeData: nodeExecutionData+ };+ } else {+ const errorOutputData = result.result || {+ error: result.error,+ nodeId,+ success: false,+ timestamp: result.timestamp || new Date().toISOString()+ };++ const errorData: INodeExecutionData[][] = [[{+ json: errorOutputData+ }]];++ return {+ success: false,+ nodeId,+ nodeType,+ nodeName: nodeDefinitions[nodeType]?.displayName || nodeType,+ timestamp: result.timestamp || new Date().toISOString(),+ executionTime: result.execution_time || executionTime,+ error: result.error,+ outputs: errorOutputData,+ data: errorOutputData,+ nodeData: errorData+ };+ }++ } catch (error: any) {+ console.error(`[WS Execution] Failed for node ${nodeId}:`, error);++ const catchErrorData = {+ error: error.message || 'WebSocket execution failed',+ nodeId,+ success: false,+ timestamp: new Date().toISOString()+ };++ return {+ success: false,+ nodeId,+ nodeType,+ nodeName: nodeDefinitions[nodeType]?.displayName || nodeType,+ timestamp: new Date().toISOString(),+ executionTime: 0,+ error: error.message || 'WebSocket execution failed',+ outputs: catchErrorData,+ data: catchErrorData,+ nodeData: [[{ json: catchErrorData }]]+ };+ }+ }++ // ============================================================================+ // HELPER METHODS+ // ============================================================================++ /**+ * Check backend health status+ */+ static async checkBackendHealth(): Promise<boolean> {+ try {+ const response = await fetch(`${API_CONFIG.PYTHON_BASE_URL}/api/workflow/health`);+ const health = await response.json();+ return health.status === 'OK';+ } catch (error) {+ console.warn('Backend health check failed:', error);+ return false;+ }+ }++ /**+ * Check if node type is supported by backend execution+ */+ static isNodeTypeSupported(nodeType: string): boolean {+ const supportedTypes = [+ // AI Nodes+ 'aiAgent',+ // Note: simpleMemory is passive - accessed by AI Agent automatically, not executed directly+ 'openaiChatModel',+ 'anthropicChatModel',+ 'geminiChatModel',+ 'azure_openaiChatModel', // Planned+ 'cohereChatModel', // Planned+ 'ollamaChatModel', // Planned+ 'mistralChatModel', // Planned+ // Google Maps Nodes+ 'createMap',+ 'addLocations',+ 'showNearbyPlaces',+ // WhatsApp Nodes+ 'whatsappSend',+ 'whatsappConnect',+ 'whatsappReceive',+ // Text Processing Nodes+ 'textGenerator',+ 'fileHandler',+ // Android Services (16 individual nodes)+ ...ANDROID_SERVICE_NODE_TYPES,+ // Android Device Setup+ ...ANDROID_DEVICE_NODE_TYPES,+ // Scheduler Nodes+ ...SCHEDULER_NODE_TYPES,+ // Code Execution Nodes+ ...CODE_NODE_TYPES,+ // Utility Nodes (HTTP, Webhooks)+ ...UTILITY_NODE_TYPES+ ];++ return supportedTypes.includes(nodeType);+ }+}\ No newline at end of filediff --git a/client/src/services/workflowApi.ts b/client/src/services/workflowApi.tsnew file mode 100644index 00000000..5e8e126d--- /dev/null+++ b/client/src/services/workflowApi.ts@@ -0,0 +1,91 @@+/**+ * Workflow API Service+ * Handles workflow CRUD operations with the backend database+ */++import { API_CONFIG } from '../config/api';++const getApiBase = () => `${API_CONFIG.PYTHON_BASE_URL}/api/database`;++export interface WorkflowSummary {+ id: string;+ name: string;+ nodeCount: number;+ createdAt: string;+ lastModified: string;+}++export interface WorkflowData {+ id: string;+ name: string;+ data: {+ nodes: any[];+ edges: any[];+ };+ createdAt: string;+ lastModified: string;+}++export const workflowApi = {+ async saveWorkflow(workflowId: string, name: string, data: { nodes: any[]; edges: any[] }): Promise<boolean> {+ try {+ const response = await fetch(`${getApiBase()}/workflows`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ workflow_id: workflowId, name, data })+ });+ const result = await response.json();+ return result.success;+ } catch (error) {+ console.error('Failed to save workflow:', error);+ return false;+ }+ },++ async getWorkflow(workflowId: string): Promise<WorkflowData | null> {+ try {+ const response = await fetch(`${getApiBase()}/workflows/${workflowId}`, {+ credentials: 'include'+ });+ const result = await response.json();+ if (result.success && result.workflow) {+ return result.workflow;+ }+ return null;+ } catch (error) {+ console.error('Failed to get workflow:', error);+ return null;+ }+ },++ async getAllWorkflows(): Promise<WorkflowSummary[]> {+ try {+ const response = await fetch(`${getApiBase()}/workflows`, {+ credentials: 'include'+ });+ const result = await response.json();+ if (result.success && result.workflows) {+ return result.workflows;+ }+ return [];+ } catch (error) {+ console.error('Failed to get workflows:', error);+ return [];+ }+ },++ async deleteWorkflow(workflowId: string): Promise<boolean> {+ try {+ const response = await fetch(`${getApiBase()}/workflows/${workflowId}`, {+ method: 'DELETE',+ credentials: 'include'+ });+ const result = await response.json();+ return result.success;+ } catch (error) {+ console.error('Failed to delete workflow:', error);+ return false;+ }+ }+};diff --git a/client/src/store/useAppStore.ts b/client/src/store/useAppStore.tsnew file mode 100644index 00000000..6c4ad27b--- /dev/null+++ b/client/src/store/useAppStore.ts@@ -0,0 +1,570 @@+import { create } from 'zustand';+import { Node, Edge } from 'reactflow';+import { SavedWorkflow } from '../components/ui/WorkflowSidebar';+import { generateWorkflowId } from '../utils/workflow';+import { theme } from '../styles/theme';+import {+ exportWorkflowToJSON as exportToJSON,+ exportWorkflowToFile as exportToFile,+ importWorkflowFromJSON as importFromJSON+} from '../utils/workflowExport';+import { workflowApi } from '../services/workflowApi';++export interface WorkflowData {+ nodes: Node[];+ edges: Edge[];+ name: string;+ id: string;+ createdAt: Date;+ lastModified: Date;+}++// Per-workflow UI state (n8n pattern - each workflow has isolated execution state)+export interface WorkflowUIState {+ selectedNodeId: string | null;+ executedNodes: string[]; // Array instead of Set for serialization+ executionOrder: string[];+ isExecuting: boolean;+ viewport?: { x: number; y: number; zoom: number };+}++interface AppStore {+ // Core state - SINGLE source of truth+ currentWorkflow: WorkflowData | null;+ hasUnsavedChanges: boolean;++ // Per-workflow UI state (n8n pattern - isolated per workflow)+ workflowUIStates: Record<string, WorkflowUIState>;++ // Global UI state (not workflow-specific)+ selectedNode: Node | null; // Kept for backward compatibility, derived from workflowUIStates+ sidebarVisible: boolean;+ componentPaletteVisible: boolean;+ whatsappSettingsOpen: boolean;+ androidSettingsOpen: boolean;+ renamingNodeId: string | null;++ // Saved workflows+ savedWorkflows: SavedWorkflow[];++ // Workflow actions+ setCurrentWorkflow: (workflow: WorkflowData) => void;+ updateWorkflow: (updates: Partial<Omit<WorkflowData, 'id' | 'createdAt'>>) => void;+ createNewWorkflow: () => void;+ saveWorkflow: () => Promise<void>;+ loadWorkflow: (id: string) => Promise<void>;+ loadSavedWorkflows: () => Promise<void>;+ deleteWorkflow: (id: string) => Promise<boolean>;+ migrateCurrentWorkflow: () => Promise<void>;++ // UI actions+ setSelectedNode: (node: Node | null) => void;+ toggleSidebar: () => void;+ toggleComponentPalette: () => void;+ setWhatsAppSettingsOpen: (open: boolean) => void;+ setAndroidSettingsOpen: (open: boolean) => void;+ setRenamingNodeId: (nodeId: string | null) => void;++ // Per-workflow UI state actions (n8n pattern)+ getWorkflowUIState: (workflowId: string) => WorkflowUIState;+ setWorkflowExecuting: (workflowId: string, isExecuting: boolean) => void;+ setWorkflowExecutedNodes: (workflowId: string, nodes: string[]) => void;+ setWorkflowExecutionOrder: (workflowId: string, order: string[]) => void;+ setWorkflowViewport: (workflowId: string, viewport: { x: number; y: number; zoom: number }) => void;+ clearWorkflowExecutionState: (workflowId: string) => void;++ // Node/Edge actions (operate on currentWorkflow)+ updateNodeData: (nodeId: string, newData: any) => void;+ updateNodes: (nodes: Node[]) => void;+ updateEdges: (edges: Edge[]) => void;+ addNode: (node: Node) => void;+ removeNodes: (nodeIds: string[]) => void;+ removeEdges: (edgeIds: string[]) => void;++ // Workflow export/import+ exportWorkflowToJSON: () => string;+ exportWorkflowToFile: () => void;+ importWorkflowFromJSON: (jsonString: string) => void;+}++// Helper functions+const createDefaultWorkflow = (): WorkflowData => ({+ id: generateWorkflowId(),+ name: theme.constants.defaultWorkflowName,+ nodes: [],+ edges: [],+ createdAt: new Date(),+ lastModified: new Date(),+});++const createDefaultUIState = (): WorkflowUIState => ({+ selectedNodeId: null,+ executedNodes: [],+ executionOrder: [],+ isExecuting: false,+ viewport: undefined,+});++// Helper to migrate old node types+const migrateNodes = (nodes: Node[]): Node[] => {+ return nodes.map(node => {+ if (node.type === 'googleChatModel') {+ return { ...node, type: 'geminiChatModel' };+ }+ return node;+ });+};++// Storage keys for UI state persistence+const STORAGE_KEYS = {+ sidebarVisible: 'ui_sidebar_visible',+ componentPaletteVisible: 'ui_component_palette_visible',+};++// Helper to load boolean from localStorage+const loadBooleanFromStorage = (key: string, defaultValue: boolean): boolean => {+ try {+ const saved = localStorage.getItem(key);+ if (saved !== null) {+ return saved === 'true';+ }+ } catch {+ // Ignore storage errors+ }+ return defaultValue;+};++// Helper to save boolean to localStorage+const saveBooleanToStorage = (key: string, value: boolean): void => {+ try {+ localStorage.setItem(key, String(value));+ } catch {+ // Ignore storage errors+ }+};++export const useAppStore = create<AppStore>((set, get) => ({+ currentWorkflow: null,+ hasUnsavedChanges: false,+ workflowUIStates: {},+ selectedNode: null,+ sidebarVisible: loadBooleanFromStorage(STORAGE_KEYS.sidebarVisible, true),+ componentPaletteVisible: loadBooleanFromStorage(STORAGE_KEYS.componentPaletteVisible, true),+ whatsappSettingsOpen: false,+ androidSettingsOpen: false,+ renamingNodeId: null,+ savedWorkflows: [],++ // Workflow management+ setCurrentWorkflow: (workflow) => {+ set({ currentWorkflow: workflow, hasUnsavedChanges: false });+ },++ updateWorkflow: (updates) => {+ const current = get().currentWorkflow;+ if (!current) return;++ const updatedWorkflow = {+ ...current,+ ...updates,+ lastModified: new Date(),+ };++ set({+ currentWorkflow: updatedWorkflow,+ hasUnsavedChanges: true,+ });+ },++ createNewWorkflow: () => {+ const newWorkflow = createDefaultWorkflow();+ set({+ currentWorkflow: newWorkflow,+ hasUnsavedChanges: false,+ selectedNode: null,+ });+ },++ saveWorkflow: async () => {+ const { currentWorkflow, savedWorkflows } = get();+ if (!currentWorkflow) return;++ const updatedWorkflow = {+ ...currentWorkflow,+ lastModified: new Date(),+ };++ // Save to database+ const success = await workflowApi.saveWorkflow(+ updatedWorkflow.id,+ updatedWorkflow.name,+ { nodes: updatedWorkflow.nodes, edges: updatedWorkflow.edges }+ );++ if (!success) {+ console.error('Failed to save workflow to database');+ return;+ }++ // Update local saved workflows list+ const existingIndex = savedWorkflows.findIndex(w => w.id === updatedWorkflow.id);++ const workflowSummary: SavedWorkflow = {+ id: updatedWorkflow.id,+ name: updatedWorkflow.name,+ createdAt: updatedWorkflow.createdAt,+ lastModified: updatedWorkflow.lastModified,+ nodeCount: updatedWorkflow.nodes.length,+ };++ let newSavedWorkflows: SavedWorkflow[];+ if (existingIndex >= 0) {+ newSavedWorkflows = [...savedWorkflows];+ newSavedWorkflows[existingIndex] = workflowSummary;+ } else {+ newSavedWorkflows = [workflowSummary, ...savedWorkflows];+ }++ set({+ currentWorkflow: updatedWorkflow,+ savedWorkflows: newSavedWorkflows,+ hasUnsavedChanges: false,+ });+ },++ loadWorkflow: async (id) => {+ const result = await workflowApi.getWorkflow(id);+ if (result) {+ // Migrate old node types+ const nodes = migrateNodes(result.data?.nodes || []);+ const edges = result.data?.edges || [];++ const workflowData: WorkflowData = {+ id: result.id,+ name: result.name,+ nodes,+ edges,+ createdAt: new Date(result.createdAt),+ lastModified: new Date(result.lastModified),+ };++ set({+ currentWorkflow: workflowData,+ hasUnsavedChanges: false,+ selectedNode: null,+ });+ }+ },++ loadSavedWorkflows: async () => {+ const workflows = await workflowApi.getAllWorkflows();+ const savedWorkflows: SavedWorkflow[] = workflows.map(w => ({+ id: w.id,+ name: w.name,+ nodeCount: w.nodeCount,+ createdAt: new Date(w.createdAt),+ lastModified: new Date(w.lastModified),+ }));+ set({ savedWorkflows });+ },++ deleteWorkflow: async (id) => {+ const { currentWorkflow, savedWorkflows } = get();++ const success = await workflowApi.deleteWorkflow(id);+ if (!success) {+ console.error('Failed to delete workflow from database');+ return false;+ }++ // Remove from saved workflows list+ const newSavedWorkflows = savedWorkflows.filter(w => w.id !== id);++ // If deleting current workflow, create a new one+ if (currentWorkflow?.id === id) {+ const newWorkflow = createDefaultWorkflow();+ set({+ currentWorkflow: newWorkflow,+ savedWorkflows: newSavedWorkflows,+ hasUnsavedChanges: false,+ selectedNode: null,+ });+ } else {+ set({ savedWorkflows: newSavedWorkflows });+ }++ return true;+ },++ migrateCurrentWorkflow: async () => {+ const { currentWorkflow } = get();+ if (!currentWorkflow || !currentWorkflow.nodes) return;++ const migratedNodes = migrateNodes(currentWorkflow.nodes);++ const hasChanges = migratedNodes.some((node, idx) =>+ node.type !== currentWorkflow.nodes[idx]?.type+ );++ if (hasChanges) {+ const migratedWorkflow = {+ ...currentWorkflow,+ nodes: migratedNodes+ };++ // Save migrated workflow to database+ await workflowApi.saveWorkflow(+ migratedWorkflow.id,+ migratedWorkflow.name,+ { nodes: migratedWorkflow.nodes, edges: migratedWorkflow.edges }+ );++ set({+ currentWorkflow: migratedWorkflow,+ hasUnsavedChanges: false+ });+ }+ },++ // UI management+ setSelectedNode: (node) => {+ set({ selectedNode: node });+ },++ toggleSidebar: () => {+ set((state) => {+ const newValue = !state.sidebarVisible;+ saveBooleanToStorage(STORAGE_KEYS.sidebarVisible, newValue);+ return { sidebarVisible: newValue };+ });+ },++ toggleComponentPalette: () => {+ set((state) => {+ const newValue = !state.componentPaletteVisible;+ saveBooleanToStorage(STORAGE_KEYS.componentPaletteVisible, newValue);+ return { componentPaletteVisible: newValue };+ });+ },++ setWhatsAppSettingsOpen: (open) => {+ set({ whatsappSettingsOpen: open });+ },++ setAndroidSettingsOpen: (open) => {+ set({ androidSettingsOpen: open });+ },++ setRenamingNodeId: (nodeId) => {+ set({ renamingNodeId: nodeId });+ },++ // Per-workflow UI state management (n8n pattern - isolated execution state per workflow)+ getWorkflowUIState: (workflowId) => {+ const { workflowUIStates } = get();+ return workflowUIStates[workflowId] || createDefaultUIState();+ },++ setWorkflowExecuting: (workflowId, isExecuting) => {+ set((state) => {+ const prevState = state.workflowUIStates[workflowId];+ return {+ workflowUIStates: {+ ...state.workflowUIStates,+ [workflowId]: {+ ...(prevState || createDefaultUIState()),+ isExecuting,+ },+ },+ };+ });+ },++ setWorkflowExecutedNodes: (workflowId, nodes) => {+ set((state) => ({+ workflowUIStates: {+ ...state.workflowUIStates,+ [workflowId]: {+ ...(state.workflowUIStates[workflowId] || createDefaultUIState()),+ executedNodes: nodes,+ },+ },+ }));+ },++ setWorkflowExecutionOrder: (workflowId, order) => {+ set((state) => ({+ workflowUIStates: {+ ...state.workflowUIStates,+ [workflowId]: {+ ...(state.workflowUIStates[workflowId] || createDefaultUIState()),+ executionOrder: order,+ },+ },+ }));+ },++ setWorkflowViewport: (workflowId, viewport) => {+ set((state) => ({+ workflowUIStates: {+ ...state.workflowUIStates,+ [workflowId]: {+ ...(state.workflowUIStates[workflowId] || createDefaultUIState()),+ viewport,+ },+ },+ }));+ },++ clearWorkflowExecutionState: (workflowId) => {+ set((state) => ({+ workflowUIStates: {+ ...state.workflowUIStates,+ [workflowId]: {+ ...(state.workflowUIStates[workflowId] || createDefaultUIState()),+ isExecuting: false,+ executedNodes: [],+ executionOrder: [],+ },+ },+ }));+ },++ updateNodeData: (nodeId, newData) => {+ const { currentWorkflow, selectedNode } = get();+ if (!currentWorkflow) return;++ const updatedNodes = currentWorkflow.nodes.map(node =>+ node.id === nodeId ? { ...node, data: { ...node.data, ...newData } } : node+ );++ const updatedWorkflow = {+ ...currentWorkflow,+ nodes: updatedNodes,+ lastModified: new Date(),+ };++ set({+ currentWorkflow: updatedWorkflow,+ hasUnsavedChanges: true,+ selectedNode: selectedNode?.id === nodeId ?+ { ...selectedNode, data: { ...selectedNode.data, ...newData } } :+ selectedNode+ });+ },++ updateNodes: (nodes) => {+ const { currentWorkflow } = get();+ if (!currentWorkflow) return;++ const updatedWorkflow = {+ ...currentWorkflow,+ nodes,+ lastModified: new Date(),+ };++ set({+ currentWorkflow: updatedWorkflow,+ hasUnsavedChanges: true,+ });+ },++ updateEdges: (edges) => {+ const { currentWorkflow } = get();+ if (!currentWorkflow) return;++ const updatedWorkflow = {+ ...currentWorkflow,+ edges,+ lastModified: new Date(),+ };++ set({+ currentWorkflow: updatedWorkflow,+ hasUnsavedChanges: true,+ });+ },++ addNode: (node) => {+ const { currentWorkflow } = get();+ if (!currentWorkflow) return;++ const updatedWorkflow = {+ ...currentWorkflow,+ nodes: [...currentWorkflow.nodes, node],+ lastModified: new Date(),+ };++ set({+ currentWorkflow: updatedWorkflow,+ hasUnsavedChanges: true,+ });+ },++ removeNodes: (nodeIds) => {+ const { currentWorkflow } = get();+ if (!currentWorkflow) return;++ const updatedNodes = currentWorkflow.nodes.filter(node => !nodeIds.includes(node.id));+ const updatedEdges = currentWorkflow.edges.filter(edge =>+ !nodeIds.includes(edge.source) && !nodeIds.includes(edge.target)+ );++ const updatedWorkflow = {+ ...currentWorkflow,+ nodes: updatedNodes,+ edges: updatedEdges,+ lastModified: new Date(),+ };++ set({+ currentWorkflow: updatedWorkflow,+ hasUnsavedChanges: true,+ selectedNode: nodeIds.includes(get().selectedNode?.id || '') ? null : get().selectedNode,+ });+ },++ removeEdges: (edgeIds) => {+ const { currentWorkflow } = get();+ if (!currentWorkflow) return;++ const updatedEdges = currentWorkflow.edges.filter(edge => !edgeIds.includes(edge.id));++ const updatedWorkflow = {+ ...currentWorkflow,+ edges: updatedEdges,+ lastModified: new Date(),+ };++ set({+ currentWorkflow: updatedWorkflow,+ hasUnsavedChanges: true,+ });+ },++ exportWorkflowToJSON: () => {+ const { currentWorkflow } = get();+ if (!currentWorkflow) {+ throw new Error('No workflow to export');+ }++ return exportToJSON(currentWorkflow);+ },++ exportWorkflowToFile: () => {+ const { currentWorkflow } = get();+ if (!currentWorkflow) {+ throw new Error('No workflow to export');+ }++ exportToFile(currentWorkflow);+ },++ importWorkflowFromJSON: (jsonString: string) => {+ const workflow = importFromJSON(jsonString);+ set({+ currentWorkflow: workflow,+ hasUnsavedChanges: true+ });+ },+}));\ No newline at end of filediff --git a/client/src/styles/theme.ts b/client/src/styles/theme.tsnew file mode 100644index 00000000..55a7f48d--- /dev/null+++ b/client/src/styles/theme.ts@@ -0,0 +1,508 @@+// Unified theme system - consolidated design tokens and component styles++// ============================================================================+// DRACULA COLOR PALETTE (vibrant action colors + dark theme backgrounds)+// ============================================================================+export const dracula = {+ // Vibrant action colors+ green: '#50fa7b', // Run/Success - bright green+ purple: '#bd93f9', // Deploy/Save - purple+ pink: '#ff79c6', // Cancel/Stop - pink+ cyan: '#8be9fd', // Info/Alternative - cyan+ red: '#ff5555', // Error/Danger - red+ orange: '#ffb86c', // Warning - orange+ yellow: '#f1fa8c', // Highlight - yellow+ // Dark theme backgrounds+ background: '#282a36', // Main background+ currentLine: '#44475a', // Current line / elevated background+ selection: '#44475a', // Selection / panel background+ comment: '#6272a4', // Comments / muted text+ foreground: '#f8f8f2', // Main text+} as const;++// ============================================================================+// SOLARIZED COLOR PALETTE+// ============================================================================+export const solarized = {+ // Base colors (dark to light)+ base03: '#002b36', // darkest background+ base02: '#073642', // dark background highlights+ base01: '#586e75', // dark content tone (comments)+ base00: '#657b83', // light content tone+ base0: '#839496', // dark content tone+ base1: '#93a1a1', // light content tone (emphasis)+ base2: '#eee8d5', // light background highlights+ base3: '#fdf6e3', // lightest background+ // Accent colors+ yellow: '#b58900',+ orange: '#cb4b16',+ red: '#dc322f',+ magenta: '#d33682',+ violet: '#6c71c4',+ blue: '#268bd2',+ cyan: '#2aa198',+ green: '#859900',+} as const;++// ============================================================================+// LIGHT THEME COLORS - Modern, clean design with proper contrast+// ============================================================================+export const lightColors = {+ // Backgrounds - slightly warmer canvas for depth+ background: '#f5f7fa', // Slightly blue-gray canvas+ backgroundAlt: '#eef1f5', // Subtle gray for contrast areas+ backgroundPanel: '#ffffff', // Pure white for panels+ backgroundElevated: '#ffffff', // Elevated surfaces+ backgroundHover: 'rgba(0,0,0,0.05)',+ backgroundActive: 'rgba(0,0,0,0.08)',+ backgroundCanvas: '#e8ecf1', // Cooler gray for canvas - more contrast with white nodes+ // Text - high contrast+ text: '#1a1d21', // Near-black for readability+ textSecondary: '#374151', // Darker secondary text (gray-700)+ textMuted: '#4b5563', // gray-600 - muted but readable+ // Borders - subtle but defined+ border: '#d1d5db', // gray-300 - more visible+ borderHover: '#9ca3af', // gray-400+ borderFocus: '#3b82f6', // Brighter blue for focus+ borderNode: '#c7ccd4', // Slightly darker for nodes+ // Shadows - more depth for light mode+ shadow: 'rgba(0,0,0,0.12)',+ shadowLight: 'rgba(0,0,0,0.06)',+ shadowHeavy: 'rgba(0,0,0,0.18)',+ shadowNode: '0 2px 8px rgba(0,0,0,0.1), 0 4px 16px rgba(0,0,0,0.06)',+ // Focus+ focus: '#3b82f6',+ focusRing: 'rgba(59, 130, 246, 0.25)',+ // Semantic+ primary: '#2563eb', // Blue-600 - slightly darker for contrast+ success: '#059669', // Emerald-600+ warning: '#d97706', // Amber-600+ error: '#dc2626', // Red-600+ info: '#0891b2', // Cyan-600+ // Special+ templateVariable: '#7c3aed', // Violet for variables+ // Node-specific+ nodeBackground: '#ffffff',+ nodeBorder: '#d1d5db',+ nodeHeaderBg: '#f3f4f6',+ // Action colors (optimized for light backgrounds - darker for contrast)+ actionRun: '#059669', // Emerald-600+ actionDeploy: '#7c3aed', // Violet+ actionStop: '#dc2626', // Red-600+ actionSave: '#0284c7', // Sky-600+ actionSettings: '#d97706', // Amber-600+ actionCredentials: '#ca8a04', // Yellow-600+ actionTheme: '#7c3aed', // Violet+ actionSidebar: '#0891b2', // Cyan-600+ actionPalette: '#7c3aed', // Violet+ statusSaved: '#059669', // Emerald-600+ statusModified: '#d97706', // Amber-600+ // Edge colors for light mode - MUCH darker for visibility+ edgeDefault: '#6b7280', // gray-500 - much more visible+ edgeSelected: '#7c3aed', // Violet+ edgeExecuting: '#7c3aed', // Violet+ edgeCompleted: '#059669', // Emerald-600+ edgeError: '#dc2626', // Red-600+ // Category colors for light mode (darker, more saturated)+ categoryWorkflow: '#ea580c', // Orange-600+ categoryTrigger: '#db2777', // Pink-600+ categoryAI: '#7c3aed', // Violet-600+ categoryLocation: '#dc2626', // Red-600+ categoryWhatsapp: '#059669', // Emerald-600+ categoryAndroid: '#0891b2', // Cyan-600+ categoryChat: '#ca8a04', // Yellow-600+ categoryCode: '#ea580c', // Orange-600+ categoryUtil: '#7c3aed', // Violet-600+} as const;++// ============================================================================+// DARK THEME COLORS (Dracula text for better contrast)+// ============================================================================+export const darkColors = {+ // Backgrounds - Solarized dark+ background: solarized.base03,+ backgroundAlt: solarized.base02,+ backgroundPanel: solarized.base02,+ backgroundElevated: '#0d1f2d',+ backgroundHover: 'rgba(255,255,255,0.04)',+ backgroundActive: 'rgba(255,255,255,0.08)',+ backgroundCanvas: solarized.base03,+ // Text - Dracula for better contrast+ text: dracula.foreground, // #f8f8f2 - bright white text+ textSecondary: '#bfbfbf', // Lighter secondary text+ textMuted: dracula.comment, // #6272a4 - muted/comments+ // Borders+ border: solarized.base01 + '60',+ borderHover: solarized.base01,+ borderFocus: solarized.blue,+ borderNode: solarized.base01,+ // Shadows+ shadow: 'rgba(0,0,0,0.4)',+ shadowLight: 'rgba(0,0,0,0.25)',+ shadowHeavy: 'rgba(0,0,0,0.5)',+ shadowNode: '0 2px 12px rgba(0,0,0,0.3)',+ // Focus+ focus: solarized.blue,+ focusRing: 'rgba(38, 139, 210, 0.3)',+ // Semantic+ primary: solarized.blue,+ success: solarized.green,+ warning: solarized.yellow,+ error: solarized.red,+ info: solarized.cyan,+ // Special+ templateVariable: solarized.cyan,+ // Node-specific+ nodeBackground: solarized.base02,+ nodeBorder: solarized.base01,+ nodeHeaderBg: solarized.base03,+ // Action colors (Dracula - optimized for dark backgrounds)+ actionRun: dracula.green, // #50fa7b - bright green+ actionDeploy: dracula.purple, // #bd93f9 - purple+ actionStop: dracula.pink, // #ff79c6 - pink+ actionSave: dracula.cyan, // #8be9fd - cyan+ actionSettings: dracula.orange, // #ffb86c - orange+ actionCredentials: dracula.yellow, // #f1fa8c - yellow+ actionTheme: dracula.yellow, // #f1fa8c - yellow (sun icon)+ actionSidebar: dracula.cyan, // #8be9fd - cyan+ actionPalette: dracula.purple, // #bd93f9 - purple+ statusSaved: dracula.green, // #50fa7b - green+ statusModified: dracula.orange, // #ffb86c - orange+ // Edge colors for dark mode+ edgeDefault: dracula.cyan, // Cyan+ edgeSelected: dracula.purple, // Purple+ edgeExecuting: dracula.purple, // Purple+ edgeCompleted: dracula.green, // Green+ edgeError: dracula.red, // Red+ // Category colors for dark mode (Dracula - vibrant)+ categoryWorkflow: dracula.orange,+ categoryTrigger: dracula.pink,+ categoryAI: dracula.purple,+ categoryLocation: dracula.red,+ categoryWhatsapp: dracula.green,+ categoryAndroid: dracula.cyan,+ categoryChat: dracula.yellow,+ categoryCode: dracula.orange,+ categoryUtil: dracula.purple,+} as const;++// ============================================================================+// BASE THEME (uses light colors by default)+// ============================================================================+export const theme = {+ // Color palette - use lightColors as default+ colors: lightColors,++ // Solarized accent colors (available in both themes)+ accent: solarized,++ // Dracula vibrant colors (for action buttons)+ dracula: dracula,++ // Essential spacing scale+ spacing: {+ xs: '4px',+ sm: '8px',+ md: '12px',+ lg: '16px',+ xl: '20px',+ xxl: '32px',+ },++ // Simplified typography+ fontSize: {+ xs: '11px',+ sm: '12px',+ base: '14px',+ lg: '16px',+ xl: '18px',+ },++ fontWeight: {+ normal: '400',+ medium: '500',+ semibold: '600',+ },++ borderRadius: {+ sm: '4px',+ md: '6px',+ lg: '8px',+ },++ // Node sizes (fixed per industry standard)+ nodeSize: {+ square: '60px', // SquareNode, BaseChatModelNode, ModelNode+ squareIcon: '28px', // Icon inside square node+ handle: '8px', // Connection handles+ statusIndicator: '10px', // Status dot+ paramButton: '16px', // Parameters gear button+ outputBadge: '14px', // Output data indicator+ },++ // Icon sizes+ iconSize: {+ xs: '12px',+ sm: '16px',+ md: '24px',+ lg: '28px',+ xl: '32px',+ },++ // Button sizes+ buttonSize: {+ sm: '24px',+ md: '32px',+ lg: '34px',+ },++ // Layout constants+ layout: {+ sidebarWidth: '288px',+ workflowSidebarWidth: '280px',+ parameterPanelWidth: '320px',+ headerHeight: '60px',+ toolbarHeight: '48px',+ },++ transitions: {+ fast: '0.2s ease',+ medium: '0.3s ease',+ },++ // App constants - moved from utils/constants.ts+ constants: {+ storageKeys: {+ workflows: 'react-flow-workflows',+ workflowData: (id: string) => `react-flow-workflows-${id}`,+ },+ defaultWorkflowName: 'Untitled Workflow',+ debounceDelay: {+ workflowUpdate: 100,+ search: 300,+ },+ gridSize: 20,+ defaultNodePosition: { x: 100, y: 200 },+ dragOffset: { x: 75, y: 50 },+ },+};++// Component styles - consolidated from components.ts + theme.ts+export const styles = {+ // Button variants+ button: {+ base: {+ padding: `${theme.spacing.sm} ${theme.spacing.lg}`,+ borderRadius: theme.borderRadius.md,+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,+ cursor: 'pointer',+ transition: theme.transitions.fast,+ border: 'none',+ outline: 'none',+ display: 'inline-flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: theme.spacing.sm,+ },+ primary: {+ backgroundColor: theme.colors.focus,+ color: 'white',+ },+ secondary: {+ backgroundColor: 'transparent',+ border: `1px solid ${theme.colors.border}`,+ color: theme.colors.textSecondary,+ },+ danger: {+ backgroundColor: '#ef4444',+ color: 'white',+ },+ },++ // Input styles+ input: {+ base: {+ width: '100%',+ padding: `${theme.spacing.sm} ${theme.spacing.md}`,+ fontSize: theme.fontSize.base,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.md,+ backgroundColor: theme.colors.background,+ color: theme.colors.text,+ fontFamily: 'system-ui, sans-serif',+ outline: 'none',+ transition: `border-color ${theme.transitions.fast}`,+ },+ },++ // Card styles+ card: {+ base: {+ backgroundColor: theme.colors.background,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.lg,+ boxShadow: `0 1px 2px ${theme.colors.shadowLight}`,+ transition: theme.transitions.fast,+ },+ },++ // Modal styles+ modal: {+ overlay: {+ position: 'fixed' as const,+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ backgroundColor: 'rgba(0, 0, 0, 0.5)',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ zIndex: 1000,+ padding: theme.spacing.xl,+ },+ content: {+ backgroundColor: theme.colors.background,+ borderRadius: theme.borderRadius.lg,+ boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.25)',+ width: '100%',+ maxHeight: '90vh',+ display: 'flex',+ flexDirection: 'column' as const,+ overflow: 'hidden',+ },+ header: {+ padding: theme.spacing.xl,+ borderBottom: `1px solid ${theme.colors.border}`,+ backgroundColor: theme.colors.backgroundAlt,+ },+ title: {+ margin: 0,+ fontSize: theme.fontSize.xl,+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.text,+ },+ },++ // Layout components+ sidebar: {+ width: '100%',+ height: '100%',+ overflowY: 'auto' as const,+ backgroundColor: theme.colors.backgroundPanel,+ display: 'flex',+ flexDirection: 'column' as const,+ },++ sidebarHeader: {+ padding: theme.spacing.xl,+ borderBottom: `1px solid ${theme.colors.border}`,+ backgroundColor: theme.colors.background,+ },++ sidebarTitle: {+ margin: 0,+ fontSize: theme.fontSize.xl,+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.text,+ fontFamily: 'system-ui, sans-serif',+ },++ // Component item styles+ componentItem: {+ padding: '10px',+ marginBottom: theme.spacing.sm,+ backgroundColor: theme.colors.background,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.md,+ cursor: 'grab',+ transition: theme.transitions.fast,+ display: 'flex',+ alignItems: 'center',+ gap: '10px',+ boxShadow: `0 1px 2px ${theme.colors.shadowLight}`,+ fontFamily: 'system-ui, sans-serif',+ },++ componentIcon: {+ fontSize: theme.fontSize.lg,+ width: '28px',+ height: '28px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ borderRadius: theme.borderRadius.md,+ color: theme.colors.background,+ boxShadow: `0 2px 4px ${theme.colors.shadow}`,+ flexShrink: 0,+ },++ componentTitle: {+ fontWeight: theme.fontWeight.medium,+ fontSize: theme.fontSize.base,+ color: theme.colors.text,+ marginBottom: '1px',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap' as const,+ },++ componentDescription: {+ fontSize: theme.fontSize.sm,+ color: theme.colors.textSecondary,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap' as const,+ },++ // Section styles+ sectionHeader: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ padding: `${theme.spacing.sm} ${theme.spacing.md}`,+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.textSecondary,+ textTransform: 'uppercase' as const,+ letterSpacing: '0.05em',+ fontFamily: 'system-ui, sans-serif',+ backgroundColor: theme.colors.backgroundPanel,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.md,+ cursor: 'pointer',+ transition: theme.transitions.fast,+ userSelect: 'none' as const,+ },++ sectionContent: {+ overflow: 'hidden',+ transition: `max-height ${theme.transitions.medium}, opacity ${theme.transitions.fast}`,+ },++ // Layout containers+ mainContainer: {+ width: '100%',+ height: '100%',+ display: 'flex',+ backgroundColor: theme.colors.background,+ color: theme.colors.text,+ fontFamily: 'system-ui, sans-serif',+ },++ canvasContainer: {+ flex: 1,+ height: '100%',+ position: 'relative' as const,+ backgroundColor: theme.colors.backgroundAlt,+ transition: `margin-left ${theme.transitions.medium}`,+ },++ reactFlowContainer: {+ width: '100%',+ height: '100%',+ backgroundColor: theme.colors.background,+ },+};+diff --git a/client/src/styles/zIndex.ts b/client/src/styles/zIndex.tsnew file mode 100644index 00000000..1df5a1da--- /dev/null+++ b/client/src/styles/zIndex.ts@@ -0,0 +1,17 @@+// Centralized z-index management to prevent conflicts+export const zIndex = {+ base: 0,+ dropdown: 1000,+ sticky: 1020,+ fixed: 1030,+ modalBackdrop: 1040,+ modal: 1050,+ popover: 1060,+ tooltip: 1070,+ // Specific application layers+ parameterPanel: 1100,+ locationPanel: 1200,+ aiConfigPanel: 1300,+ // Maximum z-index for critical overlays+ alert: 9999+} as const;\ No newline at end of filediff --git a/client/src/types/ComponentTypes.ts b/client/src/types/ComponentTypes.tsnew file mode 100644index 00000000..f3ba7cde--- /dev/null+++ b/client/src/types/ComponentTypes.ts@@ -0,0 +1,38 @@+import { INodeTypeDescription } from './INodeProperties';++export interface ComponentPaletteState {+ collapsedSections: Record<string, boolean>;+ searchQuery: string;+}++export interface ComponentPaletteActions {+ onSearchChange: (query: string) => void;+ onToggleSection: (sectionId: string) => void;+ onDragStart: (event: React.DragEvent, definition: INodeTypeDescription) => void;+}++export interface ComponentPaletteProps extends ComponentPaletteState, ComponentPaletteActions {+ nodeDefinitions: Record<string, INodeTypeDescription>;+}++export interface WorkflowHandlers {+ handleWorkflowNameChange: (name: string) => void;+ handleSave: () => void;+ handleNew: () => void;+ handleOpen: () => void;+ handleSelectWorkflow: (workflow: any) => void;+ handleDeleteWorkflow: (id: string) => void;+ handleDuplicateWorkflow: (workflow: any) => void;+}++export interface DragDropHandlers {+ onDragOver: (event: React.DragEvent) => void;+ onDrop: (event: React.DragEvent) => void;+ handleComponentDragStart: (event: React.DragEvent, definition: any) => void;+}++export interface ReactFlowHandlers {+ onConnect: (params: any) => void;+ onNodesDelete: (deleted: any[]) => void;+ onEdgesDelete: (deleted: any[]) => void;+}\ No newline at end of filediff --git a/client/src/types/EdgeCondition.ts b/client/src/types/EdgeCondition.tsnew file mode 100644index 00000000..ec905087--- /dev/null+++ b/client/src/types/EdgeCondition.ts@@ -0,0 +1,231 @@+/**+ * Edge Condition Types for Runtime Conditional Branching+ *+ * Based on Prefect-style dynamic workflow branching.+ * Conditions are evaluated against node output at runtime to determine+ * which workflow paths to follow.+ */++/**+ * Supported comparison operators for edge conditions.+ * Matches backend operators in server/services/execution/conditions.py+ */+export type ConditionOperator =+ // Equality operators+ | 'eq' // Equal (==)+ | 'neq' // Not equal (!=)+ // Comparison operators (numeric)+ | 'gt' // Greater than (>)+ | 'lt' // Less than (<)+ | 'gte' // Greater than or equal (>=)+ | 'lte' // Less than or equal (<=)+ // String/list contains+ | 'contains' // String/list contains value+ | 'not_contains' // String/list does not contain value+ // Existence checks+ | 'exists' // Field exists and is not None+ | 'not_exists' // Field does not exist or is None+ // Empty checks+ | 'is_empty' // Field is empty (None, "", [], {})+ | 'is_not_empty' // Field is not empty+ // Regex match+ | 'matches' // Regex pattern match+ // List membership+ | 'in' // Value is in list+ | 'not_in' // Value is not in list+ // String prefix/suffix+ | 'starts_with' // String starts with value+ | 'ends_with' // String ends with value+ // Boolean checks+ | 'is_true' // Value is truthy+ | 'is_false' // Value is falsy+ // Type checks+ | 'is_string' // Value is a string+ | 'is_number' // Value is a number+ | 'is_boolean' // Value is a boolean+ | 'is_array' // Value is an array+ | 'is_object'; // Value is an object++/**+ * Metadata for each operator - used by UI to render appropriate controls.+ */+export interface OperatorMetadata {+ label: string;+ description: string;+ requiresValue: boolean;+ valueType?: 'string' | 'number' | 'boolean' | 'array' | 'any';+}++/**+ * Registry of all operators with their metadata.+ * Matches OPERATORS dict in server/services/execution/conditions.py+ */+export const OPERATORS: Record<ConditionOperator, OperatorMetadata> = {+ // Equality+ eq: { label: 'Equals', description: 'Value equals target', requiresValue: true, valueType: 'any' },+ neq: { label: 'Not Equals', description: 'Value does not equal target', requiresValue: true, valueType: 'any' },+ // Comparison+ gt: { label: 'Greater Than', description: 'Value is greater than target', requiresValue: true, valueType: 'number' },+ lt: { label: 'Less Than', description: 'Value is less than target', requiresValue: true, valueType: 'number' },+ gte: { label: 'Greater or Equal', description: 'Value is greater than or equal to target', requiresValue: true, valueType: 'number' },+ lte: { label: 'Less or Equal', description: 'Value is less than or equal to target', requiresValue: true, valueType: 'number' },+ // Contains+ contains: { label: 'Contains', description: 'String/list contains value', requiresValue: true, valueType: 'string' },+ not_contains: { label: 'Does Not Contain', description: 'String/list does not contain value', requiresValue: true, valueType: 'string' },+ // Existence+ exists: { label: 'Exists', description: 'Field exists and is not null', requiresValue: false },+ not_exists: { label: 'Does Not Exist', description: 'Field does not exist or is null', requiresValue: false },+ // Empty+ is_empty: { label: 'Is Empty', description: 'Value is empty (null, "", [], {})', requiresValue: false },+ is_not_empty: { label: 'Is Not Empty', description: 'Value is not empty', requiresValue: false },+ // Regex+ matches: { label: 'Matches Regex', description: 'Value matches regex pattern', requiresValue: true, valueType: 'string' },+ // List membership+ in: { label: 'In List', description: 'Value is in list', requiresValue: true, valueType: 'array' },+ not_in: { label: 'Not In List', description: 'Value is not in list', requiresValue: true, valueType: 'array' },+ // String prefix/suffix+ starts_with: { label: 'Starts With', description: 'String starts with value', requiresValue: true, valueType: 'string' },+ ends_with: { label: 'Ends With', description: 'String ends with value', requiresValue: true, valueType: 'string' },+ // Boolean+ is_true: { label: 'Is True', description: 'Value is truthy', requiresValue: false },+ is_false: { label: 'Is False', description: 'Value is falsy', requiresValue: false },+ // Type checks+ is_string: { label: 'Is String', description: 'Value is a string', requiresValue: false },+ is_number: { label: 'Is Number', description: 'Value is a number', requiresValue: false },+ is_boolean: { label: 'Is Boolean', description: 'Value is a boolean', requiresValue: false },+ is_array: { label: 'Is Array', description: 'Value is an array', requiresValue: false },+ is_object: { label: 'Is Object', description: 'Value is an object', requiresValue: false },+};++/**+ * Single edge condition - evaluated against source node output.+ */+export interface EdgeCondition {+ /** Output field to check (supports dot notation: "result.status", "items.0.name") */+ field: string;+ /** Comparison operator */+ operator: ConditionOperator;+ /** Value to compare against (required for operators with requiresValue: true) */+ value?: string | number | boolean | any[];+}++/**+ * Extended edge data with condition support.+ * Used in edge.data field for conditional branching.+ */+export interface ConditionalEdgeData {+ /** Optional condition for this edge */+ condition?: EdgeCondition;+ /** Display label for the edge (shown on canvas) */+ label?: string;+ /** Logic for multiple conditions (future enhancement) */+ conditionLogic?: 'and' | 'or';+ /** Additional conditions (future enhancement) */+ additionalConditions?: EdgeCondition[];+}++/**+ * React Flow edge with conditional data.+ * Extends the base Edge type with typed data property.+ */+export interface ConditionalEdge {+ id: string;+ source: string;+ target: string;+ sourceHandle?: string | null;+ targetHandle?: string | null;+ type?: string;+ animated?: boolean;+ style?: React.CSSProperties;+ className?: string;+ data?: ConditionalEdgeData;+}++/**+ * Props for the EdgeConditionEditor component.+ */+export interface EdgeConditionEditorProps {+ /** The edge being edited */+ edge: ConditionalEdge;+ /** Callback when condition is updated */+ onConditionChange: (condition: EdgeCondition | undefined) => void;+ /** Callback when label is updated */+ onLabelChange: (label: string | undefined) => void;+ /** Available fields from source node output (for autocomplete) */+ availableFields?: string[];+ /** Callback to close the editor */+ onClose: () => void;+}++/**+ * Get operators that don't require a value input.+ */+export function getNoValueOperators(): ConditionOperator[] {+ return (Object.keys(OPERATORS) as ConditionOperator[]).filter(+ op => !OPERATORS[op].requiresValue+ );+}++/**+ * Get operators that require a value input.+ */+export function getValueOperators(): ConditionOperator[] {+ return (Object.keys(OPERATORS) as ConditionOperator[]).filter(+ op => OPERATORS[op].requiresValue+ );+}++/**+ * Get operators grouped by category.+ */+export function getOperatorsByCategory(): Record<string, ConditionOperator[]> {+ return {+ 'Equality': ['eq', 'neq'],+ 'Comparison': ['gt', 'lt', 'gte', 'lte'],+ 'Contains': ['contains', 'not_contains'],+ 'Existence': ['exists', 'not_exists'],+ 'Empty': ['is_empty', 'is_not_empty'],+ 'Pattern': ['matches', 'starts_with', 'ends_with'],+ 'List': ['in', 'not_in'],+ 'Boolean': ['is_true', 'is_false'],+ 'Type': ['is_string', 'is_number', 'is_boolean', 'is_array', 'is_object'],+ };+}++/**+ * Format condition for display (edge label).+ */+export function formatConditionLabel(condition: EdgeCondition): string {+ const op = OPERATORS[condition.operator];+ if (!op) return '';++ if (!op.requiresValue) {+ return `${condition.field} ${op.label.toLowerCase()}`;+ }++ const valueStr = Array.isArray(condition.value)+ ? `[${condition.value.join(', ')}]`+ : String(condition.value);++ return `${condition.field} ${op.label.toLowerCase()} ${valueStr}`;+}++/**+ * Validate a condition object.+ */+export function validateCondition(condition: EdgeCondition): { valid: boolean; error?: string } {+ if (!condition.field || condition.field.trim() === '') {+ return { valid: false, error: 'Field is required' };+ }++ if (!condition.operator || !OPERATORS[condition.operator]) {+ return { valid: false, error: 'Invalid operator' };+ }++ const op = OPERATORS[condition.operator];+ if (op.requiresValue && (condition.value === undefined || condition.value === '')) {+ return { valid: false, error: 'Value is required for this operator' };+ }++ return { valid: true };+}diff --git a/client/src/types/INodeProperties.ts b/client/src/types/INodeProperties.tsnew file mode 100644index 00000000..ff6dd12e--- /dev/null+++ b/client/src/types/INodeProperties.ts@@ -0,0 +1,288 @@+// Modern n8n-inspired node property system+// Clean implementation with n8n-compatible data flow++// ============================================================================+// DATA FLOW INTERFACES - n8n-compatible data passing between nodes+// ============================================================================++// Binary data interface for files, images, documents, etc.+export interface IBinaryData {+ mimeType: string;+ fileName?: string;+ directory?: string;+ fileExtension?: string;+ fileSize?: number;+ data: string; // Base64 encoded data+ id?: string;+}++// Core data structure that flows between nodes (n8n-compatible)+export interface INodeExecutionData {+ json: Record<string, any>; // Main JSON data+ binary?: Record<string, IBinaryData>; // Binary attachments (files, images, etc.)+ pairedItem?: {+ item: number;+ input?: number;+ };+ error?: Error;+}++// Input/Output connection types+export type NodeConnectionType =+ | 'main' // Standard data connection+ | 'trigger' // Trigger/start connection+ | 'ai' // AI service responses+ | 'file' // File data+ | 'binary' // Binary data specific+ | 'webhook'; // Webhook data++// Enhanced output definition with data structure info+export interface INodeOutputDefinition {+ name: string;+ displayName: string;+ type: NodeConnectionType;+ description: string;+ maxConnections?: number; // How many nodes can connect to this output+ dataStructure?: {+ // Expected JSON structure this output provides+ properties: Record<string, {+ type: 'string' | 'number' | 'boolean' | 'object' | 'array';+ description?: string;+ required?: boolean;+ }>;+ binaryData?: boolean; // Whether this output includes binary data+ };+}++// Enhanced input definition+export interface INodeInputDefinition {+ name: string;+ displayName: string;+ type: NodeConnectionType;+ description: string;+ required?: boolean;+ maxConnections?: number; // How many connections this input accepts+ acceptedDataTypes?: string[]; // What kind of data this input can handle+}++// ============================================================================+// PROPERTY DEFINITION INTERFACES+// ============================================================================++export interface INodePropertyOption {+ name: string;+ value: string | number | boolean;+ label?: string;+ description?: string;+ action?: string;+}++export interface INodePropertyCollection {+ displayName: string;+ name: string;+ values: INodeProperties[];+}++export interface INodePropertyTypeOptions {+ loadOptionsMethod?: string;+ loadOptionsDependsOn?: string[];+ multipleValues?: boolean;+ multipleValueButtonText?: string;+ maxValue?: number;+ minValue?: number;+ numberStepSize?: number;+ password?: boolean;+ rows?: number;+ editor?: 'code' | 'json' | 'html' | 'sql';+ editorLanguage?: string;+ // Dynamic parameter options+ dynamicOptions?: boolean;+ dependsOn?: string[];+ // File input options+ accept?: string; // MIME types or file extensions (e.g., 'image/*', '.pdf,.doc')+}++export interface INodePropertyDisplayOptions {+ show?: Record<string, any[]>;+ hide?: Record<string, any[]>;+}++export interface INodePropertyValidation {+ type?: 'regex' | 'email' | 'url' | 'json' | 'apiKey';+ pattern?: string;+ message?: string;+ // API Key validation specific properties+ provider?: string;+ showValidateButton?: boolean;+}++// Core property interface - modern n8n-inspired design+export interface INodeProperties {+ displayName: string;+ name: string;+ type:+ | 'string'+ | 'number'+ | 'boolean'+ | 'options'+ | 'multiOptions'+ | 'collection'+ | 'fixedCollection'+ | 'color'+ | 'dateTime'+ | 'json'+ | 'notice'+ | 'hidden'+ | 'resourceLocator'+ | 'code'+ | 'file';++ default?: any;+ description?: string;+ placeholder?: string;+ required?: boolean;+ noDataExpression?: boolean;++ options?: INodePropertyOption[] | INodePropertyCollection[];+ typeOptions?: INodePropertyTypeOptions;+ displayOptions?: INodePropertyDisplayOptions;+ validation?: INodePropertyValidation[];+}++export interface INodeCredentialDescription {+ name: string;+ required?: boolean;+ displayName?: string;+}++// Resource definition for Resource-Operation pattern+export interface INodeResourceDefinition {+ name: string;+ displayName: string;+ icon?: string;+ description?: string;+ operations: INodeOperationDefinition[];+}++export interface INodeOperationDefinition {+ name: string;+ displayName: string;+ description?: string;+ action?: string;+ properties: INodeProperties[];+}+++// Main node type description interface+export interface INodeTypeDescription {+ displayName: string;+ name: string;+ icon: string;+ group: string[];+ version: number;+ subtitle?: string;+ description: string;+ keywords?: string[];+ defaults: {+ name: string;+ color?: string;+ };+ inputs: string[] | INodeInputDefinition[];+ outputs: string[] | INodeOutputDefinition[];+ properties: INodeProperties[];+ credentials?: INodeCredentialDescription[];+ resources?: INodeResourceDefinition[];+ methods?: {+ loadOptions?: Record<string, (this: any) => Promise<INodePropertyOption[]>>;+ };+}++// Node type interface that nodes must implement+export interface INodeType {+ description: INodeTypeDescription;+ methods?: {+ loadOptions?: Record<string, () => Promise<INodePropertyOption[]>>;+ };+ execute?(inputData: INodeExecutionData[][]): Promise<INodeExecutionData[][]>;+}++// Execution context for nodes+export interface IExecuteContext {+ nodeId: string;+ nodeType?: string; // Add nodeType to context+ parameters: Record<string, any>;+ inputData: INodeExecutionData[][];+ workflow: {+ id: string;+ name: string;+ };+ connectionType?: NodeConnectionType;+}++// ============================================================================+// HELPER FUNCTIONS FOR DATA FLOW+// ============================================================================++// Helper to create execution data in n8n format+export function createNodeExecutionData(json: Record<string, any>, binary?: Record<string, IBinaryData>): INodeExecutionData {+ return {+ json,+ binary,+ pairedItem: { item: 0 }+ };+}++// Helper to create simple text output+export function createTextOutput(text: string, additionalData?: Record<string, any>): INodeExecutionData[] {+ return [{+ json: {+ text,+ ...additionalData+ }+ }];+}++// Helper to create file output+export function createFileOutput(filePath: string, fileName: string, mimeType: string, additionalData?: Record<string, any>): INodeExecutionData[] {+ return [{+ json: {+ fileName,+ filePath,+ mimeType,+ ...additionalData+ },+ binary: {+ file: {+ data: '', // Would be populated with actual file data+ fileName,+ mimeType,+ fileSize: 0+ }+ }+ }];+}++// Helper to create AI response output+export function createAIOutput(response: string, model: string, usage?: any, additionalData?: Record<string, any>): INodeExecutionData[] {+ return [{+ json: {+ response,+ model,+ usage,+ timestamp: new Date().toISOString(),+ ...additionalData+ }+ }];+}++// Helper to create location output+export function createLocationOutput(latitude: number, longitude: number, additionalData?: Record<string, any>): INodeExecutionData[] {+ return [{+ json: {+ latitude,+ longitude,+ timestamp: new Date().toISOString(),+ ...additionalData+ }+ }];+}\ No newline at end of filediff --git a/client/src/types/NodeTypes.ts b/client/src/types/NodeTypes.tsnew file mode 100644index 00000000..30d19958--- /dev/null+++ b/client/src/types/NodeTypes.ts@@ -0,0 +1,28 @@+export interface NodeParameter {+ name: string;+ displayName: string;+ type: 'string' | 'number' | 'boolean' | 'select' | 'slider' | 'percentage' | 'file' | 'text' | 'array' | 'options' | 'multiOptions' | 'collection' | 'fixedCollection' | 'color' | 'dateTime' | 'notice' | 'hidden' | 'resourceLocator' | 'code' | 'json';+ default?: any;+ placeholder?: string;+ description?: string;+ options?: Array<{ value: any; label?: string; name?: string }>;+ min?: number;+ max?: number;+ step?: number;+ required?: boolean;+}++export interface NodeOutput {+ name: string;+ displayName: string;+ type: 'string' | 'number' | 'boolean' | 'file' | 'array' | 'object' | string;+ description: string;+}+++export interface NodeData {+ label?: string;+ disabled?: boolean; // Skip execution when true (n8n-style disable)+ customIcon?: string; // Custom icon: emoji, text, or image URL (http://, https://, data:, or /)+ [key: string]: any;+}\ No newline at end of filediff --git a/client/src/utils/formatters.ts b/client/src/utils/formatters.tsnew file mode 100644index 00000000..fc2a3497--- /dev/null+++ b/client/src/utils/formatters.ts@@ -0,0 +1,34 @@+// Common utility functions for formatting and clipboard operations++/**+ * Copy text to clipboard with error handling+ */+export const copyToClipboard = async (data: any, successMessage?: string): Promise<boolean> => {+ try {+ const text = typeof data === 'string' ? data : JSON.stringify(data, null, 2);+ await navigator.clipboard.writeText(text);+ if (successMessage) {+ // Import message from antd dynamically to avoid circular dependencies+ const { message } = await import('antd');+ message.success(successMessage);+ }+ return true;+ } catch (error) {+ console.error('Failed to copy to clipboard:', error);+ return false;+ }+};++/**+ * Format object as JSON string+ */+export const formatJson = (obj: any, compact: boolean = false): string => {+ return JSON.stringify(obj, null, compact ? 0 : 2);+};++/**+ * Format timestamp to locale string+ */+export const formatTimestamp = (timestamp: string | number | Date): string => {+ return new Date(timestamp).toLocaleString();+};\ No newline at end of filediff --git a/client/src/utils/googleMapsLoader.ts b/client/src/utils/googleMapsLoader.tsnew file mode 100644index 00000000..accaa0a1--- /dev/null+++ b/client/src/utils/googleMapsLoader.ts@@ -0,0 +1,140 @@+// Google Maps API Loader - Singleton pattern to prevent multiple script loads+// Ensures Google Maps JavaScript API is loaded only once per page++interface GoogleMapsLoaderOptions {+ apiKey: string;+ libraries?: string[];+ version?: string;+}++class GoogleMapsLoader {+ private static instance: GoogleMapsLoader;+ private loadPromise: Promise<void> | null = null;+ private isLoaded = false;+ private isLoading = false;++ private constructor() {}++ public static getInstance(): GoogleMapsLoader {+ if (!GoogleMapsLoader.instance) {+ GoogleMapsLoader.instance = new GoogleMapsLoader();+ }+ return GoogleMapsLoader.instance;+ }++ public async loadGoogleMaps(options: GoogleMapsLoaderOptions): Promise<void> {+ // If already loaded, resolve immediately+ if (this.isLoaded) {+ return Promise.resolve();+ }++ // If currently loading, return the existing promise+ if (this.isLoading && this.loadPromise) {+ return this.loadPromise;+ }++ // Check if Google Maps is already available (loaded externally)+ if (typeof window !== 'undefined' && window.google?.maps) {+ this.isLoaded = true;+ return Promise.resolve();+ }++ // Start loading+ this.isLoading = true;+ this.loadPromise = this.createLoadPromise(options);++ try {+ await this.loadPromise;+ this.isLoaded = true;+ this.isLoading = false;+ } catch (error) {+ this.isLoading = false;+ this.loadPromise = null;+ throw error;+ }+ }++ private createLoadPromise(options: GoogleMapsLoaderOptions): Promise<void> {+ return new Promise((resolve, reject) => {+ // Check if script already exists+ const existingScript = document.querySelector('script[src*="maps.googleapis.com"]');+ if (existingScript) {+ // Script exists, wait for it to load+ if (window.google?.maps) {+ resolve();+ } else {+ existingScript.addEventListener('load', () => resolve());+ existingScript.addEventListener('error', (error) => reject(error));+ }+ return;+ }++ // Create new script element+ const script = document.createElement('script');+ script.type = 'text/javascript';+ script.async = true;+ script.defer = true;++ // Build URL with parameters+ const { apiKey, libraries = ['geometry'], version = 'weekly' } = options;+ const params = new URLSearchParams({+ key: apiKey,+ libraries: libraries.join(','),+ v: version,+ callback: '__googleMapsCallback__'+ });++ script.src = `https://maps.googleapis.com/maps/api/js?${params.toString()}`;++ // Set up callback+ (window as any).__googleMapsCallback__ = () => {+ delete (window as any).__googleMapsCallback__;+ resolve();+ };++ // Handle errors+ script.onerror = (error) => {+ delete (window as any).__googleMapsCallback__;+ reject(new Error(`Failed to load Google Maps API: ${error}`));+ };++ // Add script to document+ document.head.appendChild(script);+ });+ }++ public isGoogleMapsLoaded(): boolean {+ return this.isLoaded || (typeof window !== 'undefined' && !!window.google?.maps);+ }++ public getGoogleMaps(): typeof google.maps | null {+ if (typeof window !== 'undefined' && window.google?.maps) {+ return window.google.maps;+ }+ return null;+ }+}++// Export singleton instance and convenience functions+export const googleMapsLoader = GoogleMapsLoader.getInstance();++export const loadGoogleMaps = (options: GoogleMapsLoaderOptions): Promise<void> => {+ return googleMapsLoader.loadGoogleMaps(options);+};++export const isGoogleMapsLoaded = (): boolean => {+ return googleMapsLoader.isGoogleMapsLoaded();+};++export const getGoogleMaps = (): typeof google.maps | null => {+ return googleMapsLoader.getGoogleMaps();+};++// Type declarations for Google Maps+declare global {+ interface Window {+ google?: {+ maps: typeof google.maps;+ };+ }+}\ No newline at end of filediff --git a/client/src/utils/locationUtils.ts b/client/src/utils/locationUtils.tsnew file mode 100644index 00000000..b25b28c2--- /dev/null+++ b/client/src/utils/locationUtils.ts@@ -0,0 +1,85 @@+import { INodeTypeDescription, INodeProperties } from '../types/INodeProperties';++// Location parameter utilities+export interface LocationParams {+ latParam: INodeProperties | null;+ lngParam: INodeProperties | null;+}++// Find coordinate parameters in node definition+export const getCoordinateParams = (nodeDefinition: INodeTypeDescription | null): LocationParams => {+ if (!nodeDefinition) return { latParam: null, lngParam: null };++ const latParam = nodeDefinition.properties?.find((p: any) => {+ const name = p.name.toLowerCase();+ return name.includes('lat') || name === 'latitude';+ });++ const lngParam = nodeDefinition.properties?.find((p: any) => {+ const name = p.name.toLowerCase();+ return name.includes('lng') || name.includes('lon') || name === 'longitude';+ });++ return { latParam: latParam || null, lngParam: lngParam || null };+};++// Get current coordinates from parameters+export const getCurrentCoordinates = (+ parameters: Record<string, any>,+ locationParams: LocationParams+) => {+ const { latParam, lngParam } = locationParams;++ const lat = (latParam && parameters[latParam.name]) || latParam?.default || 40.7128;+ const lng = (lngParam && parameters[lngParam.name]) || lngParam?.default || -74.0060;++ return { lat, lng };+};++// Get map display parameters+export const getMapDisplayParams = (parameters: Record<string, any>) => {+ const zoom = parameters.zoom || 13;+ const mapTypeId = parameters.mapTypeId || 'ROADMAP';++ return { zoom, mapTypeId };+};++// Get Google Maps API key with fallbacks+export const getGoogleMapsApiKey = (): string | undefined => {+ // Note: For stored API keys, use ApiKeyManagerService.getStoredApiKeyAsync('google_maps')+ // This function now only returns the environment variable fallback+ return (import.meta as any).env?.VITE_GOOGLE_MAPS_API_KEY || undefined;+};++// Create location update handler+export const createLocationUpdateHandler = (+ locationParams: LocationParams,+ onParameterChange: (paramName: string, value: any) => void+) => {+ return (lat: number, lng: number) => {+ const { latParam, lngParam } = locationParams;++ if (latParam) {+ onParameterChange(latParam.name, lat);+ }+ if (lngParam) {+ onParameterChange(lngParam.name, lng);+ }+ };+};++// Check if a node is location-related+export const isLocationNode = (nodeDefinition: INodeTypeDescription | null): boolean => {+ if (!nodeDefinition) return false;++ const isCreateMap = nodeDefinition.name === 'createMap';+ const hasLocationGroup = nodeDefinition.group?.includes('location') ?? false;+ const hasCoordinates = getCoordinateParams(nodeDefinition).latParam !== null;++ return isCreateMap || hasLocationGroup || hasCoordinates;+};++// Check if node should show maps preview+export const shouldShowMapsPreview = (nodeDefinition: INodeTypeDescription | null): boolean => {+ return nodeDefinition?.name === 'createMap';+};\ No newline at end of filediff --git a/client/src/utils/nodeUtils.ts b/client/src/utils/nodeUtils.tsnew file mode 100644index 00000000..6de83eb9--- /dev/null+++ b/client/src/utils/nodeUtils.ts@@ -0,0 +1,31 @@+// Utility functions for node operations++// Generate short node name from nodeType for parameter references+export const getShortNodeName = (nodeType: string): string => {+ const typeMap: { [key: string]: string } = {+ // AI Chat Models+ 'openaiChatModel': 'openai',+ 'anthropicChatModel': 'claude',+ 'geminiChatModel': 'gemini',+ // AI Agents+ 'aiAgent': 'ai',+ // Location Services+ 'createMap': 'map',+ 'addLocations': 'location',+ 'showNearbyPlaces': 'places'+ };++ // If we have a specific mapping, use it+ if (typeMap[nodeType]) {+ return typeMap[nodeType];+ }++ // Otherwise, create a simplified version by removing capitals and common suffixes+ let simplified = nodeType+ .replace(/[A-Z]/g, '') // Remove capital letters+ .replace(/(Get|Set|Stop|Play|Record|Control)$/i, '') // Remove common suffixes+ .toLowerCase();++ // Return simplified name or fallback to 'node'+ return simplified || 'node';+};\ No newline at end of filediff --git a/client/src/utils/workflow.ts b/client/src/utils/workflow.tsnew file mode 100644index 00000000..460dcb6d--- /dev/null+++ b/client/src/utils/workflow.ts@@ -0,0 +1,30 @@+import { Node, Edge } from 'reactflow';++export const generateWorkflowId = (): string =>+ `workflow-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;++export const sanitizeNodesForComparison = (nodes: Node[]): Node[] =>+ nodes.map(n => ({ ...n, selected: undefined, dragging: undefined }));++export const sanitizeEdgesForComparison = (edges: Edge[]): Edge[] =>+ edges.map(e => ({ ...e, selected: undefined }));++export const serializeDateFields = <T extends { createdAt: Date; lastModified: Date }>(obj: T) => ({+ ...obj,+ createdAt: obj.createdAt.toISOString(),+ lastModified: obj.lastModified.toISOString(),+});++export const deserializeDateFields = <T extends { createdAt: string; lastModified: string }>(obj: T) => ({+ ...obj,+ createdAt: new Date(obj.createdAt),+ lastModified: new Date(obj.lastModified),+});++export const snapToGrid = (position: { x: number; y: number }, gridSize = 20) => ({+ x: Math.round(position.x / gridSize) * gridSize,+ y: Math.round(position.y / gridSize) * gridSize,+});++export const getDefaultNodePosition = (nodeCount: number): { x: number; y: number } =>+ nodeCount === 0 ? { x: 100, y: 200 } : { x: 0, y: 0 };\ No newline at end of filediff --git a/client/src/utils/workflowExport.ts b/client/src/utils/workflowExport.tsnew file mode 100644index 00000000..bff83e8f--- /dev/null+++ b/client/src/utils/workflowExport.ts@@ -0,0 +1,120 @@+/**+ * Workflow Export/Import Utilities+ * Handles exporting workflows to JSON files and importing from JSON+ */++import { WorkflowData } from '../store/useAppStore';+import { validateWorkflow, serializeWorkflow, deserializeWorkflow } from '../schemas/workflowSchema';++/**+ * Export workflow to JSON file+ */+export function exportWorkflowToFile(workflow: WorkflowData): void {+ const validation = validateWorkflow(workflow);++ if (!validation.valid) {+ console.error('Workflow validation errors:', validation.errors);+ throw new Error(`Cannot export invalid workflow: ${validation.errors.join(', ')}`);+ }++ const workflowJSON = {+ ...workflow,+ createdAt: workflow.createdAt.toISOString(),+ lastModified: workflow.lastModified.toISOString(),+ version: '1.0.0'+ };++ const jsonString = serializeWorkflow(workflowJSON);+ const blob = new Blob([jsonString], { type: 'application/json' });+ const url = URL.createObjectURL(blob);++ const a = document.createElement('a');+ a.href = url;+ a.download = `${workflow.name || 'workflow'}_${workflow.id}.json`;+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ URL.revokeObjectURL(url);+}++/**+ * Import workflow from JSON file+ */+export function importWorkflowFromFile(file: File): Promise<WorkflowData> {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();++ reader.onload = (event) => {+ try {+ const jsonString = event.target?.result as string;+ const workflow = deserializeWorkflow(jsonString);++ const validation = validateWorkflow(workflow);+ if (!validation.valid) {+ reject(new Error(`Invalid workflow JSON: ${validation.errors.join(', ')}`));+ return;+ }++ resolve(workflow);+ } catch (error) {+ reject(error);+ }+ };++ reader.onerror = () => {+ reject(new Error('Failed to read file'));+ };++ reader.readAsText(file);+ });+}++/**+ * Export workflow to JSON string+ */+export function exportWorkflowToJSON(workflow: WorkflowData): string {+ const validation = validateWorkflow(workflow);++ if (!validation.valid) {+ throw new Error(`Cannot export invalid workflow: ${validation.errors.join(', ')}`);+ }++ const workflowJSON = {+ ...workflow,+ createdAt: workflow.createdAt.toISOString(),+ lastModified: workflow.lastModified.toISOString(),+ version: '1.0.0'+ };++ return serializeWorkflow(workflowJSON);+}++/**+ * Import workflow from JSON string+ */+export function importWorkflowFromJSON(jsonString: string): WorkflowData {+ const workflow = deserializeWorkflow(jsonString);++ const validation = validateWorkflow(workflow);+ if (!validation.valid) {+ throw new Error(`Invalid workflow JSON: ${validation.errors.join(', ')}`);+ }++ return workflow;+}++/**+ * Copy workflow to clipboard as JSON+ */+export async function copyWorkflowToClipboard(workflow: WorkflowData): Promise<void> {+ const jsonString = exportWorkflowToJSON(workflow);+ await navigator.clipboard.writeText(jsonString);+}++/**+ * Paste workflow from clipboard+ */+export async function pasteWorkflowFromClipboard(): Promise<WorkflowData> {+ const jsonString = await navigator.clipboard.readText();+ return importWorkflowFromJSON(jsonString);+}diff --git a/client/tailwind.config.js b/client/tailwind.config.jsnew file mode 100644index 00000000..222e2b35--- /dev/null+++ b/client/tailwind.config.js@@ -0,0 +1,60 @@+/** @type {import('tailwindcss').Config} */+export default {+ darkMode: ["class"],+ content: [+ "./index.html",+ "./src/**/*.{js,ts,jsx,tsx}",+ ],+ theme: {+ container: {+ center: true,+ padding: "2rem",+ screens: {+ "2xl": "1400px",+ },+ },+ extend: {+ colors: {+ border: "hsl(var(--border))",+ input: "hsl(var(--input))",+ ring: "hsl(var(--ring))",+ background: "hsl(var(--background))",+ foreground: "hsl(var(--foreground))",+ primary: {+ DEFAULT: "hsl(var(--primary))",+ foreground: "hsl(var(--primary-foreground))",+ },+ secondary: {+ DEFAULT: "hsl(var(--secondary))",+ foreground: "hsl(var(--secondary-foreground))",+ },+ destructive: {+ DEFAULT: "hsl(var(--destructive))",+ foreground: "hsl(var(--destructive-foreground))",+ },+ muted: {+ DEFAULT: "hsl(var(--muted))",+ foreground: "hsl(var(--muted-foreground))",+ },+ accent: {+ DEFAULT: "hsl(var(--accent))",+ foreground: "hsl(var(--accent-foreground))",+ },+ popover: {+ DEFAULT: "hsl(var(--popover))",+ foreground: "hsl(var(--popover-foreground))",+ },+ card: {+ DEFAULT: "hsl(var(--card))",+ foreground: "hsl(var(--card-foreground))",+ },+ },+ borderRadius: {+ lg: "var(--radius)",+ md: "calc(var(--radius) - 2px)",+ sm: "calc(var(--radius) - 4px)",+ },+ },+ },+ plugins: [],+}\ No newline at end of filediff --git a/client/tsconfig.json b/client/tsconfig.jsonnew file mode 100644index 00000000..a7fc6fbf--- /dev/null+++ b/client/tsconfig.json@@ -0,0 +1,25 @@+{+ "compilerOptions": {+ "target": "ES2020",+ "useDefineForClassFields": true,+ "lib": ["ES2020", "DOM", "DOM.Iterable"],+ "module": "ESNext",+ "skipLibCheck": true,++ /* Bundler mode */+ "moduleResolution": "bundler",+ "allowImportingTsExtensions": true,+ "resolveJsonModule": true,+ "isolatedModules": true,+ "noEmit": true,+ "jsx": "react-jsx",++ /* Linting */+ "strict": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "noFallthroughCasesInSwitch": true+ },+ "include": ["src"],+ "references": [{ "path": "./tsconfig.node.json" }]+}diff --git a/client/tsconfig.node.json b/client/tsconfig.node.jsonnew file mode 100644index 00000000..8762794b--- /dev/null+++ b/client/tsconfig.node.json@@ -0,0 +1,11 @@+{+ "compilerOptions": {+ "composite": true,+ "skipLibCheck": true,+ "module": "ESNext",+ "moduleResolution": "bundler",+ "allowSyntheticDefaultImports": true,+ "strict": true+ },+ "include": ["vite.config.js"]+}diff --git a/client/vite.config.js b/client/vite.config.jsnew file mode 100644index 00000000..6508ba25--- /dev/null+++ b/client/vite.config.js@@ -0,0 +1,16 @@+import { defineConfig, loadEnv } from 'vite'+import react from '@vitejs/plugin-react'+import { resolve } from 'path'++// https://vite.dev/config/+export default defineConfig(({ mode }) => {+ const env = loadEnv(mode, resolve(process.cwd(), '..'), '')+ return {+ plugins: [react()],+ server: {+ port: parseInt(env.VITE_CLIENT_PORT),+ strictPort: false,+ host: true+ },+ }+})diff --git a/deploy.sh b/deploy.shnew file mode 100644index 00000000..ba8c9169--- /dev/null+++ b/deploy.sh@@ -0,0 +1,197 @@+#!/bin/bash++# MachinaOs Deployment to GCP+# Deploys the workflow automation platform using Docker Compose.+# Builds Docker images on the GCP server to avoid local Docker requirement.+#+# Prerequisites:+# - SSH access to GCP instance+# - Docker and Docker Compose installed on GCP instance+#+# Usage:+# ./deploy.sh [GCP_HOST]++set -e++# Load environment variables from .env if exists+if [ -f "$(dirname "$0")/server/.env" ]; then+ export $(grep -v '^#' "$(dirname "$0")/server/.env" | grep -E '^DEPLOY_|^ANDROID_RELAY_' | xargs)+fi++GCP_HOST="${1:-${DEPLOY_HOST:-user@your-server-ip}}"+SERVICE_NAME="machinaos"+DOMAIN="${DEPLOY_DOMAIN:-your-domain.com}"+REMOTE_DIR="/opt/${SERVICE_NAME}"+LOCAL_DIR="$(cd "$(dirname "$0")" && pwd)"+FRONTEND_PORT="3000"+BACKEND_PORT="3010"++echo "========================================"+echo "Deploying MachinaOs"+echo "========================================"+echo "Host: ${GCP_HOST}"+echo "Domain: ${DOMAIN}"+echo "Frontend Port: ${FRONTEND_PORT}"+echo "Backend Port: ${BACKEND_PORT}"+echo "========================================"++# Step 1: Upload source code+echo "[1/5] Uploading source code to GCP..."+ssh ${GCP_HOST} "mkdir -p /tmp/${SERVICE_NAME}"++# Create tarball of required files (excluding node_modules, __pycache__, etc.)+tar --exclude='node_modules' \+ --exclude='__pycache__' \+ --exclude='.git' \+ --exclude='*.pyc' \+ --exclude='.env' \+ --exclude='*.db' \+ --exclude='*.db-*' \+ --exclude='data' \+ --exclude='bin' \+ -czf /tmp/machinaos-src.tar.gz \+ -C "${LOCAL_DIR}" \+ client server docker-compose.prod.yml++scp /tmp/machinaos-src.tar.gz "${GCP_HOST}:/tmp/${SERVICE_NAME}/"++# Upload production .env (prefer .env.production, fallback to .env)+if [ -f "${LOCAL_DIR}/server/.env.production" ]; then+ scp "${LOCAL_DIR}/server/.env.production" "${GCP_HOST}:/tmp/${SERVICE_NAME}/.env"+elif [ -f "${LOCAL_DIR}/server/.env" ]; then+ scp "${LOCAL_DIR}/server/.env" "${GCP_HOST}:/tmp/${SERVICE_NAME}/.env"+fi++# Step 2: Build and deploy on remote+echo "[2/5] Building and deploying on GCP..."+ssh ${GCP_HOST} << 'REMOTE_SCRIPT'+set -e+SERVICE_NAME="machinaos"+DEPLOY_DIR="/opt/${SERVICE_NAME}"++# Stop existing containers+cd ${DEPLOY_DIR} 2>/dev/null && docker-compose down 2>/dev/null || true++# Setup deployment directory+sudo mkdir -p ${DEPLOY_DIR}+sudo chown -R $USER:$USER ${DEPLOY_DIR}++# Extract source code+cd ${DEPLOY_DIR}+tar -xzf /tmp/${SERVICE_NAME}/machinaos-src.tar.gz++# Copy .env file to server directory (where docker-compose expects it)+mkdir -p ${DEPLOY_DIR}/server+[ -f /tmp/${SERVICE_NAME}/.env ] && cp /tmp/${SERVICE_NAME}/.env ${DEPLOY_DIR}/server/.env++# Create docker-compose.yml from prod version+mv docker-compose.prod.yml docker-compose.yml++# Build Docker images on server+echo "Building Docker images on server..."+docker-compose build --no-cache++# Start containers+echo "Starting containers..."+docker-compose up -d++# Cleanup temp files and dangling Docker images+rm -rf /tmp/${SERVICE_NAME}+echo "Cleaning up dangling Docker images..."+docker image prune -f+docker system prune -f --volumes=false+REMOTE_SCRIPT++# Step 3: Setup nginx reverse proxy+echo "[3/5] Configuring nginx..."+ssh ${GCP_HOST} << NGINX_SCRIPT+set -e+DOMAIN="${DOMAIN}"+FRONTEND_PORT="${FRONTEND_PORT}"+BACKEND_PORT="${BACKEND_PORT}"++# Create nginx config+sudo tee /etc/nginx/sites-available/\${DOMAIN} > /dev/null <<NGINX_CONF+server {+ server_name ${DOMAIN};++ # Frontend+ location / {+ proxy_pass http://127.0.0.1:3000;+ proxy_http_version 1.1;+ proxy_set_header Host \$host;+ proxy_set_header X-Real-IP \$remote_addr;+ proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto \$scheme;+ }++ # Backend API+ location /api/ {+ proxy_pass http://127.0.0.1:3010/api/;+ proxy_http_version 1.1;+ proxy_set_header Host \$host;+ proxy_set_header X-Real-IP \$remote_addr;+ proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto \$scheme;+ }++ # Backend WebSocket+ location /ws/ {+ proxy_pass http://127.0.0.1:3010/ws/;+ proxy_http_version 1.1;+ proxy_set_header Upgrade \$http_upgrade;+ proxy_set_header Connection "upgrade";+ proxy_set_header Host \$host;+ proxy_set_header X-Real-IP \$remote_addr;+ proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;+ proxy_read_timeout 86400;+ proxy_send_timeout 86400;+ }++ # Webhook endpoint+ location /webhook/ {+ proxy_pass http://127.0.0.1:3010/webhook/;+ proxy_http_version 1.1;+ proxy_set_header Host \$host;+ proxy_set_header X-Real-IP \$remote_addr;+ proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto \$scheme;+ }++ # Health check+ location /health {+ proxy_pass http://127.0.0.1:3010/health;+ proxy_http_version 1.1;+ proxy_set_header Host \$host;+ }+}+NGINX_CONF++sudo ln -sf /etc/nginx/sites-available/\${DOMAIN} /etc/nginx/sites-enabled/+sudo nginx -t && sudo systemctl reload nginx++# Setup SSL+sudo certbot --nginx -d \${DOMAIN} --non-interactive --agree-tos --register-unsafely-without-email || true+NGINX_SCRIPT++# Step 4: Verify+echo "[4/5] Verifying deployment..."+sleep 5+ssh ${GCP_HOST} "cd /opt/${SERVICE_NAME} && docker-compose ps"++# Cleanup local temp files+rm -f /tmp/machinaos-src.tar.gz++echo "========================================"+echo "[5/5] Deployment Complete!"+echo "========================================"+echo " URL: https://${DOMAIN}"+echo " Health: https://${DOMAIN}/health"+echo " API: https://${DOMAIN}/api/"+echo " WS: wss://${DOMAIN}/ws/status"+echo "========================================"+echo ""+echo "Useful commands:"+echo " ssh ${GCP_HOST} 'cd /opt/${SERVICE_NAME} && docker-compose logs -f'"+echo " ssh ${GCP_HOST} 'cd /opt/${SERVICE_NAME} && docker-compose restart'"+echo "========================================"diff --git a/docker-compose.prod.yml b/docker-compose.prod.ymlnew file mode 100644index 00000000..5a4d2e7e--- /dev/null+++ b/docker-compose.prod.yml@@ -0,0 +1,105 @@+services:+ # Redis Cache (production performance)+ redis:+ image: redis:7-alpine+ container_name: machina-redis+ volumes:+ - redis-data:/data+ networks:+ - app-network+ restart: always+ healthcheck:+ test: ["CMD", "redis-cli", "ping"]+ interval: 10s+ timeout: 5s+ retries: 3+ command: redis-server --appendonly yes++ # Python FastAPI Backend+ backend:+ build:+ context: ./server+ dockerfile: Dockerfile+ container_name: machina-backend+ ports:+ - "3010:3010"+ volumes:+ - backend-data:/app/data+ networks:+ - app-network+ restart: always+ healthcheck:+ test: ["CMD", "curl", "-f", "http://localhost:3010/health"]+ interval: 30s+ timeout: 10s+ retries: 3+ start_period: 30s+ environment:+ - PORT=3010+ - TZ=UTC+ - ENV=production+ - LOG_LEVEL=INFO+ # Redis cache (internal Docker network)+ - REDIS_ENABLED=true+ - REDIS_URL=redis://redis:6379+ # Android relay WebSocket (set in .env or override)+ - ANDROID_RELAY_URL=${ANDROID_RELAY_URL:-}+ # WhatsApp RPC service URL (internal Docker network)+ - WHATSAPP_RPC_URL=ws://whatsapp:9400/ws/rpc+ env_file:+ - path: ./server/.env+ required: false+ depends_on:+ redis:+ condition: service_healthy+ whatsapp:+ condition: service_healthy++ # React Frontend (Production - Nginx)+ frontend:+ build:+ context: ./client+ dockerfile: Dockerfile+ target: production+ container_name: machina-frontend+ ports:+ - "3000:80"+ networks:+ - app-network+ restart: always+ depends_on:+ - backend++ # WhatsApp RPC Service (Go API only)+ whatsapp:+ build:+ context: ./server/whatsapp-rpc+ dockerfile: Dockerfile+ container_name: machina-whatsapp+ volumes:+ - whatsapp-data:/app/data+ networks:+ - app-network+ restart: always+ # Privileged mode for proper SQLite WAL mmap support+ privileged: true+ healthcheck:+ test: ["CMD", "curl", "-f", "http://localhost:9400/health"]+ interval: 30s+ timeout: 10s+ retries: 3+ start_period: 15s+ environment:+ - TZ=UTC++networks:+ app-network:+ driver: bridge++volumes:+ redis-data:+ driver: local+ backend-data:+ driver: local+ whatsapp-data:+ driver: localdiff --git a/docker-compose.yml b/docker-compose.ymlnew file mode 100644index 00000000..a079e251--- /dev/null+++ b/docker-compose.yml@@ -0,0 +1,87 @@+services:+ # Python FastAPI Backend+ backend:+ build:+ context: ./server+ dockerfile: Dockerfile+ container_name: machina-backend+ ports:+ - "3010:3010"+ volumes:+ - ./server:/app+ - backend-data:/app/data+ networks:+ - app-network+ restart: unless-stopped+ healthcheck:+ test: ["CMD", "curl", "-f", "http://localhost:3010/health"]+ interval: 30s+ timeout: 10s+ retries: 3+ start_period: 30s+ environment:+ - PORT=3010+ - TZ=UTC+ - LOG_LEVEL=INFO+ # Android relay WebSocket (optional, set in .env)+ - ANDROID_RELAY_URL=${ANDROID_RELAY_URL:-}+ # WhatsApp RPC service URL (internal Docker network)+ - WHATSAPP_RPC_URL=ws://whatsapp:9400/ws/rpc+ depends_on:+ whatsapp:+ condition: service_healthy++ # React Frontend (Vite)+ frontend:+ build:+ context: ./client+ dockerfile: Dockerfile+ target: development+ container_name: machina-frontend+ ports:+ - "3001:3001"+ volumes:+ - ./client:/app+ - /app/node_modules+ networks:+ - app-network+ restart: unless-stopped+ depends_on:+ - backend+ environment:+ - VITE_API_URL=http://backend:3010+ - VITE_WS_URL=ws://backend:3010+ - TZ=UTC++ # WhatsApp RPC Service (Go + Flask)+ whatsapp:+ build:+ context: ./server/whatsapp-rpc+ dockerfile: Dockerfile+ container_name: machina-whatsapp+ ports:+ - "9400:9400"+ - "5000:5000"+ volumes:+ - whatsapp-data:/app/data+ networks:+ - app-network+ restart: unless-stopped+ healthcheck:+ test: ["CMD", "curl", "-f", "http://localhost:5000/health"]+ interval: 30s+ timeout: 10s+ retries: 3+ start_period: 15s+ environment:+ - TZ=UTC++networks:+ app-network:+ driver: bridge++volumes:+ backend-data:+ driver: local+ whatsapp-data:+ driver: localdiff --git a/package-lock.json b/package-lock.jsonnew file mode 100644index 00000000..ce928410--- /dev/null+++ b/package-lock.json@@ -0,0 +1,11865 @@+{+ "name": "react-flow-project",+ "version": "0.0.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "react-flow-project",+ "version": "0.0.0",+ "workspaces": [+ "client"+ ],+ "devDependencies": {+ "concurrently": "^9.2.1"+ }+ },+ "client": {+ "name": "react-flow-client",+ "version": "0.0.0",+ "dependencies": {+ "@ant-design/icons": "^6.0.2",+ "@langchain/anthropic": "^0.3.28",+ "@langchain/google-genai": "^0.1.0",+ "@langchain/openai": "^0.6.12",+ "@lobehub/icons": "^2.45.0",+ "@radix-ui/react-collapsible": "^1.1.12",+ "@radix-ui/react-dialog": "^1.1.15",+ "@types/styled-components": "^5.1.34",+ "ai": "^5.0.35",+ "antd": "^5.27.4",+ "dexie": "^4.2.0",+ "openai": "^5.19.1",+ "prismjs": "^1.30.0",+ "react": "^19.1.1",+ "react-dom": "^19.1.1",+ "react-js-cron": "^5.2.0",+ "react-simple-code-editor": "^0.14.1",+ "react-use": "^17.6.0",+ "reactflow": "^11.11.4",+ "styled-components": "^6.1.19",+ "zustand": "^5.0.8"+ },+ "devDependencies": {+ "@eslint/js": "^9.33.0",+ "@types/google.maps": "^3.58.1",+ "@types/node": "^24.3.1",+ "@types/prismjs": "^1.26.5",+ "@types/react": "^19.1.10",+ "@types/react-dom": "^19.1.7",+ "@vitejs/plugin-react": "^5.0.0",+ "autoprefixer": "^10.4.21",+ "eslint": "^9.33.0",+ "eslint-plugin-react-hooks": "^7.0.1",+ "eslint-plugin-react-refresh": "^0.4.20",+ "globals": "^16.3.0",+ "postcss": "^8.5.6",+ "tailwindcss": "^4.1.13",+ "typescript": "^5.9.2",+ "vite": "^7.1.2"+ }+ },+ "node_modules/@ai-sdk/gateway": {+ "version": "2.0.18",+ "resolved": "https://registry.npmjs.org/@ai-sdk/gateway/-/gateway-2.0.18.tgz",+ "integrity": "sha512-sDQcW+6ck2m0pTIHW6BPHD7S125WD3qNkx/B8sEzJp/hurocmJ5Cni0ybExg6sQMGo+fr/GWOwpHF1cmCdg5rQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@ai-sdk/provider": "2.0.0",+ "@ai-sdk/provider-utils": "3.0.18",+ "@vercel/oidc": "3.0.5"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "zod": "^3.25.76 || ^4.1.8"+ }+ },+ "node_modules/@ai-sdk/provider": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-2.0.0.tgz",+ "integrity": "sha512-6o7Y2SeO9vFKB8lArHXehNuusnpddKPk7xqL7T2/b+OvXMRIXUO1rR4wcv1hAFUAT9avGZshty3Wlua/XA7TvA==",+ "license": "Apache-2.0",+ "dependencies": {+ "json-schema": "^0.4.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@ai-sdk/provider-utils": {+ "version": "3.0.18",+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-3.0.18.tgz",+ "integrity": "sha512-ypv1xXMsgGcNKUP+hglKqtdDuMg68nWHucPPAhIENrbFAI+xCHiqPVN8Zllxyv1TNZwGWUghPxJXU+Mqps0YRQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@ai-sdk/provider": "2.0.0",+ "@standard-schema/spec": "^1.0.0",+ "eventsource-parser": "^3.0.6"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "zod": "^3.25.76 || ^4.1.8"+ }+ },+ "node_modules/@ant-design/colors": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/@ant-design/colors/-/colors-8.0.0.tgz",+ "integrity": "sha512-6YzkKCw30EI/E9kHOIXsQDHmMvTllT8STzjMb4K2qzit33RW2pqCJP0sk+hidBntXxE+Vz4n1+RvCTfBw6OErw==",+ "license": "MIT",+ "dependencies": {+ "@ant-design/fast-color": "^3.0.0"+ }+ },+ "node_modules/@ant-design/cssinjs": {+ "version": "1.24.0",+ "resolved": "https://registry.npmjs.org/@ant-design/cssinjs/-/cssinjs-1.24.0.tgz",+ "integrity": "sha512-K4cYrJBsgvL+IoozUXYjbT6LHHNt+19a9zkvpBPxLjFHas1UpPM2A5MlhROb0BT8N8WoavM5VsP9MeSeNK/3mg==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.11.1",+ "@emotion/hash": "^0.8.0",+ "@emotion/unitless": "^0.7.5",+ "classnames": "^2.3.1",+ "csstype": "^3.1.3",+ "rc-util": "^5.35.0",+ "stylis": "^4.3.4"+ },+ "peerDependencies": {+ "react": ">=16.0.0",+ "react-dom": ">=16.0.0"+ }+ },+ "node_modules/@ant-design/cssinjs-utils": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/@ant-design/cssinjs-utils/-/cssinjs-utils-1.1.3.tgz",+ "integrity": "sha512-nOoQMLW1l+xR1Co8NFVYiP8pZp3VjIIzqV6D6ShYF2ljtdwWJn5WSsH+7kvCktXL/yhEtWURKOfH5Xz/gzlwsg==",+ "license": "MIT",+ "dependencies": {+ "@ant-design/cssinjs": "^1.21.0",+ "@babel/runtime": "^7.23.2",+ "rc-util": "^5.38.0"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/@ant-design/fast-color": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/@ant-design/fast-color/-/fast-color-3.0.0.tgz",+ "integrity": "sha512-eqvpP7xEDm2S7dUzl5srEQCBTXZMmY3ekf97zI+M2DHOYyKdJGH0qua0JACHTqbkRnD/KHFQP9J1uMJ/XWVzzA==",+ "license": "MIT",+ "engines": {+ "node": ">=8.x"+ }+ },+ "node_modules/@ant-design/icons": {+ "version": "6.1.0",+ "resolved": "https://registry.npmjs.org/@ant-design/icons/-/icons-6.1.0.tgz",+ "integrity": "sha512-KrWMu1fIg3w/1F2zfn+JlfNDU8dDqILfA5Tg85iqs1lf8ooyGlbkA+TkwfOKKgqpUmAiRY1PTFpuOU2DAIgSUg==",+ "license": "MIT",+ "dependencies": {+ "@ant-design/colors": "^8.0.0",+ "@ant-design/icons-svg": "^4.4.0",+ "@rc-component/util": "^1.3.0",+ "clsx": "^2.1.1"+ },+ "engines": {+ "node": ">=8"+ },+ "peerDependencies": {+ "react": ">=16.0.0",+ "react-dom": ">=16.0.0"+ }+ },+ "node_modules/@ant-design/icons-svg": {+ "version": "4.4.2",+ "resolved": "https://registry.npmjs.org/@ant-design/icons-svg/-/icons-svg-4.4.2.tgz",+ "integrity": "sha512-vHbT+zJEVzllwP+CM+ul7reTEfBR0vgxFe7+lREAsAA7YGsYpboiq2sQNeQeRvh09GfQgs/GyFEvZpJ9cLXpXA==",+ "license": "MIT"+ },+ "node_modules/@ant-design/react-slick": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/@ant-design/react-slick/-/react-slick-1.1.2.tgz",+ "integrity": "sha512-EzlvzE6xQUBrZuuhSAFTdsr4P2bBBHGZwKFemEfq8gIGyIQCxalYfZW/T2ORbtQx5rU69o+WycP3exY/7T1hGA==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.10.4",+ "classnames": "^2.2.5",+ "json2mq": "^0.2.0",+ "resize-observer-polyfill": "^1.5.1",+ "throttle-debounce": "^5.0.0"+ },+ "peerDependencies": {+ "react": ">=16.9.0"+ }+ },+ "node_modules/@antfu/install-pkg": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@antfu/install-pkg/-/install-pkg-1.1.0.tgz",+ "integrity": "sha512-MGQsmw10ZyI+EJo45CdSER4zEb+p31LpDAFp2Z3gkSd1yqVZGi0Ebx++YTEMonJy4oChEMLsxZ64j8FH6sSqtQ==",+ "license": "MIT",+ "dependencies": {+ "package-manager-detector": "^1.3.0",+ "tinyexec": "^1.0.1"+ },+ "funding": {+ "url": "https://github.com/sponsors/antfu"+ }+ },+ "node_modules/@anthropic-ai/sdk": {+ "version": "0.65.0",+ "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.65.0.tgz",+ "integrity": "sha512-zIdPOcrCVEI8t3Di40nH4z9EoeyGZfXbYSvWdDLsB/KkaSYMnEgC7gmcgWu83g2NTn1ZTpbMvpdttWDGGIk6zw==",+ "license": "MIT",+ "dependencies": {+ "json-schema-to-ts": "^3.1.1"+ },+ "bin": {+ "anthropic-ai-sdk": "bin/cli"+ },+ "peerDependencies": {+ "zod": "^3.25.0 || ^4.0.0"+ },+ "peerDependenciesMeta": {+ "zod": {+ "optional": true+ }+ }+ },+ "node_modules/@babel/code-frame": {+ "version": "7.27.1",+ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.27.1.tgz",+ "integrity": "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg==",+ "license": "MIT",+ "dependencies": {+ "@babel/helper-validator-identifier": "^7.27.1",+ "js-tokens": "^4.0.0",+ "picocolors": "^1.1.1"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/compat-data": {+ "version": "7.28.5",+ "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.28.5.tgz",+ "integrity": "sha512-6uFXyCayocRbqhZOB+6XcuZbkMNimwfVGFji8CTZnCzOHVGvDqzvitu1re2AU5LROliz7eQPhB8CpAMvnx9EjA==",+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/core": {+ "version": "7.28.5",+ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.28.5.tgz",+ "integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",+ "license": "MIT",+ "dependencies": {+ "@babel/code-frame": "^7.27.1",+ "@babel/generator": "^7.28.5",+ "@babel/helper-compilation-targets": "^7.27.2",+ "@babel/helper-module-transforms": "^7.28.3",+ "@babel/helpers": "^7.28.4",+ "@babel/parser": "^7.28.5",+ "@babel/template": "^7.27.2",+ "@babel/traverse": "^7.28.5",+ "@babel/types": "^7.28.5",+ "@jridgewell/remapping": "^2.3.5",+ "convert-source-map": "^2.0.0",+ "debug": "^4.1.0",+ "gensync": "^1.0.0-beta.2",+ "json5": "^2.2.3",+ "semver": "^6.3.1"+ },+ "engines": {+ "node": ">=6.9.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/babel"+ }+ },+ "node_modules/@babel/generator": {+ "version": "7.28.5",+ "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.28.5.tgz",+ "integrity": "sha512-3EwLFhZ38J4VyIP6WNtt2kUdW9dokXA9Cr4IVIFHuCpZ3H8/YFOl5JjZHisrn1fATPBmKKqXzDFvh9fUwHz6CQ==",+ "license": "MIT",+ "dependencies": {+ "@babel/parser": "^7.28.5",+ "@babel/types": "^7.28.5",+ "@jridgewell/gen-mapping": "^0.3.12",+ "@jridgewell/trace-mapping": "^0.3.28",+ "jsesc": "^3.0.2"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-compilation-targets": {+ "version": "7.27.2",+ "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.27.2.tgz",+ "integrity": "sha512-2+1thGUUWWjLTYTHZWK1n8Yga0ijBz1XAhUXcKy81rd5g6yh7hGqMp45v7cadSbEHc9G3OTv45SyneRN3ps4DQ==",+ "license": "MIT",+ "dependencies": {+ "@babel/compat-data": "^7.27.2",+ "@babel/helper-validator-option": "^7.27.1",+ "browserslist": "^4.24.0",+ "lru-cache": "^5.1.1",+ "semver": "^6.3.1"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-compilation-targets/node_modules/lru-cache": {+ "version": "5.1.1",+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",+ "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",+ "license": "ISC",+ "dependencies": {+ "yallist": "^3.0.2"+ }+ },+ "node_modules/@babel/helper-compilation-targets/node_modules/yallist": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",+ "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",+ "license": "ISC"+ },+ "node_modules/@babel/helper-define-polyfill-provider": {+ "version": "0.6.5",+ "resolved": "https://registry.npmjs.org/@babel/helper-define-polyfill-provider/-/helper-define-polyfill-provider-0.6.5.tgz",+ "integrity": "sha512-uJnGFcPsWQK8fvjgGP5LZUZZsYGIoPeRjSF5PGwrelYgq7Q15/Ft9NGFp1zglwgIv//W0uG4BevRuSJRyylZPg==",+ "license": "MIT",+ "dependencies": {+ "@babel/helper-compilation-targets": "^7.27.2",+ "@babel/helper-plugin-utils": "^7.27.1",+ "debug": "^4.4.1",+ "lodash.debounce": "^4.0.8",+ "resolve": "^1.22.10"+ },+ "peerDependencies": {+ "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0"+ }+ },+ "node_modules/@babel/helper-globals": {+ "version": "7.28.0",+ "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.28.0.tgz",+ "integrity": "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==",+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-module-imports": {+ "version": "7.27.1",+ "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.27.1.tgz",+ "integrity": "sha512-0gSFWUPNXNopqtIPQvlD5WgXYI5GY2kP2cCvoT8kczjbfcfuIljTbcWrulD1CIPIX2gt1wghbDy08yE1p+/r3w==",+ "license": "MIT",+ "dependencies": {+ "@babel/traverse": "^7.27.1",+ "@babel/types": "^7.27.1"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-module-transforms": {+ "version": "7.28.3",+ "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.3.tgz",+ "integrity": "sha512-gytXUbs8k2sXS9PnQptz5o0QnpLL51SwASIORY6XaBKF88nsOT0Zw9szLqlSGQDP/4TljBAD5y98p2U1fqkdsw==",+ "license": "MIT",+ "dependencies": {+ "@babel/helper-module-imports": "^7.27.1",+ "@babel/helper-validator-identifier": "^7.27.1",+ "@babel/traverse": "^7.28.3"+ },+ "engines": {+ "node": ">=6.9.0"+ },+ "peerDependencies": {+ "@babel/core": "^7.0.0"+ }+ },+ "node_modules/@babel/helper-plugin-utils": {+ "version": "7.27.1",+ "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.27.1.tgz",+ "integrity": "sha512-1gn1Up5YXka3YYAHGKpbideQ5Yjf1tDa9qYcgysz+cNCXukyLl6DjPXhD3VRwSb8c0J9tA4b2+rHEZtc6R0tlw==",+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-string-parser": {+ "version": "7.27.1",+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",+ "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==",+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-validator-identifier": {+ "version": "7.28.5",+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz",+ "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==",+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-validator-option": {+ "version": "7.27.1",+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.27.1.tgz",+ "integrity": "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==",+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helpers": {+ "version": "7.28.4",+ "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.28.4.tgz",+ "integrity": "sha512-HFN59MmQXGHVyYadKLVumYsA9dBFun/ldYxipEjzA4196jpLZd8UjEEBLkbEkvfYreDqJhZxYAWFPtrfhNpj4w==",+ "license": "MIT",+ "dependencies": {+ "@babel/template": "^7.27.2",+ "@babel/types": "^7.28.4"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/parser": {+ "version": "7.28.5",+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.28.5.tgz",+ "integrity": "sha512-KKBU1VGYR7ORr3At5HAtUQ+TV3SzRCXmA/8OdDZiLDBIZxVyzXuztPjfLd3BV1PRAQGCMWWSHYhL0F8d5uHBDQ==",+ "license": "MIT",+ "dependencies": {+ "@babel/types": "^7.28.5"+ },+ "bin": {+ "parser": "bin/babel-parser.js"+ },+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/@babel/plugin-transform-react-jsx-self": {+ "version": "7.27.1",+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.27.1.tgz",+ "integrity": "sha512-6UzkCs+ejGdZ5mFFC/OCUrv028ab2fp1znZmCZjAOBKiBK2jXD1O+BPSfX8X2qjJ75fZBMSnQn3Rq2mrBJK2mw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/helper-plugin-utils": "^7.27.1"+ },+ "engines": {+ "node": ">=6.9.0"+ },+ "peerDependencies": {+ "@babel/core": "^7.0.0-0"+ }+ },+ "node_modules/@babel/plugin-transform-react-jsx-source": {+ "version": "7.27.1",+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.27.1.tgz",+ "integrity": "sha512-zbwoTsBruTeKB9hSq73ha66iFeJHuaFkUbwvqElnygoNbj/jHRsSeokowZFN3CZ64IvEqcmmkVe89OPXc7ldAw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/helper-plugin-utils": "^7.27.1"+ },+ "engines": {+ "node": ">=6.9.0"+ },+ "peerDependencies": {+ "@babel/core": "^7.0.0-0"+ }+ },+ "node_modules/@babel/plugin-transform-runtime": {+ "version": "7.28.5",+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-runtime/-/plugin-transform-runtime-7.28.5.tgz",+ "integrity": "sha512-20NUVgOrinudkIBzQ2bNxP08YpKprUkRTiRSd2/Z5GOdPImJGkoN4Z7IQe1T5AdyKI1i5L6RBmluqdSzvaq9/w==",+ "license": "MIT",+ "dependencies": {+ "@babel/helper-module-imports": "^7.27.1",+ "@babel/helper-plugin-utils": "^7.27.1",+ "babel-plugin-polyfill-corejs2": "^0.4.14",+ "babel-plugin-polyfill-corejs3": "^0.13.0",+ "babel-plugin-polyfill-regenerator": "^0.6.5",+ "semver": "^6.3.1"+ },+ "engines": {+ "node": ">=6.9.0"+ },+ "peerDependencies": {+ "@babel/core": "^7.0.0-0"+ }+ },+ "node_modules/@babel/runtime": {+ "version": "7.28.4",+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.4.tgz",+ "integrity": "sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ==",+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/template": {+ "version": "7.27.2",+ "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.27.2.tgz",+ "integrity": "sha512-LPDZ85aEJyYSd18/DkjNh4/y1ntkE5KwUHWTiqgRxruuZL2F1yuHligVHLvcHY2vMHXttKFpJn6LwfI7cw7ODw==",+ "license": "MIT",+ "dependencies": {+ "@babel/code-frame": "^7.27.1",+ "@babel/parser": "^7.27.2",+ "@babel/types": "^7.27.1"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/traverse": {+ "version": "7.28.5",+ "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.28.5.tgz",+ "integrity": "sha512-TCCj4t55U90khlYkVV/0TfkJkAkUg3jZFA3Neb7unZT8CPok7iiRfaX0F+WnqWqt7OxhOn0uBKXCw4lbL8W0aQ==",+ "license": "MIT",+ "dependencies": {+ "@babel/code-frame": "^7.27.1",+ "@babel/generator": "^7.28.5",+ "@babel/helper-globals": "^7.28.0",+ "@babel/parser": "^7.28.5",+ "@babel/template": "^7.27.2",+ "@babel/types": "^7.28.5",+ "debug": "^4.3.1"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/types": {+ "version": "7.28.5",+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.28.5.tgz",+ "integrity": "sha512-qQ5m48eI/MFLQ5PxQj4PFaprjyCTLI37ElWMmNs0K8Lk3dVeOdNpB3ks8jc7yM5CDmVC73eMVk/trk3fgmrUpA==",+ "license": "MIT",+ "dependencies": {+ "@babel/helper-string-parser": "^7.27.1",+ "@babel/helper-validator-identifier": "^7.28.5"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@braintree/sanitize-url": {+ "version": "7.1.1",+ "resolved": "https://registry.npmjs.org/@braintree/sanitize-url/-/sanitize-url-7.1.1.tgz",+ "integrity": "sha512-i1L7noDNxtFyL5DmZafWy1wRVhGehQmzZaz1HiN5e7iylJMSZR7ekOV7NsIqa5qBldlLrsKv4HbgFUVlQrz8Mw==",+ "license": "MIT"+ },+ "node_modules/@cfworker/json-schema": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/@cfworker/json-schema/-/json-schema-4.1.1.tgz",+ "integrity": "sha512-gAmrUZSGtKc3AiBL71iNWxDsyUC5uMaKKGdvzYsBoTW/xi42JQHl7eKV2OYzCUqvc+D2RCcf7EXY2iCyFIk6og==",+ "license": "MIT",+ "peer": true+ },+ "node_modules/@chevrotain/cst-dts-gen": {+ "version": "11.0.3",+ "resolved": "https://registry.npmjs.org/@chevrotain/cst-dts-gen/-/cst-dts-gen-11.0.3.tgz",+ "integrity": "sha512-BvIKpRLeS/8UbfxXxgC33xOumsacaeCKAjAeLyOn7Pcp95HiRbrpl14S+9vaZLolnbssPIUuiUd8IvgkRyt6NQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@chevrotain/gast": "11.0.3",+ "@chevrotain/types": "11.0.3",+ "lodash-es": "4.17.21"+ }+ },+ "node_modules/@chevrotain/gast": {+ "version": "11.0.3",+ "resolved": "https://registry.npmjs.org/@chevrotain/gast/-/gast-11.0.3.tgz",+ "integrity": "sha512-+qNfcoNk70PyS/uxmj3li5NiECO+2YKZZQMbmjTqRI3Qchu8Hig/Q9vgkHpI3alNjr7M+a2St5pw5w5F6NL5/Q==",+ "license": "Apache-2.0",+ "dependencies": {+ "@chevrotain/types": "11.0.3",+ "lodash-es": "4.17.21"+ }+ },+ "node_modules/@chevrotain/regexp-to-ast": {+ "version": "11.0.3",+ "resolved": "https://registry.npmjs.org/@chevrotain/regexp-to-ast/-/regexp-to-ast-11.0.3.tgz",+ "integrity": "sha512-1fMHaBZxLFvWI067AVbGJav1eRY7N8DDvYCTwGBiE/ytKBgP8azTdgyrKyWZ9Mfh09eHWb5PgTSO8wi7U824RA==",+ "license": "Apache-2.0"+ },+ "node_modules/@chevrotain/types": {+ "version": "11.0.3",+ "resolved": "https://registry.npmjs.org/@chevrotain/types/-/types-11.0.3.tgz",+ "integrity": "sha512-gsiM3G8b58kZC2HaWR50gu6Y1440cHiJ+i3JUvcp/35JchYejb2+5MVeJK0iKThYpAa/P2PYFV4hoi44HD+aHQ==",+ "license": "Apache-2.0"+ },+ "node_modules/@chevrotain/utils": {+ "version": "11.0.3",+ "resolved": "https://registry.npmjs.org/@chevrotain/utils/-/utils-11.0.3.tgz",+ "integrity": "sha512-YslZMgtJUyuMbZ+aKvfF3x1f5liK4mWNxghFRv7jqRR9C3R3fAOGTTKvxXDa2Y1s9zSbcpuO0cAxDYsc9SrXoQ==",+ "license": "Apache-2.0"+ },+ "node_modules/@dnd-kit/accessibility": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz",+ "integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==",+ "license": "MIT",+ "dependencies": {+ "tslib": "^2.0.0"+ },+ "peerDependencies": {+ "react": ">=16.8.0"+ }+ },+ "node_modules/@dnd-kit/core": {+ "version": "6.3.1",+ "resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",+ "integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",+ "license": "MIT",+ "dependencies": {+ "@dnd-kit/accessibility": "^3.1.1",+ "@dnd-kit/utilities": "^3.2.2",+ "tslib": "^2.0.0"+ },+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },+ "node_modules/@dnd-kit/modifiers": {+ "version": "9.0.0",+ "resolved": "https://registry.npmjs.org/@dnd-kit/modifiers/-/modifiers-9.0.0.tgz",+ "integrity": "sha512-ybiLc66qRGuZoC20wdSSG6pDXFikui/dCNGthxv4Ndy8ylErY0N3KVxY2bgo7AWwIbxDmXDg3ylAFmnrjcbVvw==",+ "license": "MIT",+ "dependencies": {+ "@dnd-kit/utilities": "^3.2.2",+ "tslib": "^2.0.0"+ },+ "peerDependencies": {+ "@dnd-kit/core": "^6.3.0",+ "react": ">=16.8.0"+ }+ },+ "node_modules/@dnd-kit/sortable": {+ "version": "10.0.0",+ "resolved": "https://registry.npmjs.org/@dnd-kit/sortable/-/sortable-10.0.0.tgz",+ "integrity": "sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==",+ "license": "MIT",+ "dependencies": {+ "@dnd-kit/utilities": "^3.2.2",+ "tslib": "^2.0.0"+ },+ "peerDependencies": {+ "@dnd-kit/core": "^6.3.0",+ "react": ">=16.8.0"+ }+ },+ "node_modules/@dnd-kit/utilities": {+ "version": "3.2.2",+ "resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz",+ "integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==",+ "license": "MIT",+ "dependencies": {+ "tslib": "^2.0.0"+ },+ "peerDependencies": {+ "react": ">=16.8.0"+ }+ },+ "node_modules/@emoji-mart/data": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/@emoji-mart/data/-/data-1.2.1.tgz",+ "integrity": "sha512-no2pQMWiBy6gpBEiqGeU77/bFejDqUTRY7KX+0+iur13op3bqUsXdnwoZs6Xb1zbv0gAj5VvS1PWoUUckSr5Dw==",+ "license": "MIT"+ },+ "node_modules/@emoji-mart/react": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@emoji-mart/react/-/react-1.1.1.tgz",+ "integrity": "sha512-NMlFNeWgv1//uPsvLxvGQoIerPuVdXwK/EUek8OOkJ6wVOWPUizRBJU0hDqWZCOROVpfBgCemaC3m6jDOXi03g==",+ "license": "MIT",+ "peerDependencies": {+ "emoji-mart": "^5.2",+ "react": "^16.8 || ^17 || ^18"+ }+ },+ "node_modules/@emotion/babel-plugin": {+ "version": "11.13.5",+ "resolved": "https://registry.npmjs.org/@emotion/babel-plugin/-/babel-plugin-11.13.5.tgz",+ "integrity": "sha512-pxHCpT2ex+0q+HH91/zsdHkw/lXd468DIN2zvfvLtPKLLMo6gQj7oLObq8PhkrxOZb/gGCq03S3Z7PDhS8pduQ==",+ "license": "MIT",+ "dependencies": {+ "@babel/helper-module-imports": "^7.16.7",+ "@babel/runtime": "^7.18.3",+ "@emotion/hash": "^0.9.2",+ "@emotion/memoize": "^0.9.0",+ "@emotion/serialize": "^1.3.3",+ "babel-plugin-macros": "^3.1.0",+ "convert-source-map": "^1.5.0",+ "escape-string-regexp": "^4.0.0",+ "find-root": "^1.1.0",+ "source-map": "^0.5.7",+ "stylis": "4.2.0"+ }+ },+ "node_modules/@emotion/babel-plugin/node_modules/@emotion/hash": {+ "version": "0.9.2",+ "resolved": "https://registry.npmjs.org/@emotion/hash/-/hash-0.9.2.tgz",+ "integrity": "sha512-MyqliTZGuOm3+5ZRSaaBGP3USLw6+EGykkwZns2EPC5g8jJ4z9OrdZY9apkl3+UP9+sdz76YYkwCKP5gh8iY3g==",+ "license": "MIT"+ },+ "node_modules/@emotion/babel-plugin/node_modules/@emotion/memoize": {+ "version": "0.9.0",+ "resolved": "https://registry.npmjs.org/@emotion/memoize/-/memoize-0.9.0.tgz",+ "integrity": "sha512-30FAj7/EoJ5mwVPOWhAyCX+FPfMDrVecJAM+Iw9NRoSl4BBAQeqj4cApHHUXOVvIPgLVDsCFoz/hGD+5QQD1GQ==",+ "license": "MIT"+ },+ "node_modules/@emotion/babel-plugin/node_modules/convert-source-map": {+ "version": "1.9.0",+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz",+ "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==",+ "license": "MIT"+ },+ "node_modules/@emotion/babel-plugin/node_modules/source-map": {+ "version": "0.5.7",+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz",+ "integrity": "sha512-LbrmJOMUSdEVxIKvdcJzQC+nQhe8FUZQTXQy6+I75skNgn3OoQ0DZA8YnFa7gp8tqtL3KPf1kmo0R5DoApeSGQ==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/@emotion/babel-plugin/node_modules/stylis": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/stylis/-/stylis-4.2.0.tgz",+ "integrity": "sha512-Orov6g6BB1sDfYgzWfTHDOxamtX1bE/zo104Dh9e6fqJ3PooipYyfJ0pUmrZO2wAvO8YbEyeFrkV91XTsGMSrw==",+ "license": "MIT"+ },+ "node_modules/@emotion/cache": {+ "version": "11.14.0",+ "resolved": "https://registry.npmjs.org/@emotion/cache/-/cache-11.14.0.tgz",+ "integrity": "sha512-L/B1lc/TViYk4DcpGxtAVbx0ZyiKM5ktoIyafGkH6zg/tj+mA+NE//aPYKG0k8kCHSHVJrpLpcAlOBEXQ3SavA==",+ "license": "MIT",+ "dependencies": {+ "@emotion/memoize": "^0.9.0",+ "@emotion/sheet": "^1.4.0",+ "@emotion/utils": "^1.4.2",+ "@emotion/weak-memoize": "^0.4.0",+ "stylis": "4.2.0"+ }+ },+ "node_modules/@emotion/cache/node_modules/@emotion/memoize": {+ "version": "0.9.0",+ "resolved": "https://registry.npmjs.org/@emotion/memoize/-/memoize-0.9.0.tgz",+ "integrity": "sha512-30FAj7/EoJ5mwVPOWhAyCX+FPfMDrVecJAM+Iw9NRoSl4BBAQeqj4cApHHUXOVvIPgLVDsCFoz/hGD+5QQD1GQ==",+ "license": "MIT"+ },+ "node_modules/@emotion/cache/node_modules/stylis": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/stylis/-/stylis-4.2.0.tgz",+ "integrity": "sha512-Orov6g6BB1sDfYgzWfTHDOxamtX1bE/zo104Dh9e6fqJ3PooipYyfJ0pUmrZO2wAvO8YbEyeFrkV91XTsGMSrw==",+ "license": "MIT"+ },+ "node_modules/@emotion/css": {+ "version": "11.13.5",+ "resolved": "https://registry.npmjs.org/@emotion/css/-/css-11.13.5.tgz",+ "integrity": "sha512-wQdD0Xhkn3Qy2VNcIzbLP9MR8TafI0MJb7BEAXKp+w4+XqErksWR4OXomuDzPsN4InLdGhVe6EYcn2ZIUCpB8w==",+ "license": "MIT",+ "dependencies": {+ "@emotion/babel-plugin": "^11.13.5",+ "@emotion/cache": "^11.13.5",+ "@emotion/serialize": "^1.3.3",+ "@emotion/sheet": "^1.4.0",+ "@emotion/utils": "^1.4.2"+ }+ },+ "node_modules/@emotion/hash": {+ "version": "0.8.0",+ "resolved": "https://registry.npmjs.org/@emotion/hash/-/hash-0.8.0.tgz",+ "integrity": "sha512-kBJtf7PH6aWwZ6fka3zQ0p6SBYzx4fl1LoZXE2RrnYST9Xljm7WfKJrU4g/Xr3Beg72MLrp1AWNUmuYJTL7Cow==",+ "license": "MIT"+ },+ "node_modules/@emotion/is-prop-valid": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/@emotion/is-prop-valid/-/is-prop-valid-1.2.2.tgz",+ "integrity": "sha512-uNsoYd37AFmaCdXlg6EYD1KaPOaRWRByMCYzbKUX4+hhMfrxdVSelShywL4JVaAeM/eHUOSprYBQls+/neX3pw==",+ "license": "MIT",+ "dependencies": {+ "@emotion/memoize": "^0.8.1"+ }+ },+ "node_modules/@emotion/memoize": {+ "version": "0.8.1",+ "resolved": "https://registry.npmjs.org/@emotion/memoize/-/memoize-0.8.1.tgz",+ "integrity": "sha512-W2P2c/VRW1/1tLox0mVUalvnWXxavmv/Oum2aPsRcoDJuob75FC3Y8FbpfLwUegRcxINtGUMPq0tFCvYNTBXNA==",+ "license": "MIT"+ },+ "node_modules/@emotion/react": {+ "version": "11.14.0",+ "resolved": "https://registry.npmjs.org/@emotion/react/-/react-11.14.0.tgz",+ "integrity": "sha512-O000MLDBDdk/EohJPFUqvnp4qnHeYkVP5B0xEG0D/L7cOKP9kefu2DXn8dj74cQfsEzUqh+sr1RzFqiL1o+PpA==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.18.3",+ "@emotion/babel-plugin": "^11.13.5",+ "@emotion/cache": "^11.14.0",+ "@emotion/serialize": "^1.3.3",+ "@emotion/use-insertion-effect-with-fallbacks": "^1.2.0",+ "@emotion/utils": "^1.4.2",+ "@emotion/weak-memoize": "^0.4.0",+ "hoist-non-react-statics": "^3.3.1"+ },+ "peerDependencies": {+ "react": ">=16.8.0"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@emotion/serialize": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/@emotion/serialize/-/serialize-1.3.3.tgz",+ "integrity": "sha512-EISGqt7sSNWHGI76hC7x1CksiXPahbxEOrC5RjmFRJTqLyEK9/9hZvBbiYn70dw4wuwMKiEMCUlR6ZXTSWQqxA==",+ "license": "MIT",+ "dependencies": {+ "@emotion/hash": "^0.9.2",+ "@emotion/memoize": "^0.9.0",+ "@emotion/unitless": "^0.10.0",+ "@emotion/utils": "^1.4.2",+ "csstype": "^3.0.2"+ }+ },+ "node_modules/@emotion/serialize/node_modules/@emotion/hash": {+ "version": "0.9.2",+ "resolved": "https://registry.npmjs.org/@emotion/hash/-/hash-0.9.2.tgz",+ "integrity": "sha512-MyqliTZGuOm3+5ZRSaaBGP3USLw6+EGykkwZns2EPC5g8jJ4z9OrdZY9apkl3+UP9+sdz76YYkwCKP5gh8iY3g==",+ "license": "MIT"+ },+ "node_modules/@emotion/serialize/node_modules/@emotion/memoize": {+ "version": "0.9.0",+ "resolved": "https://registry.npmjs.org/@emotion/memoize/-/memoize-0.9.0.tgz",+ "integrity": "sha512-30FAj7/EoJ5mwVPOWhAyCX+FPfMDrVecJAM+Iw9NRoSl4BBAQeqj4cApHHUXOVvIPgLVDsCFoz/hGD+5QQD1GQ==",+ "license": "MIT"+ },+ "node_modules/@emotion/serialize/node_modules/@emotion/unitless": {+ "version": "0.10.0",+ "resolved": "https://registry.npmjs.org/@emotion/unitless/-/unitless-0.10.0.tgz",+ "integrity": "sha512-dFoMUuQA20zvtVTuxZww6OHoJYgrzfKM1t52mVySDJnMSEa08ruEvdYQbhvyu6soU+NeLVd3yKfTfT0NeV6qGg==",+ "license": "MIT"+ },+ "node_modules/@emotion/sheet": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/@emotion/sheet/-/sheet-1.4.0.tgz",+ "integrity": "sha512-fTBW9/8r2w3dXWYM4HCB1Rdp8NLibOw2+XELH5m5+AkWiL/KqYX6dc0kKYlaYyKjrQ6ds33MCdMPEwgs2z1rqg==",+ "license": "MIT"+ },+ "node_modules/@emotion/unitless": {+ "version": "0.7.5",+ "resolved": "https://registry.npmjs.org/@emotion/unitless/-/unitless-0.7.5.tgz",+ "integrity": "sha512-OWORNpfjMsSSUBVrRBVGECkhWcULOAJz9ZW8uK9qgxD+87M7jHRcvh/A96XXNhXTLmKcoYSQtBEX7lHMO7YRwg==",+ "license": "MIT"+ },+ "node_modules/@emotion/use-insertion-effect-with-fallbacks": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/@emotion/use-insertion-effect-with-fallbacks/-/use-insertion-effect-with-fallbacks-1.2.0.tgz",+ "integrity": "sha512-yJMtVdH59sxi/aVJBpk9FQq+OR8ll5GT8oWd57UpeaKEVGab41JWaCFA7FRLoMLloOZF/c/wsPoe+bfGmRKgDg==",+ "license": "MIT",+ "peerDependencies": {+ "react": ">=16.8.0"+ }+ },+ "node_modules/@emotion/utils": {+ "version": "1.4.2",+ "resolved": "https://registry.npmjs.org/@emotion/utils/-/utils-1.4.2.tgz",+ "integrity": "sha512-3vLclRofFziIa3J2wDh9jjbkUz9qk5Vi3IZ/FSTKViB0k+ef0fPV7dYrUIugbgupYDx7v9ud/SjrtEP8Y4xLoA==",+ "license": "MIT"+ },+ "node_modules/@emotion/weak-memoize": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/@emotion/weak-memoize/-/weak-memoize-0.4.0.tgz",+ "integrity": "sha512-snKqtPW01tN0ui7yu9rGv69aJXr/a/Ywvl11sUjNtEcRc+ng/mQriFL0wLXMef74iHa/EkftbDzU9F8iFbH+zg==",+ "license": "MIT"+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",+ "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz",+ "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz",+ "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz",+ "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz",+ "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz",+ "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz",+ "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz",+ "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz",+ "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz",+ "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz",+ "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz",+ "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz",+ "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==",+ "cpu": [+ "mips64el"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz",+ "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz",+ "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz",+ "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz",+ "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz",+ "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz",+ "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz",+ "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz",+ "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openharmony-arm64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz",+ "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz",+ "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz",+ "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz",+ "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz",+ "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@eslint-community/eslint-utils": {+ "version": "4.9.0",+ "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.0.tgz",+ "integrity": "sha512-ayVFHdtZ+hsq1t2Dy24wCmGXGe4q9Gu3smhLYALJrr473ZH27MsnSL+LKUlimp4BWJqMDMLmPpx/Q9R3OAlL4g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "eslint-visitor-keys": "^3.4.3"+ },+ "engines": {+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ },+ "peerDependencies": {+ "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0"+ }+ },+ "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": {+ "version": "3.4.3",+ "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz",+ "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/@eslint-community/regexpp": {+ "version": "4.12.2",+ "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz",+ "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^12.0.0 || ^14.0.0 || >=16.0.0"+ }+ },+ "node_modules/@eslint/config-array": {+ "version": "0.21.1",+ "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.1.tgz",+ "integrity": "sha512-aw1gNayWpdI/jSYVgzN5pL0cfzU02GT3NBpeT/DXbx1/1x7ZKxFPd9bwrzygx/qiwIQiJ1sw/zD8qY/kRvlGHA==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@eslint/object-schema": "^2.1.7",+ "debug": "^4.3.1",+ "minimatch": "^3.1.2"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ }+ },+ "node_modules/@eslint/config-helpers": {+ "version": "0.4.2",+ "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.2.tgz",+ "integrity": "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@eslint/core": "^0.17.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ }+ },+ "node_modules/@eslint/core": {+ "version": "0.17.0",+ "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz",+ "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@types/json-schema": "^7.0.15"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ }+ },+ "node_modules/@eslint/eslintrc": {+ "version": "3.3.3",+ "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.3.tgz",+ "integrity": "sha512-Kr+LPIUVKz2qkx1HAMH8q1q6azbqBAsXJUxBl/ODDuVPX45Z9DfwB8tPjTi6nNZ8BuM3nbJxC5zCAg5elnBUTQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ajv": "^6.12.4",+ "debug": "^4.3.2",+ "espree": "^10.0.1",+ "globals": "^14.0.0",+ "ignore": "^5.2.0",+ "import-fresh": "^3.2.1",+ "js-yaml": "^4.1.1",+ "minimatch": "^3.1.2",+ "strip-json-comments": "^3.1.1"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/@eslint/eslintrc/node_modules/globals": {+ "version": "14.0.0",+ "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz",+ "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/@eslint/js": {+ "version": "9.39.1",+ "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.1.tgz",+ "integrity": "sha512-S26Stp4zCy88tH94QbBv3XCuzRQiZ9yXofEILmglYTh/Ug/a9/umqvgFtYBAo3Lp0nsI/5/qH1CCrbdK3AP1Tw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://eslint.org/donate"+ }+ },+ "node_modules/@eslint/object-schema": {+ "version": "2.1.7",+ "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz",+ "integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ }+ },+ "node_modules/@eslint/plugin-kit": {+ "version": "0.4.1",+ "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz",+ "integrity": "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@eslint/core": "^0.17.0",+ "levn": "^0.4.1"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ }+ },+ "node_modules/@floating-ui/core": {+ "version": "1.7.3",+ "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.3.tgz",+ "integrity": "sha512-sGnvb5dmrJaKEZ+LDIpguvdX3bDlEllmv4/ClQ9awcmCZrlx5jQyyMWFM5kBI+EyNOCDDiKk8il0zeuX3Zlg/w==",+ "license": "MIT",+ "dependencies": {+ "@floating-ui/utils": "^0.2.10"+ }+ },+ "node_modules/@floating-ui/dom": {+ "version": "1.7.4",+ "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.4.tgz",+ "integrity": "sha512-OOchDgh4F2CchOX94cRVqhvy7b3AFb+/rQXyswmzmGakRfkMgoWVjfnLWkRirfLEfuD4ysVW16eXzwt3jHIzKA==",+ "license": "MIT",+ "dependencies": {+ "@floating-ui/core": "^1.7.3",+ "@floating-ui/utils": "^0.2.10"+ }+ },+ "node_modules/@floating-ui/react": {+ "version": "0.27.16",+ "resolved": "https://registry.npmjs.org/@floating-ui/react/-/react-0.27.16.tgz",+ "integrity": "sha512-9O8N4SeG2z++TSM8QA/KTeKFBVCNEz/AGS7gWPJf6KFRzmRWixFRnCnkPHRDwSVZW6QPDO6uT0P2SpWNKCc9/g==",+ "license": "MIT",+ "dependencies": {+ "@floating-ui/react-dom": "^2.1.6",+ "@floating-ui/utils": "^0.2.10",+ "tabbable": "^6.0.0"+ },+ "peerDependencies": {+ "react": ">=17.0.0",+ "react-dom": ">=17.0.0"+ }+ },+ "node_modules/@floating-ui/react-dom": {+ "version": "2.1.6",+ "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.6.tgz",+ "integrity": "sha512-4JX6rEatQEvlmgU80wZyq9RT96HZJa88q8hp0pBd+LrczeDI4o6uA2M+uvxngVHo4Ihr8uibXxH6+70zhAFrVw==",+ "license": "MIT",+ "dependencies": {+ "@floating-ui/dom": "^1.7.4"+ },+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },+ "node_modules/@floating-ui/utils": {+ "version": "0.2.10",+ "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.10.tgz",+ "integrity": "sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ==",+ "license": "MIT"+ },+ "node_modules/@giscus/react": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/@giscus/react/-/react-3.1.0.tgz",+ "integrity": "sha512-0TCO2TvL43+oOdyVVGHDItwxD1UMKP2ZYpT6gXmhFOqfAJtZxTzJ9hkn34iAF/b6YzyJ4Um89QIt9z/ajmAEeg==",+ "dependencies": {+ "giscus": "^1.6.0"+ },+ "peerDependencies": {+ "react": "^16 || ^17 || ^18 || ^19",+ "react-dom": "^16 || ^17 || ^18 || ^19"+ }+ },+ "node_modules/@google/generative-ai": {+ "version": "0.24.1",+ "resolved": "https://registry.npmjs.org/@google/generative-ai/-/generative-ai-0.24.1.tgz",+ "integrity": "sha512-MqO+MLfM6kjxcKoy0p1wRzG3b4ZZXtPI+z2IE26UogS2Cm/XHO+7gGRBh6gcJsOiIVoH93UwKvW4HdgiOZCy9Q==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@humanfs/core": {+ "version": "0.19.1",+ "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz",+ "integrity": "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18.18.0"+ }+ },+ "node_modules/@humanfs/node": {+ "version": "0.16.7",+ "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.7.tgz",+ "integrity": "sha512-/zUx+yOsIrG4Y43Eh2peDeKCxlRt/gET6aHfaKpuq267qXdYDFViVHfMaLyygZOnl0kGWxFIgsBy8QFuTLUXEQ==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@humanfs/core": "^0.19.1",+ "@humanwhocodes/retry": "^0.4.0"+ },+ "engines": {+ "node": ">=18.18.0"+ }+ },+ "node_modules/@humanwhocodes/module-importer": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz",+ "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=12.22"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/nzakas"+ }+ },+ "node_modules/@humanwhocodes/retry": {+ "version": "0.4.3",+ "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz",+ "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18.18"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/nzakas"+ }+ },+ "node_modules/@iconify/types": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/@iconify/types/-/types-2.0.0.tgz",+ "integrity": "sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==",+ "license": "MIT"+ },+ "node_modules/@iconify/utils": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/@iconify/utils/-/utils-3.1.0.tgz",+ "integrity": "sha512-Zlzem1ZXhI1iHeeERabLNzBHdOa4VhQbqAcOQaMKuTuyZCpwKbC2R4Dd0Zo3g9EAc+Y4fiarO8HIHRAth7+skw==",+ "license": "MIT",+ "dependencies": {+ "@antfu/install-pkg": "^1.1.0",+ "@iconify/types": "^2.0.0",+ "mlly": "^1.8.0"+ }+ },+ "node_modules/@jridgewell/gen-mapping": {+ "version": "0.3.13",+ "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",+ "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",+ "license": "MIT",+ "dependencies": {+ "@jridgewell/sourcemap-codec": "^1.5.0",+ "@jridgewell/trace-mapping": "^0.3.24"+ }+ },+ "node_modules/@jridgewell/remapping": {+ "version": "2.3.5",+ "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",+ "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",+ "license": "MIT",+ "dependencies": {+ "@jridgewell/gen-mapping": "^0.3.5",+ "@jridgewell/trace-mapping": "^0.3.24"+ }+ },+ "node_modules/@jridgewell/resolve-uri": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",+ "license": "MIT",+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/@jridgewell/sourcemap-codec": {+ "version": "1.5.5",+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",+ "license": "MIT"+ },+ "node_modules/@jridgewell/trace-mapping": {+ "version": "0.3.31",+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",+ "license": "MIT",+ "dependencies": {+ "@jridgewell/resolve-uri": "^3.1.0",+ "@jridgewell/sourcemap-codec": "^1.4.14"+ }+ },+ "node_modules/@langchain/anthropic": {+ "version": "0.3.33",+ "resolved": "https://registry.npmjs.org/@langchain/anthropic/-/anthropic-0.3.33.tgz",+ "integrity": "sha512-uaMwieUNQbFbu0TQG6Kiub2m7hGcdjQRwniu2RzB4mroUsYCcFThv3MDumEjFMQZW/9P0eyzzTGPXJCNdQUoZg==",+ "license": "MIT",+ "dependencies": {+ "@anthropic-ai/sdk": "^0.65.0",+ "fast-xml-parser": "^4.4.1"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@langchain/core": ">=0.3.58 <0.4.0"+ }+ },+ "node_modules/@langchain/core": {+ "version": "0.3.79",+ "resolved": "https://registry.npmjs.org/@langchain/core/-/core-0.3.79.tgz",+ "integrity": "sha512-ZLAs5YMM5N2UXN3kExMglltJrKKoW7hs3KMZFlXUnD7a5DFKBYxPFMeXA4rT+uvTxuJRZPCYX0JKI5BhyAWx4A==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@cfworker/json-schema": "^4.0.2",+ "ansi-styles": "^5.0.0",+ "camelcase": "6",+ "decamelize": "1.2.0",+ "js-tiktoken": "^1.0.12",+ "langsmith": "^0.3.67",+ "mustache": "^4.2.0",+ "p-queue": "^6.6.2",+ "p-retry": "4",+ "uuid": "^10.0.0",+ "zod": "^3.25.32",+ "zod-to-json-schema": "^3.22.3"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@langchain/core/node_modules/ansi-styles": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz",+ "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",+ "license": "MIT",+ "peer": true,+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },+ "node_modules/@langchain/google-genai": {+ "version": "0.1.12",+ "resolved": "https://registry.npmjs.org/@langchain/google-genai/-/google-genai-0.1.12.tgz",+ "integrity": "sha512-0Ea0E2g63ejCuormVxbuoyJQ5BYN53i2/fb6WP8bMKzyh+y43R13V8JqOtr3e/GmgNyv3ou/VeaZjx7KAvu/0g==",+ "license": "MIT",+ "dependencies": {+ "@google/generative-ai": "^0.24.0",+ "zod-to-json-schema": "^3.22.4"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@langchain/core": ">=0.3.17 <0.4.0"+ }+ },+ "node_modules/@langchain/openai": {+ "version": "0.6.16",+ "resolved": "https://registry.npmjs.org/@langchain/openai/-/openai-0.6.16.tgz",+ "integrity": "sha512-v9INBOjE0w6ZrUE7kP9UkRyNsV7daH7aPeSOsPEJ35044UI3udPHwNduQ8VmaOUsD26OvSdg1b1GDhrqWLMaRw==",+ "license": "MIT",+ "dependencies": {+ "js-tiktoken": "^1.0.12",+ "openai": "5.12.2",+ "zod": "^3.25.32"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@langchain/core": ">=0.3.68 <0.4.0"+ }+ },+ "node_modules/@langchain/openai/node_modules/openai": {+ "version": "5.12.2",+ "resolved": "https://registry.npmjs.org/openai/-/openai-5.12.2.tgz",+ "integrity": "sha512-xqzHHQch5Tws5PcKR2xsZGX9xtch+JQFz5zb14dGqlshmmDAFBFEWmeIpf7wVqWV+w7Emj7jRgkNJakyKE0tYQ==",+ "license": "Apache-2.0",+ "bin": {+ "openai": "bin/cli"+ },+ "peerDependencies": {+ "ws": "^8.18.0",+ "zod": "^3.23.8"+ },+ "peerDependenciesMeta": {+ "ws": {+ "optional": true+ },+ "zod": {+ "optional": true+ }+ }+ },+ "node_modules/@lit-labs/ssr-dom-shim": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/@lit-labs/ssr-dom-shim/-/ssr-dom-shim-1.4.0.tgz",+ "integrity": "sha512-ficsEARKnmmW5njugNYKipTm4SFnbik7CXtoencDZzmzo/dQ+2Q0bgkzJuoJP20Aj0F+izzJjOqsnkd6F/o1bw==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@lit/reactive-element": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/@lit/reactive-element/-/reactive-element-2.1.1.tgz",+ "integrity": "sha512-N+dm5PAYdQ8e6UlywyyrgI2t++wFGXfHx+dSJ1oBrg6FAxUj40jId++EaRm80MKX5JnlH1sBsyZ5h0bcZKemCg==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "@lit-labs/ssr-dom-shim": "^1.4.0"+ }+ },+ "node_modules/@lobehub/emojilib": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/@lobehub/emojilib/-/emojilib-1.0.0.tgz",+ "integrity": "sha512-s9KnjaPjsEefaNv150G3aifvB+J3P4eEKG+epY9zDPS2BeB6+V2jELWqAZll+nkogMaVovjEE813z3V751QwGw==",+ "license": "MIT"+ },+ "node_modules/@lobehub/fluent-emoji": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/@lobehub/fluent-emoji/-/fluent-emoji-2.0.0.tgz",+ "integrity": "sha512-bKjU3sf0+7NppvcdqD/raWvKGJIw8HDJVporNQ7oR8pIPoLeb9IUu/vqIYClOlwfu9qntji7FFySfbdNqXSiJw==",+ "license": "MIT",+ "dependencies": {+ "@lobehub/emojilib": "^1.0.0",+ "@lobehub/ui": "^2.0.0",+ "antd-style": "^3.7.1",+ "emoji-regex": "^10.4.0",+ "lodash-es": "^4.17.21",+ "lucide-react": "^0.469.0",+ "react-layout-kit": "^1.9.1",+ "url-join": "^5.0.0"+ },+ "peerDependencies": {+ "antd": "^5.23.0",+ "react": "^19.0.0",+ "react-dom": "^19.0.0"+ }+ },+ "node_modules/@lobehub/fluent-emoji/node_modules/emoji-regex": {+ "version": "10.6.0",+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz",+ "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==",+ "license": "MIT"+ },+ "node_modules/@lobehub/fluent-emoji/node_modules/react-layout-kit": {+ "version": "1.9.2",+ "resolved": "https://registry.npmjs.org/react-layout-kit/-/react-layout-kit-1.9.2.tgz",+ "integrity": "sha512-fzmrwMBNGIAiDIrdFMV3NvJhUNl01QC9EMcI8SP7osg51N4j+z6w4tx9i2yWxEEXZ2armLV6EtkFd3KST8PYiA==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7",+ "@emotion/css": "^11"+ },+ "peerDependencies": {+ "react": ">=18"+ }+ },+ "node_modules/@lobehub/icons": {+ "version": "2.45.0",+ "resolved": "https://registry.npmjs.org/@lobehub/icons/-/icons-2.45.0.tgz",+ "integrity": "sha512-ZPBUlufKPeGEU6BVV4zMRLHscwHDWegolDLJH4qMVVIhMeqJhnsytlO/z2RdrzBcyt96/lKrafAueuukWE2yWg==",+ "license": "MIT",+ "workspaces": [+ "packages/*"+ ],+ "dependencies": {+ "@lobehub/ui": "^2.9.3",+ "antd-style": "^3.7.1",+ "lucide-react": "^0.469.0",+ "polished": "^4.3.1",+ "react-layout-kit": "^2.0.0"+ },+ "peerDependencies": {+ "antd": "^5.23.0",+ "react": "^19.0.0",+ "react-dom": "^19.0.0"+ }+ },+ "node_modules/@lobehub/ui": {+ "version": "2.23.0",+ "resolved": "https://registry.npmjs.org/@lobehub/ui/-/ui-2.23.0.tgz",+ "integrity": "sha512-MjRfFUhdoGAIp427bqtMs5MWn44JZmbWJUGhF+9aBH0km2iLCmkmxkOi4l4NJ/eQnjO5OZQdzHDAtsQoHFynYQ==",+ "license": "MIT",+ "dependencies": {+ "@ant-design/cssinjs": "^1.24.0",+ "@dnd-kit/core": "^6.3.1",+ "@dnd-kit/modifiers": "^9.0.0",+ "@dnd-kit/sortable": "^10.0.0",+ "@dnd-kit/utilities": "^3.2.2",+ "@emoji-mart/data": "^1.2.1",+ "@emoji-mart/react": "^1.1.1",+ "@floating-ui/react": "^0.27.16",+ "@giscus/react": "^3.1.0",+ "@lobehub/fluent-emoji": "^2.0.0",+ "@lobehub/icons": "^2.43.1",+ "@mdx-js/mdx": "^3.1.1",+ "@mdx-js/react": "^3.1.1",+ "@radix-ui/react-slot": "^1.2.4",+ "@shikijs/core": "^3.15.0",+ "@shikijs/transformers": "^3.15.0",+ "@splinetool/runtime": "0.9.526",+ "ahooks": "^3.9.6",+ "antd-style": "^3.7.1",+ "chroma-js": "^3.1.2",+ "class-variance-authority": "^0.7.1",+ "dayjs": "^1.11.19",+ "emoji-mart": "^5.6.0",+ "fast-deep-equal": "^3.1.3",+ "framer-motion": "^12.23.24",+ "immer": "^10.2.0",+ "katex": "^0.16.25",+ "leva": "^0.10.1",+ "lodash-es": "^4.17.21",+ "lucide-react": "^0.553.0",+ "marked": "^17.0.0",+ "mermaid": "^11.12.1",+ "numeral": "^2.0.6",+ "polished": "^4.3.1",+ "query-string": "^9.3.1",+ "rc-collapse": "^4.0.0",+ "rc-footer": "^0.6.8",+ "rc-image": "^7.12.0",+ "rc-input-number": "^9.5.0",+ "rc-menu": "^9.16.1",+ "re-resizable": "^6.11.2",+ "react-avatar-editor": "^13.0.2",+ "react-error-boundary": "^6.0.0",+ "react-hotkeys-hook": "^5.2.1",+ "react-layout-kit": "^2.0.0",+ "react-markdown": "^10.1.0",+ "react-merge-refs": "^3.0.2",+ "react-rnd": "^10.5.2",+ "react-zoom-pan-pinch": "^3.7.0",+ "rehype-github-alerts": "^4.1.1",+ "rehype-katex": "^7.0.1",+ "rehype-raw": "^7.0.0",+ "remark-breaks": "^4.0.0",+ "remark-cjk-friendly": "^1.2.3",+ "remark-gfm": "^4.0.1",+ "remark-github": "^12.0.0",+ "remark-math": "^6.0.0",+ "shiki": "^3.15.0",+ "shiki-stream": "^0.1.3",+ "swr": "^2.3.6",+ "ts-md5": "^2.0.1",+ "unified": "^11.0.5",+ "url-join": "^5.0.0",+ "use-merge-value": "^1.2.0",+ "uuid": "^13.0.0"+ },+ "peerDependencies": {+ "antd": "^5.25.0",+ "framer-motion": "^12.0.0",+ "react": "^19.0.0",+ "react-dom": "^19.0.0"+ }+ },+ "node_modules/@lobehub/ui/node_modules/@radix-ui/react-slot": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.4.tgz",+ "integrity": "sha512-Jl+bCv8HxKnlTLVrcDE8zTMJ09R9/ukw4qBs/oZClOfoQk/cOTbDn+NceXfV7j09YPVQUryJPHurafcSg6EVKA==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "1.1.2"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@lobehub/ui/node_modules/lucide-react": {+ "version": "0.553.0",+ "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.553.0.tgz",+ "integrity": "sha512-BRgX5zrWmNy/lkVAe0dXBgd7XQdZ3HTf+Hwe3c9WK6dqgnj9h+hxV+MDncM88xDWlCq27+TKvHGE70ViODNILw==",+ "license": "ISC",+ "peerDependencies": {+ "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },+ "node_modules/@lobehub/ui/node_modules/rc-collapse": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/rc-collapse/-/rc-collapse-4.0.0.tgz",+ "integrity": "sha512-SwoOByE39/3oIokDs/BnkqI+ltwirZbP8HZdq1/3SkPSBi7xDdvWHTp7cpNI9ullozkR6mwTWQi6/E/9huQVrA==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.10.1",+ "classnames": "2.x",+ "rc-motion": "^2.3.4",+ "rc-util": "^5.27.0"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/@lobehub/ui/node_modules/uuid": {+ "version": "13.0.0",+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-13.0.0.tgz",+ "integrity": "sha512-XQegIaBTVUjSHliKqcnFqYypAd4S+WCYt5NIeRs6w/UAry7z8Y9j5ZwRRL4kzq9U3sD6v+85er9FvkEaBpji2w==",+ "funding": [+ "https://github.com/sponsors/broofa",+ "https://github.com/sponsors/ctavan"+ ],+ "license": "MIT",+ "bin": {+ "uuid": "dist-node/bin/uuid"+ }+ },+ "node_modules/@mdx-js/mdx": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/@mdx-js/mdx/-/mdx-3.1.1.tgz",+ "integrity": "sha512-f6ZO2ifpwAQIpzGWaBQT2TXxPv6z3RBzQKpVftEWN78Vl/YweF1uwussDx8ECAXVtr3Rs89fKyG9YlzUs9DyGQ==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "@types/estree-jsx": "^1.0.0",+ "@types/hast": "^3.0.0",+ "@types/mdx": "^2.0.0",+ "acorn": "^8.0.0",+ "collapse-white-space": "^2.0.0",+ "devlop": "^1.0.0",+ "estree-util-is-identifier-name": "^3.0.0",+ "estree-util-scope": "^1.0.0",+ "estree-walker": "^3.0.0",+ "hast-util-to-jsx-runtime": "^2.0.0",+ "markdown-extensions": "^2.0.0",+ "recma-build-jsx": "^1.0.0",+ "recma-jsx": "^1.0.0",+ "recma-stringify": "^1.0.0",+ "rehype-recma": "^1.0.0",+ "remark-mdx": "^3.0.0",+ "remark-parse": "^11.0.0",+ "remark-rehype": "^11.0.0",+ "source-map": "^0.7.0",+ "unified": "^11.0.0",+ "unist-util-position-from-estree": "^2.0.0",+ "unist-util-stringify-position": "^4.0.0",+ "unist-util-visit": "^5.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/@mdx-js/mdx/node_modules/source-map": {+ "version": "0.7.6",+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz",+ "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">= 12"+ }+ },+ "node_modules/@mdx-js/react": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/@mdx-js/react/-/react-3.1.1.tgz",+ "integrity": "sha512-f++rKLQgUVYDAtECQ6fn/is15GkEH9+nZPM3MS0RcxVqoTfawHvDlSCH7JbMhAM6uJ32v3eXLvLmLvjGu7PTQw==",+ "license": "MIT",+ "dependencies": {+ "@types/mdx": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ },+ "peerDependencies": {+ "@types/react": ">=16",+ "react": ">=16"+ }+ },+ "node_modules/@mermaid-js/parser": {+ "version": "0.6.3",+ "resolved": "https://registry.npmjs.org/@mermaid-js/parser/-/parser-0.6.3.tgz",+ "integrity": "sha512-lnjOhe7zyHjc+If7yT4zoedx2vo4sHaTmtkl1+or8BRTnCtDmcTpAjpzDSfCZrshM5bCoz0GyidzadJAH1xobA==",+ "license": "MIT",+ "dependencies": {+ "langium": "3.3.1"+ }+ },+ "node_modules/@opentelemetry/api": {+ "version": "1.9.0",+ "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz",+ "integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=8.0.0"+ }+ },+ "node_modules/@primer/octicons": {+ "version": "19.21.1",+ "resolved": "https://registry.npmjs.org/@primer/octicons/-/octicons-19.21.1.tgz",+ "integrity": "sha512-7tgtBkCNcg75YJnckinzvES+uxysYQCe+CHSEnzr3VYgxttzKRvfmrnVogl3aEuHCQP4xhiE9k2lFDhYwGtTzQ==",+ "license": "MIT",+ "dependencies": {+ "object-assign": "^4.1.1"+ }+ },+ "node_modules/@radix-ui/primitive": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.3.tgz",+ "integrity": "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==",+ "license": "MIT"+ },+ "node_modules/@radix-ui/react-arrow": {+ "version": "1.1.7",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-arrow/-/react-arrow-1.1.7.tgz",+ "integrity": "sha512-F+M1tLhO+mlQaOWspE8Wstg+z6PwxwRd8oQ8IXceWz92kfAmalTRf0EjrouQeo7QssEPfCn05B4Ihs1K9WQ/7w==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-primitive": "2.1.3"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-collapsible": {+ "version": "1.1.12",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-collapsible/-/react-collapsible-1.1.12.tgz",+ "integrity": "sha512-Uu+mSh4agx2ib1uIGPP4/CKNULyajb3p92LsVXmH2EHVMTfZWpll88XJ0j4W0z3f8NK1eYl1+Mf/szHPmcHzyA==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-id": "1.1.1",+ "@radix-ui/react-presence": "1.1.5",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-controllable-state": "1.2.2",+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-compose-refs": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.2.tgz",+ "integrity": "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-context": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.1.2.tgz",+ "integrity": "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-dialog": {+ "version": "1.1.15",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-dialog/-/react-dialog-1.1.15.tgz",+ "integrity": "sha512-TCglVRtzlffRNxRMEyR36DGBLJpeusFcgMVD9PZEzAKnUs1lKCgX5u9BmC2Yg+LL9MgZDugFFs1Vl+Jp4t/PGw==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-dismissable-layer": "1.1.11",+ "@radix-ui/react-focus-guards": "1.1.3",+ "@radix-ui/react-focus-scope": "1.1.7",+ "@radix-ui/react-id": "1.1.1",+ "@radix-ui/react-portal": "1.1.9",+ "@radix-ui/react-presence": "1.1.5",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-slot": "1.2.3",+ "@radix-ui/react-use-controllable-state": "1.2.2",+ "aria-hidden": "^1.2.4",+ "react-remove-scroll": "^2.6.3"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-dismissable-layer": {+ "version": "1.1.11",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-dismissable-layer/-/react-dismissable-layer-1.1.11.tgz",+ "integrity": "sha512-Nqcp+t5cTB8BinFkZgXiMJniQH0PsUt2k51FUhbdfeKvc4ACcG2uQniY/8+h1Yv6Kza4Q7lD7PQV0z0oicE0Mg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-callback-ref": "1.1.1",+ "@radix-ui/react-use-escape-keydown": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-focus-guards": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-guards/-/react-focus-guards-1.1.3.tgz",+ "integrity": "sha512-0rFg/Rj2Q62NCm62jZw0QX7a3sz6QCQU0LpZdNrJX8byRGaGVTqbrW9jAoIAHyMQqsNpeZ81YgSizOt5WXq0Pw==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-focus-scope": {+ "version": "1.1.7",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-scope/-/react-focus-scope-1.1.7.tgz",+ "integrity": "sha512-t2ODlkXBQyn7jkl6TNaw/MtVEVvIGelJDCG41Okq/KwUsJBwQ4XVZsHAVUkK4mBv3ewiAS3PGuUWuY2BoK4ZUw==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-callback-ref": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-id": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-id/-/react-id-1.1.1.tgz",+ "integrity": "sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-popper": {+ "version": "1.2.8",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-popper/-/react-popper-1.2.8.tgz",+ "integrity": "sha512-0NJQ4LFFUuWkE7Oxf0htBKS6zLkkjBH+hM1uk7Ng705ReR8m/uelduy1DBo0PyBXPKVnBA6YBlU94MBGXrSBCw==",+ "license": "MIT",+ "dependencies": {+ "@floating-ui/react-dom": "^2.0.0",+ "@radix-ui/react-arrow": "1.1.7",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-callback-ref": "1.1.1",+ "@radix-ui/react-use-layout-effect": "1.1.1",+ "@radix-ui/react-use-rect": "1.1.1",+ "@radix-ui/react-use-size": "1.1.1",+ "@radix-ui/rect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-portal": {+ "version": "1.1.9",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-portal/-/react-portal-1.1.9.tgz",+ "integrity": "sha512-bpIxvq03if6UNwXZ+HTK71JLh4APvnXntDc6XOX8UVq4XQOVl7lwok0AvIl+b8zgCw3fSaVTZMpAPPagXbKmHQ==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-presence": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.5.tgz",+ "integrity": "sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-primitive": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.3.tgz",+ "integrity": "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-slot": "1.2.3"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-slot": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.3.tgz",+ "integrity": "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "1.1.2"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-tooltip": {+ "version": "1.2.8",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-tooltip/-/react-tooltip-1.2.8.tgz",+ "integrity": "sha512-tY7sVt1yL9ozIxvmbtN5qtmH2krXcBCfjEiCgKGLqunJHvgvZG2Pcl2oQ3kbcZARb1BGEHdkLzcYGO8ynVlieg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-dismissable-layer": "1.1.11",+ "@radix-ui/react-id": "1.1.1",+ "@radix-ui/react-popper": "1.2.8",+ "@radix-ui/react-portal": "1.1.9",+ "@radix-ui/react-presence": "1.1.5",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-slot": "1.2.3",+ "@radix-ui/react-use-controllable-state": "1.2.2",+ "@radix-ui/react-visually-hidden": "1.2.3"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-use-callback-ref": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.1.tgz",+ "integrity": "sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-use-controllable-state": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.2.2.tgz",+ "integrity": "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-use-effect-event": "0.0.2",+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-use-effect-event": {+ "version": "0.0.2",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.2.tgz",+ "integrity": "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-use-escape-keydown": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-escape-keydown/-/react-use-escape-keydown-1.1.1.tgz",+ "integrity": "sha512-Il0+boE7w/XebUHyBjroE+DbByORGR9KKmITzbR7MyQ4akpORYP/ZmbhAr0DG7RmmBqoOnZdy2QlvajJ2QA59g==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-use-callback-ref": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-use-layout-effect": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.1.tgz",+ "integrity": "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-use-rect": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-rect/-/react-use-rect-1.1.1.tgz",+ "integrity": "sha512-QTYuDesS0VtuHNNvMh+CjlKJ4LJickCMUAqjlE3+j8w+RlRpwyX3apEQKGFzbZGdo7XNG1tXa+bQqIE7HIXT2w==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/rect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-use-size": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-size/-/react-use-size-1.1.1.tgz",+ "integrity": "sha512-ewrXRDTAqAXlkl6t/fkXWNAhFX9I+CkKlw6zjEwk86RSPKwZr3xpBRso655aqYafwtnbpHLj6toFzmd6xdVptQ==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-visually-hidden": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-visually-hidden/-/react-visually-hidden-1.2.3.tgz",+ "integrity": "sha512-pzJq12tEaaIhqjbzpCuv/OypJY/BPavOofm+dbab+MHLajy277+1lLm6JFcGgF5eskJ6mquGirhXY2GD/8u8Ug==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-primitive": "2.1.3"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/rect": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/rect/-/rect-1.1.1.tgz",+ "integrity": "sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw==",+ "license": "MIT"+ },+ "node_modules/@rc-component/async-validator": {+ "version": "5.0.4",+ "resolved": "https://registry.npmjs.org/@rc-component/async-validator/-/async-validator-5.0.4.tgz",+ "integrity": "sha512-qgGdcVIF604M9EqjNF0hbUTz42bz/RDtxWdWuU5EQe3hi7M8ob54B6B35rOsvX5eSvIHIzT9iH1R3n+hk3CGfg==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.24.4"+ },+ "engines": {+ "node": ">=14.x"+ }+ },+ "node_modules/@rc-component/color-picker": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/@rc-component/color-picker/-/color-picker-2.0.1.tgz",+ "integrity": "sha512-WcZYwAThV/b2GISQ8F+7650r5ZZJ043E57aVBFkQ+kSY4C6wdofXgB0hBx+GPGpIU0Z81eETNoDUJMr7oy/P8Q==",+ "license": "MIT",+ "dependencies": {+ "@ant-design/fast-color": "^2.0.6",+ "@babel/runtime": "^7.23.6",+ "classnames": "^2.2.6",+ "rc-util": "^5.38.1"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/@rc-component/color-picker/node_modules/@ant-design/fast-color": {+ "version": "2.0.6",+ "resolved": "https://registry.npmjs.org/@ant-design/fast-color/-/fast-color-2.0.6.tgz",+ "integrity": "sha512-y2217gk4NqL35giHl72o6Zzqji9O7vHh9YmhUVkPtAOpoTCH4uWxo/pr4VE8t0+ChEPs0qo4eJRC5Q1eXWo3vA==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.24.7"+ },+ "engines": {+ "node": ">=8.x"+ }+ },+ "node_modules/@rc-component/context": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/@rc-component/context/-/context-1.4.0.tgz",+ "integrity": "sha512-kFcNxg9oLRMoL3qki0OMxK+7g5mypjgaaJp/pkOis/6rVxma9nJBF/8kCIuTYHUQNr0ii7MxqE33wirPZLJQ2w==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.10.1",+ "rc-util": "^5.27.0"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/@rc-component/mini-decimal": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@rc-component/mini-decimal/-/mini-decimal-1.1.0.tgz",+ "integrity": "sha512-jS4E7T9Li2GuYwI6PyiVXmxTiM6b07rlD9Ge8uGZSCz3WlzcG5ZK7g5bbuKNeZ9pgUuPK/5guV781ujdVpm4HQ==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.18.0"+ },+ "engines": {+ "node": ">=8.x"+ }+ },+ "node_modules/@rc-component/mutate-observer": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@rc-component/mutate-observer/-/mutate-observer-1.1.0.tgz",+ "integrity": "sha512-QjrOsDXQusNwGZPf4/qRQasg7UFEj06XiCJ8iuiq/Io7CrHrgVi6Uuetw60WAMG1799v+aM8kyc+1L/GBbHSlw==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.18.0",+ "classnames": "^2.3.2",+ "rc-util": "^5.24.4"+ },+ "engines": {+ "node": ">=8.x"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/@rc-component/portal": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/@rc-component/portal/-/portal-1.1.2.tgz",+ "integrity": "sha512-6f813C0IsasTZms08kfA8kPAGxbbkYToa8ALaiDIGGECU4i9hj8Plgbx0sNJDrey3EtHO30hmdaxtT0138xZcg==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.18.0",+ "classnames": "^2.3.2",+ "rc-util": "^5.24.4"+ },+ "engines": {+ "node": ">=8.x"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/@rc-component/qrcode": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@rc-component/qrcode/-/qrcode-1.1.1.tgz",+ "integrity": "sha512-LfLGNymzKdUPjXUbRP+xOhIWY4jQ+YMj5MmWAcgcAq1Ij8XP7tRmAXqyuv96XvLUBE/5cA8hLFl9eO1JQMujrA==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.24.7"+ },+ "engines": {+ "node": ">=8.x"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/@rc-component/tour": {+ "version": "1.15.1",+ "resolved": "https://registry.npmjs.org/@rc-component/tour/-/tour-1.15.1.tgz",+ "integrity": "sha512-Tr2t7J1DKZUpfJuDZWHxyxWpfmj8EZrqSgyMZ+BCdvKZ6r1UDsfU46M/iWAAFBy961Ssfom2kv5f3UcjIL2CmQ==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.18.0",+ "@rc-component/portal": "^1.0.0-9",+ "@rc-component/trigger": "^2.0.0",+ "classnames": "^2.3.2",+ "rc-util": "^5.24.4"+ },+ "engines": {+ "node": ">=8.x"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/@rc-component/trigger": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@rc-component/trigger/-/trigger-2.3.0.tgz",+ "integrity": "sha512-iwaxZyzOuK0D7lS+0AQEtW52zUWxoGqTGkke3dRyb8pYiShmRpCjB/8TzPI4R6YySCH7Vm9BZj/31VPiiQTLBg==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.23.2",+ "@rc-component/portal": "^1.1.0",+ "classnames": "^2.3.2",+ "rc-motion": "^2.0.0",+ "rc-resize-observer": "^1.3.1",+ "rc-util": "^5.44.0"+ },+ "engines": {+ "node": ">=8.x"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/@rc-component/util": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/@rc-component/util/-/util-1.4.0.tgz",+ "integrity": "sha512-LQlShcJKu0p3JUTAenKrWtqVW0+c4PJKedOqEaef9gTVL70O3cG4xZJ7VXfm0blGzORKFEkd3oQGalaUBNZ3Lg==",+ "license": "MIT",+ "dependencies": {+ "is-mobile": "^5.0.0",+ "react-is": "^18.2.0"+ },+ "peerDependencies": {+ "react": ">=18.0.0",+ "react-dom": ">=18.0.0"+ }+ },+ "node_modules/@reactflow/background": {+ "version": "11.3.14",+ "resolved": "https://registry.npmjs.org/@reactflow/background/-/background-11.3.14.tgz",+ "integrity": "sha512-Gewd7blEVT5Lh6jqrvOgd4G6Qk17eGKQfsDXgyRSqM+CTwDqRldG2LsWN4sNeno6sbqVIC2fZ+rAUBFA9ZEUDA==",+ "license": "MIT",+ "dependencies": {+ "@reactflow/core": "11.11.4",+ "classcat": "^5.0.3",+ "zustand": "^4.4.1"+ },+ "peerDependencies": {+ "react": ">=17",+ "react-dom": ">=17"+ }+ },+ "node_modules/@reactflow/background/node_modules/zustand": {+ "version": "4.5.7",+ "resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.7.tgz",+ "integrity": "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==",+ "license": "MIT",+ "dependencies": {+ "use-sync-external-store": "^1.2.2"+ },+ "engines": {+ "node": ">=12.7.0"+ },+ "peerDependencies": {+ "@types/react": ">=16.8",+ "immer": ">=9.0.6",+ "react": ">=16.8"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "immer": {+ "optional": true+ },+ "react": {+ "optional": true+ }+ }+ },+ "node_modules/@reactflow/controls": {+ "version": "11.2.14",+ "resolved": "https://registry.npmjs.org/@reactflow/controls/-/controls-11.2.14.tgz",+ "integrity": "sha512-MiJp5VldFD7FrqaBNIrQ85dxChrG6ivuZ+dcFhPQUwOK3HfYgX2RHdBua+gx+40p5Vw5It3dVNp/my4Z3jF0dw==",+ "license": "MIT",+ "dependencies": {+ "@reactflow/core": "11.11.4",+ "classcat": "^5.0.3",+ "zustand": "^4.4.1"+ },+ "peerDependencies": {+ "react": ">=17",+ "react-dom": ">=17"+ }+ },+ "node_modules/@reactflow/controls/node_modules/zustand": {+ "version": "4.5.7",+ "resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.7.tgz",+ "integrity": "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==",+ "license": "MIT",+ "dependencies": {+ "use-sync-external-store": "^1.2.2"+ },+ "engines": {+ "node": ">=12.7.0"+ },+ "peerDependencies": {+ "@types/react": ">=16.8",+ "immer": ">=9.0.6",+ "react": ">=16.8"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "immer": {+ "optional": true+ },+ "react": {+ "optional": true+ }+ }+ },+ "node_modules/@reactflow/core": {+ "version": "11.11.4",+ "resolved": "https://registry.npmjs.org/@reactflow/core/-/core-11.11.4.tgz",+ "integrity": "sha512-H4vODklsjAq3AMq6Np4LE12i1I4Ta9PrDHuBR9GmL8uzTt2l2jh4CiQbEMpvMDcp7xi4be0hgXj+Ysodde/i7Q==",+ "license": "MIT",+ "dependencies": {+ "@types/d3": "^7.4.0",+ "@types/d3-drag": "^3.0.1",+ "@types/d3-selection": "^3.0.3",+ "@types/d3-zoom": "^3.0.1",+ "classcat": "^5.0.3",+ "d3-drag": "^3.0.0",+ "d3-selection": "^3.0.0",+ "d3-zoom": "^3.0.0",+ "zustand": "^4.4.1"+ },+ "peerDependencies": {+ "react": ">=17",+ "react-dom": ">=17"+ }+ },+ "node_modules/@reactflow/core/node_modules/zustand": {+ "version": "4.5.7",+ "resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.7.tgz",+ "integrity": "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==",+ "license": "MIT",+ "dependencies": {+ "use-sync-external-store": "^1.2.2"+ },+ "engines": {+ "node": ">=12.7.0"+ },+ "peerDependencies": {+ "@types/react": ">=16.8",+ "immer": ">=9.0.6",+ "react": ">=16.8"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "immer": {+ "optional": true+ },+ "react": {+ "optional": true+ }+ }+ },+ "node_modules/@reactflow/minimap": {+ "version": "11.7.14",+ "resolved": "https://registry.npmjs.org/@reactflow/minimap/-/minimap-11.7.14.tgz",+ "integrity": "sha512-mpwLKKrEAofgFJdkhwR5UQ1JYWlcAAL/ZU/bctBkuNTT1yqV+y0buoNVImsRehVYhJwffSWeSHaBR5/GJjlCSQ==",+ "license": "MIT",+ "dependencies": {+ "@reactflow/core": "11.11.4",+ "@types/d3-selection": "^3.0.3",+ "@types/d3-zoom": "^3.0.1",+ "classcat": "^5.0.3",+ "d3-selection": "^3.0.0",+ "d3-zoom": "^3.0.0",+ "zustand": "^4.4.1"+ },+ "peerDependencies": {+ "react": ">=17",+ "react-dom": ">=17"+ }+ },+ "node_modules/@reactflow/minimap/node_modules/zustand": {+ "version": "4.5.7",+ "resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.7.tgz",+ "integrity": "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==",+ "license": "MIT",+ "dependencies": {+ "use-sync-external-store": "^1.2.2"+ },+ "engines": {+ "node": ">=12.7.0"+ },+ "peerDependencies": {+ "@types/react": ">=16.8",+ "immer": ">=9.0.6",+ "react": ">=16.8"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "immer": {+ "optional": true+ },+ "react": {+ "optional": true+ }+ }+ },+ "node_modules/@reactflow/node-resizer": {+ "version": "2.2.14",+ "resolved": "https://registry.npmjs.org/@reactflow/node-resizer/-/node-resizer-2.2.14.tgz",+ "integrity": "sha512-fwqnks83jUlYr6OHcdFEedumWKChTHRGw/kbCxj0oqBd+ekfs+SIp4ddyNU0pdx96JIm5iNFS0oNrmEiJbbSaA==",+ "license": "MIT",+ "dependencies": {+ "@reactflow/core": "11.11.4",+ "classcat": "^5.0.4",+ "d3-drag": "^3.0.0",+ "d3-selection": "^3.0.0",+ "zustand": "^4.4.1"+ },+ "peerDependencies": {+ "react": ">=17",+ "react-dom": ">=17"+ }+ },+ "node_modules/@reactflow/node-resizer/node_modules/zustand": {+ "version": "4.5.7",+ "resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.7.tgz",+ "integrity": "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==",+ "license": "MIT",+ "dependencies": {+ "use-sync-external-store": "^1.2.2"+ },+ "engines": {+ "node": ">=12.7.0"+ },+ "peerDependencies": {+ "@types/react": ">=16.8",+ "immer": ">=9.0.6",+ "react": ">=16.8"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "immer": {+ "optional": true+ },+ "react": {+ "optional": true+ }+ }+ },+ "node_modules/@reactflow/node-toolbar": {+ "version": "1.3.14",+ "resolved": "https://registry.npmjs.org/@reactflow/node-toolbar/-/node-toolbar-1.3.14.tgz",+ "integrity": "sha512-rbynXQnH/xFNu4P9H+hVqlEUafDCkEoCy0Dg9mG22Sg+rY/0ck6KkrAQrYrTgXusd+cEJOMK0uOOFCK2/5rSGQ==",+ "license": "MIT",+ "dependencies": {+ "@reactflow/core": "11.11.4",+ "classcat": "^5.0.3",+ "zustand": "^4.4.1"+ },+ "peerDependencies": {+ "react": ">=17",+ "react-dom": ">=17"+ }+ },+ "node_modules/@reactflow/node-toolbar/node_modules/zustand": {+ "version": "4.5.7",+ "resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.7.tgz",+ "integrity": "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==",+ "license": "MIT",+ "dependencies": {+ "use-sync-external-store": "^1.2.2"+ },+ "engines": {+ "node": ">=12.7.0"+ },+ "peerDependencies": {+ "@types/react": ">=16.8",+ "immer": ">=9.0.6",+ "react": ">=16.8"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "immer": {+ "optional": true+ },+ "react": {+ "optional": true+ }+ }+ },+ "node_modules/@rolldown/pluginutils": {+ "version": "1.0.0-beta.47",+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.47.tgz",+ "integrity": "sha512-8QagwMH3kNCuzD8EWL8R2YPW5e4OrHNSAHRFDdmFqEwEaD/KcNKjVoumo+gP2vW5eKB2UPbM6vTYiGZX0ixLnw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@rollup/rollup-android-arm-eabi": {+ "version": "4.53.3",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.53.3.tgz",+ "integrity": "sha512-mRSi+4cBjrRLoaal2PnqH82Wqyb+d3HsPUN/W+WslCXsZsyHa9ZeQQX/pQsZaVIWDkPcpV6jJ+3KLbTbgnwv8w==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ]+ },+ "node_modules/@rollup/rollup-android-arm64": {+ "version": "4.53.3",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.53.3.tgz",+ "integrity": "sha512-CbDGaMpdE9sh7sCmTrTUyllhrg65t6SwhjlMJsLr+J8YjFuPmCEjbBSx4Z/e4SmDyH3aB5hGaJUP2ltV/vcs4w==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ]+ },+ "node_modules/@rollup/rollup-darwin-arm64": {+ "version": "4.53.3",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.53.3.tgz",+ "integrity": "sha512-Nr7SlQeqIBpOV6BHHGZgYBuSdanCXuw09hon14MGOLGmXAFYjx1wNvquVPmpZnl0tLjg25dEdr4IQ6GgyToCUA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@rollup/rollup-darwin-x64": {+ "version": "4.53.3",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.53.3.tgz",+ "integrity": "sha512-DZ8N4CSNfl965CmPktJ8oBnfYr3F8dTTNBQkRlffnUarJ2ohudQD17sZBa097J8xhQ26AwhHJ5mvUyQW8ddTsQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@rollup/rollup-freebsd-arm64": {+ "version": "4.53.3",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.53.3.tgz",+ "integrity": "sha512-yMTrCrK92aGyi7GuDNtGn2sNW+Gdb4vErx4t3Gv/Tr+1zRb8ax4z8GWVRfr3Jw8zJWvpGHNpss3vVlbF58DZ4w==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ]+ },+ "node_modules/@rollup/rollup-freebsd-x64": {+ "version": "4.53.3",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.53.3.tgz",+ "integrity": "sha512-lMfF8X7QhdQzseM6XaX0vbno2m3hlyZFhwcndRMw8fbAGUGL3WFMBdK0hbUBIUYcEcMhVLr1SIamDeuLBnXS+Q==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm-gnueabihf": {+ "version": "4.53.3",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.53.3.tgz",+ "integrity": "sha512-k9oD15soC/Ln6d2Wv/JOFPzZXIAIFLp6B+i14KhxAfnq76ajt0EhYc5YPeX6W1xJkAdItcVT+JhKl1QZh44/qw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm-musleabihf": {+ "version": "4.53.3",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.53.3.tgz",+ "integrity": "sha512-vTNlKq+N6CK/8UktsrFuc+/7NlEYVxgaEgRXVUVK258Z5ymho29skzW1sutgYjqNnquGwVUObAaxae8rZ6YMhg==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm64-gnu": {+ "version": "4.53.3",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.53.3.tgz",+ "integrity": "sha512-RGrFLWgMhSxRs/EWJMIFM1O5Mzuz3Xy3/mnxJp/5cVhZ2XoCAxJnmNsEyeMJtpK+wu0FJFWz+QF4mjCA7AUQ3w==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm64-musl": {+ "version": "4.53.3",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.53.3.tgz",+ "integrity": "sha512-kASyvfBEWYPEwe0Qv4nfu6pNkITLTb32p4yTgzFCocHnJLAHs+9LjUu9ONIhvfT/5lv4YS5muBHyuV84epBo/A==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-loong64-gnu": {+ "version": "4.53.3",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.53.3.tgz",+ "integrity": "sha512-JiuKcp2teLJwQ7vkJ95EwESWkNRFJD7TQgYmCnrPtlu50b4XvT5MOmurWNrCj3IFdyjBQ5p9vnrX4JM6I8OE7g==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-ppc64-gnu": {+ "version": "4.53.3",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.53.3.tgz",+ "integrity": "sha512-EoGSa8nd6d3T7zLuqdojxC20oBfNT8nexBbB/rkxgKj5T5vhpAQKKnD+h3UkoMuTyXkP5jTjK/ccNRmQrPNDuw==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-riscv64-gnu": {+ "version": "4.53.3",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.53.3.tgz",+ "integrity": "sha512-4s+Wped2IHXHPnAEbIB0YWBv7SDohqxobiiPA1FIWZpX+w9o2i4LezzH/NkFUl8LRci/8udci6cLq+jJQlh+0g==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-riscv64-musl": {+ "version": "4.53.3",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.53.3.tgz",+ "integrity": "sha512-68k2g7+0vs2u9CxDt5ktXTngsxOQkSEV/xBbwlqYcUrAVh6P9EgMZvFsnHy4SEiUl46Xf0IObWVbMvPrr2gw8A==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-s390x-gnu": {+ "version": "4.53.3",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.53.3.tgz",+ "integrity": "sha512-VYsFMpULAz87ZW6BVYw3I6sWesGpsP9OPcyKe8ofdg9LHxSbRMd7zrVrr5xi/3kMZtpWL/wC+UIJWJYVX5uTKg==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-x64-gnu": {+ "version": "4.53.3",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.53.3.tgz",+ "integrity": "sha512-3EhFi1FU6YL8HTUJZ51imGJWEX//ajQPfqWLI3BQq4TlvHy4X0MOr5q3D2Zof/ka0d5FNdPwZXm3Yyib/UEd+w==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-x64-musl": {+ "version": "4.53.3",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.53.3.tgz",+ "integrity": "sha512-eoROhjcc6HbZCJr+tvVT8X4fW3/5g/WkGvvmwz/88sDtSJzO7r/blvoBDgISDiCjDRZmHpwud7h+6Q9JxFwq1Q==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-openharmony-arm64": {+ "version": "4.53.3",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.53.3.tgz",+ "integrity": "sha512-OueLAWgrNSPGAdUdIjSWXw+u/02BRTcnfw9PN41D2vq/JSEPnJnVuBgw18VkN8wcd4fjUs+jFHVM4t9+kBSNLw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ]+ },+ "node_modules/@rollup/rollup-win32-arm64-msvc": {+ "version": "4.53.3",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.53.3.tgz",+ "integrity": "sha512-GOFuKpsxR/whszbF/bzydebLiXIHSgsEUp6M0JI8dWvi+fFa1TD6YQa4aSZHtpmh2/uAlj/Dy+nmby3TJ3pkTw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rollup/rollup-win32-ia32-msvc": {+ "version": "4.53.3",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.53.3.tgz",+ "integrity": "sha512-iah+THLcBJdpfZ1TstDFbKNznlzoxa8fmnFYK4V67HvmuNYkVdAywJSoteUszvBQ9/HqN2+9AZghbajMsFT+oA==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rollup/rollup-win32-x64-gnu": {+ "version": "4.53.3",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.53.3.tgz",+ "integrity": "sha512-J9QDiOIZlZLdcot5NXEepDkstocktoVjkaKUtqzgzpt2yWjGlbYiKyp05rWwk4nypbYUNoFAztEgixoLaSETkg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rollup/rollup-win32-x64-msvc": {+ "version": "4.53.3",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.53.3.tgz",+ "integrity": "sha512-UhTd8u31dXadv0MopwGgNOBpUVROFKWVQgAg5N1ESyCz8AuBcMqm4AuTjrwgQKGDfoFuz02EuMRHQIw/frmYKQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@shikijs/core": {+ "version": "3.19.0",+ "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-3.19.0.tgz",+ "integrity": "sha512-L7SrRibU7ZoYi1/TrZsJOFAnnHyLTE1SwHG1yNWjZIVCqjOEmCSuK2ZO9thnRbJG6TOkPp+Z963JmpCNw5nzvA==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/types": "3.19.0",+ "@shikijs/vscode-textmate": "^10.0.2",+ "@types/hast": "^3.0.4",+ "hast-util-to-html": "^9.0.5"+ }+ },+ "node_modules/@shikijs/engine-javascript": {+ "version": "3.19.0",+ "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-3.19.0.tgz",+ "integrity": "sha512-ZfWJNm2VMhKkQIKT9qXbs76RRcT0SF/CAvEz0+RkpUDAoDaCx0uFdCGzSRiD9gSlhm6AHkjdieOBJMaO2eC1rQ==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/types": "3.19.0",+ "@shikijs/vscode-textmate": "^10.0.2",+ "oniguruma-to-es": "^4.3.4"+ }+ },+ "node_modules/@shikijs/engine-oniguruma": {+ "version": "3.19.0",+ "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-3.19.0.tgz",+ "integrity": "sha512-1hRxtYIJfJSZeM5ivbUXv9hcJP3PWRo5prG/V2sWwiubUKTa+7P62d2qxCW8jiVFX4pgRHhnHNp+qeR7Xl+6kg==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/types": "3.19.0",+ "@shikijs/vscode-textmate": "^10.0.2"+ }+ },+ "node_modules/@shikijs/langs": {+ "version": "3.19.0",+ "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-3.19.0.tgz",+ "integrity": "sha512-dBMFzzg1QiXqCVQ5ONc0z2ebyoi5BKz+MtfByLm0o5/nbUu3Iz8uaTCa5uzGiscQKm7lVShfZHU1+OG3t5hgwg==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/types": "3.19.0"+ }+ },+ "node_modules/@shikijs/themes": {+ "version": "3.19.0",+ "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-3.19.0.tgz",+ "integrity": "sha512-H36qw+oh91Y0s6OlFfdSuQ0Ld+5CgB/VE6gNPK+Hk4VRbVG/XQgkjnt4KzfnnoO6tZPtKJKHPjwebOCfjd6F8A==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/types": "3.19.0"+ }+ },+ "node_modules/@shikijs/transformers": {+ "version": "3.19.0",+ "resolved": "https://registry.npmjs.org/@shikijs/transformers/-/transformers-3.19.0.tgz",+ "integrity": "sha512-e6vwrsyw+wx4OkcrDbL+FVCxwx8jgKiCoXzakVur++mIWVcgpzIi8vxf4/b4dVTYrV/nUx5RjinMf4tq8YV8Fw==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/core": "3.19.0",+ "@shikijs/types": "3.19.0"+ }+ },+ "node_modules/@shikijs/types": {+ "version": "3.19.0",+ "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-3.19.0.tgz",+ "integrity": "sha512-Z2hdeEQlzuntf/BZpFG8a+Fsw9UVXdML7w0o3TgSXV3yNESGon+bs9ITkQb3Ki7zxoXOOu5oJWqZ2uto06V9iQ==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/vscode-textmate": "^10.0.2",+ "@types/hast": "^3.0.4"+ }+ },+ "node_modules/@shikijs/vscode-textmate": {+ "version": "10.0.2",+ "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.0.2.tgz",+ "integrity": "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==",+ "license": "MIT"+ },+ "node_modules/@splinetool/runtime": {+ "version": "0.9.526",+ "resolved": "https://registry.npmjs.org/@splinetool/runtime/-/runtime-0.9.526.tgz",+ "integrity": "sha512-qznHbXA5aKwDbCgESAothCNm1IeEZcmNWG145p5aXj4w5uoqR1TZ9qkTHTKLTsUbHeitCwdhzmRqan1kxboLgQ==",+ "dependencies": {+ "on-change": "^4.0.0",+ "semver-compare": "^1.0.0"+ }+ },+ "node_modules/@standard-schema/spec": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.0.0.tgz",+ "integrity": "sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA==",+ "license": "MIT"+ },+ "node_modules/@stitches/react": {+ "version": "1.2.8",+ "resolved": "https://registry.npmjs.org/@stitches/react/-/react-1.2.8.tgz",+ "integrity": "sha512-9g9dWI4gsSVe8bNLlb+lMkBYsnIKCZTmvqvDG+Avnn69XfmHZKiaMrx7cgTaddq7aTPPmXiTsbFcUy0xgI4+wA==",+ "license": "MIT",+ "peerDependencies": {+ "react": ">= 16.3.0"+ }+ },+ "node_modules/@types/babel__core": {+ "version": "7.20.5",+ "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",+ "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/parser": "^7.20.7",+ "@babel/types": "^7.20.7",+ "@types/babel__generator": "*",+ "@types/babel__template": "*",+ "@types/babel__traverse": "*"+ }+ },+ "node_modules/@types/babel__generator": {+ "version": "7.27.0",+ "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz",+ "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/types": "^7.0.0"+ }+ },+ "node_modules/@types/babel__template": {+ "version": "7.4.4",+ "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz",+ "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/parser": "^7.1.0",+ "@babel/types": "^7.0.0"+ }+ },+ "node_modules/@types/babel__traverse": {+ "version": "7.28.0",+ "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz",+ "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/types": "^7.28.2"+ }+ },+ "node_modules/@types/d3": {+ "version": "7.4.3",+ "resolved": "https://registry.npmjs.org/@types/d3/-/d3-7.4.3.tgz",+ "integrity": "sha512-lZXZ9ckh5R8uiFVt8ogUNf+pIrK4EsWrx2Np75WvF/eTpJ0FMHNhjXk8CKEx/+gpHbNQyJWehbFaTvqmHWB3ww==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-array": "*",+ "@types/d3-axis": "*",+ "@types/d3-brush": "*",+ "@types/d3-chord": "*",+ "@types/d3-color": "*",+ "@types/d3-contour": "*",+ "@types/d3-delaunay": "*",+ "@types/d3-dispatch": "*",+ "@types/d3-drag": "*",+ "@types/d3-dsv": "*",+ "@types/d3-ease": "*",+ "@types/d3-fetch": "*",+ "@types/d3-force": "*",+ "@types/d3-format": "*",+ "@types/d3-geo": "*",+ "@types/d3-hierarchy": "*",+ "@types/d3-interpolate": "*",+ "@types/d3-path": "*",+ "@types/d3-polygon": "*",+ "@types/d3-quadtree": "*",+ "@types/d3-random": "*",+ "@types/d3-scale": "*",+ "@types/d3-scale-chromatic": "*",+ "@types/d3-selection": "*",+ "@types/d3-shape": "*",+ "@types/d3-time": "*",+ "@types/d3-time-format": "*",+ "@types/d3-timer": "*",+ "@types/d3-transition": "*",+ "@types/d3-zoom": "*"+ }+ },+ "node_modules/@types/d3-array": {+ "version": "3.2.2",+ "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",+ "integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==",+ "license": "MIT"+ },+ "node_modules/@types/d3-axis": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/@types/d3-axis/-/d3-axis-3.0.6.tgz",+ "integrity": "sha512-pYeijfZuBd87T0hGn0FO1vQ/cgLk6E1ALJjfkC0oJ8cbwkZl3TpgS8bVBLZN+2jjGgg38epgxb2zmoGtSfvgMw==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-selection": "*"+ }+ },+ "node_modules/@types/d3-brush": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/@types/d3-brush/-/d3-brush-3.0.6.tgz",+ "integrity": "sha512-nH60IZNNxEcrh6L1ZSMNA28rj27ut/2ZmI3r96Zd+1jrZD++zD3LsMIjWlvg4AYrHn/Pqz4CF3veCxGjtbqt7A==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-selection": "*"+ }+ },+ "node_modules/@types/d3-chord": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/@types/d3-chord/-/d3-chord-3.0.6.tgz",+ "integrity": "sha512-LFYWWd8nwfwEmTZG9PfQxd17HbNPksHBiJHaKuY1XeqscXacsS2tyoo6OdRsjf+NQYeB6XrNL3a25E3gH69lcg==",+ "license": "MIT"+ },+ "node_modules/@types/d3-color": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",+ "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",+ "license": "MIT"+ },+ "node_modules/@types/d3-contour": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/@types/d3-contour/-/d3-contour-3.0.6.tgz",+ "integrity": "sha512-BjzLgXGnCWjUSYGfH1cpdo41/hgdWETu4YxpezoztawmqsvCeep+8QGfiY6YbDvfgHz/DkjeIkkZVJavB4a3rg==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-array": "*",+ "@types/geojson": "*"+ }+ },+ "node_modules/@types/d3-delaunay": {+ "version": "6.0.4",+ "resolved": "https://registry.npmjs.org/@types/d3-delaunay/-/d3-delaunay-6.0.4.tgz",+ "integrity": "sha512-ZMaSKu4THYCU6sV64Lhg6qjf1orxBthaC161plr5KuPHo3CNm8DTHiLw/5Eq2b6TsNP0W0iJrUOFscY6Q450Hw==",+ "license": "MIT"+ },+ "node_modules/@types/d3-dispatch": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/@types/d3-dispatch/-/d3-dispatch-3.0.7.tgz",+ "integrity": "sha512-5o9OIAdKkhN1QItV2oqaE5KMIiXAvDWBDPrD85e58Qlz1c1kI/J0NcqbEG88CoTwJrYe7ntUCVfeUl2UJKbWgA==",+ "license": "MIT"+ },+ "node_modules/@types/d3-drag": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/@types/d3-drag/-/d3-drag-3.0.7.tgz",+ "integrity": "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-selection": "*"+ }+ },+ "node_modules/@types/d3-dsv": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/@types/d3-dsv/-/d3-dsv-3.0.7.tgz",+ "integrity": "sha512-n6QBF9/+XASqcKK6waudgL0pf/S5XHPPI8APyMLLUHd8NqouBGLsU8MgtO7NINGtPBtk9Kko/W4ea0oAspwh9g==",+ "license": "MIT"+ },+ "node_modules/@types/d3-ease": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",+ "integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==",+ "license": "MIT"+ },+ "node_modules/@types/d3-fetch": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/@types/d3-fetch/-/d3-fetch-3.0.7.tgz",+ "integrity": "sha512-fTAfNmxSb9SOWNB9IoG5c8Hg6R+AzUHDRlsXsDZsNp6sxAEOP0tkP3gKkNSO/qmHPoBFTxNrjDprVHDQDvo5aA==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-dsv": "*"+ }+ },+ "node_modules/@types/d3-force": {+ "version": "3.0.10",+ "resolved": "https://registry.npmjs.org/@types/d3-force/-/d3-force-3.0.10.tgz",+ "integrity": "sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw==",+ "license": "MIT"+ },+ "node_modules/@types/d3-format": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/@types/d3-format/-/d3-format-3.0.4.tgz",+ "integrity": "sha512-fALi2aI6shfg7vM5KiR1wNJnZ7r6UuggVqtDA+xiEdPZQwy/trcQaHnwShLuLdta2rTymCNpxYTiMZX/e09F4g==",+ "license": "MIT"+ },+ "node_modules/@types/d3-geo": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/@types/d3-geo/-/d3-geo-3.1.0.tgz",+ "integrity": "sha512-856sckF0oP/diXtS4jNsiQw/UuK5fQG8l/a9VVLeSouf1/PPbBE1i1W852zVwKwYCBkFJJB7nCFTbk6UMEXBOQ==",+ "license": "MIT",+ "dependencies": {+ "@types/geojson": "*"+ }+ },+ "node_modules/@types/d3-hierarchy": {+ "version": "3.1.7",+ "resolved": "https://registry.npmjs.org/@types/d3-hierarchy/-/d3-hierarchy-3.1.7.tgz",+ "integrity": "sha512-tJFtNoYBtRtkNysX1Xq4sxtjK8YgoWUNpIiUee0/jHGRwqvzYxkq0hGVbbOGSz+JgFxxRu4K8nb3YpG3CMARtg==",+ "license": "MIT"+ },+ "node_modules/@types/d3-interpolate": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",+ "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-color": "*"+ }+ },+ "node_modules/@types/d3-path": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz",+ "integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",+ "license": "MIT"+ },+ "node_modules/@types/d3-polygon": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/@types/d3-polygon/-/d3-polygon-3.0.2.tgz",+ "integrity": "sha512-ZuWOtMaHCkN9xoeEMr1ubW2nGWsp4nIql+OPQRstu4ypeZ+zk3YKqQT0CXVe/PYqrKpZAi+J9mTs05TKwjXSRA==",+ "license": "MIT"+ },+ "node_modules/@types/d3-quadtree": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/@types/d3-quadtree/-/d3-quadtree-3.0.6.tgz",+ "integrity": "sha512-oUzyO1/Zm6rsxKRHA1vH0NEDG58HrT5icx/azi9MF1TWdtttWl0UIUsjEQBBh+SIkrpd21ZjEv7ptxWys1ncsg==",+ "license": "MIT"+ },+ "node_modules/@types/d3-random": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/@types/d3-random/-/d3-random-3.0.3.tgz",+ "integrity": "sha512-Imagg1vJ3y76Y2ea0871wpabqp613+8/r0mCLEBfdtqC7xMSfj9idOnmBYyMoULfHePJyxMAw3nWhJxzc+LFwQ==",+ "license": "MIT"+ },+ "node_modules/@types/d3-scale": {+ "version": "4.0.9",+ "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",+ "integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-time": "*"+ }+ },+ "node_modules/@types/d3-scale-chromatic": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/@types/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz",+ "integrity": "sha512-iWMJgwkK7yTRmWqRB5plb1kadXyQ5Sj8V/zYlFGMUBbIPKQScw+Dku9cAAMgJG+z5GYDoMjWGLVOvjghDEFnKQ==",+ "license": "MIT"+ },+ "node_modules/@types/d3-selection": {+ "version": "3.0.11",+ "resolved": "https://registry.npmjs.org/@types/d3-selection/-/d3-selection-3.0.11.tgz",+ "integrity": "sha512-bhAXu23DJWsrI45xafYpkQ4NtcKMwWnAC/vKrd2l+nxMFuvOT3XMYTIj2opv8vq8AO5Yh7Qac/nSeP/3zjTK0w==",+ "license": "MIT"+ },+ "node_modules/@types/d3-shape": {+ "version": "3.1.7",+ "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.7.tgz",+ "integrity": "sha512-VLvUQ33C+3J+8p+Daf+nYSOsjB4GXp19/S/aGo60m9h1v6XaxjiT82lKVWJCfzhtuZ3yD7i/TPeC/fuKLLOSmg==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-path": "*"+ }+ },+ "node_modules/@types/d3-time": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz",+ "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",+ "license": "MIT"+ },+ "node_modules/@types/d3-time-format": {+ "version": "4.0.3",+ "resolved": "https://registry.npmjs.org/@types/d3-time-format/-/d3-time-format-4.0.3.tgz",+ "integrity": "sha512-5xg9rC+wWL8kdDj153qZcsJ0FWiFt0J5RB6LYUNZjwSnesfblqrI/bJ1wBdJ8OQfncgbJG5+2F+qfqnqyzYxyg==",+ "license": "MIT"+ },+ "node_modules/@types/d3-timer": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz",+ "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",+ "license": "MIT"+ },+ "node_modules/@types/d3-transition": {+ "version": "3.0.9",+ "resolved": "https://registry.npmjs.org/@types/d3-transition/-/d3-transition-3.0.9.tgz",+ "integrity": "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-selection": "*"+ }+ },+ "node_modules/@types/d3-zoom": {+ "version": "3.0.8",+ "resolved": "https://registry.npmjs.org/@types/d3-zoom/-/d3-zoom-3.0.8.tgz",+ "integrity": "sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-interpolate": "*",+ "@types/d3-selection": "*"+ }+ },+ "node_modules/@types/debug": {+ "version": "4.1.12",+ "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.12.tgz",+ "integrity": "sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==",+ "license": "MIT",+ "dependencies": {+ "@types/ms": "*"+ }+ },+ "node_modules/@types/estree": {+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",+ "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",+ "license": "MIT"+ },+ "node_modules/@types/estree-jsx": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/@types/estree-jsx/-/estree-jsx-1.0.5.tgz",+ "integrity": "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "*"+ }+ },+ "node_modules/@types/geojson": {+ "version": "7946.0.16",+ "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",+ "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",+ "license": "MIT"+ },+ "node_modules/@types/google.maps": {+ "version": "3.58.1",+ "resolved": "https://registry.npmjs.org/@types/google.maps/-/google.maps-3.58.1.tgz",+ "integrity": "sha512-X9QTSvGJ0nCfMzYOnaVs/k6/4L+7F5uCS+4iUmkLEls6J9S/Phv+m/i3mDeyc49ZBgwab3EFO1HEoBY7k98EGQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/hast": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz",+ "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "*"+ }+ },+ "node_modules/@types/hoist-non-react-statics": {+ "version": "3.3.7",+ "resolved": "https://registry.npmjs.org/@types/hoist-non-react-statics/-/hoist-non-react-statics-3.3.7.tgz",+ "integrity": "sha512-PQTyIulDkIDro8P+IHbKCsw7U2xxBYflVzW/FgWdCAePD9xGSidgA76/GeJ6lBKoblyhf9pBY763gbrN+1dI8g==",+ "license": "MIT",+ "dependencies": {+ "hoist-non-react-statics": "^3.3.0"+ },+ "peerDependencies": {+ "@types/react": "*"+ }+ },+ "node_modules/@types/js-cookie": {+ "version": "2.2.7",+ "resolved": "https://registry.npmjs.org/@types/js-cookie/-/js-cookie-2.2.7.tgz",+ "integrity": "sha512-aLkWa0C0vO5b4Sr798E26QgOkss68Un0bLjs7u9qxzPT5CG+8DuNTffWES58YzJs3hrVAOs1wonycqEBqNJubA==",+ "license": "MIT"+ },+ "node_modules/@types/json-schema": {+ "version": "7.0.15",+ "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",+ "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/katex": {+ "version": "0.16.7",+ "resolved": "https://registry.npmjs.org/@types/katex/-/katex-0.16.7.tgz",+ "integrity": "sha512-HMwFiRujE5PjrgwHQ25+bsLJgowjGjm5Z8FVSf0N6PwgJrwxH0QxzHYDcKsTfV3wva0vzrpqMTJS2jXPr5BMEQ==",+ "license": "MIT"+ },+ "node_modules/@types/mdast": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz",+ "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "*"+ }+ },+ "node_modules/@types/mdx": {+ "version": "2.0.13",+ "resolved": "https://registry.npmjs.org/@types/mdx/-/mdx-2.0.13.tgz",+ "integrity": "sha512-+OWZQfAYyio6YkJb3HLxDrvnx6SWWDbC0zVPfBRzUk0/nqoDyf6dNxQi3eArPe8rJ473nobTMQ/8Zk+LxJ+Yuw==",+ "license": "MIT"+ },+ "node_modules/@types/ms": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",+ "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",+ "license": "MIT"+ },+ "node_modules/@types/node": {+ "version": "24.10.1",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.1.tgz",+ "integrity": "sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "undici-types": "~7.16.0"+ }+ },+ "node_modules/@types/parse-json": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.2.tgz",+ "integrity": "sha512-dISoDXWWQwUquiKsyZ4Ng+HX2KsPL7LyHKHQwgGFEA3IaKac4Obd+h2a/a6waisAoepJlBcx9paWqjA8/HVjCw==",+ "license": "MIT"+ },+ "node_modules/@types/prismjs": {+ "version": "1.26.5",+ "resolved": "https://registry.npmjs.org/@types/prismjs/-/prismjs-1.26.5.tgz",+ "integrity": "sha512-AUZTa7hQ2KY5L7AmtSiqxlhWxb4ina0yd8hNbl4TWuqnv/pFP0nDMb3YrfSBf4hJVGLh2YEIBfKaBW/9UEl6IQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/react": {+ "version": "19.2.7",+ "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.7.tgz",+ "integrity": "sha512-MWtvHrGZLFttgeEj28VXHxpmwYbor/ATPYbBfSFZEIRK0ecCFLl2Qo55z52Hss+UV9CRN7trSeq1zbgx7YDWWg==",+ "license": "MIT",+ "dependencies": {+ "csstype": "^3.2.2"+ }+ },+ "node_modules/@types/react-dom": {+ "version": "19.2.3",+ "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz",+ "integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",+ "devOptional": true,+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "^19.2.0"+ }+ },+ "node_modules/@types/retry": {+ "version": "0.12.0",+ "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz",+ "integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==",+ "license": "MIT",+ "peer": true+ },+ "node_modules/@types/styled-components": {+ "version": "5.1.36",+ "resolved": "https://registry.npmjs.org/@types/styled-components/-/styled-components-5.1.36.tgz",+ "integrity": "sha512-pGMRNY5G2rNDKEv2DOiFYa7Ft1r0jrhmgBwHhOMzPTgCjO76bCot0/4uEfqj7K0Jf1KdQmDtAuaDk9EAs9foSw==",+ "license": "MIT",+ "dependencies": {+ "@types/hoist-non-react-statics": "*",+ "@types/react": "*",+ "csstype": "^3.2.2"+ }+ },+ "node_modules/@types/stylis": {+ "version": "4.2.5",+ "resolved": "https://registry.npmjs.org/@types/stylis/-/stylis-4.2.5.tgz",+ "integrity": "sha512-1Xve+NMN7FWjY14vLoY5tL3BVEQ/n42YLwaqJIPYhotZ9uBHt87VceMwWQpzmdEt2TNXIorIFG+YeCUUW7RInw==",+ "license": "MIT"+ },+ "node_modules/@types/trusted-types": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",+ "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",+ "license": "MIT"+ },+ "node_modules/@types/unist": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz",+ "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==",+ "license": "MIT"+ },+ "node_modules/@types/uuid": {+ "version": "10.0.0",+ "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz",+ "integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==",+ "license": "MIT",+ "peer": true+ },+ "node_modules/@ungap/structured-clone": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz",+ "integrity": "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==",+ "license": "ISC"+ },+ "node_modules/@use-gesture/core": {+ "version": "10.3.1",+ "resolved": "https://registry.npmjs.org/@use-gesture/core/-/core-10.3.1.tgz",+ "integrity": "sha512-WcINiDt8WjqBdUXye25anHiNxPc0VOrlT8F6LLkU6cycrOGUDyY/yyFmsg3k8i5OLvv25llc0QC45GhR/C8llw==",+ "license": "MIT"+ },+ "node_modules/@use-gesture/react": {+ "version": "10.3.1",+ "resolved": "https://registry.npmjs.org/@use-gesture/react/-/react-10.3.1.tgz",+ "integrity": "sha512-Yy19y6O2GJq8f7CHf7L0nxL8bf4PZCPaVOCgJrusOeFHY1LvHgYXnmnXg6N5iwAnbgbZCDjo60SiM6IPJi9C5g==",+ "license": "MIT",+ "dependencies": {+ "@use-gesture/core": "10.3.1"+ },+ "peerDependencies": {+ "react": ">= 16.8.0"+ }+ },+ "node_modules/@vercel/oidc": {+ "version": "3.0.5",+ "resolved": "https://registry.npmjs.org/@vercel/oidc/-/oidc-3.0.5.tgz",+ "integrity": "sha512-fnYhv671l+eTTp48gB4zEsTW/YtRgRPnkI2nT7x6qw5rkI1Lq2hTmQIpHPgyThI0znLK+vX2n9XxKdXZ7BUbbw==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@vitejs/plugin-react": {+ "version": "5.1.1",+ "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-5.1.1.tgz",+ "integrity": "sha512-WQfkSw0QbQ5aJ2CHYw23ZGkqnRwqKHD/KYsMeTkZzPT4Jcf0DcBxBtwMJxnu6E7oxw5+JC6ZAiePgh28uJ1HBA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/core": "^7.28.5",+ "@babel/plugin-transform-react-jsx-self": "^7.27.1",+ "@babel/plugin-transform-react-jsx-source": "^7.27.1",+ "@rolldown/pluginutils": "1.0.0-beta.47",+ "@types/babel__core": "^7.20.5",+ "react-refresh": "^0.18.0"+ },+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ },+ "peerDependencies": {+ "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"+ }+ },+ "node_modules/@xobotyi/scrollbar-width": {+ "version": "1.9.5",+ "resolved": "https://registry.npmjs.org/@xobotyi/scrollbar-width/-/scrollbar-width-1.9.5.tgz",+ "integrity": "sha512-N8tkAACJx2ww8vFMneJmaAgmjAG1tnVBZJRLRcx061tmsLRZHSEZSLuGWnwPtunsSLvSqXQ2wfp7Mgqg1I+2dQ==",+ "license": "MIT"+ },+ "node_modules/acorn": {+ "version": "8.15.0",+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",+ "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",+ "license": "MIT",+ "bin": {+ "acorn": "bin/acorn"+ },+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/acorn-jsx": {+ "version": "5.3.2",+ "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz",+ "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==",+ "license": "MIT",+ "peerDependencies": {+ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"+ }+ },+ "node_modules/ahooks": {+ "version": "3.9.6",+ "resolved": "https://registry.npmjs.org/ahooks/-/ahooks-3.9.6.tgz",+ "integrity": "sha512-Mr7f05swd5SmKlR9SZo5U6M0LsL4ErweLzpdgXjA1JPmnZ78Vr6wzx0jUtvoxrcqGKYnX0Yjc02iEASVxHFPjQ==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.21.0",+ "@types/js-cookie": "^3.0.6",+ "dayjs": "^1.9.1",+ "intersection-observer": "^0.12.0",+ "js-cookie": "^3.0.5",+ "lodash": "^4.17.21",+ "react-fast-compare": "^3.2.2",+ "resize-observer-polyfill": "^1.5.1",+ "screenfull": "^5.0.0",+ "tslib": "^2.4.1"+ },+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",+ "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },+ "node_modules/ahooks/node_modules/@types/js-cookie": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/@types/js-cookie/-/js-cookie-3.0.6.tgz",+ "integrity": "sha512-wkw9yd1kEXOPnvEeEV1Go1MmxtBJL0RR79aOTAApecWFVu7w0NNXNqhcWgvw2YgZDYadliXkl14pa3WXw5jlCQ==",+ "license": "MIT"+ },+ "node_modules/ahooks/node_modules/js-cookie": {+ "version": "3.0.5",+ "resolved": "https://registry.npmjs.org/js-cookie/-/js-cookie-3.0.5.tgz",+ "integrity": "sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw==",+ "license": "MIT",+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/ai": {+ "version": "5.0.106",+ "resolved": "https://registry.npmjs.org/ai/-/ai-5.0.106.tgz",+ "integrity": "sha512-M5obwavxSJJ3tGlAFqI6eltYNJB0D20X6gIBCFx/KVorb/X1fxVVfiZZpZb+Gslu4340droSOjT0aKQFCarNVg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@ai-sdk/gateway": "2.0.18",+ "@ai-sdk/provider": "2.0.0",+ "@ai-sdk/provider-utils": "3.0.18",+ "@opentelemetry/api": "1.9.0"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "zod": "^3.25.76 || ^4.1.8"+ }+ },+ "node_modules/ajv": {+ "version": "6.12.6",+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",+ "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.1",+ "fast-json-stable-stringify": "^2.0.0",+ "json-schema-traverse": "^0.4.1",+ "uri-js": "^4.2.2"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/epoberezkin"+ }+ },+ "node_modules/ansi-regex": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/ansi-styles": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",+ "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",+ "license": "MIT",+ "dependencies": {+ "color-convert": "^2.0.1"+ },+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },+ "node_modules/antd": {+ "version": "5.29.1",+ "resolved": "https://registry.npmjs.org/antd/-/antd-5.29.1.tgz",+ "integrity": "sha512-TTFVbpKbyL6cPfEoKq6Ya3BIjTUr7uDW9+7Z+1oysRv1gpcN7kQ4luH8r/+rXXwz4n6BIz1iBJ1ezKCdsdNW0w==",+ "license": "MIT",+ "dependencies": {+ "@ant-design/colors": "^7.2.1",+ "@ant-design/cssinjs": "^1.23.0",+ "@ant-design/cssinjs-utils": "^1.1.3",+ "@ant-design/fast-color": "^2.0.6",+ "@ant-design/icons": "^5.6.1",+ "@ant-design/react-slick": "~1.1.2",+ "@babel/runtime": "^7.26.0",+ "@rc-component/color-picker": "~2.0.1",+ "@rc-component/mutate-observer": "^1.1.0",+ "@rc-component/qrcode": "~1.1.0",+ "@rc-component/tour": "~1.15.1",+ "@rc-component/trigger": "^2.3.0",+ "classnames": "^2.5.1",+ "copy-to-clipboard": "^3.3.3",+ "dayjs": "^1.11.11",+ "rc-cascader": "~3.34.0",+ "rc-checkbox": "~3.5.0",+ "rc-collapse": "~3.9.0",+ "rc-dialog": "~9.6.0",+ "rc-drawer": "~7.3.0",+ "rc-dropdown": "~4.2.1",+ "rc-field-form": "~2.7.1",+ "rc-image": "~7.12.0",+ "rc-input": "~1.8.0",+ "rc-input-number": "~9.5.0",+ "rc-mentions": "~2.20.0",+ "rc-menu": "~9.16.1",+ "rc-motion": "^2.9.5",+ "rc-notification": "~5.6.4",+ "rc-pagination": "~5.1.0",+ "rc-picker": "~4.11.3",+ "rc-progress": "~4.0.0",+ "rc-rate": "~2.13.1",+ "rc-resize-observer": "^1.4.3",+ "rc-segmented": "~2.7.0",+ "rc-select": "~14.16.8",+ "rc-slider": "~11.1.9",+ "rc-steps": "~6.0.1",+ "rc-switch": "~4.1.0",+ "rc-table": "~7.54.0",+ "rc-tabs": "~15.7.0",+ "rc-textarea": "~1.10.2",+ "rc-tooltip": "~6.4.0",+ "rc-tree": "~5.13.1",+ "rc-tree-select": "~5.27.0",+ "rc-upload": "~4.11.0",+ "rc-util": "^5.44.4",+ "scroll-into-view-if-needed": "^3.1.0",+ "throttle-debounce": "^5.0.2"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/ant-design"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/antd-style": {+ "version": "3.7.1",+ "resolved": "https://registry.npmjs.org/antd-style/-/antd-style-3.7.1.tgz",+ "integrity": "sha512-CQOfddVp4aOvBfCepa+Kj2e7ap+2XBINg1Kn2osdE3oQvrD7KJu/K0sfnLcFLkgCJygbxmuazYdWLKb+drPDYA==",+ "license": "MIT",+ "dependencies": {+ "@ant-design/cssinjs": "^1.21.1",+ "@babel/runtime": "^7.24.1",+ "@emotion/cache": "^11.11.0",+ "@emotion/css": "^11.11.2",+ "@emotion/react": "^11.11.4",+ "@emotion/serialize": "^1.1.3",+ "@emotion/utils": "^1.2.1",+ "use-merge-value": "^1.2.0"+ },+ "peerDependencies": {+ "antd": ">=5.8.1",+ "react": ">=18"+ }+ },+ "node_modules/antd/node_modules/@ant-design/colors": {+ "version": "7.2.1",+ "resolved": "https://registry.npmjs.org/@ant-design/colors/-/colors-7.2.1.tgz",+ "integrity": "sha512-lCHDcEzieu4GA3n8ELeZ5VQ8pKQAWcGGLRTQ50aQM2iqPpq2evTxER84jfdPvsPAtEcZ7m44NI45edFMo8oOYQ==",+ "license": "MIT",+ "dependencies": {+ "@ant-design/fast-color": "^2.0.6"+ }+ },+ "node_modules/antd/node_modules/@ant-design/fast-color": {+ "version": "2.0.6",+ "resolved": "https://registry.npmjs.org/@ant-design/fast-color/-/fast-color-2.0.6.tgz",+ "integrity": "sha512-y2217gk4NqL35giHl72o6Zzqji9O7vHh9YmhUVkPtAOpoTCH4uWxo/pr4VE8t0+ChEPs0qo4eJRC5Q1eXWo3vA==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.24.7"+ },+ "engines": {+ "node": ">=8.x"+ }+ },+ "node_modules/antd/node_modules/@ant-design/icons": {+ "version": "5.6.1",+ "resolved": "https://registry.npmjs.org/@ant-design/icons/-/icons-5.6.1.tgz",+ "integrity": "sha512-0/xS39c91WjPAZOWsvi1//zjx6kAp4kxWwctR6kuU6p133w8RU0D2dSCvZC19uQyharg/sAvYxGYWl01BbZZfg==",+ "license": "MIT",+ "dependencies": {+ "@ant-design/colors": "^7.0.0",+ "@ant-design/icons-svg": "^4.4.0",+ "@babel/runtime": "^7.24.8",+ "classnames": "^2.2.6",+ "rc-util": "^5.31.1"+ },+ "engines": {+ "node": ">=8"+ },+ "peerDependencies": {+ "react": ">=16.0.0",+ "react-dom": ">=16.0.0"+ }+ },+ "node_modules/argparse": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",+ "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",+ "dev": true,+ "license": "Python-2.0"+ },+ "node_modules/aria-hidden": {+ "version": "1.2.6",+ "resolved": "https://registry.npmjs.org/aria-hidden/-/aria-hidden-1.2.6.tgz",+ "integrity": "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==",+ "license": "MIT",+ "dependencies": {+ "tslib": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/assign-symbols": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/assign-symbols/-/assign-symbols-1.0.0.tgz",+ "integrity": "sha512-Q+JC7Whu8HhmTdBph/Tq59IoRtoy6KAm5zzPv00WdujX82lbAL8K7WVjne7vdCsAmbF4AYaDOPyO3k0kl8qIrw==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/astring": {+ "version": "1.9.0",+ "resolved": "https://registry.npmjs.org/astring/-/astring-1.9.0.tgz",+ "integrity": "sha512-LElXdjswlqjWrPpJFg1Fx4wpkOCxj1TDHlSV4PlaRxHGWko024xICaa97ZkMfs6DRKlCguiAI+rbXv5GWwXIkg==",+ "license": "MIT",+ "bin": {+ "astring": "bin/astring"+ }+ },+ "node_modules/attr-accept": {+ "version": "2.2.5",+ "resolved": "https://registry.npmjs.org/attr-accept/-/attr-accept-2.2.5.tgz",+ "integrity": "sha512-0bDNnY/u6pPwHDMoF0FieU354oBi0a8rD9FcsLwzcGWbc8KS8KPIi7y+s13OlVY+gMWc/9xEMUgNE6Qm8ZllYQ==",+ "license": "MIT",+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/autoprefixer": {+ "version": "10.4.22",+ "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.22.tgz",+ "integrity": "sha512-ARe0v/t9gO28Bznv6GgqARmVqcWOV3mfgUPn9becPHMiD3o9BwlRgaeccZnwTpZ7Zwqrm+c1sUSsMxIzQzc8Xg==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/autoprefixer"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "browserslist": "^4.27.0",+ "caniuse-lite": "^1.0.30001754",+ "fraction.js": "^5.3.4",+ "normalize-range": "^0.1.2",+ "picocolors": "^1.1.1",+ "postcss-value-parser": "^4.2.0"+ },+ "bin": {+ "autoprefixer": "bin/autoprefixer"+ },+ "engines": {+ "node": "^10 || ^12 || >=14"+ },+ "peerDependencies": {+ "postcss": "^8.1.0"+ }+ },+ "node_modules/babel-plugin-macros": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/babel-plugin-macros/-/babel-plugin-macros-3.1.0.tgz",+ "integrity": "sha512-Cg7TFGpIr01vOQNODXOOaGz2NpCU5gl8x1qJFbb6hbZxR7XrcE2vtbAsTAbJ7/xwJtUuJEw8K8Zr/AE0LHlesg==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.12.5",+ "cosmiconfig": "^7.0.0",+ "resolve": "^1.19.0"+ },+ "engines": {+ "node": ">=10",+ "npm": ">=6"+ }+ },+ "node_modules/babel-plugin-polyfill-corejs2": {+ "version": "0.4.14",+ "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs2/-/babel-plugin-polyfill-corejs2-0.4.14.tgz",+ "integrity": "sha512-Co2Y9wX854ts6U8gAAPXfn0GmAyctHuK8n0Yhfjd6t30g7yvKjspvvOo9yG+z52PZRgFErt7Ka2pYnXCjLKEpg==",+ "license": "MIT",+ "dependencies": {+ "@babel/compat-data": "^7.27.7",+ "@babel/helper-define-polyfill-provider": "^0.6.5",+ "semver": "^6.3.1"+ },+ "peerDependencies": {+ "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0"+ }+ },+ "node_modules/babel-plugin-polyfill-corejs3": {+ "version": "0.13.0",+ "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs3/-/babel-plugin-polyfill-corejs3-0.13.0.tgz",+ "integrity": "sha512-U+GNwMdSFgzVmfhNm8GJUX88AadB3uo9KpJqS3FaqNIPKgySuvMb+bHPsOmmuWyIcuqZj/pzt1RUIUZns4y2+A==",+ "license": "MIT",+ "dependencies": {+ "@babel/helper-define-polyfill-provider": "^0.6.5",+ "core-js-compat": "^3.43.0"+ },+ "peerDependencies": {+ "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0"+ }+ },+ "node_modules/babel-plugin-polyfill-regenerator": {+ "version": "0.6.5",+ "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-regenerator/-/babel-plugin-polyfill-regenerator-0.6.5.tgz",+ "integrity": "sha512-ISqQ2frbiNU9vIJkzg7dlPpznPZ4jOiUQ1uSmB0fEHeowtN3COYRsXr/xexn64NpU13P06jc/L5TgiJXOgrbEg==",+ "license": "MIT",+ "dependencies": {+ "@babel/helper-define-polyfill-provider": "^0.6.5"+ },+ "peerDependencies": {+ "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0"+ }+ },+ "node_modules/bail": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/bail/-/bail-2.0.2.tgz",+ "integrity": "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/balanced-match": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/base64-js": {+ "version": "1.5.1",+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT"+ },+ "node_modules/baseline-browser-mapping": {+ "version": "2.9.0",+ "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.0.tgz",+ "integrity": "sha512-Mh++g+2LPfzZToywfE1BUzvZbfOY52Nil0rn9H1CPC5DJ7fX+Vir7nToBeoiSbB1zTNeGYbELEvJESujgGrzXw==",+ "license": "Apache-2.0",+ "bin": {+ "baseline-browser-mapping": "dist/cli.js"+ }+ },+ "node_modules/brace-expansion": {+ "version": "1.1.12",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",+ "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^1.0.0",+ "concat-map": "0.0.1"+ }+ },+ "node_modules/browserslist": {+ "version": "4.28.1",+ "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.1.tgz",+ "integrity": "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==",+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/browserslist"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/browserslist"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "baseline-browser-mapping": "^2.9.0",+ "caniuse-lite": "^1.0.30001759",+ "electron-to-chromium": "^1.5.263",+ "node-releases": "^2.0.27",+ "update-browserslist-db": "^1.2.0"+ },+ "bin": {+ "browserslist": "cli.js"+ },+ "engines": {+ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"+ }+ },+ "node_modules/callsites": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",+ "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/camelcase": {+ "version": "6.3.0",+ "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz",+ "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==",+ "license": "MIT",+ "peer": true,+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/camelize": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/camelize/-/camelize-1.0.1.tgz",+ "integrity": "sha512-dU+Tx2fsypxTgtLoE36npi3UqcjSSMNYfkqgmoEhtZrraP5VWq0K7FkWVTYa8eMPtnU/G2txVsfdCJTn9uzpuQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/caniuse-lite": {+ "version": "1.0.30001759",+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001759.tgz",+ "integrity": "sha512-Pzfx9fOKoKvevQf8oCXoyNRQ5QyxJj+3O0Rqx2V5oxT61KGx8+n6hV/IUyJeifUci2clnmmKVpvtiqRzgiWjSw==",+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/browserslist"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/caniuse-lite"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "CC-BY-4.0"+ },+ "node_modules/ccount": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz",+ "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/chalk": {+ "version": "4.1.2",+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",+ "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",+ "license": "MIT",+ "dependencies": {+ "ansi-styles": "^4.1.0",+ "supports-color": "^7.1.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/chalk/chalk?sponsor=1"+ }+ },+ "node_modules/chalk/node_modules/supports-color": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",+ "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",+ "license": "MIT",+ "dependencies": {+ "has-flag": "^4.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/character-entities": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz",+ "integrity": "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/character-entities-html4": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz",+ "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/character-entities-legacy": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz",+ "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/character-reference-invalid": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/character-reference-invalid/-/character-reference-invalid-2.0.1.tgz",+ "integrity": "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/chevrotain": {+ "version": "11.0.3",+ "resolved": "https://registry.npmjs.org/chevrotain/-/chevrotain-11.0.3.tgz",+ "integrity": "sha512-ci2iJH6LeIkvP9eJW6gpueU8cnZhv85ELY8w8WiFtNjMHA5ad6pQLaJo9mEly/9qUyCpvqX8/POVUTf18/HFdw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@chevrotain/cst-dts-gen": "11.0.3",+ "@chevrotain/gast": "11.0.3",+ "@chevrotain/regexp-to-ast": "11.0.3",+ "@chevrotain/types": "11.0.3",+ "@chevrotain/utils": "11.0.3",+ "lodash-es": "4.17.21"+ }+ },+ "node_modules/chevrotain-allstar": {+ "version": "0.3.1",+ "resolved": "https://registry.npmjs.org/chevrotain-allstar/-/chevrotain-allstar-0.3.1.tgz",+ "integrity": "sha512-b7g+y9A0v4mxCW1qUhf3BSVPg+/NvGErk/dOkrDaHA0nQIQGAtrOjlX//9OQtRlSCy+x9rfB5N8yC71lH1nvMw==",+ "license": "MIT",+ "dependencies": {+ "lodash-es": "^4.17.21"+ },+ "peerDependencies": {+ "chevrotain": "^11.0.0"+ }+ },+ "node_modules/chroma-js": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/chroma-js/-/chroma-js-3.2.0.tgz",+ "integrity": "sha512-os/OippSlX1RlWWr+QDPcGUZs0uoqr32urfxESG9U93lhUfbnlyckte84Q8P1UQY/qth983AS1JONKmLS4T0nw==",+ "license": "(BSD-3-Clause AND Apache-2.0)"+ },+ "node_modules/class-variance-authority": {+ "version": "0.7.1",+ "resolved": "https://registry.npmjs.org/class-variance-authority/-/class-variance-authority-0.7.1.tgz",+ "integrity": "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==",+ "license": "Apache-2.0",+ "dependencies": {+ "clsx": "^2.1.1"+ },+ "funding": {+ "url": "https://polar.sh/cva"+ }+ },+ "node_modules/classcat": {+ "version": "5.0.5",+ "resolved": "https://registry.npmjs.org/classcat/-/classcat-5.0.5.tgz",+ "integrity": "sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w==",+ "license": "MIT"+ },+ "node_modules/classnames": {+ "version": "2.5.1",+ "resolved": "https://registry.npmjs.org/classnames/-/classnames-2.5.1.tgz",+ "integrity": "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==",+ "license": "MIT"+ },+ "node_modules/cliui": {+ "version": "8.0.1",+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz",+ "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "string-width": "^4.2.0",+ "strip-ansi": "^6.0.1",+ "wrap-ansi": "^7.0.0"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/clsx": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",+ "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/collapse-white-space": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/collapse-white-space/-/collapse-white-space-2.1.0.tgz",+ "integrity": "sha512-loKTxY1zCOuG4j9f6EPnuyyYkf58RnhhWTvRoZEokgB+WbdXehfjFviyOVYkqzEWz1Q5kRiZdBYS5SwxbQYwzw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/color-convert": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",+ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",+ "license": "MIT",+ "dependencies": {+ "color-name": "~1.1.4"+ },+ "engines": {+ "node": ">=7.0.0"+ }+ },+ "node_modules/color-name": {+ "version": "1.1.4",+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",+ "license": "MIT"+ },+ "node_modules/colord": {+ "version": "2.9.3",+ "resolved": "https://registry.npmjs.org/colord/-/colord-2.9.3.tgz",+ "integrity": "sha512-jeC1axXpnb0/2nn/Y1LPuLdgXBLH7aDcHu4KEKfqw3CUhX7ZpfBSlPKyqXE6btIgEzfWtrX3/tyBCaCvXvMkOw==",+ "license": "MIT"+ },+ "node_modules/comma-separated-tokens": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz",+ "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/commander": {+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz",+ "integrity": "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==",+ "license": "MIT",+ "engines": {+ "node": ">= 12"+ }+ },+ "node_modules/compute-scroll-into-view": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/compute-scroll-into-view/-/compute-scroll-into-view-3.1.1.tgz",+ "integrity": "sha512-VRhuHOLoKYOy4UbilLbUzbYg93XLjv2PncJC50EuTWPA3gaja1UjBsUP/D/9/juV3vQFr6XBEzn9KCAHdUvOHw==",+ "license": "MIT"+ },+ "node_modules/concat-map": {+ "version": "0.0.1",+ "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",+ "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/concurrently": {+ "version": "9.2.1",+ "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.2.1.tgz",+ "integrity": "sha512-fsfrO0MxV64Znoy8/l1vVIjjHa29SZyyqPgQBwhiDcaW8wJc2W3XWVOGx4M3oJBnv/zdUZIIp1gDeS98GzP8Ng==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "chalk": "4.1.2",+ "rxjs": "7.8.2",+ "shell-quote": "1.8.3",+ "supports-color": "8.1.1",+ "tree-kill": "1.2.2",+ "yargs": "17.7.2"+ },+ "bin": {+ "conc": "dist/bin/concurrently.js",+ "concurrently": "dist/bin/concurrently.js"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/open-cli-tools/concurrently?sponsor=1"+ }+ },+ "node_modules/confbox": {+ "version": "0.1.8",+ "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz",+ "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==",+ "license": "MIT"+ },+ "node_modules/console-table-printer": {+ "version": "2.15.0",+ "resolved": "https://registry.npmjs.org/console-table-printer/-/console-table-printer-2.15.0.tgz",+ "integrity": "sha512-SrhBq4hYVjLCkBVOWaTzceJalvn5K1Zq5aQA6wXC/cYjI3frKWNPEMK3sZsJfNNQApvCQmgBcc13ZKmFj8qExw==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "simple-wcswidth": "^1.1.2"+ }+ },+ "node_modules/convert-source-map": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",+ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",+ "license": "MIT"+ },+ "node_modules/copy-to-clipboard": {+ "version": "3.3.3",+ "resolved": "https://registry.npmjs.org/copy-to-clipboard/-/copy-to-clipboard-3.3.3.tgz",+ "integrity": "sha512-2KV8NhB5JqC3ky0r9PMCAZKbUHSwtEo4CwCs0KXgruG43gX5PMqDEBbVU4OUzw2MuAWUfsuFmWvEKG5QRfSnJA==",+ "license": "MIT",+ "dependencies": {+ "toggle-selection": "^1.0.6"+ }+ },+ "node_modules/core-js-compat": {+ "version": "3.47.0",+ "resolved": "https://registry.npmjs.org/core-js-compat/-/core-js-compat-3.47.0.tgz",+ "integrity": "sha512-IGfuznZ/n7Kp9+nypamBhvwdwLsW6KC8IOaURw2doAK5e98AG3acVLdh0woOnEqCfUtS+Vu882JE4k/DAm3ItQ==",+ "license": "MIT",+ "dependencies": {+ "browserslist": "^4.28.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/core-js"+ }+ },+ "node_modules/cose-base": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/cose-base/-/cose-base-1.0.3.tgz",+ "integrity": "sha512-s9whTXInMSgAp/NVXVNuVxVKzGH2qck3aQlVHxDCdAEPgtMKwc4Wq6/QKhgdEdgbLSi9rBTAcPoRa6JpiG4ksg==",+ "license": "MIT",+ "dependencies": {+ "layout-base": "^1.0.0"+ }+ },+ "node_modules/cosmiconfig": {+ "version": "7.1.0",+ "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.1.0.tgz",+ "integrity": "sha512-AdmX6xUzdNASswsFtmwSt7Vj8po9IuqXm0UXz7QKPuEUmPB4XyjGfaAr2PSuELMwkRMVH1EpIkX5bTZGRB3eCA==",+ "license": "MIT",+ "dependencies": {+ "@types/parse-json": "^4.0.0",+ "import-fresh": "^3.2.1",+ "parse-json": "^5.0.0",+ "path-type": "^4.0.0",+ "yaml": "^1.10.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/cosmiconfig/node_modules/yaml": {+ "version": "1.10.2",+ "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.2.tgz",+ "integrity": "sha512-r3vXyErRCYJ7wg28yvBY5VSoAF8ZvlcW9/BwUzEtUsjvX/DKs24dIkuwjtuprwJJHsbyUbLApepYTR1BN4uHrg==",+ "license": "ISC",+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/cross-spawn": {+ "version": "7.0.6",+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "path-key": "^3.1.0",+ "shebang-command": "^2.0.0",+ "which": "^2.0.1"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/css-color-keywords": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/css-color-keywords/-/css-color-keywords-1.0.0.tgz",+ "integrity": "sha512-FyyrDHZKEjXDpNJYvVsV960FiqQyXc/LlYmsxl2BcdMb2WPx0OGRVgTg55rPSyLSNMqP52R9r8geSp7apN3Ofg==",+ "license": "ISC",+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/css-in-js-utils": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/css-in-js-utils/-/css-in-js-utils-3.1.0.tgz",+ "integrity": "sha512-fJAcud6B3rRu+KHYk+Bwf+WFL2MDCJJ1XG9x137tJQ0xYxor7XziQtuGFbWNdqrvF4Tk26O3H73nfVqXt/fW1A==",+ "license": "MIT",+ "dependencies": {+ "hyphenate-style-name": "^1.0.3"+ }+ },+ "node_modules/css-to-react-native": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/css-to-react-native/-/css-to-react-native-3.2.0.tgz",+ "integrity": "sha512-e8RKaLXMOFii+02mOlqwjbD00KSEKqblnpO9e++1aXS1fPQOpS1YoqdVHBqPjHNoxeF2mimzVqawm2KCbEdtHQ==",+ "license": "MIT",+ "dependencies": {+ "camelize": "^1.0.0",+ "css-color-keywords": "^1.0.0",+ "postcss-value-parser": "^4.0.2"+ }+ },+ "node_modules/css-tree": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-1.1.3.tgz",+ "integrity": "sha512-tRpdppF7TRazZrjJ6v3stzv93qxRcSsFmW6cX0Zm2NVKpxE1WV1HblnghVv9TreireHkqI/VDEsfolRF1p6y7Q==",+ "license": "MIT",+ "dependencies": {+ "mdn-data": "2.0.14",+ "source-map": "^0.6.1"+ },+ "engines": {+ "node": ">=8.0.0"+ }+ },+ "node_modules/csstype": {+ "version": "3.2.3",+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",+ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",+ "license": "MIT"+ },+ "node_modules/cytoscape": {+ "version": "3.33.1",+ "resolved": "https://registry.npmjs.org/cytoscape/-/cytoscape-3.33.1.tgz",+ "integrity": "sha512-iJc4TwyANnOGR1OmWhsS9ayRS3s+XQ185FmuHObThD+5AeJCakAAbWv8KimMTt08xCCLNgneQwFp+JRJOr9qGQ==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10"+ }+ },+ "node_modules/cytoscape-cose-bilkent": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/cytoscape-cose-bilkent/-/cytoscape-cose-bilkent-4.1.0.tgz",+ "integrity": "sha512-wgQlVIUJF13Quxiv5e1gstZ08rnZj2XaLHGoFMYXz7SkNfCDOOteKBE6SYRfA9WxxI/iBc3ajfDoc6hb/MRAHQ==",+ "license": "MIT",+ "dependencies": {+ "cose-base": "^1.0.0"+ },+ "peerDependencies": {+ "cytoscape": "^3.2.0"+ }+ },+ "node_modules/cytoscape-fcose": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/cytoscape-fcose/-/cytoscape-fcose-2.2.0.tgz",+ "integrity": "sha512-ki1/VuRIHFCzxWNrsshHYPs6L7TvLu3DL+TyIGEsRcvVERmxokbf5Gdk7mFxZnTdiGtnA4cfSmjZJMviqSuZrQ==",+ "license": "MIT",+ "dependencies": {+ "cose-base": "^2.2.0"+ },+ "peerDependencies": {+ "cytoscape": "^3.2.0"+ }+ },+ "node_modules/cytoscape-fcose/node_modules/cose-base": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/cose-base/-/cose-base-2.2.0.tgz",+ "integrity": "sha512-AzlgcsCbUMymkADOJtQm3wO9S3ltPfYOFD5033keQn9NJzIbtnZj+UdBJe7DYml/8TdbtHJW3j58SOnKhWY/5g==",+ "license": "MIT",+ "dependencies": {+ "layout-base": "^2.0.0"+ }+ },+ "node_modules/cytoscape-fcose/node_modules/layout-base": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/layout-base/-/layout-base-2.0.1.tgz",+ "integrity": "sha512-dp3s92+uNI1hWIpPGH3jK2kxE2lMjdXdr+DH8ynZHpd6PUlH6x6cbuXnoMmiNumznqaNO31xu9e79F0uuZ0JFg==",+ "license": "MIT"+ },+ "node_modules/d3": {+ "version": "7.9.0",+ "resolved": "https://registry.npmjs.org/d3/-/d3-7.9.0.tgz",+ "integrity": "sha512-e1U46jVP+w7Iut8Jt8ri1YsPOvFpg46k+K8TpCb0P+zjCkjkPnV7WzfDJzMHy1LnA+wj5pLT1wjO901gLXeEhA==",+ "license": "ISC",+ "dependencies": {+ "d3-array": "3",+ "d3-axis": "3",+ "d3-brush": "3",+ "d3-chord": "3",+ "d3-color": "3",+ "d3-contour": "4",+ "d3-delaunay": "6",+ "d3-dispatch": "3",+ "d3-drag": "3",+ "d3-dsv": "3",+ "d3-ease": "3",+ "d3-fetch": "3",+ "d3-force": "3",+ "d3-format": "3",+ "d3-geo": "3",+ "d3-hierarchy": "3",+ "d3-interpolate": "3",+ "d3-path": "3",+ "d3-polygon": "3",+ "d3-quadtree": "3",+ "d3-random": "3",+ "d3-scale": "4",+ "d3-scale-chromatic": "3",+ "d3-selection": "3",+ "d3-shape": "3",+ "d3-time": "3",+ "d3-time-format": "4",+ "d3-timer": "3",+ "d3-transition": "3",+ "d3-zoom": "3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-array": {+ "version": "3.2.4",+ "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",+ "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==",+ "license": "ISC",+ "dependencies": {+ "internmap": "1 - 2"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-axis": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-axis/-/d3-axis-3.0.0.tgz",+ "integrity": "sha512-IH5tgjV4jE/GhHkRV0HiVYPDtvfjHQlQfJHs0usq7M30XcSBvOotpmH1IgkcXsO/5gEQZD43B//fc7SRT5S+xw==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-brush": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-brush/-/d3-brush-3.0.0.tgz",+ "integrity": "sha512-ALnjWlVYkXsVIGlOsuWH1+3udkYFI48Ljihfnh8FZPF2QS9o+PzGLBslO0PjzVoHLZ2KCVgAM8NVkXPJB2aNnQ==",+ "license": "ISC",+ "dependencies": {+ "d3-dispatch": "1 - 3",+ "d3-drag": "2 - 3",+ "d3-interpolate": "1 - 3",+ "d3-selection": "3",+ "d3-transition": "3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-chord": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-chord/-/d3-chord-3.0.1.tgz",+ "integrity": "sha512-VE5S6TNa+j8msksl7HwjxMHDM2yNK3XCkusIlpX5kwauBfXuyLAtNg9jCp/iHH61tgI4sb6R/EIMWCqEIdjT/g==",+ "license": "ISC",+ "dependencies": {+ "d3-path": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-color": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",+ "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-contour": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/d3-contour/-/d3-contour-4.0.2.tgz",+ "integrity": "sha512-4EzFTRIikzs47RGmdxbeUvLWtGedDUNkTcmzoeyg4sP/dvCexO47AaQL7VKy/gul85TOxw+IBgA8US2xwbToNA==",+ "license": "ISC",+ "dependencies": {+ "d3-array": "^3.2.0"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-delaunay": {+ "version": "6.0.4",+ "resolved": "https://registry.npmjs.org/d3-delaunay/-/d3-delaunay-6.0.4.tgz",+ "integrity": "sha512-mdjtIZ1XLAM8bm/hx3WwjfHt6Sggek7qH043O8KEjDXN40xi3vx/6pYSVTwLjEgiXQTbvaouWKynLBiUZ6SK6A==",+ "license": "ISC",+ "dependencies": {+ "delaunator": "5"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-dispatch": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz",+ "integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-drag": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz",+ "integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==",+ "license": "ISC",+ "dependencies": {+ "d3-dispatch": "1 - 3",+ "d3-selection": "3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-dsv": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-dsv/-/d3-dsv-3.0.1.tgz",+ "integrity": "sha512-UG6OvdI5afDIFP9w4G0mNq50dSOsXHJaRE8arAS5o9ApWnIElp8GZw1Dun8vP8OyHOZ/QJUKUJwxiiCCnUwm+Q==",+ "license": "ISC",+ "dependencies": {+ "commander": "7",+ "iconv-lite": "0.6",+ "rw": "1"+ },+ "bin": {+ "csv2json": "bin/dsv2json.js",+ "csv2tsv": "bin/dsv2dsv.js",+ "dsv2dsv": "bin/dsv2dsv.js",+ "dsv2json": "bin/dsv2json.js",+ "json2csv": "bin/json2dsv.js",+ "json2dsv": "bin/json2dsv.js",+ "json2tsv": "bin/json2dsv.js",+ "tsv2csv": "bin/dsv2dsv.js",+ "tsv2json": "bin/dsv2json.js"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-dsv/node_modules/commander": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz",+ "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==",+ "license": "MIT",+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/d3-ease": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",+ "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-fetch": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-fetch/-/d3-fetch-3.0.1.tgz",+ "integrity": "sha512-kpkQIM20n3oLVBKGg6oHrUchHM3xODkTzjMoj7aWQFq5QEM+R6E4WkzT5+tojDY7yjez8KgCBRoj4aEr99Fdqw==",+ "license": "ISC",+ "dependencies": {+ "d3-dsv": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-force": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-force/-/d3-force-3.0.0.tgz",+ "integrity": "sha512-zxV/SsA+U4yte8051P4ECydjD/S+qeYtnaIyAs9tgHCqfguma/aAQDjo85A9Z6EKhBirHRJHXIgJUlffT4wdLg==",+ "license": "ISC",+ "dependencies": {+ "d3-dispatch": "1 - 3",+ "d3-quadtree": "1 - 3",+ "d3-timer": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-format": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.0.tgz",+ "integrity": "sha512-YyUI6AEuY/Wpt8KWLgZHsIU86atmikuoOmCfommt0LYHiQSPjvX2AcFc38PX0CBpr2RCyZhjex+NS/LPOv6YqA==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-geo": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.1.tgz",+ "integrity": "sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==",+ "license": "ISC",+ "dependencies": {+ "d3-array": "2.5.0 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-hierarchy": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/d3-hierarchy/-/d3-hierarchy-3.1.2.tgz",+ "integrity": "sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-interpolate": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",+ "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",+ "license": "ISC",+ "dependencies": {+ "d3-color": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-path": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz",+ "integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-polygon": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-polygon/-/d3-polygon-3.0.1.tgz",+ "integrity": "sha512-3vbA7vXYwfe1SYhED++fPUQlWSYTTGmFmQiany/gdbiWgU/iEyQzyymwL9SkJjFFuCS4902BSzewVGsHHmHtXg==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-quadtree": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-quadtree/-/d3-quadtree-3.0.1.tgz",+ "integrity": "sha512-04xDrxQTDTCFwP5H6hRhsRcb9xxv2RzkcsygFzmkSIOJy3PeRJP7sNk3VRIbKXcog561P9oU0/rVH6vDROAgUw==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-random": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-random/-/d3-random-3.0.1.tgz",+ "integrity": "sha512-FXMe9GfxTxqd5D6jFsQ+DJ8BJS4E/fT5mqqdjovykEB2oFbTMDVdg1MGFxfQW+FBOGoB++k8swBrgwSHT1cUXQ==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-sankey": {+ "version": "0.12.3",+ "resolved": "https://registry.npmjs.org/d3-sankey/-/d3-sankey-0.12.3.tgz",+ "integrity": "sha512-nQhsBRmM19Ax5xEIPLMY9ZmJ/cDvd1BG3UVvt5h3WRxKg5zGRbvnteTyWAbzeSvlh3tW7ZEmq4VwR5mB3tutmQ==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "d3-array": "1 - 2",+ "d3-shape": "^1.2.0"+ }+ },+ "node_modules/d3-sankey/node_modules/d3-array": {+ "version": "2.12.1",+ "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-2.12.1.tgz",+ "integrity": "sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "internmap": "^1.0.0"+ }+ },+ "node_modules/d3-sankey/node_modules/d3-path": {+ "version": "1.0.9",+ "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-1.0.9.tgz",+ "integrity": "sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg==",+ "license": "BSD-3-Clause"+ },+ "node_modules/d3-sankey/node_modules/d3-shape": {+ "version": "1.3.7",+ "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-1.3.7.tgz",+ "integrity": "sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "d3-path": "1"+ }+ },+ "node_modules/d3-sankey/node_modules/internmap": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/internmap/-/internmap-1.0.1.tgz",+ "integrity": "sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw==",+ "license": "ISC"+ },+ "node_modules/d3-scale": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",+ "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==",+ "license": "ISC",+ "dependencies": {+ "d3-array": "2.10.0 - 3",+ "d3-format": "1 - 3",+ "d3-interpolate": "1.2.0 - 3",+ "d3-time": "2.1.1 - 3",+ "d3-time-format": "2 - 4"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-scale-chromatic": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz",+ "integrity": "sha512-A3s5PWiZ9YCXFye1o246KoscMWqf8BsD9eRiJ3He7C9OBaxKhAd5TFCdEx/7VbKtxxTsu//1mMJFrEt572cEyQ==",+ "license": "ISC",+ "dependencies": {+ "d3-color": "1 - 3",+ "d3-interpolate": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-selection": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz",+ "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-shape": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",+ "integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==",+ "license": "ISC",+ "dependencies": {+ "d3-path": "^3.1.0"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-time": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz",+ "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==",+ "license": "ISC",+ "dependencies": {+ "d3-array": "2 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-time-format": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz",+ "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==",+ "license": "ISC",+ "dependencies": {+ "d3-time": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-timer": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",+ "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-transition": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.1.tgz",+ "integrity": "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==",+ "license": "ISC",+ "dependencies": {+ "d3-color": "1 - 3",+ "d3-dispatch": "1 - 3",+ "d3-ease": "1 - 3",+ "d3-interpolate": "1 - 3",+ "d3-timer": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ },+ "peerDependencies": {+ "d3-selection": "2 - 3"+ }+ },+ "node_modules/d3-zoom": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz",+ "integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==",+ "license": "ISC",+ "dependencies": {+ "d3-dispatch": "1 - 3",+ "d3-drag": "2 - 3",+ "d3-interpolate": "1 - 3",+ "d3-selection": "2 - 3",+ "d3-transition": "2 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/dagre-d3-es": {+ "version": "7.0.13",+ "resolved": "https://registry.npmjs.org/dagre-d3-es/-/dagre-d3-es-7.0.13.tgz",+ "integrity": "sha512-efEhnxpSuwpYOKRm/L5KbqoZmNNukHa/Flty4Wp62JRvgH2ojwVgPgdYyr4twpieZnyRDdIH7PY2mopX26+j2Q==",+ "license": "MIT",+ "dependencies": {+ "d3": "^7.9.0",+ "lodash-es": "^4.17.21"+ }+ },+ "node_modules/date-fns": {+ "version": "2.30.0",+ "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-2.30.0.tgz",+ "integrity": "sha512-fnULvOpxnC5/Vg3NCiWelDsLiUc9bRwAPs/+LfTLNvetFCtCTN+yQz15C/fs4AwX1R9K5GLtLfn8QW+dWisaAw==",+ "license": "MIT",+ "optional": true,+ "peer": true,+ "dependencies": {+ "@babel/runtime": "^7.21.0"+ },+ "engines": {+ "node": ">=0.11"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/date-fns"+ }+ },+ "node_modules/dayjs": {+ "version": "1.11.19",+ "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.19.tgz",+ "integrity": "sha512-t5EcLVS6QPBNqM2z8fakk/NKel+Xzshgt8FFKAn+qwlD1pzZWxh0nVCrvFK7ZDb6XucZeF9z8C7CBWTRIVApAw==",+ "license": "MIT"+ },+ "node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/decamelize": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz",+ "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==",+ "license": "MIT",+ "peer": true,+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/decode-named-character-reference": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.2.0.tgz",+ "integrity": "sha512-c6fcElNV6ShtZXmsgNgFFV5tVX2PaV4g+MOAkb8eXHvn6sryJBrZa9r0zV6+dtTyoCKxtDy5tyQ5ZwQuidtd+Q==",+ "license": "MIT",+ "dependencies": {+ "character-entities": "^2.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/decode-uri-component": {+ "version": "0.4.1",+ "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.4.1.tgz",+ "integrity": "sha512-+8VxcR21HhTy8nOt6jf20w0c9CADrw1O8d+VZ/YzzCt4bJ3uBjw+D1q2osAB8RnpwwaeYBxy0HyKQxD5JBMuuQ==",+ "license": "MIT",+ "engines": {+ "node": ">=14.16"+ }+ },+ "node_modules/deep-is": {+ "version": "0.1.4",+ "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",+ "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/delaunator": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.0.1.tgz",+ "integrity": "sha512-8nvh+XBe96aCESrGOqMp/84b13H9cdKbG5P2ejQCh4d4sK9RL4371qou9drQjMhvnPmhWl5hnmqbEE0fXr9Xnw==",+ "license": "ISC",+ "dependencies": {+ "robust-predicates": "^3.0.2"+ }+ },+ "node_modules/dequal": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",+ "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/detect-node-es": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/detect-node-es/-/detect-node-es-1.1.0.tgz",+ "integrity": "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==",+ "license": "MIT"+ },+ "node_modules/devlop": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz",+ "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==",+ "license": "MIT",+ "dependencies": {+ "dequal": "^2.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/dexie": {+ "version": "4.2.1",+ "resolved": "https://registry.npmjs.org/dexie/-/dexie-4.2.1.tgz",+ "integrity": "sha512-Ckej0NS6jxQ4Po3OrSQBFddayRhTCic2DoCAG5zacOfOVB9P2Q5Xc5uL/nVa7ZVs+HdMnvUPzLFCB/JwpB6Csg==",+ "license": "Apache-2.0"+ },+ "node_modules/dompurify": {+ "version": "3.3.1",+ "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.3.1.tgz",+ "integrity": "sha512-qkdCKzLNtrgPFP1Vo+98FRzJnBRGe4ffyCea9IwHB1fyxPOeNTHpLKYGd4Uk9xvNoH0ZoOjwZxNptyMwqrId1Q==",+ "license": "(MPL-2.0 OR Apache-2.0)",+ "optionalDependencies": {+ "@types/trusted-types": "^2.0.7"+ }+ },+ "node_modules/electron-to-chromium": {+ "version": "1.5.263",+ "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.263.tgz",+ "integrity": "sha512-DrqJ11Knd+lo+dv+lltvfMDLU27g14LMdH2b0O3Pio4uk0x+z7OR+JrmyacTPN2M8w3BrZ7/RTwG3R9B7irPlg==",+ "license": "ISC"+ },+ "node_modules/emoji-mart": {+ "version": "5.6.0",+ "resolved": "https://registry.npmjs.org/emoji-mart/-/emoji-mart-5.6.0.tgz",+ "integrity": "sha512-eJp3QRe79pjwa+duv+n7+5YsNhRcMl812EcFVwrnRvYKoNPoQb5qxU8DG6Bgwji0akHdp6D4Ln6tYLG58MFSow==",+ "license": "MIT"+ },+ "node_modules/emoji-regex": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",+ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/entities": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz",+ "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==",+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=0.12"+ },+ "funding": {+ "url": "https://github.com/fb55/entities?sponsor=1"+ }+ },+ "node_modules/error-ex": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz",+ "integrity": "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==",+ "license": "MIT",+ "dependencies": {+ "is-arrayish": "^0.2.1"+ }+ },+ "node_modules/error-stack-parser": {+ "version": "2.1.4",+ "resolved": "https://registry.npmjs.org/error-stack-parser/-/error-stack-parser-2.1.4.tgz",+ "integrity": "sha512-Sk5V6wVazPhq5MhpO+AUxJn5x7XSXGl1R93Vn7i+zS15KDVxQijejNCrz8340/2bgLBjR9GtEG8ZVKONDjcqGQ==",+ "license": "MIT",+ "dependencies": {+ "stackframe": "^1.3.4"+ }+ },+ "node_modules/esast-util-from-estree": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/esast-util-from-estree/-/esast-util-from-estree-2.0.0.tgz",+ "integrity": "sha512-4CyanoAudUSBAn5K13H4JhsMH6L9ZP7XbLVe/dKybkxMO7eDyLsT8UHl9TRNrU2Gr9nz+FovfSIjuXWJ81uVwQ==",+ "license": "MIT",+ "dependencies": {+ "@types/estree-jsx": "^1.0.0",+ "devlop": "^1.0.0",+ "estree-util-visit": "^2.0.0",+ "unist-util-position-from-estree": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/esast-util-from-js": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/esast-util-from-js/-/esast-util-from-js-2.0.1.tgz",+ "integrity": "sha512-8Ja+rNJ0Lt56Pcf3TAmpBZjmx8ZcK5Ts4cAzIOjsjevg9oSXJnl6SUQ2EevU8tv3h6ZLWmoKL5H4fgWvdvfETw==",+ "license": "MIT",+ "dependencies": {+ "@types/estree-jsx": "^1.0.0",+ "acorn": "^8.0.0",+ "esast-util-from-estree": "^2.0.0",+ "vfile-message": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/esbuild": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",+ "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.25.12",+ "@esbuild/android-arm": "0.25.12",+ "@esbuild/android-arm64": "0.25.12",+ "@esbuild/android-x64": "0.25.12",+ "@esbuild/darwin-arm64": "0.25.12",+ "@esbuild/darwin-x64": "0.25.12",+ "@esbuild/freebsd-arm64": "0.25.12",+ "@esbuild/freebsd-x64": "0.25.12",+ "@esbuild/linux-arm": "0.25.12",+ "@esbuild/linux-arm64": "0.25.12",+ "@esbuild/linux-ia32": "0.25.12",+ "@esbuild/linux-loong64": "0.25.12",+ "@esbuild/linux-mips64el": "0.25.12",+ "@esbuild/linux-ppc64": "0.25.12",+ "@esbuild/linux-riscv64": "0.25.12",+ "@esbuild/linux-s390x": "0.25.12",+ "@esbuild/linux-x64": "0.25.12",+ "@esbuild/netbsd-arm64": "0.25.12",+ "@esbuild/netbsd-x64": "0.25.12",+ "@esbuild/openbsd-arm64": "0.25.12",+ "@esbuild/openbsd-x64": "0.25.12",+ "@esbuild/openharmony-arm64": "0.25.12",+ "@esbuild/sunos-x64": "0.25.12",+ "@esbuild/win32-arm64": "0.25.12",+ "@esbuild/win32-ia32": "0.25.12",+ "@esbuild/win32-x64": "0.25.12"+ }+ },+ "node_modules/escalade": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/escape-string-regexp": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",+ "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/eslint": {+ "version": "9.39.1",+ "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.1.tgz",+ "integrity": "sha512-BhHmn2yNOFA9H9JmmIVKJmd288g9hrVRDkdoIgRCRuSySRUHH7r/DI6aAXW9T1WwUuY3DFgrcaqB+deURBLR5g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@eslint-community/eslint-utils": "^4.8.0",+ "@eslint-community/regexpp": "^4.12.1",+ "@eslint/config-array": "^0.21.1",+ "@eslint/config-helpers": "^0.4.2",+ "@eslint/core": "^0.17.0",+ "@eslint/eslintrc": "^3.3.1",+ "@eslint/js": "9.39.1",+ "@eslint/plugin-kit": "^0.4.1",+ "@humanfs/node": "^0.16.6",+ "@humanwhocodes/module-importer": "^1.0.1",+ "@humanwhocodes/retry": "^0.4.2",+ "@types/estree": "^1.0.6",+ "ajv": "^6.12.4",+ "chalk": "^4.0.0",+ "cross-spawn": "^7.0.6",+ "debug": "^4.3.2",+ "escape-string-regexp": "^4.0.0",+ "eslint-scope": "^8.4.0",+ "eslint-visitor-keys": "^4.2.1",+ "espree": "^10.4.0",+ "esquery": "^1.5.0",+ "esutils": "^2.0.2",+ "fast-deep-equal": "^3.1.3",+ "file-entry-cache": "^8.0.0",+ "find-up": "^5.0.0",+ "glob-parent": "^6.0.2",+ "ignore": "^5.2.0",+ "imurmurhash": "^0.1.4",+ "is-glob": "^4.0.0",+ "json-stable-stringify-without-jsonify": "^1.0.1",+ "lodash.merge": "^4.6.2",+ "minimatch": "^3.1.2",+ "natural-compare": "^1.4.0",+ "optionator": "^0.9.3"+ },+ "bin": {+ "eslint": "bin/eslint.js"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://eslint.org/donate"+ },+ "peerDependencies": {+ "jiti": "*"+ },+ "peerDependenciesMeta": {+ "jiti": {+ "optional": true+ }+ }+ },+ "node_modules/eslint-plugin-react-hooks": {+ "version": "7.0.1",+ "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-7.0.1.tgz",+ "integrity": "sha512-O0d0m04evaNzEPoSW+59Mezf8Qt0InfgGIBJnpC0h3NH/WjUAR7BIKUfysC6todmtiZ/A0oUVS8Gce0WhBrHsA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/core": "^7.24.4",+ "@babel/parser": "^7.24.4",+ "hermes-parser": "^0.25.1",+ "zod": "^3.25.0 || ^4.0.0",+ "zod-validation-error": "^3.5.0 || ^4.0.0"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0"+ }+ },+ "node_modules/eslint-plugin-react-refresh": {+ "version": "0.4.24",+ "resolved": "https://registry.npmjs.org/eslint-plugin-react-refresh/-/eslint-plugin-react-refresh-0.4.24.tgz",+ "integrity": "sha512-nLHIW7TEq3aLrEYWpVaJ1dRgFR+wLDPN8e8FpYAql/bMV2oBEfC37K0gLEGgv9fy66juNShSMV8OkTqzltcG/w==",+ "dev": true,+ "license": "MIT",+ "peerDependencies": {+ "eslint": ">=8.40"+ }+ },+ "node_modules/eslint-scope": {+ "version": "8.4.0",+ "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz",+ "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==",+ "dev": true,+ "license": "BSD-2-Clause",+ "dependencies": {+ "esrecurse": "^4.3.0",+ "estraverse": "^5.2.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/eslint-visitor-keys": {+ "version": "4.2.1",+ "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz",+ "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/espree": {+ "version": "10.4.0",+ "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz",+ "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==",+ "dev": true,+ "license": "BSD-2-Clause",+ "dependencies": {+ "acorn": "^8.15.0",+ "acorn-jsx": "^5.3.2",+ "eslint-visitor-keys": "^4.2.1"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/esquery": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.6.0.tgz",+ "integrity": "sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "estraverse": "^5.1.0"+ },+ "engines": {+ "node": ">=0.10"+ }+ },+ "node_modules/esrecurse": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz",+ "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==",+ "dev": true,+ "license": "BSD-2-Clause",+ "dependencies": {+ "estraverse": "^5.2.0"+ },+ "engines": {+ "node": ">=4.0"+ }+ },+ "node_modules/estraverse": {+ "version": "5.3.0",+ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz",+ "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=4.0"+ }+ },+ "node_modules/estree-util-attach-comments": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/estree-util-attach-comments/-/estree-util-attach-comments-3.0.0.tgz",+ "integrity": "sha512-cKUwm/HUcTDsYh/9FgnuFqpfquUbwIqwKM26BVCGDPVgvaCl/nDCCjUfiLlx6lsEZ3Z4RFxNbOQ60pkaEwFxGw==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/estree-util-build-jsx": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/estree-util-build-jsx/-/estree-util-build-jsx-3.0.1.tgz",+ "integrity": "sha512-8U5eiL6BTrPxp/CHbs2yMgP8ftMhR5ww1eIKoWRMlqvltHF8fZn5LRDvTKuxD3DUn+shRbLGqXemcP51oFCsGQ==",+ "license": "MIT",+ "dependencies": {+ "@types/estree-jsx": "^1.0.0",+ "devlop": "^1.0.0",+ "estree-util-is-identifier-name": "^3.0.0",+ "estree-walker": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/estree-util-is-identifier-name": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/estree-util-is-identifier-name/-/estree-util-is-identifier-name-3.0.0.tgz",+ "integrity": "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/estree-util-scope": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/estree-util-scope/-/estree-util-scope-1.0.0.tgz",+ "integrity": "sha512-2CAASclonf+JFWBNJPndcOpA8EMJwa0Q8LUFJEKqXLW6+qBvbFZuF5gItbQOs/umBUkjviCSDCbBwU2cXbmrhQ==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "devlop": "^1.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/estree-util-to-js": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/estree-util-to-js/-/estree-util-to-js-2.0.0.tgz",+ "integrity": "sha512-WDF+xj5rRWmD5tj6bIqRi6CkLIXbbNQUcxQHzGysQzvHmdYG2G7p/Tf0J0gpxGgkeMZNTIjT/AoSvC9Xehcgdg==",+ "license": "MIT",+ "dependencies": {+ "@types/estree-jsx": "^1.0.0",+ "astring": "^1.8.0",+ "source-map": "^0.7.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/estree-util-to-js/node_modules/source-map": {+ "version": "0.7.6",+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz",+ "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">= 12"+ }+ },+ "node_modules/estree-util-visit": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/estree-util-visit/-/estree-util-visit-2.0.0.tgz",+ "integrity": "sha512-m5KgiH85xAhhW8Wta0vShLcUvOsh3LLPI2YVwcbio1l7E09NTLL1EyMZFM1OyWowoH0skScNbhOPl4kcBgzTww==",+ "license": "MIT",+ "dependencies": {+ "@types/estree-jsx": "^1.0.0",+ "@types/unist": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/estree-walker": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0"+ }+ },+ "node_modules/esutils": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",+ "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/eventemitter3": {+ "version": "4.0.7",+ "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz",+ "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==",+ "license": "MIT",+ "peer": true+ },+ "node_modules/eventsource-parser": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.6.tgz",+ "integrity": "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==",+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/extend": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",+ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",+ "license": "MIT"+ },+ "node_modules/extend-shallow": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",+ "integrity": "sha512-zCnTtlxNoAiDc3gqY2aYAWFx7XWWiasuF2K8Me5WbN8otHKTUKBwjPtNpRs/rbUZm7KxWAaNj7P1a/p52GbVug==",+ "license": "MIT",+ "dependencies": {+ "is-extendable": "^0.1.0"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/extend-shallow/node_modules/is-extendable": {+ "version": "0.1.1",+ "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz",+ "integrity": "sha512-5BMULNob1vgFX6EjQw5izWDxrecWK9AM72rugNr0TFldMOi0fj6Jk+zeKIt0xGj4cEfQIJth4w3OKWOJ4f+AFw==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/fast-deep-equal": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",+ "license": "MIT"+ },+ "node_modules/fast-json-stable-stringify": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",+ "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/fast-levenshtein": {+ "version": "2.0.6",+ "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz",+ "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/fast-shallow-equal": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/fast-shallow-equal/-/fast-shallow-equal-1.0.0.tgz",+ "integrity": "sha512-HPtaa38cPgWvaCFmRNhlc6NG7pv6NUHqjPgVAkWGoB9mQMwYB27/K0CvOM5Czy+qpT3e8XJ6Q4aPAnzpNpzNaw=="+ },+ "node_modules/fast-xml-parser": {+ "version": "4.5.3",+ "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.5.3.tgz",+ "integrity": "sha512-RKihhV+SHsIUGXObeVy9AXiBbFwkVk7Syp8XgwN5U3JV416+Gwp/GO9i0JYKmikykgz/UHRrrV4ROuZEo/T0ig==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/NaturalIntelligence"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "strnum": "^1.1.1"+ },+ "bin": {+ "fxparser": "src/cli/cli.js"+ }+ },+ "node_modules/fastest-stable-stringify": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/fastest-stable-stringify/-/fastest-stable-stringify-2.0.2.tgz",+ "integrity": "sha512-bijHueCGd0LqqNK9b5oCMHc0MluJAx0cwqASgbWMvkO01lCYgIhacVRLcaDz3QnyYIRNJRDwMb41VuT6pHJ91Q==",+ "license": "MIT"+ },+ "node_modules/fdir": {+ "version": "6.5.0",+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12.0.0"+ },+ "peerDependencies": {+ "picomatch": "^3 || ^4"+ },+ "peerDependenciesMeta": {+ "picomatch": {+ "optional": true+ }+ }+ },+ "node_modules/file-entry-cache": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",+ "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "flat-cache": "^4.0.0"+ },+ "engines": {+ "node": ">=16.0.0"+ }+ },+ "node_modules/file-selector": {+ "version": "0.5.0",+ "resolved": "https://registry.npmjs.org/file-selector/-/file-selector-0.5.0.tgz",+ "integrity": "sha512-s8KNnmIDTBoD0p9uJ9uD0XY38SCeBOtj0UMXyQSLg1Ypfrfj8+dAvwsLjYQkQ2GjhVtp2HrnF5cJzMhBjfD8HA==",+ "license": "MIT",+ "dependencies": {+ "tslib": "^2.0.3"+ },+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/filter-obj": {+ "version": "5.1.0",+ "resolved": "https://registry.npmjs.org/filter-obj/-/filter-obj-5.1.0.tgz",+ "integrity": "sha512-qWeTREPoT7I0bifpPUXtxkZJ1XJzxWtfoWWkdVGqa+eCr3SHW/Ocp89o8vLvbUuQnadybJpjOKu4V+RwO6sGng==",+ "license": "MIT",+ "engines": {+ "node": ">=14.16"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/find-root": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/find-root/-/find-root-1.1.0.tgz",+ "integrity": "sha512-NKfW6bec6GfKc0SGx1e07QZY9PE99u0Bft/0rzSD5k3sO/vwkVUpDUKVm5Gpp5Ue3YfShPFTX2070tDs5kB9Ng==",+ "license": "MIT"+ },+ "node_modules/find-up": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz",+ "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "locate-path": "^6.0.0",+ "path-exists": "^4.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/flat-cache": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz",+ "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "flatted": "^3.2.9",+ "keyv": "^4.5.4"+ },+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/flatted": {+ "version": "3.3.3",+ "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.3.tgz",+ "integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/for-in": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz",+ "integrity": "sha512-7EwmXrOjyL+ChxMhmG5lnW9MPt1aIeZEwKhQzoBUdTV0N3zuwWDZYVJatDvZ2OyzPUvdIAZDsCetk3coyMfcnQ==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/fraction.js": {+ "version": "5.3.4",+ "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz",+ "integrity": "sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "*"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/rawify"+ }+ },+ "node_modules/framer-motion": {+ "version": "12.23.26",+ "resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-12.23.26.tgz",+ "integrity": "sha512-cPcIhgR42xBn1Uj+PzOyheMtZ73H927+uWPDVhUMqxy8UHt6Okavb6xIz9J/phFUHUj0OncR6UvMfJTXoc/LKA==",+ "license": "MIT",+ "dependencies": {+ "motion-dom": "^12.23.23",+ "motion-utils": "^12.23.6",+ "tslib": "^2.4.0"+ },+ "peerDependencies": {+ "@emotion/is-prop-valid": "*",+ "react": "^18.0.0 || ^19.0.0",+ "react-dom": "^18.0.0 || ^19.0.0"+ },+ "peerDependenciesMeta": {+ "@emotion/is-prop-valid": {+ "optional": true+ },+ "react": {+ "optional": true+ },+ "react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/fsevents": {+ "version": "2.3.3",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/function-bind": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/gensync": {+ "version": "1.0.0-beta.2",+ "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",+ "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==",+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/get-caller-file": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",+ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",+ "dev": true,+ "license": "ISC",+ "engines": {+ "node": "6.* || 8.* || >= 10.*"+ }+ },+ "node_modules/get-east-asian-width": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.4.0.tgz",+ "integrity": "sha512-QZjmEOC+IT1uk6Rx0sX22V6uHWVwbdbxf1faPqJ1QhLdGgsRGCZoyaQBm/piRdJy/D2um6hM1UP7ZEeQ4EkP+Q==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/get-nonce": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/get-nonce/-/get-nonce-1.0.1.tgz",+ "integrity": "sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/get-value": {+ "version": "2.0.6",+ "resolved": "https://registry.npmjs.org/get-value/-/get-value-2.0.6.tgz",+ "integrity": "sha512-Ln0UQDlxH1BapMu3GPtf7CuYNwRZf2gwCuPqbyG6pB8WfmFpzqcy4xtAaAMUhnNqjMKTiCPZG2oMT3YSx8U2NA==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/giscus": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/giscus/-/giscus-1.6.0.tgz",+ "integrity": "sha512-Zrsi8r4t1LVW950keaWcsURuZUQwUaMKjvJgTCY125vkW6OiEBkatE7ScJDbpqKHdZwb///7FVC21SE3iFK3PQ==",+ "license": "MIT",+ "dependencies": {+ "lit": "^3.2.1"+ }+ },+ "node_modules/glob-parent": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz",+ "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "is-glob": "^4.0.3"+ },+ "engines": {+ "node": ">=10.13.0"+ }+ },+ "node_modules/globals": {+ "version": "16.5.0",+ "resolved": "https://registry.npmjs.org/globals/-/globals-16.5.0.tgz",+ "integrity": "sha512-c/c15i26VrJ4IRt5Z89DnIzCGDn9EcebibhAOjw5ibqEHsE1wLUgkPn9RDmNcUKyU87GeaL633nyJ+pplFR2ZQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/hachure-fill": {+ "version": "0.5.2",+ "resolved": "https://registry.npmjs.org/hachure-fill/-/hachure-fill-0.5.2.tgz",+ "integrity": "sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg==",+ "license": "MIT"+ },+ "node_modules/has-flag": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",+ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/hasown": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",+ "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",+ "license": "MIT",+ "dependencies": {+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/hast-util-from-dom": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/hast-util-from-dom/-/hast-util-from-dom-5.0.1.tgz",+ "integrity": "sha512-N+LqofjR2zuzTjCPzyDUdSshy4Ma6li7p/c3pA78uTwzFgENbgbUrm2ugwsOdcjI1muO+o6Dgzp9p8WHtn/39Q==",+ "license": "ISC",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "hastscript": "^9.0.0",+ "web-namespaces": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hast-util-from-html": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/hast-util-from-html/-/hast-util-from-html-2.0.3.tgz",+ "integrity": "sha512-CUSRHXyKjzHov8yKsQjGOElXy/3EKpyX56ELnkHH34vDVw1N1XSQ1ZcAvTyAPtGqLTuKP/uxM+aLkSPqF/EtMw==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "devlop": "^1.1.0",+ "hast-util-from-parse5": "^8.0.0",+ "parse5": "^7.0.0",+ "vfile": "^6.0.0",+ "vfile-message": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hast-util-from-html-isomorphic": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/hast-util-from-html-isomorphic/-/hast-util-from-html-isomorphic-2.0.0.tgz",+ "integrity": "sha512-zJfpXq44yff2hmE0XmwEOzdWin5xwH+QIhMLOScpX91e/NSGPsAzNCvLQDIEPyO2TXi+lBmU6hjLIhV8MwP2kw==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "hast-util-from-dom": "^5.0.0",+ "hast-util-from-html": "^2.0.0",+ "unist-util-remove-position": "^5.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hast-util-from-parse5": {+ "version": "8.0.3",+ "resolved": "https://registry.npmjs.org/hast-util-from-parse5/-/hast-util-from-parse5-8.0.3.tgz",+ "integrity": "sha512-3kxEVkEKt0zvcZ3hCRYI8rqrgwtlIOFMWkbclACvjlDw8Li9S2hk/d51OI0nr/gIpdMHNepwgOKqZ/sy0Clpyg==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@types/unist": "^3.0.0",+ "devlop": "^1.0.0",+ "hastscript": "^9.0.0",+ "property-information": "^7.0.0",+ "vfile": "^6.0.0",+ "vfile-location": "^5.0.0",+ "web-namespaces": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hast-util-is-element": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/hast-util-is-element/-/hast-util-is-element-3.0.0.tgz",+ "integrity": "sha512-Val9mnv2IWpLbNPqc/pUem+a7Ipj2aHacCwgNfTiK0vJKl0LF+4Ba4+v1oPHFpf3bLYmreq0/l3Gud9S5OH42g==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hast-util-parse-selector": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/hast-util-parse-selector/-/hast-util-parse-selector-4.0.0.tgz",+ "integrity": "sha512-wkQCkSYoOGCRKERFWcxMVMOcYE2K1AaNLU8DXS9arxnLOUEWbOXKXiJUNzEpqZ3JOKpnha3jkFrumEjVliDe7A==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hast-util-raw": {+ "version": "9.1.0",+ "resolved": "https://registry.npmjs.org/hast-util-raw/-/hast-util-raw-9.1.0.tgz",+ "integrity": "sha512-Y8/SBAHkZGoNkpzqqfCldijcuUKh7/su31kEBp67cFY09Wy0mTRgtsLYsiIxMJxlu0f6AA5SUTbDR8K0rxnbUw==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@types/unist": "^3.0.0",+ "@ungap/structured-clone": "^1.0.0",+ "hast-util-from-parse5": "^8.0.0",+ "hast-util-to-parse5": "^8.0.0",+ "html-void-elements": "^3.0.0",+ "mdast-util-to-hast": "^13.0.0",+ "parse5": "^7.0.0",+ "unist-util-position": "^5.0.0",+ "unist-util-visit": "^5.0.0",+ "vfile": "^6.0.0",+ "web-namespaces": "^2.0.0",+ "zwitch": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hast-util-to-estree": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/hast-util-to-estree/-/hast-util-to-estree-3.1.3.tgz",+ "integrity": "sha512-48+B/rJWAp0jamNbAAf9M7Uf//UVqAoMmgXhBdxTDJLGKY+LRnZ99qcG+Qjl5HfMpYNzS5v4EAwVEF34LeAj7w==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "@types/estree-jsx": "^1.0.0",+ "@types/hast": "^3.0.0",+ "comma-separated-tokens": "^2.0.0",+ "devlop": "^1.0.0",+ "estree-util-attach-comments": "^3.0.0",+ "estree-util-is-identifier-name": "^3.0.0",+ "hast-util-whitespace": "^3.0.0",+ "mdast-util-mdx-expression": "^2.0.0",+ "mdast-util-mdx-jsx": "^3.0.0",+ "mdast-util-mdxjs-esm": "^2.0.0",+ "property-information": "^7.0.0",+ "space-separated-tokens": "^2.0.0",+ "style-to-js": "^1.0.0",+ "unist-util-position": "^5.0.0",+ "zwitch": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hast-util-to-html": {+ "version": "9.0.5",+ "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.5.tgz",+ "integrity": "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@types/unist": "^3.0.0",+ "ccount": "^2.0.0",+ "comma-separated-tokens": "^2.0.0",+ "hast-util-whitespace": "^3.0.0",+ "html-void-elements": "^3.0.0",+ "mdast-util-to-hast": "^13.0.0",+ "property-information": "^7.0.0",+ "space-separated-tokens": "^2.0.0",+ "stringify-entities": "^4.0.0",+ "zwitch": "^2.0.4"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hast-util-to-jsx-runtime": {+ "version": "2.3.6",+ "resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.6.tgz",+ "integrity": "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "@types/hast": "^3.0.0",+ "@types/unist": "^3.0.0",+ "comma-separated-tokens": "^2.0.0",+ "devlop": "^1.0.0",+ "estree-util-is-identifier-name": "^3.0.0",+ "hast-util-whitespace": "^3.0.0",+ "mdast-util-mdx-expression": "^2.0.0",+ "mdast-util-mdx-jsx": "^3.0.0",+ "mdast-util-mdxjs-esm": "^2.0.0",+ "property-information": "^7.0.0",+ "space-separated-tokens": "^2.0.0",+ "style-to-js": "^1.0.0",+ "unist-util-position": "^5.0.0",+ "vfile-message": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hast-util-to-parse5": {+ "version": "8.0.1",+ "resolved": "https://registry.npmjs.org/hast-util-to-parse5/-/hast-util-to-parse5-8.0.1.tgz",+ "integrity": "sha512-MlWT6Pjt4CG9lFCjiz4BH7l9wmrMkfkJYCxFwKQic8+RTZgWPuWxwAfjJElsXkex7DJjfSJsQIt931ilUgmwdA==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "comma-separated-tokens": "^2.0.0",+ "devlop": "^1.0.0",+ "property-information": "^7.0.0",+ "space-separated-tokens": "^2.0.0",+ "web-namespaces": "^2.0.0",+ "zwitch": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hast-util-to-text": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/hast-util-to-text/-/hast-util-to-text-4.0.2.tgz",+ "integrity": "sha512-KK6y/BN8lbaq654j7JgBydev7wuNMcID54lkRav1P0CaE1e47P72AWWPiGKXTJU271ooYzcvTAn/Zt0REnvc7A==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@types/unist": "^3.0.0",+ "hast-util-is-element": "^3.0.0",+ "unist-util-find-after": "^5.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hast-util-whitespace": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz",+ "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hastscript": {+ "version": "9.0.1",+ "resolved": "https://registry.npmjs.org/hastscript/-/hastscript-9.0.1.tgz",+ "integrity": "sha512-g7df9rMFX/SPi34tyGCyUBREQoKkapwdY/T04Qn9TDWfHhAYt4/I0gMVirzK5wEzeUqIjEB+LXC/ypb7Aqno5w==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "comma-separated-tokens": "^2.0.0",+ "hast-util-parse-selector": "^4.0.0",+ "property-information": "^7.0.0",+ "space-separated-tokens": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hermes-estree": {+ "version": "0.25.1",+ "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz",+ "integrity": "sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/hermes-parser": {+ "version": "0.25.1",+ "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.25.1.tgz",+ "integrity": "sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "hermes-estree": "0.25.1"+ }+ },+ "node_modules/hoist-non-react-statics": {+ "version": "3.3.2",+ "resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz",+ "integrity": "sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "react-is": "^16.7.0"+ }+ },+ "node_modules/hoist-non-react-statics/node_modules/react-is": {+ "version": "16.13.1",+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",+ "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",+ "license": "MIT"+ },+ "node_modules/html-url-attributes": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz",+ "integrity": "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/html-void-elements": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-3.0.0.tgz",+ "integrity": "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/hyphenate-style-name": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/hyphenate-style-name/-/hyphenate-style-name-1.1.0.tgz",+ "integrity": "sha512-WDC/ui2VVRrz3jOVi+XtjqkDjiVjTtFaAGiW37k6b+ohyQ5wYDOGkvCZa8+H0nx3gyvv0+BST9xuOgIyGQ00gw==",+ "license": "BSD-3-Clause"+ },+ "node_modules/iconv-lite": {+ "version": "0.6.3",+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",+ "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",+ "license": "MIT",+ "dependencies": {+ "safer-buffer": ">= 2.1.2 < 3.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/ignore": {+ "version": "5.3.2",+ "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",+ "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 4"+ }+ },+ "node_modules/immer": {+ "version": "10.2.0",+ "resolved": "https://registry.npmjs.org/immer/-/immer-10.2.0.tgz",+ "integrity": "sha512-d/+XTN3zfODyjr89gM3mPq1WNX2B8pYsu7eORitdwyA2sBubnTl3laYlBk4sXY5FUa5qTZGBDPJICVbvqzjlbw==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/immer"+ }+ },+ "node_modules/import-fresh": {+ "version": "3.3.1",+ "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",+ "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==",+ "license": "MIT",+ "dependencies": {+ "parent-module": "^1.0.0",+ "resolve-from": "^4.0.0"+ },+ "engines": {+ "node": ">=6"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/imurmurhash": {+ "version": "0.1.4",+ "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",+ "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.8.19"+ }+ },+ "node_modules/inline-style-parser": {+ "version": "0.2.7",+ "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz",+ "integrity": "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==",+ "license": "MIT"+ },+ "node_modules/inline-style-prefixer": {+ "version": "7.0.1",+ "resolved": "https://registry.npmjs.org/inline-style-prefixer/-/inline-style-prefixer-7.0.1.tgz",+ "integrity": "sha512-lhYo5qNTQp3EvSSp3sRvXMbVQTLrvGV6DycRMJ5dm2BLMiJ30wpXKdDdgX+GmJZ5uQMucwRKHamXSst3Sj/Giw==",+ "license": "MIT",+ "dependencies": {+ "css-in-js-utils": "^3.1.0"+ }+ },+ "node_modules/internmap": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz",+ "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/intersection-observer": {+ "version": "0.12.2",+ "resolved": "https://registry.npmjs.org/intersection-observer/-/intersection-observer-0.12.2.tgz",+ "integrity": "sha512-7m1vEcPCxXYI8HqnL8CKI6siDyD+eIWSwgB3DZA+ZTogxk9I4CDnj4wilt9x/+/QbHI4YG5YZNmC6458/e9Ktg==",+ "deprecated": "The Intersection Observer polyfill is no longer needed and can safely be removed. Intersection Observer has been Baseline since 2019.",+ "license": "Apache-2.0"+ },+ "node_modules/is-alphabetical": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz",+ "integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/is-alphanumerical": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz",+ "integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==",+ "license": "MIT",+ "dependencies": {+ "is-alphabetical": "^2.0.0",+ "is-decimal": "^2.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/is-arrayish": {+ "version": "0.2.1",+ "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz",+ "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==",+ "license": "MIT"+ },+ "node_modules/is-core-module": {+ "version": "2.16.1",+ "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz",+ "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==",+ "license": "MIT",+ "dependencies": {+ "hasown": "^2.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-decimal": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz",+ "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/is-extendable": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz",+ "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==",+ "license": "MIT",+ "dependencies": {+ "is-plain-object": "^2.0.4"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/is-extglob": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",+ "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/is-fullwidth-code-point": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/is-glob": {+ "version": "4.0.3",+ "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",+ "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "is-extglob": "^2.1.1"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/is-hexadecimal": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-2.0.1.tgz",+ "integrity": "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/is-mobile": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/is-mobile/-/is-mobile-5.0.0.tgz",+ "integrity": "sha512-Tz/yndySvLAEXh+Uk8liFCxOwVH6YutuR74utvOcu7I9Di+DwM0mtdPVZNaVvvBUM2OXxne/NhOs1zAO7riusQ==",+ "license": "MIT"+ },+ "node_modules/is-plain-obj": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz",+ "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/is-plain-object": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz",+ "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==",+ "license": "MIT",+ "dependencies": {+ "isobject": "^3.0.1"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/isexe": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/isobject": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",+ "integrity": "sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/js-cookie": {+ "version": "2.2.1",+ "resolved": "https://registry.npmjs.org/js-cookie/-/js-cookie-2.2.1.tgz",+ "integrity": "sha512-HvdH2LzI/EAZcUwA8+0nKNtWHqS+ZmijLA30RwZA0bo7ToCckjK5MkGhjED9KoRcXO6BaGI3I9UIzSA1FKFPOQ==",+ "license": "MIT"+ },+ "node_modules/js-tiktoken": {+ "version": "1.0.21",+ "resolved": "https://registry.npmjs.org/js-tiktoken/-/js-tiktoken-1.0.21.tgz",+ "integrity": "sha512-biOj/6M5qdgx5TKjDnFT1ymSpM5tbd3ylwDtrQvFQSu0Z7bBYko2dF+W/aUkXUPuk6IVpRxk/3Q2sHOzGlS36g==",+ "license": "MIT",+ "dependencies": {+ "base64-js": "^1.5.1"+ }+ },+ "node_modules/js-tokens": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",+ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",+ "license": "MIT"+ },+ "node_modules/js-yaml": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",+ "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "argparse": "^2.0.1"+ },+ "bin": {+ "js-yaml": "bin/js-yaml.js"+ }+ },+ "node_modules/jsesc": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",+ "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==",+ "license": "MIT",+ "bin": {+ "jsesc": "bin/jsesc"+ },+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/json-buffer": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz",+ "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/json-parse-even-better-errors": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz",+ "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==",+ "license": "MIT"+ },+ "node_modules/json-schema": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz",+ "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==",+ "license": "(AFL-2.1 OR BSD-3-Clause)"+ },+ "node_modules/json-schema-to-ts": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",+ "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.18.3",+ "ts-algebra": "^2.0.0"+ },+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/json-schema-traverse": {+ "version": "0.4.1",+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",+ "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/json-stable-stringify-without-jsonify": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz",+ "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/json2mq": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/json2mq/-/json2mq-0.2.0.tgz",+ "integrity": "sha512-SzoRg7ux5DWTII9J2qkrZrqV1gt+rTaoufMxEzXbS26Uid0NwaJd123HcoB80TgubEppxxIGdNxCx50fEoEWQA==",+ "license": "MIT",+ "dependencies": {+ "string-convert": "^0.2.0"+ }+ },+ "node_modules/json5": {+ "version": "2.2.3",+ "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",+ "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",+ "license": "MIT",+ "bin": {+ "json5": "lib/cli.js"+ },+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/katex": {+ "version": "0.16.27",+ "resolved": "https://registry.npmjs.org/katex/-/katex-0.16.27.tgz",+ "integrity": "sha512-aeQoDkuRWSqQN6nSvVCEFvfXdqo1OQiCmmW1kc9xSdjutPv7BGO7pqY9sQRJpMOGrEdfDgF2TfRXe5eUAD2Waw==",+ "funding": [+ "https://opencollective.com/katex",+ "https://github.com/sponsors/katex"+ ],+ "license": "MIT",+ "dependencies": {+ "commander": "^8.3.0"+ },+ "bin": {+ "katex": "cli.js"+ }+ },+ "node_modules/keyv": {+ "version": "4.5.4",+ "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",+ "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "json-buffer": "3.0.1"+ }+ },+ "node_modules/khroma": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/khroma/-/khroma-2.1.0.tgz",+ "integrity": "sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw=="+ },+ "node_modules/langium": {+ "version": "3.3.1",+ "resolved": "https://registry.npmjs.org/langium/-/langium-3.3.1.tgz",+ "integrity": "sha512-QJv/h939gDpvT+9SiLVlY7tZC3xB2qK57v0J04Sh9wpMb6MP1q8gB21L3WIo8T5P1MSMg3Ep14L7KkDCFG3y4w==",+ "license": "MIT",+ "dependencies": {+ "chevrotain": "~11.0.3",+ "chevrotain-allstar": "~0.3.0",+ "vscode-languageserver": "~9.0.1",+ "vscode-languageserver-textdocument": "~1.0.11",+ "vscode-uri": "~3.0.8"+ },+ "engines": {+ "node": ">=16.0.0"+ }+ },+ "node_modules/langsmith": {+ "version": "0.3.82",+ "resolved": "https://registry.npmjs.org/langsmith/-/langsmith-0.3.82.tgz",+ "integrity": "sha512-RTcxtRm0zp2lV+pMesMW7EZSsIlqN7OmR2F6sZ/sOFQwmcLVl+VErMPV4VkX4Sycs4/EIAFT5hpr36EqiHoikQ==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@types/uuid": "^10.0.0",+ "chalk": "^4.1.2",+ "console-table-printer": "^2.12.1",+ "p-queue": "^6.6.2",+ "semver": "^7.6.3",+ "uuid": "^10.0.0"+ },+ "peerDependencies": {+ "@opentelemetry/api": "*",+ "@opentelemetry/exporter-trace-otlp-proto": "*",+ "@opentelemetry/sdk-trace-base": "*",+ "openai": "*"+ },+ "peerDependenciesMeta": {+ "@opentelemetry/api": {+ "optional": true+ },+ "@opentelemetry/exporter-trace-otlp-proto": {+ "optional": true+ },+ "@opentelemetry/sdk-trace-base": {+ "optional": true+ },+ "openai": {+ "optional": true+ }+ }+ },+ "node_modules/langsmith/node_modules/semver": {+ "version": "7.7.3",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz",+ "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==",+ "license": "ISC",+ "peer": true,+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/layout-base": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/layout-base/-/layout-base-1.0.2.tgz",+ "integrity": "sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg==",+ "license": "MIT"+ },+ "node_modules/leva": {+ "version": "0.10.1",+ "resolved": "https://registry.npmjs.org/leva/-/leva-0.10.1.tgz",+ "integrity": "sha512-BcjnfUX8jpmwZUz2L7AfBtF9vn4ggTH33hmeufDULbP3YgNZ/C+ss/oO3stbrqRQyaOmRwy70y7BGTGO81S3rA==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-portal": "^1.1.4",+ "@radix-ui/react-tooltip": "^1.1.8",+ "@stitches/react": "^1.2.8",+ "@use-gesture/react": "^10.2.5",+ "colord": "^2.9.2",+ "dequal": "^2.0.2",+ "merge-value": "^1.0.0",+ "react-colorful": "^5.5.1",+ "react-dropzone": "^12.0.0",+ "v8n": "^1.3.3",+ "zustand": "^3.6.9"+ },+ "peerDependencies": {+ "react": "^18.0.0 || ^19.0.0",+ "react-dom": "^18.0.0 || ^19.0.0"+ }+ },+ "node_modules/leva/node_modules/zustand": {+ "version": "3.7.2",+ "resolved": "https://registry.npmjs.org/zustand/-/zustand-3.7.2.tgz",+ "integrity": "sha512-PIJDIZKtokhof+9+60cpockVOq05sJzHCriyvaLBmEJixseQ1a5Kdov6fWZfWOu5SK9c+FhH1jU0tntLxRJYMA==",+ "license": "MIT",+ "engines": {+ "node": ">=12.7.0"+ },+ "peerDependencies": {+ "react": ">=16.8"+ },+ "peerDependenciesMeta": {+ "react": {+ "optional": true+ }+ }+ },+ "node_modules/levn": {+ "version": "0.4.1",+ "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz",+ "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "prelude-ls": "^1.2.1",+ "type-check": "~0.4.0"+ },+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/lines-and-columns": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz",+ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",+ "license": "MIT"+ },+ "node_modules/lit": {+ "version": "3.3.1",+ "resolved": "https://registry.npmjs.org/lit/-/lit-3.3.1.tgz",+ "integrity": "sha512-Ksr/8L3PTapbdXJCk+EJVB78jDodUMaP54gD24W186zGRARvwrsPfS60wae/SSCTCNZVPd1chXqio1qHQmu4NA==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "@lit/reactive-element": "^2.1.0",+ "lit-element": "^4.2.0",+ "lit-html": "^3.3.0"+ }+ },+ "node_modules/lit-element": {+ "version": "4.2.1",+ "resolved": "https://registry.npmjs.org/lit-element/-/lit-element-4.2.1.tgz",+ "integrity": "sha512-WGAWRGzirAgyphK2urmYOV72tlvnxw7YfyLDgQ+OZnM9vQQBQnumQ7jUJe6unEzwGU3ahFOjuz1iz1jjrpCPuw==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "@lit-labs/ssr-dom-shim": "^1.4.0",+ "@lit/reactive-element": "^2.1.0",+ "lit-html": "^3.3.0"+ }+ },+ "node_modules/lit-html": {+ "version": "3.3.1",+ "resolved": "https://registry.npmjs.org/lit-html/-/lit-html-3.3.1.tgz",+ "integrity": "sha512-S9hbyDu/vs1qNrithiNyeyv64c9yqiW9l+DBgI18fL+MTvOtWoFR0FWiyq1TxaYef5wNlpEmzlXoBlZEO+WjoA==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "@types/trusted-types": "^2.0.2"+ }+ },+ "node_modules/locate-path": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",+ "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "p-locate": "^5.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/lodash": {+ "version": "4.17.21",+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",+ "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",+ "license": "MIT"+ },+ "node_modules/lodash-es": {+ "version": "4.17.21",+ "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.21.tgz",+ "integrity": "sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==",+ "license": "MIT"+ },+ "node_modules/lodash.debounce": {+ "version": "4.0.8",+ "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz",+ "integrity": "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==",+ "license": "MIT"+ },+ "node_modules/lodash.merge": {+ "version": "4.6.2",+ "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",+ "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/longest-streak": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz",+ "integrity": "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/loose-envify": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",+ "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",+ "license": "MIT",+ "dependencies": {+ "js-tokens": "^3.0.0 || ^4.0.0"+ },+ "bin": {+ "loose-envify": "cli.js"+ }+ },+ "node_modules/lucide-react": {+ "version": "0.469.0",+ "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.469.0.tgz",+ "integrity": "sha512-28vvUnnKQ/dBwiCQtwJw7QauYnE7yd2Cyp4tTTJpvglX4EMpbflcdBgrgToX2j71B3YvugK/NH3BGUk+E/p/Fw==",+ "license": "ISC",+ "peerDependencies": {+ "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },+ "node_modules/markdown-extensions": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/markdown-extensions/-/markdown-extensions-2.0.0.tgz",+ "integrity": "sha512-o5vL7aDWatOTX8LzaS1WMoaoxIiLRQJuIKKe2wAw6IeULDHaqbiqiggmx+pKvZDb1Sj+pE46Sn1T7lCqfFtg1Q==",+ "license": "MIT",+ "engines": {+ "node": ">=16"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/markdown-table": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.0.4.tgz",+ "integrity": "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/marked": {+ "version": "17.0.1",+ "resolved": "https://registry.npmjs.org/marked/-/marked-17.0.1.tgz",+ "integrity": "sha512-boeBdiS0ghpWcSwoNm/jJBwdpFaMnZWRzjA6SkUMYb40SVaN1x7mmfGKp0jvexGcx+7y2La5zRZsYFZI6Qpypg==",+ "license": "MIT",+ "bin": {+ "marked": "bin/marked.js"+ },+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/mdast-util-find-and-replace": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.2.tgz",+ "integrity": "sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "escape-string-regexp": "^5.0.0",+ "unist-util-is": "^6.0.0",+ "unist-util-visit-parents": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-find-and-replace/node_modules/escape-string-regexp": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz",+ "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/mdast-util-from-markdown": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.0.2.tgz",+ "integrity": "sha512-uZhTV/8NBuw0WHkPTrCqDOl0zVe1BIng5ZtHoDk49ME1qqcjYmmLmOf0gELgcRMxN4w2iuIeVso5/6QymSrgmA==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "@types/unist": "^3.0.0",+ "decode-named-character-reference": "^1.0.0",+ "devlop": "^1.0.0",+ "mdast-util-to-string": "^4.0.0",+ "micromark": "^4.0.0",+ "micromark-util-decode-numeric-character-reference": "^2.0.0",+ "micromark-util-decode-string": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0",+ "unist-util-stringify-position": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm/-/mdast-util-gfm-3.1.0.tgz",+ "integrity": "sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==",+ "license": "MIT",+ "dependencies": {+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-gfm-autolink-literal": "^2.0.0",+ "mdast-util-gfm-footnote": "^2.0.0",+ "mdast-util-gfm-strikethrough": "^2.0.0",+ "mdast-util-gfm-table": "^2.0.0",+ "mdast-util-gfm-task-list-item": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm-autolink-literal": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-autolink-literal/-/mdast-util-gfm-autolink-literal-2.0.1.tgz",+ "integrity": "sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "ccount": "^2.0.0",+ "devlop": "^1.0.0",+ "mdast-util-find-and-replace": "^3.0.0",+ "micromark-util-character": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm-footnote": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-footnote/-/mdast-util-gfm-footnote-2.1.0.tgz",+ "integrity": "sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "devlop": "^1.1.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm-strikethrough": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-strikethrough/-/mdast-util-gfm-strikethrough-2.0.0.tgz",+ "integrity": "sha512-mKKb915TF+OC5ptj5bJ7WFRPdYtuHv0yTRxK2tJvi+BDqbkiG7h7u/9SI89nRAYcmap2xHQL9D+QG/6wSrTtXg==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm-table": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-table/-/mdast-util-gfm-table-2.0.0.tgz",+ "integrity": "sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "devlop": "^1.0.0",+ "markdown-table": "^3.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm-task-list-item": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-task-list-item/-/mdast-util-gfm-task-list-item-2.0.0.tgz",+ "integrity": "sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "devlop": "^1.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-math": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/mdast-util-math/-/mdast-util-math-3.0.0.tgz",+ "integrity": "sha512-Tl9GBNeG/AhJnQM221bJR2HPvLOSnLE/T9cJI9tlc6zwQk2nPk/4f0cHkOdEixQPC/j8UtKDdITswvLAy1OZ1w==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "devlop": "^1.0.0",+ "longest-streak": "^3.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.1.0",+ "unist-util-remove-position": "^5.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-mdx": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/mdast-util-mdx/-/mdast-util-mdx-3.0.0.tgz",+ "integrity": "sha512-JfbYLAW7XnYTTbUsmpu0kdBUVe+yKVJZBItEjwyYJiDJuZ9w4eeaqks4HQO+R7objWgS2ymV60GYpI14Ug554w==",+ "license": "MIT",+ "dependencies": {+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-mdx-expression": "^2.0.0",+ "mdast-util-mdx-jsx": "^3.0.0",+ "mdast-util-mdxjs-esm": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-mdx-expression": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/mdast-util-mdx-expression/-/mdast-util-mdx-expression-2.0.1.tgz",+ "integrity": "sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==",+ "license": "MIT",+ "dependencies": {+ "@types/estree-jsx": "^1.0.0",+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "devlop": "^1.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-mdx-jsx": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.2.0.tgz",+ "integrity": "sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q==",+ "license": "MIT",+ "dependencies": {+ "@types/estree-jsx": "^1.0.0",+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "@types/unist": "^3.0.0",+ "ccount": "^2.0.0",+ "devlop": "^1.1.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0",+ "parse-entities": "^4.0.0",+ "stringify-entities": "^4.0.0",+ "unist-util-stringify-position": "^4.0.0",+ "vfile-message": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-mdxjs-esm": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/mdast-util-mdxjs-esm/-/mdast-util-mdxjs-esm-2.0.1.tgz",+ "integrity": "sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==",+ "license": "MIT",+ "dependencies": {+ "@types/estree-jsx": "^1.0.0",+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "devlop": "^1.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-newline-to-break": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/mdast-util-newline-to-break/-/mdast-util-newline-to-break-2.0.0.tgz",+ "integrity": "sha512-MbgeFca0hLYIEx/2zGsszCSEJJ1JSCdiY5xQxRcLDDGa8EPvlLPupJ4DSajbMPAnC0je8jfb9TiUATnxxrHUog==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-find-and-replace": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-phrasing": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/mdast-util-phrasing/-/mdast-util-phrasing-4.1.0.tgz",+ "integrity": "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "unist-util-is": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-to-hast": {+ "version": "13.2.1",+ "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz",+ "integrity": "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "@ungap/structured-clone": "^1.0.0",+ "devlop": "^1.0.0",+ "micromark-util-sanitize-uri": "^2.0.0",+ "trim-lines": "^3.0.0",+ "unist-util-position": "^5.0.0",+ "unist-util-visit": "^5.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-to-markdown": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/mdast-util-to-markdown/-/mdast-util-to-markdown-2.1.2.tgz",+ "integrity": "sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "@types/unist": "^3.0.0",+ "longest-streak": "^3.0.0",+ "mdast-util-phrasing": "^4.0.0",+ "mdast-util-to-string": "^4.0.0",+ "micromark-util-classify-character": "^2.0.0",+ "micromark-util-decode-string": "^2.0.0",+ "unist-util-visit": "^5.0.0",+ "zwitch": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-to-string": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-4.0.0.tgz",+ "integrity": "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdn-data": {+ "version": "2.0.14",+ "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.0.14.tgz",+ "integrity": "sha512-dn6wd0uw5GsdswPFfsgMp5NSB0/aDe6fK94YJV/AJDYXL6HVLWBsxeq7js7Ad+mU2K9LAlwpk6kN2D5mwCPVow==",+ "license": "CC0-1.0"+ },+ "node_modules/merge-value": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/merge-value/-/merge-value-1.0.0.tgz",+ "integrity": "sha512-fJMmvat4NeKz63Uv9iHWcPDjCWcCkoiRoajRTEO8hlhUC6rwaHg0QCF9hBOTjZmm4JuglPckPSTtcuJL5kp0TQ==",+ "license": "MIT",+ "dependencies": {+ "get-value": "^2.0.6",+ "is-extendable": "^1.0.0",+ "mixin-deep": "^1.2.0",+ "set-value": "^2.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/mermaid": {+ "version": "11.12.2",+ "resolved": "https://registry.npmjs.org/mermaid/-/mermaid-11.12.2.tgz",+ "integrity": "sha512-n34QPDPEKmaeCG4WDMGy0OT6PSyxKCfy2pJgShP+Qow2KLrvWjclwbc3yXfSIf4BanqWEhQEpngWwNp/XhZt6w==",+ "license": "MIT",+ "dependencies": {+ "@braintree/sanitize-url": "^7.1.1",+ "@iconify/utils": "^3.0.1",+ "@mermaid-js/parser": "^0.6.3",+ "@types/d3": "^7.4.3",+ "cytoscape": "^3.29.3",+ "cytoscape-cose-bilkent": "^4.1.0",+ "cytoscape-fcose": "^2.2.0",+ "d3": "^7.9.0",+ "d3-sankey": "^0.12.3",+ "dagre-d3-es": "7.0.13",+ "dayjs": "^1.11.18",+ "dompurify": "^3.2.5",+ "katex": "^0.16.22",+ "khroma": "^2.1.0",+ "lodash-es": "^4.17.21",+ "marked": "^16.2.1",+ "roughjs": "^4.6.6",+ "stylis": "^4.3.6",+ "ts-dedent": "^2.2.0",+ "uuid": "^11.1.0"+ }+ },+ "node_modules/mermaid/node_modules/marked": {+ "version": "16.4.2",+ "resolved": "https://registry.npmjs.org/marked/-/marked-16.4.2.tgz",+ "integrity": "sha512-TI3V8YYWvkVf3KJe1dRkpnjs68JUPyEa5vjKrp1XEEJUAOaQc+Qj+L1qWbPd0SJuAdQkFU0h73sXXqwDYxsiDA==",+ "license": "MIT",+ "bin": {+ "marked": "bin/marked.js"+ },+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/mermaid/node_modules/uuid": {+ "version": "11.1.0",+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz",+ "integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==",+ "funding": [+ "https://github.com/sponsors/broofa",+ "https://github.com/sponsors/ctavan"+ ],+ "license": "MIT",+ "bin": {+ "uuid": "dist/esm/bin/uuid"+ }+ },+ "node_modules/micromark": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.2.tgz",+ "integrity": "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@types/debug": "^4.0.0",+ "debug": "^4.0.0",+ "decode-named-character-reference": "^1.0.0",+ "devlop": "^1.0.0",+ "micromark-core-commonmark": "^2.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-combine-extensions": "^2.0.0",+ "micromark-util-decode-numeric-character-reference": "^2.0.0",+ "micromark-util-encode": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0",+ "micromark-util-resolve-all": "^2.0.0",+ "micromark-util-sanitize-uri": "^2.0.0",+ "micromark-util-subtokenize": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-core-commonmark": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.3.tgz",+ "integrity": "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "decode-named-character-reference": "^1.0.0",+ "devlop": "^1.0.0",+ "micromark-factory-destination": "^2.0.0",+ "micromark-factory-label": "^2.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-factory-title": "^2.0.0",+ "micromark-factory-whitespace": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-classify-character": "^2.0.0",+ "micromark-util-html-tag-name": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0",+ "micromark-util-resolve-all": "^2.0.0",+ "micromark-util-subtokenize": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-extension-cjk-friendly": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/micromark-extension-cjk-friendly/-/micromark-extension-cjk-friendly-1.2.3.tgz",+ "integrity": "sha512-gRzVLUdjXBLX6zNPSnHGDoo+ZTp5zy+MZm0g3sv+3chPXY7l9gW+DnrcHcZh/jiPR6MjPKO4AEJNp4Aw6V9z5Q==",+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.1.0",+ "micromark-extension-cjk-friendly-util": "2.1.1",+ "micromark-util-chunked": "^2.0.1",+ "micromark-util-resolve-all": "^2.0.1",+ "micromark-util-symbol": "^2.0.1"+ },+ "engines": {+ "node": ">=16"+ },+ "peerDependencies": {+ "micromark": "^4.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "peerDependenciesMeta": {+ "micromark-util-types": {+ "optional": true+ }+ }+ },+ "node_modules/micromark-extension-cjk-friendly-util": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/micromark-extension-cjk-friendly-util/-/micromark-extension-cjk-friendly-util-2.1.1.tgz",+ "integrity": "sha512-egs6+12JU2yutskHY55FyR48ZiEcFOJFyk9rsiyIhcJ6IvWB6ABBqVrBw8IobqJTDZ/wdSr9eoXDPb5S2nW1bg==",+ "license": "MIT",+ "dependencies": {+ "get-east-asian-width": "^1.3.0",+ "micromark-util-character": "^2.1.1",+ "micromark-util-symbol": "^2.0.1"+ },+ "engines": {+ "node": ">=16"+ },+ "peerDependenciesMeta": {+ "micromark-util-types": {+ "optional": true+ }+ }+ },+ "node_modules/micromark-extension-gfm": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm/-/micromark-extension-gfm-3.0.0.tgz",+ "integrity": "sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==",+ "license": "MIT",+ "dependencies": {+ "micromark-extension-gfm-autolink-literal": "^2.0.0",+ "micromark-extension-gfm-footnote": "^2.0.0",+ "micromark-extension-gfm-strikethrough": "^2.0.0",+ "micromark-extension-gfm-table": "^2.0.0",+ "micromark-extension-gfm-tagfilter": "^2.0.0",+ "micromark-extension-gfm-task-list-item": "^2.0.0",+ "micromark-util-combine-extensions": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-autolink-literal": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-autolink-literal/-/micromark-extension-gfm-autolink-literal-2.1.0.tgz",+ "integrity": "sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==",+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-sanitize-uri": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-footnote": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-footnote/-/micromark-extension-gfm-footnote-2.1.0.tgz",+ "integrity": "sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw==",+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-core-commonmark": "^2.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0",+ "micromark-util-sanitize-uri": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-strikethrough": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-strikethrough/-/micromark-extension-gfm-strikethrough-2.1.0.tgz",+ "integrity": "sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw==",+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-classify-character": "^2.0.0",+ "micromark-util-resolve-all": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-table": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-table/-/micromark-extension-gfm-table-2.1.1.tgz",+ "integrity": "sha512-t2OU/dXXioARrC6yWfJ4hqB7rct14e8f7m0cbI5hUmDyyIlwv5vEtooptH8INkbLzOatzKuVbQmAYcbWoyz6Dg==",+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-tagfilter": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-tagfilter/-/micromark-extension-gfm-tagfilter-2.0.0.tgz",+ "integrity": "sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg==",+ "license": "MIT",+ "dependencies": {+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-task-list-item": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-task-list-item/-/micromark-extension-gfm-task-list-item-2.1.0.tgz",+ "integrity": "sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw==",+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-math": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-math/-/micromark-extension-math-3.1.0.tgz",+ "integrity": "sha512-lvEqd+fHjATVs+2v/8kg9i5Q0AP2k85H0WUOwpIVvUML8BapsMvh1XAogmQjOCsLpoKRCVQqEkQBB3NhVBcsOg==",+ "license": "MIT",+ "dependencies": {+ "@types/katex": "^0.16.0",+ "devlop": "^1.0.0",+ "katex": "^0.16.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-mdx-expression": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/micromark-extension-mdx-expression/-/micromark-extension-mdx-expression-3.0.1.tgz",+ "integrity": "sha512-dD/ADLJ1AeMvSAKBwO22zG22N4ybhe7kFIZ3LsDI0GlsNr2A3KYxb0LdC1u5rj4Nw+CHKY0RVdnHX8vj8ejm4Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "devlop": "^1.0.0",+ "micromark-factory-mdx-expression": "^2.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-events-to-acorn": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-extension-mdx-jsx": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/micromark-extension-mdx-jsx/-/micromark-extension-mdx-jsx-3.0.2.tgz",+ "integrity": "sha512-e5+q1DjMh62LZAJOnDraSSbDMvGJ8x3cbjygy2qFEi7HCeUT4BDKCvMozPozcD6WmOt6sVvYDNBKhFSz3kjOVQ==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "devlop": "^1.0.0",+ "estree-util-is-identifier-name": "^3.0.0",+ "micromark-factory-mdx-expression": "^2.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-events-to-acorn": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0",+ "vfile-message": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-mdx-md": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-mdx-md/-/micromark-extension-mdx-md-2.0.0.tgz",+ "integrity": "sha512-EpAiszsB3blw4Rpba7xTOUptcFeBFi+6PY8VnJ2hhimH+vCQDirWgsMpz7w1XcZE7LVrSAUGb9VJpG9ghlYvYQ==",+ "license": "MIT",+ "dependencies": {+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-mdxjs": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-mdxjs/-/micromark-extension-mdxjs-3.0.0.tgz",+ "integrity": "sha512-A873fJfhnJ2siZyUrJ31l34Uqwy4xIFmvPY1oj+Ean5PHcPBYzEsvqvWGaWcfEIr11O5Dlw3p2y0tZWpKHDejQ==",+ "license": "MIT",+ "dependencies": {+ "acorn": "^8.0.0",+ "acorn-jsx": "^5.0.0",+ "micromark-extension-mdx-expression": "^3.0.0",+ "micromark-extension-mdx-jsx": "^3.0.0",+ "micromark-extension-mdx-md": "^2.0.0",+ "micromark-extension-mdxjs-esm": "^3.0.0",+ "micromark-util-combine-extensions": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-mdxjs-esm": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-mdxjs-esm/-/micromark-extension-mdxjs-esm-3.0.0.tgz",+ "integrity": "sha512-DJFl4ZqkErRpq/dAPyeWp15tGrcrrJho1hKK5uBS70BCtfrIFg81sqcTVu3Ta+KD1Tk5vAtBNElWxtAa+m8K9A==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "devlop": "^1.0.0",+ "micromark-core-commonmark": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-events-to-acorn": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0",+ "unist-util-position-from-estree": "^2.0.0",+ "vfile-message": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-factory-destination": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-factory-destination/-/micromark-factory-destination-2.0.1.tgz",+ "integrity": "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-factory-label": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-2.0.1.tgz",+ "integrity": "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-factory-mdx-expression": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/micromark-factory-mdx-expression/-/micromark-factory-mdx-expression-2.0.3.tgz",+ "integrity": "sha512-kQnEtA3vzucU2BkrIa8/VaSAsP+EJ3CKOvhMuJgOEGg9KDC6OAY6nSnNDVRiVNRqj7Y4SlSzcStaH/5jge8JdQ==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "devlop": "^1.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-events-to-acorn": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0",+ "unist-util-position-from-estree": "^2.0.0",+ "vfile-message": "^4.0.0"+ }+ },+ "node_modules/micromark-factory-space": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.0.1.tgz",+ "integrity": "sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-factory-title": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-2.0.1.tgz",+ "integrity": "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-factory-whitespace": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-factory-whitespace/-/micromark-factory-whitespace-2.0.1.tgz",+ "integrity": "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-character": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz",+ "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-chunked": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-chunked/-/micromark-util-chunked-2.0.1.tgz",+ "integrity": "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-classify-character": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-classify-character/-/micromark-util-classify-character-2.0.1.tgz",+ "integrity": "sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-combine-extensions": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-combine-extensions/-/micromark-util-combine-extensions-2.0.1.tgz",+ "integrity": "sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-decode-numeric-character-reference": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-2.0.2.tgz",+ "integrity": "sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-decode-string": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-decode-string/-/micromark-util-decode-string-2.0.1.tgz",+ "integrity": "sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "decode-named-character-reference": "^1.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-decode-numeric-character-reference": "^2.0.0",+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-encode": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz",+ "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT"+ },+ "node_modules/micromark-util-events-to-acorn": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/micromark-util-events-to-acorn/-/micromark-util-events-to-acorn-2.0.3.tgz",+ "integrity": "sha512-jmsiEIiZ1n7X1Rr5k8wVExBQCg5jy4UXVADItHmNk1zkwEVhBuIUKRu3fqv+hs4nxLISi2DQGlqIOGiFxgbfHg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "@types/unist": "^3.0.0",+ "devlop": "^1.0.0",+ "estree-util-visit": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0",+ "vfile-message": "^4.0.0"+ }+ },+ "node_modules/micromark-util-html-tag-name": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-html-tag-name/-/micromark-util-html-tag-name-2.0.1.tgz",+ "integrity": "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT"+ },+ "node_modules/micromark-util-normalize-identifier": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-2.0.1.tgz",+ "integrity": "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-resolve-all": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-resolve-all/-/micromark-util-resolve-all-2.0.1.tgz",+ "integrity": "sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-sanitize-uri": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz",+ "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-encode": "^2.0.0",+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-subtokenize": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-2.1.0.tgz",+ "integrity": "sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-symbol": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz",+ "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT"+ },+ "node_modules/micromark-util-types": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz",+ "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT"+ },+ "node_modules/minimatch": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",+ "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "brace-expansion": "^1.1.7"+ },+ "engines": {+ "node": "*"+ }+ },+ "node_modules/mixin-deep": {+ "version": "1.3.2",+ "resolved": "https://registry.npmjs.org/mixin-deep/-/mixin-deep-1.3.2.tgz",+ "integrity": "sha512-WRoDn//mXBiJ1H40rqa3vH0toePwSsGb45iInWlTySa+Uu4k3tYUSxa2v1KqAiLtvlrSzaExqS1gtk96A9zvEA==",+ "license": "MIT",+ "dependencies": {+ "for-in": "^1.0.2",+ "is-extendable": "^1.0.1"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/mlly": {+ "version": "1.8.0",+ "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.0.tgz",+ "integrity": "sha512-l8D9ODSRWLe2KHJSifWGwBqpTZXIXTeo8mlKjY+E2HAakaTeNpqAyBZ8GSqLzHgw4XmHmC8whvpjJNMbFZN7/g==",+ "license": "MIT",+ "dependencies": {+ "acorn": "^8.15.0",+ "pathe": "^2.0.3",+ "pkg-types": "^1.3.1",+ "ufo": "^1.6.1"+ }+ },+ "node_modules/motion-dom": {+ "version": "12.23.23",+ "resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-12.23.23.tgz",+ "integrity": "sha512-n5yolOs0TQQBRUFImrRfs/+6X4p3Q4n1dUEqt/H58Vx7OW6RF+foWEgmTVDhIWJIMXOuNNL0apKH2S16en9eiA==",+ "license": "MIT",+ "dependencies": {+ "motion-utils": "^12.23.6"+ }+ },+ "node_modules/motion-utils": {+ "version": "12.23.6",+ "resolved": "https://registry.npmjs.org/motion-utils/-/motion-utils-12.23.6.tgz",+ "integrity": "sha512-eAWoPgr4eFEOFfg2WjIsMoqJTW6Z8MTUCgn/GZ3VRpClWBdnbjryiA3ZSNLyxCTmCQx4RmYX6jX1iWHbenUPNQ==",+ "license": "MIT"+ },+ "node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "license": "MIT"+ },+ "node_modules/mustache": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/mustache/-/mustache-4.2.0.tgz",+ "integrity": "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==",+ "license": "MIT",+ "peer": true,+ "bin": {+ "mustache": "bin/mustache"+ }+ },+ "node_modules/nano-css": {+ "version": "5.6.2",+ "resolved": "https://registry.npmjs.org/nano-css/-/nano-css-5.6.2.tgz",+ "integrity": "sha512-+6bHaC8dSDGALM1HJjOHVXpuastdu2xFoZlC77Jh4cg+33Zcgm+Gxd+1xsnpZK14eyHObSp82+ll5y3SX75liw==",+ "license": "Unlicense",+ "dependencies": {+ "@jridgewell/sourcemap-codec": "^1.4.15",+ "css-tree": "^1.1.2",+ "csstype": "^3.1.2",+ "fastest-stable-stringify": "^2.0.2",+ "inline-style-prefixer": "^7.0.1",+ "rtl-css-js": "^1.16.1",+ "stacktrace-js": "^2.0.2",+ "stylis": "^4.3.0"+ },+ "peerDependencies": {+ "react": "*",+ "react-dom": "*"+ }+ },+ "node_modules/nanoid": {+ "version": "3.3.11",+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",+ "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "bin": {+ "nanoid": "bin/nanoid.cjs"+ },+ "engines": {+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"+ }+ },+ "node_modules/natural-compare": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",+ "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/node-releases": {+ "version": "2.0.27",+ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.27.tgz",+ "integrity": "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==",+ "license": "MIT"+ },+ "node_modules/normalize-range": {+ "version": "0.1.2",+ "resolved": "https://registry.npmjs.org/normalize-range/-/normalize-range-0.1.2.tgz",+ "integrity": "sha512-bdok/XvKII3nUpklnV6P2hxtMNrCboOjAcyBuQnWEhO665FwrSNRxU+AqpsyvO6LgGYPspN+lu5CLtw4jPRKNA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/numeral": {+ "version": "2.0.6",+ "resolved": "https://registry.npmjs.org/numeral/-/numeral-2.0.6.tgz",+ "integrity": "sha512-qaKRmtYPZ5qdw4jWJD6bxEf1FJEqllJrwxCLIm0sQU/A7v2/czigzOb+C2uSiFsa9lBUzeH7M1oK+Q+OLxL3kA==",+ "license": "MIT",+ "engines": {+ "node": "*"+ }+ },+ "node_modules/object-assign": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/on-change": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/on-change/-/on-change-4.0.2.tgz",+ "integrity": "sha512-cMtCyuJmTx/bg2HCpHo3ZLeF7FZnBOapLqZHr2AlLeJ5Ul0Zu2mUJJz051Fdwu/Et2YW04ZD+TtU+gVy0ACNCA==",+ "license": "MIT",+ "engines": {+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"+ },+ "funding": {+ "url": "https://github.com/sindresorhus/on-change?sponsor=1"+ }+ },+ "node_modules/oniguruma-parser": {+ "version": "0.12.1",+ "resolved": "https://registry.npmjs.org/oniguruma-parser/-/oniguruma-parser-0.12.1.tgz",+ "integrity": "sha512-8Unqkvk1RYc6yq2WBYRj4hdnsAxVze8i7iPfQr8e4uSP3tRv0rpZcbGUDvxfQQcdwHt/e9PrMvGCsa8OqG9X3w==",+ "license": "MIT"+ },+ "node_modules/oniguruma-to-es": {+ "version": "4.3.4",+ "resolved": "https://registry.npmjs.org/oniguruma-to-es/-/oniguruma-to-es-4.3.4.tgz",+ "integrity": "sha512-3VhUGN3w2eYxnTzHn+ikMI+fp/96KoRSVK9/kMTcFqj1NRDh2IhQCKvYxDnWePKRXY/AqH+Fuiyb7VHSzBjHfA==",+ "license": "MIT",+ "dependencies": {+ "oniguruma-parser": "^0.12.1",+ "regex": "^6.0.1",+ "regex-recursion": "^6.0.2"+ }+ },+ "node_modules/openai": {+ "version": "5.23.2",+ "resolved": "https://registry.npmjs.org/openai/-/openai-5.23.2.tgz",+ "integrity": "sha512-MQBzmTulj+MM5O8SKEk/gL8a7s5mktS9zUtAkU257WjvobGc9nKcBuVwjyEEcb9SI8a8Y2G/mzn3vm9n1Jlleg==",+ "license": "Apache-2.0",+ "bin": {+ "openai": "bin/cli"+ },+ "peerDependencies": {+ "ws": "^8.18.0",+ "zod": "^3.23.8"+ },+ "peerDependenciesMeta": {+ "ws": {+ "optional": true+ },+ "zod": {+ "optional": true+ }+ }+ },+ "node_modules/optionator": {+ "version": "0.9.4",+ "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",+ "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "deep-is": "^0.1.3",+ "fast-levenshtein": "^2.0.6",+ "levn": "^0.4.1",+ "prelude-ls": "^1.2.1",+ "type-check": "^0.4.0",+ "word-wrap": "^1.2.5"+ },+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/p-finally": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz",+ "integrity": "sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow==",+ "license": "MIT",+ "peer": true,+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/p-limit": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",+ "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "yocto-queue": "^0.1.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/p-locate": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz",+ "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "p-limit": "^3.0.2"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/p-queue": {+ "version": "6.6.2",+ "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-6.6.2.tgz",+ "integrity": "sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "eventemitter3": "^4.0.4",+ "p-timeout": "^3.2.0"+ },+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/p-retry": {+ "version": "4.6.2",+ "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz",+ "integrity": "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@types/retry": "0.12.0",+ "retry": "^0.13.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/p-timeout": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-3.2.0.tgz",+ "integrity": "sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "p-finally": "^1.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/package-manager-detector": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/package-manager-detector/-/package-manager-detector-1.6.0.tgz",+ "integrity": "sha512-61A5ThoTiDG/C8s8UMZwSorAGwMJ0ERVGj2OjoW5pAalsNOg15+iQiPzrLJ4jhZ1HJzmC2PIHT2oEiH3R5fzNA==",+ "license": "MIT"+ },+ "node_modules/parent-module": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",+ "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==",+ "license": "MIT",+ "dependencies": {+ "callsites": "^3.0.0"+ },+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/parse-entities": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-4.0.2.tgz",+ "integrity": "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^2.0.0",+ "character-entities-legacy": "^3.0.0",+ "character-reference-invalid": "^2.0.0",+ "decode-named-character-reference": "^1.0.0",+ "is-alphanumerical": "^2.0.0",+ "is-decimal": "^2.0.0",+ "is-hexadecimal": "^2.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/parse-entities/node_modules/@types/unist": {+ "version": "2.0.11",+ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz",+ "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==",+ "license": "MIT"+ },+ "node_modules/parse-json": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz",+ "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==",+ "license": "MIT",+ "dependencies": {+ "@babel/code-frame": "^7.0.0",+ "error-ex": "^1.3.1",+ "json-parse-even-better-errors": "^2.3.0",+ "lines-and-columns": "^1.1.6"+ },+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/parse5": {+ "version": "7.3.0",+ "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz",+ "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==",+ "license": "MIT",+ "dependencies": {+ "entities": "^6.0.0"+ },+ "funding": {+ "url": "https://github.com/inikulin/parse5?sponsor=1"+ }+ },+ "node_modules/path-data-parser": {+ "version": "0.1.0",+ "resolved": "https://registry.npmjs.org/path-data-parser/-/path-data-parser-0.1.0.tgz",+ "integrity": "sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==",+ "license": "MIT"+ },+ "node_modules/path-exists": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",+ "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/path-key": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/path-parse": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",+ "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",+ "license": "MIT"+ },+ "node_modules/path-type": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz",+ "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/pathe": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",+ "license": "MIT"+ },+ "node_modules/picocolors": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",+ "license": "ISC"+ },+ "node_modules/picomatch": {+ "version": "4.0.3",+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",+ "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/jonschlinkert"+ }+ },+ "node_modules/pkg-types": {+ "version": "1.3.1",+ "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz",+ "integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==",+ "license": "MIT",+ "dependencies": {+ "confbox": "^0.1.8",+ "mlly": "^1.7.4",+ "pathe": "^2.0.1"+ }+ },+ "node_modules/points-on-curve": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/points-on-curve/-/points-on-curve-0.2.0.tgz",+ "integrity": "sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==",+ "license": "MIT"+ },+ "node_modules/points-on-path": {+ "version": "0.2.1",+ "resolved": "https://registry.npmjs.org/points-on-path/-/points-on-path-0.2.1.tgz",+ "integrity": "sha512-25ClnWWuw7JbWZcgqY/gJ4FQWadKxGWk+3kR/7kD0tCaDtPPMj7oHu2ToLaVhfpnHrZzYby2w6tUA0eOIuUg8g==",+ "license": "MIT",+ "dependencies": {+ "path-data-parser": "0.1.0",+ "points-on-curve": "0.2.0"+ }+ },+ "node_modules/polished": {+ "version": "4.3.1",+ "resolved": "https://registry.npmjs.org/polished/-/polished-4.3.1.tgz",+ "integrity": "sha512-OBatVyC/N7SCW/FaDHrSd+vn0o5cS855TOmYi4OkdWUMSJCET/xip//ch8xGUvtr3i44X9LVyWwQlRMTN3pwSA==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.17.8"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/postcss": {+ "version": "8.5.6",+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz",+ "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/postcss"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "nanoid": "^3.3.11",+ "picocolors": "^1.1.1",+ "source-map-js": "^1.2.1"+ },+ "engines": {+ "node": "^10 || ^12 || >=14"+ }+ },+ "node_modules/postcss-value-parser": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz",+ "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==",+ "license": "MIT"+ },+ "node_modules/prelude-ls": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",+ "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/prismjs": {+ "version": "1.30.0",+ "resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.30.0.tgz",+ "integrity": "sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/prop-types": {+ "version": "15.8.1",+ "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",+ "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",+ "license": "MIT",+ "dependencies": {+ "loose-envify": "^1.4.0",+ "object-assign": "^4.1.1",+ "react-is": "^16.13.1"+ }+ },+ "node_modules/prop-types/node_modules/react-is": {+ "version": "16.13.1",+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",+ "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",+ "license": "MIT"+ },+ "node_modules/property-information": {+ "version": "7.1.0",+ "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz",+ "integrity": "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/punycode": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",+ "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/query-string": {+ "version": "9.3.1",+ "resolved": "https://registry.npmjs.org/query-string/-/query-string-9.3.1.tgz",+ "integrity": "sha512-5fBfMOcDi5SA9qj5jZhWAcTtDfKF5WFdd2uD9nVNlbxVv1baq65aALy6qofpNEGELHvisjjasxQp7BlM9gvMzw==",+ "license": "MIT",+ "dependencies": {+ "decode-uri-component": "^0.4.1",+ "filter-obj": "^5.1.0",+ "split-on-first": "^3.0.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/rc-cascader": {+ "version": "3.34.0",+ "resolved": "https://registry.npmjs.org/rc-cascader/-/rc-cascader-3.34.0.tgz",+ "integrity": "sha512-KpXypcvju9ptjW9FaN2NFcA2QH9E9LHKq169Y0eWtH4e/wHQ5Wh5qZakAgvb8EKZ736WZ3B0zLLOBsrsja5Dag==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.25.7",+ "classnames": "^2.3.1",+ "rc-select": "~14.16.2",+ "rc-tree": "~5.13.0",+ "rc-util": "^5.43.0"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-checkbox": {+ "version": "3.5.0",+ "resolved": "https://registry.npmjs.org/rc-checkbox/-/rc-checkbox-3.5.0.tgz",+ "integrity": "sha512-aOAQc3E98HteIIsSqm6Xk2FPKIER6+5vyEFMZfo73TqM+VVAIqOkHoPjgKLqSNtVLWScoaM7vY2ZrGEheI79yg==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.10.1",+ "classnames": "^2.3.2",+ "rc-util": "^5.25.2"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-collapse": {+ "version": "3.9.0",+ "resolved": "https://registry.npmjs.org/rc-collapse/-/rc-collapse-3.9.0.tgz",+ "integrity": "sha512-swDdz4QZ4dFTo4RAUMLL50qP0EY62N2kvmk2We5xYdRwcRn8WcYtuetCJpwpaCbUfUt5+huLpVxhvmnK+PHrkA==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.10.1",+ "classnames": "2.x",+ "rc-motion": "^2.3.4",+ "rc-util": "^5.27.0"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-dialog": {+ "version": "9.6.0",+ "resolved": "https://registry.npmjs.org/rc-dialog/-/rc-dialog-9.6.0.tgz",+ "integrity": "sha512-ApoVi9Z8PaCQg6FsUzS8yvBEQy0ZL2PkuvAgrmohPkN3okps5WZ5WQWPc1RNuiOKaAYv8B97ACdsFU5LizzCqg==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.10.1",+ "@rc-component/portal": "^1.0.0-8",+ "classnames": "^2.2.6",+ "rc-motion": "^2.3.0",+ "rc-util": "^5.21.0"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-drawer": {+ "version": "7.3.0",+ "resolved": "https://registry.npmjs.org/rc-drawer/-/rc-drawer-7.3.0.tgz",+ "integrity": "sha512-DX6CIgiBWNpJIMGFO8BAISFkxiuKitoizooj4BDyee8/SnBn0zwO2FHrNDpqqepj0E/TFTDpmEBCyFuTgC7MOg==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.23.9",+ "@rc-component/portal": "^1.1.1",+ "classnames": "^2.2.6",+ "rc-motion": "^2.6.1",+ "rc-util": "^5.38.1"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-dropdown": {+ "version": "4.2.1",+ "resolved": "https://registry.npmjs.org/rc-dropdown/-/rc-dropdown-4.2.1.tgz",+ "integrity": "sha512-YDAlXsPv3I1n42dv1JpdM7wJ+gSUBfeyPK59ZpBD9jQhK9jVuxpjj3NmWQHOBceA1zEPVX84T2wbdb2SD0UjmA==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.18.3",+ "@rc-component/trigger": "^2.0.0",+ "classnames": "^2.2.6",+ "rc-util": "^5.44.1"+ },+ "peerDependencies": {+ "react": ">=16.11.0",+ "react-dom": ">=16.11.0"+ }+ },+ "node_modules/rc-field-form": {+ "version": "2.7.1",+ "resolved": "https://registry.npmjs.org/rc-field-form/-/rc-field-form-2.7.1.tgz",+ "integrity": "sha512-vKeSifSJ6HoLaAB+B8aq/Qgm8a3dyxROzCtKNCsBQgiverpc4kWDQihoUwzUj+zNWJOykwSY4dNX3QrGwtVb9A==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.18.0",+ "@rc-component/async-validator": "^5.0.3",+ "rc-util": "^5.32.2"+ },+ "engines": {+ "node": ">=8.x"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-footer": {+ "version": "0.6.8",+ "resolved": "https://registry.npmjs.org/rc-footer/-/rc-footer-0.6.8.tgz",+ "integrity": "sha512-JBZ+xcb6kkex8XnBd4VHw1ZxjV6kmcwUumSHaIFdka2qzMCo7Klcy4sI6G0XtUpG/vtpislQCc+S9Bc+NLHYMg==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.11.1",+ "classnames": "^2.2.1"+ },+ "peerDependencies": {+ "react": ">=16.0.0",+ "react-dom": ">=16.0.0"+ }+ },+ "node_modules/rc-image": {+ "version": "7.12.0",+ "resolved": "https://registry.npmjs.org/rc-image/-/rc-image-7.12.0.tgz",+ "integrity": "sha512-cZ3HTyyckPnNnUb9/DRqduqzLfrQRyi+CdHjdqgsyDpI3Ln5UX1kXnAhPBSJj9pVRzwRFgqkN7p9b6HBDjmu/Q==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.11.2",+ "@rc-component/portal": "^1.0.2",+ "classnames": "^2.2.6",+ "rc-dialog": "~9.6.0",+ "rc-motion": "^2.6.2",+ "rc-util": "^5.34.1"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-input": {+ "version": "1.8.0",+ "resolved": "https://registry.npmjs.org/rc-input/-/rc-input-1.8.0.tgz",+ "integrity": "sha512-KXvaTbX+7ha8a/k+eg6SYRVERK0NddX8QX7a7AnRvUa/rEH0CNMlpcBzBkhI0wp2C8C4HlMoYl8TImSN+fuHKA==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.11.1",+ "classnames": "^2.2.1",+ "rc-util": "^5.18.1"+ },+ "peerDependencies": {+ "react": ">=16.0.0",+ "react-dom": ">=16.0.0"+ }+ },+ "node_modules/rc-input-number": {+ "version": "9.5.0",+ "resolved": "https://registry.npmjs.org/rc-input-number/-/rc-input-number-9.5.0.tgz",+ "integrity": "sha512-bKaEvB5tHebUURAEXw35LDcnRZLq3x1k7GxfAqBMzmpHkDGzjAtnUL8y4y5N15rIFIg5IJgwr211jInl3cipag==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.10.1",+ "@rc-component/mini-decimal": "^1.0.1",+ "classnames": "^2.2.5",+ "rc-input": "~1.8.0",+ "rc-util": "^5.40.1"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-mentions": {+ "version": "2.20.0",+ "resolved": "https://registry.npmjs.org/rc-mentions/-/rc-mentions-2.20.0.tgz",+ "integrity": "sha512-w8HCMZEh3f0nR8ZEd466ATqmXFCMGMN5UFCzEUL0bM/nGw/wOS2GgRzKBcm19K++jDyuWCOJOdgcKGXU3fXfbQ==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.22.5",+ "@rc-component/trigger": "^2.0.0",+ "classnames": "^2.2.6",+ "rc-input": "~1.8.0",+ "rc-menu": "~9.16.0",+ "rc-textarea": "~1.10.0",+ "rc-util": "^5.34.1"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-menu": {+ "version": "9.16.1",+ "resolved": "https://registry.npmjs.org/rc-menu/-/rc-menu-9.16.1.tgz",+ "integrity": "sha512-ghHx6/6Dvp+fw8CJhDUHFHDJ84hJE3BXNCzSgLdmNiFErWSOaZNsihDAsKq9ByTALo/xkNIwtDFGIl6r+RPXBg==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.10.1",+ "@rc-component/trigger": "^2.0.0",+ "classnames": "2.x",+ "rc-motion": "^2.4.3",+ "rc-overflow": "^1.3.1",+ "rc-util": "^5.27.0"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-motion": {+ "version": "2.9.5",+ "resolved": "https://registry.npmjs.org/rc-motion/-/rc-motion-2.9.5.tgz",+ "integrity": "sha512-w+XTUrfh7ArbYEd2582uDrEhmBHwK1ZENJiSJVb7uRxdE7qJSYjbO2eksRXmndqyKqKoYPc9ClpPh5242mV1vA==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.11.1",+ "classnames": "^2.2.1",+ "rc-util": "^5.44.0"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-notification": {+ "version": "5.6.4",+ "resolved": "https://registry.npmjs.org/rc-notification/-/rc-notification-5.6.4.tgz",+ "integrity": "sha512-KcS4O6B4qzM3KH7lkwOB7ooLPZ4b6J+VMmQgT51VZCeEcmghdeR4IrMcFq0LG+RPdnbe/ArT086tGM8Snimgiw==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.10.1",+ "classnames": "2.x",+ "rc-motion": "^2.9.0",+ "rc-util": "^5.20.1"+ },+ "engines": {+ "node": ">=8.x"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-overflow": {+ "version": "1.5.0",+ "resolved": "https://registry.npmjs.org/rc-overflow/-/rc-overflow-1.5.0.tgz",+ "integrity": "sha512-Lm/v9h0LymeUYJf0x39OveU52InkdRXqnn2aYXfWmo8WdOonIKB2kfau+GF0fWq6jPgtdO9yMqveGcK6aIhJmg==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.11.1",+ "classnames": "^2.2.1",+ "rc-resize-observer": "^1.0.0",+ "rc-util": "^5.37.0"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-pagination": {+ "version": "5.1.0",+ "resolved": "https://registry.npmjs.org/rc-pagination/-/rc-pagination-5.1.0.tgz",+ "integrity": "sha512-8416Yip/+eclTFdHXLKTxZvn70duYVGTvUUWbckCCZoIl3jagqke3GLsFrMs0bsQBikiYpZLD9206Ej4SOdOXQ==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.10.1",+ "classnames": "^2.3.2",+ "rc-util": "^5.38.0"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-picker": {+ "version": "4.11.3",+ "resolved": "https://registry.npmjs.org/rc-picker/-/rc-picker-4.11.3.tgz",+ "integrity": "sha512-MJ5teb7FlNE0NFHTncxXQ62Y5lytq6sh5nUw0iH8OkHL/TjARSEvSHpr940pWgjGANpjCwyMdvsEV55l5tYNSg==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.24.7",+ "@rc-component/trigger": "^2.0.0",+ "classnames": "^2.2.1",+ "rc-overflow": "^1.3.2",+ "rc-resize-observer": "^1.4.0",+ "rc-util": "^5.43.0"+ },+ "engines": {+ "node": ">=8.x"+ },+ "peerDependencies": {+ "date-fns": ">= 2.x",+ "dayjs": ">= 1.x",+ "luxon": ">= 3.x",+ "moment": ">= 2.x",+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ },+ "peerDependenciesMeta": {+ "date-fns": {+ "optional": true+ },+ "dayjs": {+ "optional": true+ },+ "luxon": {+ "optional": true+ },+ "moment": {+ "optional": true+ }+ }+ },+ "node_modules/rc-progress": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/rc-progress/-/rc-progress-4.0.0.tgz",+ "integrity": "sha512-oofVMMafOCokIUIBnZLNcOZFsABaUw8PPrf1/y0ZBvKZNpOiu5h4AO9vv11Sw0p4Hb3D0yGWuEattcQGtNJ/aw==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.10.1",+ "classnames": "^2.2.6",+ "rc-util": "^5.16.1"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-rate": {+ "version": "2.13.1",+ "resolved": "https://registry.npmjs.org/rc-rate/-/rc-rate-2.13.1.tgz",+ "integrity": "sha512-QUhQ9ivQ8Gy7mtMZPAjLbxBt5y9GRp65VcUyGUMF3N3fhiftivPHdpuDIaWIMOTEprAjZPC08bls1dQB+I1F2Q==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.10.1",+ "classnames": "^2.2.5",+ "rc-util": "^5.0.1"+ },+ "engines": {+ "node": ">=8.x"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-resize-observer": {+ "version": "1.4.3",+ "resolved": "https://registry.npmjs.org/rc-resize-observer/-/rc-resize-observer-1.4.3.tgz",+ "integrity": "sha512-YZLjUbyIWox8E9i9C3Tm7ia+W7euPItNWSPX5sCcQTYbnwDb5uNpnLHQCG1f22oZWUhLw4Mv2tFmeWe68CDQRQ==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.20.7",+ "classnames": "^2.2.1",+ "rc-util": "^5.44.1",+ "resize-observer-polyfill": "^1.5.1"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-segmented": {+ "version": "2.7.0",+ "resolved": "https://registry.npmjs.org/rc-segmented/-/rc-segmented-2.7.0.tgz",+ "integrity": "sha512-liijAjXz+KnTRVnxxXG2sYDGd6iLL7VpGGdR8gwoxAXy2KglviKCxLWZdjKYJzYzGSUwKDSTdYk8brj54Bn5BA==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.11.1",+ "classnames": "^2.2.1",+ "rc-motion": "^2.4.4",+ "rc-util": "^5.17.0"+ },+ "peerDependencies": {+ "react": ">=16.0.0",+ "react-dom": ">=16.0.0"+ }+ },+ "node_modules/rc-select": {+ "version": "14.16.8",+ "resolved": "https://registry.npmjs.org/rc-select/-/rc-select-14.16.8.tgz",+ "integrity": "sha512-NOV5BZa1wZrsdkKaiK7LHRuo5ZjZYMDxPP6/1+09+FB4KoNi8jcG1ZqLE3AVCxEsYMBe65OBx71wFoHRTP3LRg==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.10.1",+ "@rc-component/trigger": "^2.1.1",+ "classnames": "2.x",+ "rc-motion": "^2.0.1",+ "rc-overflow": "^1.3.1",+ "rc-util": "^5.16.1",+ "rc-virtual-list": "^3.5.2"+ },+ "engines": {+ "node": ">=8.x"+ },+ "peerDependencies": {+ "react": "*",+ "react-dom": "*"+ }+ },+ "node_modules/rc-slider": {+ "version": "11.1.9",+ "resolved": "https://registry.npmjs.org/rc-slider/-/rc-slider-11.1.9.tgz",+ "integrity": "sha512-h8IknhzSh3FEM9u8ivkskh+Ef4Yo4JRIY2nj7MrH6GQmrwV6mcpJf5/4KgH5JaVI1H3E52yCdpOlVyGZIeph5A==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.10.1",+ "classnames": "^2.2.5",+ "rc-util": "^5.36.0"+ },+ "engines": {+ "node": ">=8.x"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-steps": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/rc-steps/-/rc-steps-6.0.1.tgz",+ "integrity": "sha512-lKHL+Sny0SeHkQKKDJlAjV5oZ8DwCdS2hFhAkIjuQt1/pB81M0cA0ErVFdHq9+jmPmFw1vJB2F5NBzFXLJxV+g==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.16.7",+ "classnames": "^2.2.3",+ "rc-util": "^5.16.1"+ },+ "engines": {+ "node": ">=8.x"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-switch": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/rc-switch/-/rc-switch-4.1.0.tgz",+ "integrity": "sha512-TI8ufP2Az9oEbvyCeVE4+90PDSljGyuwix3fV58p7HV2o4wBnVToEyomJRVyTaZeqNPAp+vqeo4Wnj5u0ZZQBg==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.21.0",+ "classnames": "^2.2.1",+ "rc-util": "^5.30.0"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-table": {+ "version": "7.54.0",+ "resolved": "https://registry.npmjs.org/rc-table/-/rc-table-7.54.0.tgz",+ "integrity": "sha512-/wDTkki6wBTjwylwAGjpLKYklKo9YgjZwAU77+7ME5mBoS32Q4nAwoqhA2lSge6fobLW3Tap6uc5xfwaL2p0Sw==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.10.1",+ "@rc-component/context": "^1.4.0",+ "classnames": "^2.2.5",+ "rc-resize-observer": "^1.1.0",+ "rc-util": "^5.44.3",+ "rc-virtual-list": "^3.14.2"+ },+ "engines": {+ "node": ">=8.x"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-tabs": {+ "version": "15.7.0",+ "resolved": "https://registry.npmjs.org/rc-tabs/-/rc-tabs-15.7.0.tgz",+ "integrity": "sha512-ZepiE+6fmozYdWf/9gVp7k56PKHB1YYoDsKeQA1CBlJ/POIhjkcYiv0AGP0w2Jhzftd3AVvZP/K+V+Lpi2ankA==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.11.2",+ "classnames": "2.x",+ "rc-dropdown": "~4.2.0",+ "rc-menu": "~9.16.0",+ "rc-motion": "^2.6.2",+ "rc-resize-observer": "^1.0.0",+ "rc-util": "^5.34.1"+ },+ "engines": {+ "node": ">=8.x"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-textarea": {+ "version": "1.10.2",+ "resolved": "https://registry.npmjs.org/rc-textarea/-/rc-textarea-1.10.2.tgz",+ "integrity": "sha512-HfaeXiaSlpiSp0I/pvWpecFEHpVysZ9tpDLNkxQbMvMz6gsr7aVZ7FpWP9kt4t7DB+jJXesYS0us1uPZnlRnwQ==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.10.1",+ "classnames": "^2.2.1",+ "rc-input": "~1.8.0",+ "rc-resize-observer": "^1.0.0",+ "rc-util": "^5.27.0"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-tooltip": {+ "version": "6.4.0",+ "resolved": "https://registry.npmjs.org/rc-tooltip/-/rc-tooltip-6.4.0.tgz",+ "integrity": "sha512-kqyivim5cp8I5RkHmpsp1Nn/Wk+1oeloMv9c7LXNgDxUpGm+RbXJGL+OPvDlcRnx9DBeOe4wyOIl4OKUERyH1g==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.11.2",+ "@rc-component/trigger": "^2.0.0",+ "classnames": "^2.3.1",+ "rc-util": "^5.44.3"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-tree": {+ "version": "5.13.1",+ "resolved": "https://registry.npmjs.org/rc-tree/-/rc-tree-5.13.1.tgz",+ "integrity": "sha512-FNhIefhftobCdUJshO7M8uZTA9F4OPGVXqGfZkkD/5soDeOhwO06T/aKTrg0WD8gRg/pyfq+ql3aMymLHCTC4A==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.10.1",+ "classnames": "2.x",+ "rc-motion": "^2.0.1",+ "rc-util": "^5.16.1",+ "rc-virtual-list": "^3.5.1"+ },+ "engines": {+ "node": ">=10.x"+ },+ "peerDependencies": {+ "react": "*",+ "react-dom": "*"+ }+ },+ "node_modules/rc-tree-select": {+ "version": "5.27.0",+ "resolved": "https://registry.npmjs.org/rc-tree-select/-/rc-tree-select-5.27.0.tgz",+ "integrity": "sha512-2qTBTzwIT7LRI1o7zLyrCzmo5tQanmyGbSaGTIf7sYimCklAToVVfpMC6OAldSKolcnjorBYPNSKQqJmN3TCww==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.25.7",+ "classnames": "2.x",+ "rc-select": "~14.16.2",+ "rc-tree": "~5.13.0",+ "rc-util": "^5.43.0"+ },+ "peerDependencies": {+ "react": "*",+ "react-dom": "*"+ }+ },+ "node_modules/rc-upload": {+ "version": "4.11.0",+ "resolved": "https://registry.npmjs.org/rc-upload/-/rc-upload-4.11.0.tgz",+ "integrity": "sha512-ZUyT//2JAehfHzjWowqROcwYJKnZkIUGWaTE/VogVrepSl7AFNbQf4+zGfX4zl9Vrj/Jm8scLO0R6UlPDKK4wA==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.18.3",+ "classnames": "^2.2.5",+ "rc-util": "^5.2.0"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-util": {+ "version": "5.44.4",+ "resolved": "https://registry.npmjs.org/rc-util/-/rc-util-5.44.4.tgz",+ "integrity": "sha512-resueRJzmHG9Q6rI/DfK6Kdv9/Lfls05vzMs1Sk3M2P+3cJa+MakaZyWY8IPfehVuhPJFKrIY1IK4GqbiaiY5w==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.18.3",+ "react-is": "^18.2.0"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/rc-virtual-list": {+ "version": "3.19.2",+ "resolved": "https://registry.npmjs.org/rc-virtual-list/-/rc-virtual-list-3.19.2.tgz",+ "integrity": "sha512-Ys6NcjwGkuwkeaWBDqfI3xWuZ7rDiQXlH1o2zLfFzATfEgXcqpk8CkgMfbJD81McqjcJVez25a3kPxCR807evA==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.20.0",+ "classnames": "^2.2.6",+ "rc-resize-observer": "^1.0.0",+ "rc-util": "^5.36.0"+ },+ "engines": {+ "node": ">=8.x"+ },+ "peerDependencies": {+ "react": ">=16.9.0",+ "react-dom": ">=16.9.0"+ }+ },+ "node_modules/re-resizable": {+ "version": "6.11.2",+ "resolved": "https://registry.npmjs.org/re-resizable/-/re-resizable-6.11.2.tgz",+ "integrity": "sha512-2xI2P3OHs5qw7K0Ud1aLILK6MQxW50TcO+DetD9eIV58j84TqYeHoZcL9H4GXFXXIh7afhH8mv5iUCXII7OW7A==",+ "license": "MIT",+ "peerDependencies": {+ "react": "^16.13.1 || ^17.0.0 || ^18.0.0 || ^19.0.0",+ "react-dom": "^16.13.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },+ "node_modules/react": {+ "version": "19.2.1",+ "resolved": "https://registry.npmjs.org/react/-/react-19.2.1.tgz",+ "integrity": "sha512-DGrYcCWK7tvYMnWh79yrPHt+vdx9tY+1gPZa7nJQtO/p8bLTDaHp4dzwEhQB7pZ4Xe3ok4XKuEPrVuc+wlpkmw==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/react-avatar-editor": {+ "version": "13.0.2",+ "resolved": "https://registry.npmjs.org/react-avatar-editor/-/react-avatar-editor-13.0.2.tgz",+ "integrity": "sha512-a4ajbi7lwDh98kgEtSEeKMu0vs0CHTczkq4Xcxr1EiwMFH1GlgHCEtwGU8q/H5W8SeLnH4KPK8LUjEEaZXklxQ==",+ "license": "MIT",+ "dependencies": {+ "@babel/plugin-transform-runtime": "^7.12.1",+ "@babel/runtime": "^7.12.5",+ "prop-types": "^15.7.2"+ },+ "peerDependencies": {+ "react": "^0.14.0 || ^16.0.0 || ^17.0.0 || ^18.0.0",+ "react-dom": "^0.14.0 || ^16.0.0 || ^17.0.0 || ^18.0.0"+ }+ },+ "node_modules/react-colorful": {+ "version": "5.6.1",+ "resolved": "https://registry.npmjs.org/react-colorful/-/react-colorful-5.6.1.tgz",+ "integrity": "sha512-1exovf0uGTGyq5mXQT0zgQ80uvj2PCwvF8zY1RN9/vbJVSjSo3fsB/4L3ObbF7u70NduSiK4xu4Y6q1MHoUGEw==",+ "license": "MIT",+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },+ "node_modules/react-dom": {+ "version": "19.2.1",+ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.1.tgz",+ "integrity": "sha512-ibrK8llX2a4eOskq1mXKu/TGZj9qzomO+sNfO98M6d9zIPOEhlBkMkBUBLd1vgS0gQsLDBzA+8jJBVXDnfHmJg==",+ "license": "MIT",+ "dependencies": {+ "scheduler": "^0.27.0"+ },+ "peerDependencies": {+ "react": "^19.2.1"+ }+ },+ "node_modules/react-draggable": {+ "version": "4.4.6",+ "resolved": "https://registry.npmjs.org/react-draggable/-/react-draggable-4.4.6.tgz",+ "integrity": "sha512-LtY5Xw1zTPqHkVmtM3X8MUOxNDOUhv/khTgBgrUvwaS064bwVvxT+q5El0uUFNx5IEPKXuRejr7UqLwBIg5pdw==",+ "license": "MIT",+ "dependencies": {+ "clsx": "^1.1.1",+ "prop-types": "^15.8.1"+ },+ "peerDependencies": {+ "react": ">= 16.3.0",+ "react-dom": ">= 16.3.0"+ }+ },+ "node_modules/react-draggable/node_modules/clsx": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/clsx/-/clsx-1.2.1.tgz",+ "integrity": "sha512-EcR6r5a8bj6pu3ycsa/E/cKVGuTgZJZdsyUYHOksG/UHIiKfjxzRxYJpyVBwYaQeOvghal9fcc4PidlgzugAQg==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/react-dropzone": {+ "version": "12.1.0",+ "resolved": "https://registry.npmjs.org/react-dropzone/-/react-dropzone-12.1.0.tgz",+ "integrity": "sha512-iBYHA1rbopIvtzokEX4QubO6qk5IF/x3BtKGu74rF2JkQDXnwC4uO/lHKpaw4PJIV6iIAYOlwLv2FpiGyqHNog==",+ "license": "MIT",+ "dependencies": {+ "attr-accept": "^2.2.2",+ "file-selector": "^0.5.0",+ "prop-types": "^15.8.1"+ },+ "engines": {+ "node": ">= 10.13"+ },+ "peerDependencies": {+ "react": ">= 16.8"+ }+ },+ "node_modules/react-error-boundary": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/react-error-boundary/-/react-error-boundary-6.0.0.tgz",+ "integrity": "sha512-gdlJjD7NWr0IfkPlaREN2d9uUZUlksrfOx7SX62VRerwXbMY6ftGCIZua1VG1aXFNOimhISsTq+Owp725b9SiA==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.12.5"+ },+ "peerDependencies": {+ "react": ">=16.13.1"+ }+ },+ "node_modules/react-fast-compare": {+ "version": "3.2.2",+ "resolved": "https://registry.npmjs.org/react-fast-compare/-/react-fast-compare-3.2.2.tgz",+ "integrity": "sha512-nsO+KSNgo1SbJqJEYRE9ERzo7YtYbou/OqjSQKxV7jcKox7+usiUVZOAC+XnDOABXggQTno0Y1CpVnuWEc1boQ==",+ "license": "MIT"+ },+ "node_modules/react-flow-client": {+ "resolved": "client",+ "link": true+ },+ "node_modules/react-hotkeys-hook": {+ "version": "5.2.1",+ "resolved": "https://registry.npmjs.org/react-hotkeys-hook/-/react-hotkeys-hook-5.2.1.tgz",+ "integrity": "sha512-xbKh6zJxd/vJHT4Bw4+0pBD662Fk20V+VFhLqciCg+manTVO4qlqRqiwFOYelfHN9dBvWj9vxaPkSS26ZSIJGg==",+ "license": "MIT",+ "workspaces": [+ "packages/*"+ ],+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },+ "node_modules/react-is": {+ "version": "18.3.1",+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz",+ "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==",+ "license": "MIT"+ },+ "node_modules/react-js-cron": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/react-js-cron/-/react-js-cron-5.2.0.tgz",+ "integrity": "sha512-+Mxm3cS7qmIoAIz7NVY27jvsJKNZ4tx+H/nNtMUJW4DcKR7jUIL1GP0jOD79K5j86Dq8jvShKJMh30+c8bmVtA==",+ "license": "MIT",+ "peerDependencies": {+ "antd": ">=5.8.0",+ "react": ">=17.0.0",+ "react-dom": ">=17.0.0"+ }+ },+ "node_modules/react-layout-kit": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/react-layout-kit/-/react-layout-kit-2.0.1.tgz",+ "integrity": "sha512-MdzEviHXwCfDuUcYWiRUzbxUujW0Ft0XMrwvNbKxdxNY7Vgr9StT2CjT8ElPWSJMSkSSoXHhSyJflacKlFb6NA==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.28.2",+ "@emotion/css": "^11.13.5",+ "fast-deep-equal": "^3.1.3"+ },+ "peerDependencies": {+ "react": ">=19"+ }+ },+ "node_modules/react-markdown": {+ "version": "10.1.0",+ "resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz",+ "integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "devlop": "^1.0.0",+ "hast-util-to-jsx-runtime": "^2.0.0",+ "html-url-attributes": "^3.0.0",+ "mdast-util-to-hast": "^13.0.0",+ "remark-parse": "^11.0.0",+ "remark-rehype": "^11.0.0",+ "unified": "^11.0.0",+ "unist-util-visit": "^5.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ },+ "peerDependencies": {+ "@types/react": ">=18",+ "react": ">=18"+ }+ },+ "node_modules/react-merge-refs": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/react-merge-refs/-/react-merge-refs-3.0.2.tgz",+ "integrity": "sha512-MSZAfwFfdbEvwkKWP5EI5chuLYnNUxNS7vyS0i1Jp+wtd8J4Ga2ddzhaE68aMol2Z4vCnRM/oGOo1a3V75UPlw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/gregberge"+ },+ "peerDependencies": {+ "react": ">=16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ },+ "peerDependenciesMeta": {+ "react": {+ "optional": true+ }+ }+ },+ "node_modules/react-refresh": {+ "version": "0.18.0",+ "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.18.0.tgz",+ "integrity": "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/react-remove-scroll": {+ "version": "2.7.2",+ "resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.7.2.tgz",+ "integrity": "sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q==",+ "license": "MIT",+ "dependencies": {+ "react-remove-scroll-bar": "^2.3.7",+ "react-style-singleton": "^2.2.3",+ "tslib": "^2.1.0",+ "use-callback-ref": "^1.3.3",+ "use-sidecar": "^1.1.3"+ },+ "engines": {+ "node": ">=10"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/react-remove-scroll-bar": {+ "version": "2.3.8",+ "resolved": "https://registry.npmjs.org/react-remove-scroll-bar/-/react-remove-scroll-bar-2.3.8.tgz",+ "integrity": "sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q==",+ "license": "MIT",+ "dependencies": {+ "react-style-singleton": "^2.2.2",+ "tslib": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/react-rnd": {+ "version": "10.5.2",+ "resolved": "https://registry.npmjs.org/react-rnd/-/react-rnd-10.5.2.tgz",+ "integrity": "sha512-0Tm4x7k7pfHf2snewJA8x7Nwgt3LV+58MVEWOVsFjk51eYruFEa6Wy7BNdxt4/lH0wIRsu7Gm3KjSXY2w7YaNw==",+ "license": "MIT",+ "dependencies": {+ "re-resizable": "6.11.2",+ "react-draggable": "4.4.6",+ "tslib": "2.6.2"+ },+ "peerDependencies": {+ "react": ">=16.3.0",+ "react-dom": ">=16.3.0"+ }+ },+ "node_modules/react-rnd/node_modules/tslib": {+ "version": "2.6.2",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz",+ "integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==",+ "license": "0BSD"+ },+ "node_modules/react-simple-code-editor": {+ "version": "0.14.1",+ "resolved": "https://registry.npmjs.org/react-simple-code-editor/-/react-simple-code-editor-0.14.1.tgz",+ "integrity": "sha512-BR5DtNRy+AswWJECyA17qhUDvrrCZ6zXOCfkQY5zSmb96BVUbpVAv03WpcjcwtCwiLbIANx3gebHOcXYn1EHow==",+ "license": "MIT",+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },+ "node_modules/react-style-singleton": {+ "version": "2.2.3",+ "resolved": "https://registry.npmjs.org/react-style-singleton/-/react-style-singleton-2.2.3.tgz",+ "integrity": "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ==",+ "license": "MIT",+ "dependencies": {+ "get-nonce": "^1.0.0",+ "tslib": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/react-universal-interface": {+ "version": "0.6.2",+ "resolved": "https://registry.npmjs.org/react-universal-interface/-/react-universal-interface-0.6.2.tgz",+ "integrity": "sha512-dg8yXdcQmvgR13RIlZbTRQOoUrDciFVoSBZILwjE2LFISxZZ8loVJKAkuzswl5js8BHda79bIb2b84ehU8IjXw==",+ "peerDependencies": {+ "react": "*",+ "tslib": "*"+ }+ },+ "node_modules/react-use": {+ "version": "17.6.0",+ "resolved": "https://registry.npmjs.org/react-use/-/react-use-17.6.0.tgz",+ "integrity": "sha512-OmedEScUMKFfzn1Ir8dBxiLLSOzhKe/dPZwVxcujweSj45aNM7BEGPb9BEVIgVEqEXx6f3/TsXzwIktNgUR02g==",+ "license": "Unlicense",+ "dependencies": {+ "@types/js-cookie": "^2.2.6",+ "@xobotyi/scrollbar-width": "^1.9.5",+ "copy-to-clipboard": "^3.3.1",+ "fast-deep-equal": "^3.1.3",+ "fast-shallow-equal": "^1.0.0",+ "js-cookie": "^2.2.1",+ "nano-css": "^5.6.2",+ "react-universal-interface": "^0.6.2",+ "resize-observer-polyfill": "^1.5.1",+ "screenfull": "^5.1.0",+ "set-harmonic-interval": "^1.0.1",+ "throttle-debounce": "^3.0.1",+ "ts-easing": "^0.2.0",+ "tslib": "^2.1.0"+ },+ "peerDependencies": {+ "react": "*",+ "react-dom": "*"+ }+ },+ "node_modules/react-use/node_modules/throttle-debounce": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/throttle-debounce/-/throttle-debounce-3.0.1.tgz",+ "integrity": "sha512-dTEWWNu6JmeVXY0ZYoPuH5cRIwc0MeGbJwah9KUNYSJwommQpCzTySTpEe8Gs1J23aeWEuAobe4Ag7EHVt/LOg==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/react-zoom-pan-pinch": {+ "version": "3.7.0",+ "resolved": "https://registry.npmjs.org/react-zoom-pan-pinch/-/react-zoom-pan-pinch-3.7.0.tgz",+ "integrity": "sha512-UmReVZ0TxlKzxSbYiAj+LeGRW8s8LraAFTXRAxzMYnNRgGPsxCudwZKVkjvGmjtx7SW/hZamt69NUmGf4xrkXA==",+ "license": "MIT",+ "engines": {+ "node": ">=8",+ "npm": ">=5"+ },+ "peerDependencies": {+ "react": "*",+ "react-dom": "*"+ }+ },+ "node_modules/reactflow": {+ "version": "11.11.4",+ "resolved": "https://registry.npmjs.org/reactflow/-/reactflow-11.11.4.tgz",+ "integrity": "sha512-70FOtJkUWH3BAOsN+LU9lCrKoKbtOPnz2uq0CV2PLdNSwxTXOhCbsZr50GmZ+Rtw3jx8Uv7/vBFtCGixLfd4Og==",+ "license": "MIT",+ "dependencies": {+ "@reactflow/background": "11.3.14",+ "@reactflow/controls": "11.2.14",+ "@reactflow/core": "11.11.4",+ "@reactflow/minimap": "11.7.14",+ "@reactflow/node-resizer": "2.2.14",+ "@reactflow/node-toolbar": "1.3.14"+ },+ "peerDependencies": {+ "react": ">=17",+ "react-dom": ">=17"+ }+ },+ "node_modules/recma-build-jsx": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/recma-build-jsx/-/recma-build-jsx-1.0.0.tgz",+ "integrity": "sha512-8GtdyqaBcDfva+GUKDr3nev3VpKAhup1+RvkMvUxURHpW7QyIvk9F5wz7Vzo06CEMSilw6uArgRqhpiUcWp8ew==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "estree-util-build-jsx": "^3.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/recma-jsx": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/recma-jsx/-/recma-jsx-1.0.1.tgz",+ "integrity": "sha512-huSIy7VU2Z5OLv6oFLosQGGDqPqdO1iq6bWNAdhzMxSJP7RAso4fCZ1cKu8j9YHCZf3TPrq4dw3okhrylgcd7w==",+ "license": "MIT",+ "dependencies": {+ "acorn-jsx": "^5.0.0",+ "estree-util-to-js": "^2.0.0",+ "recma-parse": "^1.0.0",+ "recma-stringify": "^1.0.0",+ "unified": "^11.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ },+ "peerDependencies": {+ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"+ }+ },+ "node_modules/recma-parse": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/recma-parse/-/recma-parse-1.0.0.tgz",+ "integrity": "sha512-OYLsIGBB5Y5wjnSnQW6t3Xg7q3fQ7FWbw/vcXtORTnyaSFscOtABg+7Pnz6YZ6c27fG1/aN8CjfwoUEUIdwqWQ==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "esast-util-from-js": "^2.0.0",+ "unified": "^11.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/recma-stringify": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/recma-stringify/-/recma-stringify-1.0.0.tgz",+ "integrity": "sha512-cjwII1MdIIVloKvC9ErQ+OgAtwHBmcZ0Bg4ciz78FtbT8In39aAYbaA7zvxQ61xVMSPE8WxhLwLbhif4Js2C+g==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "estree-util-to-js": "^2.0.0",+ "unified": "^11.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/regex": {+ "version": "6.1.0",+ "resolved": "https://registry.npmjs.org/regex/-/regex-6.1.0.tgz",+ "integrity": "sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg==",+ "license": "MIT",+ "dependencies": {+ "regex-utilities": "^2.3.0"+ }+ },+ "node_modules/regex-recursion": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/regex-recursion/-/regex-recursion-6.0.2.tgz",+ "integrity": "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==",+ "license": "MIT",+ "dependencies": {+ "regex-utilities": "^2.3.0"+ }+ },+ "node_modules/regex-utilities": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/regex-utilities/-/regex-utilities-2.3.0.tgz",+ "integrity": "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==",+ "license": "MIT"+ },+ "node_modules/rehype-github-alerts": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/rehype-github-alerts/-/rehype-github-alerts-4.2.0.tgz",+ "integrity": "sha512-6di6kEu9WUHKLKrkKG2xX6AOuaCMGghg0Wq7MEuM/jBYUPVIq6PJpMe00dxMfU+/YSBtDXhffpDimgDi+BObIQ==",+ "license": "MIT",+ "dependencies": {+ "@primer/octicons": "^19.20.0",+ "hast-util-from-html": "^2.0.3",+ "hast-util-is-element": "^3.0.0",+ "unist-util-visit": "^5.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/chrisweb"+ }+ },+ "node_modules/rehype-katex": {+ "version": "7.0.1",+ "resolved": "https://registry.npmjs.org/rehype-katex/-/rehype-katex-7.0.1.tgz",+ "integrity": "sha512-OiM2wrZ/wuhKkigASodFoo8wimG3H12LWQaH8qSPVJn9apWKFSH3YOCtbKpBorTVw/eI7cuT21XBbvwEswbIOA==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@types/katex": "^0.16.0",+ "hast-util-from-html-isomorphic": "^2.0.0",+ "hast-util-to-text": "^4.0.0",+ "katex": "^0.16.0",+ "unist-util-visit-parents": "^6.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/rehype-raw": {+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/rehype-raw/-/rehype-raw-7.0.0.tgz",+ "integrity": "sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "hast-util-raw": "^9.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/rehype-recma": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/rehype-recma/-/rehype-recma-1.0.0.tgz",+ "integrity": "sha512-lqA4rGUf1JmacCNWWZx0Wv1dHqMwxzsDWYMTowuplHF3xH0N/MmrZ/G3BDZnzAkRmxDadujCjaKM2hqYdCBOGw==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "@types/hast": "^3.0.0",+ "hast-util-to-estree": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remark-breaks": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/remark-breaks/-/remark-breaks-4.0.0.tgz",+ "integrity": "sha512-IjEjJOkH4FuJvHZVIW0QCDWxcG96kCq7An/KVH2NfJe6rKZU2AsHeB3OEjPNRxi4QC34Xdx7I2KGYn6IpT7gxQ==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-newline-to-break": "^2.0.0",+ "unified": "^11.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remark-cjk-friendly": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/remark-cjk-friendly/-/remark-cjk-friendly-1.2.3.tgz",+ "integrity": "sha512-UvAgxwlNk+l9Oqgl/9MWK2eWRS7zgBW/nXX9AthV7nd/3lNejF138E7Xbmk9Zs4WjTJGs721r7fAEc7tNFoH7g==",+ "license": "MIT",+ "dependencies": {+ "micromark-extension-cjk-friendly": "1.2.3"+ },+ "engines": {+ "node": ">=16"+ },+ "peerDependencies": {+ "@types/mdast": "^4.0.0",+ "unified": "^11.0.0"+ },+ "peerDependenciesMeta": {+ "@types/mdast": {+ "optional": true+ }+ }+ },+ "node_modules/remark-gfm": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/remark-gfm/-/remark-gfm-4.0.1.tgz",+ "integrity": "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-gfm": "^3.0.0",+ "micromark-extension-gfm": "^3.0.0",+ "remark-parse": "^11.0.0",+ "remark-stringify": "^11.0.0",+ "unified": "^11.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remark-github": {+ "version": "12.0.0",+ "resolved": "https://registry.npmjs.org/remark-github/-/remark-github-12.0.0.tgz",+ "integrity": "sha512-ByefQKFN184LeiGRCabfl7zUJsdlMYWEhiLX1gpmQ11yFg6xSuOTW7LVCv0oc1x+YvUMJW23NU36sJX2RWGgvg==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-find-and-replace": "^3.0.0",+ "mdast-util-to-string": "^4.0.0",+ "to-vfile": "^8.0.0",+ "unist-util-visit": "^5.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remark-math": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/remark-math/-/remark-math-6.0.0.tgz",+ "integrity": "sha512-MMqgnP74Igy+S3WwnhQ7kqGlEerTETXMvJhrUzDikVZ2/uogJCb+WHUg97hK9/jcfc0dkD73s3LN8zU49cTEtA==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-math": "^3.0.0",+ "micromark-extension-math": "^3.0.0",+ "unified": "^11.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remark-mdx": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/remark-mdx/-/remark-mdx-3.1.1.tgz",+ "integrity": "sha512-Pjj2IYlUY3+D8x00UJsIOg5BEvfMyeI+2uLPn9VO9Wg4MEtN/VTIq2NEJQfde9PnX15KgtHyl9S0BcTnWrIuWg==",+ "license": "MIT",+ "dependencies": {+ "mdast-util-mdx": "^3.0.0",+ "micromark-extension-mdxjs": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remark-parse": {+ "version": "11.0.0",+ "resolved": "https://registry.npmjs.org/remark-parse/-/remark-parse-11.0.0.tgz",+ "integrity": "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "micromark-util-types": "^2.0.0",+ "unified": "^11.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remark-rehype": {+ "version": "11.1.2",+ "resolved": "https://registry.npmjs.org/remark-rehype/-/remark-rehype-11.1.2.tgz",+ "integrity": "sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "mdast-util-to-hast": "^13.0.0",+ "unified": "^11.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remark-stringify": {+ "version": "11.0.0",+ "resolved": "https://registry.npmjs.org/remark-stringify/-/remark-stringify-11.0.0.tgz",+ "integrity": "sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-to-markdown": "^2.0.0",+ "unified": "^11.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/require-directory": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",+ "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/resize-observer-polyfill": {+ "version": "1.5.1",+ "resolved": "https://registry.npmjs.org/resize-observer-polyfill/-/resize-observer-polyfill-1.5.1.tgz",+ "integrity": "sha512-LwZrotdHOo12nQuZlHEmtuXdqGoOD0OhaxopaNFxWzInpEgaLWoVuAMbTzixuosCx2nEG58ngzW3vxdWoxIgdg==",+ "license": "MIT"+ },+ "node_modules/resolve": {+ "version": "1.22.11",+ "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz",+ "integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==",+ "license": "MIT",+ "dependencies": {+ "is-core-module": "^2.16.1",+ "path-parse": "^1.0.7",+ "supports-preserve-symlinks-flag": "^1.0.0"+ },+ "bin": {+ "resolve": "bin/resolve"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/resolve-from": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",+ "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==",+ "license": "MIT",+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/retry": {+ "version": "0.13.1",+ "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz",+ "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==",+ "license": "MIT",+ "peer": true,+ "engines": {+ "node": ">= 4"+ }+ },+ "node_modules/robust-predicates": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.2.tgz",+ "integrity": "sha512-IXgzBWvWQwE6PrDI05OvmXUIruQTcoMDzRsOd5CDvHCVLcLHMTSYvOK5Cm46kWqlV3yAbuSpBZdJ5oP5OUoStg==",+ "license": "Unlicense"+ },+ "node_modules/rollup": {+ "version": "4.53.3",+ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.53.3.tgz",+ "integrity": "sha512-w8GmOxZfBmKknvdXU1sdM9NHcoQejwF/4mNgj2JuEEdRaHwwF12K7e9eXn1nLZ07ad+du76mkVsyeb2rKGllsA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/estree": "1.0.8"+ },+ "bin": {+ "rollup": "dist/bin/rollup"+ },+ "engines": {+ "node": ">=18.0.0",+ "npm": ">=8.0.0"+ },+ "optionalDependencies": {+ "@rollup/rollup-android-arm-eabi": "4.53.3",+ "@rollup/rollup-android-arm64": "4.53.3",+ "@rollup/rollup-darwin-arm64": "4.53.3",+ "@rollup/rollup-darwin-x64": "4.53.3",+ "@rollup/rollup-freebsd-arm64": "4.53.3",+ "@rollup/rollup-freebsd-x64": "4.53.3",+ "@rollup/rollup-linux-arm-gnueabihf": "4.53.3",+ "@rollup/rollup-linux-arm-musleabihf": "4.53.3",+ "@rollup/rollup-linux-arm64-gnu": "4.53.3",+ "@rollup/rollup-linux-arm64-musl": "4.53.3",+ "@rollup/rollup-linux-loong64-gnu": "4.53.3",+ "@rollup/rollup-linux-ppc64-gnu": "4.53.3",+ "@rollup/rollup-linux-riscv64-gnu": "4.53.3",+ "@rollup/rollup-linux-riscv64-musl": "4.53.3",+ "@rollup/rollup-linux-s390x-gnu": "4.53.3",+ "@rollup/rollup-linux-x64-gnu": "4.53.3",+ "@rollup/rollup-linux-x64-musl": "4.53.3",+ "@rollup/rollup-openharmony-arm64": "4.53.3",+ "@rollup/rollup-win32-arm64-msvc": "4.53.3",+ "@rollup/rollup-win32-ia32-msvc": "4.53.3",+ "@rollup/rollup-win32-x64-gnu": "4.53.3",+ "@rollup/rollup-win32-x64-msvc": "4.53.3",+ "fsevents": "~2.3.2"+ }+ },+ "node_modules/roughjs": {+ "version": "4.6.6",+ "resolved": "https://registry.npmjs.org/roughjs/-/roughjs-4.6.6.tgz",+ "integrity": "sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ==",+ "license": "MIT",+ "dependencies": {+ "hachure-fill": "^0.5.2",+ "path-data-parser": "^0.1.0",+ "points-on-curve": "^0.2.0",+ "points-on-path": "^0.2.1"+ }+ },+ "node_modules/rtl-css-js": {+ "version": "1.16.1",+ "resolved": "https://registry.npmjs.org/rtl-css-js/-/rtl-css-js-1.16.1.tgz",+ "integrity": "sha512-lRQgou1mu19e+Ya0LsTvKrVJ5TYUbqCVPAiImX3UfLTenarvPUl1QFdvu5Z3PYmHT9RCcwIfbjRQBntExyj3Zg==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.1.2"+ }+ },+ "node_modules/rw": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/rw/-/rw-1.3.3.tgz",+ "integrity": "sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==",+ "license": "BSD-3-Clause"+ },+ "node_modules/rxjs": {+ "version": "7.8.2",+ "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz",+ "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "tslib": "^2.1.0"+ }+ },+ "node_modules/safer-buffer": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",+ "license": "MIT"+ },+ "node_modules/scheduler": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",+ "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",+ "license": "MIT"+ },+ "node_modules/screenfull": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/screenfull/-/screenfull-5.2.0.tgz",+ "integrity": "sha512-9BakfsO2aUQN2K9Fdbj87RJIEZ82Q9IGim7FqM5OsebfoFC6ZHXgDq/KvniuLTPdeM8wY2o6Dj3WQ7KeQCj3cA==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/scroll-into-view-if-needed": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/scroll-into-view-if-needed/-/scroll-into-view-if-needed-3.1.0.tgz",+ "integrity": "sha512-49oNpRjWRvnU8NyGVmUaYG4jtTkNonFZI86MmGRDqBphEK2EXT9gdEUoQPZhuBM8yWHxCWbobltqYO5M4XrUvQ==",+ "license": "MIT",+ "dependencies": {+ "compute-scroll-into-view": "^3.0.2"+ }+ },+ "node_modules/semver": {+ "version": "6.3.1",+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ }+ },+ "node_modules/semver-compare": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz",+ "integrity": "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==",+ "license": "MIT"+ },+ "node_modules/set-harmonic-interval": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/set-harmonic-interval/-/set-harmonic-interval-1.0.1.tgz",+ "integrity": "sha512-AhICkFV84tBP1aWqPwLZqFvAwqEoVA9kxNMniGEUvzOlm4vLmOFLiTT3UZ6bziJTy4bOVpzWGTfSCbmaayGx8g==",+ "license": "Unlicense",+ "engines": {+ "node": ">=6.9"+ }+ },+ "node_modules/set-value": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.1.tgz",+ "integrity": "sha512-JxHc1weCN68wRY0fhCoXpyK55m/XPHafOmK4UWD7m2CI14GMcFypt4w/0+NV5f/ZMby2F6S2wwA7fgynh9gWSw==",+ "license": "MIT",+ "dependencies": {+ "extend-shallow": "^2.0.1",+ "is-extendable": "^0.1.1",+ "is-plain-object": "^2.0.3",+ "split-string": "^3.0.1"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/set-value/node_modules/is-extendable": {+ "version": "0.1.1",+ "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz",+ "integrity": "sha512-5BMULNob1vgFX6EjQw5izWDxrecWK9AM72rugNr0TFldMOi0fj6Jk+zeKIt0xGj4cEfQIJth4w3OKWOJ4f+AFw==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/shallowequal": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/shallowequal/-/shallowequal-1.1.0.tgz",+ "integrity": "sha512-y0m1JoUZSlPAjXVtPPW70aZWfIL/dSP7AFkRnniLCrK/8MDKog3TySTBmckD+RObVxH0v4Tox67+F14PdED2oQ==",+ "license": "MIT"+ },+ "node_modules/shebang-command": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "shebang-regex": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/shebang-regex": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/shell-quote": {+ "version": "1.8.3",+ "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz",+ "integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/shiki": {+ "version": "3.19.0",+ "resolved": "https://registry.npmjs.org/shiki/-/shiki-3.19.0.tgz",+ "integrity": "sha512-77VJr3OR/VUZzPiStyRhADmO2jApMM0V2b1qf0RpfWya8Zr1PeZev5AEpPGAAKWdiYUtcZGBE4F5QvJml1PvWA==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/core": "3.19.0",+ "@shikijs/engine-javascript": "3.19.0",+ "@shikijs/engine-oniguruma": "3.19.0",+ "@shikijs/langs": "3.19.0",+ "@shikijs/themes": "3.19.0",+ "@shikijs/types": "3.19.0",+ "@shikijs/vscode-textmate": "^10.0.2",+ "@types/hast": "^3.0.4"+ }+ },+ "node_modules/shiki-stream": {+ "version": "0.1.3",+ "resolved": "https://registry.npmjs.org/shiki-stream/-/shiki-stream-0.1.3.tgz",+ "integrity": "sha512-pDIqmaP/zJWHNV8bJKp0tD0CZ6OkF+lWTIvmNRLktlTjBjN3+durr19JarS657U1oSEf/WrSYmdzwr9CeD6m2Q==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/core": "^3.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/antfu"+ },+ "peerDependencies": {+ "react": "^19.0.0",+ "vue": "^3.2.0"+ },+ "peerDependenciesMeta": {+ "react": {+ "optional": true+ },+ "vue": {+ "optional": true+ }+ }+ },+ "node_modules/simple-wcswidth": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/simple-wcswidth/-/simple-wcswidth-1.1.2.tgz",+ "integrity": "sha512-j7piyCjAeTDSjzTSQ7DokZtMNwNlEAyxqSZeCS+CXH7fJ4jx3FuJ/mTW3mE+6JLs4VJBbcll0Kjn+KXI5t21Iw==",+ "license": "MIT",+ "peer": true+ },+ "node_modules/source-map": {+ "version": "0.6.1",+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",+ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/source-map-js": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/space-separated-tokens": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz",+ "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/split-on-first": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/split-on-first/-/split-on-first-3.0.0.tgz",+ "integrity": "sha512-qxQJTx2ryR0Dw0ITYyekNQWpz6f8dGd7vffGNflQQ3Iqj9NJ6qiZ7ELpZsJ/QBhIVAiDfXdag3+Gp8RvWa62AA==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/split-string": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/split-string/-/split-string-3.1.0.tgz",+ "integrity": "sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw==",+ "license": "MIT",+ "dependencies": {+ "extend-shallow": "^3.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/split-string/node_modules/extend-shallow": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-3.0.2.tgz",+ "integrity": "sha512-BwY5b5Ql4+qZoefgMj2NUmx+tehVTH/Kf4k1ZEtOHNFcm2wSxMRo992l6X3TIgni2eZVTZ85xMOjF31fwZAj6Q==",+ "license": "MIT",+ "dependencies": {+ "assign-symbols": "^1.0.0",+ "is-extendable": "^1.0.1"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/stack-generator": {+ "version": "2.0.10",+ "resolved": "https://registry.npmjs.org/stack-generator/-/stack-generator-2.0.10.tgz",+ "integrity": "sha512-mwnua/hkqM6pF4k8SnmZ2zfETsRUpWXREfA/goT8SLCV4iOFa4bzOX2nDipWAZFPTjLvQB82f5yaodMVhK0yJQ==",+ "license": "MIT",+ "dependencies": {+ "stackframe": "^1.3.4"+ }+ },+ "node_modules/stackframe": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/stackframe/-/stackframe-1.3.4.tgz",+ "integrity": "sha512-oeVtt7eWQS+Na6F//S4kJ2K2VbRlS9D43mAlMyVpVWovy9o+jfgH8O9agzANzaiLjclA0oYzUXEM4PurhSUChw==",+ "license": "MIT"+ },+ "node_modules/stacktrace-gps": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/stacktrace-gps/-/stacktrace-gps-3.1.2.tgz",+ "integrity": "sha512-GcUgbO4Jsqqg6RxfyTHFiPxdPqF+3LFmQhm7MgCuYQOYuWyqxo5pwRPz5d/u6/WYJdEnWfK4r+jGbyD8TSggXQ==",+ "license": "MIT",+ "dependencies": {+ "source-map": "0.5.6",+ "stackframe": "^1.3.4"+ }+ },+ "node_modules/stacktrace-gps/node_modules/source-map": {+ "version": "0.5.6",+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.6.tgz",+ "integrity": "sha512-MjZkVp0NHr5+TPihLcadqnlVoGIoWo4IBHptutGh9wI3ttUYvCG26HkSuDi+K6lsZ25syXJXcctwgyVCt//xqA==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/stacktrace-js": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/stacktrace-js/-/stacktrace-js-2.0.2.tgz",+ "integrity": "sha512-Je5vBeY4S1r/RnLydLl0TBTi3F2qdfWmYsGvtfZgEI+SCprPppaIhQf5nGcal4gI4cGpCV/duLcAzT1np6sQqg==",+ "license": "MIT",+ "dependencies": {+ "error-stack-parser": "^2.0.6",+ "stack-generator": "^2.0.5",+ "stacktrace-gps": "^3.0.4"+ }+ },+ "node_modules/string-convert": {+ "version": "0.2.1",+ "resolved": "https://registry.npmjs.org/string-convert/-/string-convert-0.2.1.tgz",+ "integrity": "sha512-u/1tdPl4yQnPBjnVrmdLo9gtuLvELKsAoRapekWggdiQNvvvum+jYF329d84NAa660KQw7pB2n36KrIKVoXa3A==",+ "license": "MIT"+ },+ "node_modules/string-width": {+ "version": "4.2.3",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^8.0.0",+ "is-fullwidth-code-point": "^3.0.0",+ "strip-ansi": "^6.0.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/stringify-entities": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz",+ "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==",+ "license": "MIT",+ "dependencies": {+ "character-entities-html4": "^2.0.0",+ "character-entities-legacy": "^3.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/strip-ansi": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ansi-regex": "^5.0.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/strip-json-comments": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",+ "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/strnum": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/strnum/-/strnum-1.1.2.tgz",+ "integrity": "sha512-vrN+B7DBIoTTZjnPNewwhx6cBA/H+IS7rfW68n7XxC1y7uoiGQBxaKzqucGUgavX15dJgiGztLJ8vxuEzwqBdA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/NaturalIntelligence"+ }+ ],+ "license": "MIT"+ },+ "node_modules/style-to-js": {+ "version": "1.1.21",+ "resolved": "https://registry.npmjs.org/style-to-js/-/style-to-js-1.1.21.tgz",+ "integrity": "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ==",+ "license": "MIT",+ "dependencies": {+ "style-to-object": "1.0.14"+ }+ },+ "node_modules/style-to-object": {+ "version": "1.0.14",+ "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-1.0.14.tgz",+ "integrity": "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==",+ "license": "MIT",+ "dependencies": {+ "inline-style-parser": "0.2.7"+ }+ },+ "node_modules/styled-components": {+ "version": "6.1.19",+ "resolved": "https://registry.npmjs.org/styled-components/-/styled-components-6.1.19.tgz",+ "integrity": "sha512-1v/e3Dl1BknC37cXMhwGomhO8AkYmN41CqyX9xhUDxry1ns3BFQy2lLDRQXJRdVVWB9OHemv/53xaStimvWyuA==",+ "license": "MIT",+ "dependencies": {+ "@emotion/is-prop-valid": "1.2.2",+ "@emotion/unitless": "0.8.1",+ "@types/stylis": "4.2.5",+ "css-to-react-native": "3.2.0",+ "csstype": "3.1.3",+ "postcss": "8.4.49",+ "shallowequal": "1.1.0",+ "stylis": "4.3.2",+ "tslib": "2.6.2"+ },+ "engines": {+ "node": ">= 16"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/styled-components"+ },+ "peerDependencies": {+ "react": ">= 16.8.0",+ "react-dom": ">= 16.8.0"+ }+ },+ "node_modules/styled-components/node_modules/@emotion/unitless": {+ "version": "0.8.1",+ "resolved": "https://registry.npmjs.org/@emotion/unitless/-/unitless-0.8.1.tgz",+ "integrity": "sha512-KOEGMu6dmJZtpadb476IsZBclKvILjopjUii3V+7MnXIQCYh8W3NgNcgwo21n9LXZX6EDIKvqfjYxXebDwxKmQ==",+ "license": "MIT"+ },+ "node_modules/styled-components/node_modules/csstype": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",+ "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==",+ "license": "MIT"+ },+ "node_modules/styled-components/node_modules/postcss": {+ "version": "8.4.49",+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.49.tgz",+ "integrity": "sha512-OCVPnIObs4N29kxTjzLfUryOkvZEq+pf8jTF0lg8E7uETuWHA+v7j3c/xJmiqpX450191LlmZfUKkXxkTry7nA==",+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/postcss"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "nanoid": "^3.3.7",+ "picocolors": "^1.1.1",+ "source-map-js": "^1.2.1"+ },+ "engines": {+ "node": "^10 || ^12 || >=14"+ }+ },+ "node_modules/styled-components/node_modules/stylis": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/stylis/-/stylis-4.3.2.tgz",+ "integrity": "sha512-bhtUjWd/z6ltJiQwg0dUfxEJ+W+jdqQd8TbWLWyeIJHlnsqmGLRFFd8e5mA0AZi/zx90smXRlN66YMTcaSFifg==",+ "license": "MIT"+ },+ "node_modules/styled-components/node_modules/tslib": {+ "version": "2.6.2",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz",+ "integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==",+ "license": "0BSD"+ },+ "node_modules/stylis": {+ "version": "4.3.6",+ "resolved": "https://registry.npmjs.org/stylis/-/stylis-4.3.6.tgz",+ "integrity": "sha512-yQ3rwFWRfwNUY7H5vpU0wfdkNSnvnJinhF9830Swlaxl03zsOjCfmX0ugac+3LtK0lYSgwL/KXc8oYL3mG4YFQ==",+ "license": "MIT"+ },+ "node_modules/supports-color": {+ "version": "8.1.1",+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",+ "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "has-flag": "^4.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/chalk/supports-color?sponsor=1"+ }+ },+ "node_modules/supports-preserve-symlinks-flag": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",+ "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/swr": {+ "version": "2.3.7",+ "resolved": "https://registry.npmjs.org/swr/-/swr-2.3.7.tgz",+ "integrity": "sha512-ZEquQ82QvalqTxhBVv/DlAg2mbmUjF4UgpPg9wwk4ufb9rQnZXh1iKyyKBqV6bQGu1Ie7L1QwSYO07qFIa1p+g==",+ "license": "MIT",+ "dependencies": {+ "dequal": "^2.0.3",+ "use-sync-external-store": "^1.4.0"+ },+ "peerDependencies": {+ "react": "^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },+ "node_modules/tabbable": {+ "version": "6.3.0",+ "resolved": "https://registry.npmjs.org/tabbable/-/tabbable-6.3.0.tgz",+ "integrity": "sha512-EIHvdY5bPLuWForiR/AN2Bxngzpuwn1is4asboytXtpTgsArc+WmSJKVLlhdh71u7jFcryDqB2A8lQvj78MkyQ==",+ "license": "MIT"+ },+ "node_modules/tailwindcss": {+ "version": "4.1.17",+ "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.1.17.tgz",+ "integrity": "sha512-j9Ee2YjuQqYT9bbRTfTZht9W/ytp5H+jJpZKiYdP/bpnXARAuELt9ofP0lPnmHjbga7SNQIxdTAXCmtKVYjN+Q==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/throttle-debounce": {+ "version": "5.0.2",+ "resolved": "https://registry.npmjs.org/throttle-debounce/-/throttle-debounce-5.0.2.tgz",+ "integrity": "sha512-B71/4oyj61iNH0KeCamLuE2rmKuTO5byTOSVwECM5FA7TiAiAW+UqTKZ9ERueC4qvgSttUhdmq1mXC3kJqGX7A==",+ "license": "MIT",+ "engines": {+ "node": ">=12.22"+ }+ },+ "node_modules/tinyexec": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.2.tgz",+ "integrity": "sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tinyglobby": {+ "version": "0.2.15",+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",+ "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "fdir": "^6.5.0",+ "picomatch": "^4.0.3"+ },+ "engines": {+ "node": ">=12.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/SuperchupuDev"+ }+ },+ "node_modules/to-vfile": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/to-vfile/-/to-vfile-8.0.0.tgz",+ "integrity": "sha512-IcmH1xB5576MJc9qcfEC/m/nQCFt3fzMHz45sSlgJyTWjRbKW1HAkJpuf3DgE57YzIlZcwcBZA5ENQbBo4aLkg==",+ "license": "MIT",+ "dependencies": {+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/toggle-selection": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/toggle-selection/-/toggle-selection-1.0.6.tgz",+ "integrity": "sha512-BiZS+C1OS8g/q2RRbJmy59xpyghNBqrr6k5L/uKBGRsTfxmu3ffiRnd8mlGPUVayg8pvfi5urfnu8TU7DVOkLQ==",+ "license": "MIT"+ },+ "node_modules/tree-kill": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz",+ "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==",+ "dev": true,+ "license": "MIT",+ "bin": {+ "tree-kill": "cli.js"+ }+ },+ "node_modules/trim-lines": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz",+ "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/trough": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/trough/-/trough-2.2.0.tgz",+ "integrity": "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/ts-algebra": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",+ "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==",+ "license": "MIT"+ },+ "node_modules/ts-dedent": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/ts-dedent/-/ts-dedent-2.2.0.tgz",+ "integrity": "sha512-q5W7tVM71e2xjHZTlgfTDoPF/SmqKG5hddq9SzR49CH2hayqRKJtQ4mtRlSxKaJlR/+9rEM+mnBHf7I2/BQcpQ==",+ "license": "MIT",+ "engines": {+ "node": ">=6.10"+ }+ },+ "node_modules/ts-easing": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/ts-easing/-/ts-easing-0.2.0.tgz",+ "integrity": "sha512-Z86EW+fFFh/IFB1fqQ3/+7Zpf9t2ebOAxNI/V6Wo7r5gqiqtxmgTlQ1qbqQcjLKYeSHPTsEmvlJUDg/EuL0uHQ==",+ "license": "Unlicense"+ },+ "node_modules/ts-md5": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/ts-md5/-/ts-md5-2.0.1.tgz",+ "integrity": "sha512-yF35FCoEOFBzOclSkMNEUbFQZuv89KEQ+5Xz03HrMSGUGB1+r+El+JiGOFwsP4p9RFNzwlrydYoTLvPOuICl9w==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tslib": {+ "version": "2.8.1",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",+ "license": "0BSD"+ },+ "node_modules/type-check": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",+ "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "prelude-ls": "^1.2.1"+ },+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/typescript": {+ "version": "5.9.3",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/ufo": {+ "version": "1.6.1",+ "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.1.tgz",+ "integrity": "sha512-9a4/uxlTWJ4+a5i0ooc1rU7C7YOw3wT+UGqdeNNHWnOF9qcMBgLRS+4IYUqbczewFx4mLEig6gawh7X6mFlEkA==",+ "license": "MIT"+ },+ "node_modules/undici-types": {+ "version": "7.16.0",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz",+ "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/unified": {+ "version": "11.0.5",+ "resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz",+ "integrity": "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "bail": "^2.0.0",+ "devlop": "^1.0.0",+ "extend": "^3.0.0",+ "is-plain-obj": "^4.0.0",+ "trough": "^2.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-find-after": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/unist-util-find-after/-/unist-util-find-after-5.0.0.tgz",+ "integrity": "sha512-amQa0Ep2m6hE2g72AugUItjbuM8X8cGQnFoHk0pGfrFeT9GZhzN5SW8nRsiGKK7Aif4CrACPENkA6P/Lw6fHGQ==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "unist-util-is": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-is": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz",+ "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-position": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz",+ "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-position-from-estree": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/unist-util-position-from-estree/-/unist-util-position-from-estree-2.0.0.tgz",+ "integrity": "sha512-KaFVRjoqLyF6YXCbVLNad/eS4+OfPQQn2yOd7zF/h5T/CSL2v8NpN6a5TPvtbXthAGw5nG+PuTtq+DdIZr+cRQ==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-remove-position": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/unist-util-remove-position/-/unist-util-remove-position-5.0.0.tgz",+ "integrity": "sha512-Hp5Kh3wLxv0PHj9m2yZhhLt58KzPtEYKQQ4yxfYFEO7EvHwzyDYnduhHnY1mDxoqr7VUwVuHXk9RXKIiYS1N8Q==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "unist-util-visit": "^5.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-stringify-position": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz",+ "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-visit": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.0.0.tgz",+ "integrity": "sha512-MR04uvD+07cwl/yhVuVWAtw+3GOR/knlL55Nd/wAdblk27GCVt3lqpTivy/tkJcZoNPzTwS1Y+KMojlLDhoTzg==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "unist-util-is": "^6.0.0",+ "unist-util-visit-parents": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-visit-parents": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz",+ "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "unist-util-is": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/update-browserslist-db": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.0.tgz",+ "integrity": "sha512-Dn+NlSF/7+0lVSEZ57SYQg6/E44arLzsVOGgrElBn/BlG1B8WKdbLppOocFrXwRNTkNlgdGNaBgH1o0lggDPiw==",+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/browserslist"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/browserslist"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "escalade": "^3.2.0",+ "picocolors": "^1.1.1"+ },+ "bin": {+ "update-browserslist-db": "cli.js"+ },+ "peerDependencies": {+ "browserslist": ">= 4.21.0"+ }+ },+ "node_modules/uri-js": {+ "version": "4.4.1",+ "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",+ "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",+ "dev": true,+ "license": "BSD-2-Clause",+ "dependencies": {+ "punycode": "^2.1.0"+ }+ },+ "node_modules/url-join": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/url-join/-/url-join-5.0.0.tgz",+ "integrity": "sha512-n2huDr9h9yzd6exQVnH/jU5mr+Pfx08LRXXZhkLLetAMESRj+anQsTAh940iMrIetKAmry9coFuZQ2jY8/p3WA==",+ "license": "MIT",+ "engines": {+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"+ }+ },+ "node_modules/use-callback-ref": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/use-callback-ref/-/use-callback-ref-1.3.3.tgz",+ "integrity": "sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg==",+ "license": "MIT",+ "dependencies": {+ "tslib": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/use-merge-value": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/use-merge-value/-/use-merge-value-1.2.0.tgz",+ "integrity": "sha512-DXgG0kkgJN45TcyoXL49vJnn55LehnrmoHc7MbKi+QDBvr8dsesqws8UlyIWGHMR+JXgxc1nvY+jDGMlycsUcw==",+ "license": "MIT",+ "peerDependencies": {+ "react": ">= 16.x"+ }+ },+ "node_modules/use-sidecar": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/use-sidecar/-/use-sidecar-1.1.3.tgz",+ "integrity": "sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ==",+ "license": "MIT",+ "dependencies": {+ "detect-node-es": "^1.1.0",+ "tslib": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/use-sync-external-store": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",+ "integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==",+ "license": "MIT",+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },+ "node_modules/uuid": {+ "version": "10.0.0",+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz",+ "integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==",+ "funding": [+ "https://github.com/sponsors/broofa",+ "https://github.com/sponsors/ctavan"+ ],+ "license": "MIT",+ "peer": true,+ "bin": {+ "uuid": "dist/bin/uuid"+ }+ },+ "node_modules/v8n": {+ "version": "1.5.1",+ "resolved": "https://registry.npmjs.org/v8n/-/v8n-1.5.1.tgz",+ "integrity": "sha512-LdabyT4OffkyXFCe9UT+uMkxNBs5rcTVuZClvxQr08D5TUgo1OFKkoT65qYRCsiKBl/usHjpXvP4hHMzzDRj3A==",+ "license": "MIT"+ },+ "node_modules/vfile": {+ "version": "6.0.3",+ "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz",+ "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "vfile-message": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/vfile-location": {+ "version": "5.0.3",+ "resolved": "https://registry.npmjs.org/vfile-location/-/vfile-location-5.0.3.tgz",+ "integrity": "sha512-5yXvWDEgqeiYiBe1lbxYF7UMAIm/IcopxMHrMQDq3nvKcjPKIhZklUKL+AE7J7uApI4kwe2snsK+eI6UTj9EHg==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/vfile-message": {+ "version": "4.0.3",+ "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz",+ "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "unist-util-stringify-position": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/vite": {+ "version": "7.2.6",+ "resolved": "https://registry.npmjs.org/vite/-/vite-7.2.6.tgz",+ "integrity": "sha512-tI2l/nFHC5rLh7+5+o7QjKjSR04ivXDF4jcgV0f/bTQ+OJiITy5S6gaynVsEM+7RqzufMnVbIon6Sr5x1SDYaQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "esbuild": "^0.25.0",+ "fdir": "^6.5.0",+ "picomatch": "^4.0.3",+ "postcss": "^8.5.6",+ "rollup": "^4.43.0",+ "tinyglobby": "^0.2.15"+ },+ "bin": {+ "vite": "bin/vite.js"+ },+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ },+ "funding": {+ "url": "https://github.com/vitejs/vite?sponsor=1"+ },+ "optionalDependencies": {+ "fsevents": "~2.3.3"+ },+ "peerDependencies": {+ "@types/node": "^20.19.0 || >=22.12.0",+ "jiti": ">=1.21.0",+ "less": "^4.0.0",+ "lightningcss": "^1.21.0",+ "sass": "^1.70.0",+ "sass-embedded": "^1.70.0",+ "stylus": ">=0.54.8",+ "sugarss": "^5.0.0",+ "terser": "^5.16.0",+ "tsx": "^4.8.1",+ "yaml": "^2.4.2"+ },+ "peerDependenciesMeta": {+ "@types/node": {+ "optional": true+ },+ "jiti": {+ "optional": true+ },+ "less": {+ "optional": true+ },+ "lightningcss": {+ "optional": true+ },+ "sass": {+ "optional": true+ },+ "sass-embedded": {+ "optional": true+ },+ "stylus": {+ "optional": true+ },+ "sugarss": {+ "optional": true+ },+ "terser": {+ "optional": true+ },+ "tsx": {+ "optional": true+ },+ "yaml": {+ "optional": true+ }+ }+ },+ "node_modules/vscode-jsonrpc": {+ "version": "8.2.0",+ "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.2.0.tgz",+ "integrity": "sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==",+ "license": "MIT",+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/vscode-languageserver": {+ "version": "9.0.1",+ "resolved": "https://registry.npmjs.org/vscode-languageserver/-/vscode-languageserver-9.0.1.tgz",+ "integrity": "sha512-woByF3PDpkHFUreUa7Hos7+pUWdeWMXRd26+ZX2A8cFx6v/JPTtd4/uN0/jB6XQHYaOlHbio03NTHCqrgG5n7g==",+ "license": "MIT",+ "dependencies": {+ "vscode-languageserver-protocol": "3.17.5"+ },+ "bin": {+ "installServerIntoExtension": "bin/installServerIntoExtension"+ }+ },+ "node_modules/vscode-languageserver-protocol": {+ "version": "3.17.5",+ "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.5.tgz",+ "integrity": "sha512-mb1bvRJN8SVznADSGWM9u/b07H7Ecg0I3OgXDuLdn307rl/J3A9YD6/eYOssqhecL27hK1IPZAsaqh00i/Jljg==",+ "license": "MIT",+ "dependencies": {+ "vscode-jsonrpc": "8.2.0",+ "vscode-languageserver-types": "3.17.5"+ }+ },+ "node_modules/vscode-languageserver-textdocument": {+ "version": "1.0.12",+ "resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.12.tgz",+ "integrity": "sha512-cxWNPesCnQCcMPeenjKKsOCKQZ/L6Tv19DTRIGuLWe32lyzWhihGVJ/rcckZXJxfdKCFvRLS3fpBIsV/ZGX4zA==",+ "license": "MIT"+ },+ "node_modules/vscode-languageserver-types": {+ "version": "3.17.5",+ "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.5.tgz",+ "integrity": "sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==",+ "license": "MIT"+ },+ "node_modules/vscode-uri": {+ "version": "3.0.8",+ "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.0.8.tgz",+ "integrity": "sha512-AyFQ0EVmsOZOlAnxoFOGOq1SQDWAB7C6aqMGS23svWAllfOaxbuFvcT8D1i8z3Gyn8fraVeZNNmN6e9bxxXkKw==",+ "license": "MIT"+ },+ "node_modules/web-namespaces": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/web-namespaces/-/web-namespaces-2.0.1.tgz",+ "integrity": "sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/which": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "isexe": "^2.0.0"+ },+ "bin": {+ "node-which": "bin/node-which"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/word-wrap": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",+ "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/wrap-ansi": {+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",+ "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ansi-styles": "^4.0.0",+ "string-width": "^4.1.0",+ "strip-ansi": "^6.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"+ }+ },+ "node_modules/y18n": {+ "version": "5.0.8",+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",+ "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",+ "dev": true,+ "license": "ISC",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/yaml": {+ "version": "2.8.2",+ "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.2.tgz",+ "integrity": "sha512-mplynKqc1C2hTVYxd0PU2xQAc22TI1vShAYGksCCfxbn/dFwnHTNi1bvYsBTkhdUNtGIf5xNOg938rrSSYvS9A==",+ "dev": true,+ "license": "ISC",+ "optional": true,+ "peer": true,+ "bin": {+ "yaml": "bin.mjs"+ },+ "engines": {+ "node": ">= 14.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/eemeli"+ }+ },+ "node_modules/yargs": {+ "version": "17.7.2",+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz",+ "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "cliui": "^8.0.1",+ "escalade": "^3.1.1",+ "get-caller-file": "^2.0.5",+ "require-directory": "^2.1.1",+ "string-width": "^4.2.3",+ "y18n": "^5.0.5",+ "yargs-parser": "^21.1.1"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/yargs-parser": {+ "version": "21.1.1",+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz",+ "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==",+ "dev": true,+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/yocto-queue": {+ "version": "0.1.0",+ "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",+ "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/zod": {+ "version": "3.25.76",+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },+ "node_modules/zod-to-json-schema": {+ "version": "3.25.0",+ "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.0.tgz",+ "integrity": "sha512-HvWtU2UG41LALjajJrML6uQejQhNJx+JBO9IflpSja4R03iNWfKXrj6W2h7ljuLyc1nKS+9yDyL/9tD1U/yBnQ==",+ "license": "ISC",+ "peerDependencies": {+ "zod": "^3.25 || ^4"+ }+ },+ "node_modules/zod-validation-error": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/zod-validation-error/-/zod-validation-error-4.0.2.tgz",+ "integrity": "sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ },+ "peerDependencies": {+ "zod": "^3.25.0 || ^4.0.0"+ }+ },+ "node_modules/zustand": {+ "version": "5.0.9",+ "resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.9.tgz",+ "integrity": "sha512-ALBtUj0AfjJt3uNRQoL1tL2tMvj6Gp/6e39dnfT6uzpelGru8v1tPOGBzayOWbPJvujM8JojDk3E1LxeFisBNg==",+ "license": "MIT",+ "engines": {+ "node": ">=12.20.0"+ },+ "peerDependencies": {+ "@types/react": ">=18.0.0",+ "immer": ">=9.0.6",+ "react": ">=18.0.0",+ "use-sync-external-store": ">=1.2.0"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "immer": {+ "optional": true+ },+ "react": {+ "optional": true+ },+ "use-sync-external-store": {+ "optional": true+ }+ }+ },+ "node_modules/zwitch": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",+ "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ }+ }+}diff --git a/package.json b/package.jsonnew file mode 100644index 00000000..d896444c--- /dev/null+++ b/package.json@@ -0,0 +1,39 @@+{+ "name": "react-flow-project",+ "private": true,+ "version": "0.0.0",+ "type": "module",+ "workspaces": [+ "client"+ ],+ "scripts": {+ "dev": "concurrently -t -n client,python,whatsapp -c blue,green,yellow \"npm run client:dev\" \"npm run python:dev\" \"npm run whatsapp:api\"",+ "client:dev": "cd client && set NO_COLOR=1&& npm run dev",+ "python:dev": "cd server && python -m uvicorn main:app --host 127.0.0.1 --port 3010 --reload --reload-dir . --reload-exclude \"*.pyc\" --reload-exclude \"__pycache__\" --log-level warning",+ "whatsapp:start": "cd server/whatsapp-rpc && npm start",+ "whatsapp:stop": "cd server/whatsapp-rpc && npm stop",+ "whatsapp:status": "cd server/whatsapp-rpc && npm run status",+ "whatsapp:api": "cd server/whatsapp-rpc && npm run api",+ "whatsapp:build": "cd server/whatsapp-rpc && npm run build",+ "build": "npm install && cd client && npm install && npm run build && cd ../server && python -m pip install -r requirements.txt && cd whatsapp-rpc && npm install",+ "clean": "node scripts/clean.js",+ "start": "node scripts/start.js",+ "stop": "node scripts/stop.js",+ "restart": "node scripts/restart.js",+ "status": "node scripts/status.js",+ "docker:up": "docker-compose up -d",+ "docker:down": "docker-compose down",+ "docker:logs": "docker-compose logs -f",+ "docker:build": "docker-compose build",+ "docker:restart": "docker-compose restart",+ "docker:prod:up": "docker-compose -f docker-compose.prod.yml up -d",+ "docker:prod:down": "docker-compose -f docker-compose.prod.yml down",+ "docker:prod:build": "docker-compose -f docker-compose.prod.yml build",+ "docker:prod:logs": "docker-compose -f docker-compose.prod.yml logs -f",+ "deploy": "bash deploy.sh",+ "deploy:gcp": "bash deploy.sh"+ },+ "devDependencies": {+ "concurrently": "^9.2.1"+ }+}diff --git a/scripts/clean.js b/scripts/clean.jsnew file mode 100644index 00000000..f722675f--- /dev/null+++ b/scripts/clean.js@@ -0,0 +1,84 @@+import { rm } from 'fs/promises';+import { existsSync, readdirSync, statSync } from 'fs';+import { join } from 'path';++const dirsToRemove = [+ 'node_modules',+ 'client/node_modules',+ 'client/dist',+ 'client/.vite',+ 'server/whatsapp-rpc/node_modules',+ 'server/whatsapp-rpc/dist',+ 'server/data',+ '.eslintcache'+];++const filePatternsToRemove = [+ '.db',+ '.sqlite',+ '.sqlite3'+];++// Find all __pycache__ directories and db files recursively+function findCleanTargets(dir, dirs = [], files = []) {+ if (!existsSync(dir)) return { dirs, files };++ try {+ const entries = readdirSync(dir);+ for (const entry of entries) {+ const fullPath = join(dir, entry);+ try {+ const stat = statSync(fullPath);+ if (stat.isDirectory()) {+ if (entry === '__pycache__' || entry === '.pytest_cache') {+ dirs.push(fullPath);+ } else if (entry !== 'node_modules' && entry !== '.git') {+ findCleanTargets(fullPath, dirs, files);+ }+ } else if (stat.isFile()) {+ if (filePatternsToRemove.some(ext => entry.endsWith(ext))) {+ files.push(fullPath);+ }+ }+ } catch {}+ }+ } catch {}++ return { dirs, files };+}++async function clean() {+ const serverTargets = findCleanTargets('server');+ const rootTargets = findCleanTargets('.');++ const allDirs = [...dirsToRemove, ...serverTargets.dirs];+ const allFiles = [...serverTargets.files, ...rootTargets.files.filter(f => !f.includes('node_modules'))];++ console.log('Cleaning build artifacts...');++ for (const dir of allDirs) {+ if (existsSync(dir)) {+ try {+ await rm(dir, { recursive: true, force: true });+ console.log(` Removed dir: ${dir}`);+ } catch (err) {+ console.error(` Failed to remove ${dir}: ${err.message}`);+ }+ }+ }++ for (const file of allFiles) {+ if (existsSync(file)) {+ try {+ await rm(file, { force: true });+ console.log(` Removed file: ${file}`);+ } catch (err) {+ console.error(` Failed to remove ${file}: ${err.message}`);+ }+ }+ }++ console.log('Done.');+}++clean();diff --git a/scripts/restart.js b/scripts/restart.jsnew file mode 100644index 00000000..48930937--- /dev/null+++ b/scripts/restart.js@@ -0,0 +1,21 @@+#!/usr/bin/env node+import { execSync } from 'child_process';+import { fileURLToPath } from 'url';+import { dirname, join } from 'path';++const __dirname = dirname(fileURLToPath(import.meta.url));+const sleep = ms => new Promise(r => setTimeout(r, ms));++// Set Python UTF-8 encoding to avoid charmap errors on Windows+process.env.PYTHONUTF8 = '1';++console.log('Restarting all services...\n');++console.log('--- Stopping ---');+try { execSync(`node "${join(__dirname, 'stop.js')}"`, { stdio: 'inherit' }); } catch {}++console.log('\nWaiting 2s...\n');+await sleep(2000);++console.log('--- Starting ---');+execSync(`node "${join(__dirname, 'start.js')}"`, { stdio: 'inherit' });diff --git a/scripts/start.js b/scripts/start.jsnew file mode 100644index 00000000..d581b631--- /dev/null+++ b/scripts/start.js@@ -0,0 +1,76 @@+#!/usr/bin/env node+import { execSync, spawn } from 'child_process';+import { fileURLToPath } from 'url';+import { dirname, resolve } from 'path';+import { readFileSync, existsSync } from 'fs';++const __dirname = dirname(fileURLToPath(import.meta.url));+const ROOT = resolve(__dirname, '..');+const START = Date.now();+const isWindows = process.platform === 'win32';++// Timing helper+const elapsed = () => `${((Date.now() - START) / 1000).toFixed(2)}s`;+const log = (msg) => console.log(`[${elapsed()}] ${msg}`);++// Load ports from .env+function loadPorts() {+ const envPath = existsSync(resolve(ROOT, '.env')) ? resolve(ROOT, '.env') : resolve(ROOT, '.env.template');+ if (!existsSync(envPath)) return [3000, 3010, 9400];+ const content = readFileSync(envPath, 'utf-8');+ const env = {};+ for (const line of content.split('\n')) {+ const [key, val] = line.split('=');+ if (key && val) env[key.trim()] = val.trim();+ }+ return [+ parseInt(env.VITE_CLIENT_PORT) || 3000,+ parseInt(env.PYTHON_BACKEND_PORT) || 3010,+ parseInt(env.WHATSAPP_RPC_PORT) || 9400+ ];+}++// Kill process by port using native commands+function killPort(port) {+ try {+ if (isWindows) {+ const output = execSync(`netstat -ano | findstr :${port} | findstr LISTENING`, { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] });+ const lines = output.trim().split('\n');+ const pids = new Set();+ for (const line of lines) {+ const parts = line.trim().split(/\s+/);+ const pid = parts[parts.length - 1];+ if (pid && !isNaN(parseInt(pid))) pids.add(pid);+ }+ for (const pid of pids) {+ try {+ execSync(`taskkill /PID ${pid} /F`, { stdio: 'pipe' });+ } catch {}+ }+ } else {+ const output = execSync(`lsof -ti:${port}`, { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] });+ const pids = output.trim().split('\n').filter(Boolean);+ for (const pid of pids) {+ try {+ execSync(`kill -9 ${pid}`, { stdio: 'pipe' });+ } catch {}+ }+ }+ } catch {}+}++const PORTS = loadPorts();+process.env.PYTHONUTF8 = '1';++console.log('\n=== MachinaOS Starting ===\n');++// Step 1: Free ports+log('Freeing ports...');+for (const port of PORTS) {+ killPort(port);+}+log('Ports ready');++// Step 2: Start dev server+log('Starting services...');+spawn('npm', ['run', 'dev'], { cwd: ROOT, stdio: 'inherit', shell: true });diff --git a/scripts/status.js b/scripts/status.jsnew file mode 100644index 00000000..63a9b223--- /dev/null+++ b/scripts/status.js@@ -0,0 +1,60 @@+#!/usr/bin/env node+import http from 'http';+import { readFileSync, existsSync } from 'fs';+import { resolve, dirname } from 'path';+import { fileURLToPath } from 'url';++const __dirname = dirname(fileURLToPath(import.meta.url));+const ROOT = resolve(__dirname, '..');++// Load ports from .env+function loadPorts() {+ const envPath = existsSync(resolve(ROOT, '.env')) ? resolve(ROOT, '.env') : resolve(ROOT, '.env.template');+ const content = readFileSync(envPath, 'utf-8');+ const env = {};+ for (const line of content.split('\n')) {+ const [key, val] = line.split('=');+ if (key && val) env[key.trim()] = val.trim();+ }+ return {+ frontend: parseInt(env.VITE_CLIENT_PORT),+ backend: parseInt(env.PYTHON_BACKEND_PORT),+ whatsapp: parseInt(env.WHATSAPP_RPC_PORT)+ };+}++const ports = loadPorts();++const SERVICES = [+ { name: 'Frontend', port: ports.frontend },+ { name: 'Python Backend', port: ports.backend, health: '/health' },+ { name: 'WhatsApp RPC', port: ports.whatsapp }+];++const checkHealth = (port, path) => new Promise(resolve => {+ const req = http.get(`http://localhost:${port}${path}`, { timeout: 2000 }, res => resolve(res.statusCode === 200));+ req.on('error', () => resolve(false));+ req.on('timeout', () => { req.destroy(); resolve(false); });+});++const checkPort = port => new Promise(resolve => {+ const req = http.get(`http://localhost:${port}`, { timeout: 1000 }, () => resolve(true));+ req.on('error', () => resolve(false));+ req.on('timeout', () => { req.destroy(); resolve(false); });+});++console.log('Service Status\n' + '='.repeat(60));++for (const svc of SERVICES) {+ const running = await checkPort(svc.port);+ const healthy = svc.health && running ? await checkHealth(svc.port, svc.health) : null;++ let status = running ? 'RUNNING' : 'STOPPED';+ if (healthy === true) status += ' (healthy)';+ if (healthy === false) status += ' (unhealthy)';++ console.log(`${running ? '[OK]' : '[--]'} ${svc.name.padEnd(20)} Port ${svc.port.toString().padEnd(5)} ${status}`);+}++console.log('='.repeat(60));+console.log('\nCommands: npm run start | stop | restart | status');diff --git a/scripts/stop.js b/scripts/stop.jsnew file mode 100644index 00000000..72d7150f--- /dev/null+++ b/scripts/stop.js@@ -0,0 +1,92 @@+#!/usr/bin/env node+import { execSync } from 'child_process';+import { readFileSync, existsSync } from 'fs';+import { resolve, dirname } from 'path';+import { fileURLToPath } from 'url';++const __dirname = dirname(fileURLToPath(import.meta.url));+const ROOT = resolve(__dirname, '..');+const isWindows = process.platform === 'win32';++// Load ports from .env+function loadPorts() {+ const envPath = existsSync(resolve(ROOT, '.env')) ? resolve(ROOT, '.env') : resolve(ROOT, '.env.template');+ if (!existsSync(envPath)) return [3000, 3010, 9400];+ const content = readFileSync(envPath, 'utf-8');+ const env = {};+ for (const line of content.split('\n')) {+ const [key, val] = line.split('=');+ if (key && val) env[key.trim()] = val.trim();+ }+ return [+ parseInt(env.VITE_CLIENT_PORT) || 3000,+ parseInt(env.PYTHON_BACKEND_PORT) || 3010,+ parseInt(env.WHATSAPP_RPC_PORT) || 9400+ ];+}++// Kill process by port using native commands+function killPort(port) {+ try {+ if (isWindows) {+ // Find PID using netstat and kill with taskkill+ const output = execSync(`netstat -ano | findstr :${port} | findstr LISTENING`, { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] });+ const lines = output.trim().split('\n');+ const pids = new Set();+ for (const line of lines) {+ const parts = line.trim().split(/\s+/);+ const pid = parts[parts.length - 1];+ if (pid && !isNaN(parseInt(pid))) pids.add(pid);+ }+ for (const pid of pids) {+ try {+ execSync(`taskkill /PID ${pid} /F`, { stdio: 'pipe' });+ } catch {}+ }+ return pids.size > 0;+ } else {+ // Unix: use lsof and kill+ const output = execSync(`lsof -ti:${port}`, { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] });+ const pids = output.trim().split('\n').filter(Boolean);+ for (const pid of pids) {+ try {+ execSync(`kill -9 ${pid}`, { stdio: 'pipe' });+ } catch {}+ }+ return pids.length > 0;+ }+ } catch {+ return false;+ }+}++// Kill processes by name+function killProcess(name) {+ try {+ if (isWindows) {+ execSync(`taskkill /IM ${name}.exe /F`, { stdio: 'pipe' });+ return true;+ } else {+ execSync(`pkill -9 ${name}`, { stdio: 'pipe' });+ return true;+ }+ } catch {+ return false;+ }+}++const PORTS = loadPorts();++console.log('Stopping all services...\n');++// Kill by ports+for (const port of PORTS) {+ const killed = killPort(port);+ console.log(`[Port ${port}] ${killed ? 'Killed' : 'Free'}`);+}++// Kill Python/uvicorn+const pythonKilled = killProcess('python') || killProcess('uvicorn');+console.log(`[Python] ${pythonKilled ? 'Killed' : 'Not running'}`);++console.log('\nAll services stopped.');diff --git a/server/.dockerignore b/server/.dockerignorenew file mode 100644index 00000000..665626dc--- /dev/null+++ b/server/.dockerignore@@ -0,0 +1,44 @@+# Python+__pycache__/+*.py[cod]+*$py.class+*.so+.Python+.env+.env.*+!.env.template+venv/+ENV/+.venv/+.pytest_cache/+.mypy_cache/++# IDE+.vscode/+.idea/+*.swp+*.swo++# Data (will be mounted as volume)+data/+*.db+*.sqlite++# Logs+*.log+logs/++# Git+.git/+.gitignore++# Documentation+*.md+!README.md++# Tests+tests/+test_*.py++# WhatsApp RPC (separate build)+whatsapp-rpc/diff --git a/server/.env.example b/server/.env.examplenew file mode 100644index 00000000..90181017--- /dev/null+++ b/server/.env.example@@ -0,0 +1,62 @@+# Server Configuration+HOST=0.0.0.0+PORT=3010+DEBUG=false+WORKERS=1++# Security (REQUIRED - Generate secure keys for production)+SECRET_KEY=your-secret-key-32-characters-minimum-length+API_KEY_ENCRYPTION_KEY=your-encryption-key-32-characters-minimum++# CORS Configuration+CORS_ORIGINS=http://localhost:3000,http://127.0.0.1:3000++# Database Configuration+DATABASE_URL=sqlite+aiosqlite:///./data/workflow.db+DATABASE_ECHO=false+DATABASE_POOL_SIZE=20+DATABASE_MAX_OVERFLOW=30++# Cache Configuration (Optional - Redis for production)+REDIS_URL=redis://localhost:6379/0+REDIS_ENABLED=false+CACHE_TTL=3600++# WebSocket Configuration (For remote Android device connections)+WEBSOCKET_URL=+WEBSOCKET_API_KEY=+ANDROID_RELAY_URL=++# WhatsApp Service URL+WHATSAPP_SERVICE_URL=http://localhost:5000++# External API Keys (Optional - Set only if you have them)+# These are user-managed through the UI, but you can set defaults here+# GOOGLE_MAPS_API_KEY=your-google-maps-api-key+# OPENAI_API_KEY=your-openai-api-key+# ANTHROPIC_API_KEY=your-anthropic-api-key+# GOOGLE_AI_API_KEY=your-google-ai-api-key++# API Key Management+API_KEY_CACHE_TTL=2592000++# Logging+LOG_LEVEL=INFO+LOG_FORMAT=json+# LOG_FILE=./logs/app.log++# Rate Limiting+RATE_LIMIT_ENABLED=true+RATE_LIMIT_REQUESTS=100+RATE_LIMIT_WINDOW=60++# Service Timeouts+AI_TIMEOUT=30+AI_MAX_RETRIES=3+AI_RETRY_DELAY=1.0++MAPS_TIMEOUT=10+MAPS_MAX_RPS=50++# Health Check+HEALTH_CHECK_INTERVAL=30\ No newline at end of filediff --git a/server/.env.template b/server/.env.templatenew file mode 100644index 00000000..cdd776d2--- /dev/null+++ b/server/.env.template@@ -0,0 +1,66 @@+# Server Configuration+HOST=127.0.0.1+PORT=3010+DEBUG=true+WORKERS=1++# Security (Development keys - MUST CHANGE FOR PRODUCTION)+SECRET_KEY=dev-secret-key-12345678901234567890123456789012+API_KEY_ENCRYPTION_KEY=dev-encryption-key-12345678901234567890123456++# Authentication+# AUTH_MODE: "single" (local deploy - first user is owner) or "multi" (cloud - open registration)+AUTH_MODE=single+JWT_SECRET_KEY=dev-jwt-secret-key-12345678901234567890+JWT_EXPIRE_MINUTES=10080+JWT_COOKIE_NAME=machina_token+JWT_COOKIE_SECURE=false+JWT_COOKIE_SAMESITE=lax++# CORS Configuration - Allow all common dev ports+CORS_ORIGINS=["http://localhost:3000","http://localhost:3001","http://localhost:3002","http://localhost:3003","http://localhost:3004","http://localhost:3005","http://localhost:3006","http://127.0.0.1:3000","http://127.0.0.1:3001","http://127.0.0.1:3002","http://127.0.0.1:3003","http://127.0.0.1:3004","http://127.0.0.1:3005","http://127.0.0.1:3006","http://localhost:5173"]++# Database Configuration+DATABASE_URL=sqlite+aiosqlite:///./data/workflow.db+DATABASE_ECHO=false+DATABASE_POOL_SIZE=5+DATABASE_MAX_OVERFLOW=10++# Cache Configuration (Disabled for development)+REDIS_ENABLED=false+CACHE_TTL=300++# Logging+LOG_LEVEL=DEBUG+LOG_FORMAT=text++# Rate Limiting (Relaxed for development)+RATE_LIMIT_ENABLED=false+RATE_LIMIT_REQUESTS=1000+RATE_LIMIT_WINDOW=60++# Service Timeouts (Extended for debugging)+AI_TIMEOUT=60+AI_MAX_RETRIES=1+AI_RETRY_DELAY=0.5++MAPS_TIMEOUT=30++# Health Check+HEALTH_CHECK_INTERVAL=60++# WebSocket Configuration (For remote Android device connections)+# Set your Android relay server URL and API key+WEBSOCKET_URL=+WEBSOCKET_API_KEY=+ANDROID_RELAY_URL=++# WhatsApp Service URL+WHATSAPP_SERVICE_URL=http://localhost:5000++# External API Keys+# Set these to your actual API keys (managed through UI, these are optional defaults)+OPENAI_API_KEY=+GOOGLE_MAPS_API_KEY=+ANTHROPIC_API_KEY=+GOOGLE_AI_API_KEY=diff --git a/server/.gitignore b/server/.gitignorenew file mode 100644index 00000000..a1dcba87--- /dev/null+++ b/server/.gitignore@@ -0,0 +1,13 @@+# Python cache files+__pycache__/+*.py[cod]+*$py.class++# Database files (keep structure, ignore data)+data/*.db*++# Environment files+.env+.env.local+.env.development+.env.production\ No newline at end of filediff --git a/server/Dockerfile b/server/Dockerfilenew file mode 100644index 00000000..5262f195--- /dev/null+++ b/server/Dockerfile@@ -0,0 +1,42 @@+# Python FastAPI Backend+FROM python:3.12-slim++WORKDIR /app++# Install system dependencies+RUN apt-get update && apt-get install -y \+ curl \+ gcc \+ && rm -rf /var/lib/apt/lists/*++# Copy requirements first for better caching+COPY requirements.txt .++# Install Python dependencies+RUN pip install --no-cache-dir -r requirements.txt++# Install aiohttp for WebSocket client (Android relay)+RUN pip install --no-cache-dir aiohttp>=3.9.0++# Copy application code+COPY . .++# Create data directory for SQLite database+RUN mkdir -p /app/data++# Compile Python files to optimized bytecode for faster imports+# Keep .py files since Python imports require them or __pycache__/*.pyc+# -O: optimize (remove assert statements)+# -q: quiet mode+# -f: force rebuild+RUN python -O -m compileall -q -f .++# Expose port+EXPOSE 3010++# Health check+HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \+ CMD curl -f http://localhost:3010/health || exit 1++# Run the application+CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "3010"]diff --git a/server/constants.py b/server/constants.pynew file mode 100644index 00000000..cfe2451b--- /dev/null+++ b/server/constants.py@@ -0,0 +1,193 @@+"""Centralized constants for node types and categories.++This module provides a single source of truth for all node type definitions,+eliminating duplicate string arrays across the codebase.+"""++from typing import FrozenSet++# =============================================================================+# AI NODE TYPES+# =============================================================================++AI_CHAT_MODEL_TYPES: FrozenSet[str] = frozenset([+ 'openaiChatModel',+ 'anthropicChatModel',+ 'geminiChatModel',+])++AI_AGENT_TYPES: FrozenSet[str] = frozenset([+ 'aiAgent',+])++AI_MEMORY_TYPES: FrozenSet[str] = frozenset([+ 'simpleMemory',+])++# All AI-related node types (for API key injection)+AI_MODEL_TYPES: FrozenSet[str] = AI_AGENT_TYPES | AI_CHAT_MODEL_TYPES++# =============================================================================+# GOOGLE MAPS NODE TYPES+# =============================================================================++GOOGLE_MAPS_TYPES: FrozenSet[str] = frozenset([+ 'createMap',+ 'addLocations',+ 'showNearbyPlaces',+])++# =============================================================================+# ANDROID NODE TYPES+# =============================================================================++# System monitoring nodes+ANDROID_MONITORING_TYPES: FrozenSet[str] = frozenset([+ 'batteryMonitor',+ 'networkMonitor',+ 'systemInfo',+ 'location',+])++# App management nodes+ANDROID_APP_TYPES: FrozenSet[str] = frozenset([+ 'appLauncher',+ 'appList',+])++# Device automation nodes+ANDROID_AUTOMATION_TYPES: FrozenSet[str] = frozenset([+ 'wifiAutomation',+ 'bluetoothAutomation',+ 'audioAutomation',+ 'deviceStateAutomation',+ 'screenControlAutomation',+ 'airplaneModeControl',+])++# Sensor nodes+ANDROID_SENSOR_TYPES: FrozenSet[str] = frozenset([+ 'motionDetection',+ 'environmentalSensors',+])++# Media nodes+ANDROID_MEDIA_TYPES: FrozenSet[str] = frozenset([+ 'cameraControl',+ 'mediaControl',+])++# All Android service node types (combined)+ANDROID_SERVICE_NODE_TYPES: FrozenSet[str] = (+ ANDROID_MONITORING_TYPES |+ ANDROID_APP_TYPES |+ ANDROID_AUTOMATION_TYPES |+ ANDROID_SENSOR_TYPES |+ ANDROID_MEDIA_TYPES+)++# Android device setup (separate from services)+ANDROID_SETUP_TYPES: FrozenSet[str] = frozenset([+ 'androidDeviceSetup',+])++# =============================================================================+# WHATSAPP NODE TYPES+# =============================================================================++WHATSAPP_TYPES: FrozenSet[str] = frozenset([+ 'whatsappSend',+ 'whatsappConnect',+ 'whatsappReceive',+])++# =============================================================================+# CHAT NODE TYPES+# =============================================================================++CHAT_TYPES: FrozenSet[str] = frozenset([+ 'chatSend',+ 'chatHistory',+])++# =============================================================================+# UTILITY NODE TYPES+# =============================================================================++CODE_EXECUTOR_TYPES: FrozenSet[str] = frozenset([+ 'pythonExecutor',+ 'javascriptExecutor',+])++HTTP_TYPES: FrozenSet[str] = frozenset([+ 'httpRequest',+ 'webhookResponse',+])++TEXT_TYPES: FrozenSet[str] = frozenset([+ 'textGenerator',+ 'fileHandler',+])++# =============================================================================+# WORKFLOW CONTROL NODE TYPES+# =============================================================================++WORKFLOW_CONTROL_TYPES: FrozenSet[str] = frozenset([+ 'start',+ 'cronScheduler',+])++# =============================================================================+# TRIGGER NODE TYPES (handled by event_waiter)+# =============================================================================++# Event-driven triggers that wait for external events+EVENT_TRIGGER_TYPES: FrozenSet[str] = frozenset([+ 'webhookTrigger',+ 'whatsappReceive',+ 'workflowTrigger',+])++# Legacy alias for backwards compatibility+TRIGGER_TYPES: FrozenSet[str] = EVENT_TRIGGER_TYPES++# =============================================================================+# ALL TRIGGER NODE TYPES (starting points for workflow graphs)+# =============================================================================++# Combined set of all trigger node types that can start a workflow+# These nodes have no input handles and serve as entry points+WORKFLOW_TRIGGER_TYPES: FrozenSet[str] = frozenset([+ # Manual start+ 'start',+ # Scheduled triggers+ 'cronScheduler',+ # Event-driven triggers+ 'webhookTrigger',+ 'whatsappReceive',+ 'workflowTrigger',+])++# =============================================================================+# AI PROVIDER DETECTION+# =============================================================================++def detect_ai_provider(node_type: str, parameters: dict = None) -> str:+ """Detect AI provider from node type or parameters.++ Args:+ node_type: The node type string+ parameters: Optional parameters dict (used for aiAgent)++ Returns:+ Provider string: 'openai', 'anthropic', or 'gemini'+ """+ if node_type == 'aiAgent':+ return (parameters or {}).get('provider', 'openai')+ elif 'anthropic' in node_type.lower():+ return 'anthropic'+ elif 'gemini' in node_type.lower():+ return 'gemini'+ else:+ return 'openai'diff --git a/server/core/__init__.py b/server/core/__init__.pynew file mode 100644index 00000000..712fd97f--- /dev/null+++ b/server/core/__init__.py@@ -0,0 +1 @@+# Core framework components\ No newline at end of filediff --git a/server/core/cache.py b/server/core/cache.pynew file mode 100644index 00000000..28166778--- /dev/null+++ b/server/core/cache.py@@ -0,0 +1,458 @@+"""Cache service with Redis (production) or SQLite (development) backend.++Follows n8n pattern where SQLite is sufficient for single-process deployments,+with Redis used only for distributed queue mode or high-performance needs.+"""++import json+import asyncio+from typing import Any, Dict, Optional, List, TYPE_CHECKING+from datetime import timedelta++try:+ import redis.asyncio as redis+ REDIS_AVAILABLE = True+except ImportError:+ redis = None+ REDIS_AVAILABLE = False++from core.config import Settings+from core.logging import get_logger, log_cache_operation++if TYPE_CHECKING:+ from core.database import Database++logger = get_logger(__name__)+++class CacheService:+ """Async cache service with Redis or SQLite backend.++ Backend selection:+ - Redis: When REDIS_ENABLED=true and Redis is available (production)+ - SQLite: When Redis disabled or unavailable (development)+ - Memory: Temporary fallback if both fail+ """++ def __init__(self, settings: Settings, database: Optional["Database"] = None):+ self.settings = settings+ self.database = database # SQLite backend+ self.redis: Optional[redis.Redis] = None+ self.memory_cache: Dict[str, Any] = {} # Emergency fallback only+ self.use_redis = settings.redis_enabled and REDIS_AVAILABLE+ self.use_sqlite = not self.use_redis and database is not None+ self._streams_available = False # Checked during startup++ async def startup(self):+ """Initialize cache connection."""+ if self.use_redis and self.settings.redis_url:+ try:+ self.redis = redis.from_url(+ self.settings.redis_url,+ encoding="utf-8",+ decode_responses=True,+ socket_timeout=5,+ socket_connect_timeout=5,+ retry_on_timeout=True+ )++ # Test connection+ await self.redis.ping()+ logger.info("Redis cache initialized", url=self.settings.redis_url)++ # Test Redis Streams availability (required for trigger nodes)+ await self._check_streams_support()++ except Exception as e:+ logger.warning("Redis connection failed, falling back", error=str(e))+ self.use_redis = False+ self.redis = None+ # Try SQLite fallback+ if self.database:+ self.use_sqlite = True+ logger.info("Using SQLite cache (Redis fallback)")+ else:+ if self.use_sqlite:+ logger.info("Using SQLite cache (n8n pattern - no Redis required for single-process)")+ else:+ logger.info("Using in-memory cache",+ redis_enabled=self.settings.redis_enabled,+ redis_available=REDIS_AVAILABLE)++ async def _check_streams_support(self):+ """Check if Redis supports Streams (XADD/XREAD commands).++ Some Redis-compatible services (e.g., certain cloud providers) don't support Streams.+ We test this at startup to avoid runtime failures in trigger nodes.+ """+ if not self.redis:+ self._streams_available = False+ return++ test_stream = "_machina_streams_test"+ try:+ # Try XADD - this will fail if Streams aren't supported+ msg_id = await self.redis.xadd(test_stream, {"test": "1"}, maxlen=1)+ if msg_id:+ # Clean up test stream+ await self.redis.delete(test_stream)+ self._streams_available = True+ logger.info("Redis Streams available - trigger nodes will use Redis persistence")+ else:+ self._streams_available = False+ logger.warning("Redis Streams test failed - trigger nodes will use memory mode")+ except Exception as e:+ self._streams_available = False+ error_str = str(e).lower()+ if "unknown command" in error_str:+ logger.warning("Redis Streams not supported by server - trigger nodes will use memory mode")+ else:+ logger.warning(f"Redis Streams check failed: {e} - trigger nodes will use memory mode")++ async def shutdown(self):+ """Close cache connections."""+ if self.redis:+ await self.redis.close()+ logger.info("Redis cache connections closed")++ # Clear memory cache+ self.memory_cache.clear()++ async def get(self, key: str) -> Optional[Any]:+ """Get value from cache."""+ try:+ if self.use_redis and self.redis:+ value = await self.redis.get(key)+ if value:+ log_cache_operation(logger, "get", key, hit=True)+ return json.loads(value)+ else:+ log_cache_operation(logger, "get", key, hit=False)+ return None+ elif self.use_sqlite and self.database:+ # SQLite cache+ value = await self.database.get_cache_entry(key)+ if value:+ log_cache_operation(logger, "get", key, hit=True)+ return json.loads(value)+ else:+ log_cache_operation(logger, "get", key, hit=False)+ return None+ else:+ # Memory cache fallback+ value = self.memory_cache.get(key)+ log_cache_operation(logger, "get", key, hit=value is not None)+ return value++ except Exception as e:+ logger.error("Cache get failed", key=key, error=str(e))+ return None++ async def set(self, key: str, value: Any, ttl: Optional[int] = None) -> bool:+ """Set value in cache with optional TTL."""+ try:+ ttl = ttl or self.settings.cache_ttl++ if self.use_redis and self.redis:+ serialized = json.dumps(value, default=str)+ await self.redis.setex(key, ttl, serialized)+ log_cache_operation(logger, "set", key, ttl=ttl)+ return True+ elif self.use_sqlite and self.database:+ # SQLite cache with TTL support+ serialized = json.dumps(value, default=str)+ await self.database.set_cache_entry(key, serialized, ttl)+ log_cache_operation(logger, "set", key, ttl=ttl)+ return True+ else:+ # Memory cache fallback (no TTL)+ self.memory_cache[key] = value+ log_cache_operation(logger, "set", key, ttl=ttl)+ return True++ except Exception as e:+ logger.error("Cache set failed", key=key, error=str(e))+ return False++ async def delete(self, key: str) -> bool:+ """Delete value from cache."""+ try:+ if self.use_redis and self.redis:+ deleted = await self.redis.delete(key)+ log_cache_operation(logger, "delete", key, deleted=bool(deleted))+ return bool(deleted)+ elif self.use_sqlite and self.database:+ # SQLite cache+ deleted = await self.database.delete_cache_entry(key)+ log_cache_operation(logger, "delete", key, deleted=deleted)+ return deleted+ else:+ # Memory cache fallback+ deleted = key in self.memory_cache+ if deleted:+ del self.memory_cache[key]+ log_cache_operation(logger, "delete", key, deleted=deleted)+ return deleted++ except Exception as e:+ logger.error("Cache delete failed", key=key, error=str(e))+ return False++ async def exists(self, key: str) -> bool:+ """Check if key exists in cache."""+ try:+ if self.use_redis and self.redis:+ exists = await self.redis.exists(key)+ return bool(exists)+ elif self.use_sqlite and self.database:+ return await self.database.cache_exists(key)+ else:+ return key in self.memory_cache++ except Exception as e:+ logger.error("Cache exists check failed", key=key, error=str(e))+ return False++ async def expire(self, key: str, ttl: int) -> bool:+ """Set TTL for existing key."""+ try:+ if self.use_redis and self.redis:+ return bool(await self.redis.expire(key, ttl))+ else:+ # Memory cache doesn't support TTL updates+ return key in self.memory_cache++ except Exception as e:+ logger.error("Cache expire failed", key=key, error=str(e))+ return False++ async def clear_pattern(self, pattern: str) -> int:+ """Clear keys matching pattern."""+ try:+ if self.use_redis and self.redis:+ keys = await self.redis.keys(pattern)+ if keys:+ deleted = await self.redis.delete(*keys)+ log_cache_operation(logger, "clear_pattern", pattern, deleted=deleted)+ return deleted+ return 0+ elif self.use_sqlite and self.database:+ # SQLite cache pattern matching+ deleted = await self.database.delete_cache_pattern(pattern)+ log_cache_operation(logger, "clear_pattern", pattern, deleted=deleted)+ return deleted+ else:+ # Memory cache pattern matching+ keys_to_delete = [k for k in self.memory_cache.keys() if pattern.replace("*", "") in k]+ for key in keys_to_delete:+ del self.memory_cache[key]+ log_cache_operation(logger, "clear_pattern", pattern, deleted=len(keys_to_delete))+ return len(keys_to_delete)++ except Exception as e:+ logger.error("Cache clear pattern failed", pattern=pattern, error=str(e))+ return 0++ # ============================================================================+ # API Key Specific Cache Methods+ # ============================================================================++ async def cache_api_key(self, provider: str, session_id: str, key_data: Dict[str, Any]) -> bool:+ """Cache API key data."""+ cache_key = f"api_key:{provider}:{session_id}"+ return await self.set(cache_key, key_data, self.settings.api_key_cache_ttl)++ async def get_cached_api_key(self, provider: str, session_id: str) -> Optional[Dict[str, Any]]:+ """Get cached API key data."""+ cache_key = f"api_key:{provider}:{session_id}"+ return await self.get(cache_key)++ async def remove_cached_api_key(self, provider: str, session_id: str) -> bool:+ """Remove cached API key."""+ cache_key = f"api_key:{provider}:{session_id}"+ return await self.delete(cache_key)++ async def cache_models(self, provider: str, models: List[str]) -> bool:+ """Cache available models for provider."""+ cache_key = f"models:{provider}"+ return await self.set(cache_key, {"models": models, "cached_at": "now"},+ ttl=3600) # 1 hour++ async def get_cached_models(self, provider: str) -> Optional[List[str]]:+ """Get cached models for provider."""+ cache_key = f"models:{provider}"+ data = await self.get(cache_key)+ return data.get("models") if data else None++ # ============================================================================+ # Redis Streams Methods for Event Waiting+ # ============================================================================++ async def stream_add(self, stream: str, data: Dict[str, Any], maxlen: int = 1000) -> Optional[str]:+ """Add message to Redis Stream.++ Args:+ stream: Stream name (e.g., 'events:whatsapp_message_received')+ data: Event data to store+ maxlen: Maximum stream length (approximate, uses ~)++ Returns:+ Message ID if successful, None otherwise+ """+ try:+ if self.use_redis and self.redis and self._streams_available:+ # Serialize data to JSON string for storage+ serialized = {k: json.dumps(v) if isinstance(v, (dict, list)) else str(v)+ for k, v in data.items()}+ msg_id = await self.redis.xadd(stream, serialized, maxlen=maxlen, approximate=True)+ logger.debug(f"Stream add: {stream} -> {msg_id}")+ return msg_id+ return None+ except Exception as e:+ logger.error(f"Stream add failed: {stream}", error=str(e))+ return None++ async def stream_read(+ self,+ streams: Dict[str, str],+ count: int = 1,+ block: Optional[int] = None+ ) -> Optional[List[Any]]:+ """Read from Redis Streams.++ Args:+ streams: Dict of stream_name -> last_id (use '$' for new messages only, '0' for all)+ count: Maximum number of messages to read+ block: Milliseconds to block (None = no blocking, 0 = infinite)++ Returns:+ List of [stream_name, [(msg_id, data), ...]] or None+ """+ try:+ if self.use_redis and self.redis:+ result = await self.redis.xread(streams, count=count, block=block)+ return result+ return None+ except Exception as e:+ logger.error(f"Stream read failed: {streams.keys()}", error=str(e))+ return None++ async def stream_create_group(+ self,+ stream: str,+ group: str,+ start_id: str = '$'+ ) -> bool:+ """Create consumer group for stream.++ Args:+ stream: Stream name+ group: Consumer group name+ start_id: Start reading from ('$' = new only, '0' = all)++ Returns:+ True if created or already exists+ """+ try:+ if self.use_redis and self.redis and self._streams_available:+ try:+ await self.redis.xgroup_create(stream, group, start_id, mkstream=True)+ logger.info(f"Created consumer group: {group} on {stream}")+ return True+ except Exception as e:+ if "BUSYGROUP" in str(e):+ # Group already exists - this is fine+ return True+ raise+ return False+ except Exception as e:+ logger.error(f"Stream create group failed: {stream}/{group}", error=str(e))+ return False++ async def stream_read_group(+ self,+ group: str,+ consumer: str,+ streams: Dict[str, str],+ count: int = 1,+ block: Optional[int] = None+ ) -> Optional[List[Any]]:+ """Read from streams using consumer group.++ Args:+ group: Consumer group name+ consumer: Consumer name (unique per worker)+ streams: Dict of stream_name -> last_id (use '>' for new pending messages)+ count: Maximum messages to read+ block: Milliseconds to block++ Returns:+ List of messages or None+ """+ try:+ if self.use_redis and self.redis and self._streams_available:+ result = await self.redis.xreadgroup(+ group, consumer, streams,+ count=count, block=block+ )+ return result+ return None+ except Exception as e:+ error_str = str(e).lower()+ # Timeout errors are expected during blocking reads - log at debug level+ if "timeout" in error_str or "timed out" in error_str:+ logger.debug(f"Stream read group timeout: {group}/{consumer}", error=str(e))+ else:+ logger.error(f"Stream read group failed: {group}/{consumer}", error=str(e))+ return None++ async def stream_ack(self, stream: str, group: str, *msg_ids: str) -> int:+ """Acknowledge messages in consumer group.++ Args:+ stream: Stream name+ group: Consumer group name+ msg_ids: Message IDs to acknowledge++ Returns:+ Number of messages acknowledged+ """+ try:+ if self.use_redis and self.redis:+ count = await self.redis.xack(stream, group, *msg_ids)+ return count+ return 0+ except Exception as e:+ logger.error(f"Stream ack failed: {stream}/{group}", error=str(e))+ return 0++ async def stream_delete(self, stream: str, *msg_ids: str) -> int:+ """Delete messages from stream.++ Args:+ stream: Stream name+ msg_ids: Message IDs to delete++ Returns:+ Number of messages deleted+ """+ try:+ if self.use_redis and self.redis:+ count = await self.redis.xdel(stream, *msg_ids)+ return count+ return 0+ except Exception as e:+ logger.error(f"Stream delete failed: {stream}", error=str(e))+ return 0++ def is_redis_available(self) -> bool:+ """Check if Redis is available and connected."""+ return self.use_redis and self.redis is not None++ def is_streams_available(self) -> bool:+ """Check if Redis Streams are available (for trigger nodes).++ Returns True only if Redis is connected AND supports Streams commands.+ This is checked once during startup to avoid runtime failures.+ """+ return self.use_redis and self.redis is not None and self._streams_available\ No newline at end of filediff --git a/server/core/config.py b/server/core/config.pynew file mode 100644index 00000000..00b6b2a8--- /dev/null+++ b/server/core/config.py@@ -0,0 +1,110 @@+"""Environment-driven configuration with Pydantic v2."""++from typing import List, Literal, Optional+from pathlib import Path+from pydantic import Field, field_validator+from pydantic_settings import BaseSettings+++class Settings(BaseSettings):+ """Application settings driven entirely by environment variables."""++ # Server Configuration+ host: str = Field(env="HOST")+ port: int = Field(env="PORT", ge=1024, le=65535)+ debug: bool = Field(default=False, env="DEBUG")+ workers: int = Field(default=1, env="WORKERS", ge=1, le=8)++ # Authentication+ auth_mode: Literal["single", "multi"] = Field(default="single", env="AUTH_MODE")+ jwt_secret_key: str = Field(env="JWT_SECRET_KEY", min_length=32)+ jwt_expire_minutes: int = Field(default=10080, env="JWT_EXPIRE_MINUTES", ge=60) # 7 days+ jwt_cookie_name: str = Field(default="machina_token", env="JWT_COOKIE_NAME")+ jwt_cookie_secure: bool = Field(default=False, env="JWT_COOKIE_SECURE") # True in production+ jwt_cookie_samesite: Literal["lax", "strict", "none"] = Field(default="lax", env="JWT_COOKIE_SAMESITE")++ # Security+ secret_key: str = Field(env="SECRET_KEY", min_length=32)+ cors_origins: List[str] = Field(env="CORS_ORIGINS")++ # Database Configuration+ database_url: str = Field(env="DATABASE_URL")+ database_echo: bool = Field(default=False, env="DATABASE_ECHO")+ database_pool_size: int = Field(default=20, env="DATABASE_POOL_SIZE", ge=5, le=100)+ database_max_overflow: int = Field(default=30, env="DATABASE_MAX_OVERFLOW", ge=10, le=100)++ # Cache Configuration+ redis_url: Optional[str] = Field(default=None, env="REDIS_URL")+ redis_enabled: bool = Field(default=False, env="REDIS_ENABLED")+ cache_ttl: int = Field(default=3600, env="CACHE_TTL", ge=60)++ # Execution Engine+ dlq_enabled: bool = Field(default=False, env="DLQ_ENABLED")++ # API Keys (all optional, injected at runtime)+ google_maps_api_key: Optional[str] = Field(default=None, env="GOOGLE_MAPS_API_KEY")+ openai_api_key: Optional[str] = Field(default=None, env="OPENAI_API_KEY")+ anthropic_api_key: Optional[str] = Field(default=None, env="ANTHROPIC_API_KEY")+ google_ai_api_key: Optional[str] = Field(default=None, env="GOOGLE_AI_API_KEY")++ # WhatsApp Service URL (Flask service)+ whatsapp_service_url: str = Field(default="http://localhost:5000", env="WHATSAPP_SERVICE_URL")++ # WebSocket Configuration+ websocket_url: str = Field(default="", env="WEBSOCKET_URL")+ websocket_api_key: Optional[str] = Field(default=None, env="WEBSOCKET_API_KEY")++ # API Key Security+ api_key_encryption_key: str = Field(env="API_KEY_ENCRYPTION_KEY", min_length=32)+ api_key_cache_ttl: int = Field(default=2592000, env="API_KEY_CACHE_TTL", ge=3600)++ # Logging+ log_level: str = Field(default="INFO", env="LOG_LEVEL")+ log_format: str = Field(default="json", env="LOG_FORMAT")+ log_file: Optional[str] = Field(default=None, env="LOG_FILE")++ # Rate Limiting+ rate_limit_enabled: bool = Field(default=True, env="RATE_LIMIT_ENABLED")+ rate_limit_requests: int = Field(default=100, env="RATE_LIMIT_REQUESTS", ge=10)+ rate_limit_window: int = Field(default=60, env="RATE_LIMIT_WINDOW", ge=10)++ # Service Timeouts+ ai_timeout: int = Field(default=30, env="AI_TIMEOUT", ge=5, le=300)+ ai_max_retries: int = Field(default=3, env="AI_MAX_RETRIES", ge=0, le=5)+ ai_retry_delay: float = Field(default=1.0, env="AI_RETRY_DELAY", ge=0.1, le=10.0)++ maps_timeout: int = Field(default=10, env="MAPS_TIMEOUT", ge=5, le=60)+ maps_max_requests_per_second: int = Field(default=50, env="MAPS_MAX_RPS", ge=1, le=1000)++ # Health Check+ health_check_interval: int = Field(default=30, env="HEALTH_CHECK_INTERVAL", ge=10)++ @field_validator("database_url")+ @classmethod+ def validate_database_url(cls, v):+ """Ensure database directory exists for SQLite."""+ if v and v.startswith("sqlite"):+ if ":///" in v:+ db_path = v.split("///")[1]+ Path(db_path).parent.mkdir(parents=True, exist_ok=True)+ return v+++ @property+ def is_development(self) -> bool:+ """Check if running in development mode."""+ return self.debug++ @property+ def is_production(self) -> bool:+ """Check if running in production mode."""+ return not self.debug++ model_config = {+ "env_file": ".env",+ "env_file_encoding": "utf-8",+ "case_sensitive": False,+ "extra": "forbid",+ "env_parse_none_str": "none",+ "env_nested_delimiter": "__",+ }\ No newline at end of filediff --git a/server/core/container.py b/server/core/container.pynew file mode 100644index 00000000..8425f6ea--- /dev/null+++ b/server/core/container.py@@ -0,0 +1,91 @@+"""Dependency injection container for the application."""++from dependency_injector import containers, providers+from dependency_injector.wiring import Provide, inject++from core.config import Settings+from core.database import Database+from core.cache import CacheService+from services.ai import AIService+from services.maps import MapsService+from services.workflow import WorkflowService+from services.auth import AuthService+from services.text import TextService+from services.android_service import AndroidService+from services.user_auth import UserAuthService+++class Container(containers.DeclarativeContainer):+ """Application dependency injection container."""++ # Configuration+ config = providers.Configuration()++ # Settings+ settings = providers.Singleton(+ Settings,+ )++ # Database (needed by CacheService for SQLite fallback)+ database = providers.Singleton(+ Database,+ settings=settings+ )++ # Cache service (uses Redis when available, SQLite otherwise)+ cache = providers.Singleton(+ CacheService,+ settings=settings,+ database=database+ )++ # Services+ auth_service = providers.Factory(+ AuthService,+ cache=cache,+ database=database,+ settings=settings+ )++ user_auth_service = providers.Factory(+ UserAuthService,+ database=database,+ settings=settings+ )++ ai_service = providers.Factory(+ AIService,+ auth_service=auth_service,+ database=database,+ cache=cache,+ settings=settings+ )++ maps_service = providers.Factory(+ MapsService,+ auth_service=auth_service,+ settings=settings+ )++ text_service = providers.Factory(+ TextService+ )++ android_service = providers.Factory(+ AndroidService+ )++ workflow_service = providers.Singleton(+ WorkflowService,+ database=database,+ ai_service=ai_service,+ maps_service=maps_service,+ text_service=text_service,+ android_service=android_service,+ cache=cache,+ settings=settings+ )+++# Global container instance+container = Container()\ No newline at end of filediff --git a/server/core/database.py b/server/core/database.pynew file mode 100644index 00000000..9eba651c--- /dev/null+++ b/server/core/database.py@@ -0,0 +1,759 @@+"""Modern async database service with SQLModel and SQLAlchemy 2.0."""++from datetime import datetime, timedelta, timezone+from typing import Dict, Any, List, Optional+from sqlmodel import SQLModel, select, Session+from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker+from sqlalchemy.exc import IntegrityError+from contextlib import asynccontextmanager++from core.config import Settings+from models.database import NodeParameter, Workflow, Execution, APIKey, APIKeyValidation, NodeOutput, ConversationMessage+from models.cache import CacheEntry # SQLite-backed cache for Redis alternative+from models.auth import User # Import User model to ensure table creation+from core.logging import get_logger++logger = get_logger(__name__)+++class Database:+ """Async database service with SQLModel."""++ def __init__(self, settings: Settings):+ self.settings = settings+ self.engine = None+ self.async_session = None++ async def startup(self):+ """Initialize database connection and create tables."""+ try:+ # Disable verbose database and asyncio logging+ import logging+ logging.getLogger("aiosqlite").setLevel(logging.WARNING)+ logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)+ logging.getLogger("sqlalchemy.dialects").setLevel(logging.WARNING)+ logging.getLogger("sqlalchemy.pool").setLevel(logging.WARNING)++ # Create async engine+ self.engine = create_async_engine(+ self.settings.database_url,+ echo=self.settings.database_echo,+ pool_size=self.settings.database_pool_size,+ max_overflow=self.settings.database_max_overflow,+ future=True+ )++ # Create session factory+ self.async_session = async_sessionmaker(+ bind=self.engine,+ class_=AsyncSession,+ expire_on_commit=False+ )++ # Create tables+ async with self.engine.begin() as conn:+ await conn.run_sync(SQLModel.metadata.create_all)++ logger.info("Database initialized successfully")++ except Exception as e:+ logger.error("Database startup failed", error=str(e))+ raise++ async def shutdown(self):+ """Close database connections."""+ if self.engine:+ await self.engine.dispose()+ logger.info("Database connections closed")++ @asynccontextmanager+ async def get_session(self):+ """Get async database session."""+ if not self.async_session:+ raise RuntimeError("Database not initialized")++ async with self.async_session() as session:+ try:+ yield session+ except Exception:+ await session.rollback()+ raise+ finally:+ await session.close()++ # ============================================================================+ # Node Parameters+ # ============================================================================++ async def save_node_parameters(self, node_id: str, parameters: Dict[str, Any]) -> bool:+ """Save or update node parameters."""+ try:+ async with self.get_session() as session:+ # Try to get existing parameter+ stmt = select(NodeParameter).where(NodeParameter.node_id == node_id)+ result = await session.execute(stmt)+ existing = result.scalar_one_or_none()++ if existing:+ existing.parameters = parameters+ else:+ existing = NodeParameter(+ node_id=node_id,+ parameters=parameters+ )+ session.add(existing)++ await session.commit()+ return True++ except Exception as e:+ logger.error("Failed to save node parameters", node_id=node_id, error=str(e))+ return False++ async def get_node_parameters(self, node_id: str) -> Optional[Dict[str, Any]]:+ """Get node parameters."""+ try:+ async with self.get_session() as session:+ stmt = select(NodeParameter).where(NodeParameter.node_id == node_id)+ result = await session.execute(stmt)+ parameter = result.scalar_one_or_none()++ return parameter.parameters if parameter else None++ except Exception as e:+ logger.error("Failed to get node parameters", node_id=node_id, error=str(e))+ return None++ async def delete_node_parameters(self, node_id: str) -> bool:+ """Delete node parameters."""+ try:+ async with self.get_session() as session:+ stmt = select(NodeParameter).where(NodeParameter.node_id == node_id)+ result = await session.execute(stmt)+ parameter = result.scalar_one_or_none()++ if parameter:+ await session.delete(parameter)+ await session.commit()++ return True++ except Exception as e:+ logger.error("Failed to delete node parameters", node_id=node_id, error=str(e))+ return False++ # ============================================================================+ # Workflows+ # ============================================================================++ async def save_workflow(self, workflow_id: str, name: str, data: Dict[str, Any],+ description: Optional[str] = None) -> bool:+ """Save or update workflow."""+ try:+ async with self.get_session() as session:+ stmt = select(Workflow).where(Workflow.id == workflow_id)+ result = await session.execute(stmt)+ existing = result.scalar_one_or_none()++ if existing:+ existing.name = name+ existing.description = description+ existing.data = data+ else:+ existing = Workflow(+ id=workflow_id,+ name=name,+ description=description,+ data=data+ )+ session.add(existing)++ await session.commit()+ return True++ except Exception as e:+ logger.error("Failed to save workflow", workflow_id=workflow_id, error=str(e))+ return False++ async def get_workflow(self, workflow_id: str) -> Optional[Workflow]:+ """Get workflow by ID."""+ try:+ async with self.get_session() as session:+ stmt = select(Workflow).where(Workflow.id == workflow_id)+ result = await session.execute(stmt)+ return result.scalar_one_or_none()++ except Exception as e:+ logger.error("Failed to get workflow", workflow_id=workflow_id, error=str(e))+ return None++ async def get_all_workflows(self) -> List[Workflow]:+ """Get all workflows."""+ try:+ async with self.get_session() as session:+ stmt = select(Workflow).order_by(Workflow.updated_at.desc())+ result = await session.execute(stmt)+ return result.scalars().all()++ except Exception as e:+ logger.error("Failed to get all workflows", error=str(e))+ return []++ async def delete_workflow(self, workflow_id: str) -> bool:+ """Delete workflow."""+ try:+ async with self.get_session() as session:+ stmt = select(Workflow).where(Workflow.id == workflow_id)+ result = await session.execute(stmt)+ workflow = result.scalar_one_or_none()++ if workflow:+ await session.delete(workflow)+ await session.commit()++ return True++ except Exception as e:+ logger.error("Failed to delete workflow", workflow_id=workflow_id, error=str(e))+ return False++ # ============================================================================+ # Executions+ # ============================================================================++ async def save_execution(self, execution_id: str, workflow_id: str, node_id: str,+ status: str, result: Optional[Dict[str, Any]] = None,+ error: Optional[str] = None, execution_time: Optional[float] = None) -> bool:+ """Save execution result."""+ try:+ async with self.get_session() as session:+ execution = Execution(+ id=execution_id,+ workflow_id=workflow_id,+ node_id=node_id,+ status=status,+ result=result,+ error=error,+ execution_time=execution_time+ )+ session.add(execution)+ await session.commit()+ return True++ except Exception as e:+ logger.error("Failed to save execution", execution_id=execution_id, error=str(e))+ return False++ async def get_execution(self, execution_id: str) -> Optional[Execution]:+ """Get execution by ID."""+ try:+ async with self.get_session() as session:+ stmt = select(Execution).where(Execution.id == execution_id)+ result = await session.execute(stmt)+ return result.scalar_one_or_none()++ except Exception as e:+ logger.error("Failed to get execution", execution_id=execution_id, error=str(e))+ return None++ # ============================================================================+ # API Keys+ # ============================================================================++ async def save_api_key(self, key_id: str, provider: str, session_id: str,+ key_encrypted: str, key_hash: str,+ models: Optional[List[str]] = None) -> bool:+ """Save encrypted API key."""+ logger.info(f"Database save_api_key called with key_id: {key_id}, provider: {provider}")++ try:+ async with self.get_session() as session:+ api_key = APIKey(+ id=key_id,+ provider=provider,+ session_id=session_id,+ key_encrypted=key_encrypted,+ key_hash=key_hash,+ models={"models": models} if models else None,+ last_validated=datetime.now(timezone.utc)+ )+ session.add(api_key)+ await session.commit()+ logger.info(f"Successfully saved new API key: {key_id}")+ return True++ except IntegrityError as e:+ logger.info(f"API key {key_id} already exists, attempting update. Error: {str(e)}")+ # Key already exists, update it+ try:+ async with self.get_session() as session:+ stmt = select(APIKey).where(APIKey.id == key_id)+ result = await session.execute(stmt)+ existing = result.scalar_one_or_none()++ if existing:+ logger.info(f"Found existing API key {key_id}, updating...")+ existing.key_encrypted = key_encrypted+ existing.key_hash = key_hash+ existing.models = {"models": models} if models else None+ existing.last_validated = datetime.now(timezone.utc)+ await session.commit()+ logger.info(f"Successfully updated API key: {key_id}")+ return True+ else:+ logger.error(f"Could not find existing API key {key_id} for update")+ return False+ except Exception as update_e:+ logger.error(f"Failed to update API key {key_id}", error=str(update_e))+ return False++ except Exception as e:+ logger.error("Failed to save API key", provider=provider, error=str(e))+ import traceback+ logger.error("Full traceback", traceback=traceback.format_exc())+ return False++ async def get_api_key(self, key_id: str) -> Optional[APIKey]:+ """Get API key by ID."""+ try:+ async with self.get_session() as session:+ stmt = select(APIKey).where(APIKey.id == key_id)+ result = await session.execute(stmt)+ return result.scalar_one_or_none()++ except Exception as e:+ logger.error("Failed to get API key", key_id=key_id, error=str(e))+ return None++ async def get_api_key_by_provider(self, provider: str, session_id: str = "default") -> Optional[APIKey]:+ """Get API key by provider and session."""+ try:+ async with self.get_session() as session:+ stmt = select(APIKey).where(+ APIKey.provider == provider,+ APIKey.session_id == session_id,+ APIKey.is_valid == True+ )+ result = await session.execute(stmt)+ return result.scalar_one_or_none()++ except Exception as e:+ logger.error("Failed to get API key by provider", provider=provider, error=str(e))+ return None++ async def delete_api_key(self, provider: str, session_id: str = "default") -> bool:+ """Delete API key."""+ try:+ async with self.get_session() as session:+ stmt = select(APIKey).where(+ APIKey.provider == provider,+ APIKey.session_id == session_id+ )+ result = await session.execute(stmt)+ api_key = result.scalar_one_or_none()++ if api_key:+ await session.delete(api_key)+ await session.commit()+ logger.debug("API key deleted", provider=provider, session_id=session_id)++ return True++ except Exception as e:+ logger.error("Failed to delete API key", provider=provider, error=str(e))+ return False++ # ============================================================================+ # API Key Validation Cache+ # ============================================================================++ async def save_api_key_validation(self, key_hash: str) -> bool:+ """Save API key validation status."""+ try:+ async with self.get_session() as session:+ validation = APIKeyValidation(+ key_hash=key_hash,+ validated=True+ )+ session.add(validation)+ await session.commit()+ return True++ except IntegrityError:+ # Already exists, update timestamp+ async with self.get_session() as session:+ stmt = select(APIKeyValidation).where(APIKeyValidation.key_hash == key_hash)+ result = await session.execute(stmt)+ existing = result.scalar_one_or_none()++ if existing:+ existing.timestamp = datetime.now(timezone.utc)+ await session.commit()+ return True+ return False++ except Exception as e:+ logger.error("Failed to save API key validation", key_hash=key_hash, error=str(e))+ return False++ async def is_api_key_validated(self, key_hash: str) -> bool:+ """Check if API key is validated."""+ try:+ async with self.get_session() as session:+ stmt = select(APIKeyValidation).where(APIKeyValidation.key_hash == key_hash)+ result = await session.execute(stmt)+ validation = result.scalar_one_or_none()+ return validation is not None and validation.validated++ except Exception as e:+ logger.error("Failed to check API key validation", key_hash=key_hash, error=str(e))+ return False++ # ============================================================================+ # Node Outputs+ # ============================================================================++ async def save_node_output(self, node_id: str, session_id: str, output_name: str,+ data: Dict[str, Any]) -> bool:+ """Save or update node output."""+ try:+ async with self.get_session() as session:+ # Try to get existing output+ stmt = select(NodeOutput).where(+ NodeOutput.node_id == node_id,+ NodeOutput.session_id == session_id,+ NodeOutput.output_name == output_name+ )+ result = await session.execute(stmt)+ existing = result.scalar_one_or_none()++ action = "updated"+ if existing:+ existing.data = data+ else:+ action = "inserted"+ existing = NodeOutput(+ node_id=node_id,+ session_id=session_id,+ output_name=output_name,+ data=data+ )+ session.add(existing)++ await session.commit()+ logger.info("[DB] Node output saved", action=action, node_id=node_id, session_id=session_id, output_name=output_name)+ return True++ except Exception as e:+ logger.error("Failed to save node output", node_id=node_id, error=str(e))+ import traceback+ traceback.print_exc()+ return False++ async def get_node_output(self, node_id: str, session_id: str = "default",+ output_name: str = "output_0") -> Optional[Dict[str, Any]]:+ """Get node output data."""+ try:+ async with self.get_session() as session:+ stmt = select(NodeOutput).where(+ NodeOutput.node_id == node_id,+ NodeOutput.session_id == session_id,+ NodeOutput.output_name == output_name+ )+ result = await session.execute(stmt)+ output = result.scalar_one_or_none()++ return output.data if output else None++ except Exception as e:+ logger.error("Failed to get node output", node_id=node_id, error=str(e))+ return None++ async def delete_node_output(self, node_id: str) -> int:+ """Delete all outputs for a node (any session). Returns count deleted."""+ try:+ async with self.get_session() as session:+ stmt = select(NodeOutput).where(NodeOutput.node_id == node_id)+ result = await session.execute(stmt)+ outputs = result.scalars().all()++ count = len(outputs)+ for output in outputs:+ await session.delete(output)++ await session.commit()+ logger.info("Deleted node outputs", node_id=node_id, count=count)+ return count++ except Exception as e:+ logger.error("Failed to delete node output", node_id=node_id, error=str(e))+ return 0++ async def clear_session_outputs(self, session_id: str = "default") -> int:+ """Clear all outputs for a session. Returns count deleted."""+ try:+ async with self.get_session() as session:+ stmt = select(NodeOutput).where(NodeOutput.session_id == session_id)+ result = await session.execute(stmt)+ outputs = result.scalars().all()++ count = len(outputs)+ for output in outputs:+ await session.delete(output)++ await session.commit()+ logger.info("Cleared session outputs", session_id=session_id, count=count)+ return count++ except Exception as e:+ logger.error("Failed to clear session outputs", session_id=session_id, error=str(e))+ return 0++ # ============================================================================+ # Conversation Messages (AI Memory)+ # ============================================================================++ async def add_conversation_message(self, session_id: str, role: str, content: str) -> bool:+ """Add a message to conversation history."""+ try:+ async with self.get_session() as session:+ message = ConversationMessage(+ session_id=session_id,+ role=role,+ content=content+ )+ session.add(message)+ await session.commit()+ logger.info(f"[Memory] Added {role} message to session '{session_id}'")+ return True++ except Exception as e:+ logger.error("Failed to add conversation message", session_id=session_id, error=str(e))+ return False++ async def get_conversation_messages(self, session_id: str, window_size: Optional[int] = None) -> List[Dict[str, Any]]:+ """Get conversation messages, optionally limited to last N."""+ try:+ async with self.get_session() as session:+ stmt = select(ConversationMessage).where(+ ConversationMessage.session_id == session_id+ ).order_by(ConversationMessage.created_at.asc())++ result = await session.execute(stmt)+ messages = result.scalars().all()++ # Apply window limit if specified+ if window_size and window_size > 0:+ messages = messages[-window_size:]++ return [+ {+ "role": m.role,+ "content": m.content,+ "timestamp": m.created_at.isoformat()+ }+ for m in messages+ ]++ except Exception as e:+ logger.error("Failed to get conversation messages", session_id=session_id, error=str(e))+ return []++ async def clear_conversation(self, session_id: str) -> int:+ """Clear all messages in a conversation session. Returns count deleted."""+ try:+ async with self.get_session() as session:+ stmt = select(ConversationMessage).where(+ ConversationMessage.session_id == session_id+ )+ result = await session.execute(stmt)+ messages = result.scalars().all()++ count = len(messages)+ for message in messages:+ await session.delete(message)++ await session.commit()+ logger.info(f"[Memory] Cleared {count} messages from session '{session_id}'")+ return count++ except Exception as e:+ logger.error("Failed to clear conversation", session_id=session_id, error=str(e))+ return 0++ async def get_all_conversation_sessions(self) -> List[Dict[str, Any]]:+ """Get info about all conversation sessions."""+ try:+ async with self.get_session() as session:+ # Get distinct session IDs with message count+ from sqlalchemy import func as sql_func+ stmt = select(+ ConversationMessage.session_id,+ sql_func.count(ConversationMessage.id).label('message_count'),+ sql_func.min(ConversationMessage.created_at).label('created_at')+ ).group_by(ConversationMessage.session_id)++ result = await session.execute(stmt)+ rows = result.all()++ return [+ {+ "session_id": row.session_id,+ "message_count": row.message_count,+ "created_at": row.created_at.isoformat() if row.created_at else None+ }+ for row in rows+ ]++ except Exception as e:+ logger.error("Failed to get conversation sessions", error=str(e))+ return []++ # ============================================================================+ # Cache Entries (SQLite-backed Redis alternative)+ # ============================================================================++ async def get_cache_entry(self, key: str) -> Optional[str]:+ """Get cache value by key. Returns None if expired or not found."""+ import time+ try:+ async with self.get_session() as session:+ stmt = select(CacheEntry).where(CacheEntry.key == key)+ result = await session.execute(stmt)+ entry = result.scalar_one_or_none()++ if not entry:+ return None++ # Check expiration+ if entry.expires_at and entry.expires_at < time.time():+ # Entry expired - delete it+ await session.delete(entry)+ await session.commit()+ return None++ return entry.value++ except Exception as e:+ logger.error("Failed to get cache entry", key=key, error=str(e))+ return None++ async def set_cache_entry(self, key: str, value: str, ttl: Optional[int] = None) -> bool:+ """Set cache value with optional TTL in seconds."""+ import time+ try:+ expires_at = time.time() + ttl if ttl else None++ async with self.get_session() as session:+ # Try to get existing entry+ stmt = select(CacheEntry).where(CacheEntry.key == key)+ result = await session.execute(stmt)+ existing = result.scalar_one_or_none()++ if existing:+ existing.value = value+ existing.expires_at = expires_at+ existing.created_at = time.time()+ else:+ entry = CacheEntry(+ key=key,+ value=value,+ expires_at=expires_at,+ created_at=time.time()+ )+ session.add(entry)++ await session.commit()+ return True++ except Exception as e:+ logger.error("Failed to set cache entry", key=key, error=str(e))+ return False++ async def delete_cache_entry(self, key: str) -> bool:+ """Delete cache entry by key."""+ try:+ async with self.get_session() as session:+ stmt = select(CacheEntry).where(CacheEntry.key == key)+ result = await session.execute(stmt)+ entry = result.scalar_one_or_none()++ if entry:+ await session.delete(entry)+ await session.commit()++ return True++ except Exception as e:+ logger.error("Failed to delete cache entry", key=key, error=str(e))+ return False++ async def delete_cache_pattern(self, pattern: str) -> int:+ """Delete cache entries matching pattern (uses SQL LIKE)."""+ try:+ # Convert glob pattern to SQL LIKE pattern+ sql_pattern = pattern.replace("*", "%")++ async with self.get_session() as session:+ stmt = select(CacheEntry).where(CacheEntry.key.like(sql_pattern))+ result = await session.execute(stmt)+ entries = result.scalars().all()++ count = len(entries)+ for entry in entries:+ await session.delete(entry)++ await session.commit()+ logger.debug("Deleted cache entries", pattern=pattern, count=count)+ return count++ except Exception as e:+ logger.error("Failed to delete cache pattern", pattern=pattern, error=str(e))+ return 0++ async def cleanup_expired_cache(self) -> int:+ """Remove all expired cache entries. Returns count deleted."""+ import time+ try:+ async with self.get_session() as session:+ stmt = select(CacheEntry).where(+ CacheEntry.expires_at.isnot(None),+ CacheEntry.expires_at < time.time()+ )+ result = await session.execute(stmt)+ entries = result.scalars().all()++ count = len(entries)+ for entry in entries:+ await session.delete(entry)++ await session.commit()+ if count > 0:+ logger.info("Cleaned up expired cache entries", count=count)+ return count++ except Exception as e:+ logger.error("Failed to cleanup expired cache", error=str(e))+ return 0++ async def cache_exists(self, key: str) -> bool:+ """Check if cache key exists and is not expired."""+ import time+ try:+ async with self.get_session() as session:+ stmt = select(CacheEntry).where(CacheEntry.key == key)+ result = await session.execute(stmt)+ entry = result.scalar_one_or_none()++ if not entry:+ return False++ # Check expiration+ if entry.expires_at and entry.expires_at < time.time():+ return False++ return True++ except Exception as e:+ logger.error("Failed to check cache exists", key=key, error=str(e))+ return False\ No newline at end of filediff --git a/server/core/logging.py b/server/core/logging.pynew file mode 100644index 00000000..6378d8a0--- /dev/null+++ b/server/core/logging.py@@ -0,0 +1,116 @@+"""Modern structured logging configuration."""++import sys+import structlog+import logging+from pathlib import Path+from typing import Any, Dict+from core.config import Settings+++def configure_logging(settings: Settings) -> None:+ """Configure structured logging based on settings."""++ # Set up log file if specified+ if settings.log_file:+ log_path = Path(settings.log_file)+ log_path.parent.mkdir(parents=True, exist_ok=True)++ # Configure file handler+ file_handler = logging.FileHandler(log_path)+ file_handler.setLevel(getattr(logging, settings.log_level.upper()))++ # Configure console handler+ console_handler = logging.StreamHandler(sys.stdout)+ console_handler.setLevel(getattr(logging, settings.log_level.upper()))++ # Configure root logger+ logging.basicConfig(+ level=getattr(logging, settings.log_level.upper()),+ handlers=[console_handler, file_handler],+ format="%(message)s"+ )+ else:+ # Console only+ logging.basicConfig(+ format="%(message)s",+ stream=sys.stdout,+ level=getattr(logging, settings.log_level.upper())+ )++ # Configure structlog+ processors = [+ structlog.stdlib.filter_by_level,+ structlog.stdlib.add_log_level,+ structlog.stdlib.PositionalArgumentsFormatter(),+ structlog.processors.StackInfoRenderer(),+ structlog.processors.format_exc_info,+ structlog.processors.UnicodeDecoder(),+ ]++ # Add appropriate renderer based on format+ if settings.log_format == "json":+ processors.insert(0, structlog.processors.TimeStamper(fmt="iso"))+ processors.insert(0, structlog.stdlib.add_logger_name)+ processors.append(structlog.processors.JSONRenderer())+ else:+ # Console format with timestamp+ processors.insert(0, structlog.processors.TimeStamper(fmt="%H:%M:%S"))+ processors.append(structlog.dev.ConsoleRenderer(+ colors=False, # No ANSI colors for cleaner output+ pad_event=35,+ exception_formatter=structlog.dev.plain_traceback+ ))++ structlog.configure(+ processors=processors,+ context_class=dict,+ logger_factory=structlog.stdlib.LoggerFactory(),+ wrapper_class=structlog.stdlib.BoundLogger,+ cache_logger_on_first_use=True,+ )+++def get_logger(name: str) -> structlog.BoundLogger:+ """Get a structured logger instance."""+ return structlog.get_logger(name)+++def log_execution_time(logger: structlog.BoundLogger, operation: str,+ start_time: float, end_time: float, **kwargs) -> None:+ """Log execution time with additional context."""+ execution_time = end_time - start_time+ logger.info(+ "Operation completed",+ operation=operation,+ execution_time_seconds=round(execution_time, 4),+ **kwargs+ )+++def log_api_call(logger: structlog.BoundLogger, provider: str, model: str,+ operation: str, success: bool, **kwargs) -> None:+ """Log API calls with standardized format."""+ logger.info(+ "API call completed",+ provider=provider,+ model=model,+ operation=operation,+ success=success,+ **kwargs+ )+++def log_cache_operation(logger: structlog.BoundLogger, operation: str,+ key: str, hit: bool = None, **kwargs) -> None:+ """Log cache operations."""+ log_data = {+ "operation": operation,+ "cache_key": key,+ **kwargs+ }++ if hit is not None:+ log_data["cache_hit"] = hit++ logger.debug("Cache operation", **log_data)\ No newline at end of filediff --git a/server/main.py b/server/main.pynew file mode 100644index 00000000..9177e998--- /dev/null+++ b/server/main.py@@ -0,0 +1,206 @@+"""+Modern FastAPI backend for React Flow workflow automation platform.++Refactored with dependency injection, modular services, and clean architecture.+"""++# Performance: Install uvloop if available (Linux/macOS only)+try:+ import uvloop+ uvloop.install()+except ImportError:+ pass # Windows - uvloop not available, use default asyncio++from datetime import datetime+from contextlib import asynccontextmanager++from fastapi import FastAPI+from fastapi.middleware.cors import CORSMiddleware+from fastapi.responses import ORJSONResponse++from core.container import container+from core.config import Settings+from core.logging import configure_logging, get_logger+from routers import workflow, database, maps, nodejs_compat, android, websocket, webhook, auth++# Initialize settings and logging+settings = Settings()+configure_logging(settings)+logger = get_logger(__name__)++# Suppress noisy loggers+import logging+logging.getLogger("apscheduler").setLevel(logging.WARNING)+logging.getLogger("apscheduler.scheduler").setLevel(logging.WARNING)+logging.getLogger("apscheduler.executors").setLevel(logging.WARNING)+logging.getLogger("uvicorn").setLevel(logging.WARNING)+logging.getLogger("uvicorn.access").setLevel(logging.WARNING)+logging.getLogger("uvicorn.error").setLevel(logging.WARNING)+logging.getLogger("watchfiles").setLevel(logging.WARNING)+++@asynccontextmanager+async def lifespan(app: FastAPI):+ """Application lifespan management."""+ # Startup+ logger.info("Starting React Flow Python Services")++ # Wire dependency injection+ container.wire(modules=[+ "routers.workflow",+ "routers.database",+ "routers.maps",+ "routers.nodejs_compat",+ "routers.android",+ "routers.websocket",+ "routers.webhook",+ "routers.auth",+ "middleware.auth"+ ])++ # Start services+ await container.database().startup()+ await container.cache().startup()++ # Initialize event waiter with cache service for Redis Streams support+ from services import event_waiter+ event_waiter.set_cache_service(container.cache())++ # Start APScheduler for cron jobs+ from services.scheduler import start_scheduler, shutdown_scheduler+ start_scheduler()++ # Initialize execution engine recovery sweeper+ from services.execution import (+ ExecutionCache,+ RecoverySweeper,+ set_recovery_sweeper,+ )+ execution_cache = ExecutionCache(container.cache())+ recovery_sweeper = RecoverySweeper(execution_cache)+ set_recovery_sweeper(recovery_sweeper)++ # Scan for incomplete executions on startup+ if settings.redis_enabled:+ incomplete = await recovery_sweeper.scan_on_startup()+ if incomplete:+ logger.info("Found incomplete executions on startup",+ count=len(incomplete),+ execution_ids=incomplete)++ # Start background recovery sweeper+ await recovery_sweeper.start()+ logger.info("Execution recovery sweeper started")++ logger.info("Services started successfully")+ yield++ # Shutdown+ # Stop recovery sweeper first+ if settings.redis_enabled:+ await recovery_sweeper.stop()+ logger.info("Execution recovery sweeper stopped")++ shutdown_scheduler() # Stop APScheduler+ await container.cache().shutdown()+ await container.database().shutdown()+ logger.info("Services shutdown complete")+++# Create FastAPI app+app = FastAPI(+ title="React Flow Python Services",+ version="3.0.0",+ description="Modern workflow automation backend with AI and Maps integration",+ lifespan=lifespan,+ default_response_class=ORJSONResponse+)++# Add exception handler middleware BEFORE CORS to catch all errors+from fastapi import Request, status+from fastapi.responses import JSONResponse+from starlette.middleware.base import BaseHTTPMiddleware++class CatchAllExceptionsMiddleware(BaseHTTPMiddleware):+ async def dispatch(self, request: Request, call_next):+ try:+ return await call_next(request)+ except Exception as e:+ import traceback+ traceback.print_exc()+ logger.error(f"Unhandled exception: {type(e).__name__}: {str(e)}", exc_info=True)+ return JSONResponse(+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ content={+ "success": False,+ "error": f"{type(e).__name__}: {str(e)}",+ "detail": "Internal server error"+ }+ )++app.add_middleware(CatchAllExceptionsMiddleware)++# Add Auth middleware (checks JWT cookie for protected routes)+from middleware.auth import AuthMiddleware+app.add_middleware(AuthMiddleware)++# Add CORS middleware (must be AFTER exception middleware)+logger.info("Configuring CORS middleware",+ origins_count=len(settings.cors_origins),+ origins=settings.cors_origins)+app.add_middleware(+ CORSMiddleware,+ allow_origins=settings.cors_origins,+ allow_credentials=True,+ allow_methods=["*"],+ allow_headers=["*"],+ expose_headers=["*"],+)++# Include routers+app.include_router(auth.router) # Auth routes (login, register, logout, status)+app.include_router(nodejs_compat.router) # Node.js compatibility (includes root endpoints)+app.include_router(workflow.router)+app.include_router(database.router)+app.include_router(maps.router)+app.include_router(android.router)+app.include_router(websocket.router)+app.include_router(webhook.router)++[email protected]("/health")+async def health_check():+ """Detailed health check."""+ from services import event_waiter+ from services.execution import get_recovery_sweeper++ sweeper = get_recovery_sweeper()++ return {+ "status": "OK",+ "service": "python",+ "version": "3.1.0", # Bumped for execution engine+ "environment": "development" if settings.debug else "production",+ "redis_enabled": settings.redis_enabled,+ "event_waiter_mode": event_waiter.get_backend_mode(),+ "execution_engine": {+ "enabled": settings.redis_enabled,+ "recovery_sweeper": sweeper is not None and sweeper._running,+ },+ "timestamp": datetime.now().isoformat()+ }+++if __name__ == "__main__":+ import uvicorn+ logger.info("Starting React Flow Python Services",+ host=settings.host, port=settings.port, debug=settings.debug)+ uvicorn.run(+ "main:app",+ host=settings.host,+ port=settings.port,+ reload=settings.debug,+ reload_dirs=["."] if settings.debug else None,+ reload_excludes=["*.pyc", "__pycache__", "*.log", "*.db"] if settings.debug else None,+ workers=1 if settings.debug else settings.workers+ )\ No newline at end of filediff --git a/server/middleware/__init__.py b/server/middleware/__init__.pynew file mode 100644index 00000000..c07b4c61--- /dev/null+++ b/server/middleware/__init__.py@@ -0,0 +1,5 @@+"""Middleware package for FastAPI application."""++from middleware.auth import AuthMiddleware++__all__ = ["AuthMiddleware"]diff --git a/server/middleware/auth.py b/server/middleware/auth.pynew file mode 100644index 00000000..30a20778--- /dev/null+++ b/server/middleware/auth.py@@ -0,0 +1,78 @@+"""Authentication middleware for route protection."""++import logging+from fastapi import Request, HTTPException+from fastapi.responses import JSONResponse+from starlette.middleware.base import BaseHTTPMiddleware++from core.container import container++logger = logging.getLogger(__name__)++# Public routes that don't require authentication+PUBLIC_PATHS = frozenset([+ "/health",+ "/docs",+ "/openapi.json",+ "/redoc",+ "/api/auth/status",+ "/api/auth/login",+ "/api/auth/register",+ "/api/auth/logout",+])++# Path prefixes that are public+PUBLIC_PREFIXES = (+ "/webhook/",+)+++class AuthMiddleware(BaseHTTPMiddleware):+ """Middleware to protect routes requiring authentication."""++ async def dispatch(self, request: Request, call_next):+ path = request.url.path++ # Allow public paths+ if self._is_public_path(path):+ return await call_next(request)++ # Get settings and token+ settings = container.settings()+ token = request.cookies.get(settings.jwt_cookie_name)++ if not token:+ return JSONResponse(+ status_code=401,+ content={"detail": "Not authenticated"}+ )++ # Verify token+ user_auth = container.user_auth_service()+ payload = user_auth.verify_token(token)++ if not payload:+ return JSONResponse(+ status_code=401,+ content={"detail": "Invalid or expired session"}+ )++ # Attach user info to request state for downstream handlers+ request.state.user_id = payload.get("sub")+ request.state.user_email = payload.get("email")+ request.state.is_owner = payload.get("is_owner", False)++ return await call_next(request)++ def _is_public_path(self, path: str) -> bool:+ """Check if path is public (no auth required)."""+ # Exact match+ if path in PUBLIC_PATHS:+ return True++ # Prefix match+ for prefix in PUBLIC_PREFIXES:+ if path.startswith(prefix):+ return True++ return Falsediff --git a/server/models/__init__.py b/server/models/__init__.pynew file mode 100644index 00000000..ffa92f95--- /dev/null+++ b/server/models/__init__.py@@ -0,0 +1 @@+# Database models\ No newline at end of filediff --git a/server/models/auth.py b/server/models/auth.pynew file mode 100644index 00000000..c91811b3--- /dev/null+++ b/server/models/auth.py@@ -0,0 +1,52 @@+"""User authentication models."""++from datetime import datetime, timezone+from typing import Optional+from sqlmodel import SQLModel, Field, Column, DateTime+from sqlalchemy import func+import bcrypt+++class User(SQLModel, table=True):+ """User account for authentication."""++ __tablename__ = "users"++ id: Optional[int] = Field(default=None, primary_key=True)+ email: str = Field(unique=True, index=True, max_length=255)+ password_hash: str = Field(max_length=255)+ display_name: str = Field(max_length=100)+ is_owner: bool = Field(default=False) # First user in single-owner mode+ is_active: bool = Field(default=True)+ created_at: datetime = Field(+ default_factory=lambda: datetime.now(timezone.utc),+ sa_column=Column(DateTime(timezone=True), server_default=func.now())+ )+ last_login: Optional[datetime] = Field(+ default=None,+ sa_column=Column(DateTime(timezone=True), nullable=True)+ )++ def set_password(self, password: str) -> None:+ """Hash and set password using bcrypt."""+ salt = bcrypt.gensalt()+ self.password_hash = bcrypt.hashpw(password.encode('utf-8'), salt).decode('utf-8')++ def verify_password(self, password: str) -> bool:+ """Verify password against stored hash."""+ return bcrypt.checkpw(+ password.encode('utf-8'),+ self.password_hash.encode('utf-8')+ )++ @classmethod+ def create(cls, email: str, password: str, display_name: str, is_owner: bool = False) -> "User":+ """Factory method to create a user with hashed password."""+ user = cls(+ email=email.lower().strip(),+ password_hash="", # Will be set below+ display_name=display_name.strip(),+ is_owner=is_owner+ )+ user.set_password(password)+ return userdiff --git a/server/models/cache.py b/server/models/cache.pynew file mode 100644index 00000000..3589ca57--- /dev/null+++ b/server/models/cache.py@@ -0,0 +1,24 @@+"""SQLite-backed cache model for key-value storage with TTL.++Follows n8n pattern where SQLite is sufficient for single-process deployments,+with Redis used only for distributed queue mode.+"""++import time+from typing import Optional+from sqlmodel import SQLModel, Field+++class CacheEntry(SQLModel, table=True):+ """Generic key-value cache with optional expiration.++ Used as Redis alternative for local development (no Docker required).+ Production can use Redis for better performance at scale.+ """++ __tablename__ = "cache_entries"++ key: str = Field(primary_key=True, max_length=512)+ value: str = Field(max_length=1000000) # JSON serialized, up to 1MB+ expires_at: Optional[float] = Field(default=None, index=True) # Unix timestamp+ created_at: float = Field(default_factory=time.time)diff --git a/server/models/database.py b/server/models/database.pynew file mode 100644index 00000000..5f54f702--- /dev/null+++ b/server/models/database.py@@ -0,0 +1,136 @@+"""SQLModel database models and tables."""++from datetime import datetime, timezone+from typing import Optional, Dict, Any+from sqlmodel import SQLModel, Field, Column, DateTime, JSON+from sqlalchemy import func+++class NodeParameter(SQLModel, table=True):+ """Node parameters storage."""++ __tablename__ = "node_parameters"++ id: Optional[int] = Field(default=None, primary_key=True)+ node_id: str = Field(index=True, unique=True, max_length=255)+ parameters: Dict[str, Any] = Field(sa_column=Column(JSON))+ created_at: datetime = Field(+ default_factory=lambda: datetime.now(timezone.utc),+ sa_column=Column(DateTime(timezone=True), server_default=func.now())+ )+ updated_at: datetime = Field(+ default_factory=lambda: datetime.now(timezone.utc),+ sa_column=Column(DateTime(timezone=True), onupdate=func.now())+ )+++class Workflow(SQLModel, table=True):+ """Workflow definitions."""++ __tablename__ = "workflows"++ id: str = Field(primary_key=True, max_length=255)+ name: str = Field(max_length=255)+ description: Optional[str] = Field(default=None, max_length=1000)+ data: Dict[str, Any] = Field(sa_column=Column(JSON))+ created_at: datetime = Field(+ default_factory=lambda: datetime.now(timezone.utc),+ sa_column=Column(DateTime(timezone=True), server_default=func.now())+ )+ updated_at: datetime = Field(+ default_factory=lambda: datetime.now(timezone.utc),+ sa_column=Column(DateTime(timezone=True), onupdate=func.now())+ )+++class Execution(SQLModel, table=True):+ """Workflow execution history."""++ __tablename__ = "executions"++ id: str = Field(primary_key=True, max_length=255)+ workflow_id: str = Field(foreign_key="workflows.id", max_length=255)+ node_id: str = Field(max_length=255)+ status: str = Field(default="pending", max_length=50)+ result: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))+ error: Optional[str] = Field(default=None, max_length=2000)+ execution_time: Optional[float] = Field(default=None)+ created_at: datetime = Field(+ default_factory=lambda: datetime.now(timezone.utc),+ sa_column=Column(DateTime(timezone=True), server_default=func.now())+ )+++class APIKey(SQLModel, table=True):+ """Encrypted API key storage."""++ __tablename__ = "api_keys"++ id: str = Field(primary_key=True, max_length=255)+ provider: str = Field(max_length=50)+ session_id: str = Field(default="default", max_length=255)+ key_encrypted: str = Field(max_length=1000)+ key_hash: str = Field(max_length=64, index=True)+ models: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))+ is_valid: bool = Field(default=True)+ last_validated: datetime = Field(+ default_factory=lambda: datetime.now(timezone.utc),+ sa_column=Column(DateTime(timezone=True))+ )+ created_at: datetime = Field(+ default_factory=lambda: datetime.now(timezone.utc),+ sa_column=Column(DateTime(timezone=True), server_default=func.now())+ )+ updated_at: datetime = Field(+ default_factory=lambda: datetime.now(timezone.utc),+ sa_column=Column(DateTime(timezone=True), onupdate=func.now())+ )+++class APIKeyValidation(SQLModel, table=True):+ """API key validation cache."""++ __tablename__ = "api_key_validations"++ id: Optional[int] = Field(default=None, primary_key=True)+ key_hash: str = Field(unique=True, max_length=64, index=True)+ validated: bool = Field(default=True)+ timestamp: datetime = Field(+ default_factory=lambda: datetime.now(timezone.utc),+ sa_column=Column(DateTime(timezone=True), server_default=func.now())+ )+++class NodeOutput(SQLModel, table=True):+ """Node execution output storage - persisted across server restarts."""++ __tablename__ = "node_outputs"++ id: Optional[int] = Field(default=None, primary_key=True)+ node_id: str = Field(index=True, max_length=255)+ session_id: str = Field(default="default", max_length=255)+ output_name: str = Field(default="output_0", max_length=100)+ data: Dict[str, Any] = Field(sa_column=Column(JSON))+ created_at: datetime = Field(+ default_factory=lambda: datetime.now(timezone.utc),+ sa_column=Column(DateTime(timezone=True), server_default=func.now())+ )+ updated_at: datetime = Field(+ default_factory=lambda: datetime.now(timezone.utc),+ sa_column=Column(DateTime(timezone=True), onupdate=func.now())+ )+++class ConversationMessage(SQLModel, table=True):+ """AI conversation message storage - persisted across server restarts."""++ __tablename__ = "conversation_messages"++ id: Optional[int] = Field(default=None, primary_key=True)+ session_id: str = Field(index=True, max_length=255)+ role: str = Field(max_length=20) # 'human' or 'ai'+ content: str = Field(max_length=50000) # Large content support+ created_at: datetime = Field(+ default_factory=lambda: datetime.now(timezone.utc),+ sa_column=Column(DateTime(timezone=True), server_default=func.now())+ )\ No newline at end of filediff --git a/server/models/nodes.py b/server/models/nodes.pynew file mode 100644index 00000000..dc537cd9--- /dev/null+++ b/server/models/nodes.py@@ -0,0 +1,447 @@+"""Pydantic models for node validation with discriminated unions.++This module provides type-safe node validation using Pydantic v2 discriminated unions.+Benefits:+- O(1) hash map lookup vs O(n) sequential validation+- Better error messages (identifies exact expected variant)+- Type safety with IDE autocompletion+- Automatic API documentation generation+"""++from typing import Literal, Union, Annotated, Optional, Dict, Any, List+from pydantic import BaseModel, Field, TypeAdapter+from datetime import datetime++from constants import (+ AI_CHAT_MODEL_TYPES,+ AI_AGENT_TYPES,+ AI_MEMORY_TYPES,+ GOOGLE_MAPS_TYPES,+ ANDROID_SERVICE_NODE_TYPES,+ ANDROID_SETUP_TYPES,+ WHATSAPP_TYPES,+ CHAT_TYPES,+ CODE_EXECUTOR_TYPES,+ HTTP_TYPES,+ TEXT_TYPES,+ WORKFLOW_CONTROL_TYPES,+ TRIGGER_TYPES,+)+++# =============================================================================+# BASE MODELS+# =============================================================================++class BaseNodeParams(BaseModel):+ """Base class for all node parameters."""+ model_config = {"extra": "allow"} # Allow extra fields for flexibility+++# =============================================================================+# AI NODE MODELS+# =============================================================================++class AIChatModelParams(BaseNodeParams):+ """Parameters for AI chat model nodes (OpenAI, Anthropic, Gemini)."""+ type: Literal["openaiChatModel", "anthropicChatModel", "geminiChatModel"]+ prompt: str = ""+ model: str = ""+ temperature: float = Field(default=0.7, ge=0.0, le=2.0)+ max_tokens: Optional[int] = Field(default=1000, alias="maxTokens")+ system_prompt: Optional[str] = Field(default="", alias="systemMessage")+ api_key: Optional[str] = Field(default=None, alias="apiKey")+++class AIAgentParams(BaseNodeParams):+ """Parameters for AI agent node."""+ type: Literal["aiAgent"]+ prompt: str = ""+ provider: Literal["openai", "anthropic", "gemini"] = "openai"+ model: str = ""+ temperature: float = Field(default=0.7, ge=0.0, le=2.0)+ max_tokens: Optional[int] = Field(default=1000, alias="maxTokens")+ system_message: Optional[str] = Field(default="You are a helpful assistant", alias="systemMessage")+ api_key: Optional[str] = Field(default=None, alias="apiKey")+++class SimpleMemoryParams(BaseNodeParams):+ """Parameters for simple memory node."""+ type: Literal["simpleMemory"]+ session_id: str = Field(default="default", alias="sessionId")+ memory_type: Literal["buffer", "window"] = Field(default="buffer", alias="memoryType")+ window_size: int = Field(default=10, alias="windowSize", ge=1, le=100)+ clear_on_run: bool = Field(default=False, alias="clearOnRun")+++# =============================================================================+# GOOGLE MAPS NODE MODELS+# =============================================================================++class CreateMapParams(BaseNodeParams):+ """Parameters for create map node."""+ type: Literal["createMap"]+ center_lat: float = Field(default=0.0, alias="centerLat")+ center_lng: float = Field(default=0.0, alias="centerLng")+ zoom: int = Field(default=10, ge=1, le=20)+ map_type: Literal["roadmap", "satellite", "terrain", "hybrid"] = Field(default="roadmap", alias="mapType")+ api_key: Optional[str] = Field(default=None, alias="apiKey")+++class AddLocationsParams(BaseNodeParams):+ """Parameters for add locations (geocoding) node."""+ type: Literal["addLocations"]+ address: str = ""+ api_key: Optional[str] = Field(default=None, alias="apiKey")+++class ShowNearbyPlacesParams(BaseNodeParams):+ """Parameters for show nearby places node."""+ type: Literal["showNearbyPlaces"]+ latitude: float = 0.0+ longitude: float = 0.0+ radius: int = Field(default=1000, ge=1, le=50000)+ place_type: str = Field(default="restaurant", alias="placeType")+ api_key: Optional[str] = Field(default=None, alias="apiKey")+++# =============================================================================+# ANDROID NODE MODELS+# =============================================================================++class AndroidDeviceSetupParams(BaseNodeParams):+ """Parameters for Android device setup node."""+ type: Literal["androidDeviceSetup"]+ connection_type: Literal["local", "remote"] = Field(default="local", alias="connection_type")+ device_id: str = Field(default="", alias="device_id")+ websocket_url: str = Field(default="", alias="websocket_url")+ port: int = Field(default=8888, ge=1, le=65535)+ auto_forward: bool = Field(default=True, alias="auto_forward")+ target_device_id: str = Field(default="", alias="target_device_id")+++class AndroidServiceParams(BaseNodeParams):+ """Parameters for Android service nodes (battery, network, wifi, etc.)."""+ type: str # Validated separately against ANDROID_SERVICE_NODE_TYPES+ service_id: str = Field(default="battery", alias="service_id")+ action: str = Field(default="status")+ parameters: Dict[str, Any] = Field(default_factory=dict)+ android_host: str = Field(default="localhost", alias="android_host")+ android_port: int = Field(default=8888, alias="android_port", ge=1, le=65535)+++# =============================================================================+# WHATSAPP NODE MODELS+# =============================================================================++class WhatsAppSendParams(BaseNodeParams):+ """Parameters for WhatsApp send message node."""+ type: Literal["whatsappSend"]+ phone_number: str = Field(default="", alias="phoneNumber")+ message: str = ""+ message_type: Literal["text", "image", "video", "audio", "document"] = Field(default="text", alias="messageType")+++class WhatsAppConnectParams(BaseNodeParams):+ """Parameters for WhatsApp connect node."""+ type: Literal["whatsappConnect"]+++class WhatsAppReceiveParams(BaseNodeParams):+ """Parameters for WhatsApp receive (trigger) node."""+ type: Literal["whatsappReceive"]+ message_type_filter: str = Field(default="all", alias="messageTypeFilter")+ sender_filter: str = Field(default="all", alias="filter")+ ignore_own: bool = Field(default=True, alias="ignoreOwnMessages")+ include_media: bool = Field(default=False, alias="includeMediaData")+++# =============================================================================+# CODE EXECUTOR NODE MODELS+# =============================================================================++class PythonExecutorParams(BaseNodeParams):+ """Parameters for Python code executor node."""+ type: Literal["pythonExecutor"]+ code: str = ""+ timeout: int = Field(default=30, ge=1, le=300)+++class JavaScriptExecutorParams(BaseNodeParams):+ """Parameters for JavaScript code executor node."""+ type: Literal["javascriptExecutor"]+ code: str = ""+ timeout: int = Field(default=30, ge=1, le=300)+++# =============================================================================+# HTTP NODE MODELS+# =============================================================================++class HttpRequestParams(BaseNodeParams):+ """Parameters for HTTP request node."""+ type: Literal["httpRequest"]+ url: str = ""+ method: Literal["GET", "POST", "PUT", "DELETE", "PATCH"] = "GET"+ headers: Dict[str, str] = Field(default_factory=dict)+ body: str = ""+ timeout: int = Field(default=30, ge=1, le=300)+++class WebhookTriggerParams(BaseNodeParams):+ """Parameters for webhook trigger node."""+ type: Literal["webhookTrigger"]+ path: str = ""+ method_filter: str = Field(default="all", alias="methodFilter")+ require_auth: bool = Field(default=False, alias="requireAuth")+++class WebhookResponseParams(BaseNodeParams):+ """Parameters for webhook response node."""+ type: Literal["webhookResponse"]+ status_code: int = Field(default=200, alias="statusCode", ge=100, le=599)+ content_type: str = Field(default="application/json", alias="contentType")+ body: str = ""+++# =============================================================================+# WORKFLOW CONTROL NODE MODELS+# =============================================================================++class StartNodeParams(BaseNodeParams):+ """Parameters for start node."""+ type: Literal["start"]+ initial_data: str = Field(default="{}", alias="initialData")+++class CronSchedulerParams(BaseNodeParams):+ """Parameters for cron scheduler node."""+ type: Literal["cronScheduler"]+ frequency: Literal["seconds", "minutes", "hours", "days", "weeks", "months", "once"] = "minutes"+ interval: int = Field(default=5, ge=1)+ interval_minutes: int = Field(default=5, alias="intervalMinutes", ge=1)+ interval_hours: int = Field(default=1, alias="intervalHours", ge=1)+ daily_time: str = Field(default="09:00", alias="dailyTime")+ weekly_time: str = Field(default="09:00", alias="weeklyTime")+ weekday: str = Field(default="1")+ monthly_time: str = Field(default="09:00", alias="monthlyTime")+ month_day: str = Field(default="1", alias="monthDay")+++class WorkflowTriggerParams(BaseNodeParams):+ """Parameters for workflow trigger node."""+ type: Literal["workflowTrigger"]+++# =============================================================================+# TEXT NODE MODELS+# =============================================================================++class TextGeneratorParams(BaseNodeParams):+ """Parameters for text generator node."""+ type: Literal["textGenerator"]+ template: str = ""+++class FileHandlerParams(BaseNodeParams):+ """Parameters for file handler node."""+ type: Literal["fileHandler"]+ action: Literal["read", "write", "append", "delete"] = "read"+ file_path: str = Field(default="", alias="filePath")+ content: str = ""+++# =============================================================================+# CHAT NODE MODELS+# =============================================================================++class ChatSendParams(BaseNodeParams):+ """Parameters for chat send node."""+ type: Literal["chatSend"]+ message: str = ""+++class ChatHistoryParams(BaseNodeParams):+ """Parameters for chat history node."""+ type: Literal["chatHistory"]+ limit: int = Field(default=50, ge=1, le=1000)+++# =============================================================================+# DISCRIMINATED UNION - All Node Types+# =============================================================================++# AI Nodes+AINodeParams = Annotated[+ Union[AIChatModelParams, AIAgentParams, SimpleMemoryParams],+ Field(discriminator="type")+]++# Maps Nodes+MapsNodeParams = Annotated[+ Union[CreateMapParams, AddLocationsParams, ShowNearbyPlacesParams],+ Field(discriminator="type")+]++# WhatsApp Nodes+WhatsAppNodeParams = Annotated[+ Union[WhatsAppSendParams, WhatsAppConnectParams, WhatsAppReceiveParams],+ Field(discriminator="type")+]++# Code Executor Nodes+CodeNodeParams = Annotated[+ Union[PythonExecutorParams, JavaScriptExecutorParams],+ Field(discriminator="type")+]++# HTTP Nodes+HttpNodeParams = Annotated[+ Union[HttpRequestParams, WebhookTriggerParams, WebhookResponseParams],+ Field(discriminator="type")+]++# Workflow Control Nodes+WorkflowNodeParams = Annotated[+ Union[StartNodeParams, CronSchedulerParams, WorkflowTriggerParams],+ Field(discriminator="type")+]++# Text Nodes+TextNodeParams = Annotated[+ Union[TextGeneratorParams, FileHandlerParams],+ Field(discriminator="type")+]++# Chat Nodes+ChatNodeParams = Annotated[+ Union[ChatSendParams, ChatHistoryParams],+ Field(discriminator="type")+]++# Master union of all known node types (excluding Android service which has dynamic types)+KnownNodeParams = Annotated[+ Union[+ # AI+ AIChatModelParams, AIAgentParams, SimpleMemoryParams,+ # Maps+ CreateMapParams, AddLocationsParams, ShowNearbyPlacesParams,+ # Android Setup+ AndroidDeviceSetupParams,+ WhatsAppSendParams, WhatsAppConnectParams, WhatsAppReceiveParams,+ # Code+ PythonExecutorParams, JavaScriptExecutorParams,+ # HTTP+ HttpRequestParams, WebhookTriggerParams, WebhookResponseParams,+ # Workflow+ StartNodeParams, CronSchedulerParams, WorkflowTriggerParams,+ # Text+ TextGeneratorParams, FileHandlerParams,+ # Chat+ ChatSendParams, ChatHistoryParams,+ ],+ Field(discriminator="type")+]+++# =============================================================================+# EXECUTION REQUEST MODELS+# =============================================================================++class NodeExecutionRequest(BaseModel):+ """Request model for node execution."""+ node_id: str = Field(..., alias="nodeId", min_length=1)+ node_type: str = Field(..., alias="nodeType", min_length=1)+ parameters: Dict[str, Any] = Field(default_factory=dict)+ nodes: Optional[List[Dict[str, Any]]] = None+ edges: Optional[List[Dict[str, Any]]] = None+ session_id: str = Field(default="default", alias="sessionId")++ model_config = {"populate_by_name": True}+++class NodeExecutionResponse(BaseModel):+ """Response model for node execution."""+ success: bool+ node_id: str+ node_type: str+ result: Optional[Dict[str, Any]] = None+ error: Optional[str] = None+ execution_time: float+ timestamp: str = Field(default_factory=lambda: datetime.now().isoformat())+++# =============================================================================+# VALIDATION HELPERS+# =============================================================================++# Create TypeAdapter for discriminated union (created once at module level for performance)+_known_node_adapter = TypeAdapter(KnownNodeParams)++# Set of all known node types for fallback detection+_all_known_types: set = None # Lazy initialized+++def _get_all_known_types() -> set:+ """Lazily get all known node types."""+ global _all_known_types+ if _all_known_types is None:+ _all_known_types = get_all_node_types()+ return _all_known_types+++def validate_node_params(node_type: str, params: Dict[str, Any]) -> BaseNodeParams:+ """Validate node parameters using the appropriate model.++ Uses Pydantic v2 discriminated unions for O(1) type lookup instead of+ sequential if/elif validation. The discriminator field 'type' routes+ to the correct model automatically.++ For known node types, validation errors are raised (e.g., temperature > 2.0).+ For unknown node types, falls back to BaseNodeParams (allows extensibility).++ Args:+ node_type: The node type string+ params: The parameters dictionary++ Returns:+ Validated parameters model (specific subclass based on node_type)++ Raises:+ ValidationError: If validation fails for a known node type+ """+ # Add type to params for discriminator+ params_with_type = {"type": node_type, **params}++ # Handle Android service nodes separately (dynamic types not in KnownNodeParams)+ if node_type in ANDROID_SERVICE_NODE_TYPES:+ return AndroidServiceParams(**params_with_type)++ # Check if this is a known type+ if node_type in _get_all_known_types():+ # Known type - use discriminated union (O(1) lookup)+ # ValidationError will be raised if params are invalid+ return _known_node_adapter.validate_python(params_with_type)+ else:+ # Unknown type - fall back to base model (allows extensibility)+ return BaseNodeParams(**params_with_type)+++def get_all_node_types() -> set:+ """Get set of all known node types."""+ return (+ AI_CHAT_MODEL_TYPES |+ AI_AGENT_TYPES |+ AI_MEMORY_TYPES |+ GOOGLE_MAPS_TYPES |+ ANDROID_SERVICE_NODE_TYPES |+ ANDROID_SETUP_TYPES |+ WHATSAPP_TYPES |+ CHAT_TYPES |+ CODE_EXECUTOR_TYPES |+ HTTP_TYPES |+ TEXT_TYPES |+ WORKFLOW_CONTROL_TYPES |+ TRIGGER_TYPES+ )diff --git a/server/requirements.txt b/server/requirements.txtnew file mode 100644index 00000000..a5468f2e--- /dev/null+++ b/server/requirements.txt@@ -0,0 +1,56 @@+# Core Framework+fastapi>=0.110.0+uvicorn[standard]>=0.27.0++# Performance optimization+uvloop>=0.19.0;sys_platform!='win32'+orjson>=3.10.0++# Database & ORM (Python 3.13 compatible versions)+sqlmodel>=0.0.18+sqlalchemy[asyncio]>=2.0.35+aiosqlite>=0.20.0++# Settings & Configuration+pydantic>=2.6.0+pydantic-settings>=2.2.0+python-dotenv>=1.0.0++# Dependency Injection+dependency-injector>=4.41.0++# Caching (Redis) - Python 3.13 compatible+redis>=5.0.0++# HTTP Client+httpx>=0.27.0++# WebSocket Client (for WhatsApp RPC)+websockets>=12.0++# QR Code Generation (for WhatsApp QR display)+qrcode[pil]>=7.4.0++# Logging+structlog>=23.2.0++# AI Providers (LangChain) - minimal versions+langchain-core>=0.1.40+langchain-openai>=0.1.0+langchain-anthropic>=0.1.5+langchain-google-genai>=1.0.0++# LangGraph - State machine for AI agents+langgraph>=1.0.0++# Google Services+googlemaps>=4.10.0++# Scheduling+APScheduler>=3.10.0++# Authentication+bcrypt>=4.1.0+python-jose[cryptography]>=3.3.0+email-validator>=2.0.0+diff --git a/server/routers/__init__.py b/server/routers/__init__.pynew file mode 100644index 00000000..4e602c7f--- /dev/null+++ b/server/routers/__init__.py@@ -0,0 +1 @@+# FastAPI route modules\ No newline at end of filediff --git a/server/routers/android.py b/server/routers/android.pynew file mode 100644index 00000000..733135e4--- /dev/null+++ b/server/routers/android.py@@ -0,0 +1,294 @@+"""Android System Services routes."""++from fastapi import APIRouter, Depends+from pydantic import BaseModel, Field+from typing import Dict, Any, Optional++from core.container import container+from services.android_service import AndroidService+from core.logging import get_logger++logger = get_logger(__name__)+router = APIRouter(prefix="/api/android", tags=["android"])+++class AndroidServiceRequest(BaseModel):+ """Request model for Android service execution."""+ service_id: str = Field(..., description="Android service ID (e.g., 'battery', 'network', 'app_launcher')")+ action: str = Field(..., description="Service action to perform (e.g., 'status', 'launch', 'list')")+ parameters: Dict[str, Any] = Field(default_factory=dict, description="Action-specific parameters")+ android_host: str = Field(default="localhost", description="Android device API host")+ android_port: int = Field(default=8888, description="Android device API port")++[email protected]("/execute")+async def execute_android_service(+ request: AndroidServiceRequest,+ android_service: AndroidService = Depends(lambda: container.android_service())+):+ """Execute an Android system service action.++ Examples:+ - Battery status: {"service_id": "battery", "action": "status"}+ - Launch app: {"service_id": "app_launcher", "action": "launch", "parameters": {"package_name": "com.android.settings"}}+ - List apps: {"service_id": "app_list", "action": "list", "parameters": {"include_system": false}}+ """+ logger.info(+ "[Android API] Executing service",+ service_id=request.service_id,+ action=request.action,+ android_host=request.android_host,+ android_port=request.android_port+ )++ result = await android_service.execute_service(+ node_id="api_call",+ service_id=request.service_id,+ action=request.action,+ parameters=request.parameters,+ android_host=request.android_host,+ android_port=request.android_port+ )++ return result++[email protected]("/status")+async def check_device_status(+ android_host: str = "localhost",+ android_port: int = 8888,+ android_service: AndroidService = Depends(lambda: container.android_service())+):+ """Check if Android device API is reachable."""+ logger.info(+ "[Android API] Checking device status",+ android_host=android_host,+ android_port=android_port+ )++ status = await android_service.check_device_status(+ android_host=android_host,+ android_port=android_port+ )++ return status++[email protected]("/services/{service_id}/actions")+async def get_service_actions(+ service_id: str,+ android_service: AndroidService = Depends(lambda: container.android_service())+):+ """Get available actions for a specific Android service.++ Returns list of action options that can be performed on the service.+ """+ logger.info(f"[Android API] Getting actions for service: {service_id}")++ actions = android_service.get_service_actions(service_id)++ if not actions:+ return {+ "success": False,+ "error": f"Unknown service: {service_id}",+ "actions": []+ }++ return {+ "success": True,+ "service_id": service_id,+ "actions": actions+ }++[email protected]("/services/{service_id}/actions/{action}/parameters")+async def get_action_parameters(+ service_id: str,+ action: str,+ android_service: AndroidService = Depends(lambda: container.android_service())+):+ """Get default parameters for a specific service action.++ Returns default parameter template that can be used as a starting point.+ """+ logger.info(f"[Android API] Getting parameters for: {service_id}/{action}")++ default_params = android_service.get_default_parameters(service_id, action)++ return {+ "success": True,+ "service_id": service_id,+ "action": action,+ "default_parameters": default_params+ }++[email protected]("/devices")+async def list_android_devices():+ """List all connected Android devices via ADB."""+ import subprocess+ try:+ # Run adb devices command+ result = subprocess.run(+ ["adb", "devices", "-l"],+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=5+ )++ devices = []+ lines = result.stdout.strip().split('\n')[1:] # Skip header "List of devices attached"++ for line in lines:+ if not line.strip():+ continue++ parts = line.split()+ if len(parts) >= 2:+ device_id = parts[0]+ state = parts[1]++ # Extract model and other info+ model = "Unknown"+ android_version = None++ for part in parts[2:]:+ if part.startswith("model:"):+ model = part.split(":")[1]+ elif part.startswith("device:"):+ pass # Can use this for device codename++ devices.append({+ "id": device_id,+ "state": state,+ "model": model,+ "android_version": android_version+ })++ return {+ "success": True,+ "devices": devices,+ "count": len(devices)+ }+ except FileNotFoundError:+ logger.error("[Android] ADB not found in PATH")+ return {+ "success": False,+ "error": "ADB not found. Please install Android SDK Platform Tools",+ "devices": []+ }+ except Exception as e:+ logger.error(f"[Android] Failed to list devices: {e}")+ return {+ "success": False,+ "error": str(e),+ "devices": []+ }++[email protected]("/port-forward")+async def setup_port_forwarding(+ device_id: str,+ local_port: int = 8888,+ device_port: int = 8888+):+ """Setup ADB port forwarding for Android device communication."""+ import subprocess+ try:+ # Setup port forwarding: adb -s device_id forward tcp:local_port tcp:device_port+ cmd = ["adb", "-s", device_id, "forward", f"tcp:{local_port}", f"tcp:{device_port}"]++ result = subprocess.run(+ cmd,+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=5+ )++ if result.returncode == 0:+ logger.info(+ f"[Android] Port forwarding setup: {device_id} tcp:{local_port} -> tcp:{device_port}"+ )+ return {+ "success": True,+ "device_id": device_id,+ "local_port": local_port,+ "device_port": device_port,+ "message": f"Port forwarding active: localhost:{local_port} -> device:{device_port}"+ }+ else:+ error_msg = result.stderr.strip() or result.stdout.strip()+ logger.error(f"[Android] Port forwarding failed: {error_msg}")+ return {+ "success": False,+ "error": error_msg+ }+ except FileNotFoundError:+ logger.error("[Android] ADB not found in PATH")+ return {+ "success": False,+ "error": "ADB not found. Please install Android SDK Platform Tools"+ }+ except Exception as e:+ logger.error(f"[Android] Port forwarding error: {e}")+ return {+ "success": False,+ "error": str(e)+ }++[email protected]("/health")+async def android_health_check():+ """Android service health check."""+ return {+ "status": "OK",+ "service": "android"+ }++[email protected]("/relay-status")+async def get_relay_connection_status():+ """Get relay connection status for remote Android devices.++ Returns connection status including whether a relay connection is active+ and the paired Android device.+ """+ try:+ from services.android import get_current_relay_client++ relay_client = get_current_relay_client()++ if relay_client and relay_client.is_connected():+ return {+ "success": True,+ "connected": True,+ "paired": relay_client.is_paired(),+ "connection_type": "relay",+ "device_id": relay_client.paired_device_id,+ "device_name": relay_client.paired_device_name,+ "session_token": relay_client.session_token,+ "qr_data": relay_client.qr_data if not relay_client.is_paired() else None,+ "status": "paired" if relay_client.is_paired() else "waiting_for_pairing"+ }+ else:+ return {+ "success": True,+ "connected": False,+ "paired": False,+ "connection_type": None,+ "device_id": None,+ "device_name": None,+ "status": "disconnected"+ }+ except Exception as e:+ logger.error(f"[Android] Failed to get relay status: {e}")+ return {+ "success": False,+ "connected": False,+ "error": str(e),+ "status": "error"+ }diff --git a/server/routers/auth.py b/server/routers/auth.pynew file mode 100644index 00000000..2d3e62bf--- /dev/null+++ b/server/routers/auth.py@@ -0,0 +1,203 @@+"""Authentication routes for user login, registration, and session management."""++from fastapi import APIRouter, Depends, HTTPException, Response, Request+from pydantic import BaseModel, EmailStr+from typing import Optional++from core.container import container+from core.config import Settings+from core.logging import get_logger+from services.user_auth import UserAuthService++logger = get_logger(__name__)+router = APIRouter(prefix="/api/auth", tags=["auth"])+++class RegisterRequest(BaseModel):+ email: EmailStr+ password: str+ display_name: str+++class LoginRequest(BaseModel):+ email: EmailStr+ password: str+++class UserResponse(BaseModel):+ id: int+ email: str+ display_name: str+ is_owner: bool+++def get_user_auth_service() -> UserAuthService:+ return container.user_auth_service()+++def get_settings() -> Settings:+ return container.settings()++[email protected]("/status")+async def get_auth_status(+ request: Request,+ user_auth: UserAuthService = Depends(get_user_auth_service),+ settings: Settings = Depends(get_settings)+):+ """+ Get authentication status.+ Returns auth mode and current user if authenticated.+ """+ status = user_auth.get_auth_status()++ # Check if user has a valid session+ token = request.cookies.get(settings.jwt_cookie_name)+ current_user = None++ if token:+ user = await user_auth.get_current_user(token)+ if user:+ current_user = {+ "id": user.id,+ "email": user.email,+ "display_name": user.display_name,+ "is_owner": user.is_owner+ }++ # Check if registration is available+ can_register = await user_auth.can_register()++ return {+ "auth_mode": status["auth_mode"],+ "authenticated": current_user is not None,+ "user": current_user,+ "can_register": can_register+ }++[email protected]("/register")+async def register(+ request: RegisterRequest,+ response: Response,+ user_auth: UserAuthService = Depends(get_user_auth_service),+ settings: Settings = Depends(get_settings)+):+ """+ Register a new user.+ In single-owner mode, only the first user can register.+ In multi-user mode, anyone can register.+ """+ user, error = await user_auth.register(+ email=request.email,+ password=request.password,+ display_name=request.display_name+ )++ if error:+ raise HTTPException(status_code=400, detail=error)++ # Create token and set cookie+ token = user_auth.create_access_token(user)+ response.set_cookie(+ key=settings.jwt_cookie_name,+ value=token,+ httponly=True,+ secure=settings.jwt_cookie_secure,+ samesite=settings.jwt_cookie_samesite,+ max_age=settings.jwt_expire_minutes * 60+ )++ return {+ "success": True,+ "user": {+ "id": user.id,+ "email": user.email,+ "display_name": user.display_name,+ "is_owner": user.is_owner+ }+ }++[email protected]("/login")+async def login(+ request: LoginRequest,+ response: Response,+ user_auth: UserAuthService = Depends(get_user_auth_service),+ settings: Settings = Depends(get_settings)+):+ """+ Login with email and password.+ Sets HttpOnly cookie with JWT token.+ """+ user, error = await user_auth.login(+ email=request.email,+ password=request.password+ )++ if error:+ raise HTTPException(status_code=401, detail=error)++ # Create token and set cookie+ token = user_auth.create_access_token(user)+ response.set_cookie(+ key=settings.jwt_cookie_name,+ value=token,+ httponly=True,+ secure=settings.jwt_cookie_secure,+ samesite=settings.jwt_cookie_samesite,+ max_age=settings.jwt_expire_minutes * 60+ )++ return {+ "success": True,+ "user": {+ "id": user.id,+ "email": user.email,+ "display_name": user.display_name,+ "is_owner": user.is_owner+ }+ }++[email protected]("/logout")+async def logout(+ response: Response,+ settings: Settings = Depends(get_settings)+):+ """+ Logout by clearing the auth cookie.+ """+ response.delete_cookie(+ key=settings.jwt_cookie_name,+ httponly=True,+ secure=settings.jwt_cookie_secure,+ samesite=settings.jwt_cookie_samesite+ )+ return {"success": True}++[email protected]("/me")+async def get_current_user(+ request: Request,+ user_auth: UserAuthService = Depends(get_user_auth_service),+ settings: Settings = Depends(get_settings)+):+ """+ Get current authenticated user.+ Requires valid session cookie.+ """+ token = request.cookies.get(settings.jwt_cookie_name)+ if not token:+ raise HTTPException(status_code=401, detail="Not authenticated")++ user = await user_auth.get_current_user(token)+ if not user:+ raise HTTPException(status_code=401, detail="Invalid or expired session")++ return {+ "id": user.id,+ "email": user.email,+ "display_name": user.display_name,+ "is_owner": user.is_owner+ }diff --git a/server/routers/database.py b/server/routers/database.pynew file mode 100644index 00000000..0a216821--- /dev/null+++ b/server/routers/database.py@@ -0,0 +1,151 @@+"""Database operations routes (replaces frontend storage)."""++from fastapi import APIRouter, Depends+from pydantic import BaseModel+from typing import Dict, Any, Optional, List++from core.container import container+from core.database import Database+from core.logging import get_logger++logger = get_logger(__name__)+router = APIRouter(prefix="/api/database", tags=["database"])+++class NodeParameterRequest(BaseModel):+ node_id: str+ parameters: Dict[str, Any]+++class WorkflowSaveRequest(BaseModel):+ workflow_id: str+ name: str+ data: Dict[str, Any]++[email protected]("/node-parameters")+async def save_node_parameters(+ request: NodeParameterRequest,+ database: Database = Depends(lambda: container.database())+):+ """Save node parameters (replaces frontend Dexie)."""+ try:+ success = await database.save_node_parameters(request.node_id, request.parameters)+ return {"success": success}+ except Exception as e:+ logger.error("Failed to save node parameters", error=str(e))+ return {"success": False, "error": str(e)}++[email protected]("/node-parameters/{node_id}")+async def get_node_parameters(+ node_id: str,+ database: Database = Depends(lambda: container.database())+):+ """Get node parameters (replaces frontend Dexie)."""+ try:+ parameters = await database.get_node_parameters(node_id)+ return {"success": True, "parameters": parameters}+ except Exception as e:+ logger.error("Failed to get node parameters", error=str(e))+ return {"success": False, "error": str(e)}++[email protected]("/node-parameters/{node_id}")+async def delete_node_parameters(+ node_id: str,+ database: Database = Depends(lambda: container.database())+):+ """Delete node parameters (replaces frontend Dexie)."""+ try:+ success = await database.delete_node_parameters(node_id)+ return {"success": success}+ except Exception as e:+ logger.error("Failed to delete node parameters", error=str(e))+ return {"success": False, "error": str(e)}+++# ============================================================================+# Workflow Operations+# ============================================================================+[email protected]("/workflows")+async def save_workflow(+ request: WorkflowSaveRequest,+ database: Database = Depends(lambda: container.database())+):+ """Save workflow to database."""+ try:+ success = await database.save_workflow(+ workflow_id=request.workflow_id,+ name=request.name,+ data=request.data+ )+ return {"success": success, "workflow_id": request.workflow_id}+ except Exception as e:+ logger.error("Failed to save workflow", error=str(e))+ return {"success": False, "error": str(e)}++[email protected]("/workflows")+async def get_all_workflows(+ database: Database = Depends(lambda: container.database())+):+ """Get all workflows."""+ try:+ workflows = await database.get_all_workflows()+ return {+ "success": True,+ "workflows": [+ {+ "id": w.id,+ "name": w.name,+ "nodeCount": len(w.data.get("nodes", [])) if w.data else 0,+ "createdAt": w.created_at.isoformat() if w.created_at else None,+ "lastModified": w.updated_at.isoformat() if w.updated_at else None+ }+ for w in workflows+ ]+ }+ except Exception as e:+ logger.error("Failed to get workflows", error=str(e))+ return {"success": False, "error": str(e)}++[email protected]("/workflows/{workflow_id}")+async def get_workflow(+ workflow_id: str,+ database: Database = Depends(lambda: container.database())+):+ """Get workflow by ID."""+ try:+ workflow = await database.get_workflow(workflow_id)+ if workflow:+ return {+ "success": True,+ "workflow": {+ "id": workflow.id,+ "name": workflow.name,+ "data": workflow.data,+ "createdAt": workflow.created_at.isoformat() if workflow.created_at else None,+ "lastModified": workflow.updated_at.isoformat() if workflow.updated_at else None+ }+ }+ return {"success": False, "error": "Workflow not found"}+ except Exception as e:+ logger.error("Failed to get workflow", error=str(e))+ return {"success": False, "error": str(e)}++[email protected]("/workflows/{workflow_id}")+async def delete_workflow(+ workflow_id: str,+ database: Database = Depends(lambda: container.database())+):+ """Delete workflow."""+ try:+ success = await database.delete_workflow(workflow_id)+ return {"success": success, "workflow_id": workflow_id}+ except Exception as e:+ logger.error("Failed to delete workflow", error=str(e))+ return {"success": False, "error": str(e)}\ No newline at end of filediff --git a/server/routers/maps.py b/server/routers/maps.pynew file mode 100644index 00000000..52a9f9d2--- /dev/null+++ b/server/routers/maps.py@@ -0,0 +1,142 @@+"""Google Maps service routes."""++from fastapi import APIRouter, Depends, HTTPException+from pydantic import BaseModel+from typing import Dict, Any, Optional+import httpx++from core.container import container+from services.maps import MapsService+from services.status_broadcaster import get_status_broadcaster+from core.logging import get_logger++logger = get_logger(__name__)+router = APIRouter(prefix="/python", tags=["maps"])+++class GoogleMapsRequest(BaseModel):+ node_id: str+ node_type: str+ parameters: Dict[str, Any]+ api_key: Optional[str] = None+++class ApiKeyValidationRequest(BaseModel):+ api_key: str++[email protected]("/maps/validate-key")+async def validate_google_maps_key(request: ApiKeyValidationRequest):+ """Validate Google Maps API key and broadcast status via WebSocket."""+ broadcaster = get_status_broadcaster()++ try:+ api_key = request.api_key.strip()+ if not api_key:+ await broadcaster.update_api_key_status(+ provider="google_maps",+ valid=False,+ message="API key is required"+ )+ raise HTTPException(status_code=400, detail="API key is required")++ # Test the API key with a simple geocoding request+ async with httpx.AsyncClient() as client:+ response = await client.get(+ "https://maps.googleapis.com/maps/api/geocode/json",+ params={+ "address": "1600 Amphitheatre Parkway, Mountain View, CA",+ "key": api_key+ },+ timeout=10.0+ )++ data = response.json()++ if data.get("status") == "OK":+ await broadcaster.update_api_key_status(+ provider="google_maps",+ valid=True,+ message="API key validated successfully"+ )+ return {+ "success": True,+ "valid": True,+ "message": "Google Maps API key is valid"+ }+ elif data.get("status") == "REQUEST_DENIED":+ error_msg = data.get("error_message", "Invalid API key")+ await broadcaster.update_api_key_status(+ provider="google_maps",+ valid=False,+ message=error_msg+ )+ return {+ "success": True,+ "valid": False,+ "message": error_msg+ }+ else:+ # Other statuses like ZERO_RESULTS still mean the key works+ await broadcaster.update_api_key_status(+ provider="google_maps",+ valid=True,+ message="API key validated"+ )+ return {+ "success": True,+ "valid": True,+ "message": f"API key is valid (status: {data.get('status')})"+ }++ except httpx.TimeoutException:+ await broadcaster.update_api_key_status(+ provider="google_maps",+ valid=False,+ message="Validation request timed out"+ )+ raise HTTPException(status_code=504, detail="Validation request timed out")+ except httpx.RequestError as e:+ await broadcaster.update_api_key_status(+ provider="google_maps",+ valid=False,+ message=f"Network error: {str(e)}"+ )+ raise HTTPException(status_code=503, detail=f"Network error: {str(e)}")+ except HTTPException:+ raise+ except Exception as e:+ logger.error(f"API key validation error: {e}")+ await broadcaster.update_api_key_status(+ provider="google_maps",+ valid=False,+ message=f"Validation failed: {str(e)}"+ )+ raise HTTPException(status_code=500, detail=f"Validation failed: {str(e)}")++[email protected]("/createmap/execute")+async def execute_createmap_node(+ request: GoogleMapsRequest,+ maps_service: MapsService = Depends(lambda: container.maps_service())+):+ """Execute Create Map node - Google Maps initialization."""+ return await maps_service.create_map(request.node_id, request.parameters)++[email protected]("/addlocations/execute")+async def execute_addlocations_node(+ request: GoogleMapsRequest,+ maps_service: MapsService = Depends(lambda: container.maps_service())+):+ """Execute Add Locations node - Google Maps Geocoding."""+ return await maps_service.geocode_location(request.node_id, request.parameters)++[email protected]("/shownearbyplaces/execute")+async def execute_shownearbyplaces_node(+ request: GoogleMapsRequest,+ maps_service: MapsService = Depends(lambda: container.maps_service())+):+ """Execute Show Nearby Places node - Google Places API."""+ return await maps_service.find_nearby_places(request.node_id, request.parameters)\ No newline at end of filediff --git a/server/routers/nodejs_compat.py b/server/routers/nodejs_compat.pynew file mode 100644index 00000000..f0533398--- /dev/null+++ b/server/routers/nodejs_compat.py@@ -0,0 +1,289 @@+"""Node.js API compatibility routes for seamless migration."""++from datetime import datetime+from uuid import uuid4+from fastapi import APIRouter, HTTPException, Depends+from pydantic import BaseModel+from typing import Dict, Any, List, Optional++from core.container import container+from core.database import Database+from services.workflow import WorkflowService+from core.logging import get_logger++logger = get_logger(__name__)+router = APIRouter(tags=["nodejs-compatibility"])+++# Pydantic models matching Node.js API+class NodeExecuteRequest(BaseModel):+ nodeId: str+ nodeType: str+ parameters: Optional[Dict[str, Any]] = {}+ nodes: Optional[List[Dict[str, Any]]] = []+ edges: Optional[List[Dict[str, Any]]] = []+++class WorkflowSaveRequest(BaseModel):+ name: str+ data: Dict[str, Any]+++# Health and status endpoints[email protected]("/")+async def root():+ """Node.js compatible root endpoint."""+ return {+ "message": "React Flow Project API Server",+ "status": "running",+ "version": "2.0.0-python",+ "endpoints": {+ "health": "/api/health",+ "workflows": "/api/workflows",+ "nodes": "/api/nodes",+ "execute": "/api/nodes/execute"+ },+ "services": {+ "main": "http://localhost:3010",+ "python": "http://localhost:3010"+ },+ "timestamp": datetime.now().isoformat()+ }++[email protected]("/api/health")+async def health_check():+ """Node.js compatible health check."""+ return {+ "status": "OK",+ "message": "React Flow Server is running",+ "timestamp": datetime.now().isoformat()+ }+++# Workflow management endpoints[email protected]("/api/workflows")+async def get_workflows(database: Database = Depends(lambda: container.database())):+ """Get all workflows (Node.js compatible)."""+ try:+ workflows = await database.get_all_workflows()+ return {"workflows": workflows}+ except Exception as e:+ logger.error("Failed to get workflows", error=str(e))+ return {"workflows": []}++[email protected]("/api/workflows")+async def save_workflow(+ request: WorkflowSaveRequest,+ database: Database = Depends(lambda: container.database())+):+ """Save workflow (Node.js compatible)."""+ try:+ workflow_id = str(int(datetime.now().timestamp() * 1000)) # Node.js style ID+ success = await database.save_workflow(+ workflow_id=workflow_id,+ name=request.name,+ data=request.data+ )++ if success:+ return {+ "success": True,+ "id": workflow_id,+ "message": "Workflow saved successfully"+ }+ else:+ raise HTTPException(status_code=500, detail="Failed to save workflow")++ except Exception as e:+ logger.error("Failed to save workflow", error=str(e))+ raise HTTPException(status_code=500, detail=str(e))++[email protected]("/api/workflows/{workflow_id}")+async def get_workflow(+ workflow_id: str,+ database: Database = Depends(lambda: container.database())+):+ """Get workflow by ID (Node.js compatible)."""+ try:+ workflow = await database.get_workflow(workflow_id)++ if workflow:+ return {+ "id": workflow.id,+ "name": workflow.name,+ "data": workflow.data+ }+ else:+ return {+ "id": workflow_id,+ "name": "Sample Workflow",+ "data": {"nodes": [], "edges": []}+ }++ except Exception as e:+ logger.error("Failed to get workflow", workflow_id=workflow_id, error=str(e))+ return {+ "id": workflow_id,+ "name": "Sample Workflow",+ "data": {"nodes": [], "edges": []}+ }+++# Main execution endpoint - Node.js compatible[email protected]("/api/nodes/execute")+async def execute_node(+ request: NodeExecuteRequest,+ workflow_service: WorkflowService = Depends(lambda: container.workflow_service())+):+ """Execute a single node (Node.js compatible)."""+ try:+ if not request.nodeId or not request.nodeType:+ raise HTTPException(status_code=400, detail="nodeId and nodeType are required")++ execution_id = str(uuid4())+ logger.info("Executing node", node_id=request.nodeId, execution_id=execution_id)++ # Execute the node using workflow service+ result = await workflow_service.execute_node(+ node_id=request.nodeId,+ node_type=request.nodeType,+ parameters=request.parameters or {},+ nodes=request.nodes or [],+ edges=request.edges or [],+ session_id="default"+ )++ # Transform result to match Node.js format+ if result.get("success"):+ return {+ "success": True,+ "executionId": execution_id,+ "nodeId": request.nodeId,+ "nodeType": request.nodeType,+ "result": result.get("result", {}),+ "executionTime": result.get("execution_time", 0),+ "timestamp": result.get("timestamp", datetime.now().isoformat())+ }+ else:+ return {+ "success": False,+ "executionId": execution_id,+ "nodeId": request.nodeId,+ "nodeType": request.nodeType,+ "error": result.get("error", "Unknown error"),+ "executionTime": result.get("execution_time", 0),+ "timestamp": result.get("timestamp", datetime.now().isoformat())+ }++ except Exception as e:+ logger.error("Node execution error", node_id=request.nodeId, error=str(e))+ raise HTTPException(status_code=500, detail=str(e))+++# Execution status and output endpoints[email protected]("/api/executions/{execution_id}")+async def get_execution_status(execution_id: str):+ """Get execution status (Node.js compatible)."""+ # For simplicity, return success status+ # In a full implementation, you'd track execution status+ return {+ "success": True,+ "executionId": execution_id,+ "status": "completed",+ "timestamp": datetime.now().isoformat()+ }++[email protected]("/api/nodes/{node_id}/output")+async def get_node_output(+ node_id: str,+ workflow_service: WorkflowService = Depends(lambda: container.workflow_service())+):+ """Get node output data (Node.js compatible)."""+ try:+ result = await workflow_service.get_workflow_node_output(node_id)++ if result.get("success"):+ return {+ "success": True,+ "nodeId": node_id,+ "output": result.get("data", {})+ }+ else:+ return {+ "success": False,+ "nodeId": node_id,+ "error": result.get("error", "Node output not found")+ }++ except Exception as e:+ logger.error("Get node output error", node_id=node_id, error=str(e))+ raise HTTPException(status_code=500, detail=str(e))++[email protected]("/api/executions/clear")+async def clear_execution_cache():+ """Clear execution cache (Node.js compatible)."""+ try:+ # Clear workflow service cache if implemented+ return {+ "success": True,+ "message": "Execution cache cleared"+ }+ except Exception as e:+ logger.error("Clear cache error", error=str(e))+ raise HTTPException(status_code=500, detail=str(e))+++# Legacy endpoint for backwards compatibility[email protected]("/api/execute/{node_id}")+async def legacy_execute_node(+ node_id: str,+ request: Dict[str, Any],+ workflow_service: WorkflowService = Depends(lambda: container.workflow_service())+):+ """Legacy execution endpoint (Node.js compatible)."""+ try:+ node_type = request.get("nodeType")+ if not node_type:+ raise HTTPException(status_code=400, detail="nodeType is required")++ execution_id = str(uuid4())++ result = await workflow_service.execute_node(+ node_id=node_id,+ node_type=node_type,+ parameters=request.get("parameters", {}),+ nodes=request.get("nodes", []),+ edges=request.get("edges", []),+ session_id="default"+ )++ # Return in Node.js format+ if result.get("success"):+ return {+ "success": True,+ "executionId": execution_id,+ "nodeId": node_id,+ "nodeType": node_type,+ "result": result.get("result", {}),+ "executionTime": result.get("execution_time", 0),+ "timestamp": result.get("timestamp", datetime.now().isoformat())+ }+ else:+ return {+ "success": False,+ "executionId": execution_id,+ "nodeId": node_id,+ "nodeType": node_type,+ "error": result.get("error", "Unknown error"),+ "executionTime": result.get("execution_time", 0),+ "timestamp": result.get("timestamp", datetime.now().isoformat())+ }++ except Exception as e:+ logger.error("Legacy execution error", node_id=node_id, error=str(e))+ raise HTTPException(status_code=500, detail=str(e))\ No newline at end of filediff --git a/server/routers/webhook.py b/server/routers/webhook.pynew file mode 100644index 00000000..910d0fd0--- /dev/null+++ b/server/routers/webhook.py@@ -0,0 +1,90 @@+"""Dynamic webhook endpoint router for incoming HTTP requests.++Works like WhatsApp trigger - uses broadcaster.send_custom_event() to dispatch+to event_waiter which resolves waiting trigger nodes.+"""+from fastapi import APIRouter, Request, HTTPException, Response+from fastapi.responses import JSONResponse+from typing import Dict, Any+import asyncio+import logging++from services.status_broadcaster import get_status_broadcaster++logger = logging.getLogger(__name__)+router = APIRouter(prefix="/webhook", tags=["webhook"])++# Pending responses: path -> asyncio.Future (for responseNode mode)+_pending_responses: Dict[str, asyncio.Future] = {}+++def resolve_webhook_response(node_id: str, response_data: dict):+ """Resolve a pending webhook response.++ Called by webhookResponse node execution to send response back to caller.+ Uses path from response_data to find the pending Future.+ """+ # Find pending response by path (stored when we started waiting)+ for path, future in list(_pending_responses.items()):+ if not future.done():+ future.set_result(response_data)+ logger.info(f"[Webhook] Response resolved for path: {path}")+ return++ logger.warning(f"[Webhook] No pending response found for node: {node_id}")++[email protected]_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH"])+async def handle_webhook(path: str, request: Request):+ """Handle incoming webhook requests.++ Dispatches webhook_received event to trigger waiting webhookTrigger nodes.+ Similar to how WhatsApp events dispatch to whatsappReceive nodes.+ """+ # Build webhook request data+ body = await request.body()+ json_body = None+ content_type = request.headers.get("content-type", "")++ if "application/json" in content_type and body:+ try:+ json_body = await request.json()+ except:+ pass++ webhook_data = {+ "method": request.method,+ "path": path,+ "headers": dict(request.headers),+ "query": dict(request.query_params),+ "body": body.decode('utf-8') if isinstance(body, bytes) else (body if body else ""),+ "json": json_body+ }++ logger.info(f"[Webhook] Received: {request.method} /webhook/{path}")++ # Dispatch event using broadcaster (same pattern as WhatsApp)+ broadcaster = get_status_broadcaster()+ await broadcaster.send_custom_event("webhook_received", webhook_data)++ # For now, always return immediate response+ # TODO: Support responseNode mode by storing Future and waiting+ return JSONResponse(+ content={+ "status": "received",+ "path": path,+ "message": "Webhook received and dispatched to workflow"+ },+ status_code=200+ )++[email protected]("/")+async def list_info():+ """Get webhook endpoint info."""+ return {+ "endpoint": "/webhook/{path}",+ "description": "Send HTTP requests to trigger webhookTrigger nodes",+ "usage": "Deploy a workflow with webhookTrigger node, then send requests to /webhook/{path}",+ "example": "POST /webhook/my-webhook with JSON body"+ }diff --git a/server/routers/websocket.py b/server/routers/websocket.pynew file mode 100644index 00000000..e7630dc5--- /dev/null+++ b/server/routers/websocket.py@@ -0,0 +1,1554 @@+"""WebSocket router for real-time bidirectional communication.++Handles WebSocket connections from frontend clients for ALL operations:+- Node parameters (get, save, delete)+- Node execution+- AI execution and model fetching+- API key validation and storage+- Android device operations+- Google Maps key validation+- Status broadcasts+"""++import time+import asyncio+import weakref+from typing import Dict, Any, Callable, Awaitable, Optional, Set+from datetime import datetime++from fastapi import APIRouter, WebSocket, WebSocketDisconnect+from services.status_broadcaster import get_status_broadcaster+from core.container import container+from core.logging import get_logger++logger = get_logger(__name__)++router = APIRouter(tags=["websocket"])++# =============================================================================+# Concurrent Send Protection+# =============================================================================+# Use WeakKeyDictionary to auto-cleanup when WebSocket is garbage collected+_send_locks: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()++# Track running handler tasks per WebSocket for cleanup on disconnect+_handler_tasks: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()+++async def _safe_send(websocket: WebSocket, data: dict):+ """Thread-safe WebSocket send with lock to prevent concurrent writes."""+ if websocket not in _send_locks:+ _send_locks[websocket] = asyncio.Lock()+ async with _send_locks[websocket]:+ try:+ await websocket.send_json(data)+ except Exception as e:+ logger.error(f"[WebSocket] Send error: {e}")+++# Type for message handlers+MessageHandler = Callable[[Dict[str, Any], WebSocket], Awaitable[Dict[str, Any]]]+++def ws_handler(*required_fields: str):+ """Simple decorator for WebSocket handlers. Validates required fields and wraps errors."""+ def decorator(func: MessageHandler) -> MessageHandler:+ async def wrapper(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ for field in required_fields:+ if not data.get(field):+ return {"success": False, "error": f"{field} required"}+ try:+ result = await func(data, websocket)+ if "success" not in result:+ result = {"success": True, **result}+ return result+ except Exception as e:+ logger.error(f"Handler error: {e}", exc_info=True)+ return {"success": False, "error": str(e)}+ return wrapper+ return decorator+++# ============================================================================+# Message Handlers+# ============================================================================++async def handle_ping(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Handle ping request."""+ return {"type": "pong", "timestamp": time.time()}+++async def handle_get_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get current full status."""+ broadcaster = get_status_broadcaster()+ return {"type": "full_status", "data": broadcaster.get_status()}+++async def handle_get_android_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get Android connection status."""+ broadcaster = get_status_broadcaster()+ return {"type": "android_status", "data": broadcaster.get_android_status()}+++async def handle_get_node_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get specific node status."""+ broadcaster = get_status_broadcaster()+ node_id = data.get("node_id")+ if node_id:+ status = broadcaster.get_node_status(node_id)+ return {"type": "node_status", "node_id": node_id, "data": status}+ return {"type": "error", "message": "node_id required"}+++async def handle_get_variable(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get variable value."""+ broadcaster = get_status_broadcaster()+ name = data.get("name")+ if name:+ value = broadcaster.get_variable(name)+ return {"type": "variable_update", "name": name, "value": value}+ return {"type": "error", "message": "name required"}+++# ============================================================================+# Node Parameters Handlers+# ============================================================================++@ws_handler("node_id")+async def handle_get_node_parameters(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get parameters for a specific node."""+ database = container.database()+ node_id = data["node_id"]+ parameters = await database.get_node_parameters(node_id)+ print(f"[GET_PARAMS] Node ID: {node_id}")+ print(f"[GET_PARAMS] Raw from DB: {parameters}")+ print(f"[GET_PARAMS] Code length: {len(parameters.get('code', '')) if parameters and 'code' in parameters else 'no code field'}")+ return {"node_id": node_id, "parameters": parameters or {}, "version": 1, "timestamp": time.time()}+++@ws_handler()+async def handle_get_all_node_parameters(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get parameters for multiple nodes."""+ database = container.database()+ result = {}+ for node_id in data.get("node_ids", []):+ parameters = await database.get_node_parameters(node_id)+ if parameters:+ result[node_id] = {"parameters": parameters, "version": 1}+ return {"parameters": result, "timestamp": time.time()}+++@ws_handler("node_id")+async def handle_save_node_parameters(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Save node parameters and broadcast to all clients."""+ database = container.database()+ broadcaster = get_status_broadcaster()+ node_id, parameters = data["node_id"], data.get("parameters", {})++ print(f"[SAVE_PARAMS] Node ID: {node_id}")+ print(f"[SAVE_PARAMS] Has 'code' key: {'code' in parameters}")+ if 'code' in parameters:+ print(f"[SAVE_PARAMS] Code length: {len(parameters.get('code', ''))}")+ await database.save_node_parameters(node_id, parameters)+ await broadcaster.broadcast({+ "type": "node_parameters_updated", "node_id": node_id,+ "parameters": parameters, "version": 1, "timestamp": time.time()+ })+ return {"node_id": node_id, "parameters": parameters, "version": 1, "timestamp": time.time()}+++@ws_handler("node_id")+async def handle_delete_node_parameters(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Delete node parameters."""+ database = container.database()+ await database.delete_node_parameters(data["node_id"])+ return {"node_id": data["node_id"]}+++# ============================================================================+# Node Execution Handlers+# ============================================================================++@ws_handler("node_id", "node_type")+async def handle_execute_node(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Execute a workflow node with per-workflow status scoping (n8n pattern)."""+ workflow_service = container.workflow_service()+ broadcaster = get_status_broadcaster()+ node_id, node_type = data["node_id"], data["node_type"]+ workflow_id = data.get("workflow_id") # Per-workflow isolation++ await broadcaster.update_node_status(node_id, "executing", workflow_id=workflow_id)+ result = await workflow_service.execute_node(+ node_id=node_id, node_type=node_type,+ parameters=data.get("parameters", {}),+ nodes=data.get("nodes", []), edges=data.get("edges", []),+ session_id=data.get("session_id", "default"),+ workflow_id=workflow_id,+ )++ if result.get("success"):+ await broadcaster.update_node_status(node_id, "success", result.get("result"), workflow_id=workflow_id)+ await broadcaster.update_node_output(node_id, result.get("result"), workflow_id=workflow_id)+ elif result.get("error") == "Cancelled by user":+ # Cancelled trigger nodes go back to idle, not error+ await broadcaster.update_node_status(node_id, "idle", {"message": "Cancelled"}, workflow_id=workflow_id)+ else:+ await broadcaster.update_node_status(node_id, "error", {"error": result.get("error")}, workflow_id=workflow_id)++ # Explicitly pass through success status (don't let decorator default to True)+ return {+ "success": result.get("success", False),+ "node_id": node_id,+ "result": result.get("result"),+ "error": result.get("error"),+ "execution_time": result.get("execution_time"),+ "timestamp": time.time()+ }+++@ws_handler("node_id")+async def handle_cancel_execution(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Cancel node execution."""+ broadcaster = get_status_broadcaster()+ await broadcaster.update_node_status(data["node_id"], "idle")+ return {"node_id": data["node_id"], "message": "Execution cancelled"}+++@ws_handler()+async def handle_cancel_event_wait(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Cancel an active event waiter (for trigger nodes).++ Can cancel by waiter_id or node_id.+ Note: Status update to "idle" happens in handle_execute_node when it catches CancelledError.+ """+ from services import event_waiter++ waiter_id = data.get("waiter_id")+ node_id = data.get("node_id")++ print(f"[WebSocket] handle_cancel_event_wait called: waiter_id={waiter_id}, node_id={node_id}")++ if waiter_id:+ success = event_waiter.cancel(waiter_id)+ print(f"[WebSocket] cancel by waiter_id result: success={success}")+ return {"success": success, "waiter_id": waiter_id, "message": "Cancelled" if success else "Not found"}+ elif node_id:+ count = event_waiter.cancel_for_node(node_id)+ print(f"[WebSocket] cancel by node_id result: cancelled_count={count}")+ return {"success": count > 0, "node_id": node_id, "cancelled_count": count}+ else:+ return {"success": False, "error": "waiter_id or node_id required"}+++@ws_handler()+async def handle_get_active_waiters(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get list of active event waiters (for debugging/UI)."""+ from services import event_waiter+ return {"waiters": event_waiter.get_active_waiters()}+++# ============================================================================+# Dead Letter Queue (DLQ) Handlers+# ============================================================================++@ws_handler()+async def handle_get_dlq_entries(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get DLQ entries with optional filtering.++ Optional params:+ workflow_id: Filter by workflow ID+ node_type: Filter by node type+ limit: Max entries to return (default 100)++ Returns:+ List of DLQ entries+ """+ from services.execution import ExecutionCache+ cache_service = container.cache()+ execution_cache = ExecutionCache(cache_service)++ entries = await execution_cache.get_dlq_entries(+ workflow_id=data.get("workflow_id"),+ node_type=data.get("node_type"),+ limit=data.get("limit", 100)+ )++ return {+ "entries": [entry.to_dict() for entry in entries],+ "count": len(entries),+ "timestamp": time.time()+ }+++@ws_handler("entry_id")+async def handle_get_dlq_entry(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get a single DLQ entry by ID.++ Required:+ entry_id: DLQ entry ID++ Returns:+ DLQ entry details+ """+ from services.execution import ExecutionCache+ cache_service = container.cache()+ execution_cache = ExecutionCache(cache_service)++ entry = await execution_cache.get_dlq_entry(data["entry_id"])++ if entry:+ return {"entry": entry.to_dict(), "timestamp": time.time()}+ else:+ return {"success": False, "error": "DLQ entry not found"}+++@ws_handler()+async def handle_get_dlq_stats(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get DLQ statistics.++ Returns:+ Total count, breakdown by node type and workflow+ """+ from services.execution import ExecutionCache+ cache_service = container.cache()+ execution_cache = ExecutionCache(cache_service)++ stats = await execution_cache.get_dlq_stats()+ return {"stats": stats, "timestamp": time.time()}+++@ws_handler("entry_id")+async def handle_replay_dlq_entry(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Replay a failed node from the DLQ.++ Required:+ entry_id: DLQ entry ID to replay+ nodes: Workflow nodes+ edges: Workflow edges++ Returns:+ Replay execution result+ """+ from services.execution import ExecutionCache, WorkflowExecutor+ cache_service = container.cache()+ execution_cache = ExecutionCache(cache_service)+ workflow_service = container.workflow_service()+ broadcaster = get_status_broadcaster()++ entry_id = data["entry_id"]+ nodes = data.get("nodes", [])+ edges = data.get("edges", [])++ # Get the entry to find the node_id+ entry = await execution_cache.get_dlq_entry(entry_id)+ if not entry:+ return {"success": False, "error": "DLQ entry not found"}++ # Update status+ await broadcaster.update_node_status(entry.node_id, "executing", {+ "message": "Replaying from DLQ"+ })++ # Create executor with node adapter+ async def node_executor(node_id: str, node_type: str, params: dict, context: dict) -> dict:+ return await workflow_service.execute_node(+ node_id=node_id,+ node_type=node_type,+ parameters=params,+ nodes=context.get("nodes", []),+ edges=context.get("edges", []),+ session_id=context.get("session_id", "dlq_replay"),+ execution_id=context.get("execution_id")+ )++ async def status_callback(node_id: str, status: str, status_data: dict):+ await broadcaster.update_node_status(node_id, status, status_data)++ # DLQ replay needs DLQ enabled to re-add on failure+ settings = container.settings()+ executor = WorkflowExecutor(+ cache=execution_cache,+ node_executor=node_executor,+ status_callback=status_callback,+ dlq_enabled=settings.dlq_enabled+ )++ result = await executor.replay_dlq_entry(entry_id, nodes, edges)++ # Update final status+ if result.get("success"):+ await broadcaster.update_node_status(entry.node_id, "success", result.get("result"))+ else:+ await broadcaster.update_node_status(entry.node_id, "error", {"error": result.get("error")})++ return result+++@ws_handler("entry_id")+async def handle_remove_dlq_entry(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Remove an entry from the DLQ without replaying.++ Required:+ entry_id: DLQ entry ID to remove++ Returns:+ Success status+ """+ from services.execution import ExecutionCache+ cache_service = container.cache()+ execution_cache = ExecutionCache(cache_service)++ success = await execution_cache.remove_from_dlq(data["entry_id"])+ return {"removed": success, "entry_id": data["entry_id"]}+++@ws_handler()+async def handle_purge_dlq(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Purge entries from the DLQ.++ Optional params:+ workflow_id: Only purge entries for this workflow+ node_type: Only purge entries for this node type+ older_than_hours: Only purge entries older than X hours++ Returns:+ Number of entries purged+ """+ from services.execution import ExecutionCache+ cache_service = container.cache()+ execution_cache = ExecutionCache(cache_service)++ older_than = None+ if data.get("older_than_hours"):+ older_than = time.time() - (data["older_than_hours"] * 3600)++ purged = await execution_cache.purge_dlq(+ workflow_id=data.get("workflow_id"),+ node_type=data.get("node_type"),+ older_than=older_than+ )++ return {"purged": purged, "timestamp": time.time()}+++@ws_handler("node_id")+async def handle_get_node_output(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get output data for a specific node."""+ workflow_service = container.workflow_service()+ node_id = data["node_id"]+ output_name = data.get("output_name", "output_0")+ output_data = await workflow_service.get_node_output(data.get("session_id", "default"), node_id, output_name)+ return {"node_id": node_id, "output_name": output_name, "data": output_data, "timestamp": time.time()}+++@ws_handler("node_id")+async def handle_clear_node_output(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Clear output data for a specific node from memory, database, and broadcaster cache."""+ workflow_service = container.workflow_service()+ database = container.database()+ broadcaster = get_status_broadcaster()+ node_id = data["node_id"]++ # Clear from memory - find keys ending with _{node_id}+ memory_cleared = 0+ keys_to_delete = [key for key in workflow_service.node_outputs.keys() if key.endswith(f"_{node_id}")]+ for key in keys_to_delete:+ del workflow_service.node_outputs[key]+ memory_cleared += 1++ # Clear from database (persisted storage)+ db_cleared = await database.delete_node_output(node_id)++ # Clear from broadcaster's status cache (prevents reload from showing old data)+ broadcaster_cleared = await broadcaster.clear_node_status(node_id)++ logger.info("Cleared node output", node_id=node_id, memory_cleared=memory_cleared,+ db_cleared=db_cleared, broadcaster_cleared=broadcaster_cleared)++ return {"node_id": node_id, "cleared": True, "memory_cleared": memory_cleared,+ "db_cleared": db_cleared, "broadcaster_cleared": broadcaster_cleared}+++@ws_handler()+async def handle_execute_workflow(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Execute entire workflow from start node to end.++ Expects:+ workflow_id: Workflow identifier for per-workflow status scoping+ nodes: List of workflow nodes with {id, type, data}+ edges: List of edges with {id, source, target}+ session_id: Optional session identifier++ Returns:+ Workflow execution result with all node outputs+ """+ workflow_service = container.workflow_service()+ broadcaster = get_status_broadcaster()++ workflow_id = data.get("workflow_id") # Per-workflow isolation (n8n pattern)+ nodes = data.get("nodes", [])+ edges = data.get("edges", [])+ session_id = data.get("session_id", "default")++ if not nodes:+ return {"success": False, "error": "No nodes provided"}++ # Broadcast workflow starting status+ await broadcaster.update_workflow_status(executing=True, current_node=None, progress=0)++ # Create status callback with workflow_id for per-workflow scoping (n8n pattern)+ async def status_callback(node_id: str, status: str, node_data: Optional[Dict] = None):+ await broadcaster.update_node_status(node_id, status, node_data, workflow_id=workflow_id)+ if status == "executing":+ position = node_data.get("position", 0) if node_data else 0+ total = node_data.get("total", 1) if node_data else 1+ progress = int((position / total) * 100) if total > 0 else 0+ await broadcaster.update_workflow_status(executing=True, current_node=node_id, progress=progress)++ # Execute the workflow with workflow_id for per-workflow status scoping+ result = await workflow_service.execute_workflow(+ nodes=nodes,+ edges=edges,+ session_id=session_id,+ status_callback=status_callback,+ workflow_id=workflow_id,+ )++ # Broadcast workflow completed status+ await broadcaster.update_workflow_status(+ executing=False,+ current_node=None,+ progress=100 if result.get("success") else 0+ )++ return {+ "success": result.get("success", False),+ "nodes_executed": result.get("nodes_executed", []),+ "node_results": result.get("node_results", {}),+ "execution_order": result.get("execution_order", []),+ "errors": result.get("errors", []),+ "error": result.get("error"),+ "total_nodes": result.get("total_nodes", 0),+ "completed_nodes": result.get("completed_nodes", 0),+ "execution_time": result.get("execution_time", 0),+ "timestamp": time.time()+ }+++# Per-workflow deployment tasks for proper cancellation (Temporal/n8n pattern)+# Maps workflow_id -> asyncio.Task for parallel workflow deployments+_deployment_tasks: Dict[str, asyncio.Task] = {}+++@ws_handler()+async def handle_deploy_workflow(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Deploy workflow to run continuously until cancelled.++ Expects:+ workflow_id: Workflow identifier (required for locking)+ nodes: List of workflow nodes with {id, type, data}+ edges: List of edges with {id, source, target}+ session_id: Optional session identifier+ delay_between_runs: Optional delay in seconds between iterations (default: 1.0)++ Returns:+ Deployment start confirmation (deployment runs in background)+ """+ global _deployment_tasks+ workflow_service = container.workflow_service()+ broadcaster = get_status_broadcaster()++ workflow_id = data.get("workflow_id")+ nodes = data.get("nodes", [])+ edges = data.get("edges", [])+ session_id = data.get("session_id", "default")++ if not nodes:+ return {"success": False, "error": "No nodes provided"}++ if not workflow_id:+ return {"success": False, "error": "workflow_id is required for deployment"}++ # Check if THIS specific workflow is already deployed (per-workflow isolation)+ if workflow_service.is_workflow_deployed(workflow_id):+ status = workflow_service.get_deployment_status(workflow_id)+ return {+ "success": False,+ "error": f"Workflow {workflow_id} is already deployed. Cancel it first.",+ "workflow_id": workflow_id,+ "is_running": True,+ "run_counter": status.get("run_counter", 0)+ }++ # Acquire workflow lock before starting deployment (per-workflow locking - n8n pattern)+ lock_acquired = await broadcaster.lock_workflow(workflow_id, reason="deployment")+ if not lock_acquired:+ lock_info = broadcaster.get_workflow_lock(workflow_id)+ return {+ "success": False,+ "error": f"Workflow {workflow_id} is already locked for {lock_info.get('reason', 'deployment')}",+ "locked_by": lock_info.get("workflow_id"),+ "locked_at": lock_info.get("locked_at")+ }++ # Broadcast deployment starting status using centralized method+ await broadcaster.update_workflow_status(executing=True, current_node=None, progress=0)+ await broadcaster.update_deployment_status(+ is_running=True,+ status="starting",+ active_runs=0,+ workflow_id=workflow_id+ )++ # Create status callback to broadcast node and deployment updates+ # Include workflow_id in all node status updates (n8n pattern for workflow isolation)+ async def status_callback(node_id: str, status: str, node_data: Optional[Dict] = None):+ if node_id == "__deployment__":+ # Deployment-level status update using centralized method+ active_runs = node_data.get("active_runs", 0) if node_data else 0+ await broadcaster.update_deployment_status(+ is_running=True,+ status=status,+ active_runs=active_runs,+ workflow_id=workflow_id,+ data=node_data+ )+ else:+ # Node-level status update with workflow_id for frontend filtering+ await broadcaster.update_node_status(node_id, status, node_data, workflow_id=workflow_id)+ if status == "executing":+ position = node_data.get("position", 0) if node_data else 0+ total = node_data.get("total", 1) if node_data else 1+ progress = int((position / total) * 100) if total > 0 else 0+ await broadcaster.update_workflow_status(executing=True, current_node=node_id, progress=progress)++ # Start deployment as background task (per-workflow - Temporal/n8n pattern)+ # In the event-driven pattern, deploy_workflow() returns immediately after setting up triggers.+ # The workflow stays locked until cancel_deployment is called.+ async def run_deployment():+ try:+ result = await workflow_service.deploy_workflow(+ nodes=nodes,+ edges=edges,+ session_id=session_id,+ status_callback=status_callback,+ workflow_id=workflow_id+ )++ # In event-driven mode, deploy_workflow returns immediately after trigger setup.+ # If it failed, unlock and report error. If successful, stay running.+ if not result.get("success"):+ # Setup failed - unlock and report error+ logger.error("Deployment setup failed", error=result.get("error"), workflow_id=workflow_id)+ await broadcaster.update_deployment_status(+ is_running=False,+ status="error",+ active_runs=0,+ workflow_id=workflow_id,+ error=result.get("error")+ )+ await broadcaster.unlock_workflow(workflow_id)+ # Clean up task reference for this workflow+ _deployment_tasks.pop(workflow_id, None)+ else:+ # Deployment successful - triggers are set up and running.+ # Workflow stays locked until cancel_deployment is called.+ await broadcaster.update_deployment_status(+ is_running=True,+ status="running",+ active_runs=0,+ workflow_id=workflow_id,+ data={+ "triggers_setup": result.get("triggers_setup", []),+ "deployment_id": result.get("deployment_id")+ }+ )+ logger.info("[Deployment] Event-driven deployment active",+ deployment_id=result.get("deployment_id"),+ workflow_id=workflow_id,+ triggers=len(result.get("triggers_setup", [])))++ except Exception as e:+ logger.error("Deployment task error", workflow_id=workflow_id, error=str(e))+ await broadcaster.update_deployment_status(+ is_running=False,+ status="error",+ active_runs=0,+ workflow_id=workflow_id,+ error=str(e)+ )+ await broadcaster.unlock_workflow(workflow_id)+ # Clean up task reference for this workflow+ _deployment_tasks.pop(workflow_id, None)++ # Store task per workflow for independent cancellation+ _deployment_tasks[workflow_id] = asyncio.create_task(run_deployment())++ return {+ "success": True,+ "message": "Deployment started",+ "workflow_id": workflow_id,+ "is_running": True,+ "locked": True,+ "timestamp": time.time()+ }+++@ws_handler()+async def handle_cancel_deployment(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Cancel running deployment for a specific workflow (Temporal/n8n pattern).++ Expects:+ workflow_id: Workflow to cancel (required).++ Also cancels any active event waiters (trigger nodes) and unlocks the workflow.++ Returns:+ Cancellation result with iterations completed+ """+ global _deployment_tasks+ from services import event_waiter++ workflow_service = container.workflow_service()+ broadcaster = get_status_broadcaster()++ workflow_id = data.get("workflow_id")++ if not workflow_id:+ return {"success": False, "error": "workflow_id is required for cancellation"}++ result = await workflow_service.cancel_deployment(workflow_id)++ # Cancel event waiters for this specific workflow's nodes+ cancelled_waiters = 0+ if result.get("success"):+ cancelled_waiters = result.get("waiters_cancelled", 0)++ # Cancel the deployment task for THIS specific workflow only (per-workflow isolation)+ task = _deployment_tasks.pop(workflow_id, None)+ if task and not task.done():+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ logger.info("[Deployment] Deployment task cancelled", workflow_id=workflow_id)++ # Unlock this specific workflow+ if workflow_id:+ await broadcaster.unlock_workflow(workflow_id)++ if result.get("success"):+ # Clear node statuses for all trigger nodes that were waiting+ # The result contains info about cancelled listeners (listener_{node_id})+ # Use existing clear_node_status method which broadcasts node_status_cleared+ for node_id in result.get("cancelled_listener_node_ids", []):+ await broadcaster.clear_node_status(node_id)++ # Broadcast deployment cancelled status using centralized method+ await broadcaster.update_workflow_status(executing=False, current_node=None, progress=0)+ await broadcaster.update_deployment_status(+ is_running=False,+ status="cancelled",+ active_runs=0,+ workflow_id=workflow_id,+ data={+ "iterations_completed": result.get("iterations_completed", 0)+ }+ )++ return {+ "success": result.get("success", False),+ "message": result.get("message", result.get("error")),+ "workflow_id": workflow_id,+ "was_running": result.get("was_running", False),+ "iterations_completed": result.get("iterations_completed", 0),+ "cancelled_waiters": cancelled_waiters,+ "unlocked": workflow_id is not None,+ "timestamp": time.time()+ }+++@ws_handler()+async def handle_get_deployment_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get current deployment status including workflow lock info.++ Expects (optional):+ workflow_id: Get status for specific workflow. If not provided, returns global status.++ Returns:+ Current deployment state, iteration count, and lock status+ """+ workflow_service = container.workflow_service()+ broadcaster = get_status_broadcaster()++ workflow_id = data.get("workflow_id")+ status = workflow_service.get_deployment_status(workflow_id)++ return {+ "is_running": workflow_service.is_deployment_running(workflow_id),+ "run_counter": status.get("run_counter", 0),+ "active_runs": status.get("active_runs", 0),+ "settings": workflow_service.get_deployment_settings(),+ "workflow_id": workflow_id or status.get("workflow_id"),+ "deployed_workflows": status.get("deployed_workflows", []),+ "lock": broadcaster.get_workflow_lock(),+ "timestamp": time.time()+ }+++@ws_handler()+async def handle_get_workflow_lock(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get current workflow lock status.++ Returns:+ Current lock state including locked workflow_id and reason+ """+ broadcaster = get_status_broadcaster()++ return {+ "lock": broadcaster.get_workflow_lock(),+ "timestamp": time.time()+ }+++@ws_handler()+async def handle_update_deployment_settings(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Update deployment settings (can be called during active deployment).++ Expects any of:+ delay_between_runs: float - Seconds to wait between iterations+ stop_on_error: bool - Stop deployment when a node fails+ max_iterations: int - Max iterations (0 = unlimited)++ Returns:+ Updated settings and current deployment state+ """+ workflow_service = container.workflow_service()+ broadcaster = get_status_broadcaster()++ settings_to_update = {}+ if "delay_between_runs" in data:+ settings_to_update["delay_between_runs"] = data["delay_between_runs"]+ if "stop_on_error" in data:+ settings_to_update["stop_on_error"] = data["stop_on_error"]+ if "max_iterations" in data:+ settings_to_update["max_iterations"] = data["max_iterations"]++ updated_settings = await workflow_service.update_deployment_settings(settings_to_update)++ # Broadcast settings update+ status = workflow_service.get_deployment_status()+ await broadcaster.broadcast({+ "type": "deployment_settings_updated",+ "settings": updated_settings,+ "is_running": workflow_service.is_deployment_running(),+ "run_counter": status.get("run_counter", 0)+ })++ return {+ "success": True,+ "settings": updated_settings,+ "is_running": workflow_service.is_deployment_running(),+ "run_counter": status.get("run_counter", 0),+ "active_runs": status.get("active_runs", 0),+ "timestamp": time.time()+ }+++# ============================================================================+# AI Handlers+# ============================================================================++@ws_handler("node_id", "node_type")+async def handle_execute_ai_node(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Execute an AI node (chat model or agent)."""+ workflow_service = container.workflow_service()+ broadcaster = get_status_broadcaster()+ node_id, node_type = data["node_id"], data["node_type"]++ await broadcaster.update_node_status(node_id, "executing")+ result = await workflow_service.execute_node(+ node_id=node_id, node_type=node_type,+ parameters=data.get("parameters", {}),+ nodes=data.get("nodes", []), edges=data.get("edges", []),+ session_id=data.get("session_id", "default")+ )++ if result.get("success"):+ await broadcaster.update_node_status(node_id, "success", result.get("result"))+ await broadcaster.update_node_output(node_id, result.get("result"))+ else:+ await broadcaster.update_node_status(node_id, "error", {"error": result.get("error")})++ return {"node_id": node_id, "result": result.get("result"), "error": result.get("error"),+ "execution_time": result.get("execution_time"), "timestamp": time.time()}+++@ws_handler("provider", "api_key")+async def handle_get_ai_models(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get available AI models for a provider."""+ ai_service = container.ai_service()+ models = await ai_service.fetch_models(data["provider"], data["api_key"])+ return {"provider": data["provider"], "models": models, "timestamp": time.time()}+++# ============================================================================+# API Key Handlers+# ============================================================================++@ws_handler("provider", "api_key")+async def handle_validate_api_key(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Validate and store an API key."""+ ai_service = container.ai_service()+ auth_service = container.auth_service()+ broadcaster = get_status_broadcaster()+ provider, api_key = data["provider"].lower(), data["api_key"].strip()++ models = await ai_service.fetch_models(provider, api_key)+ await auth_service.store_api_key(provider=provider, api_key=api_key, models=models,+ session_id=data.get("session_id", "default"))+ # Broadcast with hasKey and models so frontend can update reactively+ await broadcaster.update_api_key_status(+ provider=provider, valid=True, message="API key validated",+ has_key=True, models=models+ )+ return {"provider": provider, "valid": True, "models": models, "timestamp": time.time()}+++@ws_handler("provider")+async def handle_get_stored_api_key(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get stored API key for a provider."""+ auth_service = container.auth_service()+ provider = data["provider"].lower()+ api_key = await auth_service.get_api_key(provider, data.get("session_id", "default"))+ if not api_key:+ return {"provider": provider, "has_key": False}+ models = await auth_service.get_stored_models(provider, data.get("session_id", "default"))+ return {"provider": provider, "has_key": True, "api_key": api_key, "models": models, "timestamp": time.time()}+++@ws_handler("provider", "api_key")+async def handle_save_api_key(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Save an API key (without validation)."""+ auth_service = container.auth_service()+ await auth_service.store_api_key(provider=data["provider"].lower(), api_key=data["api_key"].strip(),+ models=data.get("models", []), session_id=data.get("session_id", "default"))+ return {"provider": data["provider"]}+++@ws_handler("provider")+async def handle_delete_api_key(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Delete stored API key."""+ auth_service = container.auth_service()+ await auth_service.remove_api_key(data["provider"].lower(), data.get("session_id", "default"))+ return {"provider": data["provider"]}+++# ============================================================================+# Android Handlers+# ============================================================================++@ws_handler()+async def handle_get_android_devices(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get list of connected Android devices."""+ android_service = container.android_service()+ devices = await android_service.list_devices()+ return {"devices": devices, "timestamp": time.time()}+++@ws_handler("service_id", "action")+async def handle_execute_android_action(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Execute an Android service action."""+ android_service = container.android_service()+ broadcaster = get_status_broadcaster()+ service_id, action = data["service_id"], data["action"]+ node_id = data.get("node_id", f"android_{service_id}_{action}")++ await broadcaster.update_node_status(node_id, "executing")+ result = await android_service.execute_service(+ node_id=node_id, service_id=service_id, action=action,+ parameters=data.get("parameters", {}),+ android_host=data.get("android_host", "localhost"),+ android_port=data.get("android_port", 8888)+ )++ status = "success" if result.get("success") else "error"+ await broadcaster.update_node_status(node_id, status, result.get("result") or {"error": result.get("error")})+ return result+++@ws_handler()+async def handle_setup_android_device(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Setup Android device connection."""+ workflow_service = container.workflow_service()+ broadcaster = get_status_broadcaster()+ connection_type = data.get("connection_type", "local")++ result = await workflow_service.execute_node(+ node_id=data.get("node_id", "android_setup"),+ node_type="androidDeviceSetup",+ parameters={+ "connection_type": connection_type,+ "device_id": data.get("device_id", ""),+ "websocket_url": data.get("websocket_url", ""),+ "port": data.get("port", 8888),+ "auto_forward": data.get("auto_forward", True)+ }+ )++ if result.get("success"):+ info = result.get("result", {})+ has_device = info.get("has_real_device", False)+ await broadcaster.update_android_status(+ connected=has_device,+ device_id=info.get("android_device") if has_device else None,+ connected_devices=info.get("connected_devices", []),+ connection_type=connection_type if has_device else "proxy_only"+ )+ return result+++@ws_handler()+async def handle_android_relay_connect(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Connect to Android relay server.++ Establishes WebSocket connection to relay server and broadcasts QR code for pairing.+ Status updates are automatically broadcast via the relay client's broadcaster integration.+ """+ from services.android import get_relay_client++ url = data.get("url", "")+ api_key = data.get("api_key")++ if not url:+ return {+ "success": False,+ "connected": False,+ "error": "Relay URL is required"+ }++ if not api_key:+ return {+ "success": False,+ "connected": False,+ "error": "API key is required"+ }++ logger.info(f"[WebSocket] Android relay connect: {url}")++ try:+ client, error = await get_relay_client(url, api_key)+ if client:+ return {+ "success": True,+ "connected": True,+ "session_token": client.session_token,+ "qr_data": client.qr_data,+ "message": "Connected to relay server"+ }+ else:+ return {+ "success": False,+ "connected": False,+ "error": error or "Failed to connect to relay server"+ }+ except Exception as e:+ logger.error(f"[WebSocket] Android relay connect error: {e}")+ return {"success": False, "error": str(e)}+++@ws_handler()+async def handle_android_relay_disconnect(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Disconnect from Android relay server.++ Closes the relay WebSocket connection and broadcasts disconnected status.+ """+ from services.android import close_relay_client++ logger.info("[WebSocket] Android relay disconnect requested")++ try:+ await close_relay_client()+ return {+ "success": True,+ "connected": False,+ "message": "Disconnected from relay server"+ }+ except Exception as e:+ logger.error(f"[WebSocket] Android relay disconnect error: {e}")+ return {"success": False, "error": str(e)}+++@ws_handler()+async def handle_android_relay_reconnect(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Reconnect to Android relay server with a new session token.++ Forces disconnect and reconnect to get fresh session_token and QR code.+ Useful when pairing fails or Android device needs to re-pair.+ """+ from services.android import close_relay_client, get_relay_client++ url = data.get("url", "")+ api_key = data.get("api_key")++ if not url:+ return {+ "success": False,+ "connected": False,+ "error": "Relay URL is required"+ }++ if not api_key:+ return {+ "success": False,+ "connected": False,+ "error": "API key is required"+ }++ logger.info("[WebSocket] Android relay reconnect: forcing new session")++ try:+ # Force disconnect existing connection+ await close_relay_client()++ # Small delay to ensure clean disconnect+ await asyncio.sleep(0.5)++ # Reconnect with fresh session+ client, error = await get_relay_client(url, api_key)+ if client:+ return {+ "success": True,+ "connected": True,+ "session_token": client.session_token,+ "qr_data": client.qr_data,+ "message": "Reconnected with new session token"+ }+ else:+ return {+ "success": False,+ "connected": False,+ "error": error or "Failed to reconnect to relay server"+ }+ except Exception as e:+ logger.error(f"[WebSocket] Android relay reconnect error: {e}")+ return {"success": False, "error": str(e)}+++# ============================================================================+# Maps Handlers+# ============================================================================++async def handle_validate_maps_key(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Validate Google Maps API key."""+ import httpx+ broadcaster = get_status_broadcaster()++ api_key = data.get("api_key", "").strip()++ if not api_key:+ return {"success": False, "valid": False, "error": "api_key required"}++ try:+ # Test the API key with a simple geocoding request+ async with httpx.AsyncClient() as client:+ response = await client.get(+ "https://maps.googleapis.com/maps/api/geocode/json",+ params={+ "address": "1600 Amphitheatre Parkway, Mountain View, CA",+ "key": api_key+ },+ timeout=10.0+ )++ response_data = response.json()++ if response_data.get("status") == "OK":+ await broadcaster.update_api_key_status(+ provider="google_maps",+ valid=True,+ message="API key validated successfully"+ )+ return {"success": True, "valid": True, "message": "Google Maps API key is valid"}++ elif response_data.get("status") == "REQUEST_DENIED":+ error_msg = response_data.get("error_message", "Invalid API key")+ await broadcaster.update_api_key_status(+ provider="google_maps",+ valid=False,+ message=error_msg+ )+ return {"success": True, "valid": False, "message": error_msg}++ else:+ # Other statuses like ZERO_RESULTS still mean the key works+ await broadcaster.update_api_key_status(+ provider="google_maps",+ valid=True,+ message="API key validated"+ )+ return {"success": True, "valid": True, "message": f"API key is valid (status: {response_data.get('status')})"}++ except httpx.TimeoutException:+ await broadcaster.update_api_key_status(+ provider="google_maps",+ valid=False,+ message="Validation request timed out"+ )+ return {"success": False, "valid": False, "error": "Validation request timed out"}++ except Exception as e:+ logger.error("Maps key validation failed", error=str(e))+ await broadcaster.update_api_key_status(+ provider="google_maps",+ valid=False,+ message=str(e)+ )+ return {"success": False, "valid": False, "error": str(e)}+++# ============================================================================+# WhatsApp Handlers - Wrappers for routers.whatsapp functions+# ============================================================================++from routers.whatsapp import (+ handle_whatsapp_status as _wa_status,+ handle_whatsapp_qr as _wa_qr,+ handle_whatsapp_send as _wa_send,+ handle_whatsapp_start as _wa_start,+ handle_whatsapp_restart as _wa_restart,+ handle_whatsapp_groups as _wa_groups,+ handle_whatsapp_group_info as _wa_group_info,+)+++async def handle_whatsapp_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ return await _wa_status()+++async def handle_whatsapp_qr(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ return await _wa_qr()+++async def handle_whatsapp_send(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Forward all send params to WhatsApp handler - supports all message types."""+ return await _wa_send(data)+++async def handle_whatsapp_start(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ return await _wa_start()+++async def handle_whatsapp_restart(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ return await _wa_restart()+++async def handle_whatsapp_groups(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ return await _wa_groups()+++async def handle_whatsapp_group_info(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get group participants with resolved phone numbers."""+ group_id = data.get("group_id", "")+ return await _wa_group_info(group_id)+++# ============================================================================+# Workflow Storage Operations+# ============================================================================++async def handle_save_workflow(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Save workflow to database."""+ database = container.database()+ success = await database.save_workflow(+ workflow_id=data["workflow_id"],+ name=data["name"],+ data=data.get("data", {})+ )+ return {"success": success, "workflow_id": data["workflow_id"]}+++async def handle_get_workflow(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get workflow by ID."""+ database = container.database()+ workflow = await database.get_workflow(data["workflow_id"])+ if workflow:+ return {+ "success": True,+ "workflow": {+ "id": workflow.id,+ "name": workflow.name,+ "data": workflow.data,+ "created_at": workflow.created_at.isoformat() if workflow.created_at else None,+ "updated_at": workflow.updated_at.isoformat() if workflow.updated_at else None+ }+ }+ return {"success": False, "error": "Workflow not found"}+++async def handle_get_all_workflows(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get all workflows."""+ database = container.database()+ workflows = await database.get_all_workflows()+ return {+ "success": True,+ "workflows": [+ {+ "id": w.id,+ "name": w.name,+ "nodeCount": len(w.data.get("nodes", [])) if w.data else 0,+ "created_at": w.created_at.isoformat() if w.created_at else None,+ "updated_at": w.updated_at.isoformat() if w.updated_at else None+ }+ for w in workflows+ ]+ }+++async def handle_delete_workflow(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Delete workflow."""+ database = container.database()+ success = await database.delete_workflow(data["workflow_id"])+ return {"success": success, "workflow_id": data["workflow_id"]}+++# ============================================================================+# Message Router+# ============================================================================++MESSAGE_HANDLERS: Dict[str, MessageHandler] = {+ # Status/ping+ "ping": handle_ping,+ "get_status": handle_get_status,+ "get_android_status": handle_get_android_status,+ "get_node_status": handle_get_node_status,+ "get_variable": handle_get_variable,++ # Node parameters+ "get_node_parameters": handle_get_node_parameters,+ "get_all_node_parameters": handle_get_all_node_parameters,+ "save_node_parameters": handle_save_node_parameters,+ "delete_node_parameters": handle_delete_node_parameters,++ # Node execution+ "execute_node": handle_execute_node,+ "execute_workflow": handle_execute_workflow,+ "cancel_execution": handle_cancel_execution,+ "get_node_output": handle_get_node_output,+ "clear_node_output": handle_clear_node_output,++ # Trigger/event waiting+ "cancel_event_wait": handle_cancel_event_wait,+ "get_active_waiters": handle_get_active_waiters,++ # Dead Letter Queue (DLQ) operations+ "get_dlq_entries": handle_get_dlq_entries,+ "get_dlq_entry": handle_get_dlq_entry,+ "get_dlq_stats": handle_get_dlq_stats,+ "replay_dlq_entry": handle_replay_dlq_entry,+ "remove_dlq_entry": handle_remove_dlq_entry,+ "purge_dlq": handle_purge_dlq,++ # Deployment operations+ "deploy_workflow": handle_deploy_workflow,+ "cancel_deployment": handle_cancel_deployment,+ "get_deployment_status": handle_get_deployment_status,+ "get_workflow_lock": handle_get_workflow_lock,+ "update_deployment_settings": handle_update_deployment_settings,++ # AI operations+ "execute_ai_node": handle_execute_ai_node,+ "get_ai_models": handle_get_ai_models,++ # API key operations+ "validate_api_key": handle_validate_api_key,+ "get_stored_api_key": handle_get_stored_api_key,+ "save_api_key": handle_save_api_key,+ "delete_api_key": handle_delete_api_key,++ # Android operations+ "get_android_devices": handle_get_android_devices,+ "execute_android_action": handle_execute_android_action,+ "setup_android_device": handle_setup_android_device,+ "android_relay_connect": handle_android_relay_connect,+ "android_relay_disconnect": handle_android_relay_disconnect,+ "android_relay_reconnect": handle_android_relay_reconnect,++ # Maps operations+ "validate_maps_key": handle_validate_maps_key,++ # WhatsApp operations+ "whatsapp_status": handle_whatsapp_status,+ "whatsapp_qr": handle_whatsapp_qr,+ "whatsapp_send": handle_whatsapp_send,+ "whatsapp_start": handle_whatsapp_start,+ "whatsapp_restart": handle_whatsapp_restart,+ "whatsapp_groups": handle_whatsapp_groups,+ "whatsapp_group_info": handle_whatsapp_group_info,++ # Workflow storage operations+ "save_workflow": handle_save_workflow,+ "get_workflow": handle_get_workflow,+ "get_all_workflows": handle_get_all_workflows,+ "delete_workflow": handle_delete_workflow,+}+++async def _execute_handler(+ handler: MessageHandler,+ data: Dict[str, Any],+ websocket: WebSocket,+ msg_type: str,+ request_id: Optional[str]+):+ """Execute handler and send response using safe send."""+ try:+ result = await handler(data, websocket)++ if request_id:+ await _safe_send(websocket, {+ "type": f"{msg_type}_result",+ "request_id": request_id,+ **result+ })+ else:+ await _safe_send(websocket, result)++ except asyncio.CancelledError:+ # Task was cancelled (e.g., WebSocket disconnected)+ logger.debug(f"[WebSocket] Handler cancelled: {msg_type}")+ raise+ except Exception as e:+ logger.error("Handler error", msg_type=msg_type, error=str(e))+ if request_id:+ await _safe_send(websocket, {+ "type": f"{msg_type}_result",+ "request_id": request_id,+ "success": False,+ "error": str(e)+ })++[email protected]("/ws/status")+async def websocket_status_endpoint(websocket: WebSocket):+ """WebSocket endpoint for real-time bidirectional communication.++ Uses decoupled receive/process pattern with asyncio.Queue:+ - Receive task: continuously receives messages into queue (never blocks)+ - Process task: reads from queue and spawns handler tasks (can be long-running)++ This ensures cancel messages are always processed immediately, even when+ long-running handlers (like trigger node execution) are active.++ All client requests include a request_id for correlation.+ The server responds with the same request_id for request/response matching.+ Broadcasts (without request_id) are sent to all connected clients.+ """+ # Authenticate via cookie before accepting connection+ settings = container.settings()+ token = websocket.cookies.get(settings.jwt_cookie_name)++ if not token:+ await websocket.close(code=4001, reason="Not authenticated")+ return++ user_auth = container.user_auth_service()+ payload = user_auth.verify_token(token)++ if not payload:+ await websocket.close(code=4001, reason="Invalid or expired session")+ return++ broadcaster = get_status_broadcaster()+ await broadcaster.connect(websocket)++ # Message queue for decoupling receive from processing+ message_queue: asyncio.Queue = asyncio.Queue()++ # Track handler tasks for this WebSocket+ handler_tasks: Set[asyncio.Task] = set()+ _handler_tasks[websocket] = handler_tasks++ async def receive_loop():+ """Receives messages and puts them in queue - never blocks on handlers."""+ try:+ while True:+ data = await websocket.receive_json()+ await message_queue.put(data)+ except WebSocketDisconnect:+ logger.info("[WebSocket] Client disconnected normally")+ await message_queue.put(None) # Signal shutdown+ except Exception as e:+ logger.error(f"[WebSocket] Receive error: {e}")+ await message_queue.put(None)++ async def process_loop():+ """Processes messages from queue - spawns handler tasks that can run concurrently."""+ while True:+ data = await message_queue.get()++ if data is None: # Shutdown signal+ break++ msg_type = data.get("type", "")+ request_id = data.get("request_id")++ logger.debug("WebSocket message received", msg_type=msg_type, has_request_id=bool(request_id))++ handler = MESSAGE_HANDLERS.get(msg_type)++ if handler:+ # Run handler as task so it doesn't block queue processing+ # This allows cancel_event_wait to be processed while execute_node is waiting+ task = asyncio.create_task(+ _execute_handler(handler, data, websocket, msg_type, request_id)+ )+ handler_tasks.add(task)+ task.add_done_callback(handler_tasks.discard)+ else:+ logger.warning("Unknown message type", msg_type=msg_type)+ if request_id:+ await _safe_send(websocket, {+ "type": "error",+ "request_id": request_id,+ "code": "UNKNOWN_MESSAGE_TYPE",+ "message": f"Unknown message type: {msg_type}"+ })++ try:+ # Run receive and process loops concurrently using TaskGroup (Python 3.11+)+ async with asyncio.TaskGroup() as tg:+ tg.create_task(receive_loop())+ tg.create_task(process_loop())++ except* WebSocketDisconnect:+ logger.info("[WebSocket] Client disconnected (TaskGroup)")+ except* Exception as eg:+ for exc in eg.exceptions:+ if not isinstance(exc, WebSocketDisconnect):+ logger.error(f"[WebSocket] TaskGroup error: {exc}")+ finally:+ # Cancel any running handler tasks on disconnect+ for task in list(handler_tasks):+ if not task.done():+ task.cancel()++ # Wait for tasks to finish cancellation+ if handler_tasks:+ await asyncio.gather(*handler_tasks, return_exceptions=True)++ # Cleanup+ _handler_tasks.pop(websocket, None)+ await broadcaster.disconnect(websocket)++[email protected]("/ws/info")+async def websocket_info():+ """Get WebSocket connection info."""+ broadcaster = get_status_broadcaster()+ return {+ "endpoint": "/ws/status",+ "connected_clients": broadcaster.connection_count,+ "current_status": broadcaster.get_status(),+ "supported_message_types": list(MESSAGE_HANDLERS.keys())+ }diff --git a/server/routers/whatsapp.py b/server/routers/whatsapp.pynew file mode 100644index 00000000..fd23538e--- /dev/null+++ b/server/routers/whatsapp.py@@ -0,0 +1,656 @@+"""+WhatsApp Service - JSON-RPC 2.0 integration with Go whatsmeow service.++This module provides WebSocket handlers for WhatsApp operations.+All communication goes through the RPCClient to the Go service.+"""++import asyncio+import base64+import io+import json+import logging+import os+import time+from typing import Any, Optional++import qrcode+import websockets+from websockets.exceptions import ConnectionClosed+from fastapi import HTTPException+++def qr_code_to_base64(code: str) -> str:+ """Convert QR code string to base64 PNG image."""+ qr = qrcode.QRCode(version=1, box_size=10, border=4)+ qr.add_data(code)+ qr.make(fit=True)+ img = qr.make_image(fill_color="black", back_color="white")+ buffer = io.BytesIO()+ img.save(buffer, format="PNG")+ return base64.b64encode(buffer.getvalue()).decode("utf-8")+++logger = logging.getLogger(__name__)++WHATSAPP_RPC_URL = os.getenv("WHATSAPP_RPC_URL", "ws://localhost:9400/ws/rpc")+++# Inline RPC Client with async event handling+class RPCClient:+ def __init__(self, url: str):+ self.url, self.ws, self.req_id = url, None, 0+ self.pending: dict[int, asyncio.Future] = {}+ self._connected, self._task = False, None+ self._event_handler = None++ @property+ def connected(self):+ """Check if actually connected - verify WebSocket is open."""+ if not self._connected or not self.ws:+ return False+ # websockets 15.x uses state instead of closed (state.value: 0=CONNECTING, 1=OPEN, 2=CLOSING, 3=CLOSED)+ try:+ return self.ws.state.value == 1+ except Exception:+ return False++ def set_event_handler(self, handler):+ """Set callback for handling async events from Go service."""+ self._event_handler = handler++ async def connect(self):+ # 2 second timeout for initial connection (fail fast if Go service not running)+ self.ws = await asyncio.wait_for(+ websockets.connect(self.url, ping_interval=30, max_size=100*1024*1024),+ timeout=2.0+ )+ self._connected = True+ self._task = asyncio.create_task(self._recv())++ async def close(self):+ self._connected = False+ if self._task: self._task.cancel()+ if self.ws: await self.ws.close()++ async def _recv(self):+ try:+ async for msg in self.ws:+ data = json.loads(msg)+ if data.get("id") in self.pending:+ self.pending[data["id"]].set_result(data)+ elif "method" in data and "id" not in data:+ await self._handle_event(data)+ except ConnectionClosed:+ self._connected = False++ async def _handle_event(self, data: dict):+ """Handle async events from Go service and broadcast to frontend.++ Events from schema.json:+ - event.connected: {status: "connected", device_id: string}+ - event.disconnected: {status: "disconnected", reason: string}+ - event.connection_failure: {error: string, reason: string}+ - event.logged_out: {on_connect: boolean, reason: string}+ - event.temporary_ban: {code: string, reason: string}+ - event.qr_code: {code: string, filename: string}+ - event.message_sent: {message_id, to, type, timestamp}+ - event.message_received: {message_id, sender, chat_id, ...}+ """+ method = data.get("method", "")+ params = data.get("params", {})+ logger.info(f"[WhatsApp RPC] Event: {method} params={params}")++ try:+ from services.status_broadcaster import get_status_broadcaster+ broadcaster = get_status_broadcaster()++ if method == "event.status":+ # Initial status sent on WebSocket connection+ await broadcaster.update_whatsapp_status(+ connected=params.get("connected", False),+ has_session=params.get("has_session", False),+ running=params.get("running", False),+ pairing=params.get("pairing", False),+ device_id=params.get("device_id"),+ qr=None+ )++ elif method == "event.connected":+ # Connected successfully with device_id+ await broadcaster.update_whatsapp_status(+ connected=True,+ has_session=True,+ running=True,+ pairing=False,+ device_id=params.get("device_id"),+ qr=None+ )++ elif method == "event.disconnected":+ # Disconnected - service still running+ await broadcaster.update_whatsapp_status(+ connected=False,+ has_session=False,+ running=True,+ pairing=False,+ device_id=None,+ qr=None+ )++ elif method == "event.connection_failure":+ # Connection failed+ logger.error(f"[WhatsApp] Connection failure: {params.get('error')} - {params.get('reason')}")+ await broadcaster.update_whatsapp_status(+ connected=False,+ has_session=False,+ running=True,+ pairing=False,+ device_id=None,+ qr=None+ )++ elif method == "event.logged_out":+ # Logged out - session cleared+ logger.warning(f"[WhatsApp] Logged out: {params.get('reason')}")+ await broadcaster.update_whatsapp_status(+ connected=False,+ has_session=False,+ running=True,+ pairing=False,+ device_id=None,+ qr=None+ )++ elif method == "event.temporary_ban":+ # Temporary ban+ logger.error(f"[WhatsApp] Temporary ban: code={params.get('code')} reason={params.get('reason')}")+ await broadcaster.update_whatsapp_status(+ connected=False,+ has_session=False,+ running=True,+ pairing=False,+ device_id=None,+ qr=None+ )++ elif method == "event.qr_code":+ # New QR code available for pairing+ code = params.get("code")+ qr_image = qr_code_to_base64(code) if code else None+ await broadcaster.update_whatsapp_status(+ connected=False,+ has_session=False,+ running=True,+ pairing=True,+ device_id=None,+ qr=qr_image+ )++ elif method == "event.message_sent":+ # Message sent - broadcast as custom event+ await broadcaster.send_custom_event("whatsapp_message_sent", params)++ elif method == "event.message_received":+ # Message received - broadcast as custom event+ await broadcaster.send_custom_event("whatsapp_message_received", params)++ # Forward to custom handler if set+ if self._event_handler:+ await self._event_handler(method, params)++ except Exception as e:+ logger.error(f"[WhatsApp RPC] Event handler error: {e}")++ async def call(self, method: str, params: Any = None, timeout: float = 30) -> Any:+ if not self.connected:+ raise Exception("Not connected to WhatsApp service")+ self.req_id += 1+ req_id = self.req_id # Capture request ID before any await+ req = {"jsonrpc": "2.0", "id": req_id, "method": method}+ if params:+ req["params"] = params++ # Get current event loop for future+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ loop = asyncio.get_event_loop()+ future = loop.create_future()+ self.pending[req_id] = future++ try:+ await self.ws.send(json.dumps(req))+ resp = await asyncio.wait_for(future, timeout)+ if resp.get("error"):+ raise Exception(resp["error"].get("message", "RPC Error"))+ return resp.get("result")+ except asyncio.TimeoutError:+ raise Exception(f"RPC call '{method}' timed out after {timeout}s")+ except ConnectionClosed as e:+ logger.error(f"[WhatsApp RPC] Connection closed during {method}: {e}")+ self._connected = False+ raise Exception(f"Connection lost during {method}")+ finally:+ self.pending.pop(req_id, None)++_client: Optional[RPCClient] = None+_lock = asyncio.Lock()+_send_lock = asyncio.Lock() # Serialize sends - Go service processes sequentially+++async def reset_client():+ """Force reset the RPC client connection."""+ global _client+ async with _lock:+ if _client:+ try:+ await _client.close()+ except Exception:+ pass+ _client = None+++async def get_client(force_reconnect: bool = False) -> RPCClient:+ """Get or create RPC client. Use force_reconnect=True to ensure fresh connection."""+ global _client+ async with _lock:+ # Force reconnect if requested or if client is stale+ if force_reconnect and _client:+ logger.info("[WhatsApp RPC] Force reconnecting...")+ try:+ await _client.close()+ except Exception:+ pass+ _client = None++ if not _client or not _client.connected:+ logger.info(f"[WhatsApp RPC] Creating new connection to {WHATSAPP_RPC_URL}")+ _client = RPCClient(WHATSAPP_RPC_URL)+ try:+ await _client.connect()+ logger.info("[WhatsApp RPC] Connected successfully")+ except asyncio.TimeoutError:+ _client = None+ logger.error(f"WhatsApp RPC timeout - Go service not responding at {WHATSAPP_RPC_URL}")+ raise Exception("WhatsApp service timeout - is Go service running?")+ except (ConnectionRefusedError, OSError) as e:+ _client = None+ logger.error(f"WhatsApp RPC connection refused: {e}")+ raise Exception("WhatsApp service not running - start Go whatsmeow service on port 9400")+ except Exception as e:+ _client = None+ logger.error(f"WhatsApp RPC error: {e}")+ raise Exception(f"WhatsApp connection failed: {e}")+ return _client+++# ============================================================================+# WebSocket Handlers - used by websocket.py+# ============================================================================++async def handle_whatsapp_status() -> dict:+ """Get WhatsApp connection status via direct RPC and broadcast to all clients."""+ try:+ client = await get_client()+ status_data = await client.call("status")++ # Broadcast status update to all connected WebSocket clients+ from services.status_broadcaster import get_status_broadcaster+ broadcaster = get_status_broadcaster()+ await broadcaster.update_whatsapp_status(+ connected=status_data.get("connected", False),+ has_session=status_data.get("has_session", False),+ running=status_data.get("running", False),+ pairing=status_data.get("pairing", False),+ device_id=status_data.get("device_id"),+ qr=None # QR code comes from event.qr_code events+ )++ return {+ "success": True,+ "data": status_data,+ "connected": status_data.get("connected", False),+ "device_id": status_data.get("device_id"),+ "timestamp": time.time()+ }+ except Exception as e:+ logger.error(f"WhatsApp status check failed: {e}")+ # Return error response immediately - don't broadcast here to avoid race conditions+ # The client will update its local state based on the error response+ return {+ "success": False,+ "error": str(e),+ "connected": False,+ "running": False,+ "timestamp": time.time()+ }+++async def handle_whatsapp_qr() -> dict:+ """Get WhatsApp QR code for authentication via direct RPC."""+ try:+ client = await get_client()+ status = await client.call("status")++ if status.get("connected") and status.get("has_session"):+ return {+ "success": True,+ "connected": True,+ "message": "Already connected with active session",+ "timestamp": time.time()+ }++ try:+ result = await client.call("qr")+ code = result.get("code")+ if code:+ qr_image = qr_code_to_base64(code)+ return {+ "success": True,+ "connected": False,+ "qr": qr_image,+ "message": "QR code available",+ "timestamp": time.time()+ }+ return {+ "success": True,+ "connected": False,+ "qr": None,+ "message": "No QR code available",+ "timestamp": time.time()+ }+ except Exception as qr_err:+ return {+ "success": True,+ "connected": False,+ "qr": None,+ "message": str(qr_err),+ "timestamp": time.time()+ }+ except Exception as e:+ logger.error(f"WhatsApp QR fetch failed: {e}")+ return {"success": False, "connected": False, "error": str(e)}+++async def handle_whatsapp_send(params: dict) -> dict:+ """Send a WhatsApp message via direct RPC - supports all message types.++ Uses _send_lock to serialize sends - Go service processes sequentially.++ Params from frontend node:+ - recipientType: 'phone' or 'group'+ - phone: recipient phone number (if recipientType='phone')+ - group_id: group JID (if recipientType='group')+ - messageType: text, image, video, audio, document, sticker, location, contact+ - message: text content (for text type)+ - mediaSource: base64, file, url (for media types)+ - mediaData/filePath/mediaUrl: media content based on source+ - mimeType, caption, filename: media options+ - latitude, longitude, locationName, address: location data+ - contactName, vcard: contact data+ - isReply, replyMessageId, replySender, replyContent: reply context+ """+ async with _send_lock:+ try:+ # Build RPC params matching schema.json+ rpc_params: dict[str, Any] = {}++ # Recipient+ recipient_type = params.get("recipientType", "phone")+ if recipient_type == "group":+ group_id = params.get("group_id")+ if not group_id:+ return {"success": False, "error": "group_id is required"}+ rpc_params["group_id"] = group_id+ else:+ phone = params.get("phone")+ if not phone:+ return {"success": False, "error": "phone is required"}+ rpc_params["phone"] = phone++ # Message type+ msg_type = params.get("messageType", "text")+ rpc_params["type"] = msg_type++ # Content based on type+ if msg_type == "text":+ message = params.get("message")+ if not message:+ return {"success": False, "error": "message is required for text type"}+ rpc_params["message"] = message++ elif msg_type in ["image", "video", "audio", "document", "sticker"]:+ media_source = params.get("mediaSource", "base64")+ media_data = None+ mime_type = params.get("mimeType")+ filename = params.get("filename")++ if media_source == "base64":+ media_data = params.get("mediaData")+ elif media_source == "file":+ file_param = params.get("filePath")+ if isinstance(file_param, dict) and file_param.get("type") == "upload":+ media_data = file_param.get("data")+ mime_type = mime_type or file_param.get("mimeType")+ filename = filename or file_param.get("filename")+ elif file_param:+ import base64 as b64+ try:+ with open(file_param, "rb") as f:+ media_data = b64.b64encode(f.read()).decode("utf-8")+ except Exception as e:+ return {"success": False, "error": f"Failed to read file: {e}"}+ elif media_source == "url":+ media_url = params.get("mediaUrl")+ if media_url:+ import httpx+ import base64 as b64+ try:+ async with httpx.AsyncClient() as http:+ resp = await http.get(media_url, timeout=30)+ media_data = b64.b64encode(resp.content).decode("utf-8")+ except Exception as e:+ return {"success": False, "error": f"Failed to download media: {e}"}++ if not media_data:+ return {"success": False, "error": f"media data is required for {msg_type} type"}++ rpc_params["media_data"] = {+ "data": media_data,+ "mime_type": mime_type or _guess_mime_type(msg_type)+ }+ if params.get("caption"):+ rpc_params["media_data"]["caption"] = params["caption"]+ final_filename = filename or params.get("filename")+ if final_filename:+ rpc_params["media_data"]["filename"] = final_filename++ elif msg_type == "location":+ lat = params.get("latitude")+ lng = params.get("longitude")+ if lat is None or lng is None:+ return {"success": False, "error": "latitude and longitude are required"}+ rpc_params["location"] = {"latitude": float(lat), "longitude": float(lng)}+ if params.get("locationName"):+ rpc_params["location"]["name"] = params["locationName"]+ if params.get("address"):+ rpc_params["location"]["address"] = params["address"]++ elif msg_type == "contact":+ contact_name = params.get("contactName")+ vcard = params.get("vcard")+ if not contact_name or not vcard:+ return {"success": False, "error": "contactName and vcard are required"}+ rpc_params["contact"] = {"display_name": contact_name, "vcard": vcard}++ # Reply context+ if params.get("isReply"):+ reply_id = params.get("replyMessageId")+ reply_sender = params.get("replySender")+ if reply_id and reply_sender:+ rpc_params["reply"] = {+ "message_id": reply_id,+ "sender": reply_sender,+ "content": params.get("replyContent", "")+ }++ if params.get("metadata"):+ rpc_params["metadata"] = params["metadata"]++ client = await get_client()+ result = await client.call("send", rpc_params)+ return {+ "success": True,+ "messageId": result.get("message_id"),+ "messageType": msg_type,+ "timestamp": time.time()+ }+ except Exception as e:+ logger.error(f"WhatsApp send failed: {e}")+ return {"success": False, "error": str(e)}+++def _guess_mime_type(msg_type: str) -> str:+ """Guess default MIME type based on message type."""+ defaults = {+ "image": "image/jpeg",+ "video": "video/mp4",+ "audio": "audio/ogg",+ "document": "application/octet-stream",+ "sticker": "image/webp"+ }+ return defaults.get(msg_type, "application/octet-stream")+++async def handle_whatsapp_start() -> dict:+ """Start WhatsApp connection via direct RPC and broadcast running state."""+ try:+ client = await get_client()+ result = await client.call("start")++ # Broadcast that service is now running (waiting for QR or connection)+ from services.status_broadcaster import get_status_broadcaster+ broadcaster = get_status_broadcaster()+ await broadcaster.update_whatsapp_status(+ connected=False,+ has_session=False,+ running=True,+ pairing=False, # Will be set to True by event.qr_code event+ device_id=None,+ qr=None+ )++ return {+ "success": True,+ "message": "WhatsApp connection started",+ "data": result,+ "timestamp": time.time()+ }+ except Exception as e:+ logger.error(f"WhatsApp start failed: {e}")+ return {"success": False, "error": str(e)}+++async def handle_whatsapp_restart() -> dict:+ """Restart WhatsApp connection via direct RPC.++ This calls the 'restart' RPC method which stops and starts the service,+ unlike 'start' which only starts if not running.+ """+ try:+ # Force fresh connection to avoid stale WebSocket+ client = await get_client(force_reconnect=True)++ # Broadcast that we're restarting (brief disconnected state)+ from services.status_broadcaster import get_status_broadcaster+ broadcaster = get_status_broadcaster()+ await broadcaster.update_whatsapp_status(+ connected=False,+ has_session=False,+ running=True,+ pairing=False,+ device_id=None,+ qr=None+ )++ # Call restart RPC method+ result = await client.call("restart")++ return {+ "success": True,+ "message": "WhatsApp connection restarted",+ "data": result,+ "timestamp": time.time()+ }+ except HTTPException as e:+ logger.error(f"WhatsApp restart failed: {e.detail}")+ return {"success": False, "error": e.detail}+ except Exception as e:+ logger.error(f"WhatsApp restart failed: {e}")+ return {"success": False, "error": str(e)}+++async def handle_whatsapp_groups() -> dict:+ """Get list of WhatsApp groups via direct RPC."""+ try:+ client = await get_client()+ groups = await client.call("groups")++ return {+ "success": True,+ "groups": groups or [],+ "timestamp": time.time()+ }+ except Exception as e:+ logger.error(f"WhatsApp groups fetch failed: {e}")+ return {"success": False, "error": str(e), "groups": []}+++async def handle_whatsapp_group_info(group_id: str) -> dict:+ """Get group info including participants with resolved phone numbers.++ Args:+ group_id: Group JID (e.g., '[email protected]')++ Returns:+ Group info with participants containing both 'jid' (LID) and 'phone' (resolved number)+ """+ try:+ if not group_id:+ return {"success": False, "error": "group_id is required", "participants": []}++ client = await get_client()+ result = await client.call("group_info", {"group_id": group_id})++ if not result:+ return {"success": False, "error": "Failed to get group info", "participants": []}++ # Extract participants with phone numbers+ participants = []+ for p in result.get('participants', []):+ jid = p.get('jid', '')+ phone = p.get('phone', '')+ name = p.get('name', '')++ # Only include participants with resolved phone numbers+ if phone:+ participants.append({+ "jid": jid,+ "phone": phone,+ "name": name or phone, # Use phone as fallback name+ "is_admin": p.get('is_admin', False),+ "is_super_admin": p.get('is_super_admin', False)+ })++ return {+ "success": True,+ "group_id": group_id,+ "name": result.get('name', ''),+ "participants": participants,+ "participant_count": len(participants),+ "timestamp": time.time()+ }+ except Exception as e:+ logger.error(f"WhatsApp group_info fetch failed for {group_id}: {e}")+ return {"success": False, "error": str(e), "participants": []}diff --git a/server/routers/workflow.py b/server/routers/workflow.pynew file mode 100644index 00000000..f419c152--- /dev/null+++ b/server/routers/workflow.py@@ -0,0 +1,132 @@+"""Workflow execution routes."""++from fastapi import APIRouter, Depends+from pydantic import BaseModel+from typing import Dict, Any, List++from core.container import container+from services.workflow import WorkflowService+from services.status_broadcaster import get_status_broadcaster+from core.logging import get_logger++logger = get_logger(__name__)+router = APIRouter(prefix="/api/workflow", tags=["workflow"])+++class WorkflowExecutionRequest(BaseModel):+ node_id: str+ node_type: str+ parameters: Dict[str, Any] = {}+ nodes: List[Dict[str, Any]] = []+ edges: List[Dict[str, Any]] = []+ session_id: str = "default"++[email protected]("/execute-node")+async def execute_workflow_node(+ request: WorkflowExecutionRequest,+ workflow_service: WorkflowService = Depends(lambda: container.workflow_service())+):+ """Execute a single node in a workflow with parameter resolution."""+ print(f"[DEBUG ROUTER] Received execution request: node_id={request.node_id}, node_type={request.node_type}")+ logger.info("[DEBUG ROUTER] Received execution request", node_id=request.node_id,+ node_type=request.node_type, params=request.parameters)++ # Get broadcaster and send "executing" status+ broadcaster = get_status_broadcaster()+ await broadcaster.update_node_status(+ node_id=request.node_id,+ status="executing",+ data={"node_type": request.node_type}+ )++ try:+ result = await workflow_service.execute_node(+ node_id=request.node_id,+ node_type=request.node_type,+ parameters=request.parameters,+ nodes=request.nodes,+ edges=request.edges,+ session_id=request.session_id+ )++ # Broadcast completion status based on result+ if result.get("success"):+ await broadcaster.update_node_status(+ node_id=request.node_id,+ status="success",+ data={+ "node_type": request.node_type,+ "execution_time": result.get("execution_time"),+ "result": result.get("result")+ }+ )+ # Also broadcast the output+ if result.get("result"):+ await broadcaster.update_node_output(+ node_id=request.node_id,+ output=result.get("result")+ )+ else:+ await broadcaster.update_node_status(+ node_id=request.node_id,+ status="error",+ data={+ "node_type": request.node_type,+ "error": result.get("error")+ }+ )++ return result++ except Exception as e:+ # Broadcast error status+ await broadcaster.update_node_status(+ node_id=request.node_id,+ status="error",+ data={+ "node_type": request.node_type,+ "error": str(e)+ }+ )+ raise++[email protected]("/node-output/{node_id}")+async def get_workflow_node_output(+ node_id: str,+ output_name: str = "output_0",+ session_id: str = "default",+ workflow_service: WorkflowService = Depends(lambda: container.workflow_service())+):+ """Get stored output data for a node."""+ return await workflow_service.get_workflow_node_output(node_id, output_name, session_id)++[email protected]("/clear-outputs")+async def clear_workflow_outputs(+ session_id: str = "default",+ workflow_service: WorkflowService = Depends(lambda: container.workflow_service())+):+ """Clear all stored node outputs for a session."""+ try:+ await workflow_service.clear_all_outputs(session_id)+ return {+ "success": True,+ "message": f"Cleared all outputs for session: {session_id}"+ }+ except Exception as e:+ logger.error("Failed to clear outputs", session_id=session_id, error=str(e))+ return {+ "success": False,+ "error": str(e)+ }++[email protected]("/health")+async def workflow_health_check():+ """Workflow service health check."""+ return {+ "status": "OK",+ "service": "workflow"+ }\ No newline at end of filediff --git a/server/services/__init__.py b/server/services/__init__.pynew file mode 100644index 00000000..fea2895e--- /dev/null+++ b/server/services/__init__.py@@ -0,0 +1 @@+# Business logic services\ No newline at end of filediff --git a/server/services/ai.py b/server/services/ai.pynew file mode 100644index 00000000..3cdd6bc9--- /dev/null+++ b/server/services/ai.py@@ -0,0 +1,582 @@+"""AI service for managing language models with LangGraph state machine support."""++import time+import httpx+from dataclasses import dataclass+from datetime import datetime+from typing import Dict, Any, List, Optional, Callable, Type, TypedDict, Annotated, Sequence+import operator++from langchain_openai import ChatOpenAI+from langchain_anthropic import ChatAnthropic+from langchain_google_genai import ChatGoogleGenerativeAI+from langchain_core.messages import HumanMessage, SystemMessage, AIMessage, BaseMessage+from langgraph.graph import StateGraph, END++from core.config import Settings+from core.logging import get_logger, log_execution_time, log_api_call+from services.auth import AuthService++logger = get_logger(__name__)+++# =============================================================================+# AI PROVIDER REGISTRY - Single source of truth for provider configurations+# =============================================================================++@dataclass+class ProviderConfig:+ """Configuration for an AI provider."""+ name: str+ model_class: Type+ api_key_param: str # Parameter name for API key in model constructor+ max_tokens_param: str # Parameter name for max tokens+ detection_patterns: tuple # Patterns to detect this provider from model name+ default_model: str # Default model when none specified+ models_endpoint: str # API endpoint to fetch models+ models_header_fn: Callable[[str], dict] # Function to create headers+++def _openai_headers(api_key: str) -> dict:+ return {'Authorization': f'Bearer {api_key}'}+++def _anthropic_headers(api_key: str) -> dict:+ return {'x-api-key': api_key, 'anthropic-version': '2023-06-01'}+++def _gemini_headers(api_key: str) -> dict:+ return {} # API key in URL for Gemini+++# Provider configurations+PROVIDER_CONFIGS: Dict[str, ProviderConfig] = {+ 'openai': ProviderConfig(+ name='openai',+ model_class=ChatOpenAI,+ api_key_param='openai_api_key',+ max_tokens_param='max_tokens',+ detection_patterns=('gpt', 'openai', 'o1'),+ default_model='gpt-4o-mini',+ models_endpoint='https://api.openai.com/v1/models',+ models_header_fn=_openai_headers+ ),+ 'anthropic': ProviderConfig(+ name='anthropic',+ model_class=ChatAnthropic,+ api_key_param='anthropic_api_key',+ max_tokens_param='max_tokens',+ detection_patterns=('claude', 'anthropic'),+ default_model='claude-3-5-sonnet-20241022',+ models_endpoint='https://api.anthropic.com/v1/models',+ models_header_fn=_anthropic_headers+ ),+ 'gemini': ProviderConfig(+ name='gemini',+ model_class=ChatGoogleGenerativeAI,+ api_key_param='google_api_key',+ max_tokens_param='max_output_tokens',+ detection_patterns=('gemini', 'google'),+ default_model='gemini-1.5-pro',+ models_endpoint='https://generativelanguage.googleapis.com/v1beta/models',+ models_header_fn=_gemini_headers+ ),+}+++def detect_provider_from_model(model: str) -> str:+ """Detect AI provider from model name using registry patterns."""+ model_lower = model.lower()+ for provider_name, config in PROVIDER_CONFIGS.items():+ if any(pattern in model_lower for pattern in config.detection_patterns):+ return provider_name+ return 'openai' # default+++def is_model_valid_for_provider(model: str, provider: str) -> bool:+ """Check if model name matches the provider's patterns."""+ config = PROVIDER_CONFIGS.get(provider)+ if not config:+ return True+ model_lower = model.lower()+ return any(pattern in model_lower for pattern in config.detection_patterns)+++def get_default_model(provider: str) -> str:+ """Get default model for a provider."""+ config = PROVIDER_CONFIGS.get(provider)+ return config.default_model if config else 'gpt-4o-mini'+++# =============================================================================+# LANGGRAPH STATE MACHINE DEFINITIONS+# =============================================================================++class AgentState(TypedDict):+ """State for the LangGraph agent workflow.++ Uses Annotated with operator.add to accumulate messages over steps.+ This is the core pattern from LangGraph for stateful conversations.+ """+ messages: Annotated[Sequence[BaseMessage], operator.add]+ # Tool outputs for future tool integration+ tool_outputs: Dict[str, Any]+ # Agent metadata+ iteration: int+ max_iterations: int+ should_continue: bool+++def create_agent_node(chat_model):+ """Create the agent node function for LangGraph.++ The agent node:+ 1. Receives current state with messages+ 2. Invokes the LLM+ 3. Returns updated state with new AI message+ """+ def agent_node(state: AgentState) -> Dict[str, Any]:+ """Process messages through the LLM and return response."""+ messages = state["messages"]+ iteration = state.get("iteration", 0)+ max_iterations = state.get("max_iterations", 10)++ # Invoke the model+ response = chat_model.invoke(list(messages))++ # Check if we should continue (for future tool use)+ # Currently we just do single turn, but structure supports multi-turn+ should_continue = False++ return {+ "messages": [response], # Will be appended via operator.add+ "tool_outputs": {},+ "iteration": iteration + 1,+ "max_iterations": max_iterations,+ "should_continue": should_continue+ }++ return agent_node+++def should_continue(state: AgentState) -> str:+ """Determine if the agent should continue or end.++ This is the conditional edge function for LangGraph.+ Returns "continue" to loop back to tools, or "end" to finish.+ """+ if state.get("should_continue", False):+ if state.get("iteration", 0) < state.get("max_iterations", 10):+ return "continue"+ return "end"+++def build_agent_graph(chat_model):+ """Build the LangGraph agent workflow.++ Architecture:+ START -> agent -> (conditional) -> END+ ^ |+ | v+ +--- tools --+ (future: tool execution loop)++ For now, this is a simple single-node graph that can be extended+ with tool nodes when tool integration is added.+ """+ # Create the graph with our state schema+ graph = StateGraph(AgentState)++ # Add the agent node+ agent_fn = create_agent_node(chat_model)+ graph.add_node("agent", agent_fn)++ # Set entry point+ graph.set_entry_point("agent")++ # Add conditional edge - currently always ends, but structured for tools+ graph.add_conditional_edges(+ "agent",+ should_continue,+ {+ "continue": "agent", # Loop back for multi-turn (future tools)+ "end": END+ }+ )++ # Compile the graph+ return graph.compile()+++class AIService:+ """AI model service for LangChain operations."""++ def __init__(self, auth_service: AuthService, database, cache, settings: Settings):+ self.auth = auth_service+ self.database = database+ self.cache = cache+ self.settings = settings++ def detect_provider(self, model: str) -> str:+ """Detect AI provider from model name."""+ return detect_provider_from_model(model)++ def create_model(self, provider: str, api_key: str, model: str,+ temperature: float, max_tokens: int):+ """Create LangChain model instance using provider registry."""+ config = PROVIDER_CONFIGS.get(provider)+ if not config:+ raise ValueError(f"Unsupported provider: {provider}")++ # Build kwargs dynamically from registry config+ kwargs = {+ config.api_key_param: api_key,+ 'model': model,+ 'temperature': temperature,+ config.max_tokens_param: max_tokens+ }++ return config.model_class(**kwargs)++ async def fetch_models(self, provider: str, api_key: str) -> List[str]:+ """Fetch available models from provider API."""+ async with httpx.AsyncClient(timeout=self.settings.ai_timeout) as client:+ if provider == 'openai':+ response = await client.get(+ 'https://api.openai.com/v1/models',+ headers={'Authorization': f'Bearer {api_key}'}+ )+ response.raise_for_status()+ data = response.json()++ # Filter for chat models+ models = []+ for model in data.get('data', []):+ model_id = model['id'].lower()+ if (('gpt' in model_id or 'o1' in model_id) and+ 'instruct' not in model_id and 'embedding' not in model_id):+ models.append(model['id'])++ # Sort by priority+ priority = {'gpt-4o': 1, 'gpt-4o-mini': 2, 'gpt-4-turbo': 3, 'gpt-4': 4}+ return sorted(models, key=lambda x: priority.get(x, 99))++ elif provider == 'anthropic':+ response = await client.get(+ 'https://api.anthropic.com/v1/models',+ headers={+ 'x-api-key': api_key,+ 'anthropic-version': '2023-06-01'+ }+ )+ response.raise_for_status()+ data = response.json()+ return [model['id'] for model in data.get('data', [])+ if model.get('type') == 'model']++ elif provider == 'gemini':+ response = await client.get(+ f'https://generativelanguage.googleapis.com/v1beta/models?key={api_key}'+ )+ response.raise_for_status()+ data = response.json()++ models = []+ for model in data.get('models', []):+ name = model.get('name', '')+ if ('gemini' in name and+ 'generateContent' in model.get('supportedGenerationMethods', [])):+ models.append(name.replace('models/', ''))++ return sorted(models)++ else:+ raise ValueError(f"Unsupported provider: {provider}")++ async def execute_chat(self, node_id: str, node_type: str, parameters: Dict[str, Any]) -> Dict[str, Any]:+ """Execute AI chat model."""+ start_time = time.time()++ try:+ # Flatten options collection from frontend+ options = parameters.get('options', {})+ flattened = {**parameters, **options}++ # Extract parameters with camelCase/snake_case support for LangChain+ api_key = flattened.get('api_key') or flattened.get('apiKey')+ model = flattened.get('model', 'gpt-3.5-turbo')+ prompt = flattened.get('prompt', 'Hello')++ # System prompt/message - support multiple naming conventions+ system_prompt = (flattened.get('system_prompt') or+ flattened.get('systemMessage') or+ flattened.get('systemPrompt') or '')++ # Max tokens - support camelCase from frontend+ max_tokens = int(flattened.get('max_tokens') or+ flattened.get('maxTokens') or 1000)++ temperature = float(flattened.get('temperature', 0.7))++ if not api_key:+ raise ValueError("API key is required")++ # Create model+ provider = self.detect_provider(model)+ chat_model = self.create_model(provider, api_key, model, temperature, max_tokens)++ # Prepare messages+ messages = []+ if system_prompt:+ messages.append(SystemMessage(content=system_prompt))+ messages.append(HumanMessage(content=prompt))++ # Execute+ response = chat_model.invoke(messages)++ result = {+ "response": response.content,+ "model": model,+ "provider": provider,+ "finish_reason": "stop",+ "timestamp": datetime.now().isoformat()+ }++ log_execution_time(logger, "ai_chat", start_time, time.time())+ log_api_call(logger, provider, model, "chat", True)++ return {+ "success": True,+ "node_id": node_id,+ "node_type": node_type,+ "result": result,+ "execution_time": time.time() - start_time+ }++ except Exception as e:+ logger.error("AI execution failed", node_id=node_id, error=str(e))+ log_api_call(logger, provider if 'provider' in locals() else 'unknown',+ model if 'model' in locals() else 'unknown', "chat", False, error=str(e))++ return {+ "success": False,+ "node_id": node_id,+ "node_type": node_type,+ "error": str(e),+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ async def execute_agent(self, node_id: str, parameters: Dict[str, Any],+ memory_data: Optional[Dict[str, Any]] = None,+ broadcaster = None) -> Dict[str, Any]:+ """Execute AI Agent using LangGraph state machine.++ This method uses LangGraph for structured agent execution with:+ - State management via TypedDict+ - Conditional edges for future tool integration+ - Message accumulation via operator.add pattern+ - Real-time status broadcasts for UI animations++ Args:+ node_id: The node identifier+ parameters: Node parameters including prompt, model, etc.+ memory_data: Optional memory data from connected simpleMemory node+ containing session_id, window_size for conversation history+ broadcaster: Optional StatusBroadcaster for real-time UI updates+ """+ start_time = time.time()+ provider = 'unknown'+ model = 'unknown'++ # Helper to broadcast status updates+ async def broadcast_status(phase: str, details: Dict[str, Any] = None):+ if broadcaster:+ await broadcaster.update_node_status(node_id, "executing", {+ "phase": phase,+ "agent_type": "langgraph",+ **(details or {})+ })++ try:+ # Extract top-level parameters (always visible in UI)+ prompt = parameters.get('prompt', 'Hello')+ system_message = parameters.get('systemMessage', 'You are a helpful assistant')++ # Flatten options collection from frontend+ options = parameters.get('options', {})+ flattened = {**parameters, **options}++ # Extract parameters with camelCase/snake_case support+ api_key = flattened.get('api_key') or flattened.get('apiKey')+ provider = parameters.get('provider', 'openai')+ model = parameters.get('model', '')+ temperature = float(flattened.get('temperature', 0.7))+ max_tokens = int(flattened.get('max_tokens') or flattened.get('maxTokens') or 1000)++ logger.info(f"[LangGraph] AI Agent execution - Provider: {provider}, Model: {model}, Memory: {bool(memory_data)}")++ # If no model specified or model doesn't match provider, use default from registry+ if not model or not is_model_valid_for_provider(model, provider):+ old_model = model+ model = get_default_model(provider)+ if old_model:+ logger.warning(f"Model '{old_model}' invalid for provider '{provider}', using default: {model}")+ else:+ logger.info(f"No model specified, using default: {model}")++ if not api_key:+ raise ValueError("API key is required for AI Agent")++ # Broadcast: Initializing model+ await broadcast_status("initializing", {+ "message": f"Initializing {provider} model...",+ "provider": provider,+ "model": model+ })++ # Create LLM using the provider from node configuration+ logger.info(f"[LangGraph] Creating {provider} model: {model}")+ chat_model = self.create_model(provider, api_key, model, temperature, max_tokens)++ # Build initial messages for state+ initial_messages: List[BaseMessage] = []+ if system_message:+ initial_messages.append(SystemMessage(content=system_message))++ # Add memory history if connected simpleMemory node provided data+ session_id = None+ history_count = 0+ if memory_data and memory_data.get('session_id'):+ session_id = memory_data['session_id']+ window_size = memory_data.get('window_size')++ # Broadcast: Loading memory+ await broadcast_status("loading_memory", {+ "message": f"Loading conversation history...",+ "session_id": session_id,+ "has_memory": True+ })++ # Get conversation history from database+ history_data = await self.database.get_conversation_messages(session_id, window_size)+ history_count = len(history_data)++ # Convert to LangChain messages+ for m in history_data:+ if m['role'] == 'human':+ initial_messages.append(HumanMessage(content=m['content']))+ elif m['role'] == 'ai':+ initial_messages.append(AIMessage(content=m['content']))++ logger.info(f"[LangGraph Memory] Loaded {history_count} messages from session '{session_id}'")++ # Broadcast: Memory loaded+ await broadcast_status("memory_loaded", {+ "message": f"Loaded {history_count} messages from memory",+ "session_id": session_id,+ "history_count": history_count+ })++ # Add current user prompt+ initial_messages.append(HumanMessage(content=prompt))++ # Broadcast: Building graph+ await broadcast_status("building_graph", {+ "message": "Building LangGraph agent...",+ "message_count": len(initial_messages),+ "has_memory": bool(session_id),+ "history_count": history_count+ })++ # Build and execute LangGraph agent+ logger.info(f"[LangGraph] Building agent graph with {len(initial_messages)} initial messages")+ agent_graph = build_agent_graph(chat_model)++ # Create initial state+ initial_state: AgentState = {+ "messages": initial_messages,+ "tool_outputs": {},+ "iteration": 0,+ "max_iterations": 10,+ "should_continue": False+ }++ # Broadcast: Executing graph+ await broadcast_status("invoking_llm", {+ "message": f"Invoking {provider} LLM...",+ "provider": provider,+ "model": model,+ "iteration": 1,+ "has_memory": bool(session_id),+ "history_count": history_count+ })++ # Execute the graph+ final_state = agent_graph.invoke(initial_state)++ # Extract the AI response (last message in the accumulated messages)+ all_messages = final_state["messages"]+ ai_response = all_messages[-1] if all_messages else None++ if not ai_response or not hasattr(ai_response, 'content'):+ raise ValueError("No response generated from agent")++ response_content = ai_response.content+ iterations = final_state.get("iteration", 1)++ logger.info(f"[LangGraph] Agent completed in {iterations} iteration(s)")++ # Save to memory if connected (persist to database)+ if session_id:+ # Broadcast: Saving to memory+ await broadcast_status("saving_memory", {+ "message": "Saving to conversation memory...",+ "session_id": session_id,+ "has_memory": True,+ "history_count": history_count+ })++ await self.database.add_conversation_message(session_id, 'human', prompt)+ await self.database.add_conversation_message(session_id, 'ai', response_content)+ logger.info(f"[LangGraph Memory] Saved exchange to session '{session_id}'")++ result = {+ "response": response_content,+ "model": model,+ "provider": provider,+ "agent_type": "langgraph",+ "iterations": iterations,+ "finish_reason": "stop",+ "timestamp": datetime.now().isoformat()+ }++ # Add memory info if used+ if session_id:+ result["memory"] = {+ "session_id": session_id,+ "history_loaded": history_count+ }++ log_execution_time(logger, "ai_agent_langgraph", start_time, time.time())+ log_api_call(logger, provider, model, "agent", True)++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "aiAgent",+ "result": result,+ "execution_time": time.time() - start_time+ }++ except Exception as e:+ logger.error("[LangGraph] AI agent execution failed", node_id=node_id, error=str(e))+ log_api_call(logger, provider, model, "agent", False, error=str(e))++ return {+ "success": False,+ "node_id": node_id,+ "node_type": "aiAgent",+ "error": str(e),+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }\ No newline at end of filediff --git a/server/services/android/__init__.py b/server/services/android/__init__.pynew file mode 100644index 00000000..f4cb7176--- /dev/null+++ b/server/services/android/__init__.py@@ -0,0 +1,27 @@+"""+Android Services Relay Module++Modular WebSocket client for Android device communication using JSON-RPC 2.0 protocol.++Connection: wss://<relay-server>/ws?client_type=web&api_key=<your-api-key>++Components:+- client.py: RelayWebSocketClient class+- protocol.py: JSON-RPC 2.0 message handling+- manager.py: Global client instance management+- broadcaster.py: Status broadcasting to frontend+"""++from .client import RelayWebSocketClient+from .manager import (+ get_relay_client,+ close_relay_client,+ get_current_relay_client,+)++__all__ = [+ "RelayWebSocketClient",+ "get_relay_client",+ "close_relay_client",+ "get_current_relay_client",+]diff --git a/server/services/android/broadcaster.py b/server/services/android/broadcaster.pynew file mode 100644index 00000000..9da152e8--- /dev/null+++ b/server/services/android/broadcaster.py@@ -0,0 +1,114 @@+"""+Android Status Broadcaster++Broadcasts Android relay connection status changes to frontend WebSocket clients.+"""+from typing import Optional, Set+import structlog++logger = structlog.get_logger()+++async def broadcast_android_status(+ connected: bool,+ paired: bool = False,+ device_id: Optional[str] = None,+ device_name: Optional[str] = None,+ devices: Optional[Set[str]] = None,+ qr_data: Optional[str] = None,+ session_token: Optional[str] = None+):+ """+ Broadcast Android relay status changes to frontend WebSocket clients.++ Args:+ connected: Whether connected to relay server+ paired: Whether paired with Android device+ device_id: Paired device ID (if any)+ device_name: Paired device name (if any)+ devices: Set of all connected device IDs+ qr_data: QR code data for pairing (app://pair?token=...)+ session_token: Relay session token+ """+ try:+ from services.status_broadcaster import get_status_broadcaster+ broadcaster = get_status_broadcaster()+ await broadcaster.update_android_status(+ connected=connected,+ paired=paired,+ device_id=device_id,+ device_name=device_name,+ connected_devices=list(devices) if devices else [],+ connection_type="relay" if connected else None,+ qr_data=qr_data,+ session_token=session_token+ )+ except Exception as e:+ logger.warning("[Android] Failed to broadcast status", error=str(e))+++async def broadcast_connected(device_id: str, device_name: Optional[str] = None):+ """Broadcast that Android device is paired"""+ await broadcast_android_status(+ connected=True,+ paired=True,+ device_id=device_id,+ device_name=device_name,+ devices={device_id} if device_id else set()+ )+++async def broadcast_device_disconnected(+ relay_connected: bool = True,+ qr_data: Optional[str] = None,+ session_token: Optional[str] = None+):+ """Broadcast that Android device is disconnected (but relay may still be connected).++ This is called when the Android device unpairs. The relay connection may still be active.+ Use broadcast_relay_disconnected() when the relay connection itself is closed.++ Args:+ relay_connected: Whether the relay WebSocket is still connected+ qr_data: QR code data for re-pairing+ session_token: Current session token+ """+ await broadcast_android_status(+ connected=relay_connected, # Relay may still be connected+ paired=False, # Device is disconnected+ device_id=None,+ device_name=None,+ devices=set(),+ qr_data=qr_data, # Keep QR data for re-pairing+ session_token=session_token+ )+++async def broadcast_relay_disconnected():+ """Broadcast that relay connection is closed (fully disconnected)"""+ await broadcast_android_status(+ connected=False,+ paired=False,+ device_id=None,+ device_name=None,+ devices=set()+ )+++# Legacy alias for backwards compatibility+async def broadcast_disconnected():+ """Legacy alias - use broadcast_device_disconnected or broadcast_relay_disconnected instead"""+ await broadcast_relay_disconnected()+++async def broadcast_qr_code(qr_data: str, session_token: Optional[str] = None):+ """Broadcast QR code for pairing"""+ await broadcast_android_status(+ connected=True, # Connected to relay but not paired+ paired=False,+ device_id=None,+ device_name=None,+ devices=set(),+ qr_data=qr_data,+ session_token=session_token+ )diff --git a/server/services/android/client.py b/server/services/android/client.pynew file mode 100644index 00000000..4068ef70--- /dev/null+++ b/server/services/android/client.py@@ -0,0 +1,545 @@+"""+Android Services Relay WebSocket Client++Handles WebSocket connection to relay server and communication with paired Android device.++Connection flow:+1. Connect to wss://<relay-server>/ws?client_type=web&api_key=<your-api-key>+2. Receive connection.established with session_token and qr_data+3. Display QR code for Android to scan+4. Receive pairing.connected when Android pairs+5. Exchange messages via relay.send / relay.message+"""+import asyncio+import json+import uuid+import aiohttp+from typing import Optional, Dict, Any, Set, Callable+from datetime import datetime+import structlog++from .protocol import RPCRequest, RPCResponse, RPCEvent, RPCRequestTracker, parse_message, is_response+from .broadcaster import (+ broadcast_android_status,+ broadcast_connected,+ broadcast_device_disconnected,+ broadcast_relay_disconnected,+ broadcast_qr_code+)++logger = structlog.get_logger()+++class RelayWebSocketClient:+ """WebSocket client for Android Services Relay using JSON-RPC 2.0 protocol"""++ def __init__(self, base_url: str, api_key: str):+ """+ Initialize relay client.++ Args:+ base_url: Base WebSocket URL (e.g., 'wss://your-relay-server.com/ws')+ api_key: API key for authentication+ """+ self.base_url = base_url+ self.api_key = api_key+ self.url = f"{base_url}?client_type=web&api_key={api_key}"++ # WebSocket connection+ self.ws: Optional[aiohttp.ClientWebSocketResponse] = None+ self.session: Optional[aiohttp.ClientSession] = None+ self.connected = False++ # JSON-RPC request tracking+ self._rpc_tracker = RPCRequestTracker()++ # Pairing state+ self.session_token: Optional[str] = None+ self.qr_data: Optional[str] = None+ self.paired = False+ self.paired_device_id: Optional[str] = None+ self.paired_device_name: Optional[str] = None++ # Background tasks+ self._receive_task: Optional[asyncio.Task] = None+ self._keepalive_task: Optional[asyncio.Task] = None+ self._running = False++ # Service response queues (requestId -> queue)+ self._service_queues: Dict[str, asyncio.Queue] = {}++ # Event callbacks+ self.on_pairing_connected: Optional[Callable] = None+ self.on_pairing_disconnected: Optional[Callable] = None+ self.on_relay_message: Optional[Callable] = None++ # =========================================================================+ # Connection Management+ # =========================================================================++ async def connect(self) -> tuple[bool, str]:+ """Connect to relay WebSocket server.++ Returns:+ Tuple of (success: bool, error_message: str)+ """+ try:+ logger.info("[Relay] Connecting...", url=self.url)+ timeout = aiohttp.ClientTimeout(total=None, connect=10, sock_read=300)+ self.session = aiohttp.ClientSession(timeout=timeout)++ self.ws = await self.session.ws_connect(+ self.url,+ heartbeat=30,+ autoping=True,+ ssl=True # Explicit SSL for wss://+ )+ self.connected = True+ self._running = True++ logger.info("[Relay] WebSocket connected, waiting for server message...", url=self.base_url)++ # Wait for connection.established event+ msg = await asyncio.wait_for(self.ws.receive(), timeout=10.0)++ if msg.type == aiohttp.WSMsgType.TEXT:+ data = json.loads(msg.data)+ method = data.get("method")+ logger.info("[Relay] Received initial message", method=method)++ # Handle both "welcome" and "connection.established" methods+ if method in ("welcome", "connection.established"):+ params = data.get("params", {})+ self.session_token = params.get("session_token")+ self.qr_data = params.get("qr_data")++ logger.info("[Relay] Connection established",+ session_token=self.session_token,+ has_qr=bool(self.qr_data))++ # Broadcast QR data to frontend+ if self.qr_data:+ await broadcast_qr_code(self.qr_data)++ # Start background tasks+ self._receive_task = asyncio.create_task(self._receive_loop())+ self._keepalive_task = asyncio.create_task(self._keepalive_loop())++ return True, ""+ elif data.get("error"):+ error_msg = data.get("error", {}).get("message", "Unknown server error")+ logger.error("[Relay] Server error", error=error_msg)+ return False, f"Server error: {error_msg}"+ else:+ logger.error("[Relay] Unexpected initial message", data=data)+ return False, f"Unexpected response: {method or 'unknown'}"++ elif msg.type == aiohttp.WSMsgType.CLOSE:+ close_code = msg.data+ close_reason = msg.extra or "Unknown"+ logger.error("[Relay] Connection closed by server", code=close_code, reason=close_reason)+ return False, f"Connection closed: {close_reason} (code {close_code})"++ elif msg.type == aiohttp.WSMsgType.ERROR:+ logger.error("[Relay] WebSocket error on receive")+ return False, "WebSocket error during handshake"++ return False, "No response from server"++ except asyncio.TimeoutError:+ logger.error("[Relay] Connection timeout")+ return False, "Connection timeout - server not responding"+ except aiohttp.ClientConnectorError as e:+ logger.error("[Relay] Connection failed", error=str(e))+ return False, f"Cannot connect to server: {str(e)}"+ except aiohttp.WSServerHandshakeError as e:+ logger.error("[Relay] WebSocket handshake failed", error=str(e))+ return False, f"WebSocket handshake failed: {str(e)}"+ except Exception as e:+ logger.error("[Relay] Connection error", error=str(e), exc_info=True)+ return False, f"Connection error: {str(e)}"++ async def disconnect(self):+ """Close connection and cleanup."""+ logger.info("[Relay] Disconnecting...")+ self._running = False++ # Cancel background tasks+ for task in [self._keepalive_task, self._receive_task]:+ if task and not task.done():+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass++ # Close WebSocket+ if self.ws and not self.ws.closed:+ await self.ws.close()++ if self.session and not self.session.closed:+ await self.session.close()++ # Reset state+ self.connected = False+ self.paired = False+ self.paired_device_id = None+ self.paired_device_name = None+ self.session_token = None+ self.qr_data = None++ # Cancel pending RPC requests+ self._rpc_tracker.cancel_all()++ # Broadcast relay disconnection (fully disconnected from relay server)+ await broadcast_relay_disconnected()++ logger.info("[Relay] Disconnected")++ def is_connected(self) -> bool:+ """Check if connected to relay server."""+ return self.connected and self._running and self.ws is not None and not self.ws.closed++ def is_paired(self) -> bool:+ """Check if paired with Android device."""+ return self.paired and self.paired_device_id is not None++ # =========================================================================+ # Background Tasks+ # =========================================================================++ async def _receive_loop(self):+ """Background task to receive messages."""+ logger.info("[Relay] Receive loop started")+ unexpected_disconnect = False+ try:+ while self._running and self.ws and not self.ws.closed:+ try:+ msg = await self.ws.receive()++ if msg.type == aiohttp.WSMsgType.TEXT:+ data = json.loads(msg.data)+ await self._handle_message(data)++ elif msg.type == aiohttp.WSMsgType.CLOSED:+ logger.warning("[Relay] Connection closed by server")+ self._running = False+ unexpected_disconnect = True+ break++ elif msg.type == aiohttp.WSMsgType.ERROR:+ logger.error("[Relay] WebSocket error")+ self._running = False+ unexpected_disconnect = True+ break++ except Exception as e:+ logger.error("[Relay] Receive error", error=str(e))+ await asyncio.sleep(1)++ except asyncio.CancelledError:+ pass+ finally:+ self._running = False+ self.connected = False+ logger.info("[Relay] Receive loop stopped")++ # Broadcast relay disconnection if connection dropped unexpectedly+ if unexpected_disconnect:+ try:+ await broadcast_relay_disconnected()+ except Exception as e:+ logger.warning("[Relay] Failed to broadcast disconnection", error=str(e))++ async def _keepalive_loop(self):+ """Background keepalive task."""+ try:+ while self._running and self.ws and not self.ws.closed:+ await asyncio.sleep(25)+ if self._running and self.ws and not self.ws.closed:+ try:+ await self.ws.send_json({+ "jsonrpc": "2.0",+ "method": "ping",+ "params": {}+ })+ except Exception as e:+ logger.error("[Relay] Keepalive error", error=str(e))+ self._running = False+ break+ except asyncio.CancelledError:+ pass++ # =========================================================================+ # Message Handling+ # =========================================================================++ async def _handle_message(self, data: dict):+ """Handle incoming JSON-RPC message."""+ # Log ALL incoming messages for debugging+ method = data.get("method", "")+ logger.info("[Relay] Received message", method=method, has_result="result" in data, has_error="error" in data)++ # Check if response to pending request+ if is_response(data):+ response = RPCResponse.from_dict(data)+ logger.debug("[Relay] Processing as RPC response", id=response.id)+ if self._rpc_tracker.resolve(response):+ return++ # Handle server events+ params = data.get("params", {})++ if method == "pairing.connected":+ await self._handle_pairing_connected(params)++ elif method == "pairing.disconnected":+ await self._handle_pairing_disconnected(params)++ elif method == "relay.message":+ await self._handle_relay_message(params)++ elif method == "connection.established":+ # Reconnect scenario+ self.session_token = params.get("session_token")+ self.qr_data = params.get("qr_data")+ if self.qr_data:+ await broadcast_qr_code(self.qr_data)++ async def _handle_pairing_connected(self, params: dict):+ """Handle pairing.connected event."""+ self.paired = True+ self.paired_device_id = params.get("device_id")+ self.paired_device_name = params.get("device_name")++ logger.info("[Relay] Android paired",+ device_id=self.paired_device_id,+ device_name=self.paired_device_name)++ await broadcast_connected(self.paired_device_id, self.paired_device_name)++ if self.on_pairing_connected:+ await self.on_pairing_connected(params)++ async def _handle_pairing_disconnected(self, params: dict):+ """Handle pairing.disconnected event.++ The Android device has disconnected, but the relay connection may still be active.+ This allows the user to re-scan the QR code without reconnecting to the relay.+ """+ reason = params.get("reason", "unknown")+ logger.info("[Relay] Android device disconnected", reason=reason)++ self.paired = False+ self.paired_device_id = None+ self.paired_device_name = None++ # Broadcast device disconnection - relay is still connected, pass QR data for re-pairing+ await broadcast_device_disconnected(+ relay_connected=self.is_connected(),+ qr_data=self.qr_data,+ session_token=self.session_token+ )++ if self.on_pairing_disconnected:+ await self.on_pairing_disconnected(params)++ async def _handle_relay_message(self, params: dict):+ """Handle relay.message event from Android.++ Schema: relay.message params = {"data": {...}}+ The data contains the actual message from Android.+ """+ # Schema: params = {"data": {...}}+ data = params.get("data", {})++ logger.info("[Relay] relay.message received",+ data_keys=list(data.keys()) if isinstance(data, dict) else "not_dict",+ data=data)++ # Route to service response queue if matching request_id+ # Android app uses "request_id" (underscore), not "requestId" (camelCase)+ request_id = data.get("request_id")+ logger.info("[Relay] Checking request_id", request_id=request_id, waiting_for=list(self._service_queues.keys()))++ if request_id and request_id in self._service_queues:+ logger.info("[Relay] Routing to service queue", request_id=request_id)+ await self._service_queues[request_id].put(data)+ elif self.on_relay_message:+ logger.info("[Relay] Passing to on_relay_message callback")+ await self.on_relay_message(data)+ else:+ logger.warning("[Relay] Unhandled relay message", request_id=request_id, data=data)++ # =========================================================================+ # RPC Methods+ # =========================================================================++ async def call(self, method: str, params: Dict[str, Any] = None, timeout: float = 30) -> Any:+ """+ Make JSON-RPC 2.0 call and wait for response.++ Args:+ method: RPC method name+ params: Method parameters+ timeout: Response timeout in seconds++ Returns:+ Result from the RPC call+ """+ if not self.is_connected():+ raise Exception("Not connected to relay server")++ request, future = self._rpc_tracker.create_request(method, params)++ try:+ req_dict = request.to_dict()+ logger.debug("[Relay] Sending RPC request", method=method, id=request.id)+ await self.ws.send_json(req_dict)+ result = await asyncio.wait_for(future, timeout)+ logger.debug("[Relay] RPC response received", method=method, id=request.id)+ return result+ except asyncio.TimeoutError:+ self._rpc_tracker.cancel(request.id)+ raise Exception(f"RPC call '{method}' timed out after {timeout}s")++ async def get_pairing_status(self) -> Dict[str, Any]:+ """Get current pairing status."""+ return await self.call("pairing.status")++ async def disconnect_pairing(self) -> Dict[str, Any]:+ """End pairing session."""+ result = await self.call("pairing.disconnect")+ self.paired = False+ self.paired_device_id = None+ self.paired_device_name = None+ return result++ async def relay_send(self, data: Dict[str, Any], timeout: float = 30) -> Dict[str, Any]:+ """+ Send message to paired Android device via relay.++ Schema: relay.send params = {"data": {...}}++ Args:+ data: Message data to send to Android device+ timeout: Response timeout+ """+ if not self.paired:+ raise Exception("Not paired with Android device")++ logger.info("[Relay] Sending relay.send RPC", data=data)++ # Schema: {"jsonrpc": "2.0", "method": "relay.send", "params": {"data": {...}}, "id": 1}+ result = await self.call("relay.send", {"data": data}, timeout=timeout)+ logger.info("[Relay] relay.send RPC response", result=result)+ return result++ # =========================================================================+ # Service Requests+ # =========================================================================++ async def send_service_request(+ self,+ service_id: str,+ action: str,+ parameters: Dict[str, Any] = None,+ target_id: Optional[str] = None, # Ignored, kept for compatibility+ timeout: float = 30.0+ ) -> Optional[Dict[str, Any]]:+ """+ Send service request to paired Android device.++ Args:+ service_id: Android service ID (e.g., 'battery', 'wifi_automation')+ action: Service action (e.g., 'status', 'enable')+ parameters: Action parameters+ target_id: Ignored (kept for API compatibility)+ timeout: Response timeout in seconds++ Returns:+ Response data or None if timeout/error+ """+ if not self.paired:+ logger.error("[Relay] Cannot send - not paired")+ return None++ request_id = str(uuid.uuid4())+ response_queue: asyncio.Queue = asyncio.Queue()+ self._service_queues[request_id] = response_queue++ try:+ # Send via relay - schema: relay.send params = {"data": {...}}+ # Field names must match Android app expectations:+ # - service (not serviceId)+ # - action+ # - request_id (not requestId)+ # - params (not parameters)+ await self.relay_send({+ "service": service_id,+ "action": action,+ "request_id": request_id,+ "params": parameters or {}+ }, timeout=5.0)++ logger.info("[Relay] Sent service request",+ request_id=request_id,+ service_id=service_id,+ action=action)++ # Wait for response+ logger.info("[Relay] Waiting for response", request_id=request_id, timeout=timeout)+ response = await asyncio.wait_for(response_queue.get(), timeout=timeout)+ logger.info("[Relay] Service response received", request_id=request_id, response_keys=list(response.keys()) if isinstance(response, dict) else "not_dict")+ return response++ except asyncio.TimeoutError:+ logger.warning("[Relay] Service response timeout", request_id=request_id, timeout=timeout, pending_queues=list(self._service_queues.keys()))+ return None+ except Exception as e:+ logger.error("[Relay] Service request error", error=str(e))+ return None+ finally:+ self._service_queues.pop(request_id, None)++ async def wait_for_pairing(self, timeout: float = 60.0) -> bool:+ """+ Wait for Android device to pair.++ Args:+ timeout: Maximum time to wait in seconds++ Returns:+ True if paired successfully, False if timeout+ """+ if self.paired:+ return True++ logger.info("[Relay] Waiting for pairing...", timeout=timeout)++ start = asyncio.get_event_loop().time()+ while asyncio.get_event_loop().time() - start < timeout:+ if self.paired:+ return True+ await asyncio.sleep(0.5)++ logger.warning("[Relay] Pairing timeout")+ return False++ # =========================================================================+ # Legacy Compatibility+ # =========================================================================++ def get_android_device_id(self) -> Optional[str]:+ """Get paired Android device ID."""+ return self.paired_device_id++ def has_real_android_devices(self) -> bool:+ """Check if paired with Android device."""+ return self.paired++ def get_connected_devices(self) -> Set[str]:+ """Get set of connected Android device IDs."""+ if self.paired_device_id:+ return {self.paired_device_id}+ return set()diff --git a/server/services/android/manager.py b/server/services/android/manager.pynew file mode 100644index 00000000..5d1b585e--- /dev/null+++ b/server/services/android/manager.py@@ -0,0 +1,73 @@+"""+Android Relay Client Manager++Global instance management for persistent WebSocket connection.+Provides singleton pattern for reusing connection across API requests.+"""+from typing import Optional+import structlog++from .client import RelayWebSocketClient++logger = structlog.get_logger()++# Global client instance+_relay_client: Optional[RelayWebSocketClient] = None+++async def get_relay_client(base_url: str, api_key: str) -> tuple[Optional[RelayWebSocketClient], str]:+ """+ Get or create persistent relay client instance.++ Args:+ base_url: WebSocket URL (e.g., 'wss://your-relay-server.com/ws')+ api_key: API key for authentication++ Returns:+ Tuple of (client or None, error_message)+ """+ global _relay_client++ # Reuse existing connection if valid+ if _relay_client and _relay_client.is_connected():+ logger.info("[Manager] Reusing existing connection")+ return _relay_client, ""++ # Close stale connection+ if _relay_client:+ await _relay_client.disconnect()++ # Create new connection+ logger.info("[Manager] Creating new connection", url=base_url)+ _relay_client = RelayWebSocketClient(base_url, api_key)+ connected, error = await _relay_client.connect()++ if connected:+ logger.info("[Manager] Connection established")+ return _relay_client, ""+ else:+ _relay_client = None+ logger.error("[Manager] Failed to connect", error=error)+ return None, error+++async def close_relay_client():+ """Close global relay client."""+ global _relay_client+ if _relay_client:+ logger.info("[Manager] Closing connection")+ await _relay_client.disconnect()+ _relay_client = None+++def get_current_relay_client() -> Optional[RelayWebSocketClient]:+ """+ Get current relay client if connected.++ Returns:+ Connected client or None+ """+ global _relay_client+ if _relay_client and _relay_client.is_connected():+ return _relay_client+ return Nonediff --git a/server/services/android/protocol.py b/server/services/android/protocol.pynew file mode 100644index 00000000..f773aa85--- /dev/null+++ b/server/services/android/protocol.py@@ -0,0 +1,165 @@+"""+JSON-RPC 2.0 Protocol for Android Services Relay++Handles message encoding/decoding and request/response tracking.++Request format: {"jsonrpc": "2.0", "method": "...", "params": {...}, "id": 1}+Response format: {"jsonrpc": "2.0", "result": {...}, "id": 1}+Event format: {"jsonrpc": "2.0", "method": "...", "params": {...}}++Error codes:+- -32600: Invalid request+- -32601: Method not found+- -32602: Invalid params+- -32001: Not paired+- -32002: Pairing failed+- -32003: Relay error+"""+import asyncio+from dataclasses import dataclass, field+from typing import Dict, Any, Optional+from enum import Enum+++class RPCErrorCode(Enum):+ """JSON-RPC 2.0 error codes"""+ INVALID_REQUEST = -32600+ METHOD_NOT_FOUND = -32601+ INVALID_PARAMS = -32602+ NOT_PAIRED = -32001+ PAIRING_FAILED = -32002+ RELAY_ERROR = -32003+++@dataclass+class RPCRequest:+ """JSON-RPC 2.0 request"""+ method: str+ params: Dict[str, Any] = field(default_factory=dict)+ id: Optional[int] = None++ def to_dict(self) -> Dict[str, Any]:+ msg = {+ "jsonrpc": "2.0",+ "method": self.method,+ "params": self.params,+ }+ if self.id is not None:+ msg["id"] = self.id+ return msg+++@dataclass+class RPCResponse:+ """JSON-RPC 2.0 response"""+ id: int+ result: Optional[Any] = None+ error: Optional[Dict[str, Any]] = None++ @property+ def is_error(self) -> bool:+ return self.error is not None++ @classmethod+ def from_dict(cls, data: Dict[str, Any]) -> "RPCResponse":+ return cls(+ id=data.get("id"),+ result=data.get("result"),+ error=data.get("error"),+ )+++@dataclass+class RPCEvent:+ """JSON-RPC 2.0 server event (notification without id)"""+ method: str+ params: Dict[str, Any] = field(default_factory=dict)++ @classmethod+ def from_dict(cls, data: Dict[str, Any]) -> "RPCEvent":+ return cls(+ method=data.get("method", ""),+ params=data.get("params", {}),+ )+++class RPCRequestTracker:+ """Tracks pending JSON-RPC requests and matches responses"""++ def __init__(self):+ self._request_id = 0+ self._pending: Dict[int, asyncio.Future] = {}++ def next_id(self) -> int:+ """Get next request ID"""+ self._request_id += 1+ return self._request_id++ def create_request(self, method: str, params: Dict[str, Any] = None) -> tuple[RPCRequest, asyncio.Future]:+ """Create request and future for response"""+ request_id = self.next_id()+ request = RPCRequest(method=method, params=params or {}, id=request_id)++ loop = asyncio.get_event_loop()+ future = loop.create_future()+ self._pending[request_id] = future++ return request, future++ def resolve(self, response: RPCResponse) -> bool:+ """Resolve pending request with response. Returns True if matched."""+ if response.id not in self._pending:+ return False++ future = self._pending.pop(response.id)++ if response.is_error:+ error_msg = response.error.get("message", "RPC Error")+ future.set_exception(RPCError(error_msg, response.error.get("code")))+ else:+ future.set_result(response.result)++ return True++ def cancel(self, request_id: int) -> bool:+ """Cancel pending request. Returns True if found."""+ if request_id in self._pending:+ future = self._pending.pop(request_id)+ future.cancel()+ return True+ return False++ def cancel_all(self):+ """Cancel all pending requests"""+ for future in self._pending.values():+ future.cancel()+ self._pending.clear()++ @property+ def pending_count(self) -> int:+ return len(self._pending)+++class RPCError(Exception):+ """JSON-RPC error"""+ def __init__(self, message: str, code: int = None):+ super().__init__(message)+ self.code = code+++def parse_message(data: Dict[str, Any]) -> RPCResponse | RPCEvent:+ """Parse incoming message as response or event"""+ if "id" in data and data["id"] is not None:+ return RPCResponse.from_dict(data)+ else:+ return RPCEvent.from_dict(data)+++def is_response(data: Dict[str, Any]) -> bool:+ """Check if message is a response (has id)"""+ return "id" in data and data["id"] is not None+++def is_event(data: Dict[str, Any]) -> bool:+ """Check if message is an event (no id, has method)"""+ return ("id" not in data or data["id"] is None) and "method" in datadiff --git a/server/services/android_service.py b/server/services/android_service.pynew file mode 100644index 00000000..701dbfc0--- /dev/null+++ b/server/services/android_service.py@@ -0,0 +1,588 @@+"""Android System Services integration."""++import time+import httpx+import asyncio+from datetime import datetime+from typing import Dict, Any, Optional, List++from core.logging import get_logger, log_execution_time++logger = get_logger(__name__)++# Default parameters for service actions (based on web_tester DEFAULTS)+SERVICE_DEFAULT_PARAMETERS = {+ ('app_launcher', 'launch'): '{"package_name": "com.android.settings"}',+ ('wifi_automation', 'enable'): '{}',+ ('wifi_automation', 'disable'): '{}',+ ('wifi_automation', 'status'): '{}',+ ('wifi_automation', 'scan'): '{}',+ ('bluetooth_automation', 'enable'): '{}',+ ('bluetooth_automation', 'disable'): '{}',+ ('bluetooth_automation', 'status'): '{}',+ ('audio_automation', 'get_volume'): '{}',+ ('audio_automation', 'set_volume'): '{"volume": 50}',+ ('audio_automation', 'mute'): '{}',+ ('audio_automation', 'unmute'): '{}',+ ('media_control', 'volume_control'): '{"action": "get_volume"}',+ ('media_control', 'media_control'): '{"action": "play"}',+ ('media_control', 'play_media'): '{"url": "https://www.soundjay.com/misc/bell-ringing-05.wav"}',+ ('camera_control', 'camera_info'): '{}',+ ('camera_control', 'take_photo'): '{"filename": "test_photo.jpg"}',+ ('motion_detection', 'current_motion'): '{}',+ ('motion_detection', 'shake_detection'): '{}',+ ('environmental_sensors', 'ambient_conditions'): '{}',+ ('environmental_sensors', 'proximity'): '{}',+ ('location', 'current'): '{}',+ ('location', 'start_tracking'): '{}',+ ('location', 'stop_tracking'): '{}',+ ('device_state_automation', 'airplane_mode'): '{"enabled": true}',+ ('device_state_automation', 'screen_on'): '{}',+ ('device_state_automation', 'screen_off'): '{}',+ ('device_state_automation', 'status'): '{}',+ ('screen_control_automation', 'brightness'): '{"level": 150}',+ ('screen_control_automation', 'wake'): '{}',+ ('screen_control_automation', 'status'): '{}',+ ('app_list', 'list'): '{"include_system": false, "include_disabled": false}',+ ('app_killer', 'kill'): '{"package_name": "com.example.app"}',+ ('app_usage', 'stats'): '{}',+ ('battery', 'status'): '{}',+ ('network', 'status'): '{}',+ ('system_info', 'info'): '{}',+ ('airplane_mode_control', 'status'): '{}'+}++# Service action mappings based on Android service schemas+SERVICE_ACTIONS = {+ 'battery': [+ {'name': 'Status', 'value': 'status', 'description': 'Get battery status information'}+ ],+ 'network': [+ {'name': 'Status', 'value': 'status', 'description': 'Get network connectivity status'}+ ],+ 'system_info': [+ {'name': 'Info', 'value': 'info', 'description': 'Get system and device information'}+ ],+ 'location': [+ {'name': 'Current', 'value': 'current', 'description': 'Get current location'},+ {'name': 'Start Tracking', 'value': 'start_tracking', 'description': 'Start location tracking'},+ {'name': 'Stop Tracking', 'value': 'stop_tracking', 'description': 'Stop location tracking'}+ ],+ 'app_launcher': [+ {'name': 'Launch', 'value': 'launch', 'description': 'Launch an application'}+ ],+ 'app_list': [+ {'name': 'List', 'value': 'list', 'description': 'Get list of installed apps'}+ ],+ 'app_killer': [+ {'name': 'Kill', 'value': 'kill', 'description': 'Force stop an application'}+ ],+ 'app_usage': [+ {'name': 'Stats', 'value': 'stats', 'description': 'Get app usage statistics'}+ ],+ 'wifi_automation': [+ {'name': 'Enable', 'value': 'enable', 'description': 'Enable WiFi'},+ {'name': 'Disable', 'value': 'disable', 'description': 'Disable WiFi'},+ {'name': 'Status', 'value': 'status', 'description': 'Get WiFi status'},+ {'name': 'Scan', 'value': 'scan', 'description': 'Scan for networks'}+ ],+ 'bluetooth_automation': [+ {'name': 'Enable', 'value': 'enable', 'description': 'Enable Bluetooth'},+ {'name': 'Disable', 'value': 'disable', 'description': 'Disable Bluetooth'},+ {'name': 'Status', 'value': 'status', 'description': 'Get Bluetooth status'}+ ],+ 'audio_automation': [+ {'name': 'Get Volume', 'value': 'get_volume', 'description': 'Get current volume'},+ {'name': 'Set Volume', 'value': 'set_volume', 'description': 'Set volume level'},+ {'name': 'Mute', 'value': 'mute', 'description': 'Mute audio'},+ {'name': 'Unmute', 'value': 'unmute', 'description': 'Unmute audio'}+ ],+ 'device_state_automation': [+ {'name': 'Airplane Mode', 'value': 'airplane_mode', 'description': 'Toggle airplane mode'},+ {'name': 'Screen On', 'value': 'screen_on', 'description': 'Turn screen on'},+ {'name': 'Screen Off', 'value': 'screen_off', 'description': 'Turn screen off'},+ {'name': 'Status', 'value': 'status', 'description': 'Get device state'}+ ],+ 'screen_control_automation': [+ {'name': 'Brightness', 'value': 'brightness', 'description': 'Set brightness level'},+ {'name': 'Wake', 'value': 'wake', 'description': 'Wake up screen'},+ {'name': 'Status', 'value': 'status', 'description': 'Get screen status'}+ ],+ 'motion_detection': [+ {'name': 'Current Motion', 'value': 'current_motion', 'description': 'Get current motion data'},+ {'name': 'Shake Detection', 'value': 'shake_detection', 'description': 'Detect shake gesture'}+ ],+ 'environmental_sensors': [+ {'name': 'Ambient Conditions', 'value': 'ambient_conditions', 'description': 'Get temperature, humidity, pressure'},+ {'name': 'Proximity', 'value': 'proximity', 'description': 'Get proximity sensor data'}+ ],+ 'camera_control': [+ {'name': 'Camera Info', 'value': 'camera_info', 'description': 'Get camera information'},+ {'name': 'Take Photo', 'value': 'take_photo', 'description': 'Capture a photo'}+ ],+ 'media_control': [+ {'name': 'Volume Control', 'value': 'volume_control', 'description': 'Control media volume'},+ {'name': 'Media Control', 'value': 'media_control', 'description': 'Control playback'},+ {'name': 'Play Media', 'value': 'play_media', 'description': 'Play media file'}+ ],+ 'airplane_mode_control': [+ {'name': 'Status', 'value': 'status', 'description': 'Get airplane mode status'}+ ],+ # Unavailable services on current device (emulator-5554)+ # These services returned "Service not available" errors during testing+ # 'notification_sender': [+ # {'name': 'Send', 'value': 'send', 'description': 'Send notification'}+ # ],+ # 'contact_list': [+ # {'name': 'List', 'value': 'list', 'description': 'Get contacts list'}+ # ],+ # 'clipboard_automation': [+ # {'name': 'Get', 'value': 'get', 'description': 'Get clipboard content'},+ # {'name': 'Set', 'value': 'set', 'description': 'Set clipboard content'}+ # ],+ # 'torch_control': [+ # {'name': 'Status', 'value': 'status', 'description': 'Get torch status'}+ # ],+ # 'vibrator_control': [+ # {'name': 'Vibrate', 'value': 'vibrate', 'description': 'Vibrate device'}+ # ],+ # 'sms_sender': [+ # {'name': 'Send', 'value': 'send', 'description': 'Send SMS'}+ # ],+ # 'call_automation': [+ # {'name': 'Dial', 'value': 'dial', 'description': 'Dial phone number'}+ # ],+ # 'camera_automation': [+ # {'name': 'Status', 'value': 'status', 'description': 'Get camera status'}+ # ],+ # 'flashlight': [+ # {'name': 'Turn On', 'value': 'turn_on', 'description': 'Turn flashlight on'},+ # {'name': 'Turn Off', 'value': 'turn_off', 'description': 'Turn flashlight off'},+ # {'name': 'Toggle', 'value': 'toggle', 'description': 'Toggle flashlight'}+ # ],+ # 'sound_recording': [+ # {'name': 'Start Recording', 'value': 'start_recording', 'description': 'Start audio recording'},+ # {'name': 'Stop Recording', 'value': 'stop_recording', 'description': 'Stop audio recording'}+ # ]+}+++class AndroidService:+ """Android System Services client for device automation."""++ def __init__(self):+ self.default_timeout = 30.0++ def get_service_actions(self, service_id: str) -> List[Dict[str, str]]:+ """Get available actions for a specific Android service.++ Args:+ service_id: Android service ID++ Returns:+ List of action options with name, value, and description+ """+ return SERVICE_ACTIONS.get(service_id, [])++ def get_default_parameters(self, service_id: str, action: str) -> str:+ """Get default parameters for a specific service action.++ Args:+ service_id: Android service ID+ action: Action name++ Returns:+ Default parameters as JSON string+ """+ return SERVICE_DEFAULT_PARAMETERS.get((service_id, action), '{}')++ async def _execute_via_relay(+ self,+ node_id: str,+ service_id: str,+ action: str,+ parameters: Dict[str, Any],+ start_time: float+ ) -> Dict[str, Any]:+ """Execute Android service via Relay WebSocket (remote device).++ Uses JSON-RPC 2.0 protocol via relay.send to paired Android device.++ Args:+ node_id: Node identifier+ service_id: Android service ID+ action: Service action+ parameters: Action parameters+ start_time: Execution start time++ Returns:+ Execution result with service response data+ """+ try:+ from services.android import get_current_relay_client++ relay_client = get_current_relay_client()+ if not relay_client:+ raise Exception("Relay client not available - run Android Device Setup first")++ if not relay_client.is_paired():+ raise Exception("No Android device paired. Scan QR code with Android app to pair.")++ device_id = relay_client.paired_device_id+ device_name = relay_client.paired_device_name++ logger.info(+ "[Android Service] Sending relay service request",+ service_id=service_id,+ action=action,+ device_id=device_id,+ device_name=device_name,+ parameters=parameters+ )++ # Send service request via relay+ response = await relay_client.send_service_request(+ service_id=service_id,+ action=action,+ parameters=parameters,+ timeout=30.0 # Increased timeout for relay communication+ )++ if not response:+ raise Exception(+ f"No response from Android device (timeout). "+ "Ensure the Android app is running and paired."+ )++ # Parse response - Android device may return:+ # 1. {"success": true, "data": {...}}+ # 2. {"data": {...}} (success implied)+ # 3. {"success": false, "error": "..."}+ # 4. Raw data object without wrapper+ logger.info("[Android Service] Raw relay response",+ response_keys=list(response.keys()) if isinstance(response, dict) else "not_dict",+ response=response)++ # Check for explicit success field, otherwise infer from data presence+ if 'success' in response:+ success = response.get('success', False)+ else:+ # No explicit success field - if we got data, consider it success+ success = 'data' in response or ('error' not in response and response)++ data = response.get('data', response if 'success' not in response and 'error' not in response else {})+ error_msg = response.get('error')++ logger.info("[Android Service] Relay response parsed",+ success=success,+ has_data=bool(data),+ error=error_msg)++ if success:+ result = {+ "success": True,+ "node_id": node_id,+ "node_type": "androidService",+ "result": {+ "service_id": service_id,+ "action": action,+ "data": data,+ "response_time": time.time() - start_time,+ "connection_type": "relay",+ "device_id": device_id,+ "device_name": device_name,+ "timestamp": datetime.now().isoformat()+ },+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+ else:+ result = {+ "success": False,+ "node_id": node_id,+ "node_type": "androidService",+ "error": error_msg or "Service execution failed on Android device",+ "result": {+ "service_id": service_id,+ "action": action,+ "data": data,+ "connection_type": "relay",+ "device_id": device_id,+ "timestamp": datetime.now().isoformat()+ },+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ log_execution_time(logger, f"android_service_{service_id}_{action}_relay", start_time, time.time())++ logger.info(+ "[Android Service] Relay execution completed",+ node_id=node_id,+ service_id=service_id,+ action=action,+ success=success+ )++ return result++ except Exception as e:+ logger.error(+ "[Android Service] Relay execution failed",+ node_id=node_id,+ service_id=service_id,+ action=action,+ error=str(e)+ )++ return {+ "success": False,+ "node_id": node_id,+ "node_type": "androidService",+ "error": str(e),+ "result": {+ "service_id": service_id,+ "action": action,+ "connection_type": "relay",+ "timestamp": datetime.now().isoformat()+ },+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ async def execute_service(+ self,+ node_id: str,+ service_id: str,+ action: str,+ parameters: Dict[str, Any],+ android_host: str = "localhost",+ android_port: int = 8888+ ) -> Dict[str, Any]:+ """Execute an Android system service action.++ Args:+ node_id: Node identifier+ service_id: Android service ID (e.g., 'battery', 'network', 'app_launcher')+ action: Service action to perform (e.g., 'status', 'launch', 'list')+ parameters: Action-specific parameters+ android_host: Android device API host+ android_port: Android device API port++ Returns:+ Execution result with service response data+ """+ start_time = time.time()++ try:+ # Check if relay connection is available (remote device)+ from services.android import get_current_relay_client+ relay_client = get_current_relay_client()++ if relay_client and relay_client.is_paired():+ # Use relay for remote Android device+ logger.info(+ "[Android Service] Using relay connection",+ node_id=node_id,+ service_id=service_id,+ action=action+ )+ return await self._execute_via_relay(+ node_id, service_id, action, parameters, start_time+ )+ else:+ # Use local HTTP connection+ base_url = f"http://{android_host}:{android_port}/api"+ logger.info(+ "[Android Service] Using local HTTP connection",+ node_id=node_id,+ service_id=service_id,+ action=action,+ base_url=base_url+ )++ # Build request payload+ request_payload = {+ "action": action,+ "parameters": parameters+ }++ # Make request to Android device API+ async with httpx.AsyncClient(timeout=self.default_timeout) as client:+ response = await client.post(+ f"{base_url}/{service_id}",+ json=request_payload+ )++ # Parse response+ if response.status_code == 200:+ response_data = response.json()++ # Check if Android service returned success+ service_success = response_data.get('success', True)++ result = {+ "success": service_success,+ "node_id": node_id,+ "node_type": "androidService",+ "result": {+ "service_id": service_id,+ "action": action,+ "data": response_data.get('data', response_data),+ "response_time": response.elapsed.total_seconds(),+ "android_host": android_host,+ "android_port": android_port,+ "timestamp": datetime.now().isoformat()+ },+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ if not service_success:+ result["result"]["error"] = response_data.get('error', 'Service execution failed')++ log_execution_time(logger, f"android_service_{service_id}_{action}", start_time, time.time())++ logger.info(+ "[Android Service] Execution completed",+ node_id=node_id,+ service_id=service_id,+ action=action,+ success=service_success+ )++ return result++ else:+ # HTTP error+ error_msg = f"HTTP {response.status_code}: {response.text}"+ logger.error(+ "[Android Service] HTTP error",+ node_id=node_id,+ service_id=service_id,+ status_code=response.status_code,+ error=error_msg+ )++ return {+ "success": False,+ "node_id": node_id,+ "node_type": "androidService",+ "error": error_msg,+ "result": {+ "service_id": service_id,+ "action": action,+ "status_code": response.status_code,+ "timestamp": datetime.now().isoformat()+ },+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ except httpx.ConnectError as e:+ error_msg = f"Cannot connect to Android device at {android_host}:{android_port}. Ensure ADB port forwarding is active: adb forward tcp:{android_port} tcp:{android_port}"+ logger.error(+ "[Android Service] Connection error",+ node_id=node_id,+ service_id=service_id,+ error=str(e),+ android_host=android_host,+ android_port=android_port+ )++ return {+ "success": False,+ "node_id": node_id,+ "node_type": "androidService",+ "error": error_msg,+ "result": {+ "service_id": service_id,+ "action": action,+ "connection_error": str(e),+ "timestamp": datetime.now().isoformat()+ },+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ except httpx.TimeoutException as e:+ error_msg = f"Request timeout after {self.default_timeout}s"+ logger.error(+ "[Android Service] Timeout",+ node_id=node_id,+ service_id=service_id,+ timeout=self.default_timeout+ )++ return {+ "success": False,+ "node_id": node_id,+ "node_type": "androidService",+ "error": error_msg,+ "result": {+ "service_id": service_id,+ "action": action,+ "timeout": self.default_timeout,+ "timestamp": datetime.now().isoformat()+ },+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ except Exception as e:+ logger.error(+ "[Android Service] Unexpected error",+ node_id=node_id,+ service_id=service_id,+ error=str(e),+ exc_info=True+ )++ return {+ "success": False,+ "node_id": node_id,+ "node_type": "androidService",+ "error": str(e),+ "result": {+ "service_id": service_id,+ "action": action,+ "timestamp": datetime.now().isoformat()+ },+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ async def check_device_status(+ self,+ android_host: str = "localhost",+ android_port: int = 8888+ ) -> Dict[str, Any]:+ """Check if Android device API is reachable.++ Returns:+ Status check result with online status+ """+ try:+ base_url = f"http://{android_host}:{android_port}/api"+ async with httpx.AsyncClient(timeout=5.0) as client:+ response = await client.get(f"{base_url}/status")++ return {+ "online": response.status_code == 200,+ "data": response.json() if response.status_code == 200 else None,+ "android_host": android_host,+ "android_port": android_port+ }+ except Exception as e:+ logger.warning(+ "[Android Service] Device offline",+ android_host=android_host,+ android_port=android_port,+ error=str(e)+ )+ return {+ "online": False,+ "error": str(e),+ "android_host": android_host,+ "android_port": android_port+ }diff --git a/server/services/auth.py b/server/services/auth.pynew file mode 100644index 00000000..7c40c1d8--- /dev/null+++ b/server/services/auth.py@@ -0,0 +1,131 @@+"""Simple API key management service."""++import hashlib+import base64+from datetime import datetime, timedelta+from typing import Dict, Any, Optional, List++from core.config import Settings+from core.database import Database+from core.cache import CacheService+from core.logging import get_logger++logger = get_logger(__name__)+++class AuthService:+ """Simple API key management service."""++ def __init__(self, database: Database, cache: CacheService, settings: Settings):+ self.database = database+ self.cache = cache+ self.settings = settings++ def encrypt_api_key(self, api_key: str) -> str:+ """Simple base64 encoding (compatible with frontend)."""+ return base64.b64encode(api_key.encode()).decode()++ def decrypt_api_key(self, encrypted_key: str) -> str:+ """Simple base64 decoding."""+ try:+ return base64.b64decode(encrypted_key.encode()).decode()+ except Exception:+ return ""++ def hash_api_key(self, api_key: str) -> str:+ """Create hash for API key identification."""+ return hashlib.sha256(api_key.encode()).hexdigest()[:16]++ async def store_api_key(self, provider: str, api_key: str, models: List[str],+ session_id: str = "default") -> bool:+ """Store API key with models."""+ try:+ key_id = f"{session_id}_{provider}"+ encrypted_key = self.encrypt_api_key(api_key)+ key_hash = self.hash_api_key(api_key)++ logger.info(f"Storing API key for provider: {provider}, session: {session_id}, key_id: {key_id}")++ # Store in database+ success = await self.database.save_api_key(+ key_id=key_id,+ provider=provider,+ session_id=session_id,+ key_encrypted=encrypted_key,+ key_hash=key_hash,+ models=models+ )++ logger.info(f"Database save result: {success}")++ # Cache for quick access+ if success:+ cache_data = {+ "encrypted_key": encrypted_key,+ "models": models,+ "last_validated": datetime.utcnow().isoformat()+ }+ await self.cache.cache_api_key(provider, session_id, cache_data)+ logger.info(f"Cached API key for {provider}")++ return success++ except Exception as e:+ logger.error("Failed to store API key", provider=provider, error=str(e))+ return False++ async def get_api_key(self, provider: str, session_id: str = "default") -> Optional[str]:+ """Get decrypted API key."""+ try:+ # Try cache first+ cached_data = await self.cache.get_cached_api_key(provider, session_id)+ if cached_data:+ return self.decrypt_api_key(cached_data["encrypted_key"])++ # Fallback to database+ api_key_record = await self.database.get_api_key_by_provider(provider, session_id)+ if api_key_record and api_key_record.is_valid:+ # Check if not expired (30 days)+ if datetime.utcnow() - api_key_record.last_validated < timedelta(days=30):+ return self.decrypt_api_key(api_key_record.key_encrypted)++ return None++ except Exception as e:+ logger.error("Failed to get API key", provider=provider, error=str(e))+ return None++ async def get_stored_models(self, provider: str, session_id: str = "default") -> List[str]:+ """Get stored models for provider."""+ try:+ # Try cache first+ cached_data = await self.cache.get_cached_api_key(provider, session_id)+ if cached_data and cached_data.get("models"):+ return cached_data["models"]++ # Fallback to database+ api_key_record = await self.database.get_api_key_by_provider(provider, session_id)+ if api_key_record and api_key_record.models:+ return api_key_record.models.get("models", [])++ return []++ except Exception as e:+ logger.error("Failed to get stored models", provider=provider, error=str(e))+ return []++ async def remove_api_key(self, provider: str, session_id: str = "default") -> bool:+ """Remove API key."""+ try:+ # Remove from cache and database+ await self.cache.remove_cached_api_key(provider, session_id)+ return await self.database.delete_api_key(provider, session_id)++ except Exception as e:+ logger.error("Failed to remove API key", provider=provider, error=str(e))+ return False++ async def has_valid_key(self, provider: str, session_id: str = "default") -> bool:+ """Check if valid API key exists."""+ api_key = await self.get_api_key(provider, session_id)+ return api_key is not None\ No newline at end of filediff --git a/server/services/chat_client.py b/server/services/chat_client.pynew file mode 100644index 00000000..38110828--- /dev/null+++ b/server/services/chat_client.py@@ -0,0 +1,160 @@+"""+Chat WebSocket Client - JSON-RPC 2.0 Protocol++Simple client for chat backend. Uses aiohttp (already in project).+Connection URL: ws://{host}:{port}/ws/{sessionId}?api_key={apiKey}&client_type=web+"""++import asyncio+import json+import uuid+import aiohttp+from typing import Optional, Dict, Any+import structlog++logger = structlog.get_logger()+++async def send_chat_message(+ host: str,+ port: int,+ session_id: str,+ api_key: str,+ content: str,+ metadata: Optional[Dict[str, Any]] = None,+ timeout: float = 10.0+) -> Dict[str, Any]:+ """Send a chat message via JSON-RPC 2.0 WebSocket.++ Args:+ host: Chat server host+ port: Chat server port+ session_id: Session identifier+ api_key: API key for authentication+ content: Message content+ metadata: Optional message metadata+ timeout: Request timeout in seconds++ Returns:+ JSON-RPC result or error dict+ """+ url = f"ws://{host}:{port}/ws/{session_id}?api_key={api_key}&client_type=web"+ request_id = str(uuid.uuid4())++ request = {+ "jsonrpc": "2.0",+ "method": "chat.sendMessage",+ "params": {"content": content, **(metadata or {})},+ "id": request_id+ }++ try:+ async with aiohttp.ClientSession() as session:+ async with session.ws_connect(url, timeout=timeout) as ws:+ await ws.send_json(request)++ # Wait for response with matching id+ async with asyncio.timeout(timeout):+ async for msg in ws:+ if msg.type == aiohttp.WSMsgType.TEXT:+ data = json.loads(msg.data)+ if data.get("id") == request_id:+ if "error" in data:+ return {"success": False, "error": data["error"].get("message", "Unknown error")}+ return {"success": True, "result": data.get("result", {})}+ elif msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR):+ break++ return {"success": False, "error": "No response received"}++ except asyncio.TimeoutError:+ return {"success": False, "error": "Connection timeout"}+ except Exception as e:+ logger.error("[Chat] Send error", error=str(e))+ return {"success": False, "error": str(e)}+++async def get_chat_history(+ host: str,+ port: int,+ session_id: str,+ api_key: str,+ limit: int = 50,+ timeout: float = 10.0+) -> Dict[str, Any]:+ """Get chat history via JSON-RPC 2.0 WebSocket.++ Args:+ host: Chat server host+ port: Chat server port+ session_id: Session identifier+ api_key: API key for authentication+ limit: Max messages to return+ timeout: Request timeout in seconds++ Returns:+ JSON-RPC result with messages or error dict+ """+ url = f"ws://{host}:{port}/ws/{session_id}?api_key={api_key}&client_type=web"+ request_id = str(uuid.uuid4())++ request = {+ "jsonrpc": "2.0",+ "method": "chat.getHistory",+ "params": {"limit": limit},+ "id": request_id+ }++ try:+ async with aiohttp.ClientSession() as session:+ async with session.ws_connect(url, timeout=timeout) as ws:+ await ws.send_json(request)++ async with asyncio.timeout(timeout):+ async for msg in ws:+ if msg.type == aiohttp.WSMsgType.TEXT:+ data = json.loads(msg.data)+ if data.get("id") == request_id:+ if "error" in data:+ return {"success": False, "error": data["error"].get("message", "Unknown error")}+ return {"success": True, "messages": data.get("result", {}).get("messages", [])}+ elif msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR):+ break++ return {"success": False, "error": "No response received"}++ except asyncio.TimeoutError:+ return {"success": False, "error": "Connection timeout"}+ except Exception as e:+ logger.error("[Chat] History error", error=str(e))+ return {"success": False, "error": str(e)}+++async def ping_chat_server(+ host: str,+ port: int,+ session_id: str,+ api_key: str,+ timeout: float = 5.0+) -> bool:+ """Ping chat server to check connectivity."""+ url = f"ws://{host}:{port}/ws/{session_id}?api_key={api_key}&client_type=web"+ request_id = str(uuid.uuid4())++ try:+ async with aiohttp.ClientSession() as session:+ async with session.ws_connect(url, timeout=timeout) as ws:+ await ws.send_json({"jsonrpc": "2.0", "method": "ping", "params": {}, "id": request_id})++ async with asyncio.timeout(timeout):+ async for msg in ws:+ if msg.type == aiohttp.WSMsgType.TEXT:+ data = json.loads(msg.data)+ if data.get("id") == request_id:+ return "error" not in data+ elif msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR):+ break+ return False++ except Exception:+ return Falsediff --git a/server/services/deployment/__init__.py b/server/services/deployment/__init__.pynew file mode 100644index 00000000..cb255141--- /dev/null+++ b/server/services/deployment/__init__.py@@ -0,0 +1,12 @@+"""Deployment module - Event-driven workflow deployment."""++from .state import DeploymentState, TriggerInfo+from .triggers import TriggerManager+from .manager import DeploymentManager++__all__ = [+ "DeploymentState",+ "TriggerInfo",+ "TriggerManager",+ "DeploymentManager",+]diff --git a/server/services/deployment/manager.py b/server/services/deployment/manager.pynew file mode 100644index 00000000..5a8d0a8f--- /dev/null+++ b/server/services/deployment/manager.py@@ -0,0 +1,613 @@+"""Deployment Manager - Event-driven workflow deployment lifecycle.++Implements n8n/Conductor pattern where:+- Workflow is a template stored in memory+- Trigger events spawn independent execution runs+- Runs execute concurrently (up to max_concurrent_runs)+"""++import asyncio+import json+import time+from datetime import datetime+from typing import Dict, Any, List, Optional, Callable, TYPE_CHECKING++from core.logging import get_logger+from constants import WORKFLOW_TRIGGER_TYPES+from services import event_waiter+from .state import DeploymentState, TriggerInfo+from .triggers import TriggerManager++if TYPE_CHECKING:+ from core.database import Database++logger = get_logger(__name__)+++class DeploymentManager:+ """Manages event-driven workflow deployment.++ Supports per-workflow deployments following n8n pattern:+ - Each workflow can be deployed independently+ - Multiple workflows can run concurrently+ - Each deployment has its own state, triggers, and runs+ """++ def __init__(+ self,+ database: "Database",+ execute_workflow_fn: Callable,+ store_output_fn: Callable,+ broadcaster: Any,+ ):+ self.database = database+ self._execute_workflow = execute_workflow_fn+ self._store_output = store_output_fn+ self._broadcaster = broadcaster++ # Per-workflow deployment state (n8n pattern)+ self._deployments: Dict[str, DeploymentState] = {}+ self._trigger_managers: Dict[str, TriggerManager] = {}+ self._active_runs: Dict[str, Dict[str, asyncio.Task]] = {} # workflow_id -> {run_id: task}+ self._run_counters: Dict[str, int] = {}+ self._status_callbacks: Dict[str, Callable] = {}+ self._main_loop: Optional[asyncio.AbstractEventLoop] = None++ self._settings = {+ "stop_on_error": False,+ "max_concurrent_runs": 100,+ "use_parallel_executor": True+ }++ @property+ def is_running(self) -> bool:+ """Check if ANY deployment is running (backward compatibility)."""+ return any(state.is_running for state in self._deployments.values())++ def is_workflow_deployed(self, workflow_id: str) -> bool:+ """Check if a specific workflow is deployed."""+ state = self._deployments.get(workflow_id)+ return state is not None and state.is_running++ def get_deployed_workflows(self) -> List[str]:+ """Get list of deployed workflow IDs."""+ return [wid for wid, state in self._deployments.items() if state.is_running]++ # =========================================================================+ # DEPLOYMENT LIFECYCLE+ # =========================================================================++ async def deploy(+ self,+ nodes: List[Dict],+ edges: List[Dict],+ session_id: str = "default",+ status_callback: Optional[Callable] = None,+ workflow_id: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Deploy workflow in event-driven mode.++ Args:+ nodes: Workflow nodes+ edges: Workflow edges+ session_id: Session identifier+ status_callback: Status update callback+ workflow_id: Workflow ID for per-workflow deployment tracking+ """+ # Generate workflow_id if not provided+ if not workflow_id:+ workflow_id = f"workflow_{int(time.time() * 1000)}"++ # Check if THIS workflow is already deployed+ if self.is_workflow_deployed(workflow_id):+ return {+ "success": False,+ "error": f"Workflow {workflow_id} is already deployed",+ "workflow_id": workflow_id,+ "deployment_id": self._deployments[workflow_id].deployment_id+ }++ # Setup+ deployment_id = f"deploy_{workflow_id}_{int(time.time() * 1000)}"+ self._status_callbacks[workflow_id] = status_callback+ self._run_counters[workflow_id] = 0+ self._active_runs[workflow_id] = {}++ try:+ self._main_loop = asyncio.get_running_loop()+ except RuntimeError:+ self._main_loop = asyncio.get_event_loop()++ # Create trigger manager for this workflow+ trigger_manager = TriggerManager()+ trigger_manager.set_main_loop(self._main_loop)+ trigger_manager.set_running(True)+ self._trigger_managers[workflow_id] = trigger_manager++ # Load settings+ await self._load_settings()++ # Create state for this workflow+ self._deployments[workflow_id] = DeploymentState(+ deployment_id=deployment_id,+ workflow_id=workflow_id,+ is_running=True,+ nodes=nodes,+ edges=edges,+ session_id=session_id,+ settings=self._settings.copy()+ )++ logger.info("Deployment starting", deployment_id=deployment_id, workflow_id=workflow_id, nodes=len(nodes))++ triggers_setup = []++ try:+ # Setup cron triggers+ for cron_node in TriggerManager.find_cron_nodes(nodes):+ info = await self._setup_cron_trigger(cron_node, workflow_id)+ triggers_setup.append(info.to_dict())++ # Find start and event triggers+ start_nodes, event_triggers = TriggerManager.find_trigger_nodes(nodes, edges)++ # Fire start nodes immediately+ for node in start_nodes:+ info = await self._fire_start_trigger(node, workflow_id)+ triggers_setup.append(info.to_dict())++ # Setup event triggers+ for node in event_triggers:+ info = await self._setup_event_trigger(node, workflow_id)+ triggers_setup.append(info.to_dict())++ # Notify started+ await self._notify("started", {+ "deployment_id": deployment_id,+ "workflow_id": workflow_id,+ "triggers": triggers_setup+ }, workflow_id)++ return {+ "success": True,+ "deployment_id": deployment_id,+ "workflow_id": workflow_id,+ "message": "Workflow deployed",+ "triggers_setup": triggers_setup+ }++ except Exception as e:+ logger.error("Deployment failed", workflow_id=workflow_id, error=str(e))+ await self.cancel(workflow_id)+ return {"success": False, "error": str(e), "workflow_id": workflow_id}++ async def cancel(self, workflow_id: Optional[str] = None) -> Dict[str, Any]:+ """Cancel deployment for a specific workflow.++ Args:+ workflow_id: Workflow to cancel. If None, cancels the first running deployment.+ """+ # Find workflow to cancel+ if workflow_id:+ if not self.is_workflow_deployed(workflow_id):+ return {"success": False, "error": f"Workflow {workflow_id} is not deployed"}+ else:+ # Backward compatibility: cancel first running deployment+ deployed = self.get_deployed_workflows()+ if not deployed:+ return {"success": False, "error": "No deployment running"}+ workflow_id = deployed[0]++ state = self._deployments.get(workflow_id)+ if not state:+ return {"success": False, "error": f"Deployment state not found for {workflow_id}"}++ deployment_id = state.deployment_id+ logger.info("Cancelling deployment", deployment_id=deployment_id, workflow_id=workflow_id)++ # Get trigger manager for this workflow+ trigger_manager = self._trigger_managers.get(workflow_id)+ if trigger_manager:+ trigger_manager.set_running(False)++ # Cancel active runs for this workflow+ workflow_runs = self._active_runs.get(workflow_id, {})+ listener_nodes = trigger_manager.get_listener_node_ids() if trigger_manager else []++ for task in workflow_runs.values():+ if not task.done():+ task.cancel()++ if workflow_runs:+ await asyncio.gather(*workflow_runs.values(), return_exceptions=True)+ run_count = len(workflow_runs)++ # Cleanup triggers for this workflow+ listener_count = 0+ cron_count = 0+ if trigger_manager:+ listener_count = await trigger_manager.teardown_all_listeners()+ cron_count = trigger_manager.teardown_all_crons()++ # Cancel event waiters for nodes in this workflow+ waiter_count = 0+ for node in state.nodes:+ waiter_count += event_waiter.cancel_for_node(node['id'])++ # Clear state for this workflow+ self._deployments.pop(workflow_id, None)+ self._trigger_managers.pop(workflow_id, None)+ self._active_runs.pop(workflow_id, None)+ self._run_counters.pop(workflow_id, None)+ self._status_callbacks.pop(workflow_id, None)++ return {+ "success": True,+ "deployment_id": deployment_id,+ "workflow_id": workflow_id,+ "runs_cancelled": run_count,+ "listeners_cancelled": listener_count,+ "crons_cancelled": cron_count,+ "waiters_cancelled": waiter_count,+ "cancelled_listener_node_ids": listener_nodes+ }++ def get_status(self, workflow_id: Optional[str] = None) -> Dict[str, Any]:+ """Get deployment status.++ Args:+ workflow_id: Get status for specific workflow. If None, returns global status.+ """+ if workflow_id:+ # Status for specific workflow+ state = self._deployments.get(workflow_id)+ if not state or not state.is_running:+ return {"deployed": False, "deployment_id": None, "active_runs": 0, "workflow_id": workflow_id}++ workflow_runs = self._active_runs.get(workflow_id, {})+ execution_runs = [k for k in workflow_runs if k.startswith("run_")]+ return {+ "deployed": True,+ "deployment_id": state.deployment_id,+ "workflow_id": workflow_id,+ "active_runs": len(execution_runs),+ "active_listeners": len(workflow_runs) - len(execution_runs),+ "run_counter": self._run_counters.get(workflow_id, 0),+ "deployed_at": state.deployed_at+ }++ # Global status (backward compatibility)+ if not self.is_running:+ return {"deployed": False, "deployment_id": None, "active_runs": 0}++ # Aggregate across all workflows+ total_runs = 0+ total_listeners = 0+ total_run_counter = 0+ deployed_workflows = []++ for wid, state in self._deployments.items():+ if state.is_running:+ deployed_workflows.append(wid)+ workflow_runs = self._active_runs.get(wid, {})+ execution_runs = [k for k in workflow_runs if k.startswith("run_")]+ total_runs += len(execution_runs)+ total_listeners += len(workflow_runs) - len(execution_runs)+ total_run_counter += self._run_counters.get(wid, 0)++ return {+ "deployed": True,+ "deployed_workflows": deployed_workflows,+ "active_runs": total_runs,+ "active_listeners": total_listeners,+ "run_counter": total_run_counter+ }++ # =========================================================================+ # TRIGGER SETUP+ # =========================================================================++ async def _setup_cron_trigger(self, node: Dict, workflow_id: str) -> TriggerInfo:+ """Setup cron trigger for a node."""+ node_id = node['id']+ params = await self.database.get_node_parameters(node_id) or {}++ cron_expr = TriggerManager.build_cron_expression(params)+ timezone = params.get('timezone', 'UTC')++ def on_tick():+ if self._main_loop and self._main_loop.is_running():+ trigger_data = {+ 'node_id': node_id,+ 'timestamp': datetime.now().isoformat(),+ 'trigger_type': 'cron'+ }+ asyncio.run_coroutine_threadsafe(+ self._spawn_run(node_id, trigger_data, workflow_id=workflow_id),+ self._main_loop+ )++ trigger_manager = self._trigger_managers.get(workflow_id)+ if not trigger_manager:+ raise RuntimeError(f"No trigger manager for workflow {workflow_id}")++ job_id = trigger_manager.setup_cron(node_id, cron_expr, timezone, on_tick)+ return TriggerInfo(node_id, "cron", job_id=job_id)++ async def _fire_start_trigger(self, node: Dict, workflow_id: str) -> TriggerInfo:+ """Fire a start trigger immediately."""+ node_id = node['id']+ params = await self.database.get_node_parameters(node_id) or {}++ initial_data_str = params.get('initialData', '{}')+ try:+ initial_data = json.loads(initial_data_str) if initial_data_str else {}+ except json.JSONDecodeError:+ initial_data = {}++ trigger_data = {+ 'node_id': node_id,+ 'timestamp': datetime.now().isoformat(),+ 'trigger_type': 'start',+ 'event_data': initial_data+ }++ await self._spawn_run(node_id, trigger_data, workflow_id=workflow_id)+ return TriggerInfo(node_id, "start", fired=True)++ async def _setup_event_trigger(self, node: Dict, workflow_id: str) -> TriggerInfo:+ """Setup event-based trigger."""+ node_id = node['id']+ node_type = node.get('type', '')+ params = await self.database.get_node_parameters(node_id) or {}++ async def on_event(event_data: Dict):+ trigger_data = {+ 'node_id': node_id,+ 'timestamp': datetime.now().isoformat(),+ 'trigger_type': node_type,+ 'event_data': event_data+ }+ await self._spawn_run(node_id, trigger_data, wait=True, workflow_id=workflow_id)++ trigger_manager = self._trigger_managers.get(workflow_id)+ if not trigger_manager:+ raise RuntimeError(f"No trigger manager for workflow {workflow_id}")++ await trigger_manager.setup_event_trigger(+ node_id, node_type, params, on_event, self._broadcaster,+ workflow_id=workflow_id+ )+ return TriggerInfo(node_id, node_type)++ # =========================================================================+ # EXECUTION RUNS+ # =========================================================================++ async def _spawn_run(+ self,+ trigger_node_id: str,+ trigger_data: Dict[str, Any],+ wait: bool = False,+ workflow_id: Optional[str] = None+ ) -> Optional[asyncio.Task]:+ """Spawn a new execution run for a specific workflow."""+ if not workflow_id:+ # Backward compatibility: find workflow for this trigger node+ for wid, state in self._deployments.items():+ if state.is_running and any(n['id'] == trigger_node_id for n in state.nodes):+ workflow_id = wid+ break++ if not workflow_id or not self.is_workflow_deployed(workflow_id):+ return None++ state = self._deployments[workflow_id]++ # Check concurrent limit for this workflow+ workflow_runs = self._active_runs.get(workflow_id, {})+ active_count = sum(1 for k in workflow_runs if k.startswith("run_"))+ max_concurrent = self._settings.get("max_concurrent_runs", 100)+ if active_count >= max_concurrent:+ logger.warning("Max concurrent runs reached", workflow_id=workflow_id, active=active_count)+ return None++ # Generate run ID+ self._run_counters[workflow_id] = self._run_counters.get(workflow_id, 0) + 1+ run_id = f"run_{state.deployment_id}_{self._run_counters[workflow_id]}"++ await self._notify("run_started", {+ "run_id": run_id,+ "workflow_id": workflow_id,+ "trigger_node_id": trigger_node_id,+ "active_runs": active_count + 1+ }, workflow_id)++ async def execute():+ try:+ result = await self._execute_from_trigger(+ run_id, trigger_node_id, trigger_data, workflow_id+ )+ await self._notify("run_completed", {+ "run_id": run_id,+ "workflow_id": workflow_id,+ "success": result.get("success", False),+ "execution_time": result.get("execution_time")+ }, workflow_id)+ except asyncio.CancelledError:+ logger.debug("Run cancelled", run_id=run_id, workflow_id=workflow_id)+ except Exception as e:+ logger.error("Run failed", run_id=run_id, workflow_id=workflow_id, error=str(e))+ await self._notify("run_failed", {"run_id": run_id, "error": str(e)}, workflow_id)+ finally:+ if workflow_id in self._active_runs:+ self._active_runs[workflow_id].pop(run_id, None)++ task = asyncio.create_task(execute())+ if workflow_id not in self._active_runs:+ self._active_runs[workflow_id] = {}+ self._active_runs[workflow_id][run_id] = task++ if wait:+ try:+ await task+ except (asyncio.CancelledError, Exception):+ pass+ return None++ return task++ async def _execute_from_trigger(+ self,+ run_id: str,+ trigger_node_id: str,+ trigger_data: Dict[str, Any],+ workflow_id: str+ ) -> Dict[str, Any]:+ """Execute workflow from a trigger node."""+ state = self._deployments.get(workflow_id)+ if not state:+ return {"success": False, "error": f"Workflow {workflow_id} not deployed"}++ start_time = time.time()+ run_session_id = f"{state.session_id}_{run_id}"++ # Store trigger output+ trigger_output = trigger_data.get('event_data', trigger_data)+ await self._store_output(run_session_id, trigger_node_id, "output_0", trigger_output)++ # Get downstream nodes+ downstream = self._get_downstream_nodes(+ trigger_node_id,+ state.nodes,+ state.edges+ )++ if not downstream:+ return {+ "success": True,+ "run_id": run_id,+ "workflow_id": workflow_id,+ "nodes_executed": [trigger_node_id],+ "execution_time": time.time() - start_time,+ "message": "No downstream nodes"+ }++ # Build filtered graph+ run_filter = {trigger_node_id} | {n['id'] for n in downstream}++ filtered_nodes = []+ for node in state.nodes:+ if node['id'] not in run_filter:+ continue+ node_copy = node.copy()+ if node['id'] == trigger_node_id:+ node_copy['_pre_executed'] = True+ node_copy['_trigger_output'] = trigger_output+ filtered_nodes.append(node_copy)++ filtered_edges = [+ e for e in state.edges+ if e.get('source') in run_filter and e.get('target') in run_filter+ ]++ # Execute filtered graph with deployment's workflow_id for scoped status+ status_callback = self._status_callbacks.get(workflow_id)+ result = await self._execute_workflow(+ nodes=filtered_nodes,+ edges=filtered_edges,+ session_id=run_session_id,+ status_callback=status_callback,+ skip_clear_outputs=True,+ workflow_id=workflow_id, # Pass deployment's workflow_id for status scoping+ )++ result["run_id"] = run_id+ result["workflow_id"] = workflow_id+ result["trigger_node_id"] = trigger_node_id+ return result++ def _get_downstream_nodes(+ self,+ node_id: str,+ nodes: List[Dict],+ edges: List[Dict]+ ) -> List[Dict]:+ """Get all downstream nodes from a trigger."""+ downstream_ids = set()+ node_types = {n['id']: n.get('type', '') for n in nodes}+ nodes_with_inputs = {e.get('target') for e in edges if e.get('target')}++ def collect(current_id: str):+ for edge in edges:+ if edge.get('source') != current_id:+ continue+ target_id = edge.get('target')+ if not target_id or target_id in downstream_ids:+ continue++ target_type = node_types.get(target_id, '')+ is_trigger = target_type in WORKFLOW_TRIGGER_TYPES+ has_inputs = target_id in nodes_with_inputs++ # Stop at independent triggers (no inputs)+ if is_trigger and not has_inputs:+ continue++ downstream_ids.add(target_id)+ collect(target_id)++ collect(node_id)++ # Include config nodes connected to downstream nodes+ for edge in edges:+ target = edge.get('target')+ source = edge.get('source')+ handle = edge.get('targetHandle', '')++ is_config = handle and handle.startswith('input-') and handle != 'input-main'+ if is_config and target in downstream_ids and source not in downstream_ids:+ downstream_ids.add(source)++ return [n for n in nodes if n['id'] in downstream_ids]++ # =========================================================================+ # HELPERS+ # =========================================================================++ async def _load_settings(self):+ """Load deployment settings from database."""+ try:+ db_settings = await self.database.get_deployment_settings()+ if db_settings:+ self._settings.update({+ "stop_on_error": db_settings.get("stop_on_error", False),+ "max_concurrent_runs": db_settings.get("max_concurrent_runs", 100),+ "use_parallel_executor": db_settings.get("use_parallel_executor", True)+ })+ except Exception:+ pass++ async def _notify(self, event: str, data: Dict[str, Any], workflow_id: Optional[str] = None):+ """Send status notification for a specific workflow."""+ status_callback = None+ if workflow_id:+ status_callback = self._status_callbacks.get(workflow_id)+ else:+ # Backward compatibility: use first available callback+ for cb in self._status_callbacks.values():+ if cb:+ status_callback = cb+ break++ if not status_callback:+ return++ try:+ await status_callback("__deployment__", event, {+ **data,+ "workflow_id": workflow_id,+ "timestamp": datetime.now().isoformat()+ })+ except Exception as e:+ logger.warning("Status callback failed", workflow_id=workflow_id, error=str(e))diff --git a/server/services/deployment/state.py b/server/services/deployment/state.pynew file mode 100644index 00000000..544d7375--- /dev/null+++ b/server/services/deployment/state.py@@ -0,0 +1,47 @@+"""Deployment State - Immutable state snapshot for event-driven deployment."""++from dataclasses import dataclass, field+from datetime import datetime+from typing import Dict, Any, List, Optional+++@dataclass+class DeploymentState:+ """Immutable deployment state."""+ deployment_id: str+ workflow_id: str+ is_running: bool+ nodes: List[Dict]+ edges: List[Dict]+ session_id: str+ settings: Dict[str, Any] = field(default_factory=dict)+ deployed_at: str = field(default_factory=lambda: datetime.now().isoformat())++ def to_dict(self) -> Dict[str, Any]:+ return {+ "deployment_id": self.deployment_id,+ "workflow_id": self.workflow_id,+ "is_running": self.is_running,+ "session_id": self.session_id,+ "settings": self.settings,+ "deployed_at": self.deployed_at,+ "node_count": len(self.nodes),+ "edge_count": len(self.edges),+ }+++@dataclass+class TriggerInfo:+ """Info about a registered trigger."""+ node_id: str+ node_type: str+ job_id: Optional[str] = None # For cron triggers+ fired: bool = False # For start triggers++ def to_dict(self) -> Dict[str, Any]:+ d = {"type": self.node_type, "node_id": self.node_id}+ if self.job_id:+ d["job_id"] = self.job_id+ if self.fired:+ d["fired"] = True+ return ddiff --git a/server/services/deployment/triggers.py b/server/services/deployment/triggers.pynew file mode 100644index 00000000..a6ea763c--- /dev/null+++ b/server/services/deployment/triggers.py@@ -0,0 +1,271 @@+"""Trigger Management - Setup and teardown of workflow triggers.++Handles cron scheduling, event-based triggers (webhook, whatsapp), and cleanup.+"""++import asyncio+from datetime import datetime+from typing import Dict, Any, Callable, Optional, Set++from core.logging import get_logger+from constants import WORKFLOW_TRIGGER_TYPES+from services import event_waiter+from services import scheduler as cron_scheduler++logger = get_logger(__name__)+++class TriggerManager:+ """Manages workflow trigger lifecycle."""++ def __init__(self, main_loop: Optional[asyncio.AbstractEventLoop] = None):+ self._active_cron_jobs: Dict[str, str] = {} # node_id -> job_id+ self._active_listeners: Dict[str, asyncio.Task] = {} # node_id -> task+ self._main_loop = main_loop+ self._is_running = False++ def set_running(self, running: bool):+ self._is_running = running++ def set_main_loop(self, loop: asyncio.AbstractEventLoop):+ self._main_loop = loop++ # =========================================================================+ # CRON TRIGGERS+ # =========================================================================++ def setup_cron(self, node_id: str, cron_expr: str, timezone: str,+ on_tick: Callable[[], None]) -> str:+ """Setup a cron trigger that calls on_tick on schedule."""+ job_id = f"cron_{node_id}"++ def tick_callback():+ if not self._is_running:+ return+ on_tick()++ cron_scheduler.register_cron_job(+ job_id=job_id,+ cron_expression=cron_expr,+ callback=tick_callback,+ timezone=timezone+ )++ self._active_cron_jobs[node_id] = job_id+ logger.info("Cron trigger setup", job_id=job_id, expr=cron_expr)+ return job_id++ def teardown_cron(self, node_id: str) -> bool:+ """Remove a specific cron trigger."""+ job_id = self._active_cron_jobs.pop(node_id, None)+ if job_id:+ cron_scheduler.remove_cron_job(job_id)+ logger.debug("Cron trigger removed", job_id=job_id)+ return True+ return False++ def teardown_all_crons(self) -> int:+ """Remove all cron triggers."""+ count = 0+ for node_id, job_id in list(self._active_cron_jobs.items()):+ cron_scheduler.remove_cron_job(job_id)+ count += 1+ self._active_cron_jobs.clear()+ logger.info("All cron triggers removed", count=count)+ return count++ # =========================================================================+ # EVENT TRIGGERS (Webhook, WhatsApp, etc.)+ # =========================================================================++ async def setup_event_trigger(self, node_id: str, node_type: str,+ parameters: Dict[str, Any],+ on_event: Callable[[Dict], Any],+ broadcaster: Any,+ workflow_id: Optional[str] = None) -> None:+ """Setup an event-based trigger with queue-based sequential processing.++ Args:+ node_id: The trigger node ID+ node_type: Type of trigger (whatsappReceive, webhookTrigger, etc.)+ parameters: Node parameters for filtering+ on_event: Callback when event is received+ broadcaster: Status broadcaster for real-time updates+ workflow_id: Workflow ID for scoped status updates (n8n pattern)+ """+ event_queue: asyncio.Queue = asyncio.Queue()+ is_executing = False++ async def collector():+ """Continuously collect events into queue."""+ while self._is_running:+ try:+ waiter = await event_waiter.register(node_type, node_id, parameters)+ config = event_waiter.get_trigger_config(node_type)++ if config and not is_executing:+ queue_size = event_queue.qsize()+ msg = f"Waiting for {config.display_name}..."+ if queue_size > 0:+ msg = f"Waiting... ({queue_size} queued)"+ await broadcaster.update_node_status(node_id, "waiting", {+ "message": msg,+ "event_type": config.event_type,+ "waiter_id": waiter.id,+ "queue_size": queue_size+ }, workflow_id=workflow_id)++ event_data = await event_waiter.wait_for_event(waiter)+ if self._is_running:+ await event_queue.put(event_data)++ except asyncio.CancelledError:+ break+ except Exception as e:+ logger.error("Trigger collector error", node_id=node_id, error=str(e))+ if self._is_running:+ await asyncio.sleep(1)++ async def processor():+ """Process events from queue sequentially."""+ nonlocal is_executing+ while self._is_running:+ try:+ try:+ event_data = await asyncio.wait_for(event_queue.get(), timeout=1.0)+ except asyncio.TimeoutError:+ continue++ is_executing = True+ config = event_waiter.get_trigger_config(node_type)++ # Clear waiting indicator during execution+ await broadcaster.update_node_status(node_id, "idle", {+ "message": "Graph executing...",+ "is_processing": True+ }, workflow_id=workflow_id)++ try:+ await on_event(event_data)+ except Exception as e:+ logger.error("Trigger execution error", node_id=node_id, error=str(e))++ is_executing = False++ # Return to waiting state+ queue_size = event_queue.qsize()+ name = config.display_name if config else node_type+ msg = f"Waiting for {name}..." if queue_size == 0 else f"Processing next... ({queue_size} queued)"+ await broadcaster.update_node_status(node_id, "waiting", {+ "message": msg,+ "queue_size": queue_size,+ "is_processing": False+ }, workflow_id=workflow_id)++ except asyncio.CancelledError:+ break+ except Exception as e:+ logger.error("Trigger processor error", node_id=node_id, error=str(e))+ is_executing = False++ async def combined():+ collector_task = asyncio.create_task(collector())+ processor_task = asyncio.create_task(processor())+ try:+ await asyncio.gather(collector_task, processor_task)+ except asyncio.CancelledError:+ collector_task.cancel()+ processor_task.cancel()+ await asyncio.gather(collector_task, processor_task, return_exceptions=True)++ task = asyncio.create_task(combined())+ self._active_listeners[node_id] = task++ async def teardown_all_listeners(self) -> int:+ """Cancel all event listeners."""+ count = 0+ for node_id, task in list(self._active_listeners.items()):+ if not task.done():+ task.cancel()+ count += 1++ if self._active_listeners:+ await asyncio.gather(*self._active_listeners.values(), return_exceptions=True)++ self._active_listeners.clear()+ return count++ def get_listener_node_ids(self) -> list:+ """Get node IDs of active listeners."""+ return list(self._active_listeners.keys())++ # =========================================================================+ # UTILITY METHODS+ # =========================================================================++ @staticmethod+ def build_cron_expression(parameters: Dict[str, Any]) -> Optional[str]:+ """Build cron expression from user-friendly parameters."""+ frequency = parameters.get('frequency', 'minutes')++ second, minute, hour = '0', '*/5', '*'+ day, month, weekday = '*', '*', '*'++ if frequency == 'seconds':+ interval = str(parameters.get('interval', 30))+ second, minute = f'*/{interval}', '*'++ elif frequency == 'minutes':+ interval = str(parameters.get('intervalMinutes', 5))+ minute = f'*/{interval}' if interval != '1' else '*'++ elif frequency == 'hours':+ interval = str(parameters.get('intervalHours', 1))+ minute = '0'+ hour = f'*/{interval}' if interval != '1' else '*'++ elif frequency == 'days':+ time_str = parameters.get('dailyTime', '09:00')+ parts = time_str.split(':')+ hour = parts[0] if parts else '9'+ minute = parts[1] if len(parts) > 1 else '0'++ elif frequency == 'weeks':+ time_str = parameters.get('weeklyTime', '09:00')+ parts = time_str.split(':')+ hour = parts[0] if parts else '9'+ minute = parts[1] if len(parts) > 1 else '0'+ weekday = parameters.get('weekday', '1')++ elif frequency == 'months':+ time_str = parameters.get('monthlyTime', '09:00')+ parts = time_str.split(':')+ hour = parts[0] if parts else '9'+ minute = parts[1] if len(parts) > 1 else '0'+ day = parameters.get('monthDay', '1')++ elif frequency == 'once':+ return None++ return f'{second} {minute} {hour} {day} {month} {weekday}'++ @staticmethod+ def find_trigger_nodes(nodes: list, edges: list) -> tuple:+ """Find trigger nodes, split into start nodes and event triggers."""+ # Nodes with incoming edges+ nodes_with_inputs = {e.get('target') for e in edges if e.get('target')}++ trigger_types_no_cron = WORKFLOW_TRIGGER_TYPES - {'cronScheduler'}+ triggers = [n for n in nodes+ if n.get('type') in trigger_types_no_cron+ and n.get('id') not in nodes_with_inputs]++ start_nodes = [n for n in triggers if n.get('type') == 'start']+ event_triggers = [n for n in triggers if n.get('type') != 'start']++ return start_nodes, event_triggers++ @staticmethod+ def find_cron_nodes(nodes: list) -> list:+ """Find all cron scheduler nodes."""+ return [n for n in nodes if n.get('type') == 'cronScheduler']diff --git a/server/services/event_waiter.py b/server/services/event_waiter.pynew file mode 100644index 00000000..0b7a2bbe--- /dev/null+++ b/server/services/event_waiter.py@@ -0,0 +1,759 @@+"""Event Waiter Service - Generic event waiting for trigger nodes.++Supports any trigger type (WhatsApp, Email, Webhook, MQTT, etc.)+Uses Redis Streams when available for persistence, falls back to asyncio.Future.++Architecture:+- Redis mode: Events stored in Redis Streams, waiters poll streams with blocking XREAD+- Memory mode: Events dispatched to in-memory asyncio.Future waiters+"""+import asyncio+import json+import uuid+import time+from dataclasses import dataclass, field+from typing import Dict, Any, Optional, Callable, List, TYPE_CHECKING++from core.logging import get_logger++if TYPE_CHECKING:+ from core.cache import CacheService++logger = get_logger(__name__)+++# =============================================================================+# CACHE SERVICE REFERENCE+# =============================================================================++_cache_service: Optional["CacheService"] = None+_main_loop: Optional[asyncio.AbstractEventLoop] = None+++def set_cache_service(cache: "CacheService") -> None:+ """Set the cache service for Redis Streams support.++ Called during application startup from main.py.+ """+ global _cache_service, _main_loop+ _cache_service = cache+ # Store reference to the main event loop for thread-safe dispatch+ try:+ _main_loop = asyncio.get_running_loop()+ except RuntimeError:+ _main_loop = None+ mode = "Redis Streams" if cache and cache.is_redis_available() else "asyncio.Future"+ logger.info(f"[EventWaiter] Initialized with {mode} backend")+++def get_cache_service() -> Optional["CacheService"]:+ """Get the cache service if available."""+ return _cache_service+++def is_redis_mode() -> bool:+ """Check if Redis Streams mode is active.++ Returns True only if Redis is connected AND supports Streams commands.+ This prevents runtime failures when Redis doesn't support XREADGROUP/XADD.+ """+ return _cache_service is not None and _cache_service.is_streams_available()+++# =============================================================================+# LID TO PHONE RESOLUTION CACHE+# =============================================================================++# Cache: group_jid -> {lid -> phone}+# TTL: 5 minutes (group membership can change)+_lid_phone_cache: Dict[str, Dict[str, str]] = {}+_lid_cache_timestamps: Dict[str, float] = {}+LID_CACHE_TTL = 300 # 5 minutes+++async def resolve_lid_to_phone(group_jid: str, lid: str) -> Optional[str]:+ """Resolve a LID to phone number using cached group info.++ Args:+ group_jid: The group JID (e.g., '[email protected]')+ lid: The LID to resolve (e.g., '201872623300767@lid' or just '201872623300767')++ Returns:+ Phone number if found, None otherwise+ """+ # Normalize LID (remove @lid suffix if present)+ lid_key = lid.split('@')[0] if '@' in lid else lid++ # Check cache validity+ if group_jid in _lid_phone_cache:+ cache_time = _lid_cache_timestamps.get(group_jid, 0)+ if time.time() - cache_time < LID_CACHE_TTL:+ phone = _lid_phone_cache[group_jid].get(lid_key)+ if phone:+ return phone++ # Cache miss or expired - fetch group info+ await refresh_group_lid_cache(group_jid)++ # Try again from cache+ if group_jid in _lid_phone_cache:+ phone = _lid_phone_cache[group_jid].get(lid_key)+ if phone:+ return phone++ logger.warning(f"[LIDResolver] Could not resolve LID {lid_key} in group {group_jid}")+ return None+++async def refresh_group_lid_cache(group_jid: str) -> bool:+ """Fetch group info and cache LID->phone mappings.++ Args:+ group_jid: The group JID to fetch info for++ Returns:+ True if successful, False otherwise+ """+ try:+ from routers.whatsapp import get_client++ client = await get_client()+ result = await client.call("group_info", {"group_id": group_jid})++ if not result or 'participants' not in result:+ logger.warning(f"[LIDResolver] No participants in group_info for {group_jid}")+ return False++ # Build LID->phone mapping+ lid_map: Dict[str, str] = {}+ for participant in result.get('participants', []):+ jid = participant.get('jid', '')+ phone = participant.get('phone', '')++ if jid and phone:+ # Extract LID key (number before @)+ lid_key = jid.split('@')[0] if '@' in jid else jid+ lid_map[lid_key] = phone+ logger.debug(f"[LIDResolver] Cached: {lid_key} -> {phone}")++ _lid_phone_cache[group_jid] = lid_map+ _lid_cache_timestamps[group_jid] = time.time()++ logger.debug(f"[LIDResolver] Cached {len(lid_map)} participants for group {group_jid}")+ return True++ except Exception as e:+ logger.error(f"[LIDResolver] Failed to fetch group info for {group_jid}: {e}")+ return False+++def get_cached_phone(group_jid: str, lid: str) -> Optional[str]:+ """Get phone from cache synchronously (for use in filter function).++ Args:+ group_jid: The group JID+ lid: The LID to look up++ Returns:+ Phone number if cached, None otherwise+ """+ lid_key = lid.split('@')[0] if '@' in lid else lid++ if group_jid in _lid_phone_cache:+ cache_time = _lid_cache_timestamps.get(group_jid, 0)+ if time.time() - cache_time < LID_CACHE_TTL:+ return _lid_phone_cache[group_jid].get(lid_key)++ return None+++# =============================================================================+# TRIGGER CONFIGURATION REGISTRY+# =============================================================================++@dataclass+class TriggerConfig:+ """Configuration for a trigger node type."""+ node_type: str+ event_type: str # Event to wait for (e.g., 'whatsapp_message_received')+ display_name: str+++# Registry of supported trigger types (event-based triggers only)+# Note: cronScheduler is NOT an event-based trigger - it uses APScheduler directly+TRIGGER_REGISTRY: Dict[str, TriggerConfig] = {+ 'start': TriggerConfig(+ node_type='start',+ event_type='deploy_triggered',+ display_name='Deploy Start'+ ),+ 'whatsappReceive': TriggerConfig(+ node_type='whatsappReceive',+ event_type='whatsapp_message_received',+ display_name='WhatsApp Message'+ ),+ 'webhookTrigger': TriggerConfig(+ node_type='webhookTrigger',+ event_type='webhook_received',+ display_name='Webhook Request'+ ),+ # Future triggers - just add to registry:+ # 'emailTrigger': TriggerConfig('emailTrigger', 'email_received', 'Email'),+ # 'mqttTrigger': TriggerConfig('mqttTrigger', 'mqtt_message', 'MQTT Message'),+ # 'telegramTrigger': TriggerConfig('telegramTrigger', 'telegram_message', 'Telegram'),+}+++def is_trigger_node(node_type: str) -> bool:+ """Check if a node type is a trigger node (workflow starting point).++ Uses constants.WORKFLOW_TRIGGER_TYPES for comprehensive trigger detection.+ This includes all trigger types: start, cronScheduler, and event-based triggers.+ """+ from constants import WORKFLOW_TRIGGER_TYPES+ return node_type in WORKFLOW_TRIGGER_TYPES+++def is_event_trigger_node(node_type: str) -> bool:+ """Check if a node type is an event-based trigger (waits for events).++ Event-based triggers are registered in TRIGGER_REGISTRY and wait for+ external events to fire. This excludes 'start' and 'cronScheduler' which+ have their own execution mechanisms.+ """+ return node_type in TRIGGER_REGISTRY+++def get_trigger_config(node_type: str) -> Optional[TriggerConfig]:+ """Get trigger configuration for a node type."""+ return TRIGGER_REGISTRY.get(node_type)+++# =============================================================================+# FILTER BUILDERS - One per trigger type+# =============================================================================++def build_whatsapp_filter(params: Dict) -> Callable[[Dict], bool]:+ """Build filter function for WhatsApp messages.++ Based on schema.json event.message_received fields:+ - message_type: text, image, video, audio, document, sticker, location, contact, contacts+ - sender: Sender JID (e.g., [email protected] for DMs, or LID like 123@lid for groups)+ - chat_id: Chat JID (same as sender for DMs, group JID for groups)+ - is_from_me: boolean - true if sent by connected account+ - is_group: boolean - true if message is in a group chat+ - is_forwarded: boolean - true if message is forwarded+ - text: text content (for text messages)+ - group_info: { group_jid, sender_jid, sender_name } - present for group messages+ - sender_jid may be LID format, use LID cache to resolve to real phone+ """+ msg_type = params.get('messageTypeFilter', 'all')+ sender_filter = params.get('filter', 'all')+ contact_phone = params.get('contactPhone', '')+ group_id = params.get('group_id') or params.get('groupId', '')+ sender_number = params.get('senderNumber', '') # Optional sender filter within group+ keywords = [k.strip().lower() for k in params.get('keywords', '').split(',') if k.strip()]+ ignore_own = params.get('ignoreOwnMessages', True)+ forwarded_filter = params.get('forwardedFilter', 'all') # 'all', 'only_forwarded', 'ignore_forwarded'++ logger.debug(f"[WhatsAppFilter] Built: type={msg_type}, filter={sender_filter}, group_id='{group_id}', forwarded={forwarded_filter}")++ def matches(m: Dict) -> bool:+ msg_chat_id = m.get('chat_id', '')+ msg_sender = m.get('sender', '')+ group_info = m.get('group_info', {})+ is_group = m.get('is_group', False)++ # For group messages, try to resolve LID to phone using cache+ sender_jid = group_info.get('sender_jid', '') if is_group else msg_sender+ sender_phone = ''++ if is_group and sender_jid:+ # Check if sender_jid is a LID (ends with @lid)+ if '@lid' in sender_jid:+ # Try to get resolved phone from cache+ cached_phone = get_cached_phone(msg_chat_id, sender_jid)+ if cached_phone:+ sender_phone = cached_phone+ else:+ # LID not in cache, extract number part as fallback+ sender_phone = sender_jid.split('@')[0] if '@' in sender_jid else sender_jid+ else:+ # Not a LID, extract phone from JID+ sender_phone = sender_jid.split('@')[0] if '@' in sender_jid else sender_jid+ else:+ # DM - extract phone from sender+ sender_phone = msg_sender.split('@')[0] if '@' in msg_sender else msg_sender++ # Message type filter (schema field: message_type)+ if msg_type != 'all' and m.get('message_type') != msg_type:+ return False++ # Sender filter - for contact filter, use actual phone number+ if sender_filter == 'any_contact':+ # Only accept non-group messages (individual/contact messages)+ if is_group:+ return False++ if sender_filter == 'contact':+ if contact_phone not in sender_phone:+ return False++ if sender_filter == 'group':+ # For group filter, check if message is from that group+ if not is_group:+ return False+ if msg_chat_id != group_id:+ return False+ # Optional: filter by specific sender within group using resolved phone number+ if sender_number:+ if sender_number not in sender_phone:+ return False++ if sender_filter == 'keywords':+ text = (m.get('text') or '').lower()+ if not any(kw in text for kw in keywords):+ return False++ # Ignore own messages (schema field: is_from_me)+ if ignore_own and m.get('is_from_me'):+ return False++ # Forwarded message filter (schema field: is_forwarded)+ is_forwarded = m.get('is_forwarded', False)+ logger.debug(f"[WhatsAppFilter] Forwarded check: filter={forwarded_filter}, is_forwarded={is_forwarded}, raw_value={m.get('is_forwarded')}")+ if forwarded_filter == 'only_forwarded' and not is_forwarded:+ logger.debug(f"[WhatsAppFilter] Rejected: only_forwarded but message is not forwarded")+ return False+ if forwarded_filter == 'ignore_forwarded' and is_forwarded:+ logger.debug(f"[WhatsAppFilter] Rejected: ignore_forwarded but message is forwarded")+ return False++ logger.debug(f"[WhatsAppFilter] Matched message from {sender_phone}")+ return True++ return matches+++def build_webhook_filter(params: Dict) -> Callable[[Dict], bool]:+ """Build filter function for webhook requests.++ Filters by webhook path to ensure the event is for the correct trigger node.++ Args:+ params: Node parameters with 'path' field++ Returns:+ Filter function that checks if event path matches+ """+ webhook_path = params.get('path', '')++ def matches(data: Dict) -> bool:+ event_path = data.get('path', '')+ if webhook_path and event_path != webhook_path:+ return False+ return True++ return matches+++# Registry of filter builders per trigger type+FILTER_BUILDERS: Dict[str, Callable[[Dict], Callable[[Dict], bool]]] = {+ 'whatsappReceive': build_whatsapp_filter,+ 'webhookTrigger': build_webhook_filter,+}+++def build_filter(node_type: str, params: Dict) -> Callable[[Dict], bool]:+ """Build a filter function for the given trigger type and parameters."""+ builder = FILTER_BUILDERS.get(node_type)+ if builder:+ return builder(params)+ # Default: accept all events+ return lambda x: True+++# =============================================================================+# WAITER DATA STRUCTURES+# =============================================================================++@dataclass+class Waiter:+ """Single event waiter.++ In memory mode: uses asyncio.Future+ In Redis mode: uses stream polling with stored metadata+ """+ id: str = field(default_factory=lambda: str(uuid.uuid4()))+ node_id: str = ""+ node_type: str = ""+ event_type: str = ""+ params: Dict = field(default_factory=dict) # Store params for Redis mode filter rebuild+ filter_fn: Callable[[Dict], bool] = field(default_factory=lambda: lambda x: True)+ future: Optional[asyncio.Future] = None # Only used in memory mode+ cancelled: bool = False+ created_at: float = field(default_factory=time.time)+++# Module-level waiter storage (used in both modes for tracking)+_waiters: Dict[str, Waiter] = {}++# Redis stream names+EVENTS_STREAM_PREFIX = "events:"+WAITERS_KEY_PREFIX = "waiters:"+# NOTE: Each waiter uses its own consumer group to ensure ALL waiters receive ALL messages.+# Redis consumer groups deliver each message to only ONE consumer in the group.+# For trigger nodes, we want broadcast semantics where every waiter evaluates every event.+CONSUMER_GROUP_PREFIX = "waiter_group_" # Each waiter gets: waiter_group_{waiter_id}+++def _get_stream_name(event_type: str) -> str:+ """Get Redis stream name for event type."""+ return f"{EVENTS_STREAM_PREFIX}{event_type}"+++# =============================================================================+# WAITER REGISTRATION+# =============================================================================++async def register(node_type: str, node_id: str, params: Dict) -> Waiter:+ """Register a waiter for a trigger node.++ Args:+ node_type: Type of trigger node (e.g., 'whatsappReceive')+ node_id: ID of the node waiting+ params: Node parameters for building filter++ Returns:+ Waiter object to await+ """+ config = get_trigger_config(node_type)+ if not config:+ raise ValueError(f"Unknown trigger type: {node_type}")++ # Note: LID cache for group sender resolution is populated lazily on first message+ # We don't pre-fetch here to avoid blocking deployment with sequential RPC calls+ if node_type == 'whatsappReceive':+ filter_type = params.get('filter', 'all')+ group_id = params.get('group_id') or params.get('groupId', '')+ sender_number = params.get('senderNumber', '')++ if filter_type == 'group' and group_id and sender_number:+ logger.debug(f"[EventWaiter] Group filter with sender: {group_id}, sender: {sender_number}")++ # Create waiter+ waiter = Waiter(+ node_id=node_id,+ node_type=node_type,+ event_type=config.event_type,+ params=params,+ filter_fn=build_filter(node_type, params),+ )++ if is_redis_mode():+ # Redis mode: store waiter metadata in Redis+ cache = get_cache_service()+ waiter_key = f"{WAITERS_KEY_PREFIX}{waiter.id}"++ # Each waiter gets its own consumer group for broadcast semantics+ # This ensures ALL waiters receive ALL messages (not load-balanced)+ consumer_group = f"{CONSUMER_GROUP_PREFIX}{waiter.id}"++ waiter_data = {+ "id": waiter.id,+ "node_id": node_id,+ "node_type": node_type,+ "event_type": config.event_type,+ "params": json.dumps(params),+ "created_at": waiter.created_at,+ "consumer_group": consumer_group, # Store for cleanup+ }+ await cache.set(waiter_key, waiter_data, ttl=86400) # 24 hour TTL++ # Create unique consumer group for this waiter+ # start_id='$' means only new messages from this point forward+ stream_name = _get_stream_name(config.event_type)+ await cache.stream_create_group(stream_name, consumer_group, start_id='$')++ logger.debug(f"[EventWaiter] Registered {node_type} waiter {waiter.id} (Redis)")+ else:+ # Memory mode: create asyncio.Future+ try:+ loop = asyncio.get_running_loop()+ waiter.future = loop.create_future()+ except RuntimeError:+ waiter.future = asyncio.get_event_loop().create_future()++ logger.debug(f"[EventWaiter] Registered {node_type} waiter {waiter.id}")++ _waiters[waiter.id] = waiter+ return waiter+++async def wait_for_event(waiter: Waiter, timeout: Optional[float] = None) -> Dict:+ """Wait for an event matching the waiter's filter.++ Args:+ waiter: The registered waiter+ timeout: Optional timeout in seconds (None = wait forever)++ Returns:+ Event data when matched++ Raises:+ asyncio.CancelledError: If waiter was cancelled+ asyncio.TimeoutError: If timeout exceeded+ """+ if is_redis_mode():+ return await _wait_redis(waiter, timeout)+ else:+ return await _wait_memory(waiter, timeout)+++async def _wait_memory(waiter: Waiter, timeout: Optional[float]) -> Dict:+ """Wait using asyncio.Future (memory mode)."""+ if waiter.future is None:+ raise RuntimeError("Waiter has no Future (memory mode not initialized)")++ try:+ if timeout:+ return await asyncio.wait_for(waiter.future, timeout)+ else:+ return await waiter.future+ except asyncio.CancelledError:+ _cleanup_waiter(waiter.id)+ raise+++async def _wait_redis(waiter: Waiter, timeout: Optional[float]) -> Dict:+ """Wait using Redis Streams polling.++ Polls the event stream with blocking XREAD, checking each message against the filter.+ Each waiter has its own consumer group for broadcast semantics.+ """+ cache = get_cache_service()+ stream_name = _get_stream_name(waiter.event_type)++ # Use waiter-specific consumer group for broadcast (all waiters see all messages)+ consumer_group = f"{CONSUMER_GROUP_PREFIX}{waiter.id}"+ consumer_name = f"consumer_{waiter.id}"++ # Start reading from now (new messages only)+ last_id = '$'+ block_ms = 5000 # 5 second blocks to allow cancellation checks++ start_time = time.time()++ while not waiter.cancelled:+ # Check timeout+ if timeout and (time.time() - start_time) > timeout:+ raise asyncio.TimeoutError(f"Waiter {waiter.id} timed out after {timeout}s")++ # Read from stream with blocking using waiter's own consumer group+ try:+ result = await cache.stream_read_group(+ consumer_group, # Each waiter has its own group+ consumer_name,+ {stream_name: '>'}, # '>' = new messages for this consumer+ count=10,+ block=block_ms+ )++ if not result:+ # No messages, continue polling+ continue++ # Process messages+ for stream_data in result:+ stream, messages = stream_data+ for msg_id, fields in messages:+ # Deserialize event data+ event_data = {}+ for k, v in fields.items():+ try:+ event_data[k] = json.loads(v)+ except (json.JSONDecodeError, TypeError):+ event_data[k] = v++ # Check filter+ if waiter.filter_fn(event_data):+ # Match found - acknowledge and return+ await cache.stream_ack(stream_name, consumer_group, msg_id)+ _cleanup_waiter(waiter.id)+ logger.info(f"[EventWaiter] Waiter {waiter.id} matched event {msg_id}")+ return event_data+ else:+ # No match - acknowledge but continue waiting+ await cache.stream_ack(stream_name, consumer_group, msg_id)++ except asyncio.CancelledError:+ _cleanup_waiter(waiter.id)+ raise++ # Waiter was cancelled via cancel() flag+ _cleanup_waiter(waiter.id)+ raise asyncio.CancelledError(f"Waiter {waiter.id} cancelled")+++def _cleanup_waiter(waiter_id: str) -> None:+ """Remove waiter from storage."""+ _waiters.pop(waiter_id, None)++ # Also remove from Redis if in Redis mode+ if is_redis_mode():+ cache = get_cache_service()+ waiter_key = f"{WAITERS_KEY_PREFIX}{waiter_id}"+ asyncio.create_task(cache.delete(waiter_key))+++# =============================================================================+# EVENT DISPATCH+# =============================================================================++async def dispatch_async(event_type: str, data: Dict) -> int:+ """Dispatch event asynchronously (for Redis mode).++ Args:+ event_type: Type of event (e.g., 'whatsapp_message_received')+ data: Event data++ Returns:+ 1 if event was added to stream, 0 otherwise+ """+ logger.debug(f"[EventWaiter] dispatch_async: event_type='{event_type}'")++ if is_redis_mode():+ cache = get_cache_service()+ stream_name = _get_stream_name(event_type)+ msg_id = await cache.stream_add(stream_name, data)+ if msg_id:+ logger.debug(f"[EventWaiter] Added event to stream {stream_name}: {msg_id}")+ return 1+ return 0+ else:+ # Fall back to sync dispatch for memory mode+ return dispatch(event_type, data)+++def dispatch(event_type: str, data: Dict) -> int:+ """Dispatch event to matching waiters (synchronous, memory mode).++ Thread-safe: Can be called from APScheduler threads or async context.++ Args:+ event_type: Type of event (e.g., 'whatsapp_message_received')+ data: Event data++ Returns:+ Number of waiters resolved+ """+ if is_redis_mode():+ # In Redis mode, use async dispatch+ # Handle both async context and thread context (e.g., APScheduler callbacks)+ try:+ # Try to get the current running loop+ loop = asyncio.get_running_loop()+ # We're in an async context - schedule task normally+ asyncio.create_task(dispatch_async(event_type, data))+ except RuntimeError:+ # No running loop - we're in a thread (e.g., APScheduler callback)+ # Use the stored main loop with thread-safe dispatch+ if _main_loop is not None and _main_loop.is_running():+ asyncio.run_coroutine_threadsafe(dispatch_async(event_type, data), _main_loop)+ else:+ logger.warning(f"[EventWaiter] No event loop available for dispatch of {event_type}")+ return 0 # Actual resolution happens in _wait_redis++ resolved = 0+ to_remove = []++ for wid, w in _waiters.items():+ if w.event_type == event_type and w.future and not w.future.done():+ try:+ if w.filter_fn(data):+ w.future.set_result(data)+ to_remove.append(wid)+ resolved += 1+ logger.debug(f"[EventWaiter] Resolved {w.node_type} waiter {wid}")+ except Exception as e:+ logger.error(f"[EventWaiter] Filter error for waiter {wid}: {e}")++ for wid in to_remove:+ _waiters.pop(wid, None)++ return resolved+++# =============================================================================+# WAITER CANCELLATION+# =============================================================================++def cancel(waiter_id: str) -> bool:+ """Cancel a waiter by ID."""+ if w := _waiters.pop(waiter_id, None):+ w.cancelled = True++ if w.future and not w.future.done():+ w.future.cancel()++ # Also remove from Redis if in Redis mode+ if is_redis_mode():+ cache = get_cache_service()+ waiter_key = f"{WAITERS_KEY_PREFIX}{waiter_id}"+ asyncio.create_task(cache.delete(waiter_key))++ logger.debug(f"[EventWaiter] Cancelled waiter {waiter_id}")+ return True++ return False+++def cancel_for_node(node_id: str) -> int:+ """Cancel all waiters for a node."""+ to_cancel = [wid for wid, w in _waiters.items() if w.node_id == node_id]+ for wid in to_cancel:+ cancel(wid)+ return len(to_cancel)+++# =============================================================================+# UTILITY FUNCTIONS+# =============================================================================++def get_active_waiters() -> List[Dict[str, Any]]:+ """Get info about active waiters (for debugging/UI)."""+ return [+ {+ "id": w.id,+ "node_id": w.node_id,+ "node_type": w.node_type,+ "event_type": w.event_type,+ "done": w.future.done() if w.future else False,+ "cancelled": w.cancelled,+ "age_seconds": time.time() - w.created_at,+ "mode": "redis" if is_redis_mode() else "memory",+ }+ for w in _waiters.values()+ ]+++def clear_all() -> int:+ """Clear all waiters (for testing/cleanup)."""+ count = len(_waiters)+ for w in _waiters.values():+ w.cancelled = True+ if w.future and not w.future.done():+ w.future.cancel()+ _waiters.clear()++ # Clear Redis waiter keys if in Redis mode+ if is_redis_mode():+ cache = get_cache_service()+ asyncio.create_task(cache.clear_pattern(f"{WAITERS_KEY_PREFIX}*"))++ return count+++def get_backend_mode() -> str:+ """Get current backend mode for debugging."""+ return "redis" if is_redis_mode() else "memory"diff --git a/server/services/execution/__init__.py b/server/services/execution/__init__.pynew file mode 100644index 00000000..9f980b79--- /dev/null+++ b/server/services/execution/__init__.py@@ -0,0 +1,77 @@+"""Execution engine package.++Industry-standard workflow execution with:+- Conductor-style decide pattern+- Prefect-style task caching and transactions+- Redis persistence for crash recovery+- Parallel node execution with asyncio.gather+- Runtime conditional branching+"""++from .models import (+ TaskStatus,+ WorkflowStatus,+ ExecutionContext,+ NodeExecution,+ RetryPolicy,+ DLQEntry,+ hash_inputs,+ generate_cache_key,+ get_retry_policy,+ DEFAULT_RETRY_POLICIES,+)+from .executor import WorkflowExecutor+from .cache import ExecutionCache+from .recovery import (+ RecoverySweeper,+ get_recovery_sweeper,+ set_recovery_sweeper,+)+from .conditions import (+ evaluate_condition,+ evaluate_conditions,+ decide_next_edges,+ get_nested_value,+ get_available_operators,+ OPERATORS,+)+from .dlq import (+ DLQHandler,+ NullDLQHandler,+ DLQHandlerProtocol,+ create_dlq_handler,+)++__all__ = [+ # Models+ "TaskStatus",+ "WorkflowStatus",+ "ExecutionContext",+ "NodeExecution",+ "RetryPolicy",+ "DLQEntry",+ "hash_inputs",+ "generate_cache_key",+ "get_retry_policy",+ "DEFAULT_RETRY_POLICIES",+ # Executor+ "WorkflowExecutor",+ # Cache+ "ExecutionCache",+ # Recovery+ "RecoverySweeper",+ "get_recovery_sweeper",+ "set_recovery_sweeper",+ # Conditions+ "evaluate_condition",+ "evaluate_conditions",+ "decide_next_edges",+ "get_nested_value",+ "get_available_operators",+ "OPERATORS",+ # DLQ+ "DLQHandler",+ "NullDLQHandler",+ "DLQHandlerProtocol",+ "create_dlq_handler",+]diff --git a/server/services/execution/cache.py b/server/services/execution/cache.pynew file mode 100644index 00000000..b075bfa4--- /dev/null+++ b/server/services/execution/cache.py@@ -0,0 +1,769 @@+"""Execution cache service for Redis persistence.++Provides:+- Result caching (Prefect pattern) for idempotency+- Execution state persistence+- Distributed locking (Conductor pattern)+- Transaction checkpointing+"""++import asyncio+import json+import time+import uuid+from contextlib import asynccontextmanager+from typing import Dict, Any, List, Optional, Set, Union++from core.logging import get_logger+from core.cache import CacheService+from .models import ExecutionContext, TaskStatus, WorkflowStatus, hash_inputs, DLQEntry++logger = get_logger(__name__)+++def ensure_str(value: Union[str, bytes, None]) -> Optional[str]:+ """Ensure value is a string, handling both bytes and str.++ Redis with decode_responses=True returns strings directly.+ This helper handles both cases for compatibility.+ """+ if value is None:+ return None+ if isinstance(value, bytes):+ return value.decode('utf-8')+ return value+++class ExecutionCache:+ """Redis-backed cache for workflow execution state.++ Key schema:+ execution:{id}:state -> HASH {status, workflow_id, etc}+ execution:{id}:nodes -> HASH {node_id -> NodeExecution JSON}+ execution:{id}:outputs -> HASH {node_id -> output JSON}+ execution:{id}:events -> STREAM (immutable event log)+ result:{exec}:{node}:{hash} -> JSON (cached result)+ executions:active -> SET {execution_ids}+ lock:execution:{id} -> STRING (lock token)+ heartbeat:{exec}:{node} -> STRING (timestamp)+ """++ def __init__(self, cache_service: CacheService):+ self.cache = cache_service+ self._local_locks: Dict[str, asyncio.Lock] = {}++ # =========================================================================+ # EXECUTION STATE PERSISTENCE+ # =========================================================================++ async def save_execution_state(self, ctx: ExecutionContext) -> bool:+ """Persist execution context to Redis.++ Args:+ ctx: ExecutionContext to save++ Returns:+ True if saved successfully+ """+ try:+ key = f"execution:{ctx.execution_id}:state"+ data = ctx.to_dict()++ # Use Redis HSET for structured storage+ if self.cache.is_redis_available():+ mapping = {+ k: json.dumps(v) if isinstance(v, (dict, list)) else str(v)+ for k, v in data.items()+ }+ if mapping: # Only call hset if mapping is not empty+ await self.cache.redis.hset(key, mapping=mapping)+ # Set TTL (24 hours for completed, no TTL for active)+ if ctx.status in (WorkflowStatus.COMPLETED, WorkflowStatus.FAILED,+ WorkflowStatus.CANCELLED):+ await self.cache.redis.expire(key, 86400)++ # Track active executions+ if ctx.status == WorkflowStatus.RUNNING:+ await self.cache.redis.sadd("executions:active", ctx.execution_id)+ else:+ await self.cache.redis.srem("executions:active", ctx.execution_id)++ logger.debug("Saved execution state", execution_id=ctx.execution_id,+ status=ctx.status.value)+ return True+ else:+ # Fallback to simple key-value+ await self.cache.set(key, data, ttl=86400)+ return True++ except Exception as e:+ logger.error("Failed to save execution state", execution_id=ctx.execution_id,+ error=str(e))+ return False++ async def load_execution_state(self, execution_id: str,+ nodes: List[Dict] = None,+ edges: List[Dict] = None) -> Optional[ExecutionContext]:+ """Load execution context from Redis.++ Args:+ execution_id: Execution ID to load+ nodes: Workflow nodes (not stored in Redis due to size)+ edges: Workflow edges (not stored in Redis due to size)++ Returns:+ ExecutionContext if found, None otherwise+ """+ try:+ key = f"execution:{execution_id}:state"++ if self.cache.is_redis_available():+ raw_data = await self.cache.redis.hgetall(key)+ if not raw_data:+ return None++ # Deserialize Redis hash values+ # With decode_responses=True, values are already strings+ data = {}+ for k, v in raw_data.items():+ key_str = ensure_str(k)+ val_str = ensure_str(v)+ try:+ data[key_str] = json.loads(val_str)+ except (json.JSONDecodeError, TypeError):+ data[key_str] = val_str++ return ExecutionContext.from_dict(data, nodes, edges)+ else:+ # Fallback to simple key-value+ data = await self.cache.get(key)+ if data:+ return ExecutionContext.from_dict(data, nodes, edges)+ return None++ except Exception as e:+ logger.error("Failed to load execution state", execution_id=execution_id,+ error=str(e))+ return None++ async def get_active_executions(self) -> Set[str]:+ """Get all active execution IDs.++ Returns:+ Set of execution IDs currently running+ """+ try:+ if self.cache.is_redis_available():+ members = await self.cache.redis.smembers("executions:active")+ return {ensure_str(m) for m in members}+ return set()+ except Exception as e:+ logger.error("Failed to get active executions", error=str(e))+ return set()++ async def delete_execution_state(self, execution_id: str) -> bool:+ """Delete execution state from Redis.++ Args:+ execution_id: Execution ID to delete++ Returns:+ True if deleted successfully+ """+ try:+ if self.cache.is_redis_available():+ keys = [+ f"execution:{execution_id}:state",+ f"execution:{execution_id}:events",+ ]+ await self.cache.redis.delete(*keys)+ await self.cache.redis.srem("executions:active", execution_id)+ return True+ except Exception as e:+ logger.error("Failed to delete execution state", execution_id=execution_id,+ error=str(e))+ return False++ # =========================================================================+ # RESULT CACHING (Prefect pattern)+ # =========================================================================++ async def get_cached_result(self, execution_id: str, node_id: str,+ inputs: Dict[str, Any]) -> Optional[Dict[str, Any]]:+ """Get cached result for node execution (Prefect pattern).++ Args:+ execution_id: Execution ID+ node_id: Node ID+ inputs: Node inputs for cache key++ Returns:+ Cached result if found, None otherwise+ """+ try:+ input_hash = hash_inputs(inputs)+ cache_key = f"result:{execution_id}:{node_id}:{input_hash}"+ result = await self.cache.get(cache_key)+ if result:+ logger.debug("Cache hit", node_id=node_id, input_hash=input_hash[:8])+ return result+ except Exception as e:+ logger.error("Failed to get cached result", node_id=node_id, error=str(e))+ return None++ async def set_cached_result(self, execution_id: str, node_id: str,+ inputs: Dict[str, Any], result: Dict[str, Any],+ ttl: int = 3600) -> bool:+ """Cache node execution result (Prefect pattern).++ Args:+ execution_id: Execution ID+ node_id: Node ID+ inputs: Node inputs for cache key+ result: Execution result to cache+ ttl: Time-to-live in seconds (default 1 hour)++ Returns:+ True if cached successfully+ """+ try:+ input_hash = hash_inputs(inputs)+ cache_key = f"result:{execution_id}:{node_id}:{input_hash}"+ await self.cache.set(cache_key, result, ttl=ttl)+ logger.debug("Cached result", node_id=node_id, input_hash=input_hash[:8])+ return True+ except Exception as e:+ logger.error("Failed to cache result", node_id=node_id, error=str(e))+ return False++ # =========================================================================+ # DISTRIBUTED LOCKING (Conductor pattern)+ # =========================================================================++ @asynccontextmanager+ async def distributed_lock(self, lock_name: str, timeout: int = 60):+ """Acquire distributed lock using Redis (Conductor pattern).++ Used to prevent concurrent workflow_decide() calls.++ Args:+ lock_name: Name of the lock (e.g., "execution:{id}:decide")+ timeout: Lock timeout in seconds++ Yields:+ Lock token if acquired++ Raises:+ TimeoutError: If lock cannot be acquired+ """+ lock_key = f"lock:{lock_name}"+ lock_token = str(uuid.uuid4())+ acquired = False++ try:+ # Try to acquire lock+ if self.cache.is_redis_available():+ # Redis SETNX with expiry+ acquired = await self.cache.redis.set(+ lock_key, lock_token,+ ex=timeout,+ nx=True # Only set if not exists+ )+ else:+ # Fallback to local asyncio lock+ if lock_name not in self._local_locks:+ self._local_locks[lock_name] = asyncio.Lock()+ await asyncio.wait_for(+ self._local_locks[lock_name].acquire(),+ timeout=timeout+ )+ acquired = True++ if not acquired:+ raise TimeoutError(f"Could not acquire lock: {lock_name}")++ logger.debug("Lock acquired", lock_name=lock_name, token=lock_token[:8])+ yield lock_token++ finally:+ # Release lock+ if acquired:+ if self.cache.is_redis_available():+ # Only release if we hold the lock (check token)+ # With decode_responses=True, current is already a string+ current = await self.cache.redis.get(lock_key)+ if current and current == lock_token:+ await self.cache.redis.delete(lock_key)+ logger.debug("Lock released", lock_name=lock_name)+ else:+ if lock_name in self._local_locks:+ self._local_locks[lock_name].release()++ # =========================================================================+ # HEARTBEATS (for crash recovery)+ # =========================================================================++ async def update_heartbeat(self, execution_id: str, node_id: str) -> bool:+ """Update heartbeat for running node (for crash detection).++ Args:+ execution_id: Execution ID+ node_id: Node ID++ Returns:+ True if updated successfully+ """+ try:+ key = f"heartbeat:{execution_id}:{node_id}"+ timestamp = str(time.time())+ if self.cache.is_redis_available():+ await self.cache.redis.setex(key, 300, timestamp) # 5 min TTL+ else:+ await self.cache.set(key, timestamp, ttl=300)+ return True+ except Exception as e:+ logger.error("Failed to update heartbeat", node_id=node_id, error=str(e))+ return False++ async def get_heartbeat(self, execution_id: str, node_id: str) -> Optional[float]:+ """Get last heartbeat timestamp for a node.++ Args:+ execution_id: Execution ID+ node_id: Node ID++ Returns:+ Timestamp if found, None otherwise+ """+ try:+ key = f"heartbeat:{execution_id}:{node_id}"+ if self.cache.is_redis_available():+ val = await self.cache.redis.get(key)+ # With decode_responses=True, val is already a string+ return float(val) if val else None+ else:+ val = await self.cache.get(key)+ return float(val) if val else None+ except Exception as e:+ logger.error("Failed to get heartbeat", node_id=node_id, error=str(e))+ return None++ # =========================================================================+ # EVENT HISTORY (for debugging and recovery)+ # =========================================================================++ async def add_event(self, execution_id: str, event_type: str,+ data: Dict[str, Any]) -> Optional[str]:+ """Add event to execution history stream.++ Args:+ execution_id: Execution ID+ event_type: Event type (e.g., 'node_started', 'node_completed')+ data: Event data++ Returns:+ Message ID if successful, None otherwise+ """+ try:+ stream_key = f"execution:{execution_id}:events"+ event_data = {+ "type": event_type,+ "timestamp": time.time(),+ **data+ }+ return await self.cache.stream_add(stream_key, event_data, maxlen=1000)+ except Exception as e:+ logger.error("Failed to add event", execution_id=execution_id, error=str(e))+ return None++ async def get_events(self, execution_id: str, count: int = 100) -> List[Dict[str, Any]]:+ """Get execution event history.++ Args:+ execution_id: Execution ID+ count: Maximum events to return++ Returns:+ List of events+ """+ try:+ stream_key = f"execution:{execution_id}:events"+ if not self.cache.is_redis_available():+ return []++ # Read from stream+ result = await self.cache.stream_read(+ {stream_key: "0"},+ count=count+ )++ events = []+ if result:+ for stream_name, messages in result:+ for msg_id, msg_data in messages:+ # Deserialize event data+ event = {}+ for k, v in msg_data.items():+ key_str = ensure_str(k)+ val_str = ensure_str(v)+ try:+ event[key_str] = json.loads(val_str)+ except (json.JSONDecodeError, TypeError):+ event[key_str] = val_str+ events.append(event)++ return events+ except Exception as e:+ logger.error("Failed to get events", execution_id=execution_id, error=str(e))+ return []++ # =========================================================================+ # TRANSACTION CHECKPOINTS (Prefect pattern)+ # =========================================================================++ async def checkpoint_transaction(self, transaction_id: str, node_id: str,+ result: Dict[str, Any]) -> bool:+ """Save transaction checkpoint (Prefect pattern).++ Args:+ transaction_id: Transaction ID+ node_id: Node that completed+ result: Node result++ Returns:+ True if saved successfully+ """+ try:+ key = f"txn:{transaction_id}:checkpoints"+ checkpoint = {+ "node_id": node_id,+ "result": result,+ "timestamp": time.time()+ }+ if self.cache.is_redis_available():+ await self.cache.redis.rpush(key, json.dumps(checkpoint))+ await self.cache.redis.expire(key, 86400) # 24 hour TTL+ return True+ except Exception as e:+ logger.error("Failed to checkpoint", transaction_id=transaction_id, error=str(e))+ return False++ async def rollback_transaction(self, transaction_id: str) -> bool:+ """Rollback transaction by clearing checkpoints.++ Args:+ transaction_id: Transaction ID to rollback++ Returns:+ True if rolled back successfully+ """+ try:+ key = f"txn:{transaction_id}:checkpoints"+ if self.cache.is_redis_available():+ await self.cache.redis.delete(key)+ logger.info("Transaction rolled back", transaction_id=transaction_id)+ return True+ except Exception as e:+ logger.error("Failed to rollback", transaction_id=transaction_id, error=str(e))+ return False++ async def get_transaction_checkpoints(self, transaction_id: str) -> List[Dict[str, Any]]:+ """Get transaction checkpoints for recovery.++ Args:+ transaction_id: Transaction ID++ Returns:+ List of checkpoints+ """+ try:+ key = f"txn:{transaction_id}:checkpoints"+ if not self.cache.is_redis_available():+ return []++ raw_list = await self.cache.redis.lrange(key, 0, -1)+ return [json.loads(ensure_str(item)) for item in raw_list]+ except Exception as e:+ logger.error("Failed to get checkpoints", transaction_id=transaction_id, error=str(e))+ return []++ # =========================================================================+ # DEAD LETTER QUEUE (for failed executions)+ # =========================================================================++ async def add_to_dlq(self, entry: DLQEntry) -> bool:+ """Add failed node execution to Dead Letter Queue.++ Stores the entry in multiple indices for querying:+ - dlq:entries:{id} - Individual entry data+ - dlq:workflow:{workflow_id} - List of entry IDs for workflow+ - dlq:node_type:{node_type} - List of entry IDs by node type+ - dlq:all - Set of all entry IDs++ Args:+ entry: DLQEntry to add++ Returns:+ True if added successfully+ """+ try:+ entry_data = entry.to_dict()++ if self.cache.is_redis_available():+ # Store entry data+ entry_key = f"dlq:entries:{entry.id}"+ mapping = {+ k: json.dumps(v) if isinstance(v, (dict, list)) else str(v)+ for k, v in entry_data.items()+ }+ if mapping: # Only call hset if mapping is not empty+ await self.cache.redis.hset(entry_key, mapping=mapping)+ # Set TTL (7 days for DLQ entries)+ await self.cache.redis.expire(entry_key, 604800)++ # Add to workflow index+ workflow_key = f"dlq:workflow:{entry.workflow_id}"+ await self.cache.redis.lpush(workflow_key, entry.id)+ await self.cache.redis.expire(workflow_key, 604800)++ # Add to node type index+ node_type_key = f"dlq:node_type:{entry.node_type}"+ await self.cache.redis.lpush(node_type_key, entry.id)+ await self.cache.redis.expire(node_type_key, 604800)++ # Add to global set+ await self.cache.redis.sadd("dlq:all", entry.id)++ logger.info("Added to DLQ", entry_id=entry.id, node_id=entry.node_id,+ node_type=entry.node_type, error=entry.error[:100])+ return True+ else:+ # Fallback to simple key-value+ await self.cache.set(f"dlq:entries:{entry.id}", entry_data, ttl=604800)+ return True++ except Exception as e:+ logger.error("Failed to add to DLQ", entry_id=entry.id, error=str(e))+ return False++ async def get_dlq_entry(self, entry_id: str) -> Optional[DLQEntry]:+ """Get a single DLQ entry by ID.++ Args:+ entry_id: DLQ entry ID++ Returns:+ DLQEntry if found, None otherwise+ """+ try:+ entry_key = f"dlq:entries:{entry_id}"++ if self.cache.is_redis_available():+ raw_data = await self.cache.redis.hgetall(entry_key)+ if not raw_data:+ return None++ # Deserialize Redis hash values+ data = {}+ for k, v in raw_data.items():+ key_str = ensure_str(k)+ val_str = ensure_str(v)+ try:+ data[key_str] = json.loads(val_str)+ except (json.JSONDecodeError, TypeError):+ data[key_str] = val_str++ return DLQEntry.from_dict(data)+ else:+ data = await self.cache.get(entry_key)+ if data:+ return DLQEntry.from_dict(data)+ return None++ except Exception as e:+ logger.error("Failed to get DLQ entry", entry_id=entry_id, error=str(e))+ return None++ async def get_dlq_entries(self, workflow_id: Optional[str] = None,+ node_type: Optional[str] = None,+ limit: int = 100) -> List[DLQEntry]:+ """Get DLQ entries with optional filtering.++ Args:+ workflow_id: Filter by workflow ID+ node_type: Filter by node type+ limit: Maximum entries to return++ Returns:+ List of DLQEntry objects+ """+ try:+ if not self.cache.is_redis_available():+ return []++ # Determine which index to use+ if workflow_id:+ index_key = f"dlq:workflow:{workflow_id}"+ elif node_type:+ index_key = f"dlq:node_type:{node_type}"+ else:+ # Get all entries from global set+ entry_ids = await self.cache.redis.smembers("dlq:all")+ entry_ids = [ensure_str(eid) for eid in entry_ids][:limit]+ entries = []+ for entry_id in entry_ids:+ entry = await self.get_dlq_entry(entry_id)+ if entry:+ entries.append(entry)+ # Sort by last_error_at descending+ entries.sort(key=lambda e: e.last_error_at, reverse=True)+ return entries++ # Get from LIST index+ raw_ids = await self.cache.redis.lrange(index_key, 0, limit - 1)+ entry_ids = [ensure_str(eid) for eid in raw_ids]++ entries = []+ for entry_id in entry_ids:+ entry = await self.get_dlq_entry(entry_id)+ if entry:+ entries.append(entry)++ return entries++ except Exception as e:+ logger.error("Failed to get DLQ entries", error=str(e))+ return []++ async def remove_from_dlq(self, entry_id: str) -> bool:+ """Remove entry from DLQ after successful replay or manual purge.++ Args:+ entry_id: DLQ entry ID to remove++ Returns:+ True if removed successfully+ """+ try:+ if not self.cache.is_redis_available():+ return False++ # Get entry first to know which indices to update+ entry = await self.get_dlq_entry(entry_id)+ if not entry:+ return False++ # Remove from indices+ await self.cache.redis.lrem(f"dlq:workflow:{entry.workflow_id}", 0, entry_id)+ await self.cache.redis.lrem(f"dlq:node_type:{entry.node_type}", 0, entry_id)+ await self.cache.redis.srem("dlq:all", entry_id)++ # Delete entry data+ await self.cache.redis.delete(f"dlq:entries:{entry_id}")++ logger.info("Removed from DLQ", entry_id=entry_id)+ return True++ except Exception as e:+ logger.error("Failed to remove from DLQ", entry_id=entry_id, error=str(e))+ return False++ async def update_dlq_entry(self, entry_id: str, retry_count: int,+ error: str) -> bool:+ """Update DLQ entry after failed retry attempt.++ Args:+ entry_id: DLQ entry ID+ retry_count: New retry count+ error: Latest error message++ Returns:+ True if updated successfully+ """+ try:+ if not self.cache.is_redis_available():+ return False++ entry_key = f"dlq:entries:{entry_id}"+ await self.cache.redis.hset(entry_key, mapping={+ "retry_count": str(retry_count),+ "error": error,+ "last_error_at": str(time.time())+ })++ logger.debug("Updated DLQ entry", entry_id=entry_id, retry_count=retry_count)+ return True++ except Exception as e:+ logger.error("Failed to update DLQ entry", entry_id=entry_id, error=str(e))+ return False++ async def get_dlq_stats(self) -> Dict[str, Any]:+ """Get DLQ statistics.++ Returns:+ Dictionary with DLQ stats (total count, by node type, by workflow)+ """+ try:+ if not self.cache.is_redis_available():+ return {"total": 0, "by_node_type": {}, "by_workflow": {}}++ # Get total count+ total = await self.cache.redis.scard("dlq:all")++ # Get all entries for breakdown+ entries = await self.get_dlq_entries(limit=1000)++ by_node_type = {}+ by_workflow = {}+ for entry in entries:+ by_node_type[entry.node_type] = by_node_type.get(entry.node_type, 0) + 1+ by_workflow[entry.workflow_id] = by_workflow.get(entry.workflow_id, 0) + 1++ return {+ "total": total,+ "by_node_type": by_node_type,+ "by_workflow": by_workflow+ }++ except Exception as e:+ logger.error("Failed to get DLQ stats", error=str(e))+ return {"total": 0, "by_node_type": {}, "by_workflow": {}}++ async def purge_dlq(self, workflow_id: Optional[str] = None,+ node_type: Optional[str] = None,+ older_than: Optional[float] = None) -> int:+ """Purge entries from DLQ.++ Args:+ workflow_id: Only purge entries for this workflow+ node_type: Only purge entries for this node type+ older_than: Only purge entries older than this timestamp++ Returns:+ Number of entries purged+ """+ try:+ if not self.cache.is_redis_available():+ return 0++ entries = await self.get_dlq_entries(workflow_id=workflow_id,+ node_type=node_type,+ limit=10000)++ purged = 0+ for entry in entries:+ # Check age filter+ if older_than and entry.created_at > older_than:+ continue++ if await self.remove_from_dlq(entry.id):+ purged += 1++ logger.info("Purged DLQ entries", count=purged, workflow_id=workflow_id,+ node_type=node_type)+ return purged++ except Exception as e:+ logger.error("Failed to purge DLQ", error=str(e))+ return 0diff --git a/server/services/execution/conditions.py b/server/services/execution/conditions.pynew file mode 100644index 00000000..cab70e59--- /dev/null+++ b/server/services/execution/conditions.py@@ -0,0 +1,373 @@+"""Condition evaluation for runtime conditional branching.++Evaluates edge conditions against node outputs to determine+which paths to follow in a workflow (Prefect-style dynamic branching).++Supported operators:+- eq: Equal (==)+- neq: Not equal (!=)+- gt: Greater than (>)+- lt: Less than (<)+- gte: Greater than or equal (>=)+- lte: Less than or equal (<=)+- contains: String/list contains value+- not_contains: String/list does not contain value+- exists: Field exists and is not None+- not_exists: Field does not exist or is None+- is_empty: Field is empty (None, "", [], {})+- is_not_empty: Field is not empty+- matches: Regex pattern match+- in: Value is in list+- not_in: Value is not in list+- starts_with: String starts with value+- ends_with: String ends with value+"""++import re+from typing import Dict, Any, Optional, List, Union++from core.logging import get_logger++logger = get_logger(__name__)+++# Type alias for condition dict+ConditionDict = Dict[str, Any]+++def get_nested_value(data: Dict[str, Any], field_path: str) -> Any:+ """Get a nested value from a dictionary using dot notation.++ Args:+ data: Dictionary to extract value from+ field_path: Dot-separated path (e.g., "result.status", "items.0.name")++ Returns:+ Value at path or None if not found++ Examples:+ >>> get_nested_value({"result": {"status": "ok"}}, "result.status")+ "ok"+ >>> get_nested_value({"items": [{"name": "a"}]}, "items.0.name")+ "a"+ """+ if not data or not field_path:+ return None++ parts = field_path.split('.')+ current = data++ for part in parts:+ if current is None:+ return None++ # Handle array index+ if part.isdigit():+ index = int(part)+ if isinstance(current, (list, tuple)) and 0 <= index < len(current):+ current = current[index]+ else:+ return None+ # Handle dict key+ elif isinstance(current, dict):+ current = current.get(part)+ else:+ return None++ return current+++def evaluate_condition(condition: ConditionDict, output: Dict[str, Any]) -> bool:+ """Evaluate an edge condition against node output.++ Args:+ condition: Condition dict with field, operator, value+ {+ "field": "status", # Output field to check+ "operator": "eq", # Comparison operator+ "value": "success" # Value to compare against+ }+ output: Node execution output dict++ Returns:+ True if condition matches, False otherwise+ """+ if not condition:+ return True # No condition = always follow++ field = condition.get("field", "")+ operator = condition.get("operator", "eq")+ target_value = condition.get("value")++ # Get the actual value from output+ actual_value = get_nested_value(output, field)++ logger.debug("Evaluating condition",+ field=field,+ operator=operator,+ target=target_value,+ actual=actual_value)++ try:+ result = _evaluate_operator(operator, actual_value, target_value)+ logger.debug("Condition result", result=result)+ return result+ except Exception as e:+ logger.warning("Condition evaluation error",+ field=field,+ operator=operator,+ error=str(e))+ return False+++def _evaluate_operator(operator: str, actual: Any, target: Any) -> bool:+ """Evaluate a single operator.++ Args:+ operator: Operator name+ actual: Actual value from output+ target: Target value to compare++ Returns:+ Comparison result+ """+ # Equality operators+ if operator == "eq":+ return actual == target++ elif operator == "neq":+ return actual != target++ # Comparison operators (numeric)+ elif operator == "gt":+ return _safe_compare(actual, target, lambda a, b: a > b)++ elif operator == "lt":+ return _safe_compare(actual, target, lambda a, b: a < b)++ elif operator == "gte":+ return _safe_compare(actual, target, lambda a, b: a >= b)++ elif operator == "lte":+ return _safe_compare(actual, target, lambda a, b: a <= b)++ # String/list contains+ elif operator == "contains":+ if actual is None:+ return False+ if isinstance(actual, str):+ return str(target) in actual+ elif isinstance(actual, (list, tuple)):+ return target in actual+ elif isinstance(actual, dict):+ return target in actual+ return False++ elif operator == "not_contains":+ return not _evaluate_operator("contains", actual, target)++ # Existence checks+ elif operator == "exists":+ return actual is not None++ elif operator == "not_exists":+ return actual is None++ # Empty checks+ elif operator == "is_empty":+ if actual is None:+ return True+ if isinstance(actual, (str, list, dict, tuple)):+ return len(actual) == 0+ return False++ elif operator == "is_not_empty":+ return not _evaluate_operator("is_empty", actual, target)++ # Regex match+ elif operator == "matches":+ if actual is None or target is None:+ return False+ try:+ return bool(re.search(str(target), str(actual)))+ except re.error:+ logger.warning("Invalid regex pattern", pattern=target)+ return False++ # List membership+ elif operator == "in":+ if not isinstance(target, (list, tuple)):+ return actual == target+ return actual in target++ elif operator == "not_in":+ return not _evaluate_operator("in", actual, target)++ # String prefix/suffix+ elif operator == "starts_with":+ if actual is None or target is None:+ return False+ return str(actual).startswith(str(target))++ elif operator == "ends_with":+ if actual is None or target is None:+ return False+ return str(actual).endswith(str(target))++ # Boolean checks+ elif operator == "is_true":+ return actual is True or actual == "true" or actual == 1++ elif operator == "is_false":+ return actual is False or actual == "false" or actual == 0++ # Type checks+ elif operator == "is_string":+ return isinstance(actual, str)++ elif operator == "is_number":+ return isinstance(actual, (int, float)) and not isinstance(actual, bool)++ elif operator == "is_boolean":+ return isinstance(actual, bool)++ elif operator == "is_array":+ return isinstance(actual, (list, tuple))++ elif operator == "is_object":+ return isinstance(actual, dict)++ else:+ logger.warning("Unknown operator", operator=operator)+ return False+++def _safe_compare(actual: Any, target: Any, comparator) -> bool:+ """Safely compare two values, handling type coercion.++ Args:+ actual: Actual value+ target: Target value+ comparator: Comparison function++ Returns:+ Comparison result, False if comparison impossible+ """+ if actual is None or target is None:+ return False++ # Try numeric comparison first+ try:+ return comparator(float(actual), float(target))+ except (ValueError, TypeError):+ pass++ # Fall back to string comparison+ try:+ return comparator(str(actual), str(target))+ except (ValueError, TypeError):+ return False+++def evaluate_conditions(conditions: List[ConditionDict], output: Dict[str, Any],+ logic: str = "and") -> bool:+ """Evaluate multiple conditions with AND/OR logic.++ Args:+ conditions: List of condition dicts+ output: Node execution output+ logic: "and" (all must match) or "or" (any must match)++ Returns:+ Combined evaluation result+ """+ if not conditions:+ return True++ results = [evaluate_condition(c, output) for c in conditions]++ if logic == "or":+ return any(results)+ else: # "and"+ return all(results)+++def decide_next_edges(edges: List[Dict[str, Any]], source_node_id: str,+ output: Dict[str, Any]) -> List[str]:+ """Determine which edges to follow based on conditions.++ Args:+ edges: All edges in workflow+ source_node_id: ID of the node that just completed+ output: Output from the completed node++ Returns:+ List of target node IDs to execute next+ """+ next_nodes = []+ unconditional_edges = []+ conditional_edges = []++ # Separate edges by type+ for edge in edges:+ if edge.get("source") != source_node_id:+ continue++ condition = edge.get("data", {}).get("condition")+ if condition:+ conditional_edges.append(edge)+ else:+ unconditional_edges.append(edge)++ # If there are conditional edges, evaluate them+ if conditional_edges:+ for edge in conditional_edges:+ condition = edge.get("data", {}).get("condition")+ if evaluate_condition(condition, output):+ next_nodes.append(edge["target"])+ logger.info("Conditional edge matched",+ source=source_node_id,+ target=edge["target"],+ condition=condition)++ # If no conditional edges matched, fall through to unconditional+ if not next_nodes and unconditional_edges:+ logger.info("No conditional edges matched, using unconditional",+ source=source_node_id)+ for edge in unconditional_edges:+ next_nodes.append(edge["target"])+ else:+ # No conditions - follow all unconditional edges+ for edge in unconditional_edges:+ next_nodes.append(edge["target"])++ return next_nodes+++# Operator metadata for frontend UI+OPERATORS = {+ "eq": {"label": "Equals", "description": "Value equals target", "requires_value": True},+ "neq": {"label": "Not Equals", "description": "Value does not equal target", "requires_value": True},+ "gt": {"label": "Greater Than", "description": "Value is greater than target", "requires_value": True},+ "lt": {"label": "Less Than", "description": "Value is less than target", "requires_value": True},+ "gte": {"label": "Greater or Equal", "description": "Value is greater than or equal to target", "requires_value": True},+ "lte": {"label": "Less or Equal", "description": "Value is less than or equal to target", "requires_value": True},+ "contains": {"label": "Contains", "description": "String/list contains value", "requires_value": True},+ "not_contains": {"label": "Does Not Contain", "description": "String/list does not contain value", "requires_value": True},+ "exists": {"label": "Exists", "description": "Field exists and is not null", "requires_value": False},+ "not_exists": {"label": "Does Not Exist", "description": "Field does not exist or is null", "requires_value": False},+ "is_empty": {"label": "Is Empty", "description": "Value is empty (null, '', [], {})", "requires_value": False},+ "is_not_empty": {"label": "Is Not Empty", "description": "Value is not empty", "requires_value": False},+ "matches": {"label": "Matches Regex", "description": "Value matches regex pattern", "requires_value": True},+ "in": {"label": "In List", "description": "Value is in list", "requires_value": True},+ "not_in": {"label": "Not In List", "description": "Value is not in list", "requires_value": True},+ "starts_with": {"label": "Starts With", "description": "String starts with value", "requires_value": True},+ "ends_with": {"label": "Ends With", "description": "String ends with value", "requires_value": True},+ "is_true": {"label": "Is True", "description": "Value is truthy", "requires_value": False},+ "is_false": {"label": "Is False", "description": "Value is falsy", "requires_value": False},+}+++def get_available_operators() -> Dict[str, Dict[str, Any]]:+ """Get operator metadata for frontend UI."""+ return OPERATORS.copy()diff --git a/server/services/execution/dlq.py b/server/services/execution/dlq.pynew file mode 100644index 00000000..1ebd5ec2--- /dev/null+++ b/server/services/execution/dlq.py@@ -0,0 +1,132 @@+"""Dead Letter Queue (DLQ) handler for failed node executions.++This module provides optional DLQ functionality that can be enabled/disabled+via configuration. When enabled, failed nodes (after all retries exhausted)+are stored for later inspection and replay.++Usage:+ from services.execution.dlq import DLQHandler, NullDLQHandler++ # Create handler based on config+ dlq = DLQHandler(cache) if settings.dlq_enabled else NullDLQHandler()++ # Add failed node+ await dlq.add_failed_node(ctx, node, inputs, error)+"""++from typing import Dict, Any, Protocol+from core.logging import get_logger+from .models import ExecutionContext, NodeExecution, DLQEntry++logger = get_logger(__name__)+++class DLQHandlerProtocol(Protocol):+ """Protocol for DLQ handlers (enables duck typing)."""++ async def add_failed_node(self, ctx: ExecutionContext, node: NodeExecution,+ inputs: Dict[str, Any], error: str) -> bool:+ """Add a failed node to the DLQ."""+ ...++ @property+ def enabled(self) -> bool:+ """Whether DLQ is enabled."""+ ...+++class NullDLQHandler:+ """No-op DLQ handler when DLQ is disabled.++ This follows the Null Object pattern - all operations succeed silently.+ """++ @property+ def enabled(self) -> bool:+ return False++ async def add_failed_node(self, ctx: ExecutionContext, node: NodeExecution,+ inputs: Dict[str, Any], error: str) -> bool:+ """No-op: silently succeed without storing anything."""+ logger.debug("DLQ disabled, skipping failed node storage",+ node_id=node.node_id, error=error)+ return True+++class DLQHandler:+ """Active DLQ handler that stores failed nodes in Redis.++ Stores failed node executions with full context for later inspection+ and replay via the replay_dlq_entry API.+ """++ def __init__(self, cache: "ExecutionCache"):+ """Initialize DLQ handler.++ Args:+ cache: ExecutionCache instance for Redis persistence+ """+ self.cache = cache++ @property+ def enabled(self) -> bool:+ return True++ async def add_failed_node(self, ctx: ExecutionContext, node: NodeExecution,+ inputs: Dict[str, Any], error: str) -> bool:+ """Add a failed node to the Dead Letter Queue.++ Args:+ ctx: ExecutionContext with workflow info+ node: Failed NodeExecution with retry info+ inputs: Node inputs at time of failure+ error: Final error message++ Returns:+ True if successfully added, False otherwise+ """+ try:+ dlq_entry = DLQEntry.create(ctx, node, inputs)++ success = await self.cache.add_to_dlq(dlq_entry)+ if success:+ logger.info("Node added to DLQ",+ entry_id=dlq_entry.id,+ node_id=node.node_id,+ node_type=node.node_type,+ retry_count=node.retry_count)++ await self.cache.add_event(ctx.execution_id, "node_dlq", {+ "node_id": node.node_id,+ "dlq_entry_id": dlq_entry.id,+ "error": error,+ "retry_count": node.retry_count,+ })+ return True+ else:+ logger.error("Failed to add node to DLQ",+ node_id=node.node_id, error=error)+ return False++ except Exception as e:+ logger.error("Exception adding node to DLQ",+ node_id=node.node_id, error=str(e))+ return False+++def create_dlq_handler(cache: "ExecutionCache", enabled: bool = False) -> DLQHandlerProtocol:+ """Factory function to create appropriate DLQ handler.++ Args:+ cache: ExecutionCache instance+ enabled: Whether DLQ should be enabled++ Returns:+ DLQHandler if enabled, NullDLQHandler otherwise+ """+ if enabled:+ logger.info("DLQ enabled")+ return DLQHandler(cache)+ else:+ logger.debug("DLQ disabled")+ return NullDLQHandler()diff --git a/server/services/execution/executor.py b/server/services/execution/executor.pynew file mode 100644index 00000000..f2d479da--- /dev/null+++ b/server/services/execution/executor.py@@ -0,0 +1,1303 @@+"""Workflow executor with Conductor decide pattern and parallel execution.++Implements:+- Conductor-style workflow_decide() for orchestration+- Prefect-style task caching for idempotency+- Fork/Join parallel execution with asyncio.wait (FIRST_COMPLETED pattern)+- Dynamic workflow branching at runtime+- Proper handling of long-running trigger nodes in parallel batches+"""++import asyncio+import time+from collections import defaultdict+from datetime import datetime+from typing import Dict, Any, List, Optional, Callable, Awaitable, Set++from core.logging import get_logger+from constants import WORKFLOW_TRIGGER_TYPES+from .models import (+ ExecutionContext,+ TaskStatus,+ WorkflowStatus,+ NodeExecution,+ hash_inputs,+ RetryPolicy,+ get_retry_policy,+)+from .cache import ExecutionCache+from .conditions import evaluate_condition, decide_next_edges+from .dlq import create_dlq_handler, DLQHandlerProtocol, NullDLQHandler++logger = get_logger(__name__)+++def is_trigger_node(node_type: str) -> bool:+ """Check if a node type is a trigger node (workflow starting point).++ Trigger nodes have no input handles and serve as entry points for workflows.+ They are identified by WORKFLOW_TRIGGER_TYPES in constants.py.++ Args:+ node_type: The node type string++ Returns:+ True if the node is a trigger type+ """+ return node_type in WORKFLOW_TRIGGER_TYPES+++class WorkflowExecutor:+ """Executes workflows using Conductor decide pattern with parallel execution.++ Features:+ - Isolated ExecutionContext per workflow run+ - Parallel execution of independent nodes (Fork/Join)+ - Result caching for idempotency (Prefect pattern)+ - Distributed locking to prevent race conditions+ - Event history for debugging and recovery+ """++ def __init__(self, cache: ExecutionCache,+ node_executor: Callable[[str, str, Dict, Dict], Awaitable[Dict]],+ status_callback: Callable[[str, str, Dict], Awaitable[None]] = None,+ dlq_enabled: bool = False):+ """Initialize executor.++ Args:+ cache: ExecutionCache for Redis persistence+ node_executor: Async function to execute a single node+ Signature: async def execute(node_id, node_type, params, context) -> result+ status_callback: Optional async callback for status updates+ Signature: async def callback(node_id, status, data)+ dlq_enabled: Whether to add failed nodes to Dead Letter Queue+ """+ self.cache = cache+ self.node_executor = node_executor+ self.status_callback = status_callback++ # Create DLQ handler (modular - uses Null Object pattern when disabled)+ self.dlq = create_dlq_handler(cache, enabled=dlq_enabled)++ # Active executions (in-memory for fast lookup)+ self._active_contexts: Dict[str, ExecutionContext] = {}++ # =========================================================================+ # EXECUTION ENTRY POINTS+ # =========================================================================++ async def execute_workflow(self, workflow_id: str, nodes: List[Dict],+ edges: List[Dict], session_id: str = "default",+ enable_caching: bool = True) -> Dict[str, Any]:+ """Execute a workflow with parallel node execution.++ Args:+ workflow_id: Workflow identifier+ nodes: List of workflow nodes+ edges: List of edges connecting nodes+ session_id: Session identifier+ enable_caching: Whether to use result caching++ Returns:+ Execution result dict+ """+ start_time = time.time()++ # Create isolated execution context+ ctx = ExecutionContext.create(+ workflow_id=workflow_id,+ session_id=session_id,+ nodes=nodes,+ edges=edges,+ )++ # Compute execution layers (for parallel batches)+ ctx.execution_order = self._compute_execution_layers(nodes, edges)++ logger.info("Starting workflow execution",+ execution_id=ctx.execution_id,+ workflow_id=workflow_id,+ node_count=len(nodes),+ layers=len(ctx.execution_order))++ # Track in memory+ self._active_contexts[ctx.execution_id] = ctx++ # Persist initial state+ ctx.status = WorkflowStatus.RUNNING+ ctx.started_at = time.time()+ await self.cache.save_execution_state(ctx)++ # Add workflow_started event+ await self.cache.add_event(ctx.execution_id, "workflow_started", {+ "workflow_id": workflow_id,+ "node_count": len(nodes),+ })++ try:+ # Run the decide loop+ await self._workflow_decide(ctx, enable_caching)++ # Determine final status+ if ctx.all_nodes_complete():+ ctx.status = WorkflowStatus.COMPLETED+ elif ctx.errors:+ ctx.status = WorkflowStatus.FAILED++ ctx.completed_at = time.time()+ await self.cache.save_execution_state(ctx)++ # Add workflow_completed event+ await self.cache.add_event(ctx.execution_id, "workflow_completed", {+ "status": ctx.status.value,+ "completed_nodes": len(ctx.get_completed_nodes()),+ "execution_time": ctx.completed_at - ctx.started_at,+ })++ return {+ "success": ctx.status == WorkflowStatus.COMPLETED,+ "execution_id": ctx.execution_id,+ "status": ctx.status.value,+ "nodes_executed": ctx.get_completed_nodes(),+ "outputs": ctx.outputs,+ "errors": ctx.errors,+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat(),+ }++ except asyncio.CancelledError:+ ctx.status = WorkflowStatus.CANCELLED+ ctx.completed_at = time.time()+ await self.cache.save_execution_state(ctx)+ await self.cache.add_event(ctx.execution_id, "workflow_cancelled", {})+ return {+ "success": False,+ "execution_id": ctx.execution_id,+ "status": "cancelled",+ "error": "Cancelled by user",+ "execution_time": time.time() - start_time,+ }++ except Exception as e:+ logger.error("Workflow execution failed", execution_id=ctx.execution_id,+ error=str(e))+ ctx.status = WorkflowStatus.FAILED+ ctx.errors.append({"error": str(e), "timestamp": time.time()})+ await self.cache.save_execution_state(ctx)+ await self.cache.add_event(ctx.execution_id, "workflow_failed", {+ "error": str(e),+ })+ return {+ "success": False,+ "execution_id": ctx.execution_id,+ "status": "failed",+ "error": str(e),+ "execution_time": time.time() - start_time,+ }++ finally:+ # Cleanup+ self._active_contexts.pop(ctx.execution_id, None)++ async def cancel_execution(self, execution_id: str) -> bool:+ """Cancel a running execution.++ Args:+ execution_id: Execution to cancel++ Returns:+ True if cancelled successfully+ """+ ctx = self._active_contexts.get(execution_id)+ if ctx:+ ctx.status = WorkflowStatus.CANCELLED+ for node_exec in ctx.node_executions.values():+ if node_exec.status in (TaskStatus.PENDING, TaskStatus.SCHEDULED,+ TaskStatus.RUNNING, TaskStatus.WAITING):+ node_exec.status = TaskStatus.CANCELLED+ await self.cache.save_execution_state(ctx)+ logger.info("Execution cancelled", execution_id=execution_id)+ return True+ return False++ # =========================================================================+ # CONDUCTOR DECIDE PATTERN+ # =========================================================================++ async def _workflow_decide(self, ctx: ExecutionContext,+ enable_caching: bool = True) -> None:+ """Core orchestration loop - Conductor's decide pattern.++ Evaluates current state, finds ready nodes, executes them in parallel,+ then recurses until all nodes complete or error occurs.++ Args:+ ctx: ExecutionContext to process+ enable_caching: Whether to use result caching+ """+ # Distributed lock prevents concurrent decides for same execution+ try:+ async with self.cache.distributed_lock(+ f"execution:{ctx.execution_id}:decide", timeout=60+ ):+ await self._decide_iteration(ctx, enable_caching)+ except TimeoutError:+ logger.warning("Could not acquire decide lock",+ execution_id=ctx.execution_id)+ # Retry after short delay+ await asyncio.sleep(0.5)+ await self._workflow_decide(ctx, enable_caching)++ async def _decide_iteration(self, ctx: ExecutionContext,+ enable_caching: bool) -> None:+ """Continuous scheduling loop - Temporal/Conductor pattern.++ When any node completes, immediately check for newly-ready dependents+ and start them without waiting for entire layer to complete.++ Example: Cron3 (5s) completes -> immediately start WS3,+ even while Cron1 (20s) is still running.+ """+ # Check if cancelled+ if ctx.status == WorkflowStatus.CANCELLED:+ return++ # Find initial ready nodes+ ready_nodes = self._find_ready_nodes(ctx)++ if not ready_nodes:+ if ctx.all_nodes_complete():+ logger.info("All nodes complete", execution_id=ctx.execution_id)+ else:+ pending = ctx.get_pending_nodes()+ if pending:+ logger.warning("Stuck: pending nodes with unsatisfied deps",+ execution_id=ctx.execution_id,+ pending=pending)+ return++ logger.info("Starting continuous execution",+ execution_id=ctx.execution_id,+ initial_batch=len(ready_nodes),+ nodes=[n.node_id for n in ready_nodes])++ # Execute with continuous scheduling - new pattern+ await self._execute_with_continuous_scheduling(ctx, ready_nodes, enable_caching)++ # Save final state+ await self.cache.save_execution_state(ctx)++ # =========================================================================+ # CONTINUOUS SCHEDULING (Temporal/Conductor Pattern)+ # =========================================================================++ async def _execute_with_continuous_scheduling(+ self,+ ctx: ExecutionContext,+ initial_nodes: List[NodeExecution],+ enable_caching: bool+ ) -> None:+ """Execute workflow with continuous scheduling.++ Modern pattern: When any node completes, immediately check for and start+ newly-ready dependent nodes. This enables true parallel pipelines where+ each path progresses independently.++ Uses asyncio.wait(FIRST_COMPLETED) to process completions immediately.++ Args:+ ctx: ExecutionContext+ initial_nodes: Initial batch of ready nodes+ enable_caching: Whether to use result caching+ """+ # Track all running tasks: task -> NodeExecution+ task_to_node: Dict[asyncio.Task, NodeExecution] = {}+ pending_tasks: Set[asyncio.Task] = set()+ workflow_failed = False++ def create_node_task(node: NodeExecution) -> asyncio.Task:+ """Create and track a task for node execution."""+ node.status = TaskStatus.SCHEDULED+ task = asyncio.create_task(+ self._execute_node_with_retry(ctx, node, enable_caching),+ name=f"node_{node.node_id}"+ )+ task_to_node[task] = node+ pending_tasks.add(task)+ return task++ # Start initial nodes+ for node in initial_nodes:+ create_node_task(node)+ await self._notify_status(node.node_id, "scheduled", {})+ logger.info("Scheduled node", node_id=node.node_id)++ # Process completions and schedule new nodes continuously+ while pending_tasks and not workflow_failed:+ if ctx.status == WorkflowStatus.CANCELLED:+ # Cancel all pending tasks+ for task in pending_tasks:+ task.cancel()+ break++ # Wait for ANY task to complete+ done, pending_tasks = await asyncio.wait(+ pending_tasks,+ return_when=asyncio.FIRST_COMPLETED+ )++ # Process each completed task+ for task in done:+ node = task_to_node[task]+ newly_ready = []++ try:+ result = task.result()++ if isinstance(result, Exception):+ node.status = TaskStatus.FAILED+ node.error = str(result)+ node.completed_at = time.time()+ ctx.errors.append({+ "node_id": node.node_id,+ "error": str(result),+ "timestamp": time.time(),+ })+ await self._notify_status(node.node_id, "error", {"error": str(result)})+ logger.error("Node failed", node_id=node.node_id, error=str(result))+ workflow_failed = True++ elif result.get("retries_exhausted"):+ node.status = TaskStatus.FAILED+ node.error = result.get("error", "Unknown error")+ node.completed_at = time.time()+ ctx.errors.append({+ "node_id": node.node_id,+ "error": node.error,+ "retries_exhausted": True,+ "timestamp": time.time(),+ })+ workflow_failed = True++ elif not result.get("success"):+ node.status = TaskStatus.FAILED+ node.error = result.get("error", "Unknown error")+ node.completed_at = time.time()+ ctx.errors.append({+ "node_id": node.node_id,+ "error": node.error,+ "timestamp": time.time(),+ })+ await self._notify_status(node.node_id, "error", {"error": node.error})+ logger.error("Node failed", node_id=node.node_id, error=node.error)+ workflow_failed = True++ else:+ # Success - checkpoint and find newly ready nodes+ ctx.add_checkpoint(node.node_id)+ logger.info("Node completed", node_id=node.node_id)++ # Find nodes that are now ready (their dependencies just completed)+ newly_ready = self._find_ready_nodes(ctx)++ except asyncio.CancelledError:+ node.status = TaskStatus.CANCELLED+ node.completed_at = time.time()+ logger.info("Node cancelled", node_id=node.node_id)++ except Exception as e:+ node.status = TaskStatus.FAILED+ node.error = str(e)+ node.completed_at = time.time()+ ctx.errors.append({+ "node_id": node.node_id,+ "error": str(e),+ "timestamp": time.time(),+ })+ await self._notify_status(node.node_id, "error", {"error": str(e)})+ logger.error("Node exception", node_id=node.node_id, error=str(e))+ workflow_failed = True++ # Schedule newly ready nodes immediately+ if newly_ready and not workflow_failed:+ for ready_node in newly_ready:+ create_node_task(ready_node)+ await self._notify_status(ready_node.node_id, "scheduled", {})+ logger.info("Scheduled dependent node",+ node_id=ready_node.node_id,+ triggered_by=node.node_id)++ # Periodic state save+ await self.cache.save_execution_state(ctx)++ # Handle workflow failure - cancel remaining tasks+ if workflow_failed and pending_tasks:+ logger.info("Workflow failed, cancelling remaining tasks",+ pending_count=len(pending_tasks))++ for task in pending_tasks:+ task.cancel()++ # Wait for cancelled tasks+ if pending_tasks:+ cancelled_done, _ = await asyncio.wait(+ pending_tasks,+ return_when=asyncio.ALL_COMPLETED+ )++ for task in cancelled_done:+ node = task_to_node.get(task)+ if node and node.status not in (TaskStatus.COMPLETED, TaskStatus.FAILED):+ node.status = TaskStatus.CANCELLED+ node.completed_at = time.time()++ ctx.status = WorkflowStatus.FAILED++ # =========================================================================+ # PARALLEL EXECUTION (Legacy - Fork/Join with FIRST_COMPLETED pattern)+ # =========================================================================++ async def _execute_parallel_nodes(self, ctx: ExecutionContext,+ nodes: List[NodeExecution],+ enable_caching: bool) -> None:+ """Execute multiple nodes in parallel using asyncio.wait with FIRST_COMPLETED.++ Uses the standard asyncio pattern for mixed task types:+ - Regular nodes complete quickly+ - Trigger nodes wait indefinitely for external events+ - If a regular node fails, cancel remaining trigger nodes immediately++ This follows Python asyncio best practices:+ https://docs.python.org/3/library/asyncio-task.html#asyncio.wait++ Args:+ ctx: ExecutionContext+ nodes: List of NodeExecution to run in parallel+ enable_caching: Whether to use result caching+ """+ # Mark all as scheduled+ for node in nodes:+ node.status = TaskStatus.SCHEDULED+ await self._notify_status(node.node_id, "scheduled", {})++ # Create named tasks for parallel execution+ # Using dict to track node -> task mapping for proper result handling+ node_to_task: Dict[str, asyncio.Task] = {}+ task_to_node: Dict[asyncio.Task, NodeExecution] = {}++ for node in nodes:+ task = asyncio.create_task(+ self._execute_node_with_retry(ctx, node, enable_caching),+ name=f"node_{node.node_id}"+ )+ node_to_task[node.node_id] = task+ task_to_node[task] = node++ pending: Set[asyncio.Task] = set(node_to_task.values())+ workflow_failed = False++ # Process tasks as they complete using FIRST_COMPLETED pattern+ while pending:+ # Wait for any task to complete+ done, pending = await asyncio.wait(+ pending,+ return_when=asyncio.FIRST_COMPLETED+ )++ # Process completed tasks+ for task in done:+ node = task_to_node[task]++ try:+ result = task.result()++ if isinstance(result, Exception):+ # Task raised exception+ node.status = TaskStatus.FAILED+ node.error = str(result)+ node.completed_at = time.time()+ ctx.errors.append({+ "node_id": node.node_id,+ "error": str(result),+ "timestamp": time.time(),+ })+ await self._notify_status(node.node_id, "error", {"error": str(result)})+ logger.error("Parallel node failed",+ node_id=node.node_id, error=str(result))+ workflow_failed = True++ elif result.get("retries_exhausted"):+ # Node failed after all retries - already in DLQ+ node.status = TaskStatus.FAILED+ node.error = result.get("error", "Unknown error")+ node.completed_at = time.time()+ ctx.errors.append({+ "node_id": node.node_id,+ "error": node.error,+ "retries_exhausted": True,+ "timestamp": time.time(),+ })+ workflow_failed = True++ elif not result.get("success"):+ # Node returned failure without exhausting retries+ node.status = TaskStatus.FAILED+ node.error = result.get("error", "Unknown error")+ node.completed_at = time.time()+ ctx.errors.append({+ "node_id": node.node_id,+ "error": node.error,+ "timestamp": time.time(),+ })+ await self._notify_status(node.node_id, "error", {"error": node.error})+ logger.error("Parallel node failed",+ node_id=node.node_id, error=node.error)+ workflow_failed = True++ except asyncio.CancelledError:+ # Task was cancelled (by us or externally)+ node.status = TaskStatus.CANCELLED+ node.completed_at = time.time()+ logger.info("Parallel node cancelled", node_id=node.node_id)++ except Exception as e:+ # Unexpected exception from task.result()+ node.status = TaskStatus.FAILED+ node.error = str(e)+ node.completed_at = time.time()+ ctx.errors.append({+ "node_id": node.node_id,+ "error": str(e),+ "timestamp": time.time(),+ })+ await self._notify_status(node.node_id, "error", {"error": str(e)})+ logger.error("Parallel node exception",+ node_id=node.node_id, error=str(e))+ workflow_failed = True++ # If workflow failed, cancel remaining pending tasks+ # This prevents trigger nodes from blocking forever when a regular node fails+ if workflow_failed and pending:+ logger.info("Workflow failed, cancelling remaining tasks",+ pending_count=len(pending))++ for task in pending:+ task.cancel()++ # Wait for cancelled tasks to finish+ if pending:+ cancelled_done, _ = await asyncio.wait(+ pending,+ return_when=asyncio.ALL_COMPLETED+ )++ # Mark cancelled nodes+ for task in cancelled_done:+ node = task_to_node[task]+ if node.status not in (TaskStatus.COMPLETED, TaskStatus.FAILED):+ node.status = TaskStatus.CANCELLED+ node.completed_at = time.time()+ logger.info("Cancelled pending node", node_id=node.node_id)++ pending = set() # All done now++ # Mark workflow as failed if any node failed+ if workflow_failed:+ ctx.status = WorkflowStatus.FAILED++ async def _execute_single_node(self, ctx: ExecutionContext,+ node: NodeExecution,+ enable_caching: bool) -> None:+ """Execute a single node with retry logic.++ Args:+ ctx: ExecutionContext+ node: NodeExecution to run+ enable_caching: Whether to use result caching+ """+ node.status = TaskStatus.SCHEDULED+ await self._notify_status(node.node_id, "scheduled", {})++ try:+ result = await self._execute_node_with_retry(ctx, node, enable_caching)++ if result.get("retries_exhausted"):+ # Node failed after all retries - already in DLQ+ node.status = TaskStatus.FAILED+ node.error = result.get("error", "Unknown error")+ node.completed_at = time.time()+ ctx.errors.append({+ "node_id": node.node_id,+ "error": node.error,+ "retries_exhausted": True,+ "timestamp": time.time(),+ })+ ctx.status = WorkflowStatus.FAILED++ except Exception as e:+ node.status = TaskStatus.FAILED+ node.error = str(e)+ node.completed_at = time.time()+ ctx.errors.append({+ "node_id": node.node_id,+ "error": str(e),+ "timestamp": time.time(),+ })+ await self._notify_status(node.node_id, "error", {"error": str(e)})+ ctx.status = WorkflowStatus.FAILED++ # =========================================================================+ # RETRY LOGIC+ # =========================================================================++ async def _execute_node_with_retry(self, ctx: ExecutionContext,+ node: NodeExecution,+ enable_caching: bool) -> Dict[str, Any]:+ """Execute node with retry logic and DLQ on final failure.++ Uses exponential backoff retry policy based on node type.+ On exhausted retries, adds entry to Dead Letter Queue.++ Args:+ ctx: ExecutionContext+ node: NodeExecution to run+ enable_caching: Whether to use result caching++ Returns:+ Execution result+ """+ # Get retry policy for this node type+ node_data = self._get_node_data(ctx, node.node_id)+ custom_policy = node_data.get("parameters", {}).get("retryPolicy")+ retry_policy = get_retry_policy(node.node_type, custom_policy)++ last_error = None+ inputs = self._gather_node_inputs(ctx, node.node_id)++ for attempt in range(retry_policy.max_attempts):+ try:+ node.retry_count = attempt+ result = await self._execute_node_with_caching(ctx, node, enable_caching)++ # Success - return result+ if result.get("success"):+ return result++ # Execution returned failure (not exception)+ error = result.get("error", "Unknown error")+ last_error = error++ # Check if we should retry+ if retry_policy.should_retry(error, attempt + 1):+ delay = retry_policy.calculate_delay(attempt)+ logger.info("Retrying node after failure",+ node_id=node.node_id,+ attempt=attempt + 1,+ max_attempts=retry_policy.max_attempts,+ delay=delay,+ error=error[:100])++ await self._notify_status(node.node_id, "retrying", {+ "attempt": attempt + 1,+ "max_attempts": retry_policy.max_attempts,+ "delay": delay,+ "error": error,+ })++ await asyncio.sleep(delay)++ # Reset node status for retry+ node.status = TaskStatus.PENDING+ node.error = None+ continue+ else:+ # Not retryable, break out+ break++ except asyncio.CancelledError:+ raise # Propagate cancellation+ except Exception as e:+ last_error = str(e)+ logger.warning("Node execution exception",+ node_id=node.node_id,+ attempt=attempt + 1,+ error=last_error)++ # Check if we should retry+ if retry_policy.should_retry(last_error, attempt + 1):+ delay = retry_policy.calculate_delay(attempt)+ logger.info("Retrying node after exception",+ node_id=node.node_id,+ attempt=attempt + 1,+ delay=delay)++ await asyncio.sleep(delay)+ node.status = TaskStatus.PENDING+ node.error = None+ continue+ else:+ break++ # All retries exhausted - add to DLQ (handler is no-op if disabled)+ await self.dlq.add_failed_node(ctx, node, inputs, last_error or "Unknown error")++ # Return failure result+ return {+ "success": False,+ "error": last_error or "Unknown error",+ "retries_exhausted": True,+ "retry_count": node.retry_count,+ }++ # =========================================================================+ # CACHED NODE EXECUTION (Prefect pattern)+ # =========================================================================++ async def _execute_node_with_caching(self, ctx: ExecutionContext,+ node: NodeExecution,+ enable_caching: bool) -> Dict[str, Any]:+ """Execute node with result caching (Prefect pattern).++ Args:+ ctx: ExecutionContext+ node: NodeExecution to run+ enable_caching: Whether to check cache++ Returns:+ Execution result+ """+ # Get node parameters and inputs+ node_data = self._get_node_data(ctx, node.node_id)+ inputs = self._gather_node_inputs(ctx, node.node_id)++ # Check cache first (Prefect pattern)+ if enable_caching:+ cached_result = await self.cache.get_cached_result(+ ctx.execution_id, node.node_id, inputs+ )+ if cached_result:+ logger.info("Cache hit", node_id=node.node_id)+ node.status = TaskStatus.CACHED+ node.output = cached_result+ node.input_hash = hash_inputs(inputs)+ node.completed_at = time.time()+ ctx.outputs[node.node_id] = cached_result+ await self._notify_status(node.node_id, "success",+ {"cached": True, **cached_result})+ await self.cache.add_event(ctx.execution_id, "node_cached", {+ "node_id": node.node_id,+ })+ return cached_result++ # Execute node+ node.status = TaskStatus.RUNNING+ node.started_at = time.time()+ node.input_hash = hash_inputs(inputs)+ await self._notify_status(node.node_id, "executing", {})+ await self.cache.add_event(ctx.execution_id, "node_started", {+ "node_id": node.node_id,+ "node_type": node.node_type,+ })++ # Update heartbeat (for crash detection)+ await self.cache.update_heartbeat(ctx.execution_id, node.node_id)++ # Build execution context for node handler+ # workflow_id is included for per-workflow status scoping (n8n pattern)+ exec_context = {+ "nodes": ctx.nodes,+ "edges": ctx.edges,+ "session_id": ctx.session_id,+ "execution_id": ctx.execution_id,+ "workflow_id": ctx.workflow_id, # For per-workflow status broadcasts+ "start_time": node.started_at,+ "outputs": ctx.outputs, # Previous node outputs+ }++ # Call the actual node executor+ result = await self.node_executor(+ node.node_id,+ node.node_type,+ node_data.get("parameters", {}),+ exec_context+ )++ # Process result+ if result.get("success"):+ node.status = TaskStatus.COMPLETED+ node.output = result.get("result", {})+ node.completed_at = time.time()+ ctx.outputs[node.node_id] = node.output++ # Cache result (Prefect pattern)+ if enable_caching:+ await self.cache.set_cached_result(+ ctx.execution_id, node.node_id, inputs, node.output+ )++ await self._notify_status(node.node_id, "success", node.output)+ await self.cache.add_event(ctx.execution_id, "node_completed", {+ "node_id": node.node_id,+ "execution_time": node.completed_at - node.started_at,+ })+ else:+ node.status = TaskStatus.FAILED+ node.error = result.get("error", "Unknown error")+ node.completed_at = time.time()+ ctx.errors.append({+ "node_id": node.node_id,+ "error": node.error,+ "timestamp": time.time(),+ })++ await self._notify_status(node.node_id, "error", {"error": node.error})+ await self.cache.add_event(ctx.execution_id, "node_failed", {+ "node_id": node.node_id,+ "error": node.error,+ })++ # Mark workflow as failed+ ctx.status = WorkflowStatus.FAILED++ return result++ # =========================================================================+ # DAG ANALYSIS+ # =========================================================================++ def _compute_execution_layers(self, nodes: List[Dict],+ edges: List[Dict]) -> List[List[str]]:+ """Compute execution layers for parallel execution.++ Nodes in the same layer have no dependencies on each other+ and can execute in parallel. Layer 0 contains trigger nodes+ (workflow starting points with no input handles).++ Following n8n pattern: Trigger nodes are the starting point of every+ workflow. They listen for specific events/conditions and initiate+ the execution of the entire workflow.++ Args:+ nodes: List of workflow nodes+ edges: List of edges++ Returns:+ List of layers, where each layer is a list of node IDs+ """+ # Build node type lookup for trigger detection+ node_types: Dict[str, str] = {+ node["id"]: node.get("type", "unknown") for node in nodes+ }++ # Build adjacency and in-degree maps+ in_degree: Dict[str, int] = defaultdict(int)+ adjacency: Dict[str, List[str]] = defaultdict(list)+ node_ids = {node["id"] for node in nodes}++ for edge in edges:+ source = edge.get("source")+ target = edge.get("target")+ if source in node_ids and target in node_ids:+ adjacency[source].append(target)+ in_degree[target] += 1++ # Initialize in-degree for all nodes+ for node_id in node_ids:+ if node_id not in in_degree:+ in_degree[node_id] = 0++ # Kahn's algorithm for topological sort with layers+ layers = []+ remaining = set(node_ids)+ is_first_layer = True++ while remaining:+ # Find all nodes with in-degree 0 (no dependencies)+ layer = [+ node_id for node_id in remaining+ if in_degree[node_id] == 0+ ]++ if not layer:+ # Cycle detected or stuck+ logger.warning("Cycle detected or no start nodes",+ remaining=list(remaining))+ # Add remaining as single layer to avoid infinite loop+ layers.append(list(remaining))+ break++ # For layer 0, validate that starting nodes are trigger nodes+ if is_first_layer:+ trigger_nodes = []+ non_trigger_nodes = []++ for node_id in layer:+ node_type = node_types.get(node_id, "unknown")+ if is_trigger_node(node_type):+ trigger_nodes.append(node_id)+ else:+ non_trigger_nodes.append(node_id)+ logger.warning(+ "Non-trigger node found at graph entry point",+ node_id=node_id,+ node_type=node_type,+ expected_types=list(WORKFLOW_TRIGGER_TYPES)+ )++ # Log trigger node identification+ if trigger_nodes:+ logger.info(+ "Identified trigger nodes as workflow starting points",+ trigger_count=len(trigger_nodes),+ trigger_nodes=[+ f"{nid[:8]}({node_types.get(nid)})"+ for nid in trigger_nodes+ ]+ )++ is_first_layer = False++ layers.append(layer)++ # Remove layer nodes and update in-degrees+ for node_id in layer:+ remaining.remove(node_id)+ for successor in adjacency[node_id]:+ in_degree[successor] -= 1++ logger.debug("Computed execution layers",+ layer_count=len(layers),+ layers=[[n[:8] for n in l] for l in layers])++ return layers++ def _find_ready_nodes(self, ctx: ExecutionContext) -> List[NodeExecution]:+ """Find nodes ready to execute (dependencies satisfied + conditions met).++ A node is ready if:+ - Status is PENDING+ - Not disabled (n8n-style disable feature)+ - All upstream nodes are COMPLETED, CACHED, or SKIPPED+ - Edge conditions (if any) evaluate to True based on upstream outputs++ Supports runtime conditional branching (Prefect-style dynamic workflows).++ Args:+ ctx: ExecutionContext++ Returns:+ List of NodeExecution ready to run+ """+ # Build set of completed nodes+ completed = set(ctx.get_completed_nodes())++ # Build dependency map and track conditional edges+ dependencies: Dict[str, Set[str]] = defaultdict(set)+ conditional_edges: Dict[str, List[Dict]] = defaultdict(list) # target -> edges with conditions++ for edge in ctx.edges:+ target = edge.get("target")+ source = edge.get("source")+ if target and source:+ dependencies[target].add(source)+ # Track edges with conditions for evaluation+ if edge.get("data", {}).get("condition"):+ conditional_edges[target].append(edge)++ # Find ready nodes+ ready = []+ for node_id, node_exec in ctx.node_executions.items():+ if node_exec.status != TaskStatus.PENDING:+ continue++ # Check if all dependencies are satisfied+ deps = dependencies.get(node_id, set())+ if not deps <= completed: # Not all deps completed+ continue++ # Check if node is disabled (n8n-style disable)+ node_data = self._get_node_data(ctx, node_id)+ if node_data.get("data", {}).get("disabled"):+ node_exec.status = TaskStatus.SKIPPED+ node_exec.completed_at = time.time()+ logger.debug("Skipping disabled node", node_id=node_id)+ # Notify status callback about skipped node+ asyncio.create_task(self._notify_status(node_id, "skipped", {"disabled": True}))+ continue++ # Check conditional edges for this node+ if node_id in conditional_edges:+ # Has conditional incoming edges - evaluate them+ conditions_met = self._evaluate_incoming_conditions(+ ctx, node_id, conditional_edges[node_id]+ )+ if not conditions_met:+ # Mark as SKIPPED if conditions not met and all deps done+ node_exec.status = TaskStatus.SKIPPED+ logger.info("Node skipped due to unmet conditions",+ node_id=node_id)+ continue++ ready.append(node_exec)++ return ready++ def _evaluate_incoming_conditions(self, ctx: ExecutionContext, target_node_id: str,+ edges: List[Dict]) -> bool:+ """Evaluate conditions on incoming edges to determine if node should run.++ Args:+ ctx: ExecutionContext+ target_node_id: The node we're checking+ edges: Incoming edges with conditions++ Returns:+ True if at least one conditional edge evaluates to True+ """+ for edge in edges:+ source_id = edge.get("source")+ condition = edge.get("data", {}).get("condition")++ if not condition:+ continue++ # Get output from source node+ source_output = ctx.outputs.get(source_id, {})++ # Evaluate condition+ if evaluate_condition(condition, source_output):+ logger.debug("Conditional edge matched",+ source=source_id,+ target=target_node_id,+ condition=condition)+ return True++ # No conditions matched+ logger.debug("No conditional edges matched",+ target=target_node_id,+ edge_count=len(edges))+ return False++ def _get_node_data(self, ctx: ExecutionContext, node_id: str) -> Dict[str, Any]:+ """Get node data from context.++ Args:+ ctx: ExecutionContext+ node_id: Node ID++ Returns:+ Node data dict+ """+ for node in ctx.nodes:+ if node.get("id") == node_id:+ return node+ return {}++ def _gather_node_inputs(self, ctx: ExecutionContext, node_id: str) -> Dict[str, Any]:+ """Gather inputs for a node from upstream outputs.++ Args:+ ctx: ExecutionContext+ node_id: Target node ID++ Returns:+ Dict of upstream outputs keyed by source node type+ """+ inputs = {}+ for edge in ctx.edges:+ if edge.get("target") == node_id:+ source_id = edge.get("source")+ if source_id in ctx.outputs:+ # Find source node type+ source_node = self._get_node_data(ctx, source_id)+ source_type = source_node.get("type", source_id)+ inputs[source_type] = ctx.outputs[source_id]+ return inputs++ # =========================================================================+ # STATUS NOTIFICATIONS+ # =========================================================================++ async def _notify_status(self, node_id: str, status: str,+ data: Dict[str, Any]) -> None:+ """Send status notification via callback.++ Args:+ node_id: Node ID+ status: Status string+ data: Additional data+ """+ if self.status_callback:+ try:+ await self.status_callback(node_id, status, data)+ except Exception as e:+ logger.warning("Status callback failed", node_id=node_id, error=str(e))++ # =========================================================================+ # RECOVERY+ # =========================================================================++ async def recover_execution(self, execution_id: str,+ nodes: List[Dict],+ edges: List[Dict]) -> Optional[Dict[str, Any]]:+ """Recover and resume an interrupted execution.++ Args:+ execution_id: Execution ID to recover+ nodes: Workflow nodes+ edges: Workflow edges++ Returns:+ Execution result if resumed, None if not found+ """+ ctx = await self.cache.load_execution_state(execution_id, nodes, edges)+ if not ctx:+ logger.warning("Execution not found for recovery", execution_id=execution_id)+ return None++ if ctx.status != WorkflowStatus.RUNNING:+ logger.info("Execution already complete", execution_id=execution_id,+ status=ctx.status.value)+ return {+ "success": ctx.status == WorkflowStatus.COMPLETED,+ "execution_id": execution_id,+ "status": ctx.status.value,+ "recovered": False,+ }++ logger.info("Recovering execution",+ execution_id=execution_id,+ checkpoints=ctx.checkpoints)++ # Reset any RUNNING nodes to PENDING (they were interrupted)+ for node_exec in ctx.node_executions.values():+ if node_exec.status == TaskStatus.RUNNING:+ node_exec.status = TaskStatus.PENDING+ node_exec.started_at = None++ # Track in memory+ self._active_contexts[ctx.execution_id] = ctx++ # Resume decide loop+ try:+ await self._workflow_decide(ctx, enable_caching=True)++ if ctx.all_nodes_complete():+ ctx.status = WorkflowStatus.COMPLETED+ elif ctx.errors:+ ctx.status = WorkflowStatus.FAILED++ ctx.completed_at = time.time()+ await self.cache.save_execution_state(ctx)++ return {+ "success": ctx.status == WorkflowStatus.COMPLETED,+ "execution_id": ctx.execution_id,+ "status": ctx.status.value,+ "recovered": True,+ "outputs": ctx.outputs,+ }++ finally:+ self._active_contexts.pop(ctx.execution_id, None)++ async def get_active_executions(self) -> List[str]:+ """Get list of active execution IDs.++ Returns:+ List of execution IDs currently running+ """+ return list(self._active_contexts.keys())++ # =========================================================================+ # DLQ REPLAY+ # =========================================================================++ async def replay_dlq_entry(self, entry_id: str,+ nodes: List[Dict],+ edges: List[Dict]) -> Dict[str, Any]:+ """Replay a failed node from the Dead Letter Queue.++ Creates a new execution context and attempts to re-execute the failed node.++ Args:+ entry_id: DLQ entry ID to replay+ nodes: Workflow nodes+ edges: Workflow edges++ Returns:+ Execution result dict+ """+ # Get DLQ entry+ entry = await self.cache.get_dlq_entry(entry_id)+ if not entry:+ return {+ "success": False,+ "error": f"DLQ entry not found: {entry_id}",+ }++ logger.info("Replaying DLQ entry",+ entry_id=entry_id,+ node_id=entry.node_id,+ node_type=entry.node_type,+ original_execution=entry.execution_id)++ # Create new execution context for replay+ ctx = ExecutionContext.create(+ workflow_id=entry.workflow_id,+ session_id="dlq_replay",+ nodes=nodes,+ edges=edges,+ )++ # Get the node execution+ node_exec = ctx.node_executions.get(entry.node_id)+ if not node_exec:+ return {+ "success": False,+ "error": f"Node not found in workflow: {entry.node_id}",+ }++ # Set up context with stored inputs+ ctx.outputs = entry.inputs # Restore input state++ ctx.status = WorkflowStatus.RUNNING+ ctx.started_at = time.time()+ self._active_contexts[ctx.execution_id] = ctx++ try:+ # Execute the single node with retry+ await self._execute_single_node(ctx, node_exec, enable_caching=False)++ if node_exec.status == TaskStatus.COMPLETED:+ # Success - remove from DLQ+ await self.cache.remove_from_dlq(entry_id)+ logger.info("DLQ replay succeeded",+ entry_id=entry_id,+ node_id=entry.node_id)++ return {+ "success": True,+ "execution_id": ctx.execution_id,+ "node_id": entry.node_id,+ "result": node_exec.output,+ "removed_from_dlq": True,+ }+ else:+ # Still failing - update DLQ entry+ await self.cache.update_dlq_entry(+ entry_id,+ entry.retry_count + 1,+ node_exec.error or "Unknown error"+ )++ return {+ "success": False,+ "execution_id": ctx.execution_id,+ "node_id": entry.node_id,+ "error": node_exec.error,+ "retry_count": entry.retry_count + 1,+ }++ finally:+ self._active_contexts.pop(ctx.execution_id, None)diff --git a/server/services/execution/models.py b/server/services/execution/models.pynew file mode 100644index 00000000..cb6a77c1--- /dev/null+++ b/server/services/execution/models.py@@ -0,0 +1,491 @@+"""Execution engine state models.++Based on Netflix Conductor task lifecycle and Prefect 3.0 patterns.+All models are JSON-serializable for Redis persistence and cross-runtime portability.+"""++import hashlib+import json+import time+import uuid+from dataclasses import dataclass, field, asdict+from datetime import datetime+from enum import Enum+from typing import Dict, Any, List, Optional+++class TaskStatus(str, Enum):+ """Task execution states (Conductor-style lifecycle).++ State transitions:+ PENDING -> SCHEDULED -> RUNNING -> COMPLETED+ -> FAILED+ -> CANCELLED+ CACHED (Prefect pattern - result from cache, no execution)+ """+ PENDING = "pending" # Created, not yet scheduled+ SCHEDULED = "scheduled" # In task queue, waiting for worker+ RUNNING = "running" # Worker executing+ COMPLETED = "completed" # Success, result cached+ FAILED = "failed" # Error, may retry+ CACHED = "cached" # Result from cache (Prefect pattern)+ CANCELLED = "cancelled" # User cancelled+ WAITING = "waiting" # Waiting for external event (triggers)+ SKIPPED = "skipped" # Skipped due to condition+++class WorkflowStatus(str, Enum):+ """Workflow execution states."""+ PENDING = "pending" # Created, not started+ RUNNING = "running" # At least one node executing+ PAUSED = "paused" # User paused+ COMPLETED = "completed" # All nodes completed successfully+ FAILED = "failed" # Execution failed+ CANCELLED = "cancelled" # User cancelled+++@dataclass+class RetryPolicy:+ """Retry configuration for node execution.++ Implements exponential backoff with configurable limits.+ Delay formula: min(initial_delay * (backoff_multiplier ^ attempt), max_delay)+ """+ max_attempts: int = 3+ initial_delay: float = 1.0 # seconds+ max_delay: float = 60.0 # seconds+ backoff_multiplier: float = 2.0+ retry_on_timeout: bool = True+ retry_on_connection_error: bool = True+ retry_on_server_error: bool = True # 5xx errors++ def calculate_delay(self, attempt: int) -> float:+ """Calculate delay before next retry attempt.++ Args:+ attempt: Current attempt number (0-indexed)++ Returns:+ Delay in seconds before next attempt+ """+ delay = self.initial_delay * (self.backoff_multiplier ** attempt)+ return min(delay, self.max_delay)++ def should_retry(self, error: str, attempt: int) -> bool:+ """Determine if execution should be retried.++ Args:+ error: Error message from failed execution+ attempt: Current attempt number (0-indexed)++ Returns:+ True if should retry, False otherwise+ """+ if attempt >= self.max_attempts:+ return False++ error_lower = error.lower()++ if self.retry_on_timeout and "timeout" in error_lower:+ return True+ if self.retry_on_connection_error and ("connection" in error_lower or "connect" in error_lower):+ return True+ if self.retry_on_server_error and ("500" in error or "502" in error or "503" in error or "504" in error):+ return True++ return False++ def to_dict(self) -> Dict[str, Any]:+ """Convert to JSON-serializable dict."""+ return {+ "max_attempts": self.max_attempts,+ "initial_delay": self.initial_delay,+ "max_delay": self.max_delay,+ "backoff_multiplier": self.backoff_multiplier,+ "retry_on_timeout": self.retry_on_timeout,+ "retry_on_connection_error": self.retry_on_connection_error,+ "retry_on_server_error": self.retry_on_server_error,+ }++ @classmethod+ def from_dict(cls, data: Dict[str, Any]) -> "RetryPolicy":+ """Create from dict."""+ return cls(+ max_attempts=data.get("max_attempts", 3),+ initial_delay=data.get("initial_delay", 1.0),+ max_delay=data.get("max_delay", 60.0),+ backoff_multiplier=data.get("backoff_multiplier", 2.0),+ retry_on_timeout=data.get("retry_on_timeout", True),+ retry_on_connection_error=data.get("retry_on_connection_error", True),+ retry_on_server_error=data.get("retry_on_server_error", True),+ )+++# Default retry policies for different node types+DEFAULT_RETRY_POLICIES: Dict[str, RetryPolicy] = {+ "httpRequest": RetryPolicy(max_attempts=3, initial_delay=2.0),+ "webhookTrigger": RetryPolicy(max_attempts=1), # Don't retry triggers+ "whatsappReceive": RetryPolicy(max_attempts=1), # Don't retry triggers+ "aiAgent": RetryPolicy(max_attempts=2, initial_delay=5.0, max_delay=30.0),+ "openaiChatModel": RetryPolicy(max_attempts=2, initial_delay=5.0),+ "anthropicChatModel": RetryPolicy(max_attempts=2, initial_delay=5.0),+ "googleChatModel": RetryPolicy(max_attempts=2, initial_delay=5.0),+}+++def get_retry_policy(node_type: str, custom_policy: Dict = None) -> RetryPolicy:+ """Get retry policy for a node type.++ Args:+ node_type: The node type string+ custom_policy: Optional custom policy dict from node parameters++ Returns:+ RetryPolicy instance+ """+ if custom_policy:+ return RetryPolicy.from_dict(custom_policy)+ return DEFAULT_RETRY_POLICIES.get(node_type, RetryPolicy())+++@dataclass+class DLQEntry:+ """Dead Letter Queue entry for failed node executions.++ Stores failed execution details for manual review and replay.+ """+ id: str+ execution_id: str+ workflow_id: str+ node_id: str+ node_type: str+ error: str+ inputs: Dict[str, Any]+ retry_count: int+ created_at: float = field(default_factory=time.time)+ last_error_at: float = field(default_factory=time.time)++ def to_dict(self) -> Dict[str, Any]:+ """Convert to JSON-serializable dict."""+ return {+ "id": self.id,+ "execution_id": self.execution_id,+ "workflow_id": self.workflow_id,+ "node_id": self.node_id,+ "node_type": self.node_type,+ "error": self.error,+ "inputs": self.inputs,+ "retry_count": self.retry_count,+ "created_at": self.created_at,+ "last_error_at": self.last_error_at,+ }++ @classmethod+ def from_dict(cls, data: Dict[str, Any]) -> "DLQEntry":+ """Create from dict."""+ return cls(+ id=data["id"],+ execution_id=data["execution_id"],+ workflow_id=data["workflow_id"],+ node_id=data["node_id"],+ node_type=data["node_type"],+ error=data["error"],+ inputs=data.get("inputs", {}),+ retry_count=data.get("retry_count", 0),+ created_at=data.get("created_at", time.time()),+ last_error_at=data.get("last_error_at", time.time()),+ )++ @classmethod+ def create(cls, ctx: "ExecutionContext", node_exec: "NodeExecution",+ inputs: Dict[str, Any]) -> "DLQEntry":+ """Factory method to create DLQ entry from failed execution."""+ return cls(+ id=str(uuid.uuid4()),+ execution_id=ctx.execution_id,+ workflow_id=ctx.workflow_id,+ node_id=node_exec.node_id,+ node_type=node_exec.node_type,+ error=node_exec.error or "Unknown error",+ inputs=inputs,+ retry_count=node_exec.retry_count,+ )+++@dataclass+class NodeExecution:+ """Tracks execution state for a single node.++ Prefect-style: includes input hash for cache lookup.+ """+ node_id: str+ node_type: str+ status: TaskStatus = TaskStatus.PENDING+ input_hash: Optional[str] = None # For cache lookup+ output: Optional[Dict[str, Any]] = None+ error: Optional[str] = None+ started_at: Optional[float] = None+ completed_at: Optional[float] = None+ retry_count: int = 0++ def to_dict(self) -> Dict[str, Any]:+ """Convert to JSON-serializable dict."""+ return {+ "node_id": self.node_id,+ "node_type": self.node_type,+ "status": self.status.value,+ "input_hash": self.input_hash,+ "output": self.output,+ "error": self.error,+ "started_at": self.started_at,+ "completed_at": self.completed_at,+ "retry_count": self.retry_count,+ }++ @classmethod+ def from_dict(cls, data: Dict[str, Any]) -> "NodeExecution":+ """Create from dict (Redis deserialization)."""+ return cls(+ node_id=data["node_id"],+ node_type=data["node_type"],+ status=TaskStatus(data["status"]),+ input_hash=data.get("input_hash"),+ output=data.get("output"),+ error=data.get("error"),+ started_at=data.get("started_at"),+ completed_at=data.get("completed_at"),+ retry_count=data.get("retry_count", 0),+ )+++@dataclass+class ExecutionContext:+ """Isolated execution context for a workflow run.++ Replaces global _deployment_running flag.+ Each workflow execution gets its own context with isolated state.++ Conductor pattern: workflow_id identifies the workflow definition,+ execution_id identifies this specific run.+ """+ execution_id: str+ workflow_id: str+ status: WorkflowStatus = WorkflowStatus.PENDING+ session_id: str = "default"++ # Node states and outputs+ node_executions: Dict[str, NodeExecution] = field(default_factory=dict)+ outputs: Dict[str, Any] = field(default_factory=dict)++ # DAG structure (cached for parallel batch detection)+ nodes: List[Dict[str, Any]] = field(default_factory=list)+ edges: List[Dict[str, Any]] = field(default_factory=list)++ # Execution tracking+ execution_order: List[str] = field(default_factory=list)+ current_layer: int = 0+ checkpoints: List[str] = field(default_factory=list)++ # Timing+ created_at: float = field(default_factory=time.time)+ updated_at: float = field(default_factory=time.time)+ started_at: Optional[float] = None+ completed_at: Optional[float] = None++ # Error tracking+ errors: List[Dict[str, Any]] = field(default_factory=list)++ @classmethod+ def create(cls, workflow_id: str, session_id: str = "default",+ nodes: List[Dict] = None, edges: List[Dict] = None) -> "ExecutionContext":+ """Factory method to create new execution context.++ Supports pre-executed nodes (marked with _pre_executed=True) for+ event-driven execution where trigger nodes are already complete.+ """+ execution_id = str(uuid.uuid4())+ ctx = cls(+ execution_id=execution_id,+ workflow_id=workflow_id,+ session_id=session_id,+ nodes=nodes or [],+ edges=edges or [],+ )++ # Initialize node executions for all nodes+ for node in (nodes or []):+ node_id = node.get("id")+ node_type = node.get("type", "unknown")++ # Check if node is pre-executed (e.g., trigger that already fired)+ if node.get("_pre_executed"):+ # Mark as COMPLETED with trigger output+ trigger_output = node.get("_trigger_output", {})+ node_exec = NodeExecution(+ node_id=node_id,+ node_type=node_type,+ status=TaskStatus.COMPLETED,+ output=trigger_output,+ completed_at=time.time(),+ )+ ctx.outputs[node_id] = trigger_output+ ctx.checkpoints.append(node_id)+ else:+ node_exec = NodeExecution(+ node_id=node_id,+ node_type=node_type,+ )++ ctx.node_executions[node_id] = node_exec++ return ctx++ def get_node_status(self, node_id: str) -> Optional[TaskStatus]:+ """Get status for a specific node."""+ node_exec = self.node_executions.get(node_id)+ return node_exec.status if node_exec else None++ def set_node_status(self, node_id: str, status: TaskStatus,+ output: Dict = None, error: str = None) -> None:+ """Update node execution status."""+ if node_id not in self.node_executions:+ return++ node_exec = self.node_executions[node_id]+ node_exec.status = status+ self.updated_at = time.time()++ if status == TaskStatus.RUNNING:+ node_exec.started_at = time.time()+ elif status in (TaskStatus.COMPLETED, TaskStatus.CACHED):+ node_exec.completed_at = time.time()+ if output:+ node_exec.output = output+ self.outputs[node_id] = output+ elif status == TaskStatus.SKIPPED:+ # Skipped due to conditional branching - mark as completed but no output+ node_exec.completed_at = time.time()+ elif status == TaskStatus.FAILED:+ node_exec.completed_at = time.time()+ if error:+ node_exec.error = error+ self.errors.append({+ "node_id": node_id,+ "error": error,+ "timestamp": time.time()+ })++ def add_checkpoint(self, node_id: str) -> None:+ """Add checkpoint after node completion (for recovery)."""+ self.checkpoints.append(node_id)+ self.updated_at = time.time()++ def get_completed_nodes(self) -> List[str]:+ """Get list of completed node IDs."""+ return [+ node_id for node_id, node_exec in self.node_executions.items()+ if node_exec.status in (TaskStatus.COMPLETED, TaskStatus.CACHED, TaskStatus.SKIPPED)+ ]++ def get_pending_nodes(self) -> List[str]:+ """Get list of pending node IDs."""+ return [+ node_id for node_id, node_exec in self.node_executions.items()+ if node_exec.status == TaskStatus.PENDING+ ]++ def all_nodes_complete(self) -> bool:+ """Check if all nodes are complete."""+ for node_exec in self.node_executions.values():+ if node_exec.status not in (TaskStatus.COMPLETED, TaskStatus.CACHED,+ TaskStatus.SKIPPED, TaskStatus.CANCELLED):+ return False+ return True++ def to_dict(self) -> Dict[str, Any]:+ """Convert to JSON-serializable dict for Redis storage."""+ return {+ "execution_id": self.execution_id,+ "workflow_id": self.workflow_id,+ "status": self.status.value,+ "session_id": self.session_id,+ "node_executions": {+ k: v.to_dict() for k, v in self.node_executions.items()+ },+ "outputs": self.outputs,+ "execution_order": self.execution_order,+ "current_layer": self.current_layer,+ "checkpoints": self.checkpoints,+ "created_at": self.created_at,+ "updated_at": self.updated_at,+ "started_at": self.started_at,+ "completed_at": self.completed_at,+ "errors": self.errors,+ # Don't store full nodes/edges - too large+ "node_count": len(self.nodes),+ "edge_count": len(self.edges),+ }++ @classmethod+ def from_dict(cls, data: Dict[str, Any], nodes: List[Dict] = None,+ edges: List[Dict] = None) -> "ExecutionContext":+ """Create from dict (Redis deserialization)."""+ ctx = cls(+ execution_id=data["execution_id"],+ workflow_id=data["workflow_id"],+ status=WorkflowStatus(data["status"]),+ session_id=data.get("session_id", "default"),+ nodes=nodes or [],+ edges=edges or [],+ execution_order=data.get("execution_order", []),+ current_layer=data.get("current_layer", 0),+ checkpoints=data.get("checkpoints", []),+ created_at=data.get("created_at", time.time()),+ updated_at=data.get("updated_at", time.time()),+ started_at=data.get("started_at"),+ completed_at=data.get("completed_at"),+ errors=data.get("errors", []),+ )++ # Restore node executions+ for node_id, node_data in data.get("node_executions", {}).items():+ ctx.node_executions[node_id] = NodeExecution.from_dict(node_data)++ # Restore outputs+ ctx.outputs = data.get("outputs", {})++ return ctx++ def to_json(self) -> str:+ """Serialize to JSON string."""+ return json.dumps(self.to_dict())++ @classmethod+ def from_json(cls, json_str: str, nodes: List[Dict] = None,+ edges: List[Dict] = None) -> "ExecutionContext":+ """Deserialize from JSON string."""+ data = json.loads(json_str)+ return cls.from_dict(data, nodes, edges)+++def hash_inputs(inputs: Dict[str, Any]) -> str:+ """Generate deterministic hash of inputs for cache key (Prefect pattern).++ Args:+ inputs: Dictionary of input parameters++ Returns:+ SHA256 hash of canonicalized inputs+ """+ # Canonical JSON (sorted keys, no extra whitespace)+ canonical = json.dumps(inputs, sort_keys=True, separators=(",", ":"))+ return hashlib.sha256(canonical.encode()).hexdigest()[:16]+++def generate_cache_key(execution_id: str, node_id: str, inputs: Dict[str, Any]) -> str:+ """Generate cache key for node result (Prefect pattern).++ Format: result:{execution_id}:{node_id}:{input_hash}+ """+ input_hash = hash_inputs(inputs)+ return f"result:{execution_id}:{node_id}:{input_hash}"diff --git a/server/services/execution/recovery.py b/server/services/execution/recovery.pynew file mode 100644index 00000000..e26a2369--- /dev/null+++ b/server/services/execution/recovery.py@@ -0,0 +1,235 @@+"""Recovery sweeper for crash recovery.++Runs as background task to:+- Detect abandoned executions (running but no heartbeat)+- Resume interrupted workflows+- Clean up stale data+"""++import asyncio+import time+from typing import Dict, Any, List, Optional, Callable, Awaitable++from core.logging import get_logger+from .models import TaskStatus, WorkflowStatus+from .cache import ExecutionCache++logger = get_logger(__name__)+++class RecoverySweeper:+ """Background task that recovers abandoned workflow executions.++ Conductor's sweeper pattern:+ - Periodically scans for stuck executions+ - Detects nodes with stale heartbeats+ - Resets stuck nodes to PENDING for retry+ - Triggers workflow_decide to resume+ """++ def __init__(self, cache: ExecutionCache,+ heartbeat_timeout: int = 300, # 5 minutes+ sweep_interval: int = 60, # 1 minute+ max_retries: int = 3):+ """Initialize recovery sweeper.++ Args:+ cache: ExecutionCache for Redis access+ heartbeat_timeout: Seconds before node is considered stuck+ sweep_interval: Seconds between sweep runs+ max_retries: Max retry attempts per node+ """+ self.cache = cache+ self.heartbeat_timeout = heartbeat_timeout+ self.sweep_interval = sweep_interval+ self.max_retries = max_retries+ self._running = False+ self._task: Optional[asyncio.Task] = None++ # Recovery callbacks (set by workflow service)+ self._on_recovery: Optional[Callable[[str], Awaitable[None]]] = None++ def set_recovery_callback(self, callback: Callable[[str], Awaitable[None]]) -> None:+ """Set callback to invoke when execution needs recovery.++ Args:+ callback: Async function that takes execution_id+ """+ self._on_recovery = callback++ async def start(self) -> None:+ """Start the recovery sweeper background task."""+ if self._running:+ logger.warning("Recovery sweeper already running")+ return++ self._running = True+ self._task = asyncio.create_task(self._sweep_loop())+ logger.info("Recovery sweeper started",+ heartbeat_timeout=self.heartbeat_timeout,+ sweep_interval=self.sweep_interval)++ async def stop(self) -> None:+ """Stop the recovery sweeper."""+ self._running = False+ if self._task:+ self._task.cancel()+ try:+ await self._task+ except asyncio.CancelledError:+ pass+ logger.info("Recovery sweeper stopped")++ async def _sweep_loop(self) -> None:+ """Main sweep loop - runs continuously."""+ while self._running:+ try:+ await self._sweep_once()+ except Exception as e:+ logger.error("Sweep iteration failed", error=str(e))++ # Wait before next sweep+ await asyncio.sleep(self.sweep_interval)++ async def _sweep_once(self) -> None:+ """Single sweep iteration - check all active executions."""+ # Get all active executions+ active_ids = await self.cache.get_active_executions()++ if not active_ids:+ return++ logger.debug("Sweeping active executions", count=len(active_ids))++ for execution_id in active_ids:+ try:+ await self._check_execution(execution_id)+ except Exception as e:+ logger.error("Failed to check execution",+ execution_id=execution_id, error=str(e))++ async def _check_execution(self, execution_id: str) -> None:+ """Check single execution for stuck nodes.++ Args:+ execution_id: Execution to check+ """+ # Load execution state+ ctx = await self.cache.load_execution_state(execution_id)+ if not ctx:+ # Execution not found - remove from active set+ logger.warning("Orphan execution in active set",+ execution_id=execution_id)+ if self.cache.cache.is_redis_available():+ await self.cache.cache.redis.srem("executions:active", execution_id)+ return++ # Check if already complete+ if ctx.status in (WorkflowStatus.COMPLETED, WorkflowStatus.FAILED,+ WorkflowStatus.CANCELLED):+ # Should not be in active set+ if self.cache.cache.is_redis_available():+ await self.cache.cache.redis.srem("executions:active", execution_id)+ return++ # Check for stuck nodes+ needs_recovery = False+ current_time = time.time()++ for node_id, node_exec in ctx.node_executions.items():+ if node_exec.status == TaskStatus.RUNNING:+ # Check heartbeat+ last_heartbeat = await self.cache.get_heartbeat(execution_id, node_id)++ if last_heartbeat is None:+ # No heartbeat - node is stuck+ stuck_duration = current_time - (node_exec.started_at or current_time)+ if stuck_duration > self.heartbeat_timeout:+ logger.warning("Node stuck (no heartbeat)",+ execution_id=execution_id,+ node_id=node_id,+ stuck_seconds=stuck_duration)+ needs_recovery = True++ elif current_time - last_heartbeat > self.heartbeat_timeout:+ # Heartbeat too old+ logger.warning("Node stuck (stale heartbeat)",+ execution_id=execution_id,+ node_id=node_id,+ heartbeat_age=current_time - last_heartbeat)+ needs_recovery = True++ if needs_recovery and self._on_recovery:+ logger.info("Triggering recovery", execution_id=execution_id)+ try:+ await self._on_recovery(execution_id)+ except Exception as e:+ logger.error("Recovery callback failed",+ execution_id=execution_id, error=str(e))++ async def scan_on_startup(self) -> List[str]:+ """Scan for executions that need recovery on server startup.++ Returns:+ List of execution IDs that need recovery+ """+ needs_recovery = []++ # Get all active executions+ active_ids = await self.cache.get_active_executions()++ logger.info("Startup scan for incomplete executions",+ active_count=len(active_ids))++ for execution_id in active_ids:+ ctx = await self.cache.load_execution_state(execution_id)+ if not ctx:+ continue++ # Check if execution was interrupted+ if ctx.status == WorkflowStatus.RUNNING:+ # Check how long it's been stuck+ if ctx.updated_at:+ age = time.time() - ctx.updated_at+ if age > self.heartbeat_timeout:+ logger.info("Found interrupted execution",+ execution_id=execution_id,+ age_seconds=age)+ needs_recovery.append(execution_id)++ return needs_recovery++ async def cleanup_old_executions(self, max_age_hours: int = 24) -> int:+ """Clean up completed executions older than max_age.++ Args:+ max_age_hours: Maximum age in hours++ Returns:+ Number of executions cleaned up+ """+ cleaned = 0+ max_age_seconds = max_age_hours * 3600+ current_time = time.time()++ # This would need a scan of all execution keys+ # For now, we rely on Redis TTL for cleanup+ logger.info("Cleanup skipped - using Redis TTL",+ max_age_hours=max_age_hours)++ return cleaned+++# Global sweeper instance (initialized by main.py)+_sweeper: Optional[RecoverySweeper] = None+++def get_recovery_sweeper() -> Optional[RecoverySweeper]:+ """Get global recovery sweeper instance."""+ return _sweeper+++def set_recovery_sweeper(sweeper: RecoverySweeper) -> None:+ """Set global recovery sweeper instance."""+ global _sweeper+ _sweeper = sweeperdiff --git a/server/services/handlers/__init__.py b/server/services/handlers/__init__.pynew file mode 100644index 00000000..60858f0f--- /dev/null+++ b/server/services/handlers/__init__.py@@ -0,0 +1,93 @@+"""Node handlers package - extracted from workflow.py for maintainability.++This package contains all node execution handlers organized by category:+- ai.py: AI Agent, AI Chat Model, Simple Memory+- android.py: Android Device Setup, Android Services+- code.py: Python Executor, JavaScript Executor+- http.py: HTTP Request, Webhook Response+- triggers.py: Generic trigger node handler+- utility.py: Maps, Text, Chat, Cron, Start+- whatsapp.py: WhatsApp Send, WhatsApp Connect+"""++# AI handlers+from .ai import (+ handle_ai_agent,+ handle_ai_chat_model,+ handle_simple_memory,+)++# Android handlers+from .android import (+ handle_android_device_setup,+ handle_android_service,+)++# Code execution handlers+from .code import (+ handle_python_executor,+ handle_javascript_executor,+)++# HTTP handlers+from .http import (+ handle_http_request,+ handle_webhook_response,+)++# Trigger handlers+from .triggers import (+ handle_trigger_node,+)++# Utility handlers+from .utility import (+ handle_create_map,+ handle_add_locations,+ handle_nearby_places,+ handle_text_generator,+ handle_file_handler,+ handle_chat_send,+ handle_chat_history,+ handle_start,+ handle_cron_scheduler,+ handle_timer,+)++# WhatsApp handlers+from .whatsapp import (+ handle_whatsapp_send,+ handle_whatsapp_connect,+)++__all__ = [+ # AI+ 'handle_ai_agent',+ 'handle_ai_chat_model',+ 'handle_simple_memory',+ # Android+ 'handle_android_device_setup',+ 'handle_android_service',+ # Code+ 'handle_python_executor',+ 'handle_javascript_executor',+ # HTTP+ 'handle_http_request',+ 'handle_webhook_response',+ # Triggers+ 'handle_trigger_node',+ # Utility+ 'handle_create_map',+ 'handle_add_locations',+ 'handle_nearby_places',+ 'handle_text_generator',+ 'handle_file_handler',+ 'handle_chat_send',+ 'handle_chat_history',+ 'handle_start',+ 'handle_cron_scheduler',+ 'handle_timer',+ 'handle_whatsapp_send',+ 'handle_whatsapp_connect',+]diff --git a/server/services/handlers/ai.py b/server/services/handlers/ai.pynew file mode 100644index 00000000..1a9fb1ad--- /dev/null+++ b/server/services/handlers/ai.py@@ -0,0 +1,126 @@+"""AI node handlers - AI Agent, AI Chat Model, Simple Memory."""++from typing import Dict, Any, TYPE_CHECKING+from core.logging import get_logger++if TYPE_CHECKING:+ from services.ai import AIService+ from core.database import Database++logger = get_logger(__name__)+++async def handle_ai_agent(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any],+ ai_service: "AIService",+ database: "Database"+) -> Dict[str, Any]:+ """Handle AI agent node execution with memory support.++ Args:+ node_id: The node ID+ node_type: The node type (aiAgent)+ parameters: Resolved parameters+ context: Execution context with nodes, edges, session_id, start_time, execution_id+ ai_service: The AI service instance+ database: The database instance++ Returns:+ Execution result dict+ """+ nodes = context.get('nodes')+ edges = context.get('edges')+ execution_id = context.get('execution_id', 'unknown')+ memory_data = None++ if edges and nodes:+ for edge in edges:+ if edge.get('target') == node_id and edge.get('targetHandle') == 'input-memory':+ memory_node_id = edge.get('source')+ memory_node = next((n for n in nodes if n.get('id') == memory_node_id), None)+ if memory_node and memory_node.get('type') == 'simpleMemory':+ memory_params = await database.get_node_parameters(memory_node_id) or {}+ memory_session_id = memory_params.get('sessionId', 'default')+ memory_type = memory_params.get('memoryType', 'buffer')+ window_size = int(memory_params.get('windowSize', 10)) if memory_type == 'window' else None+ memory_data = {+ 'session_id': memory_session_id,+ 'memory_type': memory_type,+ 'window_size': window_size+ }+ logger.info("AI Agent connected memory node", node_id=node_id, execution_id=execution_id,+ memory_session=memory_session_id, memory_type=memory_type)+ break++ # Get broadcaster for real-time status updates+ from services.status_broadcaster import get_status_broadcaster+ broadcaster = get_status_broadcaster()++ return await ai_service.execute_agent(node_id, parameters, memory_data, broadcaster)+++async def handle_ai_chat_model(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any],+ ai_service: "AIService"+) -> Dict[str, Any]:+ """Handle AI chat model node execution.++ Args:+ node_id: The node ID+ node_type: The node type (openaiChatModel, anthropicChatModel, etc.)+ parameters: Resolved parameters+ context: Execution context+ ai_service: The AI service instance++ Returns:+ Execution result dict+ """+ return await ai_service.execute_chat(node_id, node_type, parameters)+++async def handle_simple_memory(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any]+) -> Dict[str, Any]:+ """Handle simple memory node execution.++ Args:+ node_id: The node ID+ node_type: The node type (simpleMemory)+ parameters: Resolved parameters+ context: Execution context++ Returns:+ Execution result dict with session info and messages+ """+ from services.memory_store import get_messages, clear_session++ session_id = parameters.get('sessionId', 'default')+ memory_type = parameters.get('memoryType', 'buffer')+ window_size = int(parameters.get('windowSize', 10)) if memory_type == 'window' else None+ clear_on_run = parameters.get('clearOnRun', False)++ if clear_on_run:+ cleared = clear_session(session_id)+ logger.info(f"[Memory] Cleared {cleared} messages from session '{session_id}'")++ messages = get_messages(session_id, window_size)++ return {+ "success": True,+ "result": {+ "session_id": session_id,+ "messages": messages,+ "message_count": len(messages),+ "memory_type": memory_type,+ "window_size": window_size+ }+ }diff --git a/server/services/handlers/android.py b/server/services/handlers/android.pynew file mode 100644index 00000000..86c5c294--- /dev/null+++ b/server/services/handlers/android.py@@ -0,0 +1,264 @@+"""Android node handlers - Device Setup and Android Services."""++import json+import time+from datetime import datetime+from typing import Dict, Any, TYPE_CHECKING+from core.logging import get_logger+from constants import ANDROID_SERVICE_NODE_TYPES++if TYPE_CHECKING:+ from services.android_service import AndroidService+ from core.config import Settings++logger = get_logger(__name__)+++async def handle_android_device_setup(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any],+ settings: "Settings"+) -> Dict[str, Any]:+ """Handle Android device setup node execution.++ Supports two connection types:+ - local: ADB connection with port forwarding+ - remote: WebSocket connection to remote proxy++ Args:+ node_id: The node ID+ node_type: The node type (androidDeviceSetup)+ parameters: Resolved parameters+ context: Execution context with start_time+ settings: Application settings++ Returns:+ Execution result dict with connection info+ """+ start_time = context.get('start_time', time.time())+ connection_type = parameters.get('connection_type', 'local')+ device_id = parameters.get('device_id', '')+ websocket_url = parameters.get('websocket_url', settings.websocket_url)+ port = parameters.get('port', 8888)+ auto_forward = parameters.get('auto_forward', True)++ logger.info("[Android Device Setup] Executing", node_id=node_id, connection_type=connection_type,+ device_id=device_id, websocket_url=websocket_url, port=port, auto_forward=auto_forward)++ if connection_type == 'local' and auto_forward and device_id:+ # Local ADB connection with port forwarding+ import subprocess+ try:+ cmd = ["adb", "-s", device_id, "forward", f"tcp:{port}", f"tcp:{port}"]+ subprocess_result = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5)++ if subprocess_result.returncode == 0:+ connection_info = {+ "connection_type": "local",+ "device_id": device_id,+ "port": port,+ "port_forwarding": "active",+ "local_endpoint": f"http://localhost:{port}",+ "message": f"Port forwarding setup: localhost:{port} -> device:{port}",+ "timestamp": datetime.now().isoformat()+ }+ return {+ "success": True,+ "node_id": node_id,+ "node_type": node_type,+ "result": connection_info,+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+ else:+ error_msg = subprocess_result.stderr.strip() or subprocess_result.stdout.strip()+ return {+ "success": False,+ "node_id": node_id,+ "node_type": node_type,+ "error": f"Port forwarding failed: {error_msg}",+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+ except Exception as e:+ return {+ "success": False,+ "node_id": node_id,+ "node_type": node_type,+ "error": f"Port forwarding error: {str(e)}",+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ elif connection_type == 'remote' and websocket_url:+ # Remote WebSocket connection via Android Services Relay+ try:+ from services.android import get_relay_client++ api_key = settings.websocket_api_key+ if not api_key:+ raise ValueError("WEBSOCKET_API_KEY not configured in environment")++ logger.info("[Android Device Setup] Connecting to Relay",+ url=websocket_url, api_key=api_key[:8] + "...")++ relay_client = await get_relay_client(websocket_url, api_key)++ if relay_client and relay_client.is_connected():+ # Wait for Android device to pair via QR code+ if not relay_client.is_paired():+ logger.info("[Android Device Setup] Waiting for Android device to pair...")+ paired = await relay_client.wait_for_pairing(timeout=5.0)+ if not paired:+ # Return QR data for pairing+ connection_info = {+ "connection_type": "remote",+ "websocket_url": websocket_url,+ "port": port,+ "status": "waiting_for_pairing",+ "qr_data": relay_client.qr_data,+ "session_token": relay_client.session_token,+ "message": "Scan QR code with Android app to pair",+ "timestamp": datetime.now().isoformat()+ }+ return {+ "success": True,+ "node_id": node_id,+ "node_type": node_type,+ "result": connection_info,+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ # Device is paired+ device_id = relay_client.paired_device_id+ device_name = relay_client.paired_device_name++ connection_info = {+ "connection_type": "remote",+ "websocket_url": websocket_url,+ "port": port,+ "status": "paired",+ "paired": True,+ "device_id": device_id,+ "device_name": device_name,+ "session_token": relay_client.session_token,+ "message": f"Paired with Android device: {device_name or device_id}",+ "timestamp": datetime.now().isoformat()+ }++ logger.info("[Android Device Setup] Relay connected and paired",+ device_id=device_id, device_name=device_name)++ return {+ "success": True,+ "node_id": node_id,+ "node_type": node_type,+ "result": connection_info,+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+ else:+ logger.error("[Android Device Setup] Relay connection failed")+ return {+ "success": False,+ "node_id": node_id,+ "node_type": node_type,+ "error": "Failed to connect to relay server",+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+ except Exception as e:+ logger.error("[Android Device Setup] Relay error", error=str(e))+ return {+ "success": False,+ "node_id": node_id,+ "node_type": node_type,+ "error": f"Relay connection error: {str(e)}",+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+ else:+ # Configuration saved without active setup+ connection_info = {+ "connection_type": connection_type,+ "device_id": device_id if connection_type == 'local' else None,+ "websocket_url": websocket_url if connection_type == 'remote' else None,+ "port": port,+ "port_forwarding": "not_setup",+ "message": "Device configuration saved (auto_forward disabled or missing device info)",+ "timestamp": datetime.now().isoformat()+ }++ return {+ "success": True,+ "node_id": node_id,+ "node_type": node_type,+ "result": connection_info,+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+++async def handle_android_service(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any],+ android_service: "AndroidService"+) -> Dict[str, Any]:+ """Handle Android service node execution.++ Executes Android service actions like battery status, network info, etc.++ Args:+ node_id: The node ID+ node_type: The node type (batteryMonitor, networkMonitor, etc.)+ parameters: Resolved parameters+ context: Execution context+ android_service: The Android service instance++ Returns:+ Execution result dict+ """+ print(f"[ANDROID DEBUG] Matched! node_type={node_type}")+ logger.info("[DEBUG] Android service condition matched!", node_type=node_type,+ in_array=node_type in ANDROID_SERVICE_NODE_TYPES)++ service_id = parameters.get('service_id', 'battery')+ action = parameters.get('action', 'status')+ service_params = parameters.get('parameters', {})+ android_host = parameters.get('android_host', 'localhost')+ android_port = parameters.get('android_port', 8888)++ # Parse parameters if it's a JSON string+ if isinstance(service_params, str):+ try:+ service_params = json.loads(service_params)+ except json.JSONDecodeError:+ service_params = {}++ # Extract additional parameters that are at root level (from additionalProperties in node definitions)+ # These include: package_name (appLauncher), and any future custom parameters+ additional_param_keys = ['package_name']+ for key in additional_param_keys:+ if key in parameters and parameters[key]:+ service_params[key] = parameters[key]++ print(f"[ANDROID DEBUG] Extracted params: service_id={service_id}, action={action}, host={android_host}, port={android_port}, service_params={service_params}")+ print(f"[ANDROID DEBUG] About to call android_service.execute_service")+ logger.info("[Android Service] Executing", node_id=node_id, service_id=service_id,+ action=action, android_host=android_host, android_port=android_port)++ result = await android_service.execute_service(+ node_id=node_id,+ service_id=service_id,+ action=action,+ parameters=service_params,+ android_host=android_host,+ android_port=android_port+ )+ print(f"[ANDROID DEBUG] Got result from android_service")+ return resultdiff --git a/server/services/handlers/code.py b/server/services/handlers/code.pynew file mode 100644index 00000000..11e120bf--- /dev/null+++ b/server/services/handlers/code.py@@ -0,0 +1,278 @@+"""Code execution node handlers - Python and JavaScript executors."""++import json+import time+from datetime import datetime+from typing import Dict, Any+from core.logging import get_logger++logger = get_logger(__name__)+++async def handle_python_executor(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any],+ connected_outputs: Dict[str, Any] = None+) -> Dict[str, Any]:+ """Handle Python executor node execution.++ Executes Python code with input data access and console output capture.++ Args:+ node_id: The node ID+ node_type: The node type (pythonExecutor)+ parameters: Resolved parameters+ context: Execution context+ connected_outputs: Outputs from connected nodes++ Returns:+ Execution result dict with output and console output+ """+ import sys+ import io+ start_time = time.time()+ console_output = ""++ try:+ code = parameters.get('code', '')+ timeout = int(parameters.get('timeout', 30))++ if not code.strip():+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "pythonExecutor",+ "error": "No code provided",+ "console_output": "",+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ # Get input data from connected nodes+ input_data = connected_outputs or {}++ # Capture stdout for console output+ stdout_capture = io.StringIO()++ # Create execution namespace with safe builtins+ import math+ import json as json_module++ # Custom print function that writes to our capture buffer+ def captured_print(*args, **kwargs):+ kwargs['file'] = stdout_capture+ print(*args, **kwargs)++ safe_builtins = {+ 'abs': abs, 'all': all, 'any': any, 'bool': bool,+ 'dict': dict, 'enumerate': enumerate, 'filter': filter,+ 'float': float, 'int': int, 'len': len, 'list': list,+ 'map': map, 'max': max, 'min': min, 'print': captured_print,+ 'range': range, 'round': round, 'set': set, 'sorted': sorted,+ 'str': str, 'sum': sum, 'tuple': tuple, 'type': type, 'zip': zip,+ 'True': True, 'False': False, 'None': None,+ 'math': math, 'json': json_module+ }++ namespace = {+ '__builtins__': safe_builtins,+ 'input_data': input_data,+ 'output': None+ }++ # Execute code with timeout+ exec(code, namespace)++ # Get output and console output+ output = namespace.get('output', None)+ console_output = stdout_capture.getvalue()++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "pythonExecutor",+ "result": {+ "output": output,+ "console_output": console_output,+ "timestamp": datetime.now().isoformat()+ },+ "console_output": console_output,+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ except Exception as e:+ logger.error("Python execution failed", node_id=node_id, error=str(e))+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "pythonExecutor",+ "error": str(e),+ "console_output": console_output,+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+++async def handle_javascript_executor(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any],+ connected_outputs: Dict[str, Any] = None+) -> Dict[str, Any]:+ """Handle JavaScript executor node execution.++ Executes JavaScript code using Node.js subprocess with sandboxing.++ Args:+ node_id: The node ID+ node_type: The node type (javascriptExecutor)+ parameters: Resolved parameters+ context: Execution context+ connected_outputs: Outputs from connected nodes++ Returns:+ Execution result dict with output and console output+ """+ import subprocess+ import tempfile+ import os++ start_time = time.time()+ console_output = ""++ try:+ code = parameters.get('code', '')+ timeout = int(parameters.get('timeout', 30))++ if not code.strip():+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "javascriptExecutor",+ "error": "No code provided",+ "console_output": "",+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ # Get input data from connected nodes+ input_data = connected_outputs or {}++ # Wrapper script that provides input_data and captures output+ wrapper_code = f'''+const input_data = {json.dumps(input_data)};+let output = null;++// Capture console.log+const logs = [];+const originalLog = console.log;+const originalError = console.error;+const originalWarn = console.warn;++console.log = (...args) => {{+ logs.push(args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' '));+}};+console.error = (...args) => {{+ logs.push('[ERROR] ' + args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' '));+}};+console.warn = (...args) => {{+ logs.push('[WARN] ' + args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' '));+}};++try {{+ {code}+}} catch (e) {{+ console.error(e.message);+ throw e;+}}++// Output result+console.log = originalLog;+process.stdout.write(JSON.stringify({{+ __output__: output,+ __logs__: logs+}}));+'''++ # Write to temp file and execute with Node.js+ with tempfile.NamedTemporaryFile(mode='w', suffix='.js', delete=False, encoding='utf-8') as f:+ f.write(wrapper_code)+ temp_file = f.name++ try:+ result = subprocess.run(+ ['node', temp_file],+ capture_output=True,+ text=True,+ timeout=timeout,+ cwd=tempfile.gettempdir()+ )++ if result.returncode != 0:+ error_msg = result.stderr.strip() if result.stderr else "JavaScript execution failed"+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "javascriptExecutor",+ "error": error_msg,+ "console_output": result.stdout,+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ # Parse output+ stdout = result.stdout.strip()+ if stdout:+ output_data = json.loads(stdout)+ output = output_data.get('__output__')+ console_output = '\n'.join(output_data.get('__logs__', []))+ else:+ output = None+ console_output = ""++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "javascriptExecutor",+ "result": {+ "output": output,+ "console_output": console_output,+ "timestamp": datetime.now().isoformat()+ },+ "console_output": console_output,+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+ finally:+ # Clean up temp file+ try:+ os.unlink(temp_file)+ except:+ pass++ except subprocess.TimeoutExpired:+ logger.error("JavaScript execution timed out", node_id=node_id, timeout=timeout)+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "javascriptExecutor",+ "error": f"Execution timed out after {timeout} seconds",+ "console_output": console_output,+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+ except Exception as e:+ logger.error("JavaScript execution failed", node_id=node_id, error=str(e))+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "javascriptExecutor",+ "error": str(e),+ "console_output": console_output,+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }diff --git a/server/services/handlers/http.py b/server/services/handlers/http.pynew file mode 100644index 00000000..9be336b9--- /dev/null+++ b/server/services/handlers/http.py@@ -0,0 +1,193 @@+"""HTTP node handlers - HTTP Request and Webhook Response."""++import json+import time+from datetime import datetime+from typing import Dict, Any+from core.logging import get_logger++logger = get_logger(__name__)+++async def handle_http_request(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any]+) -> Dict[str, Any]:+ """Handle HTTP request node execution.++ Makes HTTP requests to external APIs.++ Args:+ node_id: The node ID+ node_type: The node type (httpRequest)+ parameters: Resolved parameters+ context: Execution context++ Returns:+ Execution result dict with response data+ """+ import httpx+ start_time = time.time()++ try:+ method = parameters.get('method', 'GET')+ url = parameters.get('url', '')+ headers_str = parameters.get('headers', '{}')+ body = parameters.get('body', '')+ timeout = float(parameters.get('timeout', 30))++ if not url:+ raise ValueError("URL is required")++ # Parse headers JSON+ try:+ headers = json.loads(headers_str) if headers_str else {}+ except json.JSONDecodeError:+ headers = {}++ logger.info("[HTTP Request] Executing", node_id=node_id, method=method, url=url)++ async with httpx.AsyncClient() as client:+ kwargs = {+ 'method': method,+ 'url': url,+ 'headers': headers,+ 'timeout': timeout+ }++ # Add body for POST/PUT/PATCH+ if method in ['POST', 'PUT', 'PATCH'] and body:+ try:+ kwargs['json'] = json.loads(body)+ except json.JSONDecodeError:+ kwargs['content'] = body++ response = await client.request(**kwargs)++ # Parse response data+ try:+ response_data = response.json()+ except:+ response_data = response.text++ result_data = {+ "status": response.status_code,+ "data": response_data,+ "headers": dict(response.headers),+ "url": str(response.url),+ "method": method+ }++ return {+ "success": response.status_code < 400,+ "node_id": node_id,+ "node_type": "httpRequest",+ "result": result_data,+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ except Exception as e:+ if "TimeoutException" in type(e).__name__:+ logger.error("HTTP request timed out", node_id=node_id, url=parameters.get('url'))+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "httpRequest",+ "error": f"Request timed out after {parameters.get('timeout', 30)} seconds",+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+ logger.error("HTTP request failed", node_id=node_id, error=str(e))+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "httpRequest",+ "error": str(e),+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+++async def handle_webhook_response(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any],+ connected_outputs: Dict[str, Any] = None+) -> Dict[str, Any]:+ """Handle webhook response node execution.++ Sends response back to waiting webhook caller.++ Args:+ node_id: The node ID+ node_type: The node type (webhookResponse)+ parameters: Resolved parameters+ context: Execution context+ connected_outputs: Outputs from connected nodes++ Returns:+ Execution result dict+ """+ from routers.webhook import resolve_webhook_response+ start_time = time.time()++ try:+ status_code = int(parameters.get('statusCode', 200))+ response_body = parameters.get('responseBody', '')+ content_type = parameters.get('contentType', 'application/json')++ # Resolve template variables in response body+ if response_body and connected_outputs:+ for node_type_key, output_data in connected_outputs.items():+ if isinstance(output_data, dict):+ for key, value in output_data.items():+ template = f"{{{{input.{key}}}}}"+ response_body = response_body.replace(template, str(value))+ # Also support {{nodeType.key}} format+ template_alt = f"{{{{{node_type_key}.{key}}}}}"+ response_body = response_body.replace(template_alt, str(value))++ # If response body is empty, serialize connected outputs as JSON+ if not response_body and connected_outputs:+ # Get the first connected output+ first_output = next(iter(connected_outputs.values()), {})+ response_body = json.dumps(first_output, default=str)++ logger.info("[Webhook Response] Sending", node_id=node_id, status_code=status_code,+ content_type=content_type, body_length=len(response_body))++ # Resolve the pending webhook response+ resolve_webhook_response(node_id, {+ 'statusCode': status_code,+ 'body': response_body,+ 'contentType': content_type+ })++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "webhookResponse",+ "result": {+ "sent": True,+ "statusCode": status_code,+ "contentType": content_type,+ "bodyLength": len(response_body)+ },+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ except Exception as e:+ logger.error("Webhook response failed", node_id=node_id, error=str(e))+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "webhookResponse",+ "error": str(e),+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }diff --git a/server/services/handlers/triggers.py b/server/services/handlers/triggers.pynew file mode 100644index 00000000..38a53dc7--- /dev/null+++ b/server/services/handlers/triggers.py@@ -0,0 +1,107 @@+"""Trigger node handlers - Generic event-based triggers."""++import asyncio+import time+from datetime import datetime+from typing import Dict, Any+from core.logging import get_logger+from services import event_waiter++logger = get_logger(__name__)+++async def handle_trigger_node(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any]+) -> Dict[str, Any]:+ """Handle trigger node execution (webhook, whatsapp, etc.).++ Uses event_waiter module to register waiter and await matching event.+ Works with any trigger type defined in TRIGGER_REGISTRY.++ Args:+ node_id: The node ID+ node_type: The node type (webhookTrigger, whatsappReceive, etc.)+ parameters: Resolved parameters+ context: Execution context with execution_id for tracing++ Returns:+ Execution result dict with event data+ """+ from services.status_broadcaster import get_status_broadcaster+ start_time = time.time()+ execution_id = context.get('execution_id', 'unknown')++ # Get trigger configuration+ config = event_waiter.get_trigger_config(node_type)+ if not config:+ logger.error("Unknown trigger type", node_id=node_id, node_type=node_type, execution_id=execution_id)+ return {+ "success": False,+ "node_id": node_id,+ "node_type": node_type,+ "error": f"Unknown trigger type: {node_type}",+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ try:+ # Register waiter for this trigger (async to pre-fetch LID cache)+ waiter = await event_waiter.register(node_type, node_id, parameters)++ # Get workflow_id from context for per-workflow status scoping (n8n pattern)+ workflow_id = context.get('workflow_id')++ # Broadcast waiting status to frontend+ broadcaster = get_status_broadcaster()+ logger.info("Broadcasting waiting status", node_id=node_id, execution_id=execution_id)+ await broadcaster.update_node_status(node_id, "waiting", {+ "message": f"Waiting for {config.display_name}...",+ "event_type": config.event_type,+ "waiter_id": waiter.id+ }, workflow_id=workflow_id)++ logger.info("Trigger waiting for event", node_id=node_id, node_type=node_type,+ event_type=config.event_type, execution_id=execution_id,+ backend_mode=event_waiter.get_backend_mode())++ # Wait for event indefinitely (user cancels via cancel_event_wait)+ # Uses wait_for_event which handles both Redis Streams and asyncio.Future modes+ try:+ event_data = await event_waiter.wait_for_event(waiter)+ logger.info("Event received", node_id=node_id, execution_id=execution_id)++ # Success - event received+ return {+ "success": True,+ "node_id": node_id,+ "node_type": node_type,+ "result": event_data,+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ except asyncio.CancelledError:+ logger.info("Trigger cancelled by user", node_id=node_id, node_type=node_type, execution_id=execution_id)+ return {+ "success": False,+ "node_id": node_id,+ "node_type": node_type,+ "error": "Cancelled by user",+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ except Exception as e:+ logger.error("Trigger execution failed", node_id=node_id, node_type=node_type,+ execution_id=execution_id, error=str(e))+ return {+ "success": False,+ "node_id": node_id,+ "node_type": node_type,+ "error": str(e),+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }diff --git a/server/services/handlers/utility.py b/server/services/handlers/utility.pynew file mode 100644index 00000000..381b783a--- /dev/null+++ b/server/services/handlers/utility.py@@ -0,0 +1,593 @@+"""Utility node handlers - Maps, Text, Chat, Cron, Start."""++import asyncio+import json+import time+from datetime import datetime, timedelta+from typing import Dict, Any, TYPE_CHECKING+from core.logging import get_logger++if TYPE_CHECKING:+ from services.maps import MapsService+ from services.text import TextService++logger = get_logger(__name__)+++# =============================================================================+# MAPS HANDLERS+# =============================================================================++async def handle_create_map(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any],+ maps_service: "MapsService"+) -> Dict[str, Any]:+ """Handle create map node execution.++ Args:+ node_id: The node ID+ node_type: The node type (createMap)+ parameters: Resolved parameters+ context: Execution context+ maps_service: The maps service instance++ Returns:+ Execution result dict+ """+ logger.info("[Maps Execution] Executing createMap", node_id=node_id)+ result = await maps_service.create_map(node_id, parameters)+ logger.info("[Maps Execution] createMap result", success=result.get('success'),+ has_result='result' in result,+ result_keys=list(result.get('result', {}).keys()) if isinstance(result.get('result'), dict) else 'not_dict')+ return result+++async def handle_add_locations(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any],+ maps_service: "MapsService"+) -> Dict[str, Any]:+ """Handle add locations node execution (geocoding).++ Args:+ node_id: The node ID+ node_type: The node type (addLocations)+ parameters: Resolved parameters+ context: Execution context+ maps_service: The maps service instance++ Returns:+ Execution result dict+ """+ logger.info("[Maps Execution] Executing addLocations", node_id=node_id)+ result = await maps_service.geocode_location(node_id, parameters)+ logger.info("[Maps Execution] addLocations result", success=result.get('success'),+ has_result='result' in result,+ result_keys=list(result.get('result', {}).keys()) if isinstance(result.get('result'), dict) else 'not_dict')+ return result+++async def handle_nearby_places(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any],+ maps_service: "MapsService"+) -> Dict[str, Any]:+ """Handle show nearby places node execution.++ Args:+ node_id: The node ID+ node_type: The node type (showNearbyPlaces)+ parameters: Resolved parameters+ context: Execution context+ maps_service: The maps service instance++ Returns:+ Execution result dict+ """+ logger.info("[Maps Execution] Executing showNearbyPlaces", node_id=node_id)+ result = await maps_service.find_nearby_places(node_id, parameters)+ logger.info("[Maps Execution] showNearbyPlaces result", success=result.get('success'),+ has_result='result' in result,+ result_keys=list(result.get('result', {}).keys()) if isinstance(result.get('result'), dict) else 'not_dict')+ return result+++# =============================================================================+# TEXT HANDLERS+# =============================================================================++async def handle_text_generator(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any],+ text_service: "TextService"+) -> Dict[str, Any]:+ """Handle text generator node execution.++ Args:+ node_id: The node ID+ node_type: The node type (textGenerator)+ parameters: Resolved parameters+ context: Execution context+ text_service: The text service instance++ Returns:+ Execution result dict+ """+ return await text_service.execute_text_generator(node_id, parameters)+++async def handle_file_handler(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any],+ text_service: "TextService"+) -> Dict[str, Any]:+ """Handle file handler node execution.++ Args:+ node_id: The node ID+ node_type: The node type (fileHandler)+ parameters: Resolved parameters+ context: Execution context+ text_service: The text service instance++ Returns:+ Execution result dict+ """+ return await text_service.execute_file_handler(node_id, parameters)+++# =============================================================================+# CHAT HANDLERS+# =============================================================================++async def handle_chat_send(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any]+) -> Dict[str, Any]:+ """Handle chat send message via JSON-RPC 2.0 WebSocket.++ Args:+ node_id: The node ID+ node_type: The node type (chatSend)+ parameters: Resolved parameters+ context: Execution context++ Returns:+ Execution result dict+ """+ from services.chat_client import send_chat_message+ start_time = time.time()++ try:+ host = parameters.get('host', 'localhost')+ port = int(parameters.get('port', 8080))+ session_id = parameters.get('session_id', 'default')+ api_key = parameters.get('api_key', '')+ content = parameters.get('content', '')++ if not content:+ raise ValueError("Message content is required")++ result = await send_chat_message(+ host=host, port=port, session_id=session_id,+ api_key=api_key, content=content+ )++ if result.get('success'):+ return {+ "success": True,+ "node_id": node_id,+ "node_type": "chatSend",+ "result": result.get('result', {}),+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+ else:+ raise Exception(result.get('error', 'Send failed'))++ except Exception as e:+ logger.error("Chat send failed", node_id=node_id, error=str(e))+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "chatSend",+ "error": str(e),+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+++async def handle_chat_history(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any]+) -> Dict[str, Any]:+ """Handle chat get history via JSON-RPC 2.0 WebSocket.++ Args:+ node_id: The node ID+ node_type: The node type (chatHistory)+ parameters: Resolved parameters+ context: Execution context++ Returns:+ Execution result dict with messages+ """+ from services.chat_client import get_chat_history+ start_time = time.time()++ try:+ host = parameters.get('host', 'localhost')+ port = int(parameters.get('port', 8080))+ session_id = parameters.get('session_id', 'default')+ api_key = parameters.get('api_key', '')+ limit = int(parameters.get('limit', 50))++ result = await get_chat_history(+ host=host, port=port, session_id=session_id,+ api_key=api_key, limit=limit+ )++ if result.get('success'):+ return {+ "success": True,+ "node_id": node_id,+ "node_type": "chatHistory",+ "result": {"messages": result.get('messages', [])},+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+ else:+ raise Exception(result.get('error', 'History fetch failed'))++ except Exception as e:+ logger.error("Chat history failed", node_id=node_id, error=str(e))+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "chatHistory",+ "error": str(e),+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+++# =============================================================================+# WORKFLOW CONTROL HANDLERS+# =============================================================================++async def handle_start(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any]+) -> Dict[str, Any]:+ """Handle start node execution.++ Args:+ node_id: The node ID+ node_type: The node type (start)+ parameters: Resolved parameters+ context: Execution context++ Returns:+ Execution result dict with initial data+ """+ initial_data_str = parameters.get('initialData', '{}')+ try:+ initial_data = json.loads(initial_data_str)+ except:+ initial_data = {}++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "start",+ "result": initial_data+ }+++async def handle_cron_scheduler(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any]+) -> Dict[str, Any]:+ """Handle cron scheduler node execution.++ Waits for the configured interval duration before triggering.+ Used for recurring scheduled tasks.++ Args:+ node_id: The node ID+ node_type: The node type (cronScheduler)+ parameters: Resolved parameters+ context: Execution context++ Returns:+ Execution result dict with schedule info+ """+ from services.status_broadcaster import get_status_broadcaster+ start_time = time.time()++ try:+ frequency = parameters.get('frequency', 'minutes')+ timezone = parameters.get('timezone', 'UTC')++ # Build human-readable schedule description+ schedule_desc = _get_schedule_description(parameters)++ logger.info("[CronScheduler] Executing",+ node_id=node_id,+ frequency=frequency,+ schedule=schedule_desc)++ # Calculate wait time in seconds based on frequency+ wait_seconds = _calculate_wait_seconds(parameters)++ now = datetime.now()+ trigger_time = now + timedelta(seconds=wait_seconds)++ # Get workflow_id from context for per-workflow status scoping (n8n pattern)+ workflow_id = context.get('workflow_id')++ # Broadcast waiting status to frontend+ broadcaster = get_status_broadcaster()+ await broadcaster.update_node_status(node_id, "waiting", {+ "message": f"Waiting {schedule_desc}...",+ "trigger_time": trigger_time.isoformat(),+ "wait_seconds": wait_seconds+ }, workflow_id=workflow_id)++ logger.info(f"[CronScheduler] Waiting {wait_seconds} seconds until trigger",+ node_id=node_id, trigger_time=trigger_time.isoformat())++ # Wait for the duration+ await asyncio.sleep(wait_seconds)++ # Build result data after wait completes+ triggered_at = datetime.now()+ result_data = {+ "timestamp": triggered_at.isoformat(),+ "iteration": 1,+ "frequency": frequency,+ "timezone": timezone,+ "schedule": schedule_desc,+ "scheduled_time": trigger_time.isoformat(),+ "triggered_at": triggered_at.isoformat(),+ "waited_seconds": wait_seconds+ }++ if frequency == 'once':+ result_data["message"] = f"Triggered after waiting {_format_wait_time(wait_seconds)}"+ else:+ result_data["next_run"] = schedule_desc+ result_data["message"] = f"Triggered after {_format_wait_time(wait_seconds)}, will repeat: {schedule_desc}"++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "cronScheduler",+ "result": result_data,+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ except asyncio.CancelledError:+ logger.info("[CronScheduler] Cancelled while waiting", node_id=node_id)+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "cronScheduler",+ "error": "Scheduler cancelled",+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+ except Exception as e:+ logger.error("CronScheduler execution failed", node_id=node_id, error=str(e))+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "cronScheduler",+ "error": str(e),+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+++# =============================================================================+# CRON HELPER FUNCTIONS+# =============================================================================++def _calculate_wait_seconds(parameters: Dict[str, Any]) -> int:+ """Calculate wait time in seconds based on frequency and interval."""+ frequency = parameters.get('frequency', 'minutes')++ # Calculate wait based on frequency type+ match frequency:+ case 'seconds':+ return int(parameters.get('interval', 30))+ case 'minutes':+ return int(parameters.get('intervalMinutes', 5)) * 60+ case 'hours':+ return int(parameters.get('intervalHours', 1)) * 3600+ case 'days':+ return 24 * 3600 # Wait 24 hours+ case 'weeks':+ return 7 * 24 * 3600 # Wait 7 days+ case 'months':+ return 30 * 24 * 3600 # Wait ~30 days+ case 'once':+ return 0 # Trigger immediately+ case _:+ return 300 # Default: 5 minutes+++def _format_wait_time(seconds: int) -> str:+ """Format seconds into human-readable time string."""+ if seconds < 60:+ return f"{seconds} seconds"+ elif seconds < 3600:+ minutes = seconds // 60+ return f"{minutes} minute{'s' if minutes != 1 else ''}"+ elif seconds < 86400:+ hours = seconds // 3600+ return f"{hours} hour{'s' if hours != 1 else ''}"+ else:+ days = seconds // 86400+ return f"{days} day{'s' if days != 1 else ''}"+++def _get_schedule_description(parameters: Dict[str, Any]) -> str:+ """Get human-readable schedule description from parameters."""+ frequency = parameters.get('frequency', 'minutes')++ match frequency:+ case 'seconds':+ interval = parameters.get('interval', 30)+ return f"Every {interval} seconds"+ case 'minutes':+ interval = parameters.get('intervalMinutes', 5)+ return f"Every {interval} minutes"+ case 'hours':+ interval = parameters.get('intervalHours', 1)+ return f"Every {interval} hours"+ case 'days':+ time_str = parameters.get('dailyTime', '09:00')+ return f"Daily at {time_str}"+ case 'weeks':+ weekday = parameters.get('weekday', '1')+ time_str = parameters.get('weeklyTime', '09:00')+ days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']+ day_name = days[int(weekday)] if weekday.isdigit() else weekday+ return f"Weekly on {day_name} at {time_str}"+ case 'months':+ day = parameters.get('monthDay', '1')+ time_str = parameters.get('monthlyTime', '09:00')+ return f"Monthly on day {day} at {time_str}"+ case 'once':+ return "Once (no repeat)"+ case _:+ return "Unknown schedule"+++# =============================================================================+# TIMER HANDLER+# =============================================================================++async def handle_timer(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any]+) -> Dict[str, Any]:+ """Handle timer node execution - waits for specified duration.++ Args:+ node_id: The node ID+ node_type: The node type (timer)+ parameters: Resolved parameters with duration and unit+ context: Execution context++ Returns:+ Execution result dict with timing info+ """+ from services.status_broadcaster import get_status_broadcaster+ start_time = time.time()++ try:+ duration = int(parameters.get('duration', 5))+ unit = parameters.get('unit', 'seconds')++ # Convert duration to seconds+ match unit:+ case 'seconds':+ wait_seconds = duration+ case 'minutes':+ wait_seconds = duration * 60+ case 'hours':+ wait_seconds = duration * 3600+ case _:+ wait_seconds = duration++ now = datetime.now()+ complete_time = now + timedelta(seconds=wait_seconds)++ # Get workflow_id from context for per-workflow status scoping (n8n pattern)+ workflow_id = context.get('workflow_id')+ logger.info("[Timer] Context workflow_id", node_id=node_id, workflow_id=workflow_id, context_keys=list(context.keys()))++ # Broadcast waiting status+ broadcaster = get_status_broadcaster()+ await broadcaster.update_node_status(node_id, "waiting", {+ "message": f"Waiting {duration} {unit}...",+ "complete_time": complete_time.isoformat(),+ "wait_seconds": wait_seconds+ }, workflow_id=workflow_id)++ logger.info("[Timer] Starting wait",+ node_id=node_id,+ duration=duration,+ unit=unit,+ wait_seconds=wait_seconds)++ # Wait for the duration+ await asyncio.sleep(wait_seconds)++ elapsed_ms = int((time.time() - start_time) * 1000)++ result_data = {+ "timestamp": datetime.now().isoformat(),+ "elapsed_ms": elapsed_ms,+ "duration": duration,+ "unit": unit,+ "message": f"Timer completed after {duration} {unit}"+ }++ logger.info("[Timer] Completed",+ node_id=node_id,+ elapsed_ms=elapsed_ms)++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "timer",+ "result": result_data,+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ except asyncio.CancelledError:+ logger.info("[Timer] Cancelled", node_id=node_id)+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "timer",+ "error": "Timer cancelled",+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+ except Exception as e:+ logger.error("[Timer] Failed", node_id=node_id, error=str(e))+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "timer",+ "error": str(e),+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }diff --git a/server/services/handlers/whatsapp.py b/server/services/handlers/whatsapp.pynew file mode 100644index 00000000..2a31466d--- /dev/null+++ b/server/services/handlers/whatsapp.py@@ -0,0 +1,166 @@+"""WhatsApp node handlers - Send and Connect."""++import time+from datetime import datetime+from typing import Dict, Any+from core.logging import get_logger++logger = get_logger(__name__)+++async def handle_whatsapp_send(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any]+) -> Dict[str, Any]:+ """Handle WhatsApp send message node via Go RPC service.++ Supports all message types: text, image, video, audio, document, sticker, location, contact+ Recipients: phone number or group_id+ Media sources: base64, file path, or URL++ Args:+ node_id: The node ID+ node_type: The node type (whatsappSend)+ parameters: Resolved parameters+ context: Execution context++ Returns:+ Execution result dict+ """+ from routers.whatsapp import handle_whatsapp_send as whatsapp_send_handler+ start_time = time.time()++ try:+ # Determine recipient+ recipient_type = parameters.get('recipientType', 'phone')+ # Support both group_id (node definition) and groupId (legacy)+ group_id = parameters.get('group_id') or parameters.get('groupId')+ recipient = parameters.get('phone') if recipient_type == 'phone' else group_id+ message_type = parameters.get('messageType', 'text')++ if not recipient:+ raise ValueError(f"{'Phone number' if recipient_type == 'phone' else 'Group ID'} is required")++ # For text messages, validate message content+ if message_type == 'text' and not parameters.get('message'):+ raise ValueError("Message content is required for text messages")++ # Call WhatsApp Go RPC service via handler - pass full params+ data = await whatsapp_send_handler(parameters)++ success = data.get('success', False)+ if not success:+ raise Exception(data.get('error', 'Send failed'))++ # Build informative result based on message type+ result = {+ "status": "sent",+ "recipient": recipient,+ "recipientType": recipient_type,+ "messageType": message_type,+ "timestamp": datetime.now().isoformat()+ }++ # Add type-specific details using match statement+ match message_type:+ case 'text':+ msg_content = parameters.get('message', '')+ result["preview"] = msg_content[:100] + "..." if len(msg_content) > 100 else msg_content+ case 'image' | 'video' | 'audio' | 'document' | 'sticker':+ media_source = parameters.get('mediaSource', 'base64')+ result["mediaSource"] = media_source+ if parameters.get('caption'):+ result["caption"] = parameters.get('caption')+ if parameters.get('filename'):+ result["filename"] = parameters.get('filename')+ if parameters.get('mimeType'):+ result["mimeType"] = parameters.get('mimeType')+ # For file uploads, include the uploaded filename+ file_param = parameters.get('filePath')+ if isinstance(file_param, dict) and file_param.get('type') == 'upload':+ result["uploadedFile"] = file_param.get('filename')+ result["mimeType"] = file_param.get('mimeType')+ case 'location':+ result["location"] = {+ "latitude": parameters.get('latitude'),+ "longitude": parameters.get('longitude'),+ "name": parameters.get('locationName'),+ "address": parameters.get('address')+ }+ case 'contact':+ result["contactName"] = parameters.get('contactName')++ return {+ "success": success,+ "node_id": node_id,+ "node_type": "whatsappSend",+ "result": result,+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ except Exception as e:+ logger.error("WhatsApp send failed", node_id=node_id, error=str(e))+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "whatsappSend",+ "error": str(e),+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+++async def handle_whatsapp_connect(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any]+) -> Dict[str, Any]:+ """Handle WhatsApp connect - check status via Go RPC service.++ Args:+ node_id: The node ID+ node_type: The node type (whatsappConnect)+ parameters: Resolved parameters+ context: Execution context++ Returns:+ Execution result dict with connection status+ """+ from routers.whatsapp import handle_whatsapp_status+ start_time = time.time()++ try:+ # Call WhatsApp Go RPC service via handler+ data = await handle_whatsapp_status()++ result_data = data.get('data', {})+ return {+ "success": data.get('success', False),+ "node_id": node_id,+ "node_type": "whatsappConnect",+ "result": {+ "connected": result_data.get('connected', False),+ "device_id": result_data.get('device_id'),+ "has_session": result_data.get('has_session', False),+ "running": result_data.get('running', False),+ "status": "connected" if result_data.get('connected') else "disconnected",+ "timestamp": datetime.now().isoformat()+ },+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ except Exception as e:+ logger.error("WhatsApp connect failed", node_id=node_id, error=str(e))+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "whatsappConnect",+ "error": str(e),+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }diff --git a/server/services/maps.py b/server/services/maps.pynew file mode 100644index 00000000..7705e651--- /dev/null+++ b/server/services/maps.py@@ -0,0 +1,289 @@+"""Google Maps service for location operations."""++import time+import googlemaps+from datetime import datetime+from typing import Dict, Any++from core.config import Settings+from core.logging import get_logger, log_execution_time+from services.auth import AuthService++logger = get_logger(__name__)+++class MapsService:+ """Google Maps and Places API service."""++ def __init__(self, auth_service: AuthService, settings: Settings):+ self.auth = auth_service+ self.settings = settings++ def validate_coordinates(self, lat: float, lng: float) -> bool:+ """Validate latitude and longitude."""+ return -90 <= lat <= 90 and -180 <= lng <= 180++ def validate_zoom_level(self, zoom: int) -> bool:+ """Validate Google Maps zoom level."""+ return 0 <= zoom <= 21++ async def create_map(self, node_id: str, parameters: Dict[str, Any]) -> Dict[str, Any]:+ """Create Google Maps configuration."""+ start_time = time.time()++ try:+ api_key = parameters.get('api_key') or self.settings.google_maps_api_key+ if not api_key:+ raise ValueError("Google Maps API key is required")++ # Extract and validate parameters+ lat = float(parameters.get('lat', 40.7128))+ lng = float(parameters.get('lng', -74.0060))+ zoom = int(parameters.get('zoom', 13))+ map_type = parameters.get('mapTypeId', 'ROADMAP')++ if not self.validate_coordinates(lat, lng):+ raise ValueError("Invalid coordinates")+ if not self.validate_zoom_level(zoom):+ raise ValueError("Invalid zoom level")+ if map_type not in ['ROADMAP', 'SATELLITE', 'HYBRID', 'TERRAIN']:+ raise ValueError("Invalid map type")++ result = {+ "map_config": {+ "center": {"lat": lat, "lng": lng},+ "zoom": zoom,+ "mapTypeId": map_type+ },+ "static_map_url": f"https://maps.googleapis.com/maps/api/staticmap?center={lat},{lng}&zoom={zoom}&size=600x400&maptype={map_type.lower()}&key={api_key}",+ "status": "OK"+ }++ log_execution_time(logger, "create_map", start_time, time.time())++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "createMap",+ "operation": "map_initialization",+ "result": result,+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ except Exception as e:+ logger.error("Create map failed", node_id=node_id, error=str(e))+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "createMap",+ "error": str(e),+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ async def geocode_location(self, node_id: str, parameters: Dict[str, Any]) -> Dict[str, Any]:+ """Geocode addresses or reverse geocode coordinates."""+ start_time = time.time()++ try:+ api_key = parameters.get('api_key') or self.settings.google_maps_api_key+ if not api_key:+ raise ValueError("Google Maps API key is required")++ gmaps = googlemaps.Client(key=api_key)+ service_type = parameters.get('serviceType', 'geocode')++ if service_type == 'geocode':+ address = parameters.get('address', '')+ if not address:+ raise ValueError("Address is required for geocoding")++ geocode_result = gmaps.geocode(address=address)+ result = {+ "service_type": "geocoding",+ "input": {"address": address},+ "results": geocode_result,+ "status": "OK" if geocode_result else "ZERO_RESULTS"+ }++ elif service_type == 'reverse_geocode':+ lat = float(parameters.get('lat', 0))+ lng = float(parameters.get('lng', 0))++ if not self.validate_coordinates(lat, lng):+ raise ValueError("Invalid coordinates")++ reverse_result = gmaps.reverse_geocode((lat, lng))+ result = {+ "service_type": "reverse_geocoding",+ "input": {"lat": lat, "lng": lng},+ "results": reverse_result,+ "status": "OK" if reverse_result else "ZERO_RESULTS"+ }++ else:+ raise ValueError(f"Unsupported service type: {service_type}")++ log_execution_time(logger, f"geocoding_{service_type}", start_time, time.time())++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "addLocations",+ "operation": service_type,+ "result": result,+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ except googlemaps.exceptions.ApiError as e:+ logger.error("Google Maps API error", node_id=node_id, error=str(e))+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "addLocations",+ "error": f"Google Maps API error: {str(e)}",+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ except Exception as e:+ logger.error("Geocoding failed", node_id=node_id, error=str(e))+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "addLocations",+ "error": str(e),+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ async def find_nearby_places(self, node_id: str, parameters: Dict[str, Any]) -> Dict[str, Any]:+ """Find nearby places using Google Places API."""+ start_time = time.time()++ try:+ api_key = parameters.get('api_key') or self.settings.google_maps_api_key+ if not api_key:+ raise ValueError("Google Maps API key is required")++ gmaps = googlemaps.Client(key=api_key)++ # Extract and validate parameters+ lat = float(parameters.get('lat', 40.7484))+ lng = float(parameters.get('lng', -73.9857))+ radius = int(parameters.get('radius', 500))++ if not self.validate_coordinates(lat, lng):+ raise ValueError("Invalid coordinates")+ if not (1 <= radius <= 50000):+ raise ValueError("Radius must be between 1 and 50000 meters")++ # Optional parameters+ place_type = parameters.get('type', 'restaurant')+ page_size = min(int(parameters.get('pageSize', 20)), 20)++ # Extract options (may contain keyword, name, minPrice, maxPrice, openNow, language, rankBy)+ options = parameters.get('options', {})++ # Support both nested options and top-level parameters+ keyword = options.get('keyword', '') if isinstance(options, dict) else parameters.get('keyword', '')+ name_filter = options.get('name', '') if isinstance(options, dict) else parameters.get('name', '')+ min_price = options.get('minPrice') if isinstance(options, dict) else parameters.get('minPrice')+ max_price = options.get('maxPrice') if isinstance(options, dict) else parameters.get('maxPrice')+ open_now = options.get('openNow', False) if isinstance(options, dict) else parameters.get('openNow', False)+ language = options.get('language', 'en') if isinstance(options, dict) else parameters.get('language', 'en')+ rank_by = options.get('rankBy', 'prominence') if isinstance(options, dict) else parameters.get('rankBy', 'prominence')++ logger.debug("[Nearby Places] Extracted parameters",+ keyword=keyword,+ name_filter=name_filter,+ min_price=min_price,+ max_price=max_price,+ open_now=open_now,+ language=language,+ rank_by=rank_by,+ place_type=place_type)++ # Build search request+ search_params = {+ 'location': (lat, lng),+ 'type': place_type+ }++ # Add radius unless ranking by distance+ if rank_by != 'distance':+ search_params['radius'] = radius+ else:+ search_params['rank_by'] = rank_by++ # Add optional parameters+ if keyword:+ search_params['keyword'] = keyword+ if name_filter:+ search_params['name'] = name_filter+ if min_price is not None and min_price != '':+ search_params['min_price'] = int(min_price)+ if max_price is not None and max_price != '':+ search_params['max_price'] = int(max_price)+ if open_now:+ search_params['open_now'] = True+ if language:+ search_params['language'] = language++ nearby_result = gmaps.places_nearby(**search_params)+ results = nearby_result.get('results', [])[:page_size]++ result = {+ "search_parameters": {+ "location": {"lat": lat, "lng": lng},+ "radius": radius if rank_by != 'distance' else None,+ "type": place_type,+ "keyword": keyword or None,+ "name_filter": name_filter or None,+ "min_price": min_price if min_price not in [None, ''] else None,+ "max_price": max_price if max_price not in [None, ''] else None,+ "open_now": open_now,+ "language": language,+ "rank_by": rank_by,+ "page_size": page_size+ },+ "results": results,+ "total_results": len(results),+ "status": nearby_result.get('status', 'OK')+ }++ log_execution_time(logger, "nearby_places", start_time, time.time())++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "showNearbyPlaces",+ "operation": "nearby_search",+ "result": result,+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ except googlemaps.exceptions.ApiError as e:+ logger.error("Google Places API error", node_id=node_id, error=str(e))+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "showNearbyPlaces",+ "error": f"Google Places API error: {str(e)}",+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ except Exception as e:+ logger.error("Nearby places search failed", node_id=node_id, error=str(e))+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "showNearbyPlaces",+ "error": str(e),+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }\ No newline at end of filediff --git a/server/services/memory_store.py b/server/services/memory_store.pynew file mode 100644index 00000000..4533c601--- /dev/null+++ b/server/services/memory_store.py@@ -0,0 +1,103 @@+"""Simple in-memory conversation storage for AI agents.++Uses standard Python data structures with LangChain message compatibility.+No deprecated APIs - follows LangChain 0.3+ recommendations.+"""+from typing import Dict, List, Optional, Callable+from dataclasses import dataclass, field+from datetime import datetime+import logging++logger = logging.getLogger(__name__)+++@dataclass+class Message:+ """Single conversation message."""+ role: str # 'human' or 'ai'+ content: str+ timestamp: str = field(default_factory=lambda: datetime.now().isoformat())+++@dataclass+class ConversationSession:+ """Conversation session with message history."""+ session_id: str+ messages: List[Message] = field(default_factory=list)+ created_at: str = field(default_factory=lambda: datetime.now().isoformat())+++# Global in-memory store+_sessions: Dict[str, ConversationSession] = {}+++def get_session(session_id: str) -> ConversationSession:+ """Get or create a conversation session."""+ if session_id not in _sessions:+ _sessions[session_id] = ConversationSession(session_id=session_id)+ logger.info(f"[Memory] Created new session: {session_id}")+ return _sessions[session_id]+++def add_message(session_id: str, role: str, content: str) -> None:+ """Add a message to a session."""+ session = get_session(session_id)+ session.messages.append(Message(role=role, content=content))+ logger.info(f"[Memory] Added {role} message to session '{session_id}' (total: {len(session.messages)})")+++def get_messages(session_id: str, window_size: Optional[int] = None) -> List[Dict]:+ """Get messages from a session, optionally limited to last N."""+ session = get_session(session_id)+ messages = session.messages+ if window_size and window_size > 0:+ messages = messages[-window_size:]+ return [{"role": m.role, "content": m.content, "timestamp": m.timestamp} for m in messages]+++def clear_session(session_id: str) -> int:+ """Clear a session's messages. Returns count of cleared messages."""+ if session_id in _sessions:+ count = len(_sessions[session_id].messages)+ _sessions[session_id].messages = []+ logger.info(f"[Memory] Cleared {count} messages from session '{session_id}'")+ return count+ return 0+++def delete_session(session_id: str) -> bool:+ """Delete a session entirely. Returns True if session existed."""+ if session_id in _sessions:+ del _sessions[session_id]+ logger.info(f"[Memory] Deleted session: {session_id}")+ return True+ return False+++def get_all_sessions() -> List[Dict]:+ """Get info about all sessions."""+ return [+ {+ "session_id": s.session_id,+ "message_count": len(s.messages),+ "created_at": s.created_at+ }+ for s in _sessions.values()+ ]+++def get_langchain_messages(session_id: str, window_size: Optional[int] = None):+ """Convert session messages to LangChain message format.++ Uses langchain_core.messages (modern API, not deprecated).+ """+ from langchain_core.messages import HumanMessage, AIMessage++ messages = get_messages(session_id, window_size)+ lc_messages = []+ for m in messages:+ if m['role'] == 'human':+ lc_messages.append(HumanMessage(content=m['content']))+ elif m['role'] == 'ai':+ lc_messages.append(AIMessage(content=m['content']))+ return lc_messagesdiff --git a/server/services/node_executor.py b/server/services/node_executor.pynew file mode 100644index 00000000..e69d773f--- /dev/null+++ b/server/services/node_executor.py@@ -0,0 +1,290 @@+"""Node Executor - Single node execution with handler dispatch.++Uses a registry pattern for clean handler dispatch without if-else chains.+"""++import asyncio+import time+import uuid+from dataclasses import dataclass+from datetime import datetime+from functools import partial+from typing import Dict, Any, Optional, Callable, TYPE_CHECKING++from core.logging import get_logger+from constants import (+ ANDROID_SERVICE_NODE_TYPES,+ AI_MODEL_TYPES,+ AI_CHAT_MODEL_TYPES,+ GOOGLE_MAPS_TYPES,+ detect_ai_provider,+)+from models.nodes import validate_node_params+from pydantic import ValidationError+from services import event_waiter+from services.handlers import (+ handle_ai_agent, handle_ai_chat_model, handle_simple_memory,+ handle_android_device_setup, handle_android_service,+ handle_python_executor, handle_javascript_executor,+ handle_http_request, handle_webhook_response, handle_trigger_node,+ handle_create_map, handle_add_locations, handle_nearby_places,+ handle_text_generator, handle_file_handler,+ handle_chat_send, handle_chat_history,+ handle_start, handle_cron_scheduler, handle_timer,+ handle_whatsapp_send, handle_whatsapp_connect,+)++if TYPE_CHECKING:+ from core.config import Settings+ from core.database import Database+ from services.ai import AIService+ from services.maps import MapsService+ from services.text import TextService+ from services.android_service import AndroidService++logger = get_logger(__name__)+++@dataclass+class ExecutionResult:+ """Standardized execution result."""+ success: bool+ node_id: str+ node_type: str+ result: Optional[Dict] = None+ error: Optional[str] = None+ execution_id: str = ""+ execution_time: float = 0.0+ timestamp: str = ""++ def to_dict(self) -> Dict[str, Any]:+ d = {+ "success": self.success,+ "node_id": self.node_id,+ "node_type": self.node_type,+ "execution_id": self.execution_id,+ "execution_time": self.execution_time,+ "timestamp": self.timestamp or datetime.now().isoformat(),+ }+ if self.success:+ d["result"] = self.result or {}+ else:+ d["error"] = self.error+ return d+++class NodeExecutor:+ """Executes individual workflow nodes using registry-based dispatch."""++ def __init__(+ self,+ database: "Database",+ ai_service: "AIService",+ maps_service: "MapsService",+ text_service: "TextService",+ android_service: "AndroidService",+ settings: "Settings",+ output_store: Optional[Callable] = None,+ ):+ self.database = database+ self.ai_service = ai_service+ self.maps_service = maps_service+ self.text_service = text_service+ self.android_service = android_service+ self.settings = settings+ self._output_store = output_store+ self._handlers = self._build_handler_registry()++ def _build_handler_registry(self) -> Dict[str, Callable]:+ """Build handler registry with service dependencies bound via partial."""+ registry = {+ # Workflow control+ 'start': handle_start,+ 'cronScheduler': handle_cron_scheduler,+ 'timer': handle_timer,+ # AI+ 'aiAgent': partial(handle_ai_agent, ai_service=self.ai_service, database=self.database),+ 'simpleMemory': handle_simple_memory,+ # Maps+ 'createMap': partial(handle_create_map, maps_service=self.maps_service),+ 'addLocations': partial(handle_add_locations, maps_service=self.maps_service),+ 'showNearbyPlaces': partial(handle_nearby_places, maps_service=self.maps_service),+ # Text+ 'textGenerator': partial(handle_text_generator, text_service=self.text_service),+ 'fileHandler': partial(handle_file_handler, text_service=self.text_service),+ 'whatsappSend': handle_whatsapp_send,+ 'whatsappConnect': handle_whatsapp_connect,+ # Chat+ 'chatSend': handle_chat_send,+ 'chatHistory': handle_chat_history,+ # HTTP+ 'httpRequest': handle_http_request,+ # Android setup+ 'androidDeviceSetup': partial(handle_android_device_setup, settings=self.settings),+ }++ # Register AI chat models+ for node_type in AI_CHAT_MODEL_TYPES:+ registry[node_type] = partial(handle_ai_chat_model, ai_service=self.ai_service)++ # Register Android services+ for node_type in ANDROID_SERVICE_NODE_TYPES:+ registry[node_type] = partial(handle_android_service, android_service=self.android_service)++ return registry++ async def execute(+ self,+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any],+ resolve_params_fn: Optional[Callable] = None,+ ) -> Dict[str, Any]:+ """Execute a single workflow node."""+ start_time = time.time()+ session_id = context.get('session_id', 'default')+ execution_id = context.get('execution_id') or str(uuid.uuid4())[:8]++ try:+ # Load, validate, enhance parameters+ params = await self._prepare_parameters(node_id, node_type, parameters, session_id)++ # Resolve templates if resolver provided+ nodes = context.get('nodes')+ edges = context.get('edges')+ logger.debug(f"[NodeExecutor] Template resolution check: resolve_fn={resolve_params_fn is not None}, nodes={len(nodes) if nodes else 'None'}, edges={len(edges) if edges else 'None'}")++ if resolve_params_fn and nodes is not None and edges is not None:+ logger.debug(f"[NodeExecutor] Before resolution: params={list(params.keys())}")+ params = await resolve_params_fn(params, node_id, nodes, edges, session_id)+ logger.debug(f"[NodeExecutor] After resolution: params keys={list(params.keys())}")++ # Build handler context+ handler_ctx = {+ **context,+ "start_time": start_time,+ "execution_id": execution_id,+ }+ logger.info("NodeExecutor context", node_id=node_id, workflow_id=context.get('workflow_id'))++ # Execute via registry or special handlers+ result = await self._dispatch(node_id, node_type, params, handler_ctx)+ result['execution_id'] = execution_id++ # Store output if successful+ if result.get('success') and self._output_store:+ output_data = result.get('result', {})++ # For Android service nodes, extract the nested 'data' field for cleaner template access+ # This allows {{batterymonitor.battery_level}} instead of {{batterymonitor.data.battery_level}}+ if node_type in ANDROID_SERVICE_NODE_TYPES and isinstance(output_data, dict):+ # Flatten: promote 'data' contents to top level while preserving metadata+ nested_data = output_data.get('data', {})+ if isinstance(nested_data, dict):+ # Merge nested data with metadata (service_id, action, timestamp, etc.)+ output_data = {**output_data, **nested_data}+ logger.debug(f"[NodeExecutor] Flattened Android output for {node_id}: keys={list(output_data.keys())}")++ await self._output_store(session_id, node_id, "output_0", output_data)++ return result++ except asyncio.CancelledError:+ return ExecutionResult(False, node_id, node_type, error="Cancelled",+ execution_id=execution_id, execution_time=time.time()-start_time).to_dict()+ except Exception as e:+ logger.error("Node execution error", node_id=node_id, error=str(e))+ return ExecutionResult(False, node_id, node_type, error=str(e),+ execution_id=execution_id, execution_time=time.time()-start_time).to_dict()++ async def _prepare_parameters(self, node_id: str, node_type: str, params: Dict, session_id: str) -> Dict:+ """Load from DB, validate, inject API keys."""+ # Merge with DB parameters (DB provides defaults, frontend can override)+ db_params = await self.database.get_node_parameters(node_id) or {}+ merged = {**db_params, **params} if params else db_params++ # Validate+ try:+ validated = validate_node_params(node_type, merged)+ merged = {**merged, **validated.model_dump(by_alias=True, exclude_unset=True)}+ except ValidationError as e:+ logger.warning("Validation warning", node_type=node_type, errors=str(e))++ # Inject API keys+ return await self._inject_api_keys(node_type, merged)++ async def _inject_api_keys(self, node_type: str, params: Dict) -> Dict:+ """Auto-inject API keys for AI and Maps nodes."""+ result = params.copy()++ if node_type in AI_MODEL_TYPES:+ provider = detect_ai_provider(node_type, params)+ if not result.get('api_key') and not result.get('apiKey'):+ key = await self.ai_service.auth.get_api_key(provider, "default")+ if key:+ result['api_key'] = key+ if not result.get('model'):+ models = await self.ai_service.auth.get_stored_models(provider, "default")+ if models:+ result['model'] = models[0]++ elif node_type in GOOGLE_MAPS_TYPES:+ if not result.get('api_key'):+ result['api_key'] = self.settings.google_maps_api_key++ return result++ async def _dispatch(self, node_id: str, node_type: str, params: Dict, context: Dict) -> Dict:+ """Dispatch to handler from registry or special handlers."""++ # Check registry first+ handler = self._handlers.get(node_type)+ if handler:+ return await handler(node_id, node_type, params, context)++ # Special handlers needing connected outputs+ if node_type in ('pythonExecutor', 'javascriptExecutor', 'webhookResponse'):+ outputs = await self._get_connected_outputs(context, node_id)+ handlers = {+ 'pythonExecutor': handle_python_executor,+ 'javascriptExecutor': handle_javascript_executor,+ 'webhookResponse': handle_webhook_response,+ }+ return await handlers[node_type](node_id, node_type, params, context, outputs)++ # Trigger nodes+ if event_waiter.is_trigger_node(node_type):+ return await handle_trigger_node(node_id, node_type, params, context)++ # Fallback+ return {+ "success": True,+ "node_id": node_id,+ "node_type": node_type,+ "result": {"message": f"Node {node_id} executed", "parameters": params},+ "execution_time": time.time() - context.get('start_time', time.time()),+ "timestamp": datetime.now().isoformat()+ }++ async def _get_connected_outputs(self, context: Dict, node_id: str) -> Dict[str, Any]:+ """Get outputs from connected upstream nodes."""+ get_output = context.get('get_output_fn')+ if not get_output:+ return {}++ nodes = context.get('nodes', [])+ edges = context.get('edges', [])+ session_id = context.get('session_id', 'default')+ result = {}++ for edge in edges:+ if edge.get('target') == node_id:+ source_id = edge.get('source')+ output = await get_output(session_id, source_id, "output_0")+ if output:+ source = next((n for n in nodes if n.get('id') == source_id), {})+ result[source.get('type', 'unknown')] = output++ return resultdiff --git a/server/services/parameter_resolver.py b/server/services/parameter_resolver.pynew file mode 100644index 00000000..6758a15c--- /dev/null+++ b/server/services/parameter_resolver.py@@ -0,0 +1,184 @@+"""Parameter Resolver - Template variable resolution.++Resolves {{node.field}} template variables in parameters using connected node outputs.+"""++import re+from typing import Dict, Any, List, Optional, Callable, TYPE_CHECKING++from core.logging import get_logger++if TYPE_CHECKING:+ from core.database import Database++logger = get_logger(__name__)++# Compiled regex for template matching+TEMPLATE_PATTERN = re.compile(r'\{\{([^}]+)\}\}')+++class ParameterResolver:+ """Resolves template variables in node parameters."""++ def __init__(self, database: "Database", get_output_fn: Callable):+ """+ Args:+ database: Database for loading node parameters+ get_output_fn: Async function to get node output+ Signature: async def (session_id, node_id, output_name) -> Dict+ """+ self.database = database+ self.get_output = get_output_fn++ async def resolve(+ self,+ parameters: Dict[str, Any],+ node_id: str,+ nodes: List[Dict],+ edges: List[Dict],+ session_id: str+ ) -> Dict[str, Any]:+ """Resolve all template variables in parameters."""+ # Build connected data map from upstream nodes+ connected_data = await self._gather_connected_outputs(node_id, nodes, edges, session_id)++ # Resolve templates+ return self._resolve_templates(parameters, connected_data)++ async def _gather_connected_outputs(+ self,+ node_id: str,+ nodes: List[Dict],+ edges: List[Dict],+ session_id: str+ ) -> Dict[str, Any]:+ """Gather outputs from all nodes in the workflow that have executed.++ n8n pattern: Template variables can reference ANY node's output in the workflow,+ not just directly connected nodes. This allows flexible data flow patterns like:+ - A -> B -> C where C references A's output directly+ - Parallel branches where downstream nodes reference any upstream node+ """+ connected = {}++ logger.debug(f"[ParameterResolver] Gathering outputs for node {node_id}, total nodes in workflow: {len(nodes)}")++ # Gather outputs from ALL nodes (not just directly connected)+ # This allows {{nodeName.field}} to reference any previously executed node+ for source_node in nodes:+ source_id = source_node.get('id')+ if source_id == node_id:+ continue # Skip self++ node_type = source_node.get('type', '')+ node_key = self._get_template_key(source_node)++ # Special handling for start nodes+ if node_type == 'start':+ data = await self._get_start_node_data(source_id)+ else:+ data = await self.get_output(session_id, source_id, "output_0")++ if data:+ connected[node_key] = data+ logger.debug(f"[ParameterResolver] Found output for {node_key} (type={node_type}): keys={list(data.keys()) if isinstance(data, dict) else type(data)}")++ logger.debug(f"[ParameterResolver] Available data keys for resolution: {list(connected.keys())}")+ return connected++ async def _get_start_node_data(self, node_id: str) -> Optional[Dict]:+ """Get initial data from start node parameters."""+ import json+ params = await self.database.get_node_parameters(node_id)+ if not params or 'initialData' not in params:+ return {}++ initial_data = params.get('initialData', '{}')+ try:+ return json.loads(initial_data) if isinstance(initial_data, str) else initial_data+ except Exception:+ return {}++ def _get_template_key(self, node: Dict) -> str:+ """Get template key for a node (lowercase, no spaces).++ Priority matches frontend useDragVariable hook:+ 1. node.data.label (user-defined label)+ 2. node.data.displayName (from node definition)+ 3. node.type (lowercased)+ 4. node.id (fallback)+ """+ # Priority 1: User-defined label+ label = node.get('data', {}).get('label')+ if label:+ return re.sub(r'\s+', '', label.lower())++ # Priority 2: displayName from node definition (passed in node.data)+ display_name = node.get('data', {}).get('displayName')+ if display_name:+ return re.sub(r'\s+', '', display_name.lower())++ # Priority 3: node type+ node_type = node.get('type', '')+ if node_type:+ return node_type.lower()++ # Priority 4: node id+ return node.get('id', 'unknown').lower()++ def _resolve_templates(self, parameters: Dict[str, Any], connected_data: Dict[str, Any]) -> Dict[str, Any]:+ """Resolve {{variable}} templates in parameters recursively."""+ # Case-insensitive lookup+ data_lower = {k.lower(): v for k, v in connected_data.items()}++ # Log template resolution context+ template_params = {k: v for k, v in parameters.items() if isinstance(v, str) and '{{' in v}+ if template_params:+ logger.info(f"[ParameterResolver] Resolving templates: params_with_templates={list(template_params.keys())}, available_nodes={list(data_lower.keys())}")++ def resolve(value: Any) -> Any:+ if isinstance(value, str) and '{{' in value:+ return self._resolve_string(value, data_lower)+ if isinstance(value, dict):+ return {k: resolve(v) for k, v in value.items()}+ if isinstance(value, list):+ return [resolve(item) for item in value]+ return value++ return {k: resolve(v) for k, v in parameters.items()}++ def _resolve_string(self, value: str, data: Dict[str, Any]) -> Any:+ """Resolve templates in a string value."""+ result = value++ for match in TEMPLATE_PATTERN.finditer(value):+ full_match = match.group(0)+ path = match.group(1).split('.')+ node_name = path[0].lower()+ property_path = path[1:]++ node_data = data.get(node_name)+ resolved_value = self._navigate_path(node_data, property_path)++ logger.debug(f"[ParameterResolver] Resolving '{full_match}': node_name={node_name}, path={property_path}, found_data={node_data is not None}, resolved={resolved_value is not None}")++ if resolved_value is not None:+ # If entire value is just the template, preserve type+ if value.strip() == full_match:+ return resolved_value+ result = result.replace(full_match, str(resolved_value))+ else:+ # Log missing resolution for debugging+ logger.debug(f"[ParameterResolver] Could not resolve '{full_match}': available keys={list(data.keys())}")+ result = result.replace(full_match, '')++ return result++ def _navigate_path(self, data: Any, path: List[str]) -> Any:+ """Navigate through nested dict using path parts."""+ current = data+ for part in path:+ if not isinstance(current, dict) or part not in current:+ return None+ current = current[part]+ return currentdiff --git a/server/services/scheduler.py b/server/services/scheduler.pynew file mode 100644index 00000000..faf4277d--- /dev/null+++ b/server/services/scheduler.py@@ -0,0 +1,155 @@+"""+Cron Scheduler Service using APScheduler.+Manages scheduled jobs for workflow automation.+"""+from apscheduler.schedulers.asyncio import AsyncIOScheduler+from apscheduler.triggers.cron import CronTrigger+from apscheduler.jobstores.base import JobLookupError+from typing import Callable, Dict, Optional+import logging++logger = logging.getLogger(__name__)++_scheduler: Optional[AsyncIOScheduler] = None+++def get_scheduler() -> AsyncIOScheduler:+ """Get or create the singleton scheduler instance."""+ global _scheduler+ if _scheduler is None:+ _scheduler = AsyncIOScheduler(timezone="UTC")+ return _scheduler+++def start_scheduler():+ """Start the scheduler if not already running."""+ scheduler = get_scheduler()+ if not scheduler.running:+ scheduler.start()+ logger.info("[Scheduler] Started")+++def shutdown_scheduler():+ """Shutdown the scheduler gracefully."""+ scheduler = get_scheduler()+ if scheduler.running:+ scheduler.shutdown(wait=False)+ logger.info("[Scheduler] Shutdown")+++def register_cron_job(+ job_id: str,+ cron_expression: str,+ callback: Callable,+ timezone: str = "UTC",+ **kwargs+) -> str:+ """+ Register a cron job with the scheduler.++ Args:+ job_id: Unique identifier for the job+ cron_expression: 6-field cron expression (second minute hour day month weekday)+ or 5-field (minute hour day month weekday)+ callback: Async function to call when job fires+ timezone: Timezone for schedule (default: UTC)+ **kwargs: Additional arguments passed to the callback++ Returns:+ The job_id+ """+ scheduler = get_scheduler()++ # Parse cron expression - support both 5-field and 6-field formats+ parts = cron_expression.split()++ if len(parts) >= 6:+ # 6-field format: second minute hour day month weekday+ trigger = CronTrigger(+ second=parts[0],+ minute=parts[1],+ hour=parts[2],+ day=parts[3],+ month=parts[4],+ day_of_week=parts[5],+ timezone=timezone+ )+ else:+ # 5-field format: minute hour day month weekday (default second=0)+ if len(parts) < 5:+ parts.extend(['*'] * (5 - len(parts)))+ trigger = CronTrigger(+ second='0',+ minute=parts[0],+ hour=parts[1],+ day=parts[2],+ month=parts[3],+ day_of_week=parts[4],+ timezone=timezone+ )++ scheduler.add_job(+ callback,+ trigger=trigger,+ id=job_id,+ replace_existing=True,+ kwargs=kwargs+ )++ logger.info(f"[Scheduler] Registered cron job: {job_id} with expression: {cron_expression}")+ return job_id+++def remove_cron_job(job_id: str) -> bool:+ """+ Remove a cron job from the scheduler.++ Args:+ job_id: The job identifier to remove++ Returns:+ True if job was removed, False if not found+ """+ scheduler = get_scheduler()+ try:+ scheduler.remove_job(job_id)+ logger.info(f"[Scheduler] Removed cron job: {job_id}")+ return True+ except JobLookupError:+ logger.warning(f"[Scheduler] Job not found: {job_id}")+ return False+++def get_job_info(job_id: str) -> Optional[Dict]:+ """+ Get information about a scheduled job.++ Args:+ job_id: The job identifier++ Returns:+ Dict with job info or None if not found+ """+ scheduler = get_scheduler()+ job = scheduler.get_job(job_id)+ if job:+ return {+ "id": job.id,+ "next_run_time": job.next_run_time.isoformat() if job.next_run_time else None,+ "trigger": str(job.trigger)+ }+ return None+++def get_all_jobs() -> list:+ """Get list of all scheduled jobs."""+ scheduler = get_scheduler()+ jobs = scheduler.get_jobs()+ return [+ {+ "id": job.id,+ "next_run_time": job.next_run_time.isoformat() if job.next_run_time else None,+ "trigger": str(job.trigger)+ }+ for job in jobs+ ]diff --git a/server/services/status_broadcaster.py b/server/services/status_broadcaster.pynew file mode 100644index 00000000..9fe73c88--- /dev/null+++ b/server/services/status_broadcaster.py@@ -0,0 +1,607 @@+"""WebSocket Status Broadcaster Service.++Manages WebSocket connections and broadcasts status updates to all connected clients.+Supports all node types, variable updates, and workflow state changes.+"""++import asyncio+import json+import orjson+from typing import Set, Dict, Any, Optional, List+from fastapi import WebSocket+from core.logging import get_logger++logger = get_logger(__name__)+++class StatusBroadcaster:+ """Manages WebSocket connections and broadcasts status updates."""++ def __init__(self):+ self._connections: Set[WebSocket] = set()+ self._lock = asyncio.Lock()++ # Current state for all status types+ self._status: Dict[str, Any] = {+ "android": {+ "connected": False,+ "paired": False,+ "device_id": None,+ "device_name": None,+ "connected_devices": [],+ "connection_type": None,+ "qr_data": None,+ "session_token": None+ },+ "whatsapp": {+ "connected": False,+ "has_session": False,+ "running": False,+ "pairing": False,+ "device_id": None,+ "qr": None+ },+ "api_keys": {}, # provider -> validation status+ "nodes": {}, # node_id -> node status+ "variables": {}, # variable_name -> value+ "workflow": {+ "executing": False,+ "current_node": None+ },+ "workflow_lock": {+ "locked": False,+ "workflow_id": None,+ "locked_at": None,+ "reason": None+ },+ "deployment": {+ "isRunning": False,+ "activeRuns": 0,+ "status": "idle",+ "workflow_id": None+ }+ }++ async def connect(self, websocket: WebSocket):+ """Accept a new WebSocket connection."""+ await websocket.accept()+ async with self._lock:+ self._connections.add(websocket)+ logger.info(f"[StatusBroadcaster] Client connected. Total: {len(self._connections)}")++ # Send current full status immediately+ try:+ await websocket.send_json({+ "type": "initial_status",+ "data": self._status+ })+ except Exception as e:+ logger.error(f"[StatusBroadcaster] Failed to send initial status: {e}")++ async def disconnect(self, websocket: WebSocket):+ """Remove a WebSocket connection."""+ async with self._lock:+ self._connections.discard(websocket)+ logger.info(f"[StatusBroadcaster] Client disconnected. Total: {len(self._connections)}")++ async def broadcast(self, message: Dict[str, Any]):+ """Broadcast a message to all connected clients using TaskGroup.++ Uses asyncio.TaskGroup (Python 3.11+) for structured concurrency:+ - All tasks complete or cancel together+ - Proper exception handling via ExceptionGroup+ """+ if not self._connections:+ return++ # Get connections list while holding lock+ async with self._lock:+ connections_list = list(self._connections)++ if not connections_list:+ return++ message_bytes = orjson.dumps(message).decode()+ disconnected: set[WebSocket] = set()++ async def send_to_client(connection: WebSocket):+ """Send message to a single client."""+ try:+ await connection.send_text(message_bytes)+ except Exception as e:+ logger.warning(f"[StatusBroadcaster] Send failed: {e}")+ disconnected.add(connection)++ # Execute all sends concurrently with TaskGroup+ try:+ async with asyncio.TaskGroup() as tg:+ for conn in connections_list:+ tg.create_task(send_to_client(conn))+ except* Exception as eg:+ # TaskGroup aggregates exceptions - log them but continue+ for exc in eg.exceptions:+ logger.warning(f"[StatusBroadcaster] TaskGroup exception: {exc}")++ # Remove failed connections+ if disconnected:+ async with self._lock:+ self._connections -= disconnected++ # =========================================================================+ # API Key Validation Status Updates+ # =========================================================================++ async def update_api_key_status(+ self,+ provider: str,+ valid: bool,+ message: Optional[str] = None,+ has_key: bool = True,+ models: Optional[List[str]] = None+ ):+ """Update API key validation status and broadcast."""+ self._status["api_keys"][provider] = {+ "valid": valid,+ "hasKey": has_key,+ "message": message,+ "models": models or [],+ "timestamp": asyncio.get_event_loop().time()+ }++ await self.broadcast({+ "type": "api_key_status",+ "provider": provider,+ "data": self._status["api_keys"][provider]+ })++ def get_api_key_status(self, provider: str) -> Optional[Dict[str, Any]]:+ """Get API key validation status for a provider."""+ return self._status["api_keys"].get(provider)++ # =========================================================================+ # Android Status Updates+ # =========================================================================++ async def update_android_status(+ self,+ connected: bool,+ paired: bool = False,+ device_id: Optional[str] = None,+ device_name: Optional[str] = None,+ connected_devices: Optional[List[str]] = None,+ connection_type: Optional[str] = None,+ qr_data: Optional[str] = None,+ session_token: Optional[str] = None+ ):+ """Update Android relay connection status and broadcast."""+ self._status["android"] = {+ "connected": connected,+ "paired": paired,+ "device_id": device_id,+ "device_name": device_name,+ "connected_devices": connected_devices or [],+ "connection_type": connection_type,+ "qr_data": qr_data,+ "session_token": session_token+ }++ await self.broadcast({+ "type": "android_status",+ "data": self._status["android"]+ })++ # =========================================================================+ # WhatsApp Status Updates+ # =========================================================================++ async def update_whatsapp_status(+ self,+ connected: bool,+ has_session: bool = False,+ running: bool = False,+ pairing: bool = False,+ device_id: Optional[str] = None,+ qr: Optional[str] = None+ ):+ """Update WhatsApp connection status and broadcast."""+ import time+ self._status["whatsapp"] = {+ "connected": connected,+ "has_session": has_session,+ "running": running,+ "pairing": pairing,+ "device_id": device_id,+ "qr": qr,+ "timestamp": time.time()+ }++ await self.broadcast({+ "type": "whatsapp_status",+ "data": self._status["whatsapp"]+ })++ def get_whatsapp_status(self) -> Dict[str, Any]:+ """Get WhatsApp connection status."""+ return self._status["whatsapp"].copy()++ # =========================================================================+ # Node Status Updates+ # =========================================================================++ async def update_node_status(+ self,+ node_id: str,+ status: str, # "idle", "executing", "waiting", "success", "error"+ data: Optional[Dict[str, Any]] = None,+ workflow_id: Optional[str] = None+ ):+ """Update a specific node's status and broadcast.++ Args:+ node_id: The node ID+ status: Status string+ data: Optional status data+ workflow_id: Optional workflow ID to scope the status update (n8n pattern)+ """+ print(f"[BROADCAST] update_node_status: node={node_id}, status={status}, workflow={workflow_id}, connections={len(self._connections)}")+ self._status["nodes"][node_id] = {+ "status": status,+ "data": data or {},+ "timestamp": asyncio.get_event_loop().time(),+ "workflow_id": workflow_id+ }++ await self.broadcast({+ "type": "node_status",+ "node_id": node_id,+ "workflow_id": workflow_id,+ "data": self._status["nodes"][node_id]+ })++ async def update_node_output(+ self,+ node_id: str,+ output: Any,+ workflow_id: Optional[str] = None+ ):+ """Update a node's output data and broadcast."""+ if node_id not in self._status["nodes"]:+ self._status["nodes"][node_id] = {"status": "idle", "data": {}}++ self._status["nodes"][node_id]["output"] = output+ if workflow_id:+ self._status["nodes"][node_id]["workflow_id"] = workflow_id++ await self.broadcast({+ "type": "node_output",+ "node_id": node_id,+ "workflow_id": workflow_id,+ "output": output+ })++ # =========================================================================+ # Variable Updates+ # =========================================================================++ async def update_variable(self, name: str, value: Any):+ """Update a workflow variable and broadcast."""+ self._status["variables"][name] = value++ await self.broadcast({+ "type": "variable_update",+ "name": name,+ "value": value+ })++ async def update_variables(self, variables: Dict[str, Any]):+ """Update multiple variables at once and broadcast."""+ self._status["variables"].update(variables)++ await self.broadcast({+ "type": "variables_update",+ "variables": variables+ })++ # =========================================================================+ # Workflow Status Updates+ # =========================================================================++ async def update_workflow_status(+ self,+ executing: bool,+ current_node: Optional[str] = None,+ progress: Optional[float] = None+ ):+ """Update workflow execution status and broadcast."""+ self._status["workflow"] = {+ "executing": executing,+ "current_node": current_node,+ "progress": progress+ }++ await self.broadcast({+ "type": "workflow_status",+ "data": self._status["workflow"]+ })++ async def update_deployment_status(+ self,+ is_running: bool,+ status: str = "idle",+ active_runs: int = 0,+ workflow_id: Optional[str] = None,+ data: Optional[Dict[str, Any]] = None,+ error: Optional[str] = None+ ):+ """Update deployment status and broadcast.++ Follows n8n/Conductor pattern where deployment state is tracked centrally.+ See DESIGN.md for architecture details.++ Args:+ is_running: Whether deployment is active+ status: Current status (idle, starting, running, stopped, cancelled, error)+ active_runs: Number of concurrent execution runs+ workflow_id: The deployed workflow ID+ data: Optional additional data (e.g., run_id, trigger info)+ error: Optional error message if status is 'error'+ """+ self._status["deployment"] = {+ "isRunning": is_running,+ "activeRuns": active_runs,+ "status": status,+ "workflow_id": workflow_id+ }++ # Broadcast deployment_status message (matches frontend handler)+ await self.broadcast({+ "type": "deployment_status",+ "status": status,+ "workflow_id": workflow_id,+ "data": data,+ "error": error+ })++ # =========================================================================+ # Workflow Lock Management (Per-Workflow Locks - n8n pattern)+ # =========================================================================++ async def lock_workflow(+ self,+ workflow_id: str,+ reason: str = "deployment"+ ) -> bool:+ """Lock a specific workflow to prevent concurrent modifications.++ Per-workflow locking (n8n pattern): Each workflow has its own independent lock.+ Multiple workflows can be locked simultaneously.++ Args:+ workflow_id: The workflow ID to lock+ reason: Reason for locking (e.g., "deployment", "execution")++ Returns:+ True if lock acquired, False if THIS workflow is already locked+ """+ import time++ # Initialize workflow_locks if not present+ if "workflow_locks" not in self._status:+ self._status["workflow_locks"] = {}++ # Check if THIS workflow is already locked+ if workflow_id in self._status["workflow_locks"]:+ existing_lock = self._status["workflow_locks"][workflow_id]+ if existing_lock.get("locked"):+ logger.warning(+ f"[WorkflowLock] Workflow {workflow_id} is already locked "+ f"for {existing_lock.get('reason')}"+ )+ return False++ # Lock this specific workflow+ lock_info = {+ "locked": True,+ "workflow_id": workflow_id,+ "locked_at": time.time(),+ "reason": reason+ }+ self._status["workflow_locks"][workflow_id] = lock_info++ # Also update legacy single lock for backward compatibility+ self._status["workflow_lock"] = lock_info.copy()++ await self.broadcast({+ "type": "workflow_lock",+ "workflow_id": workflow_id,+ "data": lock_info+ })++ logger.info(f"[WorkflowLock] Locked workflow {workflow_id} for {reason}")+ return True++ async def unlock_workflow(self, workflow_id: str) -> bool:+ """Unlock a specific workflow after deployment/execution completes.++ Args:+ workflow_id: The workflow ID to unlock++ Returns:+ True if unlocked successfully+ """+ # Initialize workflow_locks if not present+ if "workflow_locks" not in self._status:+ self._status["workflow_locks"] = {}++ # Check if this workflow is locked+ if workflow_id not in self._status["workflow_locks"]:+ logger.debug(f"[WorkflowLock] Workflow {workflow_id} not locked")+ return True # Already unlocked++ existing_lock = self._status["workflow_locks"].get(workflow_id, {})+ if not existing_lock.get("locked"):+ logger.debug(f"[WorkflowLock] Workflow {workflow_id} not locked")+ return True++ # Remove lock for this workflow+ del self._status["workflow_locks"][workflow_id]++ # Update legacy single lock if it was for this workflow+ if self._status["workflow_lock"].get("workflow_id") == workflow_id:+ self._status["workflow_lock"] = {+ "locked": False,+ "workflow_id": None,+ "locked_at": None,+ "reason": None+ }++ await self.broadcast({+ "type": "workflow_lock",+ "workflow_id": workflow_id,+ "data": {+ "locked": False,+ "workflow_id": workflow_id,+ "locked_at": None,+ "reason": None+ }+ })++ logger.info(f"[WorkflowLock] Unlocked workflow {workflow_id}")+ return True++ def is_workflow_locked(self, workflow_id: Optional[str] = None) -> bool:+ """Check if a specific workflow is locked.++ Args:+ workflow_id: Workflow ID to check. If None, checks if any workflow is locked.++ Returns:+ True if the specified workflow is locked (or any if workflow_id is None)+ """+ # Initialize workflow_locks if not present+ if "workflow_locks" not in self._status:+ self._status["workflow_locks"] = {}++ if workflow_id is None:+ # Check if ANY workflow is locked+ return any(+ lock.get("locked", False)+ for lock in self._status["workflow_locks"].values()+ )++ # Check specific workflow+ lock = self._status["workflow_locks"].get(workflow_id, {})+ return lock.get("locked", False)++ def get_workflow_lock(self, workflow_id: Optional[str] = None) -> Dict[str, Any]:+ """Get workflow lock status.++ Args:+ workflow_id: Specific workflow to check. If None, returns legacy single lock.++ Returns:+ Lock info for the specified workflow or legacy lock+ """+ if workflow_id:+ # Initialize workflow_locks if not present+ if "workflow_locks" not in self._status:+ self._status["workflow_locks"] = {}++ lock = self._status["workflow_locks"].get(workflow_id, {})+ return {+ "locked": lock.get("locked", False),+ "workflow_id": workflow_id,+ "locked_at": lock.get("locked_at"),+ "reason": lock.get("reason")+ }++ # Return legacy single lock for backward compatibility+ return self._status["workflow_lock"].copy()++ def get_all_workflow_locks(self) -> Dict[str, Dict[str, Any]]:+ """Get all active workflow locks."""+ if "workflow_locks" not in self._status:+ return {}+ return {+ wid: lock.copy()+ for wid, lock in self._status["workflow_locks"].items()+ if lock.get("locked")+ }++ # =========================================================================+ # Generic Updates+ # =========================================================================++ async def send_custom_event(self, event_type: str, data: Any):+ """Send a custom event to all connected clients AND dispatch to event waiters.++ Uses dispatch_async() directly since we're in an async context.+ The sync dispatch() is for thread contexts like APScheduler callbacks.+ See DESIGN.md section "Cross-Thread Event Dispatch" for pattern details.+ """+ # Broadcast to all WebSocket clients+ await self.broadcast({+ "type": event_type,+ "data": data+ })++ # Dispatch to event waiters (for trigger nodes)+ # Use dispatch_async directly - we're in async context+ try:+ from services import event_waiter+ event_data = data if isinstance(data, dict) else {"data": data}+ resolved_count = await event_waiter.dispatch_async(event_type, event_data)+ if resolved_count > 0:+ logger.info(f"[StatusBroadcaster] Event {event_type} resolved {resolved_count} waiters")+ except Exception as e:+ logger.error(f"[StatusBroadcaster] Failed to dispatch to event waiters: {e}")++ # =========================================================================+ # Getters+ # =========================================================================++ def get_status(self) -> Dict[str, Any]:+ """Get the full current status."""+ return self._status.copy()++ def get_android_status(self) -> Dict[str, Any]:+ """Get Android connection status."""+ return self._status["android"].copy()++ def get_node_status(self, node_id: str) -> Optional[Dict[str, Any]]:+ """Get a specific node's status."""+ return self._status["nodes"].get(node_id)++ async def clear_node_status(self, node_id: str) -> bool:+ """Clear a node's status and output from the cache."""+ if node_id in self._status["nodes"]:+ del self._status["nodes"][node_id]+ logger.info(f"[StatusBroadcaster] Cleared node status: {node_id}")+ # Broadcast that node status was cleared+ await self.broadcast({+ "type": "node_status_cleared",+ "node_id": node_id+ })+ return True+ return False++ def get_variable(self, name: str) -> Any:+ """Get a variable value."""+ return self._status["variables"].get(name)++ @property+ def connection_count(self) -> int:+ """Get the number of active WebSocket connections."""+ return len(self._connections)+++# Global singleton instance+_broadcaster: Optional[StatusBroadcaster] = None+++def get_status_broadcaster() -> StatusBroadcaster:+ """Get or create the global StatusBroadcaster instance."""+ global _broadcaster+ if _broadcaster is None:+ _broadcaster = StatusBroadcaster()+ return _broadcasterdiff --git a/server/services/text.py b/server/services/text.pynew file mode 100644index 00000000..e1a42c95--- /dev/null+++ b/server/services/text.py@@ -0,0 +1,111 @@+"""Text generation service."""++import time+from datetime import datetime+from typing import Dict, Any++from core.logging import get_logger, log_execution_time++logger = get_logger(__name__)+++class TextService:+ """Text generation and processing service."""++ def __init__(self):+ pass++ async def execute_text_generator(self, node_id: str, parameters: Dict[str, Any]) -> Dict[str, Any]:+ """Execute text generator node (migrated from Node.js)."""+ start_time = time.time()++ try:+ text = parameters.get('text', 'Hello World')+ include_timestamp = parameters.get('includeTimestamp', True)++ result_data = {+ "text": text,+ "length": len(text),+ "nodeId": node_id+ }++ if include_timestamp:+ result_data["timestamp"] = datetime.now().isoformat()++ result = {+ "type": "text",+ "data": result_data,+ "nodeId": node_id,+ "timestamp": datetime.now().isoformat()+ }++ log_execution_time(logger, "text_generator", start_time, time.time())++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "textGenerator",+ "result": result,+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ except Exception as e:+ logger.error("Text generator execution failed", node_id=node_id, error=str(e))+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "textGenerator",+ "error": str(e),+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ async def execute_file_handler(self, node_id: str, parameters: Dict[str, Any]) -> Dict[str, Any]:+ """Execute file handler node (migrated from Node.js)."""+ start_time = time.time()++ try:+ file_type = parameters.get('fileType', 'generic')+ file_content = parameters.get('content', '')+ file_name = parameters.get('fileName', 'untitled.txt')++ # Basic file processing+ result_data = {+ "fileName": file_name,+ "fileType": file_type,+ "content": file_content,+ "size": len(file_content),+ "processed": True,+ "processingType": file_type,+ "nodeId": node_id+ }++ result = {+ "type": "file",+ "data": result_data,+ "nodeId": node_id,+ "timestamp": datetime.now().isoformat()+ }++ log_execution_time(logger, "file_handler", start_time, time.time())++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "fileHandler",+ "result": result,+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ except Exception as e:+ logger.error("File handler execution failed", node_id=node_id, error=str(e))+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "fileHandler",+ "error": str(e),+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }\ No newline at end of filediff --git a/server/services/user_auth.py b/server/services/user_auth.pynew file mode 100644index 00000000..b2343b42--- /dev/null+++ b/server/services/user_auth.py@@ -0,0 +1,172 @@+"""User authentication service with JWT handling."""++import logging+from datetime import datetime, timezone, timedelta+from typing import Optional, Dict, Any++from jose import jwt, JWTError+from sqlmodel import select++from core.config import Settings+from core.database import Database+from models.auth import User++logger = logging.getLogger(__name__)+++class UserAuthService:+ """Handles user authentication, registration, and JWT token management."""++ def __init__(self, database: Database, settings: Settings):+ self.database = database+ self.settings = settings+ self._algorithm = "HS256"++ async def get_user_count(self) -> int:+ """Get total number of users."""+ async with self.database.get_session() as session:+ result = await session.execute(select(User))+ return len(result.scalars().all())++ async def get_user_by_email(self, email: str) -> Optional[User]:+ """Get user by email address."""+ async with self.database.get_session() as session:+ result = await session.execute(+ select(User).where(User.email == email.lower().strip())+ )+ return result.scalars().first()++ async def get_user_by_id(self, user_id: int) -> Optional[User]:+ """Get user by ID."""+ async with self.database.get_session() as session:+ result = await session.execute(+ select(User).where(User.id == user_id)+ )+ return result.scalars().first()++ async def can_register(self) -> bool:+ """Check if registration is allowed based on auth mode."""+ if self.settings.auth_mode == "multi":+ return True+ # Single-owner mode: only allow if no users exist+ count = await self.get_user_count()+ return count == 0++ async def register(+ self, email: str, password: str, display_name: str+ ) -> tuple[Optional[User], Optional[str]]:+ """+ Register a new user.+ Returns (user, None) on success, (None, error_message) on failure.+ """+ # Check if registration is allowed+ if not await self.can_register():+ if self.settings.auth_mode == "single":+ return None, "Registration disabled - owner account already exists"+ return None, "Registration is currently disabled"++ # Check if email already exists+ existing = await self.get_user_by_email(email)+ if existing:+ return None, "Email already registered"++ # Validate password strength+ if len(password) < 8:+ return None, "Password must be at least 8 characters"++ # Determine if this is the owner (first user in single-owner mode)+ is_owner = self.settings.auth_mode == "single" and await self.get_user_count() == 0++ # Create user+ user = User.create(+ email=email,+ password=password,+ display_name=display_name,+ is_owner=is_owner+ )++ async with self.database.get_session() as session:+ session.add(user)+ await session.commit()+ await session.refresh(user)++ logger.info(f"User registered: {email} (owner={is_owner})")+ return user, None++ async def login(+ self, email: str, password: str+ ) -> tuple[Optional[User], Optional[str]]:+ """+ Authenticate user and return user object.+ Returns (user, None) on success, (None, error_message) on failure.+ """+ user = await self.get_user_by_email(email)+ if not user:+ return None, "Invalid email or password"++ if not user.is_active:+ return None, "Account is disabled"++ if not user.verify_password(password):+ return None, "Invalid email or password"++ # Update last login+ async with self.database.get_session() as session:+ result = await session.execute(+ select(User).where(User.id == user.id)+ )+ db_user = result.scalars().first()+ if db_user:+ db_user.last_login = datetime.now(timezone.utc)+ await session.commit()++ logger.info(f"User logged in: {email}")+ return user, None++ def create_access_token(self, user: User) -> str:+ """Create JWT access token for user."""+ expire = datetime.now(timezone.utc) + timedelta(minutes=self.settings.jwt_expire_minutes)+ payload = {+ "sub": str(user.id),+ "email": user.email,+ "display_name": user.display_name,+ "is_owner": user.is_owner,+ "exp": expire,+ "iat": datetime.now(timezone.utc)+ }+ return jwt.encode(payload, self.settings.jwt_secret_key, algorithm=self._algorithm)++ def verify_token(self, token: str) -> Optional[Dict[str, Any]]:+ """+ Verify JWT token and return payload.+ Returns None if token is invalid or expired.+ """+ try:+ payload = jwt.decode(+ token,+ self.settings.jwt_secret_key,+ algorithms=[self._algorithm]+ )+ return payload+ except JWTError as e:+ logger.debug(f"Token verification failed: {e}")+ return None++ async def get_current_user(self, token: str) -> Optional[User]:+ """Get current user from token."""+ payload = self.verify_token(token)+ if not payload:+ return None++ user_id = payload.get("sub")+ if not user_id:+ return None++ return await self.get_user_by_id(int(user_id))++ def get_auth_status(self) -> Dict[str, Any]:+ """Get authentication status and mode info."""+ return {+ "auth_mode": self.settings.auth_mode,+ "registration_enabled": self.settings.auth_mode == "multi"+ }diff --git a/server/services/websocket_client.py b/server/services/websocket_client.pynew file mode 100644index 00000000..7fb1cefd--- /dev/null+++ b/server/services/websocket_client.py@@ -0,0 +1,29 @@+"""+Android WebSocket Client - DEPRECATED++This module is deprecated. Use services.android instead:++ from services.android import (+ RelayWebSocketClient,+ get_relay_client,+ close_relay_client,+ get_current_relay_client,+ )++This file re-exports from the new module for backwards compatibility.+"""++from services.android import (+ RelayWebSocketClient,+ get_relay_client,+ close_relay_client,+ get_current_relay_client,+)++# Re-export for backwards compatibility+__all__ = [+ "RelayWebSocketClient",+ "get_relay_client",+ "close_relay_client",+ "get_current_relay_client",+]diff --git a/server/services/workflow.py b/server/services/workflow.pynew file mode 100644index 00000000..2f2ab4d9--- /dev/null+++ b/server/services/workflow.py@@ -0,0 +1,522 @@+"""Workflow Service - Facade for workflow execution and deployment.++This is a thin facade that delegates to specialized modules:+- NodeExecutor: Single node execution+- ParameterResolver: Template variable resolution+- DeploymentManager: Event-driven deployment lifecycle+- WorkflowExecutor: Parallel/sequential orchestration++Following n8n/Conductor patterns for clean separation of concerns.+"""++import time+from datetime import datetime+from typing import Dict, Any, List, Optional, TYPE_CHECKING++from core.logging import get_logger+from constants import WORKFLOW_TRIGGER_TYPES+from services.node_executor import NodeExecutor+from services.parameter_resolver import ParameterResolver+from services.deployment import DeploymentManager+from services.execution import WorkflowExecutor, ExecutionCache++if TYPE_CHECKING:+ from core.config import Settings+ from core.database import Database+ from core.cache import CacheService+ from services.ai import AIService+ from services.maps import MapsService+ from services.text import TextService+ from services.android_service import AndroidService++logger = get_logger(__name__)+++class WorkflowService:+ """Workflow execution and deployment service.++ Thin facade delegating to specialized modules for:+ - Node execution (NodeExecutor)+ - Parameter resolution (ParameterResolver)+ - Deployment lifecycle (DeploymentManager)+ - Workflow orchestration (WorkflowExecutor)+ """++ def __init__(+ self,+ database: "Database",+ ai_service: "AIService",+ maps_service: "MapsService",+ text_service: "TextService",+ android_service: "AndroidService",+ cache: "CacheService",+ settings: "Settings",+ ):+ self.database = database+ self.settings = settings++ # In-memory output storage (fast access during execution)+ self._outputs: Dict[str, Dict[str, Any]] = {}++ # Initialize NodeExecutor+ self._node_executor = NodeExecutor(+ database=database,+ ai_service=ai_service,+ maps_service=maps_service,+ text_service=text_service,+ android_service=android_service,+ settings=settings,+ output_store=self.store_node_output,+ )++ # Initialize ParameterResolver+ self._param_resolver = ParameterResolver(+ database=database,+ get_output_fn=self.get_node_output,+ )++ # Initialize Execution Cache+ self._execution_cache = ExecutionCache(cache)+ self._workflow_executor: Optional[WorkflowExecutor] = None++ # Initialize DeploymentManager (lazy - needs broadcaster)+ self._deployment_manager: Optional[DeploymentManager] = None+ self._broadcaster = None++ # Deployment settings+ self._settings = {+ "stop_on_error": False,+ "max_concurrent_runs": 100,+ "use_parallel_executor": True,+ }++ def _get_deployment_manager(self) -> DeploymentManager:+ """Get or create DeploymentManager."""+ if self._deployment_manager is None:+ from services.status_broadcaster import get_status_broadcaster+ self._broadcaster = get_status_broadcaster()+ self._deployment_manager = DeploymentManager(+ database=self.database,+ execute_workflow_fn=self.execute_workflow,+ store_output_fn=self.store_node_output,+ broadcaster=self._broadcaster,+ )+ return self._deployment_manager++ def _get_workflow_executor(self, status_callback=None) -> WorkflowExecutor:+ """Get or create WorkflowExecutor."""+ if self._workflow_executor is None or status_callback:+ self._workflow_executor = WorkflowExecutor(+ cache=self._execution_cache,+ node_executor=self._execute_node_adapter,+ status_callback=status_callback,+ dlq_enabled=self.settings.dlq_enabled,+ )+ return self._workflow_executor++ # =========================================================================+ # NODE EXECUTION+ # =========================================================================++ async def execute_node(+ self,+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ nodes: List[Dict] = None,+ edges: List[Dict] = None,+ session_id: str = "default",+ execution_id: str = None,+ workflow_id: str = None,+ ) -> Dict[str, Any]:+ """Execute a single workflow node."""+ context = {+ "nodes": nodes,+ "edges": edges,+ "session_id": session_id,+ "execution_id": execution_id,+ "workflow_id": workflow_id, # For per-workflow status scoping (n8n pattern)+ "get_output_fn": self.get_node_output,+ }+ return await self._node_executor.execute(+ node_id=node_id,+ node_type=node_type,+ parameters=parameters,+ context=context,+ resolve_params_fn=self._param_resolver.resolve,+ )++ async def _execute_node_adapter(+ self,+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any],+ ) -> Dict[str, Any]:+ """Adapter for WorkflowExecutor to call NodeExecutor."""+ return await self.execute_node(+ node_id=node_id,+ node_type=node_type,+ parameters=parameters,+ nodes=context.get("nodes"),+ edges=context.get("edges"),+ session_id=context.get("session_id", "default"),+ execution_id=context.get("execution_id"),+ workflow_id=context.get("workflow_id"), # Pass workflow_id for status scoping+ )++ # =========================================================================+ # WORKFLOW EXECUTION+ # =========================================================================++ async def execute_workflow(+ self,+ nodes: List[Dict],+ edges: List[Dict],+ session_id: str = "default",+ status_callback=None,+ use_parallel: bool = None,+ skip_clear_outputs: bool = False,+ workflow_id: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Execute entire workflow.++ Args:+ nodes: Workflow nodes+ edges: Workflow edges+ session_id: Session identifier+ status_callback: Status update callback+ use_parallel: Force parallel/sequential execution+ skip_clear_outputs: Skip clearing outputs (for deployment runs)+ workflow_id: Workflow ID for per-workflow status scoping (n8n pattern)+ """+ start_time = time.time()++ # Clear outputs unless skipped+ if not skip_clear_outputs:+ await self.clear_all_outputs(session_id)++ if not nodes:+ return self._error_result("No nodes in workflow", start_time)++ # Find start node+ start_node = self._find_start_node(nodes)+ if not start_node:+ return self._error_result("No start node found", start_time)++ # Determine execution mode+ if use_parallel is None:+ use_parallel = self._settings.get("use_parallel_executor", True)++ # Use parallel executor if enabled and Redis available+ if use_parallel and self.settings.redis_enabled:+ return await self._execute_parallel(nodes, edges, session_id, status_callback, start_time, workflow_id)++ # Fall back to sequential+ return await self._execute_sequential(nodes, edges, session_id, status_callback, start_time, workflow_id)++ async def _execute_parallel(self, nodes, edges, session_id, status_callback, start_time, workflow_id: Optional[str] = None) -> Dict:+ """Execute with parallel orchestration engine."""+ # Use passed workflow_id (from deployment) or generate new one+ if not workflow_id:+ workflow_id = f"workflow_{session_id}_{int(time.time() * 1000)}"+ executor = self._get_workflow_executor(status_callback)++ result = await executor.execute_workflow(+ workflow_id=workflow_id,+ nodes=nodes,+ edges=edges,+ session_id=session_id,+ enable_caching=True,+ )++ return {+ "success": result.get("success", False),+ "execution_id": result.get("execution_id"),+ "nodes_executed": result.get("nodes_executed", []),+ "outputs": result.get("outputs", {}),+ "errors": result.get("errors", []),+ "execution_time": result.get("execution_time", time.time() - start_time),+ "parallel_execution": True,+ "timestamp": datetime.now().isoformat(),+ }++ async def _execute_sequential(self, nodes, edges, session_id, status_callback, start_time, workflow_id: Optional[str] = None) -> Dict:+ """Execute nodes sequentially (fallback mode)."""+ start_node = self._find_start_node(nodes)+ execution_order = self._build_execution_order(start_node, nodes, edges)++ results = {}+ executed = []++ for node in execution_order:+ node_id = node['id']+ node_type = node.get('type', 'unknown')++ # Skip pre-executed trigger nodes+ if node.get('_pre_executed'):+ executed.append(node_id)+ continue++ # Skip disabled nodes (n8n-style disable)+ if node.get('data', {}).get('disabled'):+ logger.debug(f"Skipping disabled node: {node_id}")+ executed.append(node_id)+ if status_callback:+ try:+ await status_callback(node_id, "skipped", {"disabled": True})+ except Exception:+ pass+ continue++ # Notify executing+ if status_callback:+ try:+ await status_callback(node_id, "executing", {})+ except Exception:+ pass++ # Execute with workflow_id for per-workflow status scoping (n8n pattern)+ result = await self.execute_node(+ node_id=node_id,+ node_type=node_type,+ parameters={},+ nodes=nodes,+ edges=edges,+ session_id=session_id,+ workflow_id=workflow_id,+ )++ results[node_id] = result+ executed.append(node_id)++ # Notify completed+ if status_callback:+ status = "completed" if result.get("success") else "error"+ try:+ await status_callback(node_id, status, result)+ except Exception:+ pass++ if not result.get("success") and self._settings.get("stop_on_error"):+ break++ return {+ "success": all(r.get("success", False) for r in results.values()),+ "nodes_executed": executed,+ "node_results": results,+ "execution_time": time.time() - start_time,+ "parallel_execution": False,+ "timestamp": datetime.now().isoformat(),+ }++ # =========================================================================+ # DEPLOYMENT+ # =========================================================================++ async def deploy_workflow(+ self,+ nodes: List[Dict],+ edges: List[Dict],+ session_id: str = "default",+ status_callback=None,+ workflow_id: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Deploy workflow in event-driven mode.++ Args:+ nodes: Workflow nodes+ edges: Workflow edges+ session_id: Session identifier+ status_callback: Status update callback+ workflow_id: Workflow ID for per-workflow deployment tracking+ """+ manager = self._get_deployment_manager()+ return await manager.deploy(nodes, edges, session_id, status_callback, workflow_id)++ async def cancel_deployment(self, workflow_id: Optional[str] = None) -> Dict[str, Any]:+ """Cancel active deployment.++ Args:+ workflow_id: Specific workflow to cancel. If None, cancels first running deployment.+ """+ manager = self._get_deployment_manager()+ return await manager.cancel(workflow_id)++ def get_deployment_status(self, workflow_id: Optional[str] = None) -> Dict[str, Any]:+ """Get deployment status.++ Args:+ workflow_id: Get status for specific workflow. If None, returns global status.+ """+ manager = self._get_deployment_manager()+ return manager.get_status(workflow_id)++ def is_deployment_running(self, workflow_id: Optional[str] = None) -> bool:+ """Check if deployment is running.++ Args:+ workflow_id: Check specific workflow. If None, checks if ANY deployment is running.+ """+ manager = self._get_deployment_manager()+ if workflow_id:+ return manager.is_workflow_deployed(workflow_id)+ return manager.is_running++ def is_workflow_deployed(self, workflow_id: str) -> bool:+ """Check if a specific workflow is deployed."""+ return self._get_deployment_manager().is_workflow_deployed(workflow_id)++ def get_deployed_workflows(self) -> List[str]:+ """Get list of deployed workflow IDs."""+ return self._get_deployment_manager().get_deployed_workflows()++ # =========================================================================+ # OUTPUT STORAGE+ # =========================================================================++ async def store_node_output(+ self,+ session_id: str,+ node_id: str,+ output_name: str,+ data: Dict[str, Any],+ ) -> None:+ """Store node execution output."""+ key = f"{session_id}_{node_id}"+ if key not in self._outputs:+ self._outputs[key] = {}+ self._outputs[key][output_name] = data+ await self.database.save_node_output(node_id, session_id, output_name, data)++ async def get_node_output(+ self,+ session_id: str,+ node_id: str,+ output_name: str,+ ) -> Optional[Dict[str, Any]]:+ """Get stored node output."""+ key = f"{session_id}_{node_id}"+ output = self._outputs.get(key, {}).get(output_name)++ if output is None:+ output = await self.database.get_node_output(node_id, session_id, output_name)+ if output:+ if key not in self._outputs:+ self._outputs[key] = {}+ self._outputs[key][output_name] = output++ # Special handling for start nodes+ if output is None and node_id.startswith('start-'):+ import json+ params = await self.database.get_node_parameters(node_id)+ if params and 'initialData' in params:+ try:+ output = json.loads(params.get('initialData', '{}'))+ except Exception:+ output = {}++ return output++ async def get_workflow_node_output(+ self,+ node_id: str,+ output_name: str = "output_0",+ session_id: str = "default",+ ) -> Dict[str, Any]:+ """Get stored output data for a node."""+ output = await self.get_node_output(session_id, node_id, output_name)+ if output:+ return {"success": True, "node_id": node_id, "data": output}+ return {"success": False, "node_id": node_id, "error": "No output found"}++ async def clear_all_outputs(self, session_id: str = "default") -> None:+ """Clear all outputs for a session."""+ keys = [k for k in self._outputs if k.startswith(f"{session_id}_")]+ for k in keys:+ del self._outputs[k]+ await self.database.clear_session_outputs(session_id)++ # =========================================================================+ # HELPERS+ # =========================================================================++ def _find_start_node(self, nodes: List[Dict]) -> Optional[Dict]:+ """Find workflow entry point."""+ # Priority: start > cronScheduler > other triggers+ for node in nodes:+ if node.get('type') == 'start':+ return node+ for node in nodes:+ if node.get('type') == 'cronScheduler':+ return node+ for node in nodes:+ if node.get('type') in WORKFLOW_TRIGGER_TYPES:+ return node+ return None++ def _build_execution_order(self, start: Dict, nodes: List[Dict], edges: List[Dict]) -> List[Dict]:+ """Build BFS execution order from start node."""+ visited = set()+ order = []+ queue = [start['id']]++ # Build adjacency map+ adj = {}+ for e in edges:+ src = e.get('source')+ if src:+ adj.setdefault(src, []).append(e.get('target'))++ node_map = {n['id']: n for n in nodes}++ while queue:+ nid = queue.pop(0)+ if nid in visited:+ continue+ visited.add(nid)+ node = node_map.get(nid)+ if node:+ order.append(node)+ queue.extend(t for t in adj.get(nid, []) if t not in visited)++ return order++ def _error_result(self, error: str, start_time: float) -> Dict:+ """Build error result."""+ return {+ "success": False,+ "error": error,+ "nodes_executed": [],+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat(),+ }++ # =========================================================================+ # SETTINGS+ # =========================================================================++ async def load_deployment_settings(self) -> Dict[str, Any]:+ """Load deployment settings from database."""+ try:+ db = await self.database.get_deployment_settings()+ if db:+ self._settings.update(db)+ except Exception:+ pass+ return self._settings.copy()++ async def update_deployment_settings(self, settings: Dict[str, Any]) -> Dict[str, Any]:+ """Update deployment settings."""+ self._settings.update(settings)+ await self.database.save_deployment_settings(self._settings)+ return self._settings.copy()++ def get_deployment_settings(self) -> Dict[str, Any]:+ """Get current deployment settings."""+ return self._settings.copy()++ @property+ def node_outputs(self) -> Dict[str, Dict[str, Any]]:+ """Backward compatibility: expose outputs as node_outputs."""+ return self._outputsdiff --git a/server/whatsapp-rpc/.dockerignore b/server/whatsapp-rpc/.dockerignorenew file mode 100644index 00000000..87bf5fb7--- /dev/null+++ b/server/whatsapp-rpc/.dockerignore@@ -0,0 +1,30 @@+# Git+.git+.gitignore++# Build artifacts+bin/+*.exe++# Data (mounted as volume)+data/++# Node modules+node_modules/++# Python cache+__pycache__/+*.pyc+*.pyo+.pytest_cache/++# IDE+.vscode/+.idea/++# Docs+*.md+!README.md++# Plans+.claude/diff --git a/server/whatsapp-rpc/.gitignore b/server/whatsapp-rpc/.gitignorenew file mode 100644index 00000000..42cd6a2e--- /dev/null+++ b/server/whatsapp-rpc/.gitignore@@ -0,0 +1,35 @@+# Build artifacts+*.exe+whatsapp-rpc++# Runtime data+data/++# Node+node_modules/+package-lock.json++# Python+__pycache__/+*.pyc+*.pyo+.venv/+venv/+.env++# IDE+.idea/+.vscode/+*.swp+*.swo++# OS+.DS_Store+Thumbs.db++# Logs+*.log++# Claude+CLAUDE.md+.claude/diff --git a/server/whatsapp-rpc/Dockerfile b/server/whatsapp-rpc/Dockerfilenew file mode 100644index 00000000..356452ab--- /dev/null+++ b/server/whatsapp-rpc/Dockerfile@@ -0,0 +1,44 @@+# Build stage+FROM golang:1.24-alpine AS builder++WORKDIR /app++# Install build dependencies+RUN apk add --no-cache git++# Copy go mod files+COPY go.mod go.sum ./+RUN go mod download++# Copy source code+COPY src/go/ ./src/go/++# Build binary+RUN CGO_ENABLED=0 GOOS=linux go build -o whatsapp-rpc-server ./src/go/cmd/server++# Runtime stage+FROM alpine:latest++WORKDIR /app++# Install ca-certificates for HTTPS+RUN apk add --no-cache ca-certificates tzdata++# Create data directories+RUN mkdir -p /app/data/qr /app/configs++# Copy binary from builder+COPY --from=builder /app/whatsapp-rpc-server .++# Copy config if exists+COPY configs/config.yaml ./configs/++# Expose WebSocket port+EXPOSE 9400++# Health check+HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \+ CMD wget --no-verbose --tries=1 --spider http://localhost:9400/health || exit 1++# Run server+CMD ["./whatsapp-rpc-server"]diff --git a/server/whatsapp-rpc/Dockerfile.web b/server/whatsapp-rpc/Dockerfile.webnew file mode 100644index 00000000..c6dc2d7c--- /dev/null+++ b/server/whatsapp-rpc/Dockerfile.web@@ -0,0 +1,17 @@+# Python Web UI+FROM python:3.11-slim++WORKDIR /app++# Install dependencies+COPY web/requirements.txt ./+RUN pip install --no-cache-dir -r requirements.txt++# Copy web app+COPY web/ ./++# Expose port+EXPOSE 5000++# Run Flask app+CMD ["python", "app.py"]diff --git a/server/whatsapp-rpc/README.md b/server/whatsapp-rpc/README.mdnew file mode 100644index 00000000..3a79bae7--- /dev/null+++ b/server/whatsapp-rpc/README.md@@ -0,0 +1,139 @@+# WhatsApp RPC++WebSocket JSON-RPC 2.0 API for WhatsApp.++<img width="1280" height="676" alt="image" src="https://github.com/user-attachments/assets/ddc7324a-8c4d-4557-ac6f-cb091a8ce31f" />++## Architecture++```+┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐+│ Your App │ │ Web UI │ │ Python Client │+│ (Any Language) │ │ (Flask) │ │ Library │+└────────┬────────┘ └────────┬────────┘ └────────┬────────┘+ │ │ │+ │ WebSocket │ HTTP │+ │ JSON-RPC 2.0 │ :5000 │+ │ │ │+ └───────────┬───────────┴───────────────────────┘+ │+ ▼+ ┌───────────────────────┐+ │ Go WebSocket API │+ │ :9400 │+ │ ┌─────────────────┐ │+ │ │ RPC Handler │ │+ │ │ Rate Limiter │ │+ │ │ Event Emitter │ │+ │ └────────┬────────┘ │+ └───────────┼───────────┘+ │+ ▼+ ┌───────────────────────┐+ │ WhatsApp Service │+ │ ┌─────────────────┐ │+ │ │ whatsmeow │ │+ │ │ (Go Library) │ │+ │ └────────┬────────┘ │+ └───────────┼───────────┘+ │+ ▼+ ┌───────────────────────┐+ │ WhatsApp Servers │+ └───────────────────────┘++Data Storage:+┌─────────────────────────────────┐+│ data/ │+│ ├── whatsapp.db (SQLite) │+│ ├── qr/*.png (QR codes) │+│ └── groups.json (Group cache)│+└─────────────────────────────────┘+```++## Setup++### Native+```bash+npm start # Start API + Web UI+npm stop # Stop all+npm run restart # Restart all+npm run status # Check if running+npm run api # Start API only+npm run web # Start Web UI only+npm run build # Build Go binary+npm run clean # Full cleanup (bin, data, node_modules)+```++All commands auto-install dependencies if missing.++### Docker+```bash+docker-compose up -d # Start+docker-compose down # Stop+docker-compose logs -f # View logs+```++## Endpoints++| Port | Service |+|------|---------|+| 9400 | WebSocket API - `ws://localhost:9400/ws/rpc` |+| 5000 | Web UI - `http://localhost:5000` |++## API++Connect via WebSocket and send JSON-RPC 2.0 requests:++```json+{"jsonrpc": "2.0", "id": 1, "method": "send", "params": {"phone": "1234567890", "type": "text", "message": "Hello"}}+```++### Methods++| Method | Params | Description |+|--------|--------|-------------|+| `status` | - | Connection status |+| `start` | - | Start WhatsApp |+| `stop` | - | Stop WhatsApp |+| `restart` | - | Full reset (logout, delete DB, new QR) |+| `qr` | - | Get QR code (base64 PNG) |+| `send` | `phone/group_id`, `type`, `message/media_data` | Send message |+| `media` | `message_id` | Download received media |+| `groups` | - | List all groups |+| `group_info` | `group_id` | Get group details |+| `contact_check` | `phones[]` | Check if numbers are on WhatsApp |++Full schema: [schema.json](schema.json)++## Events++Server pushes events as JSON-RPC notifications (no `id`):++```json+{"jsonrpc": "2.0", "method": "event.message_received", "params": {...}}+```++Events: `connected`, `disconnected`, `qr_code`, `message_received`, `message_sent`++## Data Files++- `data/whatsapp.db` - SQLite database (session, contacts)+- `data/qr/*.png` - QR code images+- `data/groups.json` - Auto-generated on connection (indexed group data)++## Structure++```+src/go/ # Go backend+src/python/ # Python client library+web/ # Flask web UI+scripts/ # CLI tools+configs/ # YAML config+```++## Requirements++- Go 1.21++- Python 3.8++- Node.js 16+diff --git a/server/whatsapp-rpc/cli.js b/server/whatsapp-rpc/cli.jsnew file mode 100644index 00000000..03c346ce--- /dev/null+++ b/server/whatsapp-rpc/cli.js@@ -0,0 +1,95 @@+#!/usr/bin/env node+import { program } from 'commander';+import chalk from 'chalk';+import { execa } from 'execa';+import killPort from 'kill-port';+import { Socket } from 'net';+import { execSync, spawn } from 'child_process';+import { existsSync, statSync, unlinkSync, readdirSync } from 'fs';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';++const __dirname = dirname(fileURLToPath(import.meta.url));+const API_PORT = 9400, WEB_PORT = 5000;+const BIN = process.platform === 'win32' ? 'whatsapp-rpc.exe' : 'whatsapp-rpc';++const log = (m, c = 'blue') => console.log(chalk[c](m));+const sleep = ms => new Promise(r => setTimeout(r, ms));++const portUp = port => new Promise(r => {+ const s = new Socket();+ s.setTimeout(2000);+ s.on('connect', () => { s.destroy(); r(true); });+ s.on('timeout', () => { s.destroy(); r(false); });+ s.on('error', () => r(false));+ s.connect(port, '127.0.0.1');+});++const wait = async (port, ms = 10000) => {+ const t = Date.now();+ while (Date.now() - t < ms) { if (await portUp(port)) return true; await sleep(500); }+ return false;+};++const kill = async (port, name) => {+ try { await killPort(port); log(`${name} stopped`, 'green'); }+ catch { log(`${name} not running`, 'yellow'); }+};++const py = () => {+ try { execSync('python --version', { stdio: 'ignore' }); return 'python'; }+ catch { try { execSync('python3 --version', { stdio: 'ignore' }); return 'python3'; } catch { return null; } }+};++async function api() {+ if (await portUp(API_PORT)) { log(`API already on ${API_PORT}`, 'yellow'); return; }+ const bin = join(__dirname, BIN);+ if (!existsSync(bin)) { log('Building...', 'yellow'); await build(); }+ spawn(bin, [], { cwd: __dirname, detached: true, stdio: 'ignore' }).unref();+ if (await wait(API_PORT)) log(`API: ws://localhost:${API_PORT}/ws/rpc`, 'green');+ else log('API failed to start', 'red');+}++async function web() {+ if (await portUp(WEB_PORT)) { log(`Web already on ${WEB_PORT}`, 'yellow'); return; }+ const p = py(); if (!p) { log('Python not found', 'red'); return; }+ if (!await portUp(API_PORT)) log('Warning: API not running', 'yellow');+ spawn(p, ['app.py'], { cwd: join(__dirname, 'web'), detached: true, stdio: 'ignore' }).unref();+ if (await wait(WEB_PORT)) log(`Web: http://localhost:${WEB_PORT}`, 'green');+ else log('Web failed to start', 'red');+}++async function start() { await api(); await sleep(1000); await web(); }+async function stop() { await kill(API_PORT, 'API'); await kill(WEB_PORT, 'Web'); }++async function status() {+ const a = await portUp(API_PORT), w = await portUp(WEB_PORT);+ log(`API (${API_PORT}): ${a ? 'UP' : 'DOWN'}`, a ? 'green' : 'red');+ log(`Web (${WEB_PORT}): ${w ? 'UP' : 'DOWN'}`, w ? 'green' : 'red');+}++async function build() {+ const bin = join(__dirname, BIN);+ if (existsSync(bin)) unlinkSync(bin);+ await execa('go', ['build', '-o', BIN, '.'], { cwd: __dirname, stdio: 'inherit' });+ log(`Built: ${BIN} (${(statSync(bin).size / 1024 / 1024).toFixed(1)}MB)`, 'green');+}++async function clean() {+ const bin = join(__dirname, BIN);+ if (existsSync(bin)) { unlinkSync(bin); log(`Removed ${BIN}`, 'green'); }+ readdirSync(__dirname).filter(f => f.startsWith('qr_') && f.endsWith('.png')).forEach(f => {+ unlinkSync(join(__dirname, f)); log(`Removed ${f}`, 'green');+ });+}++program.name('wa').version('1.0.0');+program.command('start').description('Start all').action(start);+program.command('stop').description('Stop all').action(stop);+program.command('restart').description('Restart all').action(async () => { await stop(); await sleep(1000); await start(); });+program.command('status').description('Status').action(status);+program.command('api').description('Start API only').action(api);+program.command('web').description('Start Web only').action(web);+program.command('build').description('Build binary').action(build);+program.command('clean').description('Clean artifacts').action(clean);+program.parse();diff --git a/server/whatsapp-rpc/configs/config.yaml b/server/whatsapp-rpc/configs/config.yamlnew file mode 100644index 00000000..88491512--- /dev/null+++ b/server/whatsapp-rpc/configs/config.yaml@@ -0,0 +1,7 @@+environment: "development"+log_level: 4+server:+ port: 9400+ host: "0.0.0.0"+database:+ path: "data/whatsapp.db"\ No newline at end of filediff --git a/server/whatsapp-rpc/docker-compose.yml b/server/whatsapp-rpc/docker-compose.ymlnew file mode 100644index 00000000..f24bb078--- /dev/null+++ b/server/whatsapp-rpc/docker-compose.yml@@ -0,0 +1,35 @@+services:+ api:+ build: .+ container_name: whatsapp-rpc-api+ ports:+ - "9400:9400"+ volumes:+ - ./data:/app/data+ - ./configs:/app/configs+ environment:+ - WA_SERVER_PORT=9400+ - WA_DATABASE_PATH=data/whatsapp.db+ restart: unless-stopped+ healthcheck:+ test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:9400/health"]+ interval: 30s+ timeout: 10s+ retries: 3++ web:+ build:+ context: .+ dockerfile: Dockerfile.web+ container_name: whatsapp-rpc-web+ ports:+ - "5000:5000"+ environment:+ - GO_WS_RPC_URL=ws://api:9400/ws/rpc+ depends_on:+ api:+ condition: service_healthy+ restart: unless-stopped++volumes:+ data:diff --git a/server/whatsapp-rpc/docs/API.md b/server/whatsapp-rpc/docs/API.mdnew file mode 100644index 00000000..cbdfc261--- /dev/null+++ b/server/whatsapp-rpc/docs/API.md@@ -0,0 +1,410 @@+# WhatsApp RPC API++## Connection++```+ws://localhost:9400/ws/rpc+```++All requests use JSON-RPC 2.0 format:+```json+{"jsonrpc": "2.0", "id": 1, "method": "METHOD_NAME", "params": {...}}+```++## Quick Examples++### Send Text Message+```json+{"jsonrpc": "2.0", "id": 1, "method": "send", "params": {+ "phone": "919876543210",+ "type": "text",+ "message": "Hello!"+}}+```++### Send to Group+```json+{"jsonrpc": "2.0", "id": 1, "method": "send", "params": {+ "group_id": "[email protected]",+ "type": "text",+ "message": "Hello group!"+}}+```++### Send Image+```json+{"jsonrpc": "2.0", "id": 1, "method": "send", "params": {+ "phone": "919876543210",+ "type": "image",+ "media_data": {+ "data": "BASE64_IMAGE_DATA",+ "mime_type": "image/jpeg",+ "caption": "Check this out"+ }+}}+```++### Send Document+```json+{"jsonrpc": "2.0", "id": 1, "method": "send", "params": {+ "phone": "919876543210",+ "type": "document",+ "media_data": {+ "data": "BASE64_FILE_DATA",+ "mime_type": "application/pdf",+ "filename": "report.pdf"+ }+}}+```++### Send Location+```json+{"jsonrpc": "2.0", "id": 1, "method": "send", "params": {+ "phone": "919876543210",+ "type": "location",+ "location": {+ "latitude": 37.7749,+ "longitude": -122.4194,+ "name": "San Francisco",+ "address": "California, USA"+ }+}}+```++### Reply to Message+```json+{"jsonrpc": "2.0", "id": 1, "method": "send", "params": {+ "phone": "919876543210",+ "type": "text",+ "message": "This is a reply",+ "reply": {+ "message_id": "ABC123",+ "sender": "[email protected]",+ "content": "Original message text"+ }+}}+```++---++## All Methods++### Connection++#### `status`+Get connection status.+```json+{"jsonrpc": "2.0", "id": 1, "method": "status", "params": {}}+```+Response:+```json+{+ "connected": true,+ "has_session": true,+ "running": true,+ "pairing": false,+ "device_id": "[email protected]"+}+```++#### `start`+Start WhatsApp service.+```json+{"jsonrpc": "2.0", "id": 1, "method": "start", "params": {}}+```++#### `stop`+Stop WhatsApp service.+```json+{"jsonrpc": "2.0", "id": 1, "method": "stop", "params": {}}+```++#### `restart`+Full reset: logout, delete database, generate new QR.+```json+{"jsonrpc": "2.0", "id": 1, "method": "restart", "params": {}}+```++#### `qr`+Get QR code for pairing.+```json+{"jsonrpc": "2.0", "id": 1, "method": "qr", "params": {}}+```+Response:+```json+{+ "has_qr": true,+ "code": "QR_STRING",+ "filename": "data/qr/qr_123.png",+ "image_data": "BASE64_PNG"+}+```++---++### Messaging++#### `send`+Send message (text, image, video, audio, document, sticker, location, contact).++| Param | Type | Required | Description |+|-------|------|----------|-------------|+| `phone` | string | * | Phone number (without +) |+| `group_id` | string | * | Group JID (e.g., `[email protected]`) |+| `type` | string | Yes | `text`, `image`, `video`, `audio`, `document`, `sticker`, `location`, `contact` |+| `message` | string | For text | Text content |+| `media_data` | object | For media | `{data, mime_type, filename?, caption?, thumbnail?}` |+| `location` | object | For location | `{latitude, longitude, name?, address?}` |+| `contact` | object | For contact | `{display_name, vcard}` |+| `reply` | object | Optional | `{message_id, sender, content}` |++*Either `phone` or `group_id` required.++#### `media`+Download media from received message.+```json+{"jsonrpc": "2.0", "id": 1, "method": "media", "params": {+ "message_id": "ABC123DEF456"+}}+```+Response:+```json+{+ "data": "BASE64_MEDIA_DATA",+ "mime_type": "image/jpeg"+}+```++---++### Groups++#### `groups`+List all groups.+```json+{"jsonrpc": "2.0", "id": 1, "method": "groups", "params": {}}+```++#### `group_info`+Get group details.+```json+{"jsonrpc": "2.0", "id": 1, "method": "group_info", "params": {+ "group_id": "[email protected]"+}}+```+Response:+```json+{+ "jid": "[email protected]",+ "name": "Group Name",+ "topic": "Description",+ "owner": "[email protected]",+ "size": 25,+ "participants": [+ {"jid": "...", "phone": "919876543210", "is_admin": true, "is_super_admin": true}+ ]+}+```++#### `group_participants_add`+Add members to group.+```json+{"jsonrpc": "2.0", "id": 1, "method": "group_participants_add", "params": {+ "group_id": "[email protected]",+ "participants": ["919876543210", "918765432109"]+}}+```++#### `group_participants_remove`+Remove members from group.+```json+{"jsonrpc": "2.0", "id": 1, "method": "group_participants_remove", "params": {+ "group_id": "[email protected]",+ "participants": ["919876543210"]+}}+```++#### `group_invite_link`+Get group invite link.+```json+{"jsonrpc": "2.0", "id": 1, "method": "group_invite_link", "params": {+ "group_id": "[email protected]"+}}+```++---++### Contacts++#### `contact_check`+Check if numbers are on WhatsApp.+```json+{"jsonrpc": "2.0", "id": 1, "method": "contact_check", "params": {+ "phones": ["919876543210", "918765432109"]+}}+```+Response:+```json+[+ {"query": "919876543210", "jid": "[email protected]", "is_registered": true, "is_business": false},+ {"query": "918765432109", "is_registered": false}+]+```++#### `contact_profile_pic`+Get profile picture.+```json+{"jsonrpc": "2.0", "id": 1, "method": "contact_profile_pic", "params": {+ "jid": "[email protected]"+}}+```++---++### Presence++#### `typing`+Send typing indicator.+```json+{"jsonrpc": "2.0", "id": 1, "method": "typing", "params": {+ "jid": "[email protected]",+ "state": "composing"+}}+```+States: `composing`, `paused`++#### `presence`+Set online status.+```json+{"jsonrpc": "2.0", "id": 1, "method": "presence", "params": {+ "status": "available"+}}+```+Status: `available`, `unavailable`++#### `mark_read`+Mark messages as read.+```json+{"jsonrpc": "2.0", "id": 1, "method": "mark_read", "params": {+ "message_ids": ["ABC123", "DEF456"],+ "chat_jid": "[email protected]"+}}+```++---++### Rate Limiting++#### `rate_limit_get`+Get rate limit config and stats.+```json+{"jsonrpc": "2.0", "id": 1, "method": "rate_limit_get", "params": {}}+```++#### `rate_limit_set`+Update rate limit config.+```json+{"jsonrpc": "2.0", "id": 1, "method": "rate_limit_set", "params": {+ "enabled": true,+ "min_delay_ms": 3000,+ "max_messages_per_hour": 60,+ "simulate_typing": true+}}+```++---++## Events++Server pushes events as JSON-RPC notifications (no `id` field):++### `event.connected`+```json+{"jsonrpc": "2.0", "method": "event.connected", "params": {+ "status": "connected",+ "device_id": "[email protected]"+}}+```++### `event.disconnected`+```json+{"jsonrpc": "2.0", "method": "event.disconnected", "params": {+ "status": "disconnected",+ "reason": "..."+}}+```++### `event.qr_code`+```json+{"jsonrpc": "2.0", "method": "event.qr_code", "params": {+ "code": "QR_STRING",+ "filename": "data/qr/qr_123.png",+ "image_data": "BASE64_PNG"+}}+```++### `event.message_received`+```json+{"jsonrpc": "2.0", "method": "event.message_received", "params": {+ "message_id": "ABC123",+ "sender": "[email protected]",+ "chat_id": "[email protected]",+ "is_from_me": false,+ "is_group": false,+ "message_type": "text",+ "text": "Hello!",+ "timestamp": "2025-01-15T10:30:00Z"+}}+```++### `event.message_sent`+```json+{"jsonrpc": "2.0", "method": "event.message_sent", "params": {+ "message_id": "XYZ789",+ "to": "[email protected]",+ "type": "text",+ "timestamp": "2025-01-15T10:30:00Z"+}}+```++---++## Error Codes++| Code | Description |+|------|-------------|+| -32700 | Parse error - Invalid JSON |+| -32600 | Invalid Request |+| -32601 | Method not found |+| -32602 | Invalid params |+| -32000 | Server error (WhatsApp operation failed) |+| -32001 | No QR available |++---++## Data Files++| File | Description |+|------|-------------|+| `data/whatsapp.db` | SQLite database (session, messages) |+| `data/qr/*.png` | QR code images |+| `data/groups.json` | Auto-generated group data (on connection) |++The `groups.json` file is indexed for fast lookups:+```json+{+ "generated_at": "2025-01-15T10:30:00Z",+ "device_id": "[email protected]",+ "groups": {+ "[email protected]": {+ "name": "Group Name",+ "participants": {+ "919876543210": {"phone": "919876543210", "is_admin": true}+ }+ }+ },+ "phone_to_groups": {+ "919876543210": ["[email protected]", "[email protected]"]+ }+}+```diff --git a/server/whatsapp-rpc/go.mod b/server/whatsapp-rpc/go.modnew file mode 100644index 00000000..753e0add--- /dev/null+++ b/server/whatsapp-rpc/go.mod@@ -0,0 +1,67 @@+module whatsapp-rpc++go 1.24.0++require (+ github.com/gin-gonic/gin v1.9.1+ github.com/gorilla/websocket v1.5.3+ github.com/sirupsen/logrus v1.9.3+ github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e+ github.com/spf13/viper v1.21.0+ go.mau.fi/whatsmeow v0.0.0-20251120135021-071293c6b9f0+ google.golang.org/protobuf v1.36.10+ modernc.org/sqlite v1.40.1+)++require (+ filippo.io/edwards25519 v1.1.0 // indirect+ github.com/beeper/argo-go v1.1.2 // indirect+ github.com/bytedance/sonic v1.9.1 // indirect+ github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect+ github.com/coder/websocket v1.8.14 // indirect+ github.com/dustin/go-humanize v1.0.1 // indirect+ github.com/elliotchance/orderedmap/v3 v3.1.0 // indirect+ github.com/fsnotify/fsnotify v1.9.0 // indirect+ github.com/gabriel-vasile/mimetype v1.4.2 // indirect+ github.com/gin-contrib/sse v0.1.0 // indirect+ github.com/go-playground/locales v0.14.1 // indirect+ github.com/go-playground/universal-translator v0.18.1 // indirect+ github.com/go-playground/validator/v10 v10.14.0 // indirect+ github.com/go-viper/mapstructure/v2 v2.4.0 // indirect+ github.com/goccy/go-json v0.10.2 // indirect+ github.com/google/uuid v1.6.0 // indirect+ github.com/json-iterator/go v1.1.12 // indirect+ github.com/klauspost/cpuid/v2 v2.2.4 // indirect+ github.com/leodido/go-urn v1.2.4 // indirect+ github.com/mattn/go-colorable v0.1.14 // indirect+ github.com/mattn/go-isatty v0.0.20 // indirect+ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect+ github.com/modern-go/reflect2 v1.0.2 // indirect+ github.com/ncruces/go-strftime v0.1.9 // indirect+ github.com/pelletier/go-toml/v2 v2.2.4 // indirect+ github.com/petermattis/goid v0.0.0-20250904145737-900bdf8bb490 // indirect+ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect+ github.com/rs/zerolog v1.34.0 // indirect+ github.com/sagikazarmark/locafero v0.11.0 // indirect+ github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect+ github.com/spf13/afero v1.15.0 // indirect+ github.com/spf13/cast v1.10.0 // indirect+ github.com/spf13/pflag v1.0.10 // indirect+ github.com/subosito/gotenv v1.6.0 // indirect+ github.com/twitchyliquid64/golang-asm v0.15.1 // indirect+ github.com/ugorji/go/codec v1.2.11 // indirect+ github.com/vektah/gqlparser/v2 v2.5.27 // indirect+ go.mau.fi/libsignal v0.2.1 // indirect+ go.mau.fi/util v0.9.3 // indirect+ go.yaml.in/yaml/v3 v3.0.4 // indirect+ golang.org/x/arch v0.3.0 // indirect+ golang.org/x/crypto v0.44.0 // indirect+ golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 // indirect+ golang.org/x/net v0.47.0 // indirect+ golang.org/x/sys v0.38.0 // indirect+ golang.org/x/text v0.31.0 // indirect+ gopkg.in/yaml.v3 v3.0.1 // indirect+ modernc.org/libc v1.66.10 // indirect+ modernc.org/mathutil v1.7.1 // indirect+ modernc.org/memory v1.11.0 // indirect+)diff --git a/server/whatsapp-rpc/go.sum b/server/whatsapp-rpc/go.sumnew file mode 100644index 00000000..d3909828--- /dev/null+++ b/server/whatsapp-rpc/go.sum@@ -0,0 +1,203 @@+filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=+filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=+github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU=+github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU=+github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM=+github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=+github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ=+github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8=+github.com/beeper/argo-go v1.1.2 h1:UQI2G8F+NLfGTOmTUI0254pGKx/HUU/etbUGTJv91Fs=+github.com/beeper/argo-go v1.1.2/go.mod h1:M+LJAnyowKVQ6Rdj6XYGEn+qcVFkb3R/MUpqkGR0hM4=+github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=+github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=+github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=+github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=+github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams=+github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=+github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g=+github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=+github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=+github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=+github.com/elliotchance/orderedmap/v3 v3.1.0 h1:j4DJ5ObEmMBt/lcwIecKcoRxIQUEnw0L804lXYDt/pg=+github.com/elliotchance/orderedmap/v3 v3.1.0/go.mod h1:G+Hc2RwaZvJMcS4JpGCOyViCnGeKf0bTYCGTO4uhjSo=+github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=+github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=+github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=+github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=+github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=+github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=+github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=+github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=+github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=+github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=+github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=+github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=+github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=+github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=+github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=+github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=+github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js=+github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=+github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=+github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=+github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=+github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=+github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=+github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=+github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=+github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=+github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=+github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=+github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=+github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=+github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=+github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk=+github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=+github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=+github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=+github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=+github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=+github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=+github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=+github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=+github.com/mattn/go-sqlite3 v1.14.32 h1:JD12Ag3oLy1zQA+BNn74xRgaBbdhbNIDYvQUEuuErjs=+github.com/mattn/go-sqlite3 v1.14.32/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=+github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=+github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=+github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=+github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=+github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=+github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=+github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=+github.com/petermattis/goid v0.0.0-20250904145737-900bdf8bb490 h1:QTvNkZ5ylY0PGgA+Lih+GdboMLY/G9SEGLMEGVjTVA4=+github.com/petermattis/goid v0.0.0-20250904145737-900bdf8bb490/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4=+github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=+github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=+github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=+github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=+github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=+github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=+github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc=+github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik=+github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8=+github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=+github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=+github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=+github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=+github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=+github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw=+github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U=+github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=+github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=+github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=+github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=+github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=+github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=+github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=+github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=+github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=+github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=+github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=+github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=+github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=+github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=+github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=+github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=+github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=+github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=+github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=+github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=+github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=+github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=+github.com/vektah/gqlparser/v2 v2.5.27 h1:RHPD3JOplpk5mP5JGX8RKZkt2/Vwj/PZv0HxTdwFp0s=+github.com/vektah/gqlparser/v2 v2.5.27/go.mod h1:D1/VCZtV3LPnQrcPBeR/q5jkSQIPti0uYCP/RI0gIeo=+go.mau.fi/libsignal v0.2.1 h1:vRZG4EzTn70XY6Oh/pVKrQGuMHBkAWlGRC22/85m9L0=+go.mau.fi/libsignal v0.2.1/go.mod h1:iVvjrHyfQqWajOUaMEsIfo3IqgVMrhWcPiiEzk7NgoU=+go.mau.fi/util v0.9.3 h1:aqNF8KDIN8bFpFbybSk+mEBil7IHeBwlujfyTnvP0uU=+go.mau.fi/util v0.9.3/go.mod h1:krWWfBM1jWTb5f8NCa2TLqWMQuM81X7TGQjhMjBeXmQ=+go.mau.fi/whatsmeow v0.0.0-20251120135021-071293c6b9f0 h1:ZDDLaG7VZ3peRWOsJMCxIhoeYuRGc937DzoUtnShqd0=+go.mau.fi/whatsmeow v0.0.0-20251120135021-071293c6b9f0/go.mod h1:5aYaEa3FF5e5XWsA8Xa80ttUXZvb6HyaBGgo2SfzUkE=+go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=+go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=+golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=+golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k=+golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=+golang.org/x/crypto v0.44.0 h1:A97SsFvM3AIwEEmTBiaxPPTYpDC47w720rdiiUvgoAU=+golang.org/x/crypto v0.44.0/go.mod h1:013i+Nw79BMiQiMsOPcVCB5ZIJbYkerPrGnOa00tvmc=+golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 h1:zfMcR1Cs4KNuomFFgGefv5N0czO2XZpUbxGUy8i8ug0=+golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6/go.mod h1:46edojNIoXTNOhySWIWdix628clX9ODXwPsQuG6hsK0=+golang.org/x/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk=+golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc=+golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=+golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=+golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=+golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=+golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=+golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=+golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=+golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=+golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ=+golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ=+google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=+google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=+gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=+gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=+modernc.org/cc/v4 v4.26.5 h1:xM3bX7Mve6G8K8b+T11ReenJOT+BmVqQj0FY5T4+5Y4=+modernc.org/cc/v4 v4.26.5/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=+modernc.org/ccgo/v4 v4.28.1 h1:wPKYn5EC/mYTqBO373jKjvX2n+3+aK7+sICCv4Fjy1A=+modernc.org/ccgo/v4 v4.28.1/go.mod h1:uD+4RnfrVgE6ec9NGguUNdhqzNIeeomeXf6CL0GTE5Q=+modernc.org/fileutil v1.3.40 h1:ZGMswMNc9JOCrcrakF1HrvmergNLAmxOPjizirpfqBA=+modernc.org/fileutil v1.3.40/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc=+modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=+modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=+modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=+modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=+modernc.org/libc v1.66.10 h1:yZkb3YeLx4oynyR+iUsXsybsX4Ubx7MQlSYEw4yj59A=+modernc.org/libc v1.66.10/go.mod h1:8vGSEwvoUoltr4dlywvHqjtAqHBaw0j1jI7iFBTAr2I=+modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=+modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=+modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=+modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=+modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=+modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=+modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=+modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=+modernc.org/sqlite v1.40.1 h1:VfuXcxcUWWKRBuP8+BR9L7VnmusMgBNNnBYGEe9w/iY=+modernc.org/sqlite v1.40.1/go.mod h1:9fjQZ0mB1LLP0GYrp39oOJXx/I2sxEnZtzCmEQIKvGE=+modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=+modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=+modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=+modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=+rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=diff --git a/server/whatsapp-rpc/package-lock.json b/server/whatsapp-rpc/package-lock.jsonnew file mode 100644index 00000000..d59e77b2--- /dev/null+++ b/server/whatsapp-rpc/package-lock.json@@ -0,0 +1,272 @@+{+ "name": "whatsapp-rpc",+ "version": "1.0.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "whatsapp-rpc",+ "version": "1.0.0",+ "dependencies": {+ "chalk": "^5.3.0",+ "commander": "^11.1.0",+ "execa": "^8.0.1",+ "kill-port": "^2.0.1"+ },+ "bin": {+ "wa": "scripts/cli.js"+ }+ },+ "node_modules/chalk": {+ "version": "5.6.2",+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz",+ "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==",+ "license": "MIT",+ "engines": {+ "node": "^12.17.0 || ^14.13 || >=16.0.0"+ },+ "funding": {+ "url": "https://github.com/chalk/chalk?sponsor=1"+ }+ },+ "node_modules/commander": {+ "version": "11.1.0",+ "resolved": "https://registry.npmjs.org/commander/-/commander-11.1.0.tgz",+ "integrity": "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ==",+ "license": "MIT",+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/cross-spawn": {+ "version": "7.0.6",+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",+ "license": "MIT",+ "dependencies": {+ "path-key": "^3.1.0",+ "shebang-command": "^2.0.0",+ "which": "^2.0.1"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/execa": {+ "version": "8.0.1",+ "resolved": "https://registry.npmjs.org/execa/-/execa-8.0.1.tgz",+ "integrity": "sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg==",+ "license": "MIT",+ "dependencies": {+ "cross-spawn": "^7.0.3",+ "get-stream": "^8.0.1",+ "human-signals": "^5.0.0",+ "is-stream": "^3.0.0",+ "merge-stream": "^2.0.0",+ "npm-run-path": "^5.1.0",+ "onetime": "^6.0.0",+ "signal-exit": "^4.1.0",+ "strip-final-newline": "^3.0.0"+ },+ "engines": {+ "node": ">=16.17"+ },+ "funding": {+ "url": "https://github.com/sindresorhus/execa?sponsor=1"+ }+ },+ "node_modules/get-stream": {+ "version": "8.0.1",+ "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-8.0.1.tgz",+ "integrity": "sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA==",+ "license": "MIT",+ "engines": {+ "node": ">=16"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/get-them-args": {+ "version": "1.3.2",+ "resolved": "https://registry.npmjs.org/get-them-args/-/get-them-args-1.3.2.tgz",+ "integrity": "sha512-LRn8Jlk+DwZE4GTlDbT3Hikd1wSHgLMme/+7ddlqKd7ldwR6LjJgTVWzBnR01wnYGe4KgrXjg287RaI22UHmAw==",+ "license": "MIT"+ },+ "node_modules/human-signals": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-5.0.0.tgz",+ "integrity": "sha512-AXcZb6vzzrFAUE61HnN4mpLqd/cSIwNQjtNWR0euPm6y0iqx3G4gOXaIDdtdDwZmhwe82LA6+zinmW4UBWVePQ==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=16.17.0"+ }+ },+ "node_modules/is-stream": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-3.0.0.tgz",+ "integrity": "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA==",+ "license": "MIT",+ "engines": {+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/isexe": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",+ "license": "ISC"+ },+ "node_modules/kill-port": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/kill-port/-/kill-port-2.0.1.tgz",+ "integrity": "sha512-e0SVOV5jFo0mx8r7bS29maVWp17qGqLBZ5ricNSajON6//kmb7qqqNnml4twNE8Dtj97UQD+gNFOaipS/q1zzQ==",+ "license": "MIT",+ "dependencies": {+ "get-them-args": "1.3.2",+ "shell-exec": "1.0.2"+ },+ "bin": {+ "kill-port": "cli.js"+ }+ },+ "node_modules/merge-stream": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",+ "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==",+ "license": "MIT"+ },+ "node_modules/mimic-fn": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz",+ "integrity": "sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/npm-run-path": {+ "version": "5.3.0",+ "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.3.0.tgz",+ "integrity": "sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ==",+ "license": "MIT",+ "dependencies": {+ "path-key": "^4.0.0"+ },+ "engines": {+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/npm-run-path/node_modules/path-key": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz",+ "integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/onetime": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/onetime/-/onetime-6.0.0.tgz",+ "integrity": "sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==",+ "license": "MIT",+ "dependencies": {+ "mimic-fn": "^4.0.0"+ },+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/path-key": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/shebang-command": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",+ "license": "MIT",+ "dependencies": {+ "shebang-regex": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/shebang-regex": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/shell-exec": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/shell-exec/-/shell-exec-1.0.2.tgz",+ "integrity": "sha512-jyVd+kU2X+mWKMmGhx4fpWbPsjvD53k9ivqetutVW/BQ+WIZoDoP4d8vUMGezV6saZsiNoW2f9GIhg9Dondohg==",+ "license": "MIT"+ },+ "node_modules/signal-exit": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",+ "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==",+ "license": "ISC",+ "engines": {+ "node": ">=14"+ },+ "funding": {+ "url": "https://github.com/sponsors/isaacs"+ }+ },+ "node_modules/strip-final-newline": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-3.0.0.tgz",+ "integrity": "sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/which": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",+ "license": "ISC",+ "dependencies": {+ "isexe": "^2.0.0"+ },+ "bin": {+ "node-which": "bin/node-which"+ },+ "engines": {+ "node": ">= 8"+ }+ }+ }+}diff --git a/server/whatsapp-rpc/package.json b/server/whatsapp-rpc/package.jsonnew file mode 100644index 00000000..416df22d--- /dev/null+++ b/server/whatsapp-rpc/package.json@@ -0,0 +1,30 @@+{+ "name": "whatsapp-rpc",+ "version": "1.0.0",+ "type": "module",+ "description": "WhatsApp WebSocket RPC Server",+ "bin": { "wa": "scripts/cli.js" },+ "scripts": {+ "prestart": "node -e \"require('fs').existsSync('node_modules')||require('child_process').execSync('npm i',{stdio:'inherit'})\"",+ "start": "node scripts/cli.js start",+ "prestop": "node -e \"require('fs').existsSync('node_modules')||require('child_process').execSync('npm i',{stdio:'inherit'})\"",+ "stop": "node scripts/cli.js stop",+ "prerestart": "node -e \"require('fs').existsSync('node_modules')||require('child_process').execSync('npm i',{stdio:'inherit'})\"",+ "restart": "node scripts/cli.js restart",+ "prestatus": "node -e \"require('fs').existsSync('node_modules')||require('child_process').execSync('npm i',{stdio:'inherit'})\"",+ "status": "node scripts/cli.js status",+ "preapi": "node -e \"require('fs').existsSync('node_modules')||require('child_process').execSync('npm i',{stdio:'inherit'})\"",+ "api": "node scripts/cli.js api",+ "preweb": "node -e \"require('fs').existsSync('node_modules')||require('child_process').execSync('npm i',{stdio:'inherit'})\"",+ "web": "node scripts/cli.js web",+ "prebuild": "node -e \"require('fs').existsSync('node_modules')||require('child_process').execSync('npm i',{stdio:'inherit'})\"",+ "build": "node -e \"const fs=require('fs'),p=process.platform==='win32'?'.exe':'',d='bin';fs.existsSync(d)||fs.mkdirSync(d);require('child_process').execSync('go build -v -o '+d+'/whatsapp-rpc-server'+p+' ./src/go/cmd/server',{stdio:'inherit'});console.log('Build complete: '+d+'/whatsapp-rpc-server'+p)\"",+ "clean": "node scripts/clean.cjs"+ },+ "dependencies": {+ "chalk": "^5.3.0",+ "commander": "^11.1.0",+ "execa": "^8.0.1",+ "kill-port": "^2.0.1"+ }+}diff --git a/server/whatsapp-rpc/schema.json b/server/whatsapp-rpc/schema.jsonnew file mode 100644index 00000000..6c09133b--- /dev/null+++ b/server/whatsapp-rpc/schema.json@@ -0,0 +1,1134 @@+{+ "openrpc": "1.3.2",+ "info": {+ "title": "WhatsApp RPC API",+ "version": "1.0.0",+ "description": "JSON-RPC 2.0 API over WebSocket for WhatsApp messaging"+ },+ "servers": [+ {+ "name": "default",+ "url": "ws://localhost:9400/ws/rpc"+ }+ ],+ "methods": [+ {+ "name": "status",+ "summary": "Get WhatsApp connection status",+ "params": [],+ "result": {+ "name": "StatusResult",+ "schema": {+ "type": "object",+ "properties": {+ "connected": { "type": "boolean", "description": "Whether WhatsApp is connected" },+ "has_session": { "type": "boolean", "description": "Whether a session exists" },+ "running": { "type": "boolean", "description": "Whether the service is running" },+ "pairing": { "type": "boolean", "description": "Whether pairing is in progress" },+ "device_id": { "type": "string", "description": "Device JID if connected" },+ "timestamp": { "type": "string", "format": "date-time" }+ },+ "required": ["connected", "has_session", "running", "pairing", "timestamp"]+ }+ }+ },+ {+ "name": "start",+ "summary": "Start WhatsApp service",+ "params": [],+ "result": {+ "name": "StartResult",+ "schema": {+ "type": "object",+ "properties": {+ "message": { "type": "string", "enum": ["Started"] }+ }+ }+ }+ },+ {+ "name": "stop",+ "summary": "Stop WhatsApp service",+ "params": [],+ "result": {+ "name": "StopResult",+ "schema": {+ "type": "object",+ "properties": {+ "message": { "type": "string", "enum": ["Stopped"] }+ }+ }+ }+ },+ {+ "name": "restart",+ "summary": "Full reset: logout, delete DB, cleanup QR, reinit, start fresh",+ "description": "Performs a complete reset: 1) Logout from WhatsApp servers, 2) Shutdown service, 3) Delete device session, 4) Delete database files, 5) Delete QR code files, 6) Reinitialize client, 7) Start pairing",+ "params": [],+ "result": {+ "name": "RestartResult",+ "schema": {+ "type": "object",+ "properties": {+ "message": { "type": "string", "enum": ["Restarted (session cleared)"] }+ }+ }+ }+ },+ {+ "name": "reset",+ "summary": "Reset WhatsApp session (logout and delete credentials)",+ "params": [],+ "result": {+ "name": "ResetResult",+ "schema": {+ "type": "object",+ "properties": {+ "message": { "type": "string", "enum": ["Reset"] }+ }+ }+ }+ },+ {+ "name": "diagnostics",+ "summary": "Get detailed diagnostics information",+ "params": [],+ "result": {+ "name": "DiagnosticsResult",+ "schema": {+ "type": "object",+ "properties": {+ "client_connected": { "type": "boolean" },+ "client_logged_in": { "type": "boolean" },+ "store_has_id": { "type": "boolean" },+ "service_running": { "type": "boolean" },+ "service_pairing": { "type": "boolean" },+ "service_shutdown": { "type": "boolean" },+ "events_channel_open": { "type": "boolean" },+ "device_store": {+ "type": "object",+ "properties": {+ "device_id": { "type": "string" },+ "user": { "type": "string" },+ "device": { "type": "integer" },+ "server": { "type": "string" }+ }+ },+ "timestamp": { "type": "string", "format": "date-time" }+ }+ }+ }+ },+ {+ "name": "qr",+ "summary": "Get current QR code for pairing",+ "params": [],+ "result": {+ "name": "QRResult",+ "schema": {+ "type": "object",+ "properties": {+ "has_qr": { "type": "boolean", "enum": [true] },+ "code": { "type": "string", "description": "QR code content string" },+ "filename": { "type": "string", "description": "PNG file path" },+ "image_data": { "type": "string", "description": "Base64-encoded PNG data (for Docker/remote access)" }+ },+ "required": ["has_qr", "code", "filename"]+ }+ },+ "errors": [+ {+ "code": -32001,+ "message": "No QR available"+ }+ ]+ },+ {+ "name": "send",+ "summary": "Send a WhatsApp message",+ "params": [+ {+ "name": "phone",+ "description": "Recipient phone number (without + prefix)",+ "schema": { "type": "string" },+ "required": false+ },+ {+ "name": "group_id",+ "description": "Group JID (e.g., [email protected])",+ "schema": { "type": "string" },+ "required": false+ },+ {+ "name": "type",+ "description": "Message type",+ "schema": {+ "type": "string",+ "enum": ["text", "image", "video", "audio", "document", "sticker", "location", "contact"]+ },+ "required": true+ },+ {+ "name": "message",+ "description": "Text content (for text messages)",+ "schema": { "type": "string" },+ "required": false+ },+ {+ "name": "media_data",+ "description": "Media content (for media messages)",+ "schema": { "$ref": "#/components/schemas/MediaData" },+ "required": false+ },+ {+ "name": "location",+ "description": "Location data (for location messages)",+ "schema": { "$ref": "#/components/schemas/LocationData" },+ "required": false+ },+ {+ "name": "contact",+ "description": "Contact card (for contact messages)",+ "schema": { "$ref": "#/components/schemas/ContactCard" },+ "required": false+ },+ {+ "name": "reply",+ "description": "Reply context for quoting a message",+ "schema": { "$ref": "#/components/schemas/ReplyData" },+ "required": false+ },+ {+ "name": "metadata",+ "description": "Custom metadata key-value pairs",+ "schema": { "type": "object", "additionalProperties": { "type": "string" } },+ "required": false+ }+ ],+ "result": {+ "name": "SendResult",+ "schema": {+ "type": "object",+ "properties": {+ "message": { "type": "string", "enum": ["Sent"] }+ }+ }+ }+ },+ {+ "name": "media",+ "summary": "Download media from a received message",+ "params": [+ {+ "name": "message_id",+ "description": "Message ID containing media",+ "schema": { "type": "string" },+ "required": true+ }+ ],+ "result": {+ "name": "MediaResult",+ "schema": {+ "type": "object",+ "properties": {+ "data": { "type": "string", "description": "Base64-encoded media data" },+ "mime_type": { "type": "string", "description": "MIME type of the media" }+ },+ "required": ["data", "mime_type"]+ }+ }+ },+ {+ "name": "groups",+ "summary": "List all groups the user is a member of",+ "params": [],+ "result": {+ "name": "GroupsResult",+ "schema": {+ "type": "array",+ "items": { "$ref": "#/components/schemas/GroupInfo" }+ }+ }+ },+ {+ "name": "group_info",+ "summary": "Get detailed information about a specific group",+ "params": [+ {+ "name": "group_id",+ "description": "Group JID (e.g., [email protected])",+ "schema": { "type": "string" },+ "required": true+ }+ ],+ "result": {+ "name": "GroupInfoResult",+ "schema": { "$ref": "#/components/schemas/GroupInfo" }+ }+ },+ {+ "name": "group_update",+ "summary": "Update group name and/or description",+ "params": [+ {+ "name": "group_id",+ "description": "Group JID",+ "schema": { "type": "string" },+ "required": true+ },+ {+ "name": "name",+ "description": "New group name",+ "schema": { "type": "string" },+ "required": false+ },+ {+ "name": "topic",+ "description": "New group description",+ "schema": { "type": "string" },+ "required": false+ }+ ],+ "result": {+ "name": "GroupUpdateResult",+ "schema": {+ "type": "object",+ "properties": {+ "message": { "type": "string", "enum": ["Updated"] }+ }+ }+ }+ },+ {+ "name": "contact_check",+ "summary": "Check if phone numbers are registered on WhatsApp",+ "params": [+ {+ "name": "phones",+ "description": "Array of phone numbers to check (without + prefix)",+ "schema": { "type": "array", "items": { "type": "string" } },+ "required": true+ }+ ],+ "result": {+ "name": "ContactCheckResult",+ "schema": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "query": { "type": "string", "description": "Original phone number queried" },+ "jid": { "type": "string", "description": "WhatsApp JID if registered" },+ "is_registered": { "type": "boolean" },+ "is_business": { "type": "boolean" },+ "business_name": { "type": "string" }+ },+ "required": ["query", "is_registered"]+ }+ }+ }+ },+ {+ "name": "contact_profile_pic",+ "summary": "Get profile picture for a user or group",+ "params": [+ {+ "name": "jid",+ "description": "User or group JID",+ "schema": { "type": "string" },+ "required": true+ },+ {+ "name": "preview",+ "description": "Get smaller preview image",+ "schema": { "type": "boolean" },+ "required": false+ }+ ],+ "result": {+ "name": "ProfilePicResult",+ "schema": {+ "type": "object",+ "properties": {+ "exists": { "type": "boolean", "description": "Whether profile picture exists" },+ "url": { "type": "string", "description": "URL to download image" },+ "id": { "type": "string", "description": "Image identifier" },+ "data": { "type": "string", "description": "Base64-encoded image data" }+ },+ "required": ["exists"]+ }+ }+ },+ {+ "name": "typing",+ "summary": "Send typing indicator to a chat",+ "params": [+ {+ "name": "jid",+ "description": "Chat JID (individual or group)",+ "schema": { "type": "string" },+ "required": true+ },+ {+ "name": "state",+ "description": "Typing state: 'composing' or 'paused'",+ "schema": { "type": "string", "enum": ["composing", "paused"] },+ "required": true+ },+ {+ "name": "media",+ "description": "Media type: '' for text, 'audio' for voice recording",+ "schema": { "type": "string", "enum": ["", "text", "audio"] },+ "required": false+ }+ ],+ "result": {+ "name": "TypingResult",+ "schema": {+ "type": "object",+ "properties": {+ "message": { "type": "string", "enum": ["Typing indicator sent"] }+ }+ }+ }+ },+ {+ "name": "presence",+ "summary": "Set online/offline presence status",+ "params": [+ {+ "name": "status",+ "description": "Presence status: 'available' or 'unavailable'",+ "schema": { "type": "string", "enum": ["available", "unavailable"] },+ "required": true+ }+ ],+ "result": {+ "name": "PresenceResult",+ "schema": {+ "type": "object",+ "properties": {+ "message": { "type": "string", "enum": ["Presence set"] }+ }+ }+ }+ },+ {+ "name": "mark_read",+ "summary": "Mark messages as read",+ "params": [+ {+ "name": "message_ids",+ "description": "Array of message IDs to mark as read",+ "schema": { "type": "array", "items": { "type": "string" } },+ "required": true+ },+ {+ "name": "chat_jid",+ "description": "Chat JID where messages are from",+ "schema": { "type": "string" },+ "required": true+ },+ {+ "name": "sender_jid",+ "description": "Sender JID (required for group messages)",+ "schema": { "type": "string" },+ "required": false+ }+ ],+ "result": {+ "name": "MarkReadResult",+ "schema": {+ "type": "object",+ "properties": {+ "message": { "type": "string", "enum": ["Messages marked as read"] }+ }+ }+ }+ },+ {+ "name": "group_participants_add",+ "summary": "Add participants to a group",+ "params": [+ {+ "name": "group_id",+ "description": "Group JID (e.g., [email protected])",+ "schema": { "type": "string" },+ "required": true+ },+ {+ "name": "participants",+ "description": "Array of phone numbers or JIDs to add",+ "schema": { "type": "array", "items": { "type": "string" } },+ "required": true+ }+ ],+ "result": {+ "name": "GroupParticipantsAddResult",+ "schema": { "$ref": "#/components/schemas/GroupParticipantsResult" }+ }+ },+ {+ "name": "group_participants_remove",+ "summary": "Remove participants from a group",+ "params": [+ {+ "name": "group_id",+ "description": "Group JID (e.g., [email protected])",+ "schema": { "type": "string" },+ "required": true+ },+ {+ "name": "participants",+ "description": "Array of phone numbers or JIDs to remove",+ "schema": { "type": "array", "items": { "type": "string" } },+ "required": true+ }+ ],+ "result": {+ "name": "GroupParticipantsRemoveResult",+ "schema": { "$ref": "#/components/schemas/GroupParticipantsResult" }+ }+ },+ {+ "name": "group_invite_link",+ "summary": "Get group invite link",+ "params": [+ {+ "name": "group_id",+ "description": "Group JID",+ "schema": { "type": "string" },+ "required": true+ }+ ],+ "result": {+ "name": "GroupInviteLinkResult",+ "schema": { "$ref": "#/components/schemas/GroupInviteLinkResult" }+ }+ },+ {+ "name": "group_revoke_invite",+ "summary": "Revoke and regenerate group invite link",+ "params": [+ {+ "name": "group_id",+ "description": "Group JID",+ "schema": { "type": "string" },+ "required": true+ }+ ],+ "result": {+ "name": "GroupRevokeInviteResult",+ "schema": { "$ref": "#/components/schemas/GroupInviteLinkResult" }+ }+ },+ {+ "name": "rate_limit_get",+ "summary": "Get rate limit configuration and statistics",+ "params": [],+ "result": {+ "name": "RateLimitGetResult",+ "schema": {+ "type": "object",+ "properties": {+ "config": { "$ref": "#/components/schemas/RateLimitConfig" },+ "stats": { "$ref": "#/components/schemas/RateLimitStats" }+ },+ "required": ["config", "stats"]+ }+ }+ },+ {+ "name": "rate_limit_set",+ "summary": "Update rate limit configuration",+ "params": [+ {+ "name": "enabled",+ "description": "Enable/disable rate limiting",+ "schema": { "type": "boolean" },+ "required": false+ },+ {+ "name": "min_delay_ms",+ "description": "Minimum delay between messages (milliseconds)",+ "schema": { "type": "integer" },+ "required": false+ },+ {+ "name": "max_delay_ms",+ "description": "Maximum delay for randomization (milliseconds)",+ "schema": { "type": "integer" },+ "required": false+ },+ {+ "name": "typing_delay_ms",+ "description": "Typing indicator duration (milliseconds)",+ "schema": { "type": "integer" },+ "required": false+ },+ {+ "name": "link_extra_delay_ms",+ "description": "Extra delay for messages with links (milliseconds)",+ "schema": { "type": "integer" },+ "required": false+ },+ {+ "name": "max_messages_per_minute",+ "description": "Maximum messages per minute",+ "schema": { "type": "integer" },+ "required": false+ },+ {+ "name": "max_messages_per_hour",+ "description": "Maximum messages per hour",+ "schema": { "type": "integer" },+ "required": false+ },+ {+ "name": "max_new_contacts_per_day",+ "description": "Maximum new contacts per day",+ "schema": { "type": "integer" },+ "required": false+ },+ {+ "name": "simulate_typing",+ "description": "Send typing indicator before messages",+ "schema": { "type": "boolean" },+ "required": false+ },+ {+ "name": "randomize_delays",+ "description": "Add random variance to delays",+ "schema": { "type": "boolean" },+ "required": false+ },+ {+ "name": "pause_on_low_response",+ "description": "Auto-pause if response rate drops",+ "schema": { "type": "boolean" },+ "required": false+ },+ {+ "name": "response_rate_threshold",+ "description": "Minimum response rate threshold (0.0-1.0)",+ "schema": { "type": "number" },+ "required": false+ }+ ],+ "result": {+ "name": "RateLimitSetResult",+ "schema": {+ "type": "object",+ "properties": {+ "message": { "type": "string" },+ "config": { "$ref": "#/components/schemas/RateLimitConfig" }+ }+ }+ }+ },+ {+ "name": "rate_limit_stats",+ "summary": "Get current rate limiting statistics only",+ "params": [],+ "result": {+ "name": "RateLimitStatsResult",+ "schema": { "$ref": "#/components/schemas/RateLimitStats" }+ }+ },+ {+ "name": "rate_limit_unpause",+ "summary": "Resume rate limiting after automatic pause",+ "params": [],+ "result": {+ "name": "RateLimitUnpauseResult",+ "schema": {+ "type": "object",+ "properties": {+ "message": { "type": "string" },+ "stats": { "$ref": "#/components/schemas/RateLimitStats" }+ }+ }+ }+ }+ ],+ "components": {+ "schemas": {+ "MediaData": {+ "type": "object",+ "description": "Media content for sending",+ "properties": {+ "data": { "type": "string", "description": "Base64-encoded media data" },+ "mime_type": { "type": "string", "description": "MIME type (e.g., image/jpeg, video/mp4)" },+ "filename": { "type": "string", "description": "Optional filename for documents" },+ "caption": { "type": "string", "description": "Optional caption for images/videos" },+ "thumbnail": { "type": "string", "description": "Optional base64 thumbnail" }+ },+ "required": ["data", "mime_type"]+ },+ "LocationData": {+ "type": "object",+ "description": "Location information",+ "properties": {+ "latitude": { "type": "number" },+ "longitude": { "type": "number" },+ "name": { "type": "string", "description": "Location name" },+ "address": { "type": "string", "description": "Address" }+ },+ "required": ["latitude", "longitude"]+ },+ "ContactCard": {+ "type": "object",+ "description": "Contact vCard",+ "properties": {+ "display_name": { "type": "string" },+ "vcard": { "type": "string", "description": "vCard 3.0 format string" }+ },+ "required": ["display_name", "vcard"]+ },+ "ReplyData": {+ "type": "object",+ "description": "Reply context for quoting messages",+ "properties": {+ "message_id": { "type": "string", "description": "ID of message to reply to" },+ "sender": { "type": "string", "description": "Sender JID of quoted message" },+ "content": { "type": "string", "description": "Text preview of quoted message" }+ },+ "required": ["message_id", "sender", "content"]+ },+ "GroupInfo": {+ "type": "object",+ "description": "Group information",+ "properties": {+ "jid": { "type": "string", "description": "Group JID (e.g., [email protected])" },+ "name": { "type": "string" },+ "topic": { "type": "string", "description": "Group description" },+ "owner": { "type": "string", "description": "Owner JID" },+ "participants": {+ "type": "array",+ "items": { "$ref": "#/components/schemas/GroupParticipant" }+ },+ "created_at": { "type": "string", "format": "date-time" },+ "size": { "type": "integer", "description": "Number of participants" },+ "is_announce": { "type": "boolean", "description": "Only admins can send messages" },+ "is_locked": { "type": "boolean", "description": "Only admins can edit group info" }+ },+ "required": ["jid", "name", "owner", "participants", "size"]+ },+ "GroupParticipant": {+ "type": "object",+ "description": "Group member with resolved phone number",+ "properties": {+ "jid": { "type": "string", "description": "Participant JID (may be LID format)" },+ "phone": { "type": "string", "description": "Real phone number (resolved from LID if needed)" },+ "name": { "type": "string" },+ "is_admin": { "type": "boolean" },+ "is_super_admin": { "type": "boolean", "description": "True for group owner" }+ },+ "required": ["jid", "phone", "is_admin", "is_super_admin"]+ },+ "GroupParticipantsResult": {+ "type": "object",+ "description": "Result of participant changes",+ "properties": {+ "group_id": { "type": "string", "description": "Group JID" },+ "action": { "type": "string", "enum": ["add", "remove"], "description": "Action performed" },+ "results": {+ "type": "array",+ "items": { "$ref": "#/components/schemas/GroupParticipantChangeResult" }+ },+ "added": { "type": "integer", "description": "Number of participants successfully added" },+ "removed": { "type": "integer", "description": "Number of participants successfully removed" },+ "failed": { "type": "integer", "description": "Number of failed operations" }+ },+ "required": ["group_id", "action", "results", "failed"]+ },+ "GroupParticipantChangeResult": {+ "type": "object",+ "description": "Result for a single participant change",+ "properties": {+ "jid": { "type": "string", "description": "Participant JID" },+ "phone": { "type": "string", "description": "Phone number" },+ "success": { "type": "boolean", "description": "Whether operation succeeded" },+ "error": { "type": "string", "description": "Error message if failed" }+ },+ "required": ["jid", "success"]+ },+ "GroupInviteLinkResult": {+ "type": "object",+ "description": "Group invite link information",+ "properties": {+ "group_id": { "type": "string", "description": "Group JID" },+ "invite_link": { "type": "string", "description": "Full invite link (https://chat.whatsapp.com/...)" },+ "revoked": { "type": "boolean", "description": "Whether old link was revoked" }+ },+ "required": ["group_id", "invite_link"]+ },+ "RateLimitConfig": {+ "type": "object",+ "description": "Rate limiting configuration for anti-ban protection",+ "properties": {+ "enabled": { "type": "boolean", "default": true, "description": "Enable rate limiting" },+ "min_delay_ms": { "type": "integer", "default": 3000, "description": "Minimum delay between messages (ms)" },+ "max_delay_ms": { "type": "integer", "default": 8000, "description": "Maximum delay for randomization (ms)" },+ "typing_delay_ms": { "type": "integer", "default": 2000, "description": "Typing indicator duration (ms)" },+ "link_extra_delay_ms": { "type": "integer", "default": 5000, "description": "Extra delay for messages with links (ms)" },+ "max_messages_per_minute": { "type": "integer", "default": 10, "description": "Per-minute message limit" },+ "max_messages_per_hour": { "type": "integer", "default": 60, "description": "Per-hour message limit" },+ "max_new_contacts_per_day": { "type": "integer", "default": 20, "description": "Daily new contacts limit" },+ "simulate_typing": { "type": "boolean", "default": true, "description": "Send typing indicator before messages" },+ "randomize_delays": { "type": "boolean", "default": true, "description": "Add random variance to delays" },+ "pause_on_low_response": { "type": "boolean", "default": false, "description": "Auto-pause if response rate drops" },+ "response_rate_threshold": { "type": "number", "default": 0.3, "description": "Minimum response rate (0.0-1.0)" }+ }+ },+ "RateLimitStats": {+ "type": "object",+ "description": "Current rate limiting statistics",+ "properties": {+ "messages_sent_last_minute": { "type": "integer", "description": "Messages sent in last 60 seconds" },+ "messages_sent_last_hour": { "type": "integer", "description": "Messages sent in last 60 minutes" },+ "messages_sent_today": { "type": "integer", "description": "Total messages sent today" },+ "new_contacts_today": { "type": "integer", "description": "New contacts messaged today" },+ "responses_received": { "type": "integer", "description": "Responses received today" },+ "response_rate": { "type": "number", "description": "Response rate (responses/sent)" },+ "is_paused": { "type": "boolean", "description": "Whether rate limiting is paused" },+ "pause_reason": { "type": "string", "description": "Reason for pause if paused" },+ "last_message_time": { "type": "string", "format": "date-time", "description": "Time of last sent message" },+ "next_allowed_time": { "type": "string", "format": "date-time", "description": "Earliest time next message allowed" }+ }+ },+ "ReceivedMedia": {+ "type": "object",+ "description": "Received media (image/video) information",+ "properties": {+ "mime_type": { "type": "string" },+ "file_sha256": { "type": "string" },+ "file_length": { "type": "integer" },+ "caption": { "type": "string" },+ "url": { "type": "string" },+ "seconds": { "type": "integer", "description": "Duration for video" }+ }+ },+ "ReceivedAudio": {+ "type": "object",+ "description": "Received audio/voice message information",+ "properties": {+ "mime_type": { "type": "string" },+ "file_sha256": { "type": "string" },+ "file_length": { "type": "integer" },+ "seconds": { "type": "integer" },+ "ptt": { "type": "boolean", "description": "True for voice messages (push-to-talk)" },+ "url": { "type": "string" }+ }+ },+ "ReceivedDocument": {+ "type": "object",+ "description": "Received document information",+ "properties": {+ "mime_type": { "type": "string" },+ "file_sha256": { "type": "string" },+ "file_length": { "type": "integer" },+ "file_name": { "type": "string" },+ "title": { "type": "string" },+ "caption": { "type": "string" },+ "url": { "type": "string" }+ }+ },+ "ReceivedContact": {+ "type": "object",+ "description": "Received contact vCard",+ "properties": {+ "display_name": { "type": "string" },+ "vcard": { "type": "string" }+ }+ },+ "ReceivedSticker": {+ "type": "object",+ "description": "Received sticker information",+ "properties": {+ "mime_type": { "type": "string" },+ "file_sha256": { "type": "string" },+ "file_length": { "type": "integer" },+ "is_animated": { "type": "boolean", "description": "True for animated stickers" },+ "url": { "type": "string" }+ }+ }+ },+ "events": {+ "description": "Server-sent notifications (JSON-RPC without id)",+ "types": {+ "event.status": {+ "description": "Initial status sent on WebSocket connection",+ "params": {+ "connected": { "type": "boolean" },+ "has_session": { "type": "boolean" },+ "running": { "type": "boolean" },+ "pairing": { "type": "boolean" },+ "device_id": { "type": "string" },+ "timestamp": { "type": "string", "format": "date-time" }+ }+ },+ "event.connected": {+ "description": "WhatsApp connected successfully",+ "params": {+ "status": { "type": "string", "enum": ["connected"] },+ "device_id": { "type": "string" }+ }+ },+ "event.disconnected": {+ "description": "WhatsApp disconnected",+ "params": {+ "status": { "type": "string", "enum": ["disconnected"] },+ "reason": { "type": "string" }+ }+ },+ "event.connection_failure": {+ "description": "Connection failed",+ "params": {+ "error": { "type": "string" },+ "reason": { "type": "string" }+ }+ },+ "event.logged_out": {+ "description": "User logged out",+ "params": {+ "on_connect": { "type": "boolean" },+ "reason": { "type": "string" }+ }+ },+ "event.temporary_ban": {+ "description": "Temporary ban received",+ "params": {+ "code": { "type": "string" },+ "reason": { "type": "string" }+ }+ },+ "event.qr_code": {+ "description": "New QR code available for pairing",+ "params": {+ "code": { "type": "string", "description": "QR code content" },+ "filename": { "type": "string", "description": "PNG file path" },+ "image_data": { "type": "string", "description": "Base64-encoded PNG data" }+ }+ },+ "event.message_sent": {+ "description": "Message sent successfully",+ "params": {+ "message_id": { "type": "string" },+ "to": { "type": "string" },+ "type": { "type": "string" },+ "timestamp": { "type": "string", "format": "date-time" }+ }+ },+ "event.message_received": {+ "description": "New message received",+ "params": {+ "message_id": { "type": "string" },+ "sender": { "type": "string", "description": "Sender JID" },+ "chat_id": { "type": "string", "description": "Chat JID (same as sender for DMs, group JID for groups)" },+ "timestamp": { "type": "string", "format": "date-time" },+ "is_from_me": { "type": "boolean" },+ "is_group": { "type": "boolean" },+ "is_forwarded": { "type": "boolean", "description": "Whether the message was forwarded" },+ "forwarding_score": { "type": "integer", "description": "Number of times forwarded (higher = forwarded many times)" },+ "message_type": {+ "type": "string",+ "enum": ["text", "image", "video", "audio", "document", "sticker", "location", "contact", "contacts"]+ },+ "content": { "type": "object", "description": "Message content (varies by type)" },+ "text": { "type": "string", "description": "Text content (for text messages)" },+ "image": { "$ref": "#/components/schemas/ReceivedMedia" },+ "video": { "$ref": "#/components/schemas/ReceivedMedia" },+ "audio": { "$ref": "#/components/schemas/ReceivedAudio" },+ "document": { "$ref": "#/components/schemas/ReceivedDocument" },+ "sticker": { "$ref": "#/components/schemas/ReceivedSticker" },+ "location": { "$ref": "#/components/schemas/LocationData" },+ "contact": { "$ref": "#/components/schemas/ReceivedContact" },+ "contacts": {+ "type": "array",+ "items": { "$ref": "#/components/schemas/ReceivedContact" }+ },+ "group_info": {+ "type": "object",+ "description": "Present for group messages",+ "properties": {+ "group_jid": { "type": "string" },+ "sender_jid": { "type": "string" },+ "sender_name": { "type": "string" }+ }+ },+ "is_reply": { "type": "boolean" },+ "quoted_message_id": { "type": "string" }+ }+ }+ }+ }+ },+ "examples": {+ "request": {+ "description": "JSON-RPC 2.0 request format",+ "value": {+ "jsonrpc": "2.0",+ "id": 1,+ "method": "status",+ "params": {}+ }+ },+ "response": {+ "description": "JSON-RPC 2.0 response format",+ "value": {+ "jsonrpc": "2.0",+ "id": 1,+ "result": {+ "connected": true,+ "has_session": true,+ "running": true,+ "pairing": false,+ "device_id": "[email protected]",+ "timestamp": "2025-01-15T10:30:00Z"+ }+ }+ },+ "event": {+ "description": "JSON-RPC 2.0 notification (no id)",+ "value": {+ "jsonrpc": "2.0",+ "method": "event.message_received",+ "params": {+ "message_id": "ABC123",+ "sender": "[email protected]",+ "chat_id": "[email protected]",+ "timestamp": "2025-01-15T10:30:00Z",+ "is_from_me": false,+ "is_group": false,+ "message_type": "text",+ "text": "Hello world!",+ "content": "Hello world!"+ }+ }+ },+ "send_text": {+ "description": "Send text message",+ "value": {+ "jsonrpc": "2.0",+ "id": 2,+ "method": "send",+ "params": {+ "phone": "1234567890",+ "type": "text",+ "message": "Hello from API!"+ }+ }+ },+ "send_image": {+ "description": "Send image message",+ "value": {+ "jsonrpc": "2.0",+ "id": 3,+ "method": "send",+ "params": {+ "phone": "1234567890",+ "type": "image",+ "media_data": {+ "data": "base64_encoded_image_data",+ "mime_type": "image/jpeg",+ "caption": "Check this out!"+ }+ }+ }+ },+ "send_to_group": {+ "description": "Send message to group",+ "value": {+ "jsonrpc": "2.0",+ "id": 4,+ "method": "send",+ "params": {+ "group_id": "[email protected]",+ "type": "text",+ "message": "Hello group!"+ }+ }+ },+ "send_location": {+ "description": "Send location message",+ "value": {+ "jsonrpc": "2.0",+ "id": 5,+ "method": "send",+ "params": {+ "phone": "1234567890",+ "type": "location",+ "location": {+ "latitude": 37.7749,+ "longitude": -122.4194,+ "name": "San Francisco",+ "address": "California, USA"+ }+ }+ }+ },+ "download_media": {+ "description": "Download media from message",+ "value": {+ "jsonrpc": "2.0",+ "id": 6,+ "method": "media",+ "params": {+ "message_id": "ABC123DEF456"+ }+ }+ },+ "error_response": {+ "description": "Error response format",+ "value": {+ "jsonrpc": "2.0",+ "id": 1,+ "error": {+ "code": -32000,+ "message": "WhatsApp not connected"+ }+ }+ },+ "rate_limit_get": {+ "description": "Get rate limit config and stats",+ "value": {+ "jsonrpc": "2.0",+ "id": 7,+ "method": "rate_limit_get",+ "params": {}+ }+ },+ "rate_limit_set": {+ "description": "Update rate limit configuration",+ "value": {+ "jsonrpc": "2.0",+ "id": 8,+ "method": "rate_limit_set",+ "params": {+ "enabled": true,+ "min_delay_ms": 5000,+ "max_messages_per_hour": 30,+ "simulate_typing": true+ }+ }+ },+ "rate_limit_unpause": {+ "description": "Resume after automatic pause",+ "value": {+ "jsonrpc": "2.0",+ "id": 9,+ "method": "rate_limit_unpause",+ "params": {}+ }+ }+ },+ "errorCodes": {+ "-32700": "Parse error - Invalid JSON",+ "-32600": "Invalid Request - Not a valid JSON-RPC 2.0 request",+ "-32601": "Method not found",+ "-32602": "Invalid params",+ "-32000": "Server error (WhatsApp operation failed)",+ "-32001": "No QR available"+ }+}diff --git a/server/whatsapp-rpc/scripts/clean.cjs b/server/whatsapp-rpc/scripts/clean.cjsnew file mode 100644index 00000000..3ede1632--- /dev/null+++ b/server/whatsapp-rpc/scripts/clean.cjs@@ -0,0 +1,66 @@+#!/usr/bin/env node+// Standalone clean script - no npm dependencies required+const { existsSync, unlinkSync, readdirSync, rmSync } = require('fs');+const { join } = require('path');+const { execSync } = require('child_process');++const ROOT = join(__dirname, '..');+const BIN = process.platform === 'win32' ? 'whatsapp-rpc-server.exe' : 'whatsapp-rpc-server';+const BIN_DIR = join(ROOT, 'bin');++const log = (msg, color) => {+ const colors = { green: '\x1b[32m', blue: '\x1b[34m', yellow: '\x1b[33m', reset: '\x1b[0m' };+ console.log(`${colors[color] || ''}${msg}${colors.reset}`);+};++// Kill process on port+const killPort = (port, name) => {+ try {+ if (process.platform === 'win32') {+ execSync(`for /f "tokens=5" %a in ('netstat -aon ^| findstr :${port} ^| findstr LISTENING') do taskkill /F /PID %a`, { stdio: 'ignore', shell: 'cmd.exe' });+ } else {+ execSync(`lsof -ti:${port} | xargs kill -9 2>/dev/null || true`, { stdio: 'ignore' });+ }+ log(`${name} stopped`, 'green');+ } catch { log(`${name} not running`, 'yellow'); }+};++log('Stopping all processes...', 'blue');+killPort(9400, 'API');+killPort(5000, 'Web');++// Remove binary+const bin = join(BIN_DIR, BIN);+if (existsSync(bin)) { unlinkSync(bin); log(`Removed ${BIN}`, 'green'); }++// Remove bin directory if empty+if (existsSync(BIN_DIR) && readdirSync(BIN_DIR).length === 0) {+ rmSync(BIN_DIR, { recursive: true }); log('Removed bin/', 'green');+}++// Remove entire data directory (database, QR codes, etc.)+const dataDir = join(ROOT, 'data');+if (existsSync(dataDir)) {+ rmSync(dataDir, { recursive: true });+ log('Removed data/', 'green');+}++// Remove any .db files in project root (legacy locations)+readdirSync(ROOT).filter(f => f.endsWith('.db') || f.endsWith('.db-wal') || f.endsWith('.db-shm')).forEach(f => {+ unlinkSync(join(ROOT, f));+ log(`Removed ${f}`, 'green');+});++// Remove node_modules+const nodeModules = join(ROOT, 'node_modules');+if (existsSync(nodeModules)) { rmSync(nodeModules, { recursive: true }); log('Removed node_modules/', 'green'); }++// Remove Python cache+const pycache = join(ROOT, 'web', '__pycache__');+if (existsSync(pycache)) { rmSync(pycache, { recursive: true }); log('Removed web/__pycache__/', 'green'); }++// Remove package-lock.json+const lockFile = join(ROOT, 'package-lock.json');+if (existsSync(lockFile)) { unlinkSync(lockFile); log('Removed package-lock.json', 'green'); }++log('Clean complete', 'green');diff --git a/server/whatsapp-rpc/scripts/cli.js b/server/whatsapp-rpc/scripts/cli.jsnew file mode 100644index 00000000..df7e2d6b--- /dev/null+++ b/server/whatsapp-rpc/scripts/cli.js@@ -0,0 +1,132 @@+#!/usr/bin/env node+import { program } from 'commander';+import chalk from 'chalk';+import { execa } from 'execa';+import killPort from 'kill-port';+import { Socket } from 'net';+import { execSync, spawn } from 'child_process';+import { existsSync, statSync, unlinkSync, readdirSync, rmSync } from 'fs';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';++const __dirname = dirname(fileURLToPath(import.meta.url));+const ROOT = join(__dirname, '..');+const API_PORT = 9400, WEB_PORT = 5000;+const BIN = process.platform === 'win32' ? 'whatsapp-rpc-server.exe' : 'whatsapp-rpc-server';+const BIN_DIR = join(ROOT, 'bin');++const log = (m, c = 'blue') => console.log(chalk[c](m));+const sleep = ms => new Promise(r => setTimeout(r, ms));++const portUp = port => new Promise(r => {+ const s = new Socket();+ s.setTimeout(2000);+ s.on('connect', () => { s.destroy(); r(true); });+ s.on('timeout', () => { s.destroy(); r(false); });+ s.on('error', () => r(false));+ s.connect(port, '127.0.0.1');+});++const wait = async (port, ms = 10000) => {+ const t = Date.now();+ while (Date.now() - t < ms) { if (await portUp(port)) return true; await sleep(500); }+ return false;+};++const kill = async (port, name) => {+ try { await killPort(port); log(`${name} stopped`, 'green'); }+ catch { log(`${name} not running`, 'yellow'); }+};++const py = () => {+ try { execSync('python --version', { stdio: 'ignore' }); return 'python'; }+ catch { try { execSync('python3 --version', { stdio: 'ignore' }); return 'python3'; } catch { return null; } }+};++async function api() {+ if (await portUp(API_PORT)) { log(`API already on ${API_PORT}`, 'yellow'); return; }+ const bin = join(BIN_DIR, BIN);+ if (!existsSync(bin)) { log('Building...', 'yellow'); await build(); }+ spawn(bin, [], { cwd: ROOT, detached: true, stdio: 'ignore' }).unref();+ if (await wait(API_PORT)) log(`API: ws://localhost:${API_PORT}/ws/rpc`, 'green');+ else log('API failed to start', 'red');+}++async function web() {+ if (await portUp(WEB_PORT)) { log(`Web already on ${WEB_PORT}`, 'yellow'); return; }+ const p = py(); if (!p) { log('Python not found', 'red'); return; }+ if (!await portUp(API_PORT)) log('Warning: API not running', 'yellow');+ spawn(p, ['app.py'], { cwd: join(ROOT, 'web'), detached: true, stdio: 'ignore' }).unref();+ if (await wait(WEB_PORT)) log(`Web: http://localhost:${WEB_PORT}`, 'green');+ else log('Web failed to start', 'red');+}++async function start() { await api(); await sleep(1000); await web(); }+async function stop() { await kill(API_PORT, 'API'); await kill(WEB_PORT, 'Web'); }++async function status() {+ const a = await portUp(API_PORT), w = await portUp(WEB_PORT);+ log(`API (${API_PORT}): ${a ? 'UP' : 'DOWN'}`, a ? 'green' : 'red');+ log(`Web (${WEB_PORT}): ${w ? 'UP' : 'DOWN'}`, w ? 'green' : 'red');+}++async function build() {+ const bin = join(BIN_DIR, BIN);+ if (!existsSync(BIN_DIR)) { await execa('mkdir', ['-p', BIN_DIR]); }+ if (existsSync(bin)) unlinkSync(bin);+ await execa('go', ['build', '-o', bin, './src/go/cmd/server'], { cwd: ROOT, stdio: 'inherit' });+ log(`Built: ${BIN} (${(statSync(bin).size / 1024 / 1024).toFixed(1)}MB)`, 'green');+}++async function clean() {+ log('Stopping all processes...', 'blue');+ await stop();+ await sleep(1000);++ // Remove binary+ const bin = join(BIN_DIR, BIN);+ if (existsSync(bin)) { unlinkSync(bin); log(`Removed ${BIN}`, 'green'); }++ // Remove bin directory if empty+ if (existsSync(BIN_DIR) && readdirSync(BIN_DIR).length === 0) {+ rmSync(BIN_DIR, { recursive: true }); log('Removed bin/', 'green');+ }++ // Remove entire data directory (database, QR codes, etc.)+ const dataDir = join(ROOT, 'data');+ if (existsSync(dataDir)) {+ rmSync(dataDir, { recursive: true });+ log('Removed data/', 'green');+ }++ // Remove any .db files in project root (legacy locations)+ readdirSync(ROOT).filter(f => f.endsWith('.db') || f.endsWith('.db-wal') || f.endsWith('.db-shm')).forEach(f => {+ unlinkSync(join(ROOT, f));+ log(`Removed ${f}`, 'green');+ });++ // Remove node_modules+ const nodeModules = join(ROOT, 'node_modules');+ if (existsSync(nodeModules)) { rmSync(nodeModules, { recursive: true }); log('Removed node_modules/', 'green'); }++ // Remove Python cache+ const pycache = join(ROOT, 'web', '__pycache__');+ if (existsSync(pycache)) { rmSync(pycache, { recursive: true }); log('Removed web/__pycache__/', 'green'); }++ // Remove package-lock.json+ const lockFile = join(ROOT, 'package-lock.json');+ if (existsSync(lockFile)) { unlinkSync(lockFile); log('Removed package-lock.json', 'green'); }++ log('Clean complete', 'green');+}++program.name('wa').version('1.0.0');+program.command('start').description('Start all').action(start);+program.command('stop').description('Stop all').action(stop);+program.command('restart').description('Restart all').action(async () => { await stop(); await sleep(1000); await start(); });+program.command('status').description('Status').action(status);+program.command('api').description('Start API only').action(api);+program.command('web').description('Start Web only').action(web);+program.command('build').description('Build binary').action(build);+program.command('clean').description('Clean artifacts').action(clean);+program.parse();diff --git a/server/whatsapp-rpc/src/go/cmd/server/main.go b/server/whatsapp-rpc/src/go/cmd/server/main.gonew file mode 100644index 00000000..c90247d0--- /dev/null+++ b/server/whatsapp-rpc/src/go/cmd/server/main.go@@ -0,0 +1,81 @@+package main++import (+ "context"+ "fmt"+ "net/http"+ "os"+ "os/signal"+ "syscall"+ "time"++ "github.com/sirupsen/logrus"++ "whatsapp-rpc/src/go/config"+ server "whatsapp-rpc/src/go/rpc"+ "whatsapp-rpc/src/go/whatsapp"+)++func main() {+ // Initialize logger+ logger := logrus.New()+ logger.SetFormatter(&logrus.TextFormatter{+ FullTimestamp: true,+ })++ // Load configuration+ cfg, err := config.Load()+ if err != nil {+ logger.Fatalf("Failed to load config: %v", err)+ }++ // Set log level (5 = Debug, 4 = Info)+ if cfg.LogLevel >= 5 {+ logger.SetLevel(logrus.DebugLevel)+ }++ logger.Info("Starting WhatsApp WebSocket RPC Server")++ // Initialize WhatsApp service+ whatsappService, err := whatsapp.NewService(cfg.Database, logger)+ if err != nil {+ logger.Fatalf("Failed to initialize WhatsApp service: %v", err)+ }++ // Create and start server (WebSocket RPC only)+ srv := server.New(whatsappService, logger)+ router := srv.SetupRoutes()++ httpServer := &http.Server{+ Addr: fmt.Sprintf(":%d", cfg.Server.Port),+ Handler: router,+ }++ // Start server in goroutine+ go func() {+ logger.Infof("WebSocket RPC server listening on port %d", cfg.Server.Port)+ logger.Infof("Connect via: ws://localhost:%d/ws/rpc", cfg.Server.Port)+ if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {+ logger.Fatalf("Server error: %v", err)+ }+ }()++ // Wait for interrupt signal+ quit := make(chan os.Signal, 1)+ signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)+ <-quit++ logger.Info("Shutting down server...")++ // Graceful shutdown+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ whatsappService.Shutdown()++ if err := httpServer.Shutdown(ctx); err != nil {+ logger.Errorf("Server shutdown error: %v", err)+ }++ logger.Info("Server stopped")+}diff --git a/server/whatsapp-rpc/src/go/config/config.go b/server/whatsapp-rpc/src/go/config/config.gonew file mode 100644index 00000000..566f127e--- /dev/null+++ b/server/whatsapp-rpc/src/go/config/config.go@@ -0,0 +1,49 @@+package config++import (+ "github.com/spf13/viper"+)++type Config struct {+ Environment string `mapstructure:"environment"`+ LogLevel int `mapstructure:"log_level"`+ Server ServerConfig `mapstructure:"server"`+ Database DatabaseConfig `mapstructure:"database"`+}++type ServerConfig struct {+ Port int `mapstructure:"port"`+ Host string `mapstructure:"host"`+}++type DatabaseConfig struct {+ Path string `mapstructure:"path"`+}++func Load() (*Config, error) {+ viper.SetDefault("environment", "development")+ viper.SetDefault("log_level", 4) // Info level+ viper.SetDefault("server.port", 9400)+ viper.SetDefault("server.host", "0.0.0.0")+ viper.SetDefault("database.path", "data/whatsapp.db")++ // Environment variables+ viper.SetEnvPrefix("WA")+ viper.AutomaticEnv()++ // Config file+ viper.SetConfigName("config")+ viper.SetConfigType("yaml")+ viper.AddConfigPath(".")+ viper.AddConfigPath("./configs")++ // Read config file (optional)+ viper.ReadInConfig()++ var config Config+ if err := viper.Unmarshal(&config); err != nil {+ return nil, err+ }++ return &config, nil+}\ No newline at end of filediff --git a/server/whatsapp-rpc/src/go/rpc/rpc.go b/server/whatsapp-rpc/src/go/rpc/rpc.gonew file mode 100644index 00000000..fc6e595a--- /dev/null+++ b/server/whatsapp-rpc/src/go/rpc/rpc.go@@ -0,0 +1,373 @@+package server++import (+ "encoding/base64"+ "encoding/json"+ "os"+ "sync"++ "github.com/gorilla/websocket"+ "github.com/sirupsen/logrus"++ "whatsapp-rpc/src/go/whatsapp"+)++// JSON-RPC 2.0 message types+type RPCRequest struct {+ JSONRPC string `json:"jsonrpc"`+ ID interface{} `json:"id,omitempty"`+ Method string `json:"method"`+ Params json.RawMessage `json:"params,omitempty"`+}++type RPCResponse struct {+ JSONRPC string `json:"jsonrpc"`+ ID interface{} `json:"id,omitempty"`+ Result interface{} `json:"result,omitempty"`+ Error *RPCError `json:"error,omitempty"`+}++type RPCError struct {+ Code int `json:"code"`+ Message string `json:"message"`+}++// RPCHandler processes JSON-RPC requests+type RPCHandler struct {+ service *whatsapp.Service+ logger *logrus.Logger+}++// NewRPCHandler creates a new RPC handler+func NewRPCHandler(service *whatsapp.Service, logger *logrus.Logger) *RPCHandler {+ return &RPCHandler{+ service: service,+ logger: logger,+ }+}++// HandleRequest processes a JSON-RPC request and returns a response+func (h *RPCHandler) HandleRequest(req *RPCRequest) RPCResponse {+ resp := RPCResponse{JSONRPC: "2.0", ID: req.ID}++ switch req.Method {+ case "status":+ resp.Result = h.service.GetStatus()++ case "start":+ if err := h.service.Start(); err != nil {+ resp.Error = &RPCError{Code: -32000, Message: err.Error()}+ } else {+ resp.Result = map[string]string{"message": "Started"}+ }++ case "stop":+ h.service.Shutdown()+ resp.Result = map[string]string{"message": "Stopped"}++ case "restart":+ // Full restart: cleanup QR codes, reset session, then start fresh+ h.service.CleanupQRCodes()+ if err := h.service.Reset(); err != nil {+ resp.Error = &RPCError{Code: -32000, Message: err.Error()}+ } else if err := h.service.Start(); err != nil {+ resp.Error = &RPCError{Code: -32000, Message: err.Error()}+ } else {+ resp.Result = map[string]string{"message": "Restarted (session cleared)"}+ }++ case "reset":+ if err := h.service.Reset(); err != nil {+ resp.Error = &RPCError{Code: -32000, Message: err.Error()}+ } else {+ resp.Result = map[string]string{"message": "Reset"}+ }++ case "diagnostics":+ resp.Result = h.service.GetDiagnostics()++ case "qr":+ if qr := h.service.GetCurrentQRCode(); qr != nil {+ result := map[string]interface{}{+ "has_qr": true,+ "code": qr.Code,+ "filename": qr.Filename,+ }+ // Read PNG file and encode to base64 for Docker compatibility+ // qr.Filename already contains full path like "data/qr/qr_xxx.png"+ if data, err := os.ReadFile(qr.Filename); err == nil {+ result["image_data"] = base64.StdEncoding.EncodeToString(data)+ }+ resp.Result = result+ } else {+ resp.Error = &RPCError{Code: -32001, Message: "No QR available"}+ }++ case "send":+ var msgReq whatsapp.MessageRequest+ if err := json.Unmarshal(req.Params, &msgReq); err != nil {+ resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}+ } else if err := h.service.SendEnhancedMessage(&msgReq); err != nil {+ resp.Error = &RPCError{Code: -32000, Message: err.Error()}+ } else {+ resp.Result = map[string]string{"message": "Sent"}+ }++ case "media":+ var p struct {+ MessageID string `json:"message_id"`+ }+ if err := json.Unmarshal(req.Params, &p); err != nil {+ resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}+ } else if data, mime, err := h.service.DownloadMedia(p.MessageID); err != nil {+ resp.Error = &RPCError{Code: -32000, Message: err.Error()}+ } else {+ resp.Result = map[string]interface{}{+ "data": data,+ "mime_type": mime,+ }+ }++ case "groups":+ if groups, err := h.service.GetGroups(); err != nil {+ resp.Error = &RPCError{Code: -32000, Message: err.Error()}+ } else {+ resp.Result = groups+ }++ case "group_info":+ var p struct {+ GroupID string `json:"group_id"`+ }+ if err := json.Unmarshal(req.Params, &p); err != nil {+ resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}+ } else if p.GroupID == "" {+ resp.Error = &RPCError{Code: -32602, Message: "group_id is required"}+ } else if info, err := h.service.GetGroupInfo(p.GroupID); err != nil {+ resp.Error = &RPCError{Code: -32000, Message: err.Error()}+ } else {+ resp.Result = info+ }++ case "group_update":+ var p whatsapp.GroupUpdateRequest+ if err := json.Unmarshal(req.Params, &p); err != nil {+ resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}+ } else if p.GroupID == "" {+ resp.Error = &RPCError{Code: -32602, Message: "group_id is required"}+ } else if p.Name == "" && p.Topic == "" {+ resp.Error = &RPCError{Code: -32602, Message: "name or topic is required"}+ } else if err := h.service.UpdateGroupInfo(p.GroupID, p.Name, p.Topic); err != nil {+ resp.Error = &RPCError{Code: -32000, Message: err.Error()}+ } else {+ resp.Result = map[string]string{"message": "Updated"}+ }++ case "contact_check":+ var p struct {+ Phones []string `json:"phones"`+ }+ if err := json.Unmarshal(req.Params, &p); err != nil {+ resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}+ } else if len(p.Phones) == 0 {+ resp.Error = &RPCError{Code: -32602, Message: "phones array is required and must not be empty"}+ } else if results, err := h.service.CheckContacts(p.Phones); err != nil {+ resp.Error = &RPCError{Code: -32000, Message: err.Error()}+ } else {+ resp.Result = results+ }++ case "contact_profile_pic":+ var p struct {+ JID string `json:"jid"`+ Preview bool `json:"preview"`+ }+ if err := json.Unmarshal(req.Params, &p); err != nil {+ resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}+ } else if p.JID == "" {+ resp.Error = &RPCError{Code: -32602, Message: "jid is required"}+ } else if result, err := h.service.GetProfilePicture(p.JID, p.Preview); err != nil {+ resp.Error = &RPCError{Code: -32000, Message: err.Error()}+ } else {+ resp.Result = result+ }++ case "typing":+ var p struct {+ JID string `json:"jid"`+ State string `json:"state"`+ Media string `json:"media"`+ }+ if err := json.Unmarshal(req.Params, &p); err != nil {+ resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}+ } else if p.JID == "" {+ resp.Error = &RPCError{Code: -32602, Message: "jid is required"}+ } else if p.State == "" {+ resp.Error = &RPCError{Code: -32602, Message: "state is required ('composing' or 'paused')"}+ } else if err := h.service.SendTyping(p.JID, p.State, p.Media); err != nil {+ resp.Error = &RPCError{Code: -32000, Message: err.Error()}+ } else {+ resp.Result = map[string]string{"message": "Typing indicator sent"}+ }++ case "presence":+ var p struct {+ Status string `json:"status"`+ }+ if err := json.Unmarshal(req.Params, &p); err != nil {+ resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}+ } else if p.Status == "" {+ resp.Error = &RPCError{Code: -32602, Message: "status is required ('available' or 'unavailable')"}+ } else if err := h.service.SetPresence(p.Status); err != nil {+ resp.Error = &RPCError{Code: -32000, Message: err.Error()}+ } else {+ resp.Result = map[string]string{"message": "Presence set"}+ }++ case "mark_read":+ var p struct {+ MessageIDs []string `json:"message_ids"`+ ChatJID string `json:"chat_jid"`+ SenderJID string `json:"sender_jid"`+ }+ if err := json.Unmarshal(req.Params, &p); err != nil {+ resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}+ } else if len(p.MessageIDs) == 0 {+ resp.Error = &RPCError{Code: -32602, Message: "message_ids array is required"}+ } else if p.ChatJID == "" {+ resp.Error = &RPCError{Code: -32602, Message: "chat_jid is required"}+ } else if err := h.service.MarkRead(p.MessageIDs, p.ChatJID, p.SenderJID); err != nil {+ resp.Error = &RPCError{Code: -32000, Message: err.Error()}+ } else {+ resp.Result = map[string]string{"message": "Messages marked as read"}+ }++ case "group_participants_add":+ var p struct {+ GroupID string `json:"group_id"`+ Participants []string `json:"participants"`+ }+ if err := json.Unmarshal(req.Params, &p); err != nil {+ resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}+ } else if p.GroupID == "" {+ resp.Error = &RPCError{Code: -32602, Message: "group_id is required"}+ } else if len(p.Participants) == 0 {+ resp.Error = &RPCError{Code: -32602, Message: "participants array is required and must not be empty"}+ } else if result, err := h.service.AddGroupParticipants(p.GroupID, p.Participants); err != nil {+ resp.Error = &RPCError{Code: -32000, Message: err.Error()}+ } else {+ resp.Result = result+ }++ case "group_participants_remove":+ var p struct {+ GroupID string `json:"group_id"`+ Participants []string `json:"participants"`+ }+ if err := json.Unmarshal(req.Params, &p); err != nil {+ resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}+ } else if p.GroupID == "" {+ resp.Error = &RPCError{Code: -32602, Message: "group_id is required"}+ } else if len(p.Participants) == 0 {+ resp.Error = &RPCError{Code: -32602, Message: "participants array is required and must not be empty"}+ } else if result, err := h.service.RemoveGroupParticipants(p.GroupID, p.Participants); err != nil {+ resp.Error = &RPCError{Code: -32000, Message: err.Error()}+ } else {+ resp.Result = result+ }++ case "group_invite_link":+ var p struct {+ GroupID string `json:"group_id"`+ }+ if err := json.Unmarshal(req.Params, &p); err != nil {+ resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}+ } else if p.GroupID == "" {+ resp.Error = &RPCError{Code: -32602, Message: "group_id is required"}+ } else if result, err := h.service.GetGroupInviteLink(p.GroupID); err != nil {+ resp.Error = &RPCError{Code: -32000, Message: err.Error()}+ } else {+ resp.Result = result+ }++ case "group_revoke_invite":+ var p struct {+ GroupID string `json:"group_id"`+ }+ if err := json.Unmarshal(req.Params, &p); err != nil {+ resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}+ } else if p.GroupID == "" {+ resp.Error = &RPCError{Code: -32602, Message: "group_id is required"}+ } else if result, err := h.service.RevokeGroupInviteLink(p.GroupID); err != nil {+ resp.Error = &RPCError{Code: -32000, Message: err.Error()}+ } else {+ resp.Result = result+ }++ case "rate_limit_get":+ resp.Result = map[string]interface{}{+ "config": h.service.GetRateLimitConfig(),+ "stats": h.service.GetRateLimitStats(),+ }++ case "rate_limit_set":+ var config whatsapp.RateLimitConfig+ if err := json.Unmarshal(req.Params, &config); err != nil {+ resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}+ } else if err := h.service.SetRateLimitConfig(&config); err != nil {+ resp.Error = &RPCError{Code: -32000, Message: err.Error()}+ } else {+ resp.Result = map[string]interface{}{+ "message": "Rate limit config updated",+ "config": h.service.GetRateLimitConfig(),+ }+ }++ case "rate_limit_stats":+ resp.Result = h.service.GetRateLimitStats()++ case "rate_limit_unpause":+ h.service.UnpauseRateLimiting()+ resp.Result = map[string]interface{}{+ "message": "Rate limiting unpaused",+ "stats": h.service.GetRateLimitStats(),+ }++ default:+ resp.Error = &RPCError{Code: -32601, Message: "Method not found: " + req.Method}+ }++ return resp+}++// ForwardEvents sends WhatsApp events as JSON-RPC notifications+func (h *RPCHandler) ForwardEvents(conn *websocket.Conn, mu *sync.Mutex, done chan struct{}) {+ eventChan := h.service.GetEventChannel()+ for {+ select {+ case <-done:+ return+ case event, ok := <-eventChan:+ if !ok {+ return+ }+ notif := RPCRequest{+ JSONRPC: "2.0",+ Method: "event." + event.Type,+ Params: mustMarshal(event.Data),+ }+ mu.Lock()+ if err := conn.WriteJSON(notif); err != nil {+ mu.Unlock()+ h.logger.Errorf("Failed to send event: %v", err)+ return+ }+ mu.Unlock()+ }+ }+}++func mustMarshal(v interface{}) json.RawMessage {+ b, _ := json.Marshal(v)+ return b+}diff --git a/server/whatsapp-rpc/src/go/rpc/server.go b/server/whatsapp-rpc/src/go/rpc/server.gonew file mode 100644index 00000000..3eaa5cc6--- /dev/null+++ b/server/whatsapp-rpc/src/go/rpc/server.go@@ -0,0 +1,112 @@+package server++import (+ "net/http"+ "sync"++ "github.com/gin-gonic/gin"+ "github.com/gorilla/websocket"+ "github.com/sirupsen/logrus"++ "whatsapp-rpc/src/go/whatsapp"+)++// Server handles WebSocket RPC connections+type Server struct {+ whatsapp *whatsapp.Service+ logger *logrus.Logger+ upgrader websocket.Upgrader+}++// New creates a new WebSocket RPC server+func New(whatsappService *whatsapp.Service, logger *logrus.Logger) *Server {+ return &Server{+ whatsapp: whatsappService,+ logger: logger,+ upgrader: websocket.Upgrader{+ CheckOrigin: func(r *http.Request) bool {+ return true+ },+ ReadBufferSize: 1024 * 1024, // 1 MB read buffer+ WriteBufferSize: 100 * 1024 * 1024, // 100 MB write buffer for large media+ },+ }+}++// SetupRoutes configures WebSocket RPC routes only+func (s *Server) SetupRoutes() *gin.Engine {+ gin.SetMode(gin.ReleaseMode)+ router := gin.New()+ router.Use(gin.Recovery())++ // CORS middleware+ router.Use(func(c *gin.Context) {+ c.Header("Access-Control-Allow-Origin", "*")+ c.Header("Access-Control-Allow-Methods", "GET, OPTIONS")+ c.Header("Access-Control-Allow-Headers", "Content-Type")+ if c.Request.Method == "OPTIONS" {+ c.AbortWithStatus(200)+ return+ }+ c.Next()+ })++ // WebSocket RPC endpoint - the only endpoint+ router.GET("/ws/rpc", s.handleWebSocketRPC)++ // Health check+ router.GET("/health", func(c *gin.Context) {+ c.JSON(200, gin.H{"status": "ok", "type": "websocket-rpc"})+ })++ return router+}++// handleWebSocketRPC handles bidirectional JSON-RPC over WebSocket+func (s *Server) handleWebSocketRPC(c *gin.Context) {+ conn, err := s.upgrader.Upgrade(c.Writer, c.Request, nil)+ if err != nil {+ s.logger.Errorf("WebSocket upgrade failed: %v", err)+ return+ }+ defer conn.Close()++ s.logger.Info("RPC client connected")++ var writeMu sync.Mutex+ done := make(chan struct{})+ handler := NewRPCHandler(s.whatsapp, s.logger)++ // Forward events as JSON-RPC notifications+ go handler.ForwardEvents(conn, &writeMu, done)++ // Send initial status+ status := s.whatsapp.GetStatus()+ writeMu.Lock()+ conn.WriteJSON(RPCRequest{+ JSONRPC: "2.0",+ Method: "event.status",+ Params: mustMarshal(status),+ })+ writeMu.Unlock()++ // Read and handle incoming requests+ for {+ var req RPCRequest+ if err := conn.ReadJSON(&req); err != nil {+ s.logger.Debugf("RPC client disconnected: %v", err)+ close(done)+ return+ }++ s.logger.Debugf("RPC request: %s", req.Method)++ // Process request and send response+ resp := handler.HandleRequest(&req)+ if req.ID != nil {+ writeMu.Lock()+ conn.WriteJSON(resp)+ writeMu.Unlock()+ }+ }+}diff --git a/server/whatsapp-rpc/src/go/whatsapp/messages.go b/server/whatsapp-rpc/src/go/whatsapp/messages.gonew file mode 100644index 00000000..2a98059f--- /dev/null+++ b/server/whatsapp-rpc/src/go/whatsapp/messages.go@@ -0,0 +1,390 @@+package whatsapp++import (+ "context"+ "encoding/base64"+ "fmt"+ "strings"+ "time"++ "go.mau.fi/whatsmeow"+ "go.mau.fi/whatsmeow/proto/waE2E"+ "go.mau.fi/whatsmeow/types"+ "google.golang.org/protobuf/proto"+)++// SendMessage - Legacy simple message sending (kept for backward compatibility)+func (s *Service) SendMessage(phone, message string) error {+ req := &MessageRequest{+ Phone: phone,+ Message: message,+ Type: "text",+ }+ return s.SendEnhancedMessage(req)+}++// SendEnhancedMessage - Comprehensive message sending with all WhatsApp features+func (s *Service) SendEnhancedMessage(req *MessageRequest) error {+ if !s.client.IsConnected() {+ return fmt.Errorf("WhatsApp not connected")+ }++ var targetJID types.JID+ var err error++ // Log received data for debugging+ s.logger.Infof("SendEnhancedMessage: Type=%s, Phone='%s', GroupID='%s'", req.Type, req.Phone, req.GroupID)++ // Determine target JID (individual or group)+ if req.GroupID != "" {+ targetJID, err = types.ParseJID(req.GroupID)+ if err != nil {+ return fmt.Errorf("invalid group ID '%s': %w", req.GroupID, err)+ }+ } else if req.Phone != "" {+ // Validate phone number is not empty after trimming+ if len(req.Phone) == 0 {+ return fmt.Errorf("phone number cannot be empty")+ }+ targetJID = types.NewJID(req.Phone, types.DefaultUserServer)+ } else {+ return fmt.Errorf("either phone or group_id is required (received: phone='%s', group_id='%s')", req.Phone, req.GroupID)+ }++ // Determine recipient for rate limiting (use phone or group ID)+ recipient := req.Phone+ if recipient == "" {+ recipient = req.GroupID+ }++ // Check rate limits before proceeding+ if err := s.CheckRateLimit(recipient); err != nil {+ s.logger.Warnf("Rate limit check failed: %v", err)+ return err+ }++ // Send typing indicator if enabled (simulates human behavior)+ s.SendTypingIfEnabled(targetJID.String())++ // Check if message contains links for extra delay+ hasLinks := strings.Contains(req.Message, "http://") || strings.Contains(req.Message, "https://")++ // Apply message delay (with randomization for human-like behavior)+ s.ApplyMessageDelay(hasLinks)++ // Create message based on type+ var message *waE2E.Message+ switch req.Type {+ case "text":+ message = s.createTextMessage(req)+ case "image":+ message, err = s.createImageMessage(req)+ case "document":+ message, err = s.createDocumentMessage(req)+ case "audio":+ message, err = s.createAudioMessage(req)+ case "video":+ message, err = s.createVideoMessage(req)+ case "location":+ message = s.createLocationMessage(req)+ case "sticker":+ message, err = s.createStickerMessage(req)+ case "contact":+ message = s.createContactMessage(req)+ default:+ return fmt.Errorf("unsupported message type: %s", req.Type)+ }++ if err != nil {+ return fmt.Errorf("failed to create %s message: %w", req.Type, err)+ }++ // Add reply context if specified+ if req.Reply != nil {+ msgText := message.GetConversation()+ message.ExtendedTextMessage = &waE2E.ExtendedTextMessage{+ Text: &msgText,+ ContextInfo: &waE2E.ContextInfo{+ StanzaID: proto.String(req.Reply.MessageID),+ Participant: proto.String(req.Reply.Sender),+ QuotedMessage: &waE2E.Message{Conversation: proto.String(req.Reply.Content)},+ },+ }+ message.Conversation = nil+ }++ // Send the message+ resp, err := s.client.SendMessage(context.Background(), targetJID, message)+ if err != nil {+ return fmt.Errorf("failed to send message: %w", err)+ }++ // Record message sent for rate limiting stats+ s.RecordMessageSent(recipient)++ // Log successful send+ s.logger.Infof("Message sent successfully: %s to %s", resp.ID, targetJID.String())++ // Send event notification+ s.safeEventSend(Event{+ Type: "message_sent",+ Data: map[string]interface{}{+ "message_id": resp.ID,+ "to": targetJID.String(),+ "type": req.Type,+ "timestamp": resp.Timestamp,+ },+ Time: time.Now(),+ })++ return nil+}++// SendTyping sends typing indicator+// TODO: Fix context API breaking changes+/*+func (s *Service) SendTyping(jidStr string, typing bool) error {+ if !s.client.IsConnected() {+ return fmt.Errorf("WhatsApp not connected")+ }++ var presence types.Presence+ if typing {+ presence = types.PresenceAvailable+ } else {+ presence = types.PresenceUnavailable+ }++ sendErr := s.client.SendPresence(context.Background(), presence)+ if sendErr != nil {+ return fmt.Errorf("failed to send typing indicator: %w", sendErr)+ }++ return nil+}++// MarkMessageAsRead marks a message as read+func (s *Service) MarkMessageAsRead(messageID, senderJID string) error {+ if !s.client.IsConnected() {+ return fmt.Errorf("WhatsApp not connected")+ }++ jid, err := types.ParseJID(senderJID)+ if err != nil {+ return fmt.Errorf("invalid sender JID: %w", err)+ }++ err = s.client.MarkRead(context.Background(), []string{messageID}, time.Now(), jid, jid)+ if err != nil {+ return fmt.Errorf("failed to mark message as read: %w", err)+ }++ return nil+}+*/++// Helper functions to create different message types++func (s *Service) createTextMessage(req *MessageRequest) *waE2E.Message {+ return &waE2E.Message{+ Conversation: proto.String(req.Message),+ }+}++func (s *Service) createImageMessage(req *MessageRequest) (*waE2E.Message, error) {+ if req.MediaData == nil {+ return nil, fmt.Errorf("media_data is required for image messages")+ }++ // Decode base64 media data+ mediaBytes, err := base64.StdEncoding.DecodeString(req.MediaData.Data)+ if err != nil {+ return nil, fmt.Errorf("invalid base64 media data: %w", err)+ }++ // Upload media to WhatsApp servers+ uploaded, err := s.client.Upload(context.Background(), mediaBytes, whatsmeow.MediaImage)+ if err != nil {+ return nil, fmt.Errorf("failed to upload image: %w", err)+ }++ // Create image message+ message := &waE2E.Message{+ ImageMessage: &waE2E.ImageMessage{+ Caption: proto.String(req.MediaData.Caption),+ Mimetype: proto.String(req.MediaData.MimeType),+ URL: proto.String(uploaded.URL),+ DirectPath: proto.String(uploaded.DirectPath),+ MediaKey: uploaded.MediaKey,+ FileEncSHA256: uploaded.FileEncSHA256,+ FileSHA256: uploaded.FileSHA256,+ FileLength: proto.Uint64(uint64(len(mediaBytes))),+ },+ }++ return message, nil+}++func (s *Service) createDocumentMessage(req *MessageRequest) (*waE2E.Message, error) {+ if req.MediaData == nil {+ return nil, fmt.Errorf("media_data is required for document messages")+ }++ // Decode base64 media data+ mediaBytes, err := base64.StdEncoding.DecodeString(req.MediaData.Data)+ if err != nil {+ return nil, fmt.Errorf("invalid base64 media data: %w", err)+ }++ // Upload media to WhatsApp servers+ uploaded, err := s.client.Upload(context.Background(), mediaBytes, whatsmeow.MediaDocument)+ if err != nil {+ return nil, fmt.Errorf("failed to upload document: %w", err)+ }++ // Create document message+ message := &waE2E.Message{+ DocumentMessage: &waE2E.DocumentMessage{+ Title: proto.String(req.MediaData.Filename),+ FileName: proto.String(req.MediaData.Filename),+ Mimetype: proto.String(req.MediaData.MimeType),+ URL: proto.String(uploaded.URL),+ DirectPath: proto.String(uploaded.DirectPath),+ MediaKey: uploaded.MediaKey,+ FileEncSHA256: uploaded.FileEncSHA256,+ FileSHA256: uploaded.FileSHA256,+ FileLength: proto.Uint64(uint64(len(mediaBytes))),+ },+ }++ return message, nil+}++func (s *Service) createAudioMessage(req *MessageRequest) (*waE2E.Message, error) {+ if req.MediaData == nil {+ return nil, fmt.Errorf("media_data is required for audio messages")+ }++ // Decode base64 media data+ mediaBytes, err := base64.StdEncoding.DecodeString(req.MediaData.Data)+ if err != nil {+ return nil, fmt.Errorf("invalid base64 media data: %w", err)+ }++ // Upload media to WhatsApp servers+ uploaded, err := s.client.Upload(context.Background(), mediaBytes, whatsmeow.MediaAudio)+ if err != nil {+ return nil, fmt.Errorf("failed to upload audio: %w", err)+ }++ // Create audio message+ message := &waE2E.Message{+ AudioMessage: &waE2E.AudioMessage{+ Mimetype: proto.String(req.MediaData.MimeType),+ URL: proto.String(uploaded.URL),+ DirectPath: proto.String(uploaded.DirectPath),+ MediaKey: uploaded.MediaKey,+ FileEncSHA256: uploaded.FileEncSHA256,+ FileSHA256: uploaded.FileSHA256,+ FileLength: proto.Uint64(uint64(len(mediaBytes))),+ PTT: proto.Bool(strings.Contains(req.MediaData.MimeType, "ogg")), // Voice note for OGG+ },+ }++ return message, nil+}++func (s *Service) createVideoMessage(req *MessageRequest) (*waE2E.Message, error) {+ if req.MediaData == nil {+ return nil, fmt.Errorf("media_data is required for video messages")+ }++ // Decode base64 media data+ mediaBytes, err := base64.StdEncoding.DecodeString(req.MediaData.Data)+ if err != nil {+ return nil, fmt.Errorf("invalid base64 media data: %w", err)+ }++ // Upload media to WhatsApp servers+ uploaded, err := s.client.Upload(context.Background(), mediaBytes, whatsmeow.MediaVideo)+ if err != nil {+ return nil, fmt.Errorf("failed to upload video: %w", err)+ }++ // Create video message+ message := &waE2E.Message{+ VideoMessage: &waE2E.VideoMessage{+ Caption: proto.String(req.MediaData.Caption),+ Mimetype: proto.String(req.MediaData.MimeType),+ URL: proto.String(uploaded.URL),+ DirectPath: proto.String(uploaded.DirectPath),+ MediaKey: uploaded.MediaKey,+ FileEncSHA256: uploaded.FileEncSHA256,+ FileSHA256: uploaded.FileSHA256,+ FileLength: proto.Uint64(uint64(len(mediaBytes))),+ },+ }++ return message, nil+}++func (s *Service) createLocationMessage(req *MessageRequest) *waE2E.Message {+ if req.Location == nil {+ return &waE2E.Message{Conversation: proto.String("Invalid location data")}+ }++ return &waE2E.Message{+ LocationMessage: &waE2E.LocationMessage{+ DegreesLatitude: proto.Float64(req.Location.Latitude),+ DegreesLongitude: proto.Float64(req.Location.Longitude),+ Name: proto.String(req.Location.Name),+ Address: proto.String(req.Location.Address),+ },+ }+}++func (s *Service) createStickerMessage(req *MessageRequest) (*waE2E.Message, error) {+ if req.MediaData == nil {+ return nil, fmt.Errorf("media_data is required for sticker messages")+ }++ // Decode base64 media data+ mediaBytes, err := base64.StdEncoding.DecodeString(req.MediaData.Data)+ if err != nil {+ return nil, fmt.Errorf("invalid base64 media data: %w", err)+ }++ // Upload media to WhatsApp servers+ uploaded, err := s.client.Upload(context.Background(), mediaBytes, whatsmeow.MediaImage)+ if err != nil {+ return nil, fmt.Errorf("failed to upload sticker: %w", err)+ }++ // Create sticker message+ message := &waE2E.Message{+ StickerMessage: &waE2E.StickerMessage{+ Mimetype: proto.String(req.MediaData.MimeType),+ URL: proto.String(uploaded.URL),+ DirectPath: proto.String(uploaded.DirectPath),+ MediaKey: uploaded.MediaKey,+ FileEncSHA256: uploaded.FileEncSHA256,+ FileSHA256: uploaded.FileSHA256,+ FileLength: proto.Uint64(uint64(len(mediaBytes))),+ },+ }++ return message, nil+}++func (s *Service) createContactMessage(req *MessageRequest) *waE2E.Message {+ if req.Contact == nil {+ return &waE2E.Message{Conversation: proto.String("Invalid contact data")}+ }++ return &waE2E.Message{+ ContactMessage: &waE2E.ContactMessage{+ DisplayName: proto.String(req.Contact.DisplayName),+ Vcard: proto.String(req.Contact.VCard),+ },+ }+}\ No newline at end of filediff --git a/server/whatsapp-rpc/src/go/whatsapp/service.go b/server/whatsapp-rpc/src/go/whatsapp/service.gonew file mode 100644index 00000000..ebf3e77f--- /dev/null+++ b/server/whatsapp-rpc/src/go/whatsapp/service.go@@ -0,0 +1,1834 @@+package whatsapp++import (+ "context"+ "encoding/json"+ "fmt"+ "math/rand"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "time"++ "github.com/sirupsen/logrus"+ "github.com/skip2/go-qrcode"+ "go.mau.fi/whatsmeow"+ "go.mau.fi/whatsmeow/proto/waE2E"+ "go.mau.fi/whatsmeow/store"+ "go.mau.fi/whatsmeow/store/sqlstore"+ "go.mau.fi/whatsmeow/types"+ "go.mau.fi/whatsmeow/types/events"+ waLog "go.mau.fi/whatsmeow/util/log"+ _ "modernc.org/sqlite"++ "whatsapp-rpc/src/go/config"+)++type Service struct {+ mu sync.Mutex+ client *whatsmeow.Client+ container *sqlstore.Container // Database container for proper cleanup+ dbPath string // Database file path+ logger *logrus.Logger+ events chan Event+ running bool+ pairing bool+ shutdown bool+ lastQRCode *QRCodeData+ lastQRCodeTime time.Time+ messages map[string]*events.Message // Store messages by ID for media download+ messageOrder []string // Track message insertion order for FIFO cleanup++ // Rate limiting for anti-ban protection+ rateMu sync.Mutex+ rateLimitConfig *RateLimitConfig+ rateLimitStats *RateLimitStats+ messageTimes []time.Time // Sliding window of message times+ contactsSeen map[string]bool // Track known contacts+ newContactsToday map[string]time.Time // New contacts with timestamp+ dailyResetTime time.Time // When daily counters were last reset+}++++func NewService(dbConfig config.DatabaseConfig, logger *logrus.Logger) (*Service, error) {+ // Set device name (shows in WhatsApp linked devices)+ store.SetOSInfo("MachinaOs", [3]uint32{1, 0, 0})++ // Ensure database directory exists+ dbDir := filepath.Dir(dbConfig.Path)+ if dbDir != "" && dbDir != "." {+ if err := os.MkdirAll(dbDir, 0755); err != nil {+ return nil, fmt.Errorf("failed to create database directory: %w", err)+ }+ }++ // Setup database with WAL mode for concurrent access and extended busy timeout+ dbLog := waLog.Stdout("Database", "INFO", true)+ ctx := context.Background()+ // Increased busy timeout to 30 seconds and added cache=shared for better concurrency on Windows+ container, err := sqlstore.New(ctx, "sqlite", "file:"+dbConfig.Path+"?_pragma=foreign_keys(1)&_journal_mode=WAL&_busy_timeout=30000&cache=shared", dbLog)+ if err != nil {+ return nil, fmt.Errorf("failed to initialize database: %w", err)+ }++ // Get device store+ deviceStore, err := container.GetFirstDevice(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to get device: %w", err)+ }++ // Create client - NO extra configuration like working example+ clientLog := waLog.Stdout("WhatsApp", "INFO", true)+ client := whatsmeow.NewClient(deviceStore, clientLog)++ service := &Service{+ client: client,+ container: container,+ dbPath: dbConfig.Path,+ logger: logger,+ events: make(chan Event, 100),+ running: false,+ pairing: false,+ shutdown: false,+ messages: make(map[string]*events.Message),+ messageOrder: make([]string, 0, 100),+ rateLimitConfig: DefaultRateLimitConfig(),+ rateLimitStats: &RateLimitStats{},+ messageTimes: make([]time.Time, 0, 100),+ contactsSeen: make(map[string]bool),+ newContactsToday: make(map[string]time.Time),+ dailyResetTime: time.Now(),+ }++ // Reset any previous connection state on service creation+ if client.IsConnected() {+ client.Disconnect()+ }++ // Add event handler+ client.AddEventHandler(service.eventHandler)++ return service, nil+}++func (s *Service) safeEventSend(event Event) {+ if s.shutdown {+ return+ }++ defer func() {+ if r := recover(); r != nil {+ s.logger.Errorf("Event send panic recovered: %v", r)+ }+ }()++ select {+ case s.events <- event:+ // Event sent successfully+ default:+ if s.shutdown {+ s.logger.Info("Service is shutdown, skipping event")+ } else {+ s.logger.Warn("Events channel blocked, skipping event")+ }+ }+}++func (s *Service) Start() error {+ s.mu.Lock()+ defer s.mu.Unlock()++ if s.running {+ s.logger.Warn("Service already running")+ return nil+ }++ // Events channel is kept open across restarts (not closed in Shutdown)+ // This allows existing WebSocket ForwardEvents goroutines to continue working++ s.shutdown = false+ s.running = true++ s.logger.Info("Starting WhatsApp service...")++ // Simple flow like working example+ if s.client.Store.ID == nil {+ s.logger.Info("No existing session found, starting pairing")+ // Run pairing synchronously like working example+ go func() {+ if err := s.startPairing(); err != nil {+ s.logger.Errorf("Pairing failed: %v", err)+ }+ }()+ return nil+ }++ // Connect with existing session+ s.logger.Info("Existing session found, connecting...")+ err := s.client.Connect()+ if err != nil {+ s.logger.Errorf("Failed to connect: %v", err)+ return err+ }++ s.logger.Info("Connected successfully")+ return nil+}++func (s *Service) startPairing() error {+ s.logger.Info("Starting pairing process")+ s.pairing = true++ // Get QR channel - use simple context like working example+ qrChan, err := s.client.GetQRChannel(context.Background())+ if err != nil {+ s.logger.Errorf("Failed to get QR channel: %v", err)+ s.pairing = false+ return err+ }++ // Connect to WhatsApp+ err = s.client.Connect()+ if err != nil {+ s.logger.Errorf("Failed to connect: %v", err)+ s.pairing = false+ return err+ }++ // Process QR events - simple loop like working example+ for evt := range qrChan {+ if evt.Event == "code" {+ s.logger.Info("QR code received, generating PNG")+ qrData := s.handleQRCode(evt.Code)++ s.safeEventSend(Event{+ Type: "qr_code",+ Data: map[string]interface{}{+ "code": qrData.Code,+ "filename": qrData.Filename,+ },+ Time: time.Now(),+ })+ } else if evt.Event == "success" {+ s.logger.Info("Pairing successful")+ s.pairing = false+ s.safeEventSend(Event{+ Type: "connected",+ Data: map[string]interface{}{"status": "connected"},+ Time: time.Now(),+ })+ return nil+ } else {+ s.logger.Infof("QR event: %s", evt.Event)+ }+ }++ s.pairing = false+ return fmt.Errorf("QR channel closed")+}++func (s *Service) handleQRCode(code string) QRCodeData {+ // Delete old QR code files before creating new one+ s.cleanupOldQRCodes()++ // Ensure data/qr directory exists+ qrDir := "data/qr"+ os.MkdirAll(qrDir, 0755)++ filename := filepath.Join(qrDir, fmt.Sprintf("qr_%d.png", time.Now().Unix()))++ s.logger.Infof("Generating QR code PNG file: %s", filename)+ s.logger.Debugf("QR code content (first 50 chars): %s...", code[:min(50, len(code))])++ // Save QR code as PNG+ err := qrcode.WriteFile(code, qrcode.Medium, 256, filename)+ if err != nil {+ s.logger.Errorf("Failed to save QR code to file %s: %v", filename, err)+ } else {+ s.logger.Infof("QR code successfully saved to %s", filename)+ }++ qrData := QRCodeData{+ Code: code,+ Filename: filename,+ Time: time.Now(),+ }++ // Store QR code for API retrieval+ s.mu.Lock()+ s.lastQRCode = &qrData+ s.lastQRCodeTime = time.Now()+ s.mu.Unlock()++ s.logger.Info("QR code ready for scanning. Instructions:")+ s.logger.Info("1. Open WhatsApp on your phone")+ s.logger.Info("2. Go to Settings > Linked Devices")+ s.logger.Info("3. Tap 'Link a Device'")+ s.logger.Info("4. Scan the QR code from the generated PNG file or terminal")+ s.logger.Infof("5. QR code file location: %s", filename)++ return qrData+}+++func (s *Service) eventHandler(evt interface{}) {+ if s.shutdown {+ return+ }++ switch v := evt.(type) {+ case *events.Connected:+ s.logger.Infof("Successfully connected to WhatsApp! Device ID: %s", s.client.Store.ID.String())+ s.pairing = false++ // Generate groups JSON file asynchronously+ go func() {+ time.Sleep(2 * time.Second) // Wait for connection to stabilize+ if err := s.generateGroupsJSON(); err != nil {+ s.logger.Errorf("Failed to generate groups.json: %v", err)+ }+ }()++ s.safeEventSend(Event{+ Type: "connected",+ Data: map[string]interface{}{+ "status": "connected",+ "device_id": s.client.Store.ID.String(),+ },+ Time: time.Now(),+ })+ case *events.Disconnected:+ s.logger.Warnf("Disconnected from WhatsApp. Reason: %+v", v)+ s.safeEventSend(Event{+ Type: "disconnected",+ Data: map[string]interface{}{+ "status": "disconnected",+ "reason": fmt.Sprintf("%+v", v),+ },+ Time: time.Now(),+ })+ case *events.ConnectFailure:+ s.logger.Errorf("Connection failure: %+v", v)+ s.safeEventSend(Event{+ Type: "connection_failure",+ Data: map[string]interface{}{+ "error": fmt.Sprintf("%+v", v),+ "reason": v.Reason.String(),+ },+ Time: time.Now(),+ })+ case *events.LoggedOut:+ s.logger.Warnf("=== LOGOUT EVENT RECEIVED ===")+ s.logger.Warnf("OnConnect: %v", v.OnConnect)+ s.logger.Warnf("Reason: %s", v.Reason.String())+ s.logger.Warnf("Full logout event: %+v", v)+ s.logger.Warnf("Device Store ID: %v", s.client.Store.ID)+ s.logger.Warnf("Is Connected: %v", s.client.IsConnected())+ s.logger.Warnf("=== END LOGOUT EVENT ===")+ s.safeEventSend(Event{+ Type: "logged_out",+ Data: map[string]interface{}{+ "on_connect": v.OnConnect,+ "reason": v.Reason.String(),+ "full_event": fmt.Sprintf("%+v", v),+ },+ Time: time.Now(),+ })+ case *events.TemporaryBan:+ s.logger.Errorf("Temporary ban received: %+v", v)+ s.safeEventSend(Event{+ Type: "temporary_ban",+ Data: map[string]interface{}{+ "code": v.Code.String(),+ "reason": fmt.Sprintf("%+v", v),+ },+ Time: time.Now(),+ })+ case *events.Message:+ s.handleIncomingMessage(v)+ default:+ s.logger.Debugf("Unhandled event type: %T, data: %+v", evt, evt)+ }+}++// handleIncomingMessage processes incoming messages and extracts all message types+func (s *Service) handleIncomingMessage(v *events.Message) {+ // Extract basic info+ sender := v.Info.Sender.String()+ chatID := v.Info.Chat.String()+ timestamp := v.Info.Timestamp+ messageID := v.Info.ID+ isGroup := v.Info.IsGroup++ // Resolve LID to phone number (LIDs can appear in both group and individual chats)+ senderPhone := v.Info.Sender.User // Default to JID user part+ if v.Info.Sender.Server == "lid" && s.client.Store.LIDs != nil {+ ctx := context.Background()+ pn, err := s.client.Store.LIDs.GetPNForLID(ctx, v.Info.Sender)+ if err == nil && pn.User != "" {+ senderPhone = pn.User+ s.logger.Debugf("Resolved LID %s to phone %s", sender, senderPhone)+ } else if err != nil {+ s.logger.Debugf("Could not resolve LID %s: %v", sender, err)+ }+ }++ if isGroup {+ s.logger.Infof("Processing group message from %s (phone: %s) in %s (ID: %s)", sender, senderPhone, chatID, messageID)+ } else {+ s.logger.Infof("Processing individual message from %s (phone: %s) (ID: %s)", sender, senderPhone, messageID)+ }++ // Store message for later media download (keep last 100 messages to avoid memory issues)+ s.mu.Lock()+ // Check if message already exists (avoid duplicates)+ if _, exists := s.messages[messageID]; !exists {+ // Remove oldest messages if at capacity (FIFO cleanup)+ maxMessages := 100+ for len(s.messageOrder) >= maxMessages {+ oldestID := s.messageOrder[0]+ s.messageOrder = s.messageOrder[1:]+ delete(s.messages, oldestID)+ s.logger.Debugf("Removed oldest message %s from cache (capacity: %d)", oldestID, maxMessages)+ }+ // Add new message+ s.messages[messageID] = v+ s.messageOrder = append(s.messageOrder, messageID)+ s.logger.Debugf("Cached message %s for media download (total: %d)", messageID, len(s.messages))+ }+ s.mu.Unlock()++ // Prepare event data with common fields+ eventData := map[string]interface{}{+ "message_id": messageID,+ "sender": sender,+ "sender_phone": senderPhone,+ "chat_id": chatID,+ "timestamp": timestamp,+ "is_from_me": v.Info.IsFromMe,+ "is_group": isGroup,+ }++ // Add group info for group messages+ if isGroup {+ groupInfo := map[string]interface{}{+ "group_jid": chatID,+ "sender_jid": sender,+ "sender_phone": senderPhone,+ }+ // Try to get group name from push name or leave empty+ if v.Info.PushName != "" {+ groupInfo["sender_name"] = v.Info.PushName+ }+ eventData["group_info"] = groupInfo+ }++ // Determine message type and extract content+ msg := v.Message+ messageType := "unknown"+ var messageContent interface{}++ // Helper function to extract forwarded info from ContextInfo+ extractForwardedInfo := func(ctx *waE2E.ContextInfo) {+ if ctx == nil {+ return+ }+ if ctx.GetIsForwarded() {+ eventData["is_forwarded"] = true+ eventData["forwarding_score"] = ctx.GetForwardingScore()+ }+ }++ switch {+ case msg.Conversation != nil && *msg.Conversation != "":+ // Plain text message (no ContextInfo, cannot be forwarded)+ messageType = "text"+ messageContent = *msg.Conversation+ eventData["text"] = *msg.Conversation++ case msg.ExtendedTextMessage != nil:+ // Extended text message (with link preview, quoted message, etc.)+ messageType = "text"+ if msg.ExtendedTextMessage.Text != nil {+ messageContent = *msg.ExtendedTextMessage.Text+ eventData["text"] = *msg.ExtendedTextMessage.Text+ }+ // Check forwarded status+ extractForwardedInfo(msg.ExtendedTextMessage.ContextInfo)+ // Check if it's a reply/quoted message+ if msg.ExtendedTextMessage.ContextInfo != nil && msg.ExtendedTextMessage.ContextInfo.QuotedMessage != nil {+ eventData["is_reply"] = true+ if msg.ExtendedTextMessage.ContextInfo.StanzaID != nil {+ eventData["quoted_message_id"] = *msg.ExtendedTextMessage.ContextInfo.StanzaID+ }+ }++ case msg.ImageMessage != nil:+ // Image message+ messageType = "image"+ imageData := map[string]interface{}{+ "mime_type": msg.ImageMessage.GetMimetype(),+ "file_sha256": fmt.Sprintf("%x", msg.ImageMessage.GetFileSHA256()),+ "file_length": msg.ImageMessage.GetFileLength(),+ }+ if msg.ImageMessage.Caption != nil {+ imageData["caption"] = *msg.ImageMessage.Caption+ }+ if msg.ImageMessage.URL != nil {+ imageData["url"] = *msg.ImageMessage.URL+ }+ messageContent = imageData+ eventData["image"] = imageData+ // Check forwarded status+ extractForwardedInfo(msg.ImageMessage.ContextInfo)++ case msg.VideoMessage != nil:+ // Video message+ messageType = "video"+ videoData := map[string]interface{}{+ "mime_type": msg.VideoMessage.GetMimetype(),+ "file_sha256": fmt.Sprintf("%x", msg.VideoMessage.GetFileSHA256()),+ "file_length": msg.VideoMessage.GetFileLength(),+ "seconds": msg.VideoMessage.GetSeconds(),+ }+ if msg.VideoMessage.Caption != nil {+ videoData["caption"] = *msg.VideoMessage.Caption+ }+ if msg.VideoMessage.URL != nil {+ videoData["url"] = *msg.VideoMessage.URL+ }+ messageContent = videoData+ eventData["video"] = videoData+ // Check forwarded status+ extractForwardedInfo(msg.VideoMessage.ContextInfo)++ case msg.AudioMessage != nil:+ // Audio/Voice message+ messageType = "audio"+ audioData := map[string]interface{}{+ "mime_type": msg.AudioMessage.GetMimetype(),+ "file_sha256": fmt.Sprintf("%x", msg.AudioMessage.GetFileSHA256()),+ "file_length": msg.AudioMessage.GetFileLength(),+ "seconds": msg.AudioMessage.GetSeconds(),+ "ptt": msg.AudioMessage.GetPTT(), // Push-to-talk (voice message)+ }+ if msg.AudioMessage.URL != nil {+ audioData["url"] = *msg.AudioMessage.URL+ }+ messageContent = audioData+ eventData["audio"] = audioData+ // Check forwarded status+ extractForwardedInfo(msg.AudioMessage.ContextInfo)++ case msg.DocumentMessage != nil:+ // Document message+ messageType = "document"+ docData := map[string]interface{}{+ "mime_type": msg.DocumentMessage.GetMimetype(),+ "file_sha256": fmt.Sprintf("%x", msg.DocumentMessage.GetFileSHA256()),+ "file_length": msg.DocumentMessage.GetFileLength(),+ }+ if msg.DocumentMessage.FileName != nil {+ docData["file_name"] = *msg.DocumentMessage.FileName+ }+ if msg.DocumentMessage.Title != nil {+ docData["title"] = *msg.DocumentMessage.Title+ }+ if msg.DocumentMessage.Caption != nil {+ docData["caption"] = *msg.DocumentMessage.Caption+ }+ if msg.DocumentMessage.URL != nil {+ docData["url"] = *msg.DocumentMessage.URL+ }+ messageContent = docData+ eventData["document"] = docData+ // Check forwarded status+ extractForwardedInfo(msg.DocumentMessage.ContextInfo)++ case msg.StickerMessage != nil:+ // Sticker message+ messageType = "sticker"+ stickerData := map[string]interface{}{+ "mime_type": msg.StickerMessage.GetMimetype(),+ "file_sha256": fmt.Sprintf("%x", msg.StickerMessage.GetFileSHA256()),+ "file_length": msg.StickerMessage.GetFileLength(),+ "is_animated": msg.StickerMessage.GetIsAnimated(),+ }+ if msg.StickerMessage.URL != nil {+ stickerData["url"] = *msg.StickerMessage.URL+ }+ messageContent = stickerData+ eventData["sticker"] = stickerData+ // Check forwarded status+ extractForwardedInfo(msg.StickerMessage.ContextInfo)++ case msg.LocationMessage != nil:+ // Location message+ messageType = "location"+ locationData := map[string]interface{}{+ "latitude": msg.LocationMessage.GetDegreesLatitude(),+ "longitude": msg.LocationMessage.GetDegreesLongitude(),+ }+ if msg.LocationMessage.Name != nil {+ locationData["name"] = *msg.LocationMessage.Name+ }+ if msg.LocationMessage.Address != nil {+ locationData["address"] = *msg.LocationMessage.Address+ }+ messageContent = locationData+ eventData["location"] = locationData++ case msg.ContactMessage != nil:+ // Contact card message+ messageType = "contact"+ contactData := map[string]interface{}{+ "display_name": msg.ContactMessage.GetDisplayName(),+ "vcard": msg.ContactMessage.GetVcard(),+ }+ messageContent = contactData+ eventData["contact"] = contactData++ case msg.ContactsArrayMessage != nil:+ // Multiple contacts+ messageType = "contacts"+ contacts := []map[string]interface{}{}+ for _, contact := range msg.ContactsArrayMessage.Contacts {+ contacts = append(contacts, map[string]interface{}{+ "display_name": contact.GetDisplayName(),+ "vcard": contact.GetVcard(),+ })+ }+ messageContent = contacts+ eventData["contacts"] = contacts++ case msg.ReactionMessage != nil:+ // Reaction to a message - skip broadcasting these+ s.logger.Debugf("Skipping reaction message from %s to message %s", sender, msg.ReactionMessage.GetKey().GetID())+ return++ case msg.ProtocolMessage != nil:+ // Protocol messages (edits, deletes, ephemeral settings) - skip these+ s.logger.Debugf("Skipping protocol message from %s (type: %v)", sender, msg.ProtocolMessage.GetType())+ return++ default:+ // Unknown message type - silently skip (don't log or broadcast)+ return+ }++ eventData["message_type"] = messageType+ eventData["content"] = messageContent++ // Log the message+ s.logger.Infof("Received %s message from %s", messageType, sender)++ // Broadcast event+ s.safeEventSend(Event{+ Type: "message_received",+ Data: eventData,+ Time: time.Now(),+ })+}++func (s *Service) GetStatus() map[string]interface{} {+ status := map[string]interface{}{+ "connected": s.client.IsConnected(),+ "has_session": s.client.Store.ID != nil,+ "running": s.running,+ "pairing": s.pairing,+ "timestamp": time.Now(),+ }++ // Add device information if available+ if s.client.Store.ID != nil {+ status["device_id"] = s.client.Store.ID.String()+ }++ return status+}++func (s *Service) GetDiagnostics() map[string]interface{} {+ diagnostics := map[string]interface{}{+ "client_connected": s.client.IsConnected(),+ "client_logged_in": s.client.IsLoggedIn(),+ "store_has_id": s.client.Store.ID != nil,+ "service_running": s.running,+ "service_pairing": s.pairing,+ "service_shutdown": s.shutdown,+ "events_channel_open": !s.shutdown,+ "timestamp": time.Now(),+ }++ // Add store information if available+ if s.client.Store.ID != nil {+ diagnostics["device_store"] = map[string]interface{}{+ "device_id": s.client.Store.ID.String(),+ "user": s.client.Store.ID.User,+ "device": s.client.Store.ID.Device,+ "server": s.client.Store.ID.Server,+ }+ }++ return diagnostics+}++func (s *Service) GetEventChannel() <-chan Event {+ return s.events+}++func (s *Service) IsConnected() bool {+ return s.client.IsConnected()+}++// DownloadMedia downloads media from a message by ID+func (s *Service) DownloadMedia(messageID string) ([]byte, string, error) {+ s.mu.Lock()+ msg, exists := s.messages[messageID]+ cachedCount := len(s.messages)+ s.mu.Unlock()++ if !exists {+ s.logger.Warnf("Media download failed: message %s not found in cache (cached: %d messages)", messageID, cachedCount)+ return nil, "", fmt.Errorf("message not found or expired (message_id: %s, cached: %d)", messageID, cachedCount)+ }++ // Download media based on message type+ var data []byte+ var err error+ var mimeType string+ var mediaType string++ ctx := context.Background()++ switch {+ case msg.Message.ImageMessage != nil:+ mediaType = "image"+ s.logger.Infof("Downloading image from message %s", messageID)+ data, err = s.client.Download(ctx, msg.Message.ImageMessage)+ mimeType = msg.Message.ImageMessage.GetMimetype()+ case msg.Message.VideoMessage != nil:+ mediaType = "video"+ s.logger.Infof("Downloading video from message %s", messageID)+ data, err = s.client.Download(ctx, msg.Message.VideoMessage)+ mimeType = msg.Message.VideoMessage.GetMimetype()+ case msg.Message.AudioMessage != nil:+ mediaType = "audio"+ s.logger.Infof("Downloading audio from message %s", messageID)+ data, err = s.client.Download(ctx, msg.Message.AudioMessage)+ mimeType = msg.Message.AudioMessage.GetMimetype()+ case msg.Message.DocumentMessage != nil:+ mediaType = "document"+ s.logger.Infof("Downloading document from message %s", messageID)+ data, err = s.client.Download(ctx, msg.Message.DocumentMessage)+ mimeType = msg.Message.DocumentMessage.GetMimetype()+ case msg.Message.StickerMessage != nil:+ mediaType = "sticker"+ s.logger.Infof("Downloading sticker from message %s", messageID)+ data, err = s.client.Download(ctx, msg.Message.StickerMessage)+ mimeType = msg.Message.StickerMessage.GetMimetype()+ default:+ s.logger.Warnf("Media download failed: message %s does not contain downloadable media", messageID)+ return nil, "", fmt.Errorf("message does not contain downloadable media")+ }++ if err != nil {+ s.logger.Errorf("Failed to download %s from message %s: %v", mediaType, messageID, err)+ return nil, "", fmt.Errorf("failed to download %s: %w", mediaType, err)+ }++ s.logger.Infof("Successfully downloaded %s from message %s (%d bytes, %s)", mediaType, messageID, len(data), mimeType)+ return data, mimeType, nil+}++// resolveParticipantPhone gets the real phone number for a participant+// Uses LID store to resolve if PhoneNumber is empty and JID is a LID+func (s *Service) resolveParticipantPhone(ctx context.Context, p types.GroupParticipant) string {+ // First try PhoneNumber field+ if p.PhoneNumber.User != "" {+ return p.PhoneNumber.User+ }++ // Check if JID is a LID (ends with @lid server)+ if p.JID.Server == "lid" && s.client.Store.LIDs != nil {+ // Try to resolve LID to phone number+ pn, err := s.client.Store.LIDs.GetPNForLID(ctx, p.JID)+ if err == nil && pn.User != "" {+ return pn.User+ }+ }++ // Fall back to JID.User+ return p.JID.User+}++// generateGroupsJSON fetches all groups and saves to data/groups.json+// Called automatically on WhatsApp connection for fast offline access+func (s *Service) generateGroupsJSON() error {+ if !s.client.IsConnected() {+ return fmt.Errorf("not connected")+ }++ ctx := context.Background()+ groups, err := s.client.GetJoinedGroups(ctx)+ if err != nil {+ return fmt.Errorf("failed to get groups: %w", err)+ }++ // Build indexed structure for fast lookups+ groupsMap := make(map[string]interface{})+ phoneToGroups := make(map[string][]string)++ for _, g := range groups {+ participantsMap := make(map[string]interface{})++ for _, p := range g.Participants {+ phone := s.resolveParticipantPhone(ctx, p)+ participantsMap[phone] = map[string]interface{}{+ "jid": p.JID.String(),+ "phone": phone,+ "is_admin": p.IsAdmin,+ "is_super_admin": p.IsSuperAdmin,+ }+ // Build reverse index: phone -> groups+ phoneToGroups[phone] = append(phoneToGroups[phone], g.JID.String())+ }++ groupsMap[g.JID.String()] = map[string]interface{}{+ "jid": g.JID.String(),+ "name": g.Name,+ "topic": g.Topic,+ "owner": g.OwnerJID.String(),+ "size": len(g.Participants),+ "is_announce": g.IsAnnounce,+ "is_locked": g.IsLocked,+ "created_at": g.GroupCreated,+ "participants": participantsMap,+ }+ }++ data := map[string]interface{}{+ "generated_at": time.Now().UTC(),+ "device_id": s.client.Store.ID.String(),+ "groups": groupsMap,+ "phone_to_groups": phoneToGroups,+ }++ // Ensure data directory exists+ if err := os.MkdirAll("data", 0755); err != nil {+ return fmt.Errorf("failed to create data directory: %w", err)+ }++ // Write JSON file with pretty formatting+ jsonData, err := json.MarshalIndent(data, "", " ")+ if err != nil {+ return fmt.Errorf("failed to marshal JSON: %w", err)+ }++ if err := os.WriteFile("data/groups.json", jsonData, 0644); err != nil {+ return fmt.Errorf("failed to write file: %w", err)+ }++ s.logger.Infof("Generated data/groups.json with %d groups", len(groups))+ return nil+}++// GetGroups returns all groups the user is a member of+func (s *Service) GetGroups() ([]GroupInfo, error) {+ if !s.client.IsConnected() {+ return nil, fmt.Errorf("WhatsApp not connected")+ }++ ctx := context.Background()+ groups, err := s.client.GetJoinedGroups(ctx)+ if err != nil {+ s.logger.Errorf("Failed to get joined groups: %v", err)+ return nil, fmt.Errorf("failed to get groups: %w", err)+ }++ result := make([]GroupInfo, 0, len(groups))+ for _, g := range groups {+ participants := make([]GroupParticipant, 0, len(g.Participants))+ for _, p := range g.Participants {+ phone := s.resolveParticipantPhone(ctx, p)+ participants = append(participants, GroupParticipant{+ JID: p.JID.String(),+ Phone: phone,+ IsAdmin: p.IsAdmin,+ IsSuperAdmin: p.IsSuperAdmin,+ })+ }++ result = append(result, GroupInfo{+ JID: g.JID.String(),+ Name: g.Name,+ Topic: g.Topic,+ Owner: g.OwnerJID.String(),+ Participants: participants,+ CreatedAt: g.GroupCreated,+ Size: len(g.Participants),+ IsAnnounce: g.IsAnnounce,+ IsLocked: g.IsLocked,+ })+ }++ s.logger.Infof("Retrieved %d groups", len(result))+ return result, nil+}++// GetGroupInfo returns detailed information about a specific group+func (s *Service) GetGroupInfo(groupJID string) (*GroupInfo, error) {+ if !s.client.IsConnected() {+ return nil, fmt.Errorf("WhatsApp not connected")+ }++ jid, err := types.ParseJID(groupJID)+ if err != nil {+ return nil, fmt.Errorf("invalid group JID: %w", err)+ }++ ctx := context.Background()+ info, err := s.client.GetGroupInfo(ctx, jid)+ if err != nil {+ s.logger.Errorf("Failed to get group info for %s: %v", groupJID, err)+ return nil, fmt.Errorf("failed to get group info: %w", err)+ }++ participants := make([]GroupParticipant, 0, len(info.Participants))+ for _, p := range info.Participants {+ phone := s.resolveParticipantPhone(ctx, p)+ participants = append(participants, GroupParticipant{+ JID: p.JID.String(),+ Phone: phone,+ IsAdmin: p.IsAdmin,+ IsSuperAdmin: p.IsSuperAdmin,+ })+ }++ result := &GroupInfo{+ JID: info.JID.String(),+ Name: info.Name,+ Topic: info.Topic,+ Owner: info.OwnerJID.String(),+ Participants: participants,+ CreatedAt: info.GroupCreated,+ Size: len(info.Participants),+ IsAnnounce: info.IsAnnounce,+ IsLocked: info.IsLocked,+ }++ s.logger.Infof("Retrieved info for group %s (%s)", info.Name, groupJID)+ return result, nil+}++// UpdateGroupInfo updates the name and/or topic of a group+func (s *Service) UpdateGroupInfo(groupJID, name, topic string) error {+ if !s.client.IsConnected() {+ return fmt.Errorf("WhatsApp not connected")+ }++ jid, err := types.ParseJID(groupJID)+ if err != nil {+ return fmt.Errorf("invalid group JID: %w", err)+ }++ ctx := context.Background()++ // Update name if provided+ if name != "" {+ err = s.client.SetGroupName(ctx, jid, name)+ if err != nil {+ s.logger.Errorf("Failed to update group name for %s: %v", groupJID, err)+ return fmt.Errorf("failed to update group name: %w", err)+ }+ s.logger.Infof("Updated group name for %s to: %s", groupJID, name)+ }++ // Update topic/description if provided+ if topic != "" {+ // SetGroupTopic requires: ctx, jid, previousTopicID, newTopicID, topic+ // Using empty strings for topic IDs as they're optional for setting new topic+ err = s.client.SetGroupTopic(ctx, jid, "", "", topic)+ if err != nil {+ s.logger.Errorf("Failed to update group topic for %s: %v", groupJID, err)+ return fmt.Errorf("failed to update group topic: %w", err)+ }+ s.logger.Infof("Updated group topic for %s", groupJID)+ }++ return nil+}++// CheckContacts checks if phone numbers are registered on WhatsApp+func (s *Service) CheckContacts(phones []string) ([]ContactCheckResult, error) {+ if !s.client.IsConnected() {+ return nil, fmt.Errorf("WhatsApp not connected")+ }++ ctx := context.Background()+ results, err := s.client.IsOnWhatsApp(ctx, phones)+ if err != nil {+ s.logger.Errorf("Failed to check contacts: %v", err)+ return nil, fmt.Errorf("failed to check contacts: %w", err)+ }++ response := make([]ContactCheckResult, 0, len(results))+ for _, r := range results {+ result := ContactCheckResult{+ Query: r.Query,+ IsRegistered: r.IsIn,+ }+ if r.IsIn && r.JID.User != "" {+ result.JID = r.JID.String()+ }+ if r.VerifiedName != nil {+ result.IsBusiness = true+ result.BusinessName = r.VerifiedName.Details.GetVerifiedName()+ }+ response = append(response, result)+ }++ s.logger.Infof("Checked %d phone numbers, %d registered", len(phones), countRegistered(response))+ return response, nil+}++func countRegistered(results []ContactCheckResult) int {+ count := 0+ for _, r := range results {+ if r.IsRegistered {+ count+++ }+ }+ return count+}++// GetProfilePicture gets profile picture for a JID+func (s *Service) GetProfilePicture(jidStr string, preview bool) (*ProfilePicResult, error) {+ if !s.client.IsConnected() {+ return nil, fmt.Errorf("WhatsApp not connected")+ }++ jid, err := types.ParseJID(jidStr)+ if err != nil {+ return nil, fmt.Errorf("invalid JID: %w", err)+ }++ ctx := context.Background()+ params := &whatsmeow.GetProfilePictureParams{+ Preview: preview,+ }++ info, err := s.client.GetProfilePictureInfo(ctx, jid, params)+ if err != nil {+ // Profile picture may not exist - this is not an error+ errStr := err.Error()+ if strings.Contains(errStr, "item-not-found") || strings.Contains(errStr, "not-authorized") {+ return &ProfilePicResult{Exists: false}, nil+ }+ s.logger.Errorf("Failed to get profile picture for %s: %v", jidStr, err)+ return nil, fmt.Errorf("failed to get profile picture: %w", err)+ }++ result := &ProfilePicResult{+ Exists: true,+ URL: info.URL,+ ID: info.ID,+ }++ s.logger.Infof("Retrieved profile picture for %s", jidStr)+ return result, nil+}++// SendTyping sends typing indicator to a chat+func (s *Service) SendTyping(jidStr, state, media string) error {+ if !s.client.IsConnected() {+ return fmt.Errorf("WhatsApp not connected")+ }++ jid, err := types.ParseJID(jidStr)+ if err != nil {+ return fmt.Errorf("invalid JID: %w", err)+ }++ // Convert state string to ChatPresence+ var chatPresence types.ChatPresence+ switch state {+ case "composing":+ chatPresence = types.ChatPresenceComposing+ case "paused":+ chatPresence = types.ChatPresencePaused+ default:+ return fmt.Errorf("invalid state: %s (must be 'composing' or 'paused')", state)+ }++ // Convert media string to ChatPresenceMedia+ var chatMedia types.ChatPresenceMedia+ switch media {+ case "", "text":+ chatMedia = types.ChatPresenceMediaText+ case "audio":+ chatMedia = types.ChatPresenceMediaAudio+ default:+ return fmt.Errorf("invalid media: %s (must be 'text' or 'audio')", media)+ }++ ctx := context.Background()+ err = s.client.SendChatPresence(ctx, jid, chatPresence, chatMedia)+ if err != nil {+ s.logger.Errorf("Failed to send typing indicator to %s: %v", jidStr, err)+ return fmt.Errorf("failed to send typing indicator: %w", err)+ }++ s.logger.Infof("Sent typing indicator (%s) to %s", state, jidStr)+ return nil+}++// SetPresence sets online/offline presence status+func (s *Service) SetPresence(status string) error {+ if !s.client.IsConnected() {+ return fmt.Errorf("WhatsApp not connected")+ }++ var presence types.Presence+ switch status {+ case "available", "online":+ presence = types.PresenceAvailable+ case "unavailable", "offline":+ presence = types.PresenceUnavailable+ default:+ return fmt.Errorf("invalid status: %s (must be 'available' or 'unavailable')", status)+ }++ ctx := context.Background()+ err := s.client.SendPresence(ctx, presence)+ if err != nil {+ s.logger.Errorf("Failed to set presence to %s: %v", status, err)+ return fmt.Errorf("failed to set presence: %w", err)+ }++ s.logger.Infof("Set presence to %s", status)+ return nil+}++// MarkRead marks messages as read+func (s *Service) MarkRead(messageIDs []string, chatJID, senderJID string) error {+ if !s.client.IsConnected() {+ return fmt.Errorf("WhatsApp not connected")+ }++ if len(messageIDs) == 0 {+ return fmt.Errorf("at least one message_id is required")+ }++ chat, err := types.ParseJID(chatJID)+ if err != nil {+ return fmt.Errorf("invalid chat_jid: %w", err)+ }++ // For DMs, sender is the same as chat+ // For groups, sender is the actual message sender+ sender := chat+ if senderJID != "" {+ sender, err = types.ParseJID(senderJID)+ if err != nil {+ return fmt.Errorf("invalid sender_jid: %w", err)+ }+ }++ ctx := context.Background()+ err = s.client.MarkRead(ctx, messageIDs, time.Now(), chat, sender)+ if err != nil {+ s.logger.Errorf("Failed to mark messages as read: %v", err)+ return fmt.Errorf("failed to mark messages as read: %w", err)+ }++ s.logger.Infof("Marked %d message(s) as read in %s", len(messageIDs), chatJID)+ return nil+}++// normalizeToJID converts a phone number or JID string to types.JID+func (s *Service) normalizeToJID(input string) (types.JID, error) {+ // If it's already a JID (contains @), parse it directly+ if strings.Contains(input, "@") {+ return types.ParseJID(input)+ }++ // Otherwise, treat as phone number and create user JID+ // Remove any non-digit characters+ phone := strings.Map(func(r rune) rune {+ if r >= '0' && r <= '9' {+ return r+ }+ return -1+ }, input)++ if phone == "" {+ return types.JID{}, fmt.Errorf("invalid phone number: %s", input)+ }++ return types.NewJID(phone, types.DefaultUserServer), nil+}++// AddGroupParticipants adds participants to a group+func (s *Service) AddGroupParticipants(groupJID string, participants []string) (*GroupParticipantsResult, error) {+ if !s.client.IsConnected() {+ return nil, fmt.Errorf("WhatsApp not connected")+ }++ jid, err := types.ParseJID(groupJID)+ if err != nil {+ return nil, fmt.Errorf("invalid group JID: %w", err)+ }++ // Convert phone numbers/JIDs to types.JID slice+ participantJIDs := make([]types.JID, 0, len(participants))+ for _, p := range participants {+ pJID, err := s.normalizeToJID(p)+ if err != nil {+ s.logger.Warnf("Invalid participant %s: %v", p, err)+ continue+ }+ participantJIDs = append(participantJIDs, pJID)+ }++ if len(participantJIDs) == 0 {+ return nil, fmt.Errorf("no valid participants provided")+ }++ ctx := context.Background()+ results, err := s.client.UpdateGroupParticipants(ctx, jid, participantJIDs, whatsmeow.ParticipantChangeAdd)+ if err != nil {+ s.logger.Errorf("Failed to add participants to %s: %v", groupJID, err)+ return nil, fmt.Errorf("failed to add participants: %w", err)+ }++ // Build result+ response := &GroupParticipantsResult{+ GroupID: groupJID,+ Action: "add",+ Results: make([]GroupParticipantChangeResult, 0, len(results)),+ }++ for _, r := range results {+ result := GroupParticipantChangeResult{+ JID: r.JID.String(),+ Phone: r.JID.User,+ Success: r.Error == 0, // 0 means success+ }+ if r.Error != 0 {+ result.Error = fmt.Sprintf("error code: %d", r.Error)+ response.Failed+++ } else {+ response.Added+++ }+ response.Results = append(response.Results, result)+ }++ s.logger.Infof("Added %d participants to group %s (failed: %d)", response.Added, groupJID, response.Failed)+ return response, nil+}++// RemoveGroupParticipants removes participants from a group+func (s *Service) RemoveGroupParticipants(groupJID string, participants []string) (*GroupParticipantsResult, error) {+ if !s.client.IsConnected() {+ return nil, fmt.Errorf("WhatsApp not connected")+ }++ jid, err := types.ParseJID(groupJID)+ if err != nil {+ return nil, fmt.Errorf("invalid group JID: %w", err)+ }++ // Convert phone numbers/JIDs to types.JID slice+ participantJIDs := make([]types.JID, 0, len(participants))+ for _, p := range participants {+ pJID, err := s.normalizeToJID(p)+ if err != nil {+ s.logger.Warnf("Invalid participant %s: %v", p, err)+ continue+ }+ participantJIDs = append(participantJIDs, pJID)+ }++ if len(participantJIDs) == 0 {+ return nil, fmt.Errorf("no valid participants provided")+ }++ ctx := context.Background()+ results, err := s.client.UpdateGroupParticipants(ctx, jid, participantJIDs, whatsmeow.ParticipantChangeRemove)+ if err != nil {+ s.logger.Errorf("Failed to remove participants from %s: %v", groupJID, err)+ return nil, fmt.Errorf("failed to remove participants: %w", err)+ }++ // Build result+ response := &GroupParticipantsResult{+ GroupID: groupJID,+ Action: "remove",+ Results: make([]GroupParticipantChangeResult, 0, len(results)),+ }++ for _, r := range results {+ result := GroupParticipantChangeResult{+ JID: r.JID.String(),+ Phone: r.JID.User,+ Success: r.Error == 0,+ }+ if r.Error != 0 {+ result.Error = fmt.Sprintf("error code: %d", r.Error)+ response.Failed+++ } else {+ response.Removed+++ }+ response.Results = append(response.Results, result)+ }++ s.logger.Infof("Removed %d participants from group %s (failed: %d)", response.Removed, groupJID, response.Failed)+ return response, nil+}++// GetGroupInviteLink gets the invite link for a group+func (s *Service) GetGroupInviteLink(groupJID string) (*GroupInviteLinkResult, error) {+ if !s.client.IsConnected() {+ return nil, fmt.Errorf("WhatsApp not connected")+ }++ jid, err := types.ParseJID(groupJID)+ if err != nil {+ return nil, fmt.Errorf("invalid group JID: %w", err)+ }++ ctx := context.Background()+ link, err := s.client.GetGroupInviteLink(ctx, jid, false)+ if err != nil {+ s.logger.Errorf("Failed to get invite link for %s: %v", groupJID, err)+ return nil, fmt.Errorf("failed to get invite link: %w", err)+ }++ s.logger.Infof("Retrieved invite link for group %s", groupJID)+ return &GroupInviteLinkResult{+ GroupID: groupJID,+ InviteLink: link,+ Revoked: false,+ }, nil+}++// RevokeGroupInviteLink revokes the current invite link and generates a new one+func (s *Service) RevokeGroupInviteLink(groupJID string) (*GroupInviteLinkResult, error) {+ if !s.client.IsConnected() {+ return nil, fmt.Errorf("WhatsApp not connected")+ }++ jid, err := types.ParseJID(groupJID)+ if err != nil {+ return nil, fmt.Errorf("invalid group JID: %w", err)+ }++ ctx := context.Background()+ // reset=true revokes the old link and generates new one+ link, err := s.client.GetGroupInviteLink(ctx, jid, true)+ if err != nil {+ s.logger.Errorf("Failed to revoke invite link for %s: %v", groupJID, err)+ return nil, fmt.Errorf("failed to revoke invite link: %w", err)+ }++ s.logger.Infof("Revoked and regenerated invite link for group %s", groupJID)+ return &GroupInviteLinkResult{+ GroupID: groupJID,+ InviteLink: link,+ Revoked: true,+ }, nil+}++// GetCurrentQRCode returns the last generated QR code if recent+func (s *Service) GetCurrentQRCode() *QRCodeData {+ s.mu.Lock()+ defer s.mu.Unlock()++ if s.lastQRCode == nil {+ return nil+ }++ // Return QR if it was generated within last 60 seconds+ if time.Since(s.lastQRCodeTime) > 60*time.Second {+ return nil+ }++ return s.lastQRCode+}++// ============================================================================+// Rate Limiting Methods+// ============================================================================++// GetRateLimitConfig returns the current rate limit configuration+func (s *Service) GetRateLimitConfig() *RateLimitConfig {+ s.rateMu.Lock()+ defer s.rateMu.Unlock()+ return s.rateLimitConfig+}++// SetRateLimitConfig updates the rate limit configuration+func (s *Service) SetRateLimitConfig(config *RateLimitConfig) error {+ s.rateMu.Lock()+ defer s.rateMu.Unlock()++ // Validate config+ if config.MinDelayMs < 0 {+ return fmt.Errorf("min_delay_ms cannot be negative")+ }+ if config.MaxDelayMs < config.MinDelayMs {+ config.MaxDelayMs = config.MinDelayMs+ }+ if config.MaxMessagesPerMinute < 0 {+ config.MaxMessagesPerMinute = 0+ }+ if config.MaxMessagesPerHour < 0 {+ config.MaxMessagesPerHour = 0+ }+ if config.MaxNewContactsPerDay < 0 {+ config.MaxNewContactsPerDay = 0+ }++ s.rateLimitConfig = config+ s.logger.Infof("Rate limit config updated: enabled=%v, delay=%d-%dms, typing=%v",+ config.Enabled, config.MinDelayMs, config.MaxDelayMs, config.SimulateTyping)+ return nil+}++// GetRateLimitStats returns current rate limiting statistics+func (s *Service) GetRateLimitStats() *RateLimitStats {+ s.rateMu.Lock()+ defer s.rateMu.Unlock()++ // Reset daily counters if needed+ s.resetDailyCountersIfNeeded()++ // Calculate stats from sliding window+ now := time.Now()+ minuteAgo := now.Add(-1 * time.Minute)+ hourAgo := now.Add(-1 * time.Hour)++ minuteCount := 0+ hourCount := 0+ for _, t := range s.messageTimes {+ if t.After(minuteAgo) {+ minuteCount+++ }+ if t.After(hourAgo) {+ hourCount+++ }+ }++ // Count new contacts today+ newContactsCount := 0+ for _, t := range s.newContactsToday {+ if t.After(s.dailyResetTime) {+ newContactsCount+++ }+ }++ // Calculate response rate (simplified - based on messages received vs sent)+ responseRate := 0.0+ if s.rateLimitStats.MessagesSentToday > 0 {+ responseRate = float64(s.rateLimitStats.ResponsesReceived) / float64(s.rateLimitStats.MessagesSentToday)+ }++ // Calculate next allowed time+ nextAllowed := s.rateLimitStats.LastMessageTime.Add(time.Duration(s.rateLimitConfig.MinDelayMs) * time.Millisecond)++ return &RateLimitStats{+ MessagesSentLastMinute: minuteCount,+ MessagesSentLastHour: hourCount,+ MessagesSentToday: s.rateLimitStats.MessagesSentToday,+ NewContactsToday: newContactsCount,+ ResponsesReceived: s.rateLimitStats.ResponsesReceived,+ ResponseRate: responseRate,+ IsPaused: s.rateLimitStats.IsPaused,+ PauseReason: s.rateLimitStats.PauseReason,+ LastMessageTime: s.rateLimitStats.LastMessageTime,+ NextAllowedTime: nextAllowed,+ }+}++// resetDailyCountersIfNeeded resets daily counters at midnight+func (s *Service) resetDailyCountersIfNeeded() {+ now := time.Now()+ // Check if we've crossed midnight since last reset+ if now.Day() != s.dailyResetTime.Day() || now.Month() != s.dailyResetTime.Month() {+ s.rateLimitStats.MessagesSentToday = 0+ s.rateLimitStats.ResponsesReceived = 0+ s.newContactsToday = make(map[string]time.Time)+ s.dailyResetTime = now+ s.logger.Info("Daily rate limit counters reset")+ }+}++// CheckRateLimit checks rate limits and waits if necessary. Returns error only for hard limits.+func (s *Service) CheckRateLimit(recipient string) error {+ s.rateMu.Lock()+ config := s.rateLimitConfig+ s.rateMu.Unlock()++ if !config.Enabled {+ return nil+ }++ // Keep checking and waiting until we're within limits+ for {+ waitDuration, hardError := s.checkRateLimitInternal(recipient)+ if hardError != nil {+ return hardError // New contacts limit or paused - can't wait+ }+ if waitDuration <= 0 {+ return nil // Within limits, proceed+ }++ // Wait until we're within rate limits+ s.logger.Infof("Rate limit reached, waiting %v before sending...", waitDuration)+ time.Sleep(waitDuration)+ }+}++// checkRateLimitInternal checks limits and returns wait duration or hard error+func (s *Service) checkRateLimitInternal(recipient string) (time.Duration, error) {+ s.rateMu.Lock()+ defer s.rateMu.Unlock()++ // Reset daily counters if needed+ s.resetDailyCountersIfNeeded()++ // Check if paused - this is a hard error, can't wait+ if s.rateLimitStats.IsPaused {+ return 0, fmt.Errorf("rate limiting paused: %s", s.rateLimitStats.PauseReason)+ }++ now := time.Now()++ // Clean up old message times (keep only last hour)+ hourAgo := now.Add(-1 * time.Hour)+ newTimes := make([]time.Time, 0, len(s.messageTimes))+ for _, t := range s.messageTimes {+ if t.After(hourAgo) {+ newTimes = append(newTimes, t)+ }+ }+ s.messageTimes = newTimes++ // Count messages in last minute and hour+ minuteAgo := now.Add(-1 * time.Minute)+ minuteCount := 0+ hourCount := len(s.messageTimes)++ // Find oldest message in last minute (to calculate wait time)+ var oldestInMinute time.Time+ var oldestInHour time.Time+ for _, t := range s.messageTimes {+ if t.After(minuteAgo) {+ minuteCount+++ if oldestInMinute.IsZero() || t.Before(oldestInMinute) {+ oldestInMinute = t+ }+ }+ if oldestInHour.IsZero() || t.Before(oldestInHour) {+ oldestInHour = t+ }+ }++ // Check per-minute limit - calculate wait time if exceeded+ if s.rateLimitConfig.MaxMessagesPerMinute > 0 && minuteCount >= s.rateLimitConfig.MaxMessagesPerMinute {+ // Wait until oldest message in minute window expires+ waitUntil := oldestInMinute.Add(1 * time.Minute)+ waitDuration := waitUntil.Sub(now) + 100*time.Millisecond // Add small buffer+ if waitDuration > 0 {+ s.logger.Debugf("Per-minute limit reached (%d/%d), need to wait %v",+ minuteCount, s.rateLimitConfig.MaxMessagesPerMinute, waitDuration)+ return waitDuration, nil+ }+ }++ // Check per-hour limit - calculate wait time if exceeded+ if s.rateLimitConfig.MaxMessagesPerHour > 0 && hourCount >= s.rateLimitConfig.MaxMessagesPerHour {+ // Wait until oldest message in hour window expires+ waitUntil := oldestInHour.Add(1 * time.Hour)+ waitDuration := waitUntil.Sub(now) + 100*time.Millisecond // Add small buffer+ if waitDuration > 0 {+ s.logger.Debugf("Per-hour limit reached (%d/%d), need to wait %v",+ hourCount, s.rateLimitConfig.MaxMessagesPerHour, waitDuration)+ return waitDuration, nil+ }+ }++ // Check new contacts limit - this is a HARD limit, return error (can't wait for tomorrow)+ if s.rateLimitConfig.MaxNewContactsPerDay > 0 {+ if _, seen := s.contactsSeen[recipient]; !seen {+ newContactsCount := 0+ for _, t := range s.newContactsToday {+ if t.After(s.dailyResetTime) {+ newContactsCount+++ }+ }+ if newContactsCount >= s.rateLimitConfig.MaxNewContactsPerDay {+ return 0, fmt.Errorf("new contacts limit exceeded: %d new contacts/day (max: %d) - try again tomorrow",+ newContactsCount, s.rateLimitConfig.MaxNewContactsPerDay)+ }+ }+ }++ // Check response rate threshold (if enabled) - hard error+ if s.rateLimitConfig.PauseOnLowResponse && s.rateLimitStats.MessagesSentToday >= 10 {+ responseRate := float64(s.rateLimitStats.ResponsesReceived) / float64(s.rateLimitStats.MessagesSentToday)+ if responseRate < s.rateLimitConfig.ResponseRateThreshold {+ s.rateLimitStats.IsPaused = true+ s.rateLimitStats.PauseReason = fmt.Sprintf("low response rate: %.1f%% (threshold: %.1f%%)",+ responseRate*100, s.rateLimitConfig.ResponseRateThreshold*100)+ return 0, fmt.Errorf("rate limiting paused: %s", s.rateLimitStats.PauseReason)+ }+ }++ return 0, nil // Within all limits+}++// ApplyMessageDelay applies the configured delay before sending a message+func (s *Service) ApplyMessageDelay(hasLinks bool) {+ s.rateMu.Lock()+ config := s.rateLimitConfig+ s.rateMu.Unlock()++ if !config.Enabled || config.MinDelayMs <= 0 {+ return+ }++ delay := config.MinDelayMs++ // Add randomization if enabled+ if config.RandomizeDelays && config.MaxDelayMs > config.MinDelayMs {+ delay = config.MinDelayMs + rand.Intn(config.MaxDelayMs-config.MinDelayMs)+ }++ // Add extra delay for messages with links+ if hasLinks && config.LinkExtraDelayMs > 0 {+ delay += config.LinkExtraDelayMs+ }++ s.logger.Debugf("Applying message delay: %dms (links: %v)", delay, hasLinks)+ time.Sleep(time.Duration(delay) * time.Millisecond)+}++// SendTypingIfEnabled sends typing indicator if configured+// The typing indicator stays active until the message is sent+func (s *Service) SendTypingIfEnabled(jidStr string) {+ s.rateMu.Lock()+ config := s.rateLimitConfig+ s.rateMu.Unlock()++ if !config.Enabled || !config.SimulateTyping || config.TypingDelayMs <= 0 {+ return+ }++ // Parse JID+ jid, err := types.ParseJID(jidStr)+ if err != nil {+ s.logger.Debugf("Could not parse JID for typing indicator: %v", err)+ return+ }++ // Send composing indicator - stays active until message is sent+ ctx := context.Background()+ err = s.client.SendChatPresence(ctx, jid, types.ChatPresenceComposing, types.ChatPresenceMediaText)+ if err != nil {+ s.logger.Debugf("Failed to send typing indicator: %v", err)+ return+ }++ s.logger.Debugf("Sent typing indicator to %s, waiting %dms", jidStr, config.TypingDelayMs)++ // Wait for typing duration (indicator stays active)+ time.Sleep(time.Duration(config.TypingDelayMs) * time.Millisecond)++ // No paused indicator - typing stays active until message is sent+ // WhatsApp clears the typing indicator when the message arrives+}++// RecordMessageSent updates rate limiting stats after a message is sent+func (s *Service) RecordMessageSent(recipient string) {+ s.rateMu.Lock()+ defer s.rateMu.Unlock()++ now := time.Now()++ // Record message time+ s.messageTimes = append(s.messageTimes, now)+ s.rateLimitStats.MessagesSentToday+++ s.rateLimitStats.LastMessageTime = now++ // Track new contacts+ if _, seen := s.contactsSeen[recipient]; !seen {+ s.contactsSeen[recipient] = true+ s.newContactsToday[recipient] = now+ s.logger.Debugf("New contact recorded: %s (total today: %d)", recipient, len(s.newContactsToday))+ }+}++// RecordResponseReceived increments the response counter (call when receiving a message)+func (s *Service) RecordResponseReceived() {+ s.rateMu.Lock()+ defer s.rateMu.Unlock()+ s.rateLimitStats.ResponsesReceived+++}++// UnpauseRateLimiting resumes rate limiting after it was paused+func (s *Service) UnpauseRateLimiting() {+ s.rateMu.Lock()+ defer s.rateMu.Unlock()+ s.rateLimitStats.IsPaused = false+ s.rateLimitStats.PauseReason = ""+ s.logger.Info("Rate limiting unpaused")+}++func (s *Service) Shutdown() {+ if s.shutdown {+ return // Already shutdown+ }++ s.logger.Info("Shutting down WhatsApp service...")+ s.shutdown = true+ s.running = false+ s.pairing = false++ if s.client != nil {+ s.client.Disconnect()+ }++ // Give goroutines more time to exit cleanly+ time.Sleep(500 * time.Millisecond)++ // Drain any remaining events but DON'T close the channel+ // This allows ForwardEvents goroutines to continue working after restart+ for {+ select {+ case <-s.events:+ // Keep draining+ default:+ goto done+ }+ }+ done:++ // DO NOT close(s.events) - keep channel open for restart+ s.logger.Info("WhatsApp service shutdown complete")+}++func (s *Service) Reset() error {+ s.logger.Info("Starting full reset with logout...")++ // Logout from WhatsApp servers first (invalidates session on server side)+ if s.client != nil && s.client.IsLoggedIn() {+ s.logger.Info("Logging out from WhatsApp...")+ if err := s.client.Logout(context.Background()); err != nil {+ s.logger.Warnf("Logout failed (may already be logged out): %v", err)+ } else {+ s.logger.Info("Logged out from WhatsApp successfully")+ }+ }++ // Shutdown the service (disconnect, close channels)+ s.Shutdown()++ // Delete the device session from store+ if s.client != nil && s.client.Store != nil {+ s.logger.Info("Deleting device session from store...")+ if err := s.client.Store.Delete(context.Background()); err != nil {+ s.logger.Warnf("Failed to delete device store: %v", err)+ }+ }++ // Clear client reference to allow GC and release DB locks+ s.client = nil+ s.container = nil++ // Give time for database to release locks+ time.Sleep(2 * time.Second)++ // Delete database files+ dbFiles := []string{s.dbPath, s.dbPath + "-wal", s.dbPath + "-shm"}+ for _, file := range dbFiles {+ if _, err := os.Stat(file); err == nil {+ s.logger.Infof("Deleting: %s", file)+ if err := os.Remove(file); err != nil {+ s.logger.Warnf("Failed to delete %s: %v", file, err)+ }+ }+ }++ // Reinitialize client with fresh database+ if err := s.reinitClient(); err != nil {+ s.logger.Errorf("Failed to reinitialize client: %v", err)+ return fmt.Errorf("failed to reinitialize client: %w", err)+ }++ s.logger.Info("WhatsApp reset complete")+ return nil+}++// reinitClient creates a new database and client after reset+func (s *Service) reinitClient() error {+ s.logger.Info("Reinitializing WhatsApp client...")++ // Create new database+ dbLog := waLog.Stdout("Database", "INFO", true)+ ctx := context.Background()+ container, err := sqlstore.New(ctx, "sqlite", "file:"+s.dbPath+"?_pragma=foreign_keys(1)&_journal_mode=WAL&_busy_timeout=30000&cache=shared", dbLog)+ if err != nil {+ return fmt.Errorf("failed to initialize database: %w", err)+ }++ // Get device store+ deviceStore, err := container.GetFirstDevice(ctx)+ if err != nil {+ return fmt.Errorf("failed to get device: %w", err)+ }++ // Create new client+ clientLog := waLog.Stdout("WhatsApp", "INFO", true)+ client := whatsmeow.NewClient(deviceStore, clientLog)++ // Update service references+ s.container = container+ s.client = client++ // Add event handler to new client+ client.AddEventHandler(s.eventHandler)++ s.logger.Info("WhatsApp client reinitialized successfully")+ return nil+}++func (s *Service) cleanupOldQRCodes() {+ s.CleanupQRCodes()+}++// CleanupQRCodes deletes all QR code PNG files+func (s *Service) CleanupQRCodes() {+ // Delete all old QR code PNG files+ files, err := filepath.Glob("data/qr/qr_*.png")+ if err != nil {+ s.logger.Warnf("Failed to find old QR code files: %v", err)+ return+ }++ if len(files) > 0 {+ s.logger.Infof("Cleaning up %d old QR code file(s)", len(files))+ for _, file := range files {+ if err := os.Remove(file); err != nil {+ s.logger.Warnf("Failed to delete old QR code file %s: %v", file, err)+ } else {+ s.logger.Debugf("Deleted old QR code file: %s", file)+ }+ }+ }++ // Clear cached QR code+ s.lastQRCode = nil+}\ No newline at end of filediff --git a/server/whatsapp-rpc/src/go/whatsapp/types.go b/server/whatsapp-rpc/src/go/whatsapp/types.gonew file mode 100644index 00000000..d05dd67f--- /dev/null+++ b/server/whatsapp-rpc/src/go/whatsapp/types.go@@ -0,0 +1,260 @@+package whatsapp++import "time"++// Event represents a WhatsApp service event+type Event struct {+ Type string `json:"type"`+ Data map[string]interface{} `json:"data"`+ Time time.Time `json:"timestamp"`+}++// QRCodeData represents QR code information+type QRCodeData struct {+ Code string `json:"code"`+ Filename string `json:"filename"`+ ImageData string `json:"image_data,omitempty"` // Base64 PNG data+ Time time.Time `json:"timestamp"`+}++// MessageRequest represents various message types for sending+type MessageRequest struct {+ Phone string `json:"phone,omitempty"`+ GroupID string `json:"group_id,omitempty"`+ Message string `json:"message,omitempty"`+ Type string `json:"type"` // text, image, document, audio, video, location, sticker, contact+ MediaData *MediaData `json:"media_data,omitempty"`+ Location *LocationData `json:"location,omitempty"`+ Contact *ContactCard `json:"contact,omitempty"`+ Reply *ReplyData `json:"reply,omitempty"`+ Metadata map[string]string `json:"metadata,omitempty"`+}++// MediaData represents media content for messages+type MediaData struct {+ Data string `json:"data"` // base64 encoded data+ MimeType string `json:"mime_type"` // image/jpeg, audio/mp3, etc.+ Filename string `json:"filename"` // optional filename+ Caption string `json:"caption"` // optional caption for media+ Thumbnail string `json:"thumbnail"` // base64 encoded thumbnail (optional)+}++// LocationData represents location information+type LocationData struct {+ Latitude float64 `json:"latitude"`+ Longitude float64 `json:"longitude"`+ Name string `json:"name,omitempty"` // optional location name+ Address string `json:"address,omitempty"` // optional address+}++// ReplyData represents reply context for messages+type ReplyData struct {+ MessageID string `json:"message_id"`+ Sender string `json:"sender"`+ Content string `json:"content"`+}++// ContactCard represents a contact vCard for sharing+type ContactCard struct {+ DisplayName string `json:"display_name"`+ VCard string `json:"vcard"` // vCard format string+}++// ContactInfo represents comprehensive contact information+type ContactInfo struct {+ JID string `json:"jid"`+ Phone string `json:"phone"`+ Name string `json:"name,omitempty"`+ BusinessName string `json:"business_name,omitempty"`+ PushName string `json:"push_name,omitempty"`+ IsContact bool `json:"is_contact"`+ IsBusiness bool `json:"is_business"`+ LastSeen time.Time `json:"last_seen,omitempty"`+ ProfilePic string `json:"profile_pic,omitempty"` // base64 encoded+}++// GroupInfo represents comprehensive group information+type GroupInfo struct {+ JID string `json:"jid"`+ Name string `json:"name"`+ Topic string `json:"topic,omitempty"`+ Owner string `json:"owner"`+ Participants []GroupParticipant `json:"participants"`+ CreatedAt time.Time `json:"created_at"`+ Size int `json:"size"`+ IsAnnounce bool `json:"is_announce"` // Only admins can send messages+ IsLocked bool `json:"is_locked"` // Only admins can edit group info+}++// GroupUpdateRequest represents parameters for updating a group+type GroupUpdateRequest struct {+ GroupID string `json:"group_id"`+ Name string `json:"name,omitempty"`+ Topic string `json:"topic,omitempty"`+}++// GroupParticipant represents a group member+type GroupParticipant struct {+ JID string `json:"jid"`+ Phone string `json:"phone"`+ Name string `json:"name,omitempty"`+ IsAdmin bool `json:"is_admin"`+ IsSuperAdmin bool `json:"is_super_admin"`+}++// MessageInfo represents received message information+type MessageInfo struct {+ ID string `json:"id"`+ From string `json:"from"`+ To string `json:"to"`+ Type string `json:"type"`+ Content string `json:"content,omitempty"`+ MediaInfo *ReceivedMediaInfo `json:"media_info,omitempty"`+ Location *LocationData `json:"location,omitempty"`+ GroupInfo *GroupMessageInfo `json:"group_info,omitempty"`+ Reply *ReplyData `json:"reply,omitempty"`+ Timestamp time.Time `json:"timestamp"`+ IsFromMe bool `json:"is_from_me"`+ Status string `json:"status"` // sent, delivered, read+}++// ReceivedMediaInfo represents received media message information+type ReceivedMediaInfo struct {+ MimeType string `json:"mime_type"`+ Size int64 `json:"size"`+ Filename string `json:"filename,omitempty"`+ Caption string `json:"caption,omitempty"`+ URL string `json:"url"` // download URL+ SHA256 string `json:"sha256"` // file hash+}++// GroupMessageInfo represents group message context+type GroupMessageInfo struct {+ GroupJID string `json:"group_jid"`+ GroupName string `json:"group_name,omitempty"`+ SenderJID string `json:"sender_jid"`+ SenderName string `json:"sender_name,omitempty"`+}++// PresenceInfo represents presence information+type PresenceInfo struct {+ JID string `json:"jid"`+ Status string `json:"status"` // available, unavailable, composing, paused+ LastSeen time.Time `json:"last_seen,omitempty"`+}++// WebhookConfig represents webhook configuration+type WebhookConfig struct {+ URL string `json:"url"`+ Secret string `json:"secret,omitempty"`+ Events []string `json:"events"` // message, status, presence, etc.+ Headers map[string]string `json:"headers"` // custom headers+ Enabled bool `json:"enabled"`+}++// MessageStatus represents delivery status+type MessageStatus struct {+ ID string `json:"id"`+ Status string `json:"status"` // sent, delivered, read+ Timestamp time.Time `json:"timestamp"`+ From string `json:"from"`+ To string `json:"to"`+}++// ContactCheckResult represents the result of checking if a phone is on WhatsApp+type ContactCheckResult struct {+ Query string `json:"query"` // Original phone number queried+ JID string `json:"jid,omitempty"` // WhatsApp JID if registered+ IsRegistered bool `json:"is_registered"` // Whether registered on WhatsApp+ IsBusiness bool `json:"is_business"` // Whether it's a business account+ BusinessName string `json:"business_name,omitempty"` // Business verified name+}++// ProfilePicResult represents profile picture information+type ProfilePicResult struct {+ URL string `json:"url,omitempty"` // URL to download image+ ID string `json:"id,omitempty"` // Image identifier+ Data string `json:"data,omitempty"` // Base64-encoded image data+ Exists bool `json:"exists"` // Whether profile picture exists+}++// GroupParticipantChangeResult represents result for a single participant change+type GroupParticipantChangeResult struct {+ JID string `json:"jid"`+ Phone string `json:"phone,omitempty"`+ Success bool `json:"success"`+ Error string `json:"error,omitempty"`+}++// GroupParticipantsResult represents batch participant change result+type GroupParticipantsResult struct {+ GroupID string `json:"group_id"`+ Action string `json:"action"` // "add" or "remove"+ Results []GroupParticipantChangeResult `json:"results"`+ Added int `json:"added,omitempty"`+ Removed int `json:"removed,omitempty"`+ Failed int `json:"failed"`+}++// GroupInviteLinkResult represents invite link response+type GroupInviteLinkResult struct {+ GroupID string `json:"group_id"`+ InviteLink string `json:"invite_link"`+ Revoked bool `json:"revoked,omitempty"`+}++// RateLimitConfig represents configurable rate limiting settings for anti-ban protection+type RateLimitConfig struct {+ Enabled bool `json:"enabled"`++ // Message delays (milliseconds)+ MinDelayMs int `json:"min_delay_ms"` // Minimum delay between messages (default: 3000)+ MaxDelayMs int `json:"max_delay_ms"` // Maximum delay for randomization (default: 8000)+ TypingDelayMs int `json:"typing_delay_ms"` // Typing indicator duration (default: 2000)+ LinkExtraDelayMs int `json:"link_extra_delay_ms"` // Extra delay for messages with links (default: 5000)++ // Rate limits+ MaxMessagesPerMinute int `json:"max_messages_per_minute"` // Per-minute limit (default: 10)+ MaxMessagesPerHour int `json:"max_messages_per_hour"` // Per-hour limit (default: 60)+ MaxNewContactsPerDay int `json:"max_new_contacts_per_day"` // New contacts limit (default: 20)++ // Human simulation+ SimulateTyping bool `json:"simulate_typing"` // Send typing indicator before message+ RandomizeDelays bool `json:"randomize_delays"` // Add random variance to delays++ // Safety+ PauseOnLowResponse bool `json:"pause_on_low_response"` // Pause if response rate < threshold+ ResponseRateThreshold float64 `json:"response_rate_threshold"` // Min response rate (0.3 = 30%)+}++// RateLimitStats represents current rate limiting statistics+type RateLimitStats struct {+ MessagesSentLastMinute int `json:"messages_sent_last_minute"`+ MessagesSentLastHour int `json:"messages_sent_last_hour"`+ MessagesSentToday int `json:"messages_sent_today"`+ NewContactsToday int `json:"new_contacts_today"`+ ResponsesReceived int `json:"responses_received"`+ ResponseRate float64 `json:"response_rate"`+ IsPaused bool `json:"is_paused"`+ PauseReason string `json:"pause_reason,omitempty"`+ LastMessageTime time.Time `json:"last_message_time"`+ NextAllowedTime time.Time `json:"next_allowed_time"`+}++// DefaultRateLimitConfig returns conservative defaults for anti-ban protection+func DefaultRateLimitConfig() *RateLimitConfig {+ return &RateLimitConfig{+ Enabled: true,+ MinDelayMs: 3000, // 3 seconds minimum+ MaxDelayMs: 8000, // Up to 8 seconds with randomization+ TypingDelayMs: 2000, // 2 seconds typing+ LinkExtraDelayMs: 5000, // 5 extra seconds for links+ MaxMessagesPerMinute: 10, // Conservative+ MaxMessagesPerHour: 60, // 1 per minute average+ MaxNewContactsPerDay: 20, // Critical for new accounts+ SimulateTyping: true, // Major anti-detection+ RandomizeDelays: true, // Avoid fixed patterns+ PauseOnLowResponse: false, // Disabled by default+ ResponseRateThreshold: 0.3, // 30% minimum+ }+}\ No newline at end of filediff --git a/server/whatsapp-rpc/src/python/pyproject.toml b/server/whatsapp-rpc/src/python/pyproject.tomlnew file mode 100644index 00000000..38b277a2--- /dev/null+++ b/server/whatsapp-rpc/src/python/pyproject.toml@@ -0,0 +1,15 @@+[build-system]+requires = ["setuptools>=61.0"]+build-backend = "setuptools.build_meta"++[project]+name = "whatsapp-rpc"+version = "1.0.0"+description = "Python client for WhatsApp RPC API"+requires-python = ">=3.8"+dependencies = [+ "websockets>=12.0",+]++[tool.setuptools.packages.find]+where = ["."]diff --git a/server/whatsapp-rpc/src/python/whatsapp_rpc/__init__.py b/server/whatsapp-rpc/src/python/whatsapp_rpc/__init__.pynew file mode 100644index 00000000..60db3f6a--- /dev/null+++ b/server/whatsapp-rpc/src/python/whatsapp_rpc/__init__.py@@ -0,0 +1,4 @@+from .client import WhatsAppRPCClient++__version__ = "1.0.0"+__all__ = ["WhatsAppRPCClient"]diff --git a/server/whatsapp-rpc/src/python/whatsapp_rpc/client.py b/server/whatsapp-rpc/src/python/whatsapp_rpc/client.pynew file mode 100644index 00000000..eee7b64c--- /dev/null+++ b/server/whatsapp-rpc/src/python/whatsapp_rpc/client.py@@ -0,0 +1,427 @@+"""+WhatsApp RPC Client - Async JSON-RPC 2.0 client over WebSocket++Uses the official `websockets` library for stable async WebSocket communication.+Implements JSON-RPC 2.0 protocol for bidirectional communication with Go backend.+"""++import asyncio+import json+import logging+from typing import Any, Callable, Optional++import websockets+from websockets.exceptions import ConnectionClosed++logger = logging.getLogger(__name__)+++class WhatsAppRPCClient:+ """Async JSON-RPC 2.0 client using official websockets library."""++ def __init__(self, ws_url: str):+ """+ Initialize RPC client.++ Args:+ ws_url: WebSocket URL (e.g., 'ws://localhost:9400/ws/rpc')+ """+ self.ws_url = ws_url+ self.ws = None+ self.request_id = 0+ self.pending: dict[int, asyncio.Future] = {}+ self.event_callback: Optional[Callable[[dict], None]] = None+ self._recv_task: Optional[asyncio.Task] = None+ self._connected = False++ @property+ def connected(self) -> bool:+ """Check if WebSocket is connected."""+ return self._connected and self.ws is not None++ async def connect(self) -> None:+ """Connect to WebSocket RPC endpoint."""+ try:+ self.ws = await websockets.connect(+ self.ws_url,+ ping_interval=300, # 5 minutes, same as Go server+ ping_timeout=60,+ max_size=100 * 1024 * 1024, # 100 MB max message size for large media+ close_timeout=10,+ )+ self._connected = True+ self._recv_task = asyncio.create_task(self._receive_loop())+ logger.info(f"Connected to RPC endpoint: {self.ws_url}")+ except Exception as e:+ logger.error(f"Failed to connect to RPC endpoint: {e}")+ raise++ async def close(self) -> None:+ """Close connection."""+ self._connected = False+ if self._recv_task:+ self._recv_task.cancel()+ try:+ await self._recv_task+ except asyncio.CancelledError:+ pass+ if self.ws:+ await self.ws.close()+ self.ws = None+ logger.info("RPC connection closed")++ async def _receive_loop(self) -> None:+ """Handle incoming messages (responses and events)."""+ try:+ async for message in self.ws:+ try:+ data = json.loads(message)++ if "id" in data and data["id"] is not None:+ # Response to a request+ req_id = data["id"]+ if req_id in self.pending:+ self.pending[req_id].set_result(data)+ elif data.get("method", "").startswith("event."):+ # Event notification from server+ if self.event_callback:+ try:+ self.event_callback(data)+ except Exception as e:+ logger.error(f"Error in event callback: {e}")+ except json.JSONDecodeError as e:+ logger.error(f"Invalid JSON received: {e}")+ except ConnectionClosed:+ logger.warning("WebSocket connection closed")+ self._connected = False+ except Exception as e:+ logger.error(f"Error in receive loop: {e}")+ self._connected = False++ async def call(self, method: str, params: Any = None, timeout: float = 30) -> Any:+ """+ Call RPC method and wait for response.++ Args:+ method: RPC method name (e.g., 'status', 'send')+ params: Method parameters (optional)+ timeout: Response timeout in seconds++ Returns:+ Result from the RPC call++ Raises:+ Exception: If RPC call fails or times out+ """+ if not self.connected:+ raise Exception("Not connected to RPC endpoint")++ self.request_id += 1+ req_id = self.request_id++ request = {"jsonrpc": "2.0", "id": req_id, "method": method}+ if params is not None:+ request["params"] = params++ future = asyncio.get_event_loop().create_future()+ self.pending[req_id] = future++ try:+ await self.ws.send(json.dumps(request))+ response = await asyncio.wait_for(future, timeout)++ if "error" in response and response["error"]:+ error = response["error"]+ raise Exception(f"RPC Error {error.get('code', -1)}: {error.get('message', 'Unknown error')}")++ return response.get("result")+ except asyncio.TimeoutError:+ raise Exception(f"RPC call '{method}' timed out after {timeout}s")+ finally:+ self.pending.pop(req_id, None)++ # Convenience methods for each RPC command+ async def status(self) -> dict:+ """Get WhatsApp connection status."""+ return await self.call("status")++ async def start(self) -> dict:+ """Start WhatsApp service."""+ return await self.call("start")++ async def stop(self) -> dict:+ """Stop WhatsApp service."""+ return await self.call("stop")++ async def restart(self) -> dict:+ """Restart WhatsApp service."""+ return await self.call("restart")++ async def reset(self) -> dict:+ """Reset WhatsApp session."""+ return await self.call("reset")++ async def diagnostics(self) -> dict:+ """Get diagnostics information."""+ return await self.call("diagnostics")++ async def qr(self) -> dict:+ """Get QR code for pairing."""+ return await self.call("qr")++ async def send(self, **kwargs) -> dict:+ """+ Send WhatsApp message.++ Supports all message types: text, image, video, audio, document,+ sticker, location, contact.++ Args:+ phone: Recipient phone number (or use group_id)+ group_id: Group JID (or use phone)+ type: Message type (text, image, etc.)+ message: Text content (for text messages)+ media_data: Media content (for media messages)+ location: Location data (for location messages)+ contact: Contact data (for contact messages)+ reply: Reply context (optional)+ """+ return await self.call("send", kwargs)++ async def media(self, message_id: str) -> dict:+ """+ Download media from a received message.++ Args:+ message_id: ID of the message containing media++ Returns:+ Dict with 'data' (base64) and 'mime_type'+ """+ # Use longer timeout for media downloads (videos can be large)+ return await self.call("media", {"message_id": message_id}, timeout=120)++ async def groups(self) -> list:+ """+ Get all groups the user is a member of.++ Returns:+ List of group info dicts with jid, name, topic, participants, etc.+ """+ return await self.call("groups")++ async def group_info(self, group_id: str) -> dict:+ """+ Get detailed information about a specific group.++ Args:+ group_id: Group JID (e.g., '[email protected]')++ Returns:+ Dict with group details including participants+ """+ return await self.call("group_info", {"group_id": group_id})++ async def group_update(self, group_id: str, name: str = None, topic: str = None) -> dict:+ """+ Update group name and/or topic (description).++ Args:+ group_id: Group JID+ name: New group name (optional)+ topic: New group description (optional)++ Returns:+ Success message+ """+ params = {"group_id": group_id}+ if name is not None:+ params["name"] = name+ if topic is not None:+ params["topic"] = topic+ return await self.call("group_update", params)++ async def contact_check(self, phones: list) -> list:+ """+ Check if phone numbers are registered on WhatsApp.++ Args:+ phones: List of phone numbers (without + prefix)++ Returns:+ List of dicts with query, jid, is_registered, is_business, business_name+ """+ return await self.call("contact_check", {"phones": phones})++ async def contact_profile_pic(self, jid: str, preview: bool = False) -> dict:+ """+ Get profile picture for a user or group.++ Args:+ jid: User or group JID (e.g., '[email protected]')+ preview: Get smaller preview image instead of full size++ Returns:+ Dict with exists, url, id, data (base64 if available)+ """+ return await self.call("contact_profile_pic", {"jid": jid, "preview": preview})++ async def typing(self, jid: str, state: str = "composing", media: str = "") -> dict:+ """+ Send typing indicator to a chat.++ Args:+ jid: Chat JID (individual or group)+ state: 'composing' (typing) or 'paused' (stopped typing)+ media: '' for text typing, 'audio' for recording voice++ Returns:+ Success message+ """+ params = {"jid": jid, "state": state}+ if media:+ params["media"] = media+ return await self.call("typing", params)++ async def presence(self, status: str) -> dict:+ """+ Set online/offline presence status.++ Args:+ status: 'available' (online) or 'unavailable' (offline)++ Returns:+ Success message+ """+ return await self.call("presence", {"status": status})++ async def mark_read(self, message_ids: list, chat_jid: str, sender_jid: str = None) -> dict:+ """+ Mark messages as read.++ Args:+ message_ids: List of message IDs to mark as read+ chat_jid: Chat JID where messages are from+ sender_jid: Sender JID (required for group messages)++ Returns:+ Success message+ """+ params = {"message_ids": message_ids, "chat_jid": chat_jid}+ if sender_jid:+ params["sender_jid"] = sender_jid+ return await self.call("mark_read", params)++ async def group_participants_add(self, group_id: str, participants: list) -> dict:+ """+ Add participants to a group.++ Args:+ group_id: Group JID (e.g., '[email protected]')+ participants: List of phone numbers or JIDs to add++ Returns:+ Dict with group_id, action, results (list with success/error per participant),+ added count, and failed count+ """+ return await self.call("group_participants_add", {+ "group_id": group_id,+ "participants": participants+ })++ async def group_participants_remove(self, group_id: str, participants: list) -> dict:+ """+ Remove participants from a group.++ Args:+ group_id: Group JID (e.g., '[email protected]')+ participants: List of phone numbers or JIDs to remove++ Returns:+ Dict with group_id, action, results (list with success/error per participant),+ removed count, and failed count+ """+ return await self.call("group_participants_remove", {+ "group_id": group_id,+ "participants": participants+ })++ async def group_invite_link(self, group_id: str) -> dict:+ """+ Get the invite link for a group.++ Args:+ group_id: Group JID (e.g., '[email protected]')++ Returns:+ Dict with group_id, invite_link+ """+ return await self.call("group_invite_link", {"group_id": group_id})++ async def group_revoke_invite(self, group_id: str) -> dict:+ """+ Revoke and regenerate the group invite link.++ Args:+ group_id: Group JID (e.g., '[email protected]')++ Returns:+ Dict with group_id, invite_link (new), revoked=true+ """+ return await self.call("group_revoke_invite", {"group_id": group_id})++ # ========================================================================+ # Rate Limiting Methods (Anti-Ban Protection)+ # ========================================================================++ async def rate_limit_get(self) -> dict:+ """+ Get current rate limit configuration and statistics.++ Returns:+ Dict with 'config' (RateLimitConfig) and 'stats' (RateLimitStats)+ """+ return await self.call("rate_limit_get")++ async def rate_limit_set(self, **config) -> dict:+ """+ Update rate limit configuration dynamically.++ Args:+ enabled: Enable/disable rate limiting+ min_delay_ms: Minimum delay between messages (ms, default: 3000)+ max_delay_ms: Maximum delay for randomization (ms, default: 8000)+ typing_delay_ms: Typing indicator duration (ms, default: 2000)+ link_extra_delay_ms: Extra delay for messages with links (ms, default: 5000)+ max_messages_per_minute: Per-minute message limit (default: 10)+ max_messages_per_hour: Per-hour message limit (default: 60)+ max_new_contacts_per_day: Daily new contact limit (default: 20)+ simulate_typing: Send typing indicator before messages (default: true)+ randomize_delays: Add random variance to delays (default: true)+ pause_on_low_response: Pause if response rate < threshold (default: false)+ response_rate_threshold: Min response rate 0.0-1.0 (default: 0.3)++ Returns:+ Dict with 'message' and updated 'config'+ """+ return await self.call("rate_limit_set", config)++ async def rate_limit_stats(self) -> dict:+ """+ Get current rate limiting statistics.++ Returns:+ Dict with messages_sent_last_minute, messages_sent_last_hour,+ messages_sent_today, new_contacts_today, response_rate,+ is_paused, pause_reason, last_message_time, next_allowed_time+ """+ return await self.call("rate_limit_stats")++ async def rate_limit_unpause(self) -> dict:+ """+ Unpause rate limiting after it was paused due to low response rate.++ Returns:+ Dict with 'message' and current 'stats'+ """+ return await self.call("rate_limit_unpause")diff --git a/server/whatsapp-rpc/web/app.py b/server/whatsapp-rpc/web/app.pynew file mode 100644index 00000000..20d252a0--- /dev/null+++ b/server/whatsapp-rpc/web/app.py@@ -0,0 +1,609 @@+"""+WhatsApp Controller Web UI - WebSocket RPC Version+Uses WebSocket RPC as the primary and only communication method with Go backend.+"""++import os+import asyncio+import json+import logging+import threading+import time+from flask import Flask, render_template, request, jsonify, redirect, url_for, flash, send_from_directory+from flask_socketio import SocketIO, emit+from flask_limiter import Limiter+from flask_limiter.util import get_remote_address++from rpc_client import WhatsAppRPCClient++# Setup logging+logging.basicConfig(+ level=logging.INFO,+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'+)+logger = logging.getLogger(__name__)++app = Flask(__name__)+app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'dev-secret-key')+socketio_app = SocketIO(app, cors_allowed_origins="*")++# Configuration+GO_WS_RPC_URL = os.getenv('GO_WS_RPC_URL', 'ws://localhost:9400/ws/rpc')++# Rate Limiting Configuration+RATE_LIMIT_ENABLED = os.getenv('RATE_LIMIT_ENABLED', 'true').lower() == 'true'+RATE_LIMIT_GLOBAL = os.getenv('RATE_LIMIT_GLOBAL', '20 per minute')+RATE_LIMIT_PER_USER = os.getenv('RATE_LIMIT_PER_USER', '10 per minute')+MESSAGE_DELAY_SECONDS = float(os.getenv('MESSAGE_DELAY_SECONDS', '3'))++# Initialize rate limiter+limiter = Limiter(+ app=app,+ key_func=get_remote_address,+ default_limits=[] if not RATE_LIMIT_ENABLED else [RATE_LIMIT_GLOBAL],+ storage_uri="memory://",+ strategy="fixed-window"+)++# RPC Client globals+rpc_loop: asyncio.AbstractEventLoop = None+rpc_client: WhatsAppRPCClient = None+++def get_recipient_key():+ """Extract recipient (phone or group_id) for per-user rate limiting"""+ try:+ if request.is_json:+ data = request.json+ return data.get('phone') or data.get('group_id') or get_remote_address()+ elif request.form:+ return request.form.get('phone') or request.form.get('group_id') or get_remote_address()+ except:+ pass+ return get_remote_address()+++def apply_message_delay():+ """Add delay between messages to simulate human behavior"""+ if RATE_LIMIT_ENABLED and MESSAGE_DELAY_SECONDS > 0:+ time.sleep(MESSAGE_DELAY_SECONDS)+++def run_async(coro, timeout=30):+ """Run async coroutine from sync Flask context."""+ if rpc_loop is None or rpc_client is None:+ raise Exception("RPC client not initialized")+ if not rpc_client.connected:+ raise Exception("RPC client not connected")+ return asyncio.run_coroutine_threadsafe(coro, rpc_loop).result(timeout=timeout)+++def init_rpc_client():+ """Initialize RPC client in background thread."""+ global rpc_loop, rpc_client++ rpc_client = WhatsAppRPCClient(GO_WS_RPC_URL)++ # Set event callback to forward to Socket.IO clients+ def on_event(event):+ try:+ method = event.get("method", "")+ event_type = method.replace("event.", "") if method.startswith("event.") else method+ params = event.get("params", {})++ data = {"type": event_type, "data": params}+ socketio_app.emit('whatsapp_event', data, namespace='/')+ logger.debug(f"Event forwarded: {event_type}")+ except Exception as e:+ logger.error(f"Error forwarding event: {e}")++ rpc_client.event_callback = on_event++ def start_loop():+ global rpc_loop+ rpc_loop = asyncio.new_event_loop()+ asyncio.set_event_loop(rpc_loop)+ try:+ rpc_loop.run_until_complete(rpc_client.connect())+ logger.info(f"RPC client connected to {GO_WS_RPC_URL}")+ rpc_loop.run_forever()+ except Exception as e:+ logger.error(f"RPC client connection failed: {e}")++ thread = threading.Thread(target=start_loop, daemon=True)+ thread.start()+ logger.info("RPC client initialization started")+++# ============================================================================+# Routes+# ============================================================================+[email protected]('/')+def index():+ """Main dashboard"""+ try:+ status = run_async(rpc_client.status())+ return render_template('dashboard.html', status={"success": True, "data": status})+ except Exception as e:+ return render_template('dashboard.html', status={"success": False, "error": str(e)})++[email protected]('/api/status')+def api_status():+ """Get WhatsApp connection status"""+ try:+ result = run_async(rpc_client.status())+ return jsonify({"success": True, "data": result})+ except Exception as e:+ return jsonify({"success": False, "error": str(e)}), 500++[email protected]('/api/start', methods=['POST'])+def api_start():+ """Start WhatsApp service"""+ try:+ result = run_async(rpc_client.start())+ return jsonify({"success": True, "data": result})+ except Exception as e:+ return jsonify({"success": False, "error": str(e)}), 500++[email protected]('/api/stop', methods=['POST'])+def api_stop():+ """Stop WhatsApp service"""+ try:+ result = run_async(rpc_client.stop())+ return jsonify({"success": True, "data": result})+ except Exception as e:+ return jsonify({"success": False, "error": str(e)}), 500++[email protected]('/api/restart', methods=['POST'])+def api_restart():+ """Restart WhatsApp service"""+ try:+ result = run_async(rpc_client.restart())+ return jsonify({"success": True, "data": result})+ except Exception as e:+ return jsonify({"success": False, "error": str(e)}), 500++[email protected]('/api/reset', methods=['POST'])+def api_reset():+ """Reset WhatsApp session"""+ try:+ result = run_async(rpc_client.reset())+ return jsonify({"success": True, "data": result})+ except Exception as e:+ return jsonify({"success": False, "error": str(e)}), 500++[email protected]('/api/qr')+def api_qr():+ """Get QR code information"""+ try:+ result = run_async(rpc_client.qr())+ return jsonify({"success": True, "data": result})+ except Exception as e:+ return jsonify({"success": False, "error": str(e)}), 404++[email protected]('/api/diagnostics')+def api_diagnostics():+ """Get diagnostics information"""+ try:+ result = run_async(rpc_client.diagnostics())+ return jsonify({"success": True, "data": result})+ except Exception as e:+ return jsonify({"success": False, "error": str(e)}), 500++[email protected]('/api/send', methods=['POST'])[email protected](RATE_LIMIT_PER_USER, key_func=get_recipient_key)+def api_send():+ """Send WhatsApp message (simple)"""+ data = request.json+ if not data or 'phone' not in data or 'message' not in data:+ return jsonify({"success": False, "error": "Phone and message required"}), 400++ apply_message_delay()++ try:+ result = run_async(rpc_client.send(+ phone=data['phone'],+ message=data['message'],+ type='text'+ ))+ return jsonify({"success": True, "data": result})+ except Exception as e:+ return jsonify({"success": False, "error": str(e)}), 500++[email protected]('/api/send/enhanced', methods=['POST'])[email protected](RATE_LIMIT_PER_USER, key_func=get_recipient_key)+def api_send_enhanced():+ """Send enhanced WhatsApp message (all types)"""+ data = request.json+ if not data:+ return jsonify({"success": False, "error": "Message data required"}), 400++ apply_message_delay()++ try:+ result = run_async(rpc_client.send(**data))+ return jsonify({"success": True, "data": result})+ except Exception as e:+ return jsonify({"success": False, "error": str(e)}), 500++[email protected]('/api/media/<message_id>')+def api_media(message_id):+ """Download media from a message"""+ try:+ # Use longer timeout for media downloads (videos can be large)+ result = run_async(rpc_client.media(message_id), timeout=120)+ return jsonify({"success": True, "data": result})+ except Exception as e:+ logger.error(f"Media download failed for {message_id}: {e}")+ return jsonify({"success": False, "error": str(e)}), 404++[email protected]('/api/groups')+def api_groups():+ """Get all groups"""+ try:+ result = run_async(rpc_client.groups())+ return jsonify({"success": True, "data": result})+ except Exception as e:+ logger.error(f"Failed to get groups: {e}")+ return jsonify({"success": False, "error": str(e)}), 500++[email protected]('/api/groups/<path:group_id>')+def api_group_info(group_id):+ """Get group info"""+ try:+ result = run_async(rpc_client.group_info(group_id))+ return jsonify({"success": True, "data": result})+ except Exception as e:+ logger.error(f"Failed to get group info for {group_id}: {e}")+ return jsonify({"success": False, "error": str(e)}), 500++[email protected]('/api/groups/update', methods=['POST'])+def api_group_update():+ """Update group name/topic"""+ data = request.json+ if not data or 'group_id' not in data:+ return jsonify({"success": False, "error": "group_id required"}), 400++ try:+ result = run_async(rpc_client.group_update(+ group_id=data['group_id'],+ name=data.get('name'),+ topic=data.get('topic')+ ))+ return jsonify({"success": True, "data": result})+ except Exception as e:+ logger.error(f"Failed to update group {data.get('group_id')}: {e}")+ return jsonify({"success": False, "error": str(e)}), 500+++# ============================================================================+# Rate Limiting API Routes+# ============================================================================+[email protected]('/api/rate-limit')+def api_rate_limit_get():+ """Get rate limit configuration and stats"""+ try:+ result = run_async(rpc_client.rate_limit_get())+ return jsonify({"success": True, "data": result})+ except Exception as e:+ logger.error(f"Failed to get rate limit config: {e}")+ return jsonify({"success": False, "error": str(e)}), 500++[email protected]('/api/rate-limit', methods=['POST'])+def api_rate_limit_set():+ """Update rate limit configuration"""+ data = request.json+ if not data:+ return jsonify({"success": False, "error": "Configuration data required"}), 400++ try:+ result = run_async(rpc_client.rate_limit_set(**data))+ return jsonify({"success": True, "data": result})+ except Exception as e:+ logger.error(f"Failed to update rate limit config: {e}")+ return jsonify({"success": False, "error": str(e)}), 500++[email protected]('/api/rate-limit/stats')+def api_rate_limit_stats():+ """Get rate limiting statistics"""+ try:+ result = run_async(rpc_client.rate_limit_stats())+ return jsonify({"success": True, "data": result})+ except Exception as e:+ logger.error(f"Failed to get rate limit stats: {e}")+ return jsonify({"success": False, "error": str(e)}), 500++[email protected]('/api/rate-limit/unpause', methods=['POST'])+def api_rate_limit_unpause():+ """Unpause rate limiting"""+ try:+ result = run_async(rpc_client.rate_limit_unpause())+ return jsonify({"success": True, "data": result})+ except Exception as e:+ logger.error(f"Failed to unpause rate limiting: {e}")+ return jsonify({"success": False, "error": str(e)}), 500+++# ============================================================================+# Pages+# ============================================================================+[email protected]('/send')+def send_page():+ """Send message page"""+ return render_template('send.html')++[email protected]('/send', methods=['POST'])[email protected](RATE_LIMIT_PER_USER, key_func=get_recipient_key)+def send_message():+ """Handle message sending from form"""+ phone = request.form.get('phone')+ message = request.form.get('message')++ if not phone or not message:+ flash('Phone number and message are required', 'error')+ return redirect(url_for('send_page'))++ apply_message_delay()++ try:+ run_async(rpc_client.send(phone=phone, message=message, type='text'))+ flash(f'Message sent to {phone}!', 'success')+ except Exception as e:+ flash(f'Failed to send message: {str(e)}', 'error')++ return redirect(url_for('send_page'))++[email protected]('/messaging')+def messaging_page():+ """Enhanced messaging page"""+ return render_template('messaging.html')++[email protected]('/messages')+def messages_page():+ """Messages viewing page"""+ return render_template('messages.html')++[email protected]('/groups')+def groups_page():+ """Groups management page"""+ return render_template('groups.html')++[email protected]('/contacts')+def contacts_page():+ """Contacts management page"""+ return render_template('contacts.html')++[email protected]('/settings')+def settings_page():+ """Rate limiting and settings page"""+ return render_template('settings.html')++[email protected]('/qr/<filename>')+def serve_qr_file(filename):+ """Serve QR PNG files from project root"""+ if filename.startswith('qr_') and filename.endswith('.png'):+ current_dir = os.path.dirname(os.path.abspath(__file__))+ project_root = os.path.dirname(current_dir)+ file_path = os.path.join(project_root, filename)++ if os.path.exists(file_path):+ return send_from_directory(project_root, filename, mimetype='image/png')+ else:+ return jsonify({"success": False, "error": "File not found"}), 404+ return jsonify({"success": False, "error": "Invalid filename"}), 400+++# ============================================================================+# WebSocket Events (Flask-SocketIO for browser clients)+# ============================================================================++@socketio_app.on('connect')+def handle_connect():+ logger.info('Browser client connected')+ try:+ status = run_async(rpc_client.status())+ emit('status_update', {"success": True, "data": status})+ except Exception as e:+ emit('status_update', {"success": False, "error": str(e)})+++@socketio_app.on('disconnect')+def handle_disconnect():+ logger.info('Browser client disconnected')+++@socketio_app.on('request_status')+def handle_status_request():+ try:+ status = run_async(rpc_client.status())+ emit('status_update', {"success": True, "data": status})+ except Exception as e:+ emit('status_update', {"success": False, "error": str(e)})+++@socketio_app.on('subscribe_messages')+def handle_subscribe_messages():+ """Client subscribes to receive all WhatsApp events"""+ logger.info('Client subscribed to messages')+ emit('subscribed', {'success': True})+++@socketio_app.on('contact_check')+def handle_contact_check(data):+ """Check if phone numbers are registered on WhatsApp"""+ phones = data.get('phones', [])+ if not phones:+ emit('contact_check_result', {"success": False, "error": "phones array required"})+ return+ try:+ result = run_async(rpc_client.contact_check(phones))+ emit('contact_check_result', {"success": True, "data": result})+ except Exception as e:+ logger.error(f"Failed to check contacts: {e}")+ emit('contact_check_result', {"success": False, "error": str(e)})+++@socketio_app.on('contact_profile_pic')+def handle_contact_profile_pic(data):+ """Get profile picture for a user or group"""+ jid = data.get('jid')+ if not jid:+ emit('contact_profile_pic_result', {"success": False, "error": "jid required"})+ return+ try:+ result = run_async(rpc_client.contact_profile_pic(jid, data.get('preview', False)))+ emit('contact_profile_pic_result', {"success": True, "data": result, "jid": jid})+ except Exception as e:+ logger.error(f"Failed to get profile picture: {e}")+ emit('contact_profile_pic_result', {"success": False, "error": str(e), "jid": jid})+++@socketio_app.on('typing')+def handle_typing(data):+ """Send typing indicator to a chat"""+ jid = data.get('jid')+ if not jid:+ emit('typing_result', {"success": False, "error": "jid required"})+ return+ try:+ result = run_async(rpc_client.typing(+ jid=jid,+ state=data.get('state', 'composing'),+ media=data.get('media', '')+ ))+ emit('typing_result', {"success": True, "data": result})+ except Exception as e:+ logger.error(f"Failed to send typing indicator: {e}")+ emit('typing_result', {"success": False, "error": str(e)})+++@socketio_app.on('presence')+def handle_presence(data):+ """Set online/offline presence status"""+ status = data.get('status')+ if not status:+ emit('presence_result', {"success": False, "error": "status required"})+ return+ try:+ result = run_async(rpc_client.presence(status))+ emit('presence_result', {"success": True, "data": result})+ except Exception as e:+ logger.error(f"Failed to set presence: {e}")+ emit('presence_result', {"success": False, "error": str(e)})+++@socketio_app.on('mark_read')+def handle_mark_read(data):+ """Mark messages as read"""+ message_ids = data.get('message_ids', [])+ chat_jid = data.get('chat_jid')+ if not message_ids or not chat_jid:+ emit('mark_read_result', {"success": False, "error": "message_ids and chat_jid required"})+ return+ try:+ result = run_async(rpc_client.mark_read(+ message_ids=message_ids,+ chat_jid=chat_jid,+ sender_jid=data.get('sender_jid')+ ))+ emit('mark_read_result', {"success": True, "data": result})+ except Exception as e:+ logger.error(f"Failed to mark messages as read: {e}")+ emit('mark_read_result', {"success": False, "error": str(e)})+++@socketio_app.on('rate_limit_get')+def handle_rate_limit_get():+ """Get rate limit configuration and stats"""+ try:+ result = run_async(rpc_client.rate_limit_get())+ emit('rate_limit_result', {"success": True, "data": result})+ except Exception as e:+ logger.error(f"Failed to get rate limit config: {e}")+ emit('rate_limit_result', {"success": False, "error": str(e)})+++@socketio_app.on('rate_limit_set')+def handle_rate_limit_set(data):+ """Update rate limit configuration"""+ try:+ result = run_async(rpc_client.rate_limit_set(**data))+ emit('rate_limit_result', {"success": True, "data": result})+ except Exception as e:+ logger.error(f"Failed to update rate limit config: {e}")+ emit('rate_limit_result', {"success": False, "error": str(e)})+++@socketio_app.on('rate_limit_stats')+def handle_rate_limit_stats():+ """Get rate limiting statistics"""+ try:+ result = run_async(rpc_client.rate_limit_stats())+ emit('rate_limit_stats_result', {"success": True, "data": result})+ except Exception as e:+ logger.error(f"Failed to get rate limit stats: {e}")+ emit('rate_limit_stats_result', {"success": False, "error": str(e)})+++@socketio_app.on('rate_limit_unpause')+def handle_rate_limit_unpause():+ """Unpause rate limiting"""+ try:+ result = run_async(rpc_client.rate_limit_unpause())+ emit('rate_limit_result', {"success": True, "data": result})+ except Exception as e:+ logger.error(f"Failed to unpause rate limiting: {e}")+ emit('rate_limit_result', {"success": False, "error": str(e)})+++# ============================================================================+# Main+# ============================================================================++if __name__ == '__main__':+ port = int(os.getenv('PORT', 5000))+ debug = os.getenv('FLASK_ENV') == 'development'++ if debug:+ logging.getLogger().setLevel(logging.DEBUG)++ print(f"Starting WhatsApp Web UI (WebSocket RPC) on port {port}")+ print(f"Go WebSocket RPC URL: {GO_WS_RPC_URL}")++ # Initialize RPC client+ print("Connecting to Go backend via WebSocket RPC...")+ init_rpc_client()+ time.sleep(2) # Give RPC client time to connect++ # Print routes+ print("Registered routes:")+ for rule in app.url_map.iter_rules():+ print(f" {rule.rule} - {rule.methods}")++ socketio_app.run(app, host='0.0.0.0', port=port, debug=debug, allow_unsafe_werkzeug=True)diff --git a/server/whatsapp-rpc/web/requirements.txt b/server/whatsapp-rpc/web/requirements.txtnew file mode 100644index 00000000..083185c9--- /dev/null+++ b/server/whatsapp-rpc/web/requirements.txt@@ -0,0 +1,6 @@+# WhatsApp Controller Web UI - WebSocket RPC Version+Flask==3.0.0+Flask-SocketIO==5.3.6+Flask-Limiter==3.5.0+python-socketio==5.10.0+websockets>=12.0diff --git a/server/whatsapp-rpc/web/rpc_client.py b/server/whatsapp-rpc/web/rpc_client.pynew file mode 100644index 00000000..eee7b64c--- /dev/null+++ b/server/whatsapp-rpc/web/rpc_client.py@@ -0,0 +1,427 @@+"""+WhatsApp RPC Client - Async JSON-RPC 2.0 client over WebSocket++Uses the official `websockets` library for stable async WebSocket communication.+Implements JSON-RPC 2.0 protocol for bidirectional communication with Go backend.+"""++import asyncio+import json+import logging+from typing import Any, Callable, Optional++import websockets+from websockets.exceptions import ConnectionClosed++logger = logging.getLogger(__name__)+++class WhatsAppRPCClient:+ """Async JSON-RPC 2.0 client using official websockets library."""++ def __init__(self, ws_url: str):+ """+ Initialize RPC client.++ Args:+ ws_url: WebSocket URL (e.g., 'ws://localhost:9400/ws/rpc')+ """+ self.ws_url = ws_url+ self.ws = None+ self.request_id = 0+ self.pending: dict[int, asyncio.Future] = {}+ self.event_callback: Optional[Callable[[dict], None]] = None+ self._recv_task: Optional[asyncio.Task] = None+ self._connected = False++ @property+ def connected(self) -> bool:+ """Check if WebSocket is connected."""+ return self._connected and self.ws is not None++ async def connect(self) -> None:+ """Connect to WebSocket RPC endpoint."""+ try:+ self.ws = await websockets.connect(+ self.ws_url,+ ping_interval=300, # 5 minutes, same as Go server+ ping_timeout=60,+ max_size=100 * 1024 * 1024, # 100 MB max message size for large media+ close_timeout=10,+ )+ self._connected = True+ self._recv_task = asyncio.create_task(self._receive_loop())+ logger.info(f"Connected to RPC endpoint: {self.ws_url}")+ except Exception as e:+ logger.error(f"Failed to connect to RPC endpoint: {e}")+ raise++ async def close(self) -> None:+ """Close connection."""+ self._connected = False+ if self._recv_task:+ self._recv_task.cancel()+ try:+ await self._recv_task+ except asyncio.CancelledError:+ pass+ if self.ws:+ await self.ws.close()+ self.ws = None+ logger.info("RPC connection closed")++ async def _receive_loop(self) -> None:+ """Handle incoming messages (responses and events)."""+ try:+ async for message in self.ws:+ try:+ data = json.loads(message)++ if "id" in data and data["id"] is not None:+ # Response to a request+ req_id = data["id"]+ if req_id in self.pending:+ self.pending[req_id].set_result(data)+ elif data.get("method", "").startswith("event."):+ # Event notification from server+ if self.event_callback:+ try:+ self.event_callback(data)+ except Exception as e:+ logger.error(f"Error in event callback: {e}")+ except json.JSONDecodeError as e:+ logger.error(f"Invalid JSON received: {e}")+ except ConnectionClosed:+ logger.warning("WebSocket connection closed")+ self._connected = False+ except Exception as e:+ logger.error(f"Error in receive loop: {e}")+ self._connected = False++ async def call(self, method: str, params: Any = None, timeout: float = 30) -> Any:+ """+ Call RPC method and wait for response.++ Args:+ method: RPC method name (e.g., 'status', 'send')+ params: Method parameters (optional)+ timeout: Response timeout in seconds++ Returns:+ Result from the RPC call++ Raises:+ Exception: If RPC call fails or times out+ """+ if not self.connected:+ raise Exception("Not connected to RPC endpoint")++ self.request_id += 1+ req_id = self.request_id++ request = {"jsonrpc": "2.0", "id": req_id, "method": method}+ if params is not None:+ request["params"] = params++ future = asyncio.get_event_loop().create_future()+ self.pending[req_id] = future++ try:+ await self.ws.send(json.dumps(request))+ response = await asyncio.wait_for(future, timeout)++ if "error" in response and response["error"]:+ error = response["error"]+ raise Exception(f"RPC Error {error.get('code', -1)}: {error.get('message', 'Unknown error')}")++ return response.get("result")+ except asyncio.TimeoutError:+ raise Exception(f"RPC call '{method}' timed out after {timeout}s")+ finally:+ self.pending.pop(req_id, None)++ # Convenience methods for each RPC command+ async def status(self) -> dict:+ """Get WhatsApp connection status."""+ return await self.call("status")++ async def start(self) -> dict:+ """Start WhatsApp service."""+ return await self.call("start")++ async def stop(self) -> dict:+ """Stop WhatsApp service."""+ return await self.call("stop")++ async def restart(self) -> dict:+ """Restart WhatsApp service."""+ return await self.call("restart")++ async def reset(self) -> dict:+ """Reset WhatsApp session."""+ return await self.call("reset")++ async def diagnostics(self) -> dict:+ """Get diagnostics information."""+ return await self.call("diagnostics")++ async def qr(self) -> dict:+ """Get QR code for pairing."""+ return await self.call("qr")++ async def send(self, **kwargs) -> dict:+ """+ Send WhatsApp message.++ Supports all message types: text, image, video, audio, document,+ sticker, location, contact.++ Args:+ phone: Recipient phone number (or use group_id)+ group_id: Group JID (or use phone)+ type: Message type (text, image, etc.)+ message: Text content (for text messages)+ media_data: Media content (for media messages)+ location: Location data (for location messages)+ contact: Contact data (for contact messages)+ reply: Reply context (optional)+ """+ return await self.call("send", kwargs)++ async def media(self, message_id: str) -> dict:+ """+ Download media from a received message.++ Args:+ message_id: ID of the message containing media++ Returns:+ Dict with 'data' (base64) and 'mime_type'+ """+ # Use longer timeout for media downloads (videos can be large)+ return await self.call("media", {"message_id": message_id}, timeout=120)++ async def groups(self) -> list:+ """+ Get all groups the user is a member of.++ Returns:+ List of group info dicts with jid, name, topic, participants, etc.+ """+ return await self.call("groups")++ async def group_info(self, group_id: str) -> dict:+ """+ Get detailed information about a specific group.++ Args:+ group_id: Group JID (e.g., '[email protected]')++ Returns:+ Dict with group details including participants+ """+ return await self.call("group_info", {"group_id": group_id})++ async def group_update(self, group_id: str, name: str = None, topic: str = None) -> dict:+ """+ Update group name and/or topic (description).++ Args:+ group_id: Group JID+ name: New group name (optional)+ topic: New group description (optional)++ Returns:+ Success message+ """+ params = {"group_id": group_id}+ if name is not None:+ params["name"] = name+ if topic is not None:+ params["topic"] = topic+ return await self.call("group_update", params)++ async def contact_check(self, phones: list) -> list:+ """+ Check if phone numbers are registered on WhatsApp.++ Args:+ phones: List of phone numbers (without + prefix)++ Returns:+ List of dicts with query, jid, is_registered, is_business, business_name+ """+ return await self.call("contact_check", {"phones": phones})++ async def contact_profile_pic(self, jid: str, preview: bool = False) -> dict:+ """+ Get profile picture for a user or group.++ Args:+ jid: User or group JID (e.g., '[email protected]')+ preview: Get smaller preview image instead of full size++ Returns:+ Dict with exists, url, id, data (base64 if available)+ """+ return await self.call("contact_profile_pic", {"jid": jid, "preview": preview})++ async def typing(self, jid: str, state: str = "composing", media: str = "") -> dict:+ """+ Send typing indicator to a chat.++ Args:+ jid: Chat JID (individual or group)+ state: 'composing' (typing) or 'paused' (stopped typing)+ media: '' for text typing, 'audio' for recording voice++ Returns:+ Success message+ """+ params = {"jid": jid, "state": state}+ if media:+ params["media"] = media+ return await self.call("typing", params)++ async def presence(self, status: str) -> dict:+ """+ Set online/offline presence status.++ Args:+ status: 'available' (online) or 'unavailable' (offline)++ Returns:+ Success message+ """+ return await self.call("presence", {"status": status})++ async def mark_read(self, message_ids: list, chat_jid: str, sender_jid: str = None) -> dict:+ """+ Mark messages as read.++ Args:+ message_ids: List of message IDs to mark as read+ chat_jid: Chat JID where messages are from+ sender_jid: Sender JID (required for group messages)++ Returns:+ Success message+ """+ params = {"message_ids": message_ids, "chat_jid": chat_jid}+ if sender_jid:+ params["sender_jid"] = sender_jid+ return await self.call("mark_read", params)++ async def group_participants_add(self, group_id: str, participants: list) -> dict:+ """+ Add participants to a group.++ Args:+ group_id: Group JID (e.g., '[email protected]')+ participants: List of phone numbers or JIDs to add++ Returns:+ Dict with group_id, action, results (list with success/error per participant),+ added count, and failed count+ """+ return await self.call("group_participants_add", {+ "group_id": group_id,+ "participants": participants+ })++ async def group_participants_remove(self, group_id: str, participants: list) -> dict:+ """+ Remove participants from a group.++ Args:+ group_id: Group JID (e.g., '[email protected]')+ participants: List of phone numbers or JIDs to remove++ Returns:+ Dict with group_id, action, results (list with success/error per participant),+ removed count, and failed count+ """+ return await self.call("group_participants_remove", {+ "group_id": group_id,+ "participants": participants+ })++ async def group_invite_link(self, group_id: str) -> dict:+ """+ Get the invite link for a group.++ Args:+ group_id: Group JID (e.g., '[email protected]')++ Returns:+ Dict with group_id, invite_link+ """+ return await self.call("group_invite_link", {"group_id": group_id})++ async def group_revoke_invite(self, group_id: str) -> dict:+ """+ Revoke and regenerate the group invite link.++ Args:+ group_id: Group JID (e.g., '[email protected]')++ Returns:+ Dict with group_id, invite_link (new), revoked=true+ """+ return await self.call("group_revoke_invite", {"group_id": group_id})++ # ========================================================================+ # Rate Limiting Methods (Anti-Ban Protection)+ # ========================================================================++ async def rate_limit_get(self) -> dict:+ """+ Get current rate limit configuration and statistics.++ Returns:+ Dict with 'config' (RateLimitConfig) and 'stats' (RateLimitStats)+ """+ return await self.call("rate_limit_get")++ async def rate_limit_set(self, **config) -> dict:+ """+ Update rate limit configuration dynamically.++ Args:+ enabled: Enable/disable rate limiting+ min_delay_ms: Minimum delay between messages (ms, default: 3000)+ max_delay_ms: Maximum delay for randomization (ms, default: 8000)+ typing_delay_ms: Typing indicator duration (ms, default: 2000)+ link_extra_delay_ms: Extra delay for messages with links (ms, default: 5000)+ max_messages_per_minute: Per-minute message limit (default: 10)+ max_messages_per_hour: Per-hour message limit (default: 60)+ max_new_contacts_per_day: Daily new contact limit (default: 20)+ simulate_typing: Send typing indicator before messages (default: true)+ randomize_delays: Add random variance to delays (default: true)+ pause_on_low_response: Pause if response rate < threshold (default: false)+ response_rate_threshold: Min response rate 0.0-1.0 (default: 0.3)++ Returns:+ Dict with 'message' and updated 'config'+ """+ return await self.call("rate_limit_set", config)++ async def rate_limit_stats(self) -> dict:+ """+ Get current rate limiting statistics.++ Returns:+ Dict with messages_sent_last_minute, messages_sent_last_hour,+ messages_sent_today, new_contacts_today, response_rate,+ is_paused, pause_reason, last_message_time, next_allowed_time+ """+ return await self.call("rate_limit_stats")++ async def rate_limit_unpause(self) -> dict:+ """+ Unpause rate limiting after it was paused due to low response rate.++ Returns:+ Dict with 'message' and current 'stats'+ """+ return await self.call("rate_limit_unpause")diff --git a/server/whatsapp-rpc/web/static/openapi.yaml b/server/whatsapp-rpc/web/static/openapi.yamlnew file mode 100644index 00000000..4b1d4747--- /dev/null+++ b/server/whatsapp-rpc/web/static/openapi.yaml@@ -0,0 +1,59 @@+openapi: 3.0.0+info:+ title: WhatsApp Controller API+ version: 1.0.0+ description: WhatsApp Web API with enhanced messaging capabilities++servers:+ - url: http://localhost:5000+ description: Flask Server++paths:+ /api/status:+ get:+ summary: Get WhatsApp status+ tags: [Status]+ responses:+ '200':+ description: Success++ /api/start:+ post:+ summary: Start WhatsApp service+ tags: [Status]+ responses:+ '200':+ description: Service started++ /api/send/enhanced:+ post:+ summary: Send message+ tags: [Messaging]+ requestBody:+ content:+ application/json:+ schema:+ type: object+ properties:+ phone:+ type: string+ type:+ type: string+ message:+ type: string+ responses:+ '200':+ description: Message sent++ /api/messages:+ get:+ summary: Get received messages+ tags: [Messages]+ parameters:+ - name: limit+ in: query+ schema:+ type: integer+ responses:+ '200':+ description: Messages retrieveddiff --git a/server/whatsapp-rpc/web/templates/base.html b/server/whatsapp-rpc/web/templates/base.htmlnew file mode 100644index 00000000..f6c9e702--- /dev/null+++ b/server/whatsapp-rpc/web/templates/base.html@@ -0,0 +1,150 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>{% block title %}WhatsApp Controller{% endblock %}</title>++ <!-- Tailwind CSS -->+ <script src="https://cdn.tailwindcss.com"></script>++ <!-- Socket.IO -->+ <script src="https://cdn.socket.io/4.7.4/socket.io.min.js"></script>++ <!-- QR Code Library -->+ <script src="https://unpkg.com/[email protected]/dist/qrious.min.js"></script>++ <style>+ .status-indicator {+ @apply inline-block w-3 h-3 rounded-full mr-2;+ }+ .status-connected { @apply bg-green-500; }+ .status-disconnected { @apply bg-red-500; }+ .status-connecting { @apply bg-yellow-500 animate-pulse; }+ </style>+</head>+<body class="bg-gray-100 min-h-screen">+ <!-- Navigation -->+ <nav class="bg-green-600 shadow-lg">+ <div class="max-w-7xl mx-auto px-4">+ <div class="flex justify-between items-center h-16">+ <div class="flex items-center">+ <h1 class="text-white text-xl font-bold">+ <a href="{{ url_for('index') }}">WhatsApp Controller</a>+ </h1>+ </div>++ <div class="flex items-center space-x-4">+ <!-- Status indicator -->+ <div id="status-indicator" class="flex items-center text-white">+ <span class="status-indicator status-disconnected" id="status-dot"></span>+ <span id="status-text">Disconnected</span>+ </div>++ <!-- Navigation links -->+ <div class="flex items-center space-x-1">+ <a href="{{ url_for('index') }}" class="text-white hover:text-green-200 px-3 py-2 rounded text-sm">+ Dashboard+ </a>++ <!-- Messaging Dropdown -->+ <div class="relative group">+ <button class="text-white hover:text-green-200 px-3 py-2 rounded text-sm flex items-center">+ Messaging+ <svg class="w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>+ </svg>+ </button>+ <div class="absolute left-0 mt-2 w-48 bg-white rounded-md shadow-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 z-50">+ <a href="{{ url_for('send_page') }}" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">Simple Send</a>+ <a href="{{ url_for('messaging_page') }}" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">Enhanced Messaging</a>+ <a href="{{ url_for('messages_page') }}" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">Received Messages</a>+ </div>+ </div>++ <a href="{{ url_for('groups_page') }}" class="text-white hover:text-green-200 px-3 py-2 rounded text-sm">+ Groups+ </a>+ <a href="{{ url_for('contacts_page') }}" class="text-white hover:text-green-200 px-3 py-2 rounded text-sm">+ Contacts+ </a>+ <a href="{{ url_for('settings_page') }}" class="text-white hover:text-green-200 px-3 py-2 rounded text-sm">+ Settings+ </a>+ </div>+ </div>+ </div>+ </div>+ </nav>++ <!-- Flash messages -->+ {% with messages = get_flashed_messages(with_categories=true) %}+ {% if messages %}+ <div class="max-w-7xl mx-auto px-4 py-4">+ {% for category, message in messages %}+ <div class="alert alert-{{ 'success' if category == 'success' else 'error' }} mb-4 p-4 rounded-lg+ {{ 'bg-green-100 border border-green-400 text-green-700' if category == 'success' else 'bg-red-100 border border-red-400 text-red-700' }}">+ {{ message }}+ </div>+ {% endfor %}+ </div>+ {% endif %}+ {% endwith %}++ <!-- Main content -->+ <main class="max-w-7xl mx-auto px-4 py-8">+ {% block content %}{% endblock %}+ </main>++ <!-- Footer -->+ <footer class="bg-white border-t mt-12">+ <div class="max-w-7xl mx-auto px-4 py-6">+ <p class="text-center text-gray-600">+ WhatsApp Controller - Modern Web Interface+ </p>+ </div>+ </footer>++ <!-- JavaScript -->+ <script>+ // Initialize Socket.IO connection+ const socket = io();++ // Status elements+ const statusDot = document.getElementById('status-dot');+ const statusText = document.getElementById('status-text');++ // Socket events+ socket.on('connect', function() {+ console.log('Connected to WebSocket');+ socket.emit('request_status');+ });++ socket.on('disconnect', function() {+ console.log('Disconnected from WebSocket');+ updateStatus('disconnected', 'Disconnected');+ });++ socket.on('status_update', function(data) {+ console.log('Status update:', data);+ if (data.success && data.data) {+ const connected = data.data.connected;+ updateStatus(connected ? 'connected' : 'disconnected',+ connected ? 'Connected' : 'Disconnected');+ }+ });++ function updateStatus(status, text) {+ statusDot.className = `status-indicator status-${status}`;+ statusText.textContent = text;+ }++ // Auto-refresh status every 30 seconds+ setInterval(() => {+ socket.emit('request_status');+ }, 30000);+ </script>++ {% block scripts %}{% endblock %}+</body>+</html>\ No newline at end of filediff --git a/server/whatsapp-rpc/web/templates/contacts.html b/server/whatsapp-rpc/web/templates/contacts.htmlnew file mode 100644index 00000000..7ab4169a--- /dev/null+++ b/server/whatsapp-rpc/web/templates/contacts.html@@ -0,0 +1,240 @@+{% extends "base.html" %}+{% block title %}Contacts - WhatsApp Controller{% endblock %}++{% block content %}+<div class="space-y-8">+ <!-- Page Header -->+ <div>+ <h1 class="text-3xl font-bold text-gray-900">Contacts</h1>+ <p class="text-gray-600 mt-1">Check if phone numbers are on WhatsApp and view profile pictures</p>+ </div>++ <!-- Check Numbers Section -->+ <div class="bg-white rounded-lg shadow-md p-6">+ <h2 class="text-xl font-semibold mb-4">Check Phone Numbers</h2>+ <p class="text-gray-600 mb-4">Enter phone numbers (one per line) to check if they are registered on WhatsApp</p>++ <div class="space-y-4">+ <div>+ <label class="block text-sm font-medium text-gray-700 mb-2">Phone Numbers</label>+ <textarea id="phone-numbers" rows="5"+ placeholder="Enter phone numbers, one per line (without + prefix) e.g. 919876543210 14155551234"+ class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500"></textarea>+ </div>++ <button onclick="checkContacts()" class="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 flex items-center">+ <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>+ </svg>+ Check Numbers+ </button>+ </div>++ <!-- Results -->+ <div id="check-results" class="mt-6 hidden">+ <h3 class="font-semibold text-gray-800 mb-3">Results</h3>+ <div id="results-container" class="space-y-2"></div>+ </div>+ </div>++ <!-- Profile Picture Section -->+ <div class="bg-white rounded-lg shadow-md p-6">+ <h2 class="text-xl font-semibold mb-4">Profile Picture</h2>+ <p class="text-gray-600 mb-4">View profile picture for a user or group</p>++ <div class="flex flex-wrap gap-4 items-end">+ <div class="flex-1 min-w-[250px]">+ <label class="block text-sm font-medium text-gray-700 mb-2">JID (Phone or Group)</label>+ <input type="text" id="profile-jid"+ placeholder="[email protected] or [email protected]"+ class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500">+ </div>+ <button onclick="getProfilePicture()" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center">+ <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path>+ </svg>+ Get Picture+ </button>+ </div>++ <!-- Profile Picture Result -->+ <div id="profile-result" class="mt-6 hidden">+ <div id="profile-container" class="flex items-center space-x-4">+ <img id="profile-image" src="" alt="Profile Picture" class="w-24 h-24 rounded-full object-cover border-4 border-gray-200">+ <div>+ <p id="profile-jid-display" class="font-semibold text-gray-800"></p>+ <p id="profile-status" class="text-sm text-gray-600"></p>+ </div>+ </div>+ <div id="profile-no-picture" class="hidden text-gray-500">+ <svg class="w-24 h-24 text-gray-300 mx-auto" fill="currentColor" viewBox="0 0 24 24">+ <path d="M24 20.993V24H0v-2.996A14.977 14.977 0 0112.004 15c4.904 0 9.26 2.354 11.996 5.993zM16.002 8.999a4 4 0 11-8 0 4 4 0 018 0z"></path>+ </svg>+ <p class="text-center mt-2">No profile picture available</p>+ </div>+ </div>+ </div>++ <!-- Presence Section -->+ <div class="bg-white rounded-lg shadow-md p-6">+ <h2 class="text-xl font-semibold mb-4">Presence Status</h2>+ <p class="text-gray-600 mb-4">Set your online/offline presence status</p>++ <div class="flex flex-wrap gap-4">+ <button onclick="setPresence('available')" class="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 flex items-center">+ <span class="w-3 h-3 bg-green-300 rounded-full mr-2"></span>+ Set Online+ </button>+ <button onclick="setPresence('unavailable')" class="px-6 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 flex items-center">+ <span class="w-3 h-3 bg-gray-400 rounded-full mr-2"></span>+ Set Offline+ </button>+ </div>+ <p id="presence-status" class="mt-3 text-sm text-gray-600"></p>+ </div>+</div>+{% endblock %}++{% block scripts %}+<script>+ // Listen for contact check result+ socket.on('contact_check_result', function(data) {+ const resultsSection = document.getElementById('check-results');+ const container = document.getElementById('results-container');++ resultsSection.classList.remove('hidden');++ if (!data.success) {+ container.innerHTML = `<div class="text-red-600">Error: ${data.error}</div>`;+ return;+ }++ const results = data.data;+ container.innerHTML = results.map(r => {+ const statusClass = r.is_registered ? 'bg-green-100 border-green-300' : 'bg-red-100 border-red-300';+ const statusIcon = r.is_registered+ ? '<svg class="w-5 h-5 text-green-600" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path></svg>'+ : '<svg class="w-5 h-5 text-red-600" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"></path></svg>';++ let businessBadge = '';+ if (r.is_business) {+ businessBadge = `<span class="ml-2 px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded">Business${r.business_name ? ': ' + escapeHtml(r.business_name) : ''}</span>`;+ }++ return `+ <div class="flex items-center justify-between p-3 border rounded-lg ${statusClass}">+ <div class="flex items-center space-x-3">+ ${statusIcon}+ <div>+ <p class="font-medium">${escapeHtml(r.query)}</p>+ ${r.is_registered ? `<p class="text-xs text-gray-600">${escapeHtml(r.jid || '')}</p>` : ''}+ </div>+ ${businessBadge}+ </div>+ <span class="text-sm font-medium ${r.is_registered ? 'text-green-700' : 'text-red-700'}">+ ${r.is_registered ? 'On WhatsApp' : 'Not on WhatsApp'}+ </span>+ </div>+ `;+ }).join('');+ });++ // Listen for profile picture result+ socket.on('contact_profile_pic_result', function(data) {+ const resultSection = document.getElementById('profile-result');+ const container = document.getElementById('profile-container');+ const noPicture = document.getElementById('profile-no-picture');+ const image = document.getElementById('profile-image');+ const jidDisplay = document.getElementById('profile-jid-display');+ const statusDisplay = document.getElementById('profile-status');++ resultSection.classList.remove('hidden');++ if (!data.success) {+ container.classList.add('hidden');+ noPicture.classList.remove('hidden');+ noPicture.innerHTML = `<p class="text-red-600">Error: ${data.error}</p>`;+ return;+ }++ jidDisplay.textContent = data.jid || '';++ if (data.data.exists) {+ container.classList.remove('hidden');+ noPicture.classList.add('hidden');++ if (data.data.data) {+ // Base64 data available+ image.src = 'data:image/jpeg;base64,' + data.data.data;+ } else if (data.data.url) {+ // URL available+ image.src = data.data.url;+ }+ statusDisplay.textContent = 'Profile picture found';+ } else {+ container.classList.add('hidden');+ noPicture.classList.remove('hidden');+ noPicture.innerHTML = `+ <svg class="w-24 h-24 text-gray-300 mx-auto" fill="currentColor" viewBox="0 0 24 24">+ <path d="M24 20.993V24H0v-2.996A14.977 14.977 0 0112.004 15c4.904 0 9.26 2.354 11.996 5.993zM16.002 8.999a4 4 0 11-8 0 4 4 0 018 0z"></path>+ </svg>+ <p class="text-center mt-2">No profile picture available</p>+ `;+ }+ });++ // Listen for presence result+ socket.on('presence_result', function(data) {+ const status = document.getElementById('presence-status');+ if (data.success) {+ status.textContent = 'Presence updated successfully';+ status.className = 'mt-3 text-sm text-green-600';+ } else {+ status.textContent = 'Failed: ' + data.error;+ status.className = 'mt-3 text-sm text-red-600';+ }+ });++ function checkContacts() {+ const textarea = document.getElementById('phone-numbers');+ const lines = textarea.value.split('\n').map(l => l.trim()).filter(l => l.length > 0);++ if (lines.length === 0) {+ alert('Please enter at least one phone number');+ return;+ }++ socket.emit('contact_check', { phones: lines });+ }++ function getProfilePicture() {+ const jid = document.getElementById('profile-jid').value.trim();++ if (!jid) {+ alert('Please enter a JID');+ return;+ }++ // Auto-append @s.whatsapp.net if no @ present+ let fullJid = jid;+ if (!jid.includes('@')) {+ fullJid = jid + '@s.whatsapp.net';+ }++ socket.emit('contact_profile_pic', { jid: fullJid, preview: false });+ }++ function setPresence(status) {+ socket.emit('presence', { status: status });+ document.getElementById('presence-status').textContent = 'Setting presence...';+ document.getElementById('presence-status').className = 'mt-3 text-sm text-blue-600';+ }++ function escapeHtml(text) {+ if (!text) return '';+ const div = document.createElement('div');+ div.textContent = text;+ return div.innerHTML;+ }+</script>+{% endblock %}diff --git a/server/whatsapp-rpc/web/templates/dashboard.html b/server/whatsapp-rpc/web/templates/dashboard.htmlnew file mode 100644index 00000000..aaba43ff--- /dev/null+++ b/server/whatsapp-rpc/web/templates/dashboard.html@@ -0,0 +1,320 @@+{% extends "base.html" %}++{% block title %}Dashboard - WhatsApp Controller{% endblock %}++{% block content %}+<div class="grid grid-cols-1 lg:grid-cols-3 gap-8">++ <!-- Status Card -->+ <div class="bg-white rounded-lg shadow-md p-6">+ <h2 class="text-xl font-semibold mb-4 flex items-center">+ <svg class="w-6 h-6 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>+ </svg>+ Connection Status+ </h2>++ <div id="status-details" class="space-y-3">+ <div class="flex justify-between items-center">+ <span>Status:</span>+ <span id="connection-status" class="font-medium">+ {{ 'Connected' if status.get('data', {}).get('connected') else 'Disconnected' }}+ </span>+ </div>+ <div class="flex justify-between items-center">+ <span>Session:</span>+ <span id="session-status" class="font-medium">+ {{ 'Active' if status.get('data', {}).get('has_session') else 'None' }}+ </span>+ </div>+ <div class="flex justify-between items-center">+ <span>Last Check:</span>+ <span id="last-check" class="text-sm text-gray-600">+ Never+ </span>+ </div>+ </div>++ <div class="mt-6 space-y-3">+ <button id="start-btn" onclick="startWhatsApp()"+ class="w-full bg-green-600 text-white py-2 px-4 rounded-lg hover:bg-green-700 transition">+ Start WhatsApp+ </button>+ <button id="restart-btn" onclick="restartWhatsApp()"+ class="w-full bg-orange-600 text-white py-2 px-4 rounded-lg hover:bg-orange-700 transition">+ Restart+ </button>+ </div>+ </div>++ <!-- QR Code Card -->+ <div class="bg-white rounded-lg shadow-md p-6">+ <h2 class="text-xl font-semibold mb-4 flex items-center">+ <svg class="w-6 h-6 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z"></path>+ </svg>+ QR Code+ </h2>++ <div id="qr-container" class="text-center">+ <div class="bg-gray-100 rounded-lg p-8 mb-4">+ <svg class="w-16 h-16 mx-auto text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z"></path>+ </svg>+ <p class="text-gray-600 mt-2">No QR code available</p>+ </div>+ <p class="text-sm text-gray-600">+ Start WhatsApp service to generate QR code for pairing+ </p>+ </div>+ </div>++ <!-- Quick Send Card -->+ <div class="bg-white rounded-lg shadow-md p-6">+ <h2 class="text-xl font-semibold mb-4 flex items-center">+ <svg class="w-6 h-6 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path>+ </svg>+ Quick Send+ </h2>++ <form id="quick-send-form" class="space-y-4">+ <div>+ <label class="block text-sm font-medium mb-1">Phone Number</label>+ <input type="text" id="quick-phone" placeholder="1234567890" required+ class="w-full border rounded-lg px-3 py-2 focus:ring-2 focus:ring-green-500 focus:border-transparent">+ </div>+ <div>+ <label class="block text-sm font-medium mb-1">Message</label>+ <textarea id="quick-message" placeholder="Enter your message..." rows="3" required+ class="w-full border rounded-lg px-3 py-2 focus:ring-2 focus:ring-green-500 focus:border-transparent"></textarea>+ </div>+ <button type="submit"+ class="w-full bg-green-600 text-white py-2 px-4 rounded-lg hover:bg-green-700 transition">+ Send Message+ </button>+ </form>+ </div>+</div>++<!-- Activity Feed -->+<div class="mt-8 bg-white rounded-lg shadow-md p-6">+ <h2 class="text-xl font-semibold mb-4">Activity Feed</h2>+ <div id="activity-feed" class="space-y-2">+ <p class="text-gray-600">No recent activity</p>+ </div>+</div>+{% endblock %}++{% block scripts %}+<script>+ // Dashboard specific JavaScript+ let activityFeed = [];++ function startWhatsApp() {+ const btn = document.getElementById('start-btn');+ btn.disabled = true;+ btn.textContent = 'Starting...';++ fetch('/api/start', { method: 'POST' })+ .then(response => response.json())+ .then(data => {+ if (data.success) {+ addActivity('success', 'WhatsApp service started successfully');+ // Start loading QR code immediately+ setTimeout(() => loadQRCode(), 1500);+ } else {+ addActivity('error', `Failed to start WhatsApp: ${data.error}`);+ }+ })+ .catch(error => {+ addActivity('error', `Error: ${error.message}`);+ })+ .finally(() => {+ btn.disabled = false;+ btn.textContent = 'Start WhatsApp';+ setTimeout(refreshStatus, 2000);+ });+ }++ function refreshStatus() {+ fetch('/api/status')+ .then(response => response.json())+ .then(data => {+ if (data.success && data.data) {+ updateStatusDisplay(data.data);+ addActivity('info', 'Status refreshed');+ }+ })+ .catch(error => {+ addActivity('error', `Failed to refresh status: ${error.message}`);+ });+ }++ function updateStatusDisplay(status) {+ document.getElementById('connection-status').textContent =+ status.connected ? 'Connected' : 'Disconnected';+ document.getElementById('session-status').textContent =+ status.has_session ? 'Active' : 'None';+ document.getElementById('last-check').textContent =+ new Date().toLocaleTimeString();+ }++ function addActivity(type, message) {+ const timestamp = new Date().toLocaleTimeString();+ activityFeed.unshift({ type, message, timestamp });++ // Keep only last 10 activities+ if (activityFeed.length > 10) {+ activityFeed = activityFeed.slice(0, 10);+ }++ renderActivityFeed();+ }++ function renderActivityFeed() {+ const container = document.getElementById('activity-feed');+ if (activityFeed.length === 0) {+ container.innerHTML = '<p class="text-gray-600">No recent activity</p>';+ return;+ }++ container.innerHTML = activityFeed.map(activity => {+ const colorClass = activity.type === 'success' ? 'text-green-600' :+ activity.type === 'error' ? 'text-red-600' : 'text-blue-600';+ return `+ <div class="flex justify-between items-center py-2 border-b last:border-b-0">+ <span class="${colorClass}">${activity.message}</span>+ <span class="text-sm text-gray-500">${activity.timestamp}</span>+ </div>+ `;+ }).join('');+ }++ // Quick send form+ document.getElementById('quick-send-form').addEventListener('submit', function(e) {+ e.preventDefault();++ const phone = document.getElementById('quick-phone').value;+ const message = document.getElementById('quick-message').value;++ if (!phone || !message) {+ addActivity('error', 'Phone number and message are required');+ return;+ }++ fetch('/api/send', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ phone, message })+ })+ .then(response => response.json())+ .then(data => {+ if (data.success) {+ addActivity('success', `Message sent to ${phone}`);+ document.getElementById('quick-message').value = '';+ } else {+ addActivity('error', `Failed to send message: ${data.error}`);+ }+ })+ .catch(error => {+ addActivity('error', `Error sending message: ${error.message}`);+ });+ });++ function loadQRCode(maxAttempts = 10, attemptNum = 1) {+ fetch('/api/qr')+ .then(response => response.json())+ .then(data => {+ const container = document.getElementById('qr-container');+ if (data.success && data.data && data.data.has_qr) {+ // Display base64 image directly (Docker compatible)+ const imgSrc = data.data.image_data+ ? `data:image/png;base64,${data.data.image_data}`+ : `/qr/${data.data.filename}`;+ container.innerHTML = `+ <div class="text-center">+ <img src="${imgSrc}" alt="QR Code" class="mx-auto mb-4 border-2 border-gray-300 rounded" style="width: 256px; height: 256px;" />+ <p class="text-sm text-gray-600">Scan this QR code with WhatsApp</p>+ </div>+ `;+ addActivity('info', 'QR code loaded');+ } else {+ // QR not ready yet, poll again if we haven't exceeded max attempts+ if (attemptNum < maxAttempts) {+ container.innerHTML = `+ <div class="bg-gray-100 rounded-lg p-8 mb-4">+ <svg class="w-16 h-16 mx-auto text-gray-400 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>+ </svg>+ <p class="text-gray-600 mt-2">Waiting for QR code... (${attemptNum}/${maxAttempts})</p>+ </div>+ `;+ setTimeout(() => loadQRCode(maxAttempts, attemptNum + 1), 1000);+ } else {+ container.innerHTML = `+ <div class="bg-gray-100 rounded-lg p-8 mb-4">+ <svg class="w-16 h-16 mx-auto text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z"></path>+ </svg>+ <p class="text-gray-600 mt-2">QR code not available</p>+ </div>+ <p class="text-sm text-gray-600">+ Try clicking "Regenerate QR Code" again+ </p>+ `;+ addActivity('error', 'QR code generation timed out');+ }+ }+ })+ .catch(error => {+ addActivity('error', `Failed to load QR code: ${error.message}`);+ });+ }++ function restartWhatsApp() {+ const btn = event.target;+ btn.disabled = true;+ btn.textContent = 'Restarting...';++ fetch('/api/restart', { method: 'POST' })+ .then(response => response.json())+ .then(data => {+ if (data.success) {+ addActivity('success', 'WhatsApp service restarted successfully');+ // Start loading QR code immediately+ setTimeout(() => loadQRCode(), 1500);+ } else {+ addActivity('error', `Failed to restart WhatsApp: ${data.error}`);+ }+ })+ .catch(error => {+ addActivity('error', `Error: ${error.message}`);+ })+ .finally(() => {+ btn.disabled = false;+ btn.textContent = 'Restart';+ setTimeout(refreshStatus, 2000);+ });+ }++ // Socket.IO events for real-time updates+ socket.on('qr_code', function(data) {+ loadQRCode(); // Reload QR code when event received+ addActivity('info', 'New QR code generated');+ });++ socket.on('connected', function(data) {+ addActivity('success', 'WhatsApp connected successfully');+ refreshStatus();+ });++ socket.on('disconnected', function(data) {+ addActivity('warning', 'WhatsApp disconnected');+ refreshStatus();+ });++ // Initial status check only (QR code must be manually regenerated)+ refreshStatus();+</script>+{% endblock %}\ No newline at end of filediff --git a/server/whatsapp-rpc/web/templates/groups.html b/server/whatsapp-rpc/web/templates/groups.htmlnew file mode 100644index 00000000..d9395f2c--- /dev/null+++ b/server/whatsapp-rpc/web/templates/groups.html@@ -0,0 +1,328 @@+{% extends "base.html" %}++{% block title %}Groups - WhatsApp Controller{% endblock %}++{% block content %}+<div class="max-w-6xl mx-auto">+ <div class="bg-white rounded-lg shadow-md p-6">+ <div class="flex justify-between items-center mb-6">+ <h2 class="text-2xl font-bold text-gray-800">WhatsApp Groups</h2>+ <button onclick="loadGroups()" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition">+ Refresh+ </button>+ </div>++ <!-- Groups count -->+ <div class="mb-4 p-3 bg-gray-100 rounded">+ <p class="text-sm text-gray-600">+ <span class="font-semibold">Total Groups:</span>+ <span id="group-count">0</span>+ </p>+ </div>++ <!-- Loading indicator -->+ <div id="loading" class="hidden text-center py-8">+ <p class="text-gray-500">Loading groups...</p>+ </div>++ <!-- Error message -->+ <div id="error-message" class="hidden mb-4 p-4 bg-red-100 border border-red-400 text-red-700 rounded">+ </div>++ <!-- Groups container -->+ <div id="groups-container" class="space-y-4">+ <p class="text-gray-500 text-center py-8">Click Refresh to load groups.</p>+ </div>+ </div>+</div>++<!-- Group Info Modal -->+<div id="group-modal" class="fixed inset-0 bg-black bg-opacity-75 hidden z-50 flex items-center justify-center">+ <div class="bg-white rounded-lg max-w-3xl max-h-[90vh] w-full m-4 overflow-hidden">+ <div class="flex justify-between items-center p-4 border-b">+ <h3 class="text-lg font-semibold" id="group-modal-title">Group Details</h3>+ <button onclick="closeGroupModal()" class="text-gray-500 hover:text-gray-700">+ <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>+ </svg>+ </button>+ </div>+ <div id="group-modal-content" class="p-4 overflow-auto max-h-[calc(90vh-80px)]">+ <p class="text-gray-500">Loading...</p>+ </div>+ </div>+</div>++<!-- Edit Group Modal -->+<div id="edit-modal" class="fixed inset-0 bg-black bg-opacity-75 hidden z-50 flex items-center justify-center">+ <div class="bg-white rounded-lg max-w-md w-full m-4">+ <div class="flex justify-between items-center p-4 border-b">+ <h3 class="text-lg font-semibold">Edit Group</h3>+ <button onclick="closeEditModal()" class="text-gray-500 hover:text-gray-700">+ <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>+ </svg>+ </button>+ </div>+ <form id="edit-form" class="p-4">+ <input type="hidden" id="edit-group-id">+ <div class="mb-4">+ <label class="block text-sm font-medium text-gray-700 mb-1">Group Name</label>+ <input type="text" id="edit-name" class="w-full px-3 py-2 border rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500">+ </div>+ <div class="mb-4">+ <label class="block text-sm font-medium text-gray-700 mb-1">Description</label>+ <textarea id="edit-topic" rows="3" class="w-full px-3 py-2 border rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500"></textarea>+ </div>+ <div class="flex justify-end space-x-2">+ <button type="button" onclick="closeEditModal()" class="px-4 py-2 bg-gray-300 text-gray-700 rounded hover:bg-gray-400">+ Cancel+ </button>+ <button type="submit" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">+ Save Changes+ </button>+ </div>+ </form>+ </div>+</div>++{% endblock %}++{% block scripts %}+<script>+ let groups = [];+ const groupsContainer = document.getElementById('groups-container');+ const groupCount = document.getElementById('group-count');+ const loading = document.getElementById('loading');+ const errorMessage = document.getElementById('error-message');++ // Load groups on page load+ loadGroups();++ function showLoading(show) {+ loading.classList.toggle('hidden', !show);+ }++ function showError(message) {+ errorMessage.textContent = message;+ errorMessage.classList.remove('hidden');+ setTimeout(() => errorMessage.classList.add('hidden'), 5000);+ }++ function loadGroups() {+ showLoading(true);+ groupsContainer.innerHTML = '';++ fetch('/api/groups')+ .then(response => response.json())+ .then(data => {+ showLoading(false);+ if (data.success) {+ groups = data.data || [];+ renderGroups();+ } else {+ showError(data.error || 'Failed to load groups');+ groupsContainer.innerHTML = '<p class="text-gray-500 text-center py-8">Failed to load groups.</p>';+ }+ })+ .catch(error => {+ showLoading(false);+ console.error('Error loading groups:', error);+ showError('Failed to load groups: ' + error.message);+ groupsContainer.innerHTML = '<p class="text-gray-500 text-center py-8">Failed to load groups.</p>';+ });+ }++ function renderGroups() {+ if (groups.length === 0) {+ groupsContainer.innerHTML = '<p class="text-gray-500 text-center py-8">No groups found.</p>';+ groupCount.textContent = '0';+ return;+ }++ groupCount.textContent = groups.length;++ groupsContainer.innerHTML = groups.map(group => `+ <div class="border rounded-lg p-4 hover:bg-gray-50 transition">+ <div class="flex justify-between items-start">+ <div class="flex-1">+ <h3 class="text-lg font-semibold text-gray-800">${escapeHtml(group.name)}</h3>+ <p class="text-sm text-gray-500 mt-1">${escapeHtml(group.jid)}</p>+ ${group.topic ? `<p class="text-sm text-gray-600 mt-2">${escapeHtml(group.topic)}</p>` : ''}+ <div class="flex items-center space-x-4 mt-2 text-sm text-gray-500">+ <span>${group.size} members</span>+ ${group.is_announce ? '<span class="px-2 py-1 bg-yellow-100 text-yellow-800 rounded text-xs">Announcement</span>' : ''}+ ${group.is_locked ? '<span class="px-2 py-1 bg-red-100 text-red-800 rounded text-xs">Locked</span>' : ''}+ </div>+ </div>+ <div class="flex space-x-2">+ <button onclick="viewGroupInfo('${group.jid}')" class="px-3 py-1 bg-blue-500 text-white rounded text-sm hover:bg-blue-600">+ View+ </button>+ <button onclick="openEditModal('${group.jid}', '${escapeHtml(group.name)}', '${escapeHtml(group.topic || '')}')" class="px-3 py-1 bg-gray-500 text-white rounded text-sm hover:bg-gray-600">+ Edit+ </button>+ </div>+ </div>+ </div>+ `).join('');+ }++ function viewGroupInfo(groupId) {+ const modal = document.getElementById('group-modal');+ const modalTitle = document.getElementById('group-modal-title');+ const modalContent = document.getElementById('group-modal-content');++ modal.classList.remove('hidden');+ modalContent.innerHTML = '<p class="text-gray-500">Loading group details...</p>';++ fetch(`/api/groups/${encodeURIComponent(groupId)}`)+ .then(response => response.json())+ .then(data => {+ if (data.success) {+ const info = data.data;+ modalTitle.textContent = info.name;+ modalContent.innerHTML = `+ <div class="space-y-4">+ <div>+ <h4 class="font-semibold text-gray-700">Group JID</h4>+ <p class="text-sm text-gray-600">${escapeHtml(info.jid)}</p>+ </div>+ ${info.topic ? `+ <div>+ <h4 class="font-semibold text-gray-700">Description</h4>+ <p class="text-sm text-gray-600">${escapeHtml(info.topic)}</p>+ </div>+ ` : ''}+ <div>+ <h4 class="font-semibold text-gray-700">Owner</h4>+ <p class="text-sm text-gray-600">${escapeHtml(info.owner)}</p>+ </div>+ <div>+ <h4 class="font-semibold text-gray-700">Created</h4>+ <p class="text-sm text-gray-600">${new Date(info.created_at).toLocaleString()}</p>+ </div>+ <div class="flex space-x-4">+ ${info.is_announce ? '<span class="px-2 py-1 bg-yellow-100 text-yellow-800 rounded text-sm">Announcement Only</span>' : ''}+ ${info.is_locked ? '<span class="px-2 py-1 bg-red-100 text-red-800 rounded text-sm">Info Locked</span>' : ''}+ </div>+ <div>+ <h4 class="font-semibold text-gray-700 mb-2">Participants (${info.participants.length})</h4>+ <div class="max-h-64 overflow-y-auto border rounded">+ <table class="w-full text-sm">+ <thead class="bg-gray-100 sticky top-0">+ <tr>+ <th class="text-left px-3 py-2">Phone</th>+ <th class="text-left px-3 py-2">Role</th>+ </tr>+ </thead>+ <tbody>+ ${info.participants.map(p => `+ <tr class="border-t">+ <td class="px-3 py-2 font-mono text-sm">${formatPhone(p.phone || p.jid)}</td>+ <td class="px-3 py-2">+ ${p.is_super_admin ? '<span class="px-2 py-1 bg-purple-100 text-purple-800 rounded text-xs">Owner</span>' :+ p.is_admin ? '<span class="px-2 py-1 bg-blue-100 text-blue-800 rounded text-xs">Admin</span>' :+ '<span class="text-gray-500">Member</span>'}+ </td>+ </tr>+ `).join('')}+ </tbody>+ </table>+ </div>+ </div>+ </div>+ `;+ } else {+ modalContent.innerHTML = `<p class="text-red-500">Error: ${data.error}</p>`;+ }+ })+ .catch(error => {+ modalContent.innerHTML = `<p class="text-red-500">Error: ${error.message}</p>`;+ });+ }++ function closeGroupModal() {+ document.getElementById('group-modal').classList.add('hidden');+ }++ function openEditModal(groupId, name, topic) {+ document.getElementById('edit-group-id').value = groupId;+ document.getElementById('edit-name').value = name;+ document.getElementById('edit-topic').value = topic;+ document.getElementById('edit-modal').classList.remove('hidden');+ }++ function closeEditModal() {+ document.getElementById('edit-modal').classList.add('hidden');+ }++ document.getElementById('edit-form').addEventListener('submit', function(e) {+ e.preventDefault();+ const groupId = document.getElementById('edit-group-id').value;+ const name = document.getElementById('edit-name').value.trim();+ const topic = document.getElementById('edit-topic').value.trim();++ if (!name && !topic) {+ showError('Please enter a name or description to update');+ return;+ }++ const payload = { group_id: groupId };+ if (name) payload.name = name;+ if (topic) payload.topic = topic;++ fetch('/api/groups/update', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(payload)+ })+ .then(response => response.json())+ .then(data => {+ if (data.success) {+ closeEditModal();+ loadGroups();+ } else {+ showError(data.error || 'Failed to update group');+ }+ })+ .catch(error => {+ showError('Failed to update group: ' + error.message);+ });+ });++ function escapeHtml(text) {+ if (!text) return '';+ const div = document.createElement('div');+ div.textContent = text;+ return div.innerHTML;+ }++ function formatPhone(phone) {+ if (!phone) return 'Unknown';+ // Check if it's a LID (contains @lid or is too long to be a real phone)+ const isLID = phone.includes('@lid') || (phone.replace(/\D/g, '').length > 13);+ // Remove @s.whatsapp.net or @lid suffix+ phone = phone.replace(/@s\.whatsapp\.net$/, '').replace(/@lid$/, '');+ // Real phone numbers are 10-13 digits (with country code)+ // LIDs are typically 15+ digits+ if (isLID || phone.length > 13) {+ // This is a LID - phone hidden due to WhatsApp privacy+ return '<span class="text-gray-400" title="Phone hidden (WhatsApp Privacy)">Hidden</span>';+ }+ // Add + prefix for international format+ if (/^\d+$/.test(phone) && phone.length >= 10) {+ return '+' + phone;+ }+ return phone;+ }++ // Close modals on escape key+ document.addEventListener('keydown', function(e) {+ if (e.key === 'Escape') {+ closeGroupModal();+ closeEditModal();+ }+ });+</script>+{% endblock %}diff --git a/server/whatsapp-rpc/web/templates/messages.html b/server/whatsapp-rpc/web/templates/messages.htmlnew file mode 100644index 00000000..a039d368--- /dev/null+++ b/server/whatsapp-rpc/web/templates/messages.html@@ -0,0 +1,465 @@+{% extends "base.html" %}++{% block title %}Received Messages - WhatsApp Controller{% endblock %}++{% block content %}+<div class="max-w-6xl mx-auto">+ <div class="bg-white rounded-lg shadow-md p-6">+ <div class="flex justify-between items-center mb-6">+ <h2 class="text-2xl font-bold text-gray-800">Received Messages</h2>+ <div class="flex items-center space-x-4">+ <button onclick="loadMessages()" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition">+ Refresh+ </button>+ <button onclick="clearMessages()" class="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600 transition">+ Clear Display+ </button>+ </div>+ </div>++ <!-- Messages count -->+ <div class="mb-4 p-3 bg-gray-100 rounded">+ <p class="text-sm text-gray-600">+ <span class="font-semibold">Total Messages:</span>+ <span id="message-count">0</span>+ </p>+ </div>++ <!-- Messages container -->+ <div id="messages-container" class="space-y-4 max-h-[600px] overflow-y-auto p-4 bg-gray-50 rounded">+ <p class="text-gray-500 text-center py-8">No messages yet. Waiting for incoming messages...</p>+ </div>+ </div>+</div>++<!-- Media Viewer Modal -->+<div id="media-modal" class="fixed inset-0 bg-black bg-opacity-75 hidden z-50 flex items-center justify-center">+ <div class="bg-white rounded-lg max-w-4xl max-h-[90vh] w-full m-4 overflow-hidden">+ <div class="flex justify-between items-center p-4 border-b">+ <h3 class="text-lg font-semibold" id="media-modal-title">Media Viewer</h3>+ <button onclick="closeMediaModal()" class="text-gray-500 hover:text-gray-700">+ <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>+ </svg>+ </button>+ </div>+ <div id="media-modal-content" class="p-4 overflow-auto max-h-[calc(90vh-80px)] flex items-center justify-center bg-gray-100">+ <p class="text-gray-500">Loading...</p>+ </div>+ </div>+</div>++{% endblock %}++{% block scripts %}+<script>+ let messages = [];+ let groupsCache = {}; // Cache group names by JID+ const messagesContainer = document.getElementById('messages-container');+ const messageCount = document.getElementById('message-count');++ // Load groups cache on page load+ loadGroupsCache();++ // Subscribe to messages via WebSocket+ socket.emit('subscribe_messages');++ // Load groups into cache for name lookup+ async function loadGroupsCache() {+ try {+ const response = await fetch('/api/groups');+ const data = await response.json();+ if (data.success && data.data) {+ data.data.forEach(group => {+ groupsCache[group.jid] = group.name;+ });+ console.log(`Cached ${Object.keys(groupsCache).length} group names`);+ }+ } catch (error) {+ console.error('Failed to load groups cache:', error);+ }+ }++ // Get group name from cache+ function getGroupName(jid) {+ return groupsCache[jid] || null;+ }++ // Listen for new messages via WebSocket+ socket.on('whatsapp_event', function(data) {+ console.log('Received WhatsApp event:', data);++ if (data.type === 'message_received') {+ // Add new message to the beginning+ messages.unshift(data);+ renderMessages();++ // Show notification+ showNotification('New message received from ' + formatSender(data.data.sender));+ }+ });++ // Refresh just re-renders (messages come via WebSocket)+ function loadMessages() {+ renderMessages();+ console.log('Messages display refreshed');+ }++ // Render all messages+ function renderMessages() {+ if (messages.length === 0) {+ messagesContainer.innerHTML = `+ <div class="text-center py-8">+ <p class="text-gray-500 mb-2">No messages yet.</p>+ <p class="text-sm text-gray-400">Messages will appear here in real-time as they are received.</p>+ <p class="text-xs text-gray-400 mt-2">Make sure WhatsApp is connected.</p>+ </div>+ `;+ messageCount.textContent = '0';+ return;+ }++ messageCount.textContent = messages.length;++ messagesContainer.innerHTML = messages.map(msg => {+ const data = msg.data || {};+ return createMessageCard(data);+ }).join('');+ }++ // Create message card HTML+ function createMessageCard(data) {+ const messageType = data.message_type || 'unknown';+ const timestamp = formatTimestamp(data.timestamp);+ const sender = formatSender(data.sender);+ const isFromMe = data.is_from_me;+ const isGroup = data.is_group || false;+ const isForwarded = data.is_forwarded || false;+ const forwardingScore = data.forwarding_score || 0;+ const chatId = data.chat_id || '';++ // Get group name if it's a group message+ let groupName = null;+ if (isGroup && chatId) {+ groupName = getGroupName(chatId);+ }++ let contentHtml = '';+ let typeIcon = '';+ let typeColor = 'bg-blue-100 text-blue-800';++ // Render based on message type+ switch(messageType) {+ case 'text':+ typeIcon = '💬'; // Speech bubble+ contentHtml = `<p class="text-gray-800">${escapeHtml(data.text || '')}</p>`;+ break;++ case 'image':+ typeIcon = '📷'; // Camera+ typeColor = 'bg-purple-100 text-purple-800';+ const imageInfo = data.image || {};+ contentHtml = `+ <div class="flex items-center space-x-3 mb-2">+ <svg class="w-16 h-16 text-purple-400" fill="currentColor" viewBox="0 0 20 20">+ <path fill-rule="evenodd" d="M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm12 12H4l4-8 3 6 2-4 3 6z" clip-rule="evenodd"></path>+ </svg>+ <div class="flex-1">+ <p class="text-sm text-gray-600">Image message</p>+ <p class="text-xs text-gray-500">${imageInfo.mime_type || 'image'} - ${formatFileSize(imageInfo.file_length || 0)}</p>+ ${data.caption ? `<p class="text-gray-800 italic mt-1">${escapeHtml(data.caption)}</p>` : ''}+ </div>+ </div>+ ${imageInfo.url ? `<button onclick="viewMedia('${escapeHtml(data.message_id)}', 'image', '${escapeHtml(imageInfo.url)}')" class="mt-2 px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600 text-sm">View Image</button>` : ''}+ `;+ break;++ case 'video':+ typeIcon = '🎥'; // Video camera+ typeColor = 'bg-pink-100 text-pink-800';+ const videoInfo = data.video || {};+ contentHtml = `+ <div class="flex items-center space-x-3 mb-2">+ <svg class="w-16 h-16 text-pink-400" fill="currentColor" viewBox="0 0 20 20">+ <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z" clip-rule="evenodd"></path>+ </svg>+ <div class="flex-1">+ <p class="text-sm text-gray-600">Video message</p>+ <p class="text-xs text-gray-500">${videoInfo.mime_type || 'video'} - ${formatFileSize(videoInfo.file_length || 0)} - ${videoInfo.seconds || 0}s</p>+ ${data.caption ? `<p class="text-gray-800 italic mt-1">${escapeHtml(data.caption)}</p>` : ''}+ </div>+ </div>+ ${videoInfo.url ? `<button onclick="viewMedia('${escapeHtml(data.message_id)}', 'video', '${escapeHtml(videoInfo.url)}')" class="mt-2 px-4 py-2 bg-pink-500 text-white rounded hover:bg-pink-600 text-sm">View Video</button>` : ''}+ `;+ break;++ case 'audio':+ typeIcon = '🎵'; // Musical note+ typeColor = 'bg-green-100 text-green-800';+ contentHtml = `<p class="text-sm text-gray-600">Audio message</p>`;+ break;++ case 'document':+ typeIcon = '📄'; // Document+ typeColor = 'bg-yellow-100 text-yellow-800';+ contentHtml = `+ <p class="text-sm text-gray-600 mb-2">Document</p>+ ${data.file_name ? `<p class="text-gray-700 font-mono text-xs">${escapeHtml(data.file_name)}</p>` : ''}+ `;+ break;++ case 'sticker':+ typeIcon = '😎'; // Sticker emoji+ typeColor = 'bg-orange-100 text-orange-800';+ contentHtml = `<p class="text-sm text-gray-600">Sticker</p>`;+ break;++ case 'location':+ typeIcon = '📍'; // Pin+ typeColor = 'bg-red-100 text-red-800';+ contentHtml = `+ <p class="text-sm text-gray-600 mb-2">Location</p>+ ${data.location ? `+ <p class="text-gray-800">+ <span class="font-semibold">${escapeHtml(data.location.name || 'Unknown')}</span><br>+ <span class="text-sm text-gray-600">${escapeHtml(data.location.address || '')}</span><br>+ <span class="text-xs text-gray-500">Lat: ${data.location.latitude}, Lon: ${data.location.longitude}</span>+ </p>+ ` : ''}+ `;+ break;++ case 'contact':+ typeIcon = '👤'; // Contact+ typeColor = 'bg-indigo-100 text-indigo-800';+ contentHtml = `+ <p class="text-sm text-gray-600 mb-2">Contact Card</p>+ ${data.contact ? `+ <p class="text-gray-800 font-semibold">${escapeHtml(data.contact.display_name || 'Unknown')}</p>+ ` : ''}+ `;+ break;++ case 'contacts':+ typeIcon = '👥'; // Contacts+ typeColor = 'bg-teal-100 text-teal-800';+ contentHtml = `<p class="text-sm text-gray-600">Multiple contacts (${data.contacts_count || 0})</p>`;+ break;++ default:+ typeIcon = '❓'; // Question mark+ typeColor = 'bg-gray-100 text-gray-800';+ contentHtml = `<p class="text-sm text-gray-600">Unknown message type: ${messageType}</p>`;+ }++ // Add quoted message if exists+ let quotedHtml = '';+ if (data.quoted) {+ quotedHtml = `+ <div class="mt-2 p-2 bg-gray-100 border-l-4 border-gray-400 rounded">+ <p class="text-xs text-gray-600">Replying to:</p>+ <p class="text-sm text-gray-700 italic">${escapeHtml(data.quoted.content || '')}</p>+ </div>+ `;+ }++ // Build group info line+ let groupInfoHtml = '';+ if (isGroup) {+ const displayGroupName = groupName || chatId.replace('@g.us', '');+ groupInfoHtml = `<p class="text-xs text-purple-600">in <span class="font-medium">${escapeHtml(displayGroupName)}</span></p>`;+ }++ // Build forwarded indicator+ let forwardedHtml = '';+ if (isForwarded) {+ const forwardedLabel = forwardingScore > 4 ? 'Forwarded many times' : 'Forwarded';+ forwardedHtml = `<span class="inline-block px-2 py-1 rounded text-xs font-medium bg-gray-200 text-gray-700 ml-1" title="Forwarding score: ${forwardingScore}">↷ ${forwardedLabel}</span>`;+ }++ return `+ <div class="bg-white border rounded-lg p-4 shadow-sm hover:shadow-md transition ${isFromMe ? 'border-l-4 border-green-500' : isGroup ? 'border-l-4 border-purple-500' : 'border-l-4 border-blue-500'}">+ <div class="flex justify-between items-start mb-2">+ <div class="flex items-center space-x-2">+ <span class="text-2xl">${typeIcon}</span>+ <div>+ <p class="font-semibold text-gray-800">${sender}</p>+ ${groupInfoHtml}+ <span class="inline-block px-2 py-1 rounded text-xs font-medium ${typeColor}">${messageType}</span>${forwardedHtml}+ </div>+ </div>+ <div class="text-right">+ <p class="text-xs text-gray-500">${timestamp}</p>+ ${isFromMe ? '<span class="text-xs text-green-600 font-medium">Sent by me</span>' : ''}+ ${isGroup && !isFromMe ? '<span class="text-xs text-purple-600 font-medium">Group message</span>' : ''}+ </div>+ </div>+ <div class="mt-2">+ ${contentHtml}+ ${quotedHtml}+ </div>+ <div class="mt-2 pt-2 border-t text-xs text-gray-400 flex justify-between items-center">+ <span class="font-mono">ID: ${escapeHtml(data.message_id || 'N/A')}</span>+ ${!isFromMe ? `<button onclick="markAsRead('${escapeHtml(data.message_id)}', '${escapeHtml(chatId)}', '${escapeHtml(data.sender || '')}')" class="px-2 py-1 bg-blue-500 text-white rounded text-xs hover:bg-blue-600">Mark Read</button>` : ''}+ </div>+ </div>+ `;+ }++ // Format timestamp+ function formatTimestamp(timestamp) {+ if (!timestamp) return 'Unknown time';+ // Handle both ISO 8601 strings and Unix timestamps+ const date = typeof timestamp === 'string' ? new Date(timestamp) : new Date(timestamp * 1000);+ if (isNaN(date.getTime())) return 'Invalid Date';+ return date.toLocaleString();+ }++ // Format sender+ function formatSender(sender) {+ if (!sender) return 'Unknown';+ // Remove @s.whatsapp.net suffix+ return sender.replace('@s.whatsapp.net', '').replace('@c.us', '');+ }++ // Escape HTML+ function escapeHtml(text) {+ const div = document.createElement('div');+ div.textContent = text;+ return div.innerHTML;+ }++ // Clear messages display+ function clearMessages() {+ if (confirm('Clear all displayed messages? (This will not delete them from storage)')) {+ messages = [];+ renderMessages();+ }+ }++ // Format file size+ function formatFileSize(bytes) {+ if (!bytes || bytes === 0) return '0 B';+ const k = 1024;+ const sizes = ['B', 'KB', 'MB', 'GB'];+ const i = Math.floor(Math.log(bytes) / Math.log(k));+ return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i];+ }++ // View media function+ function viewMedia(messageId, mediaType, url) {+ console.log('View media:', messageId, mediaType, url);++ const modal = document.getElementById('media-modal');+ const modalTitle = document.getElementById('media-modal-title');+ const modalContent = document.getElementById('media-modal-content');++ // Show modal+ modal.classList.remove('hidden');++ // Set title+ modalTitle.textContent = `Viewing ${mediaType}`;++ // Show loading+ modalContent.innerHTML = '<p class="text-gray-500">Downloading and decrypting media...</p>';++ // Fetch media via Flask RPC endpoint (returns JSON with base64 data)+ fetch(`/api/media/${messageId}`)+ .then(response => response.json())+ .then(result => {+ if (!result.success) {+ throw new Error(result.error || 'Failed to download media');+ }++ const mediaData = result.data;+ const base64Data = mediaData.data;+ const mimeType = mediaData.mime_type || 'application/octet-stream';++ // Convert base64 to blob+ const byteCharacters = atob(base64Data);+ const byteNumbers = new Array(byteCharacters.length);+ for (let i = 0; i < byteCharacters.length; i++) {+ byteNumbers[i] = byteCharacters.charCodeAt(i);+ }+ const byteArray = new Uint8Array(byteNumbers);+ const blob = new Blob([byteArray], { type: mimeType });+ const blobUrl = URL.createObjectURL(blob);++ if (mediaType === 'image') {+ modalContent.innerHTML = `+ <img src="${blobUrl}" class="max-w-full max-h-full object-contain" alt="WhatsApp Image">+ `;+ } else if (mediaType === 'video') {+ modalContent.innerHTML = `+ <video controls class="max-w-full max-h-full" autoplay>+ <source src="${blobUrl}" type="${mimeType}">+ Your browser does not support the video tag.+ </video>+ `;+ } else if (mediaType === 'audio') {+ modalContent.innerHTML = `+ <audio controls autoplay class="w-full">+ <source src="${blobUrl}" type="${mimeType}">+ Your browser does not support the audio tag.+ </audio>+ `;+ } else {+ modalContent.innerHTML = `+ <div class="text-center">+ <p class="text-gray-600 mb-4">Media loaded successfully</p>+ <a href="${blobUrl}" download class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">+ Download ${mediaType}+ </a>+ </div>+ `;+ }+ })+ .catch(error => {+ console.error('Error loading media:', error);+ modalContent.innerHTML = `+ <div class="text-center text-red-600">+ <p>Failed to load media: ${error.message}</p>+ <p class="text-sm text-gray-500 mt-2">The message may have expired or been deleted.</p>+ </div>+ `;+ });+ }++ // Close media modal+ function closeMediaModal() {+ const modal = document.getElementById('media-modal');+ modal.classList.add('hidden');++ // Clear content to stop videos/audio+ const modalContent = document.getElementById('media-modal-content');+ modalContent.innerHTML = '<p class="text-gray-500">Loading...</p>';+ }++ // Show notification+ function showNotification(message, type = 'info') {+ // Simple console notification for now+ console.log(`[${type.toUpperCase()}] ${message}`);++ // Could add a toast notification here in the future+ }++ // Mark message as read via WebSocket+ function markAsRead(messageId, chatJid, senderJid) {+ console.log('Marking as read:', messageId, chatJid, senderJid);+ socket.emit('mark_read', {+ message_ids: [messageId],+ chat_jid: chatJid,+ sender_jid: senderJid || null+ });+ }++ // Listen for mark_read result+ socket.on('mark_read_result', function(data) {+ if (data.success) {+ showNotification('Message marked as read');+ } else {+ showNotification('Failed to mark as read: ' + data.error, 'error');+ }+ });+</script>+{% endblock %}diff --git a/server/whatsapp-rpc/web/templates/messaging.html b/server/whatsapp-rpc/web/templates/messaging.htmlnew file mode 100644index 00000000..138436ac--- /dev/null+++ b/server/whatsapp-rpc/web/templates/messaging.html@@ -0,0 +1,681 @@+{% extends "base.html" %}+{% block title %}Enhanced Messaging - WhatsApp Controller{% endblock %}++{% block content %}+<div class="space-y-8">+ <!-- Page Header -->+ <div>+ <h1 class="text-3xl font-bold text-gray-900">Enhanced Messaging</h1>+ <p class="text-gray-600 mt-1">Send messages with advanced features: media, location, stickers, contact cards, replies, and more</p>++ <!-- Connection Status Badge -->+ <div id="connection-status" class="mt-3 inline-flex items-center px-4 py-2 rounded-lg">+ <span class="mr-2">Checking connection...</span>+ </div>+ </div>++ <!-- Enhanced Message Composer -->+ <div class="bg-white rounded-lg shadow-md p-6">+ <h2 class="text-xl font-semibold mb-6">Compose Enhanced Message</h2>++ <form id="enhanced-message-form" class="space-y-6">+ <!-- Recipient -->+ <div class="grid grid-cols-1 md:grid-cols-2 gap-4">+ <div>+ <label class="block text-sm font-medium text-gray-700 mb-2">Send To</label>+ <div class="flex space-x-4">+ <label class="flex items-center">+ <input type="radio" name="recipient_type" value="phone" checked class="mr-2">+ <span>Phone Number</span>+ </label>+ <label class="flex items-center">+ <input type="radio" name="recipient_type" value="group" class="mr-2">+ <span>Group</span>+ </label>+ </div>+ </div>+ </div>++ <div class="grid grid-cols-1 md:grid-cols-2 gap-4">+ <div id="phone-input">+ <label class="block text-sm font-medium text-gray-700 mb-2">Phone Number</label>+ <input type="text" id="phone" placeholder="919876543210"+ class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500">+ </div>+ <div id="group-input" class="hidden">+ <label class="block text-sm font-medium text-gray-700 mb-2">Select Group</label>+ <div class="flex space-x-2">+ <select id="group_id" class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500">+ <option value="">-- Select a group --</option>+ </select>+ <button type="button" onclick="loadGroupsDropdown()" class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 whitespace-nowrap">+ Load Groups+ </button>+ </div>+ <p id="groups-status" class="text-xs text-gray-500 mt-1"></p>+ </div>+ </div>++ <!-- Message Type -->+ <div>+ <label class="block text-sm font-medium text-gray-700 mb-2">Message Type</label>+ <select id="message-type" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500">+ <option value="text">Text Message</option>+ <option value="image">Image</option>+ <option value="video">Video</option>+ <option value="audio">Audio</option>+ <option value="document">Document</option>+ <option value="sticker">Sticker</option>+ <option value="location">Location</option>+ <option value="contact">Contact Card</option>+ </select>+ </div>++ <!-- Text Message -->+ <div id="text-section">+ <label class="block text-sm font-medium text-gray-700 mb-2">Message</label>+ <textarea id="message-text" placeholder="Enter your message..."+ rows="4" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500"></textarea>+ </div>++ <!-- Media Section -->+ <div id="media-section" class="hidden space-y-4">+ <div>+ <label class="block text-sm font-medium text-gray-700 mb-2">Select Media File</label>+ <input type="file" id="media-file-input" accept="image/*,video/*,audio/*,.pdf,.doc,.docx"+ class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100">+ <p class="text-sm text-gray-500 mt-1">Choose a file from your computer</p>+ <div id="messaging-file-preview" class="mt-2 hidden">+ <div class="flex items-center gap-2 text-sm text-gray-600 bg-gray-50 p-2 rounded">+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>+ </svg>+ <span id="messaging-file-name">No file selected</span>+ <span id="messaging-file-size" class="text-xs text-gray-500"></span>+ </div>+ </div>+ </div>++ <div>+ <label class="block text-sm font-medium text-gray-700 mb-2">Caption (optional)</label>+ <textarea id="media-caption" placeholder="Enter caption for media..."+ rows="2" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500"></textarea>+ </div>+ </div>++ <!-- Location Section -->+ <div id="location-section" class="hidden space-y-4">+ <div class="grid grid-cols-1 md:grid-cols-2 gap-4">+ <div>+ <label class="block text-sm font-medium text-gray-700 mb-2">Latitude</label>+ <input type="number" id="latitude" step="any" placeholder="19.0760"+ class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500">+ </div>+ <div>+ <label class="block text-sm font-medium text-gray-700 mb-2">Longitude</label>+ <input type="number" id="longitude" step="any" placeholder="72.8777"+ class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500">+ </div>+ </div>+ <div class="grid grid-cols-1 md:grid-cols-2 gap-4">+ <div>+ <label class="block text-sm font-medium text-gray-700 mb-2">Location Name (optional)</label>+ <input type="text" id="location-name" placeholder="Mumbai, India"+ class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500">+ </div>+ <div>+ <label class="block text-sm font-medium text-gray-700 mb-2">Address (optional)</label>+ <input type="text" id="location-address" placeholder="Full address"+ class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500">+ </div>+ </div>+ </div>++ <!-- Contact Card Section -->+ <div id="contact-section" class="hidden space-y-4">+ <div>+ <label class="block text-sm font-medium text-gray-700 mb-2">Display Name</label>+ <input type="text" id="contact-display-name" placeholder="John Doe"+ class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500">+ </div>+ <div>+ <label class="block text-sm font-medium text-gray-700 mb-2">vCard Data</label>+ <textarea id="contact-vcard" placeholder="BEGIN:VCARD VERSION:3.0 FN:John Doe TEL:+1234567890 EMAIL:[email protected] END:VCARD"+ rows="6" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 font-mono text-sm"></textarea>+ <p class="text-sm text-gray-500 mt-1">Enter vCard format contact information</p>+ </div>+ <div class="bg-blue-50 p-4 rounded-lg border border-blue-200">+ <h4 class="font-semibold text-blue-900 mb-2">Quick vCard Template</h4>+ <button type="button" onclick="fillVCardTemplate()" class="text-sm bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700">+ Use Template+ </button>+ </div>+ </div>++ <!-- Reply Section -->+ <div class="border-t pt-6">+ <div class="flex items-center justify-between mb-4">+ <label class="flex items-center">+ <input type="checkbox" id="enable-reply" class="mr-2">+ <span class="font-medium text-gray-700">Reply to Message</span>+ </label>+ </div>++ <div id="reply-section" class="hidden space-y-4 bg-gray-50 p-4 rounded-lg">+ <div class="grid grid-cols-1 md:grid-cols-2 gap-4">+ <div>+ <label class="block text-sm font-medium text-gray-700 mb-2">Original Message ID</label>+ <input type="text" id="reply-message-id" placeholder="Message ID to reply to"+ class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500">+ </div>+ <div>+ <label class="block text-sm font-medium text-gray-700 mb-2">Original Sender</label>+ <input type="text" id="reply-sender" placeholder="Sender JID"+ class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500">+ </div>+ </div>+ <div>+ <label class="block text-sm font-medium text-gray-700 mb-2">Original Message Content</label>+ <textarea id="reply-content" placeholder="Content of the message being replied to"+ rows="2" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500"></textarea>+ </div>+ </div>+ </div>++ <!-- Actions -->+ <div class="flex flex-wrap gap-4 pt-6 border-t">+ <button type="submit" class="bg-green-600 text-white px-6 py-2 rounded-lg hover:bg-green-700 flex items-center">+ <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path>+ </svg>+ Send Enhanced Message+ </button>+ <button type="button" id="send-typing" class="bg-blue-500 text-white px-6 py-2 rounded-lg hover:bg-blue-600 flex items-center">+ <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>+ </svg>+ Send Typing...+ </button>+ <button type="button" id="clear-form" class="bg-gray-600 text-white px-6 py-2 rounded-lg hover:bg-gray-700">+ Clear Form+ </button>+ </div>+ </form>+ </div>++ <!-- Message Status -->+ <div id="message-status" class="hidden">+ <div class="bg-white rounded-lg shadow-md p-6">+ <h2 class="text-xl font-semibold mb-4">Message Status</h2>+ <div id="status-content" class="space-y-2"></div>+ </div>+ </div>+</div>+{% endblock %}++{% block scripts %}+<script>+const mimeTypes = {+ image: ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],+ video: ['video/mp4', 'video/3gpp', 'video/quicktime', 'video/avi'],+ audio: ['audio/mpeg', 'audio/ogg', 'audio/wav', 'audio/aac'],+ document: ['application/pdf', 'text/plain', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']+};++let messagingFileBase64 = null;+let messagingFileName = '';+let messagingFileMimeType = '';++document.addEventListener('DOMContentLoaded', function() {+ // Event listeners+ document.getElementById('enhanced-message-form').addEventListener('submit', sendEnhancedMessage);+ document.getElementById('message-type').addEventListener('change', handleMessageTypeChange);+ document.getElementById('enable-reply').addEventListener('change', toggleReplySection);+ document.getElementById('clear-form').addEventListener('click', clearForm);+ document.getElementById('send-typing').addEventListener('click', sendTypingIndicator);++ // File selection handler+ document.getElementById('media-file-input').addEventListener('change', handleFileSelection);++ // Recipient type change+ document.querySelectorAll('input[name="recipient_type"]').forEach(radio => {+ radio.addEventListener('change', handleRecipientTypeChange);+ });++ // Initialize+ handleMessageTypeChange();++ // Check connection status on load and periodically+ updateConnectionStatus();+ setInterval(updateConnectionStatus, 5000); // Update every 5 seconds++ // Listen for typing result+ socket.on('typing_result', function(data) {+ if (data.success) {+ showStatus('Typing indicator sent', 'success');+ } else {+ showStatus('Failed: ' + data.error, 'error');+ }+ });+});++async function updateConnectionStatus() {+ try {+ const response = await fetch('/api/status');+ const status = await response.json();++ const statusBadge = document.getElementById('connection-status');++ if (status.data && status.data.connected) {+ statusBadge.className = 'mt-3 inline-flex items-center px-4 py-2 rounded-lg bg-green-100 border border-green-300';+ statusBadge.innerHTML = `+ <svg class="w-4 h-4 mr-2 text-green-600" fill="currentColor" viewBox="0 0 20 20">+ <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path>+ </svg>+ <span class="text-green-800 font-medium">WhatsApp Connected</span>+ `;+ } else {+ statusBadge.className = 'mt-3 inline-flex items-center px-4 py-2 rounded-lg bg-red-100 border border-red-300';+ statusBadge.innerHTML = `+ <svg class="w-4 h-4 mr-2 text-red-600" fill="currentColor" viewBox="0 0 20 20">+ <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"></path>+ </svg>+ <span class="text-red-800 font-medium">WhatsApp Not Connected - <a href="/" class="underline">Go to Dashboard</a></span>+ `;+ }+ } catch (error) {+ const statusBadge = document.getElementById('connection-status');+ statusBadge.className = 'mt-3 inline-flex items-center px-4 py-2 rounded-lg bg-yellow-100 border border-yellow-300';+ statusBadge.innerHTML = `+ <svg class="w-4 h-4 mr-2 text-yellow-600" fill="currentColor" viewBox="0 0 20 20">+ <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"></path>+ </svg>+ <span class="text-yellow-800 font-medium">Unable to check connection status</span>+ `;+ }+}++function handleFileSelection(e) {+ const file = e.target.files[0];+ if (!file) {+ messagingFileBase64 = null;+ messagingFileName = '';+ messagingFileMimeType = '';+ document.getElementById('messaging-file-preview').classList.add('hidden');+ return;+ }++ messagingFileName = file.name;+ messagingFileMimeType = file.type;++ // Update preview+ document.getElementById('messaging-file-name').textContent = file.name;+ document.getElementById('messaging-file-size').textContent = formatFileSize(file.size);+ document.getElementById('messaging-file-preview').classList.remove('hidden');++ // Read file as base64+ const reader = new FileReader();+ reader.onload = function(event) {+ messagingFileBase64 = event.target.result.split(',')[1];+ showStatus('File loaded: ' + file.name, 'success');+ };+ reader.onerror = function() {+ showStatus('Failed to read file', 'error');+ messagingFileBase64 = null;+ };+ reader.readAsDataURL(file);+}++function formatFileSize(bytes) {+ if (bytes === 0) return '0 Bytes';+ const k = 1024;+ const sizes = ['Bytes', 'KB', 'MB', 'GB'];+ const i = Math.floor(Math.log(bytes) / Math.log(k));+ return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];+}++function handleRecipientTypeChange() {+ const recipientType = document.querySelector('input[name="recipient_type"]:checked').value;++ if (recipientType === 'phone') {+ document.getElementById('phone-input').classList.remove('hidden');+ document.getElementById('group-input').classList.add('hidden');+ } else {+ document.getElementById('phone-input').classList.add('hidden');+ document.getElementById('group-input').classList.remove('hidden');+ }+}++function handleMessageTypeChange() {+ const messageType = document.getElementById('message-type').value;++ // Hide all sections+ document.getElementById('text-section').classList.add('hidden');+ document.getElementById('media-section').classList.add('hidden');+ document.getElementById('location-section').classList.add('hidden');+ document.getElementById('contact-section').classList.add('hidden');++ // Show relevant section+ if (messageType === 'text') {+ document.getElementById('text-section').classList.remove('hidden');+ } else if (['image', 'video', 'audio', 'document', 'sticker'].includes(messageType)) {+ document.getElementById('media-section').classList.remove('hidden');++ // Update file accept attribute based on type+ const fileInput = document.getElementById('media-file-input');+ if (messageType === 'sticker') {+ fileInput.accept = 'image/webp,image/png';+ } else if (messageType === 'image') {+ fileInput.accept = 'image/*';+ } else if (messageType === 'video') {+ fileInput.accept = 'video/*';+ } else if (messageType === 'audio') {+ fileInput.accept = 'audio/*';+ } else if (messageType === 'document') {+ fileInput.accept = '.pdf,.doc,.docx,.txt,.zip';+ }+ } else if (messageType === 'location') {+ document.getElementById('location-section').classList.remove('hidden');+ } else if (messageType === 'contact') {+ document.getElementById('contact-section').classList.remove('hidden');+ }+}++function toggleReplySection() {+ const enabled = document.getElementById('enable-reply').checked;+ const section = document.getElementById('reply-section');++ if (enabled) {+ section.classList.remove('hidden');+ } else {+ section.classList.add('hidden');+ }+}++async function sendEnhancedMessage(e) {+ e.preventDefault();++ // Check WhatsApp connection status first+ try {+ const statusResponse = await fetch('/api/status');+ const status = await statusResponse.json();++ if (!status.data || !status.data.connected) {+ showStatus('WhatsApp is not connected. Please connect first from the dashboard.', 'error');+ return;+ }+ } catch (error) {+ showStatus('Failed to check connection status. Please try again.', 'error');+ return;+ }++ const messageType = document.getElementById('message-type').value;+ const recipientType = document.querySelector('input[name="recipient_type"]:checked').value;++ // Build message data+ const messageData = {+ type: messageType+ };++ // Set recipient+ if (recipientType === 'phone') {+ messageData.phone = document.getElementById('phone').value.trim();+ } else {+ messageData.group_id = document.getElementById('group_id').value.trim();+ }++ // Add content based on type+ if (messageType === 'text') {+ messageData.message = document.getElementById('message-text').value.trim();+ } else if (['image', 'video', 'audio', 'document', 'sticker'].includes(messageType)) {+ if (!messagingFileBase64) {+ showStatus('Please select a file first', 'error');+ return;+ }++ const caption = document.getElementById('media-caption').value.trim();++ messageData.media_data = {+ data: messagingFileBase64,+ mime_type: messagingFileMimeType,+ filename: messagingFileName,+ caption: caption+ };+ } else if (messageType === 'location') {+ messageData.location = {+ latitude: parseFloat(document.getElementById('latitude').value),+ longitude: parseFloat(document.getElementById('longitude').value),+ name: document.getElementById('location-name').value.trim(),+ address: document.getElementById('location-address').value.trim()+ };+ } else if (messageType === 'contact') {+ const displayName = document.getElementById('contact-display-name').value.trim();+ const vcard = document.getElementById('contact-vcard').value.trim();++ if (!displayName || !vcard) {+ showStatus('Please enter display name and vCard data', 'error');+ return;+ }++ messageData.contact = {+ display_name: displayName,+ vcard: vcard+ };+ }++ // Add reply data if enabled+ if (document.getElementById('enable-reply').checked) {+ messageData.reply = {+ message_id: document.getElementById('reply-message-id').value.trim(),+ sender: document.getElementById('reply-sender').value.trim(),+ content: document.getElementById('reply-content').value.trim()+ };+ }++ try {+ showStatus('Sending message...', 'info');++ const response = await fetch('/api/send/enhanced', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify(messageData)+ });++ const result = await response.json();++ // Clear the "sending" message+ document.getElementById('status-content').innerHTML = '';++ // Show detailed error if available+ if (!result.success) {+ let errorMsg = result.error || 'Unknown error occurred';++ // Provide user-friendly messages for common errors+ if (errorMsg.includes('websocket not connected')) {+ errorMsg = 'WhatsApp connection lost. Please check the dashboard and reconnect.';+ } else if (errorMsg.includes('not connected')) {+ errorMsg = 'WhatsApp is not connected. Please connect first.';+ } else if (errorMsg.includes('invalid')) {+ errorMsg = 'Invalid data provided: ' + errorMsg;+ }++ showMessageStatus({ success: false, error: errorMsg });+ } else {+ showMessageStatus(result);+ // Clear form on success+ clearForm();+ }+ } catch (error) {+ console.error('Error sending message:', error);+ showMessageStatus({+ success: false,+ error: 'Network error: Unable to reach the API server. Please check if services are running.'+ });+ }+}++function clearForm() {+ document.getElementById('enhanced-message-form').reset();+ document.getElementById('enable-reply').checked = false;+ toggleReplySection();+ handleMessageTypeChange();+ handleRecipientTypeChange();+}++function showMessageStatus(result) {+ const statusDiv = document.getElementById('message-status');+ const content = document.getElementById('status-content');++ const timestamp = new Date().toLocaleString();+ const statusClass = result.success ? 'bg-green-50 text-green-800 border-green-200' : 'bg-red-50 text-red-800 border-red-200';++ const statusHtml = `+ <div class="border rounded-lg p-4 ${statusClass}">+ <div class="flex justify-between items-start">+ <div class="flex-1">+ <h3 class="font-semibold">${result.success ? 'Success' : 'Error'}</h3>+ <p class="text-sm mt-1">${result.success ? (result.message || 'Message sent successfully') : result.error}</p>+ <p class="text-xs mt-2 opacity-75">${timestamp}</p>+ </div>+ <button onclick="this.parentElement.parentElement.remove()" class="text-gray-400 hover:text-gray-600">+ <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>+ </svg>+ </button>+ </div>+ </div>+ `;++ content.insertAdjacentHTML('afterbegin', statusHtml);+ statusDiv.classList.remove('hidden');++ // Auto-remove after 10 seconds for success messages+ if (result.success) {+ setTimeout(() => {+ const firstStatus = content.firstElementChild;+ if (firstStatus) {+ firstStatus.remove();+ if (content.children.length === 0) {+ statusDiv.classList.add('hidden');+ }+ }+ }, 10000);+ }+}++function fillVCardTemplate() {+ const template = `BEGIN:VCARD+VERSION:3.0+FN:John Doe+TEL:+1234567890+EMAIL:[email protected]+ORG:Example Company+TITLE:Software Engineer+END:VCARD`;++ document.getElementById('contact-display-name').value = 'John Doe';+ document.getElementById('contact-vcard').value = template;+ showStatus('vCard template filled. Please customize the details.', 'success');+}++async function loadGroupsDropdown() {+ const select = document.getElementById('group_id');+ const status = document.getElementById('groups-status');++ status.textContent = 'Loading groups...';+ status.className = 'text-xs text-blue-500 mt-1';++ try {+ const response = await fetch('/api/groups');+ const data = await response.json();++ if (data.success && data.data) {+ const groups = data.data;+ select.innerHTML = '<option value="">-- Select a group --</option>';++ groups.forEach(group => {+ const option = document.createElement('option');+ option.value = group.jid;+ option.textContent = `${group.name} (${group.size} members)`;+ select.appendChild(option);+ });++ status.textContent = `${groups.length} groups loaded`;+ status.className = 'text-xs text-green-600 mt-1';+ } else {+ status.textContent = data.error || 'Failed to load groups';+ status.className = 'text-xs text-red-500 mt-1';+ }+ } catch (error) {+ status.textContent = 'Error: ' + error.message;+ status.className = 'text-xs text-red-500 mt-1';+ }+}++function showStatus(message, type) {+ if (type === 'info') {+ // Show info message differently+ const statusDiv = document.getElementById('message-status');+ const content = document.getElementById('status-content');++ const statusHtml = `+ <div class="border rounded-lg p-4 bg-blue-50 text-blue-800 border-blue-200">+ <div class="flex items-center">+ <svg class="w-5 h-5 mr-2 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>+ </svg>+ <span>${message}</span>+ </div>+ </div>+ `;++ content.innerHTML = statusHtml;+ statusDiv.classList.remove('hidden');+ } else {+ showMessageStatus({+ success: type === 'success',+ message: type === 'success' ? message : null,+ error: type === 'error' ? message : null+ });+ }+}++function sendTypingIndicator() {+ const recipientType = document.querySelector('input[name="recipient_type"]:checked').value;+ let jid;++ if (recipientType === 'phone') {+ const phone = document.getElementById('phone').value.trim();+ if (!phone) {+ showStatus('Please enter a phone number first', 'error');+ return;+ }+ jid = phone + '@s.whatsapp.net';+ } else {+ jid = document.getElementById('group_id').value.trim();+ if (!jid) {+ showStatus('Please select a group first', 'error');+ return;+ }+ }++ // Send typing indicator via WebSocket+ socket.emit('typing', {+ jid: jid,+ state: 'composing'+ });++ showStatus('Sending typing indicator...', 'info');++ // Auto-stop typing after 5 seconds+ setTimeout(() => {+ socket.emit('typing', {+ jid: jid,+ state: 'paused'+ });+ }, 5000);+}+</script>+{% endblock %}\ No newline at end of filediff --git a/server/whatsapp-rpc/web/templates/send.html b/server/whatsapp-rpc/web/templates/send.htmlnew file mode 100644index 00000000..48b0c79b--- /dev/null+++ b/server/whatsapp-rpc/web/templates/send.html@@ -0,0 +1,259 @@+{% extends "base.html" %}++{% block title %}Send Message - WhatsApp Controller{% endblock %}++{% block content %}+<div class="max-w-2xl mx-auto">+ <div class="bg-white rounded-lg shadow-md p-6">+ <h1 class="text-2xl font-semibold mb-6 flex items-center">+ <svg class="w-8 h-8 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path>+ </svg>+ Send WhatsApp Message+ </h1>++ <form method="POST" class="space-y-6">+ <!-- Phone Number Input -->+ <div>+ <label for="phone" class="block text-sm font-medium text-gray-700 mb-2">+ Phone Number+ </label>+ <div class="relative">+ <input type="text"+ id="phone"+ name="phone"+ placeholder="e.g., 1234567890"+ required+ class="w-full border border-gray-300 rounded-lg px-4 py-3 focus:ring-2 focus:ring-green-500 focus:border-transparent">+ <div class="absolute inset-y-0 right-0 pr-3 flex items-center">+ <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"></path>+ </svg>+ </div>+ </div>+ <p class="text-sm text-gray-600 mt-1">+ Enter phone number with country code (without + sign)+ </p>+ </div>++ <!-- Message Input -->+ <div>+ <label for="message" class="block text-sm font-medium text-gray-700 mb-2">+ Message+ </label>+ <textarea id="message"+ name="message"+ rows="6"+ placeholder="Enter your message here..."+ required+ class="w-full border border-gray-300 rounded-lg px-4 py-3 focus:ring-2 focus:ring-green-500 focus:border-transparent"></textarea>+ <div class="flex justify-between items-center mt-1">+ <p class="text-sm text-gray-600">+ Type your WhatsApp message+ </p>+ <span id="char-count" class="text-sm text-gray-500">0 characters</span>+ </div>+ </div>++ <!-- Action Buttons -->+ <div class="flex space-x-4">+ <button type="submit"+ id="send-btn"+ class="flex-1 bg-green-600 text-white py-3 px-6 rounded-lg hover:bg-green-700 transition font-medium flex items-center justify-center">+ <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path>+ </svg>+ Send Message+ </button>++ <button type="button"+ onclick="clearForm()"+ class="px-6 py-3 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition font-medium">+ Clear+ </button>+ </div>+ </form>++ <!-- Connection Status Warning -->+ <div id="connection-warning" class="mt-6 hidden">+ <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">+ <div class="flex">+ <svg class="w-5 h-5 text-yellow-400 mr-3" fill="currentColor" viewBox="0 0 20 20">+ <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"></path>+ </svg>+ <div>+ <h3 class="text-sm font-medium text-yellow-800">WhatsApp Not Connected</h3>+ <p class="text-sm text-yellow-700 mt-1">+ Please start WhatsApp service from the <a href="{{ url_for('index') }}" class="underline">dashboard</a> before sending messages.+ </p>+ </div>+ </div>+ </div>+ </div>+ </div>++ <!-- Recent Messages -->+ <div class="bg-white rounded-lg shadow-md p-6 mt-6">+ <h2 class="text-lg font-semibold mb-4">Recent Messages</h2>+ <div id="recent-messages" class="space-y-3">+ <p class="text-gray-600">No recent messages</p>+ </div>+ </div>+</div>+{% endblock %}++{% block scripts %}+<script>+ let recentMessages = JSON.parse(localStorage.getItem('recentMessages') || '[]');++ // Character counter+ document.getElementById('message').addEventListener('input', function(e) {+ const count = e.target.value.length;+ document.getElementById('char-count').textContent = `${count} characters`;+ });++ // Form submission+ document.querySelector('form').addEventListener('submit', function(e) {+ e.preventDefault();++ const phone = document.getElementById('phone').value.trim();+ const message = document.getElementById('message').value.trim();+ const sendBtn = document.getElementById('send-btn');++ if (!phone || !message) {+ alert('Please fill in both phone number and message');+ return;+ }++ // Disable button and show loading+ sendBtn.disabled = true;+ sendBtn.innerHTML = `+ <svg class="w-5 h-5 mr-2 animate-spin" fill="none" viewBox="0 0 24 24">+ <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>+ <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>+ </svg>+ Sending...+ `;++ fetch('/api/send', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ phone, message })+ })+ .then(response => response.json())+ .then(data => {+ if (data.success) {+ // Add to recent messages+ addRecentMessage(phone, message, 'sent');++ // Clear message field+ document.getElementById('message').value = '';+ document.getElementById('char-count').textContent = '0 characters';++ // Show success message+ showNotification('Message sent successfully!', 'success');+ } else {+ showNotification(`Failed to send message: ${data.error}`, 'error');+ }+ })+ .catch(error => {+ showNotification(`Error: ${error.message}`, 'error');+ })+ .finally(() => {+ // Re-enable button+ sendBtn.disabled = false;+ sendBtn.innerHTML = `+ <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path>+ </svg>+ Send Message+ `;+ });+ });++ function clearForm() {+ document.getElementById('phone').value = '';+ document.getElementById('message').value = '';+ document.getElementById('char-count').textContent = '0 characters';+ }++ function addRecentMessage(phone, message, status) {+ const messageObj = {+ phone,+ message: message.substring(0, 100) + (message.length > 100 ? '...' : ''),+ status,+ timestamp: new Date().toLocaleString()+ };++ recentMessages.unshift(messageObj);+ if (recentMessages.length > 5) {+ recentMessages = recentMessages.slice(0, 5);+ }++ localStorage.setItem('recentMessages', JSON.stringify(recentMessages));+ renderRecentMessages();+ }++ function renderRecentMessages() {+ const container = document.getElementById('recent-messages');++ if (recentMessages.length === 0) {+ container.innerHTML = '<p class="text-gray-600">No recent messages</p>';+ return;+ }++ container.innerHTML = recentMessages.map(msg => `+ <div class="border rounded-lg p-3 bg-gray-50">+ <div class="flex justify-between items-start mb-2">+ <span class="font-medium text-gray-900">${msg.phone}</span>+ <span class="text-xs text-gray-500">${msg.timestamp}</span>+ </div>+ <p class="text-gray-700 text-sm">${msg.message}</p>+ <span class="inline-block mt-2 px-2 py-1 text-xs rounded-full ${+ msg.status === 'sent' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'+ }">${msg.status}</span>+ </div>+ `).join('');+ }++ function showNotification(message, type) {+ // Create notification element+ const notification = document.createElement('div');+ notification.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 ${+ type === 'success' ? 'bg-green-500 text-white' : 'bg-red-500 text-white'+ }`;+ notification.textContent = message;++ document.body.appendChild(notification);++ // Remove after 3 seconds+ setTimeout(() => {+ notification.remove();+ }, 3000);+ }++ // Check connection status and show warning if needed+ function checkConnectionStatus() {+ fetch('/api/status')+ .then(response => response.json())+ .then(data => {+ const warning = document.getElementById('connection-warning');+ if (data.success && data.data && !data.data.connected) {+ warning.classList.remove('hidden');+ } else {+ warning.classList.add('hidden');+ }+ })+ .catch(() => {+ document.getElementById('connection-warning').classList.remove('hidden');+ });+ }++ // Initialize+ renderRecentMessages();+ checkConnectionStatus();++ // Check status periodically+ setInterval(checkConnectionStatus, 30000);+</script>+{% endblock %}\ No newline at end of filediff --git a/server/whatsapp-rpc/web/templates/settings.html b/server/whatsapp-rpc/web/templates/settings.htmlnew file mode 100644index 00000000..65535dbb--- /dev/null+++ b/server/whatsapp-rpc/web/templates/settings.html@@ -0,0 +1,459 @@+{% extends "base.html" %}++{% block title %}Settings - WhatsApp Controller{% endblock %}++{% block content %}+<div class="space-y-6">+ <!-- Page Header -->+ <div class="flex items-center justify-between">+ <div>+ <h1 class="text-2xl font-bold text-gray-900">Settings</h1>+ <p class="text-gray-600">Configure rate limiting and anti-ban protection</p>+ </div>+ <button id="refresh-stats" class="bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700 flex items-center">+ <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>+ </svg>+ Refresh+ </button>+ </div>++ <!-- Status Alert -->+ <div id="status-alert" class="hidden"></div>++ <!-- Stats Cards -->+ <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">+ <!-- Messages Last Minute -->+ <div class="bg-white rounded-lg shadow p-6">+ <div class="flex items-center">+ <div class="p-3 rounded-full bg-blue-100 text-blue-600">+ <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"></path>+ </svg>+ </div>+ <div class="ml-4">+ <p class="text-sm text-gray-500">Messages/Min</p>+ <p class="text-2xl font-semibold text-gray-900"><span id="stat-messages-minute">-</span><span class="text-sm text-gray-400" id="stat-messages-minute-limit"></span></p>+ </div>+ </div>+ </div>++ <!-- Messages Last Hour -->+ <div class="bg-white rounded-lg shadow p-6">+ <div class="flex items-center">+ <div class="p-3 rounded-full bg-green-100 text-green-600">+ <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>+ </svg>+ </div>+ <div class="ml-4">+ <p class="text-sm text-gray-500">Messages/Hour</p>+ <p class="text-2xl font-semibold text-gray-900"><span id="stat-messages-hour">-</span><span class="text-sm text-gray-400" id="stat-messages-hour-limit"></span></p>+ </div>+ </div>+ </div>++ <!-- New Contacts Today -->+ <div class="bg-white rounded-lg shadow p-6">+ <div class="flex items-center">+ <div class="p-3 rounded-full bg-purple-100 text-purple-600">+ <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z"></path>+ </svg>+ </div>+ <div class="ml-4">+ <p class="text-sm text-gray-500">New Contacts Today</p>+ <p class="text-2xl font-semibold text-gray-900"><span id="stat-new-contacts">-</span><span class="text-sm text-gray-400" id="stat-new-contacts-limit"></span></p>+ </div>+ </div>+ </div>++ <!-- Response Rate -->+ <div class="bg-white rounded-lg shadow p-6">+ <div class="flex items-center">+ <div class="p-3 rounded-full bg-yellow-100 text-yellow-600">+ <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>+ </svg>+ </div>+ <div class="ml-4">+ <p class="text-sm text-gray-500">Response Rate</p>+ <p class="text-2xl font-semibold text-gray-900"><span id="stat-response-rate">-</span>%</p>+ </div>+ </div>+ </div>+ </div>++ <!-- Pause Status -->+ <div id="pause-alert" class="hidden bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-lg">+ <div class="flex items-center justify-between">+ <div class="flex items-center">+ <svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">+ <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd"></path>+ </svg>+ <span><strong>Rate Limiting Paused:</strong> <span id="pause-reason"></span></span>+ </div>+ <button id="unpause-btn" class="bg-red-600 text-white px-4 py-1 rounded hover:bg-red-700">+ Unpause+ </button>+ </div>+ </div>++ <!-- Configuration Section -->+ <div class="bg-white rounded-lg shadow">+ <div class="px-6 py-4 border-b border-gray-200">+ <h2 class="text-lg font-semibold text-gray-900">Rate Limiting Configuration</h2>+ <p class="text-sm text-gray-500">Configure delays and limits to avoid WhatsApp detection and bans</p>+ </div>++ <form id="config-form" class="p-6 space-y-6">+ <!-- Enable/Disable -->+ <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">+ <div>+ <h3 class="font-medium text-gray-900">Enable Rate Limiting</h3>+ <p class="text-sm text-gray-500">Master switch for all rate limiting features</p>+ </div>+ <label class="relative inline-flex items-center cursor-pointer">+ <input type="checkbox" id="config-enabled" class="sr-only peer" checked>+ <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-green-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-green-600"></div>+ </label>+ </div>++ <!-- Delays Section -->+ <div class="border-t pt-6">+ <h3 class="text-md font-medium text-gray-900 mb-4">Message Delays (milliseconds)</h3>+ <div class="grid grid-cols-1 md:grid-cols-2 gap-6">+ <div>+ <label class="block text-sm font-medium text-gray-700 mb-1">Minimum Delay</label>+ <input type="number" id="config-min-delay" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500" min="0" step="100">+ <p class="text-xs text-gray-500 mt-1">Minimum time between messages (default: 3000ms)</p>+ </div>+ <div>+ <label class="block text-sm font-medium text-gray-700 mb-1">Maximum Delay</label>+ <input type="number" id="config-max-delay" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500" min="0" step="100">+ <p class="text-xs text-gray-500 mt-1">Maximum for randomization (default: 8000ms)</p>+ </div>+ <div>+ <label class="block text-sm font-medium text-gray-700 mb-1">Typing Indicator Duration</label>+ <input type="number" id="config-typing-delay" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500" min="0" step="100">+ <p class="text-xs text-gray-500 mt-1">How long to show typing (default: 2000ms)</p>+ </div>+ <div>+ <label class="block text-sm font-medium text-gray-700 mb-1">Extra Delay for Links</label>+ <input type="number" id="config-link-delay" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500" min="0" step="100">+ <p class="text-xs text-gray-500 mt-1">Additional delay for messages with URLs (default: 5000ms)</p>+ </div>+ </div>+ </div>++ <!-- Rate Limits Section -->+ <div class="border-t pt-6">+ <h3 class="text-md font-medium text-gray-900 mb-4">Rate Limits</h3>+ <div class="grid grid-cols-1 md:grid-cols-3 gap-6">+ <div>+ <label class="block text-sm font-medium text-gray-700 mb-1">Messages per Minute</label>+ <input type="number" id="config-per-minute" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500" min="0">+ <p class="text-xs text-gray-500 mt-1">0 = unlimited (default: 10)</p>+ </div>+ <div>+ <label class="block text-sm font-medium text-gray-700 mb-1">Messages per Hour</label>+ <input type="number" id="config-per-hour" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500" min="0">+ <p class="text-xs text-gray-500 mt-1">0 = unlimited (default: 60)</p>+ </div>+ <div>+ <label class="block text-sm font-medium text-gray-700 mb-1">New Contacts per Day</label>+ <input type="number" id="config-new-contacts" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500" min="0">+ <p class="text-xs text-gray-500 mt-1">Critical for new accounts (default: 20)</p>+ </div>+ </div>+ </div>++ <!-- Human Simulation Section -->+ <div class="border-t pt-6">+ <h3 class="text-md font-medium text-gray-900 mb-4">Human Simulation</h3>+ <div class="grid grid-cols-1 md:grid-cols-2 gap-6">+ <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">+ <div>+ <h4 class="font-medium text-gray-900">Simulate Typing</h4>+ <p class="text-sm text-gray-500">Send typing indicator before messages</p>+ </div>+ <label class="relative inline-flex items-center cursor-pointer">+ <input type="checkbox" id="config-simulate-typing" class="sr-only peer">+ <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-green-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-green-600"></div>+ </label>+ </div>+ <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">+ <div>+ <h4 class="font-medium text-gray-900">Randomize Delays</h4>+ <p class="text-sm text-gray-500">Add random variance to avoid patterns</p>+ </div>+ <label class="relative inline-flex items-center cursor-pointer">+ <input type="checkbox" id="config-randomize" class="sr-only peer">+ <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-green-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-green-600"></div>+ </label>+ </div>+ </div>+ </div>++ <!-- Safety Section -->+ <div class="border-t pt-6">+ <h3 class="text-md font-medium text-gray-900 mb-4">Safety Settings</h3>+ <div class="grid grid-cols-1 md:grid-cols-2 gap-6">+ <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">+ <div>+ <h4 class="font-medium text-gray-900">Pause on Low Response</h4>+ <p class="text-sm text-gray-500">Auto-pause if response rate drops too low</p>+ </div>+ <label class="relative inline-flex items-center cursor-pointer">+ <input type="checkbox" id="config-pause-low-response" class="sr-only peer">+ <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-green-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-green-600"></div>+ </label>+ </div>+ <div>+ <label class="block text-sm font-medium text-gray-700 mb-1">Response Rate Threshold</label>+ <div class="flex items-center">+ <input type="number" id="config-response-threshold" class="w-24 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500" min="0" max="100" step="5">+ <span class="ml-2 text-gray-500">%</span>+ </div>+ <p class="text-xs text-gray-500 mt-1">Minimum acceptable response rate (default: 30%)</p>+ </div>+ </div>+ </div>++ <!-- Actions -->+ <div class="border-t pt-6 flex justify-between items-center">+ <button type="button" id="reset-defaults" class="text-gray-600 hover:text-gray-800">+ Reset to Defaults+ </button>+ <div class="flex gap-4">+ <button type="button" id="cancel-changes" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">+ Cancel+ </button>+ <button type="submit" class="bg-green-600 text-white px-6 py-2 rounded-lg hover:bg-green-700">+ Save Configuration+ </button>+ </div>+ </div>+ </form>+ </div>++ <!-- Info Cards -->+ <div class="grid grid-cols-1 md:grid-cols-2 gap-6">+ <!-- Tips Card -->+ <div class="bg-blue-50 border border-blue-200 rounded-lg p-6">+ <h3 class="font-semibold text-blue-800 mb-3">Anti-Ban Tips</h3>+ <ul class="text-sm text-blue-700 space-y-2">+ <li>- First 10 days have highest ban risk for new numbers</li>+ <li>- Keep new contacts under 20/day for new accounts</li>+ <li>- Always enable typing simulation</li>+ <li>- Use randomized delays to avoid patterns</li>+ <li>- Messages with links need extra delay for preview generation</li>+ <li>- Monitor response rate - low rates may indicate blocked messages</li>+ </ul>+ </div>++ <!-- Current Time Info -->+ <div class="bg-gray-50 border border-gray-200 rounded-lg p-6">+ <h3 class="font-semibold text-gray-800 mb-3">Timing Information</h3>+ <div class="text-sm text-gray-600 space-y-2">+ <p><strong>Last Message:</strong> <span id="info-last-message">-</span></p>+ <p><strong>Next Allowed:</strong> <span id="info-next-allowed">-</span></p>+ <p><strong>Messages Today:</strong> <span id="info-messages-today">-</span></p>+ <p><strong>Responses Received:</strong> <span id="info-responses">-</span></p>+ </div>+ </div>+ </div>+</div>+{% endblock %}++{% block scripts %}+<script>+let currentConfig = {};+let currentStats = {};++document.addEventListener('DOMContentLoaded', function() {+ // Load initial data+ loadRateLimitData();++ // Event listeners+ document.getElementById('refresh-stats').addEventListener('click', loadRateLimitData);+ document.getElementById('config-form').addEventListener('submit', saveConfiguration);+ document.getElementById('unpause-btn').addEventListener('click', unpauseRateLimiting);+ document.getElementById('reset-defaults').addEventListener('click', resetToDefaults);+ document.getElementById('cancel-changes').addEventListener('click', loadRateLimitData);++ // Auto-refresh every 10 seconds+ setInterval(loadStats, 10000);+});++async function loadRateLimitData() {+ try {+ const response = await fetch('/api/rate-limit');+ const result = await response.json();++ if (result.success) {+ currentConfig = result.data.config;+ currentStats = result.data.stats;+ updateUI();+ } else {+ showAlert('Failed to load rate limit data: ' + result.error, 'error');+ }+ } catch (error) {+ showAlert('Error loading rate limit data: ' + error.message, 'error');+ }+}++async function loadStats() {+ try {+ const response = await fetch('/api/rate-limit/stats');+ const result = await response.json();++ if (result.success) {+ currentStats = result.data;+ updateStats();+ }+ } catch (error) {+ console.error('Error loading stats:', error);+ }+}++function updateUI() {+ updateStats();+ updateConfigForm();+}++function updateStats() {+ // Stats cards+ document.getElementById('stat-messages-minute').textContent = currentStats.messages_sent_last_minute || 0;+ document.getElementById('stat-messages-minute-limit').textContent = currentConfig.max_messages_per_minute ? ` / ${currentConfig.max_messages_per_minute}` : '';++ document.getElementById('stat-messages-hour').textContent = currentStats.messages_sent_last_hour || 0;+ document.getElementById('stat-messages-hour-limit').textContent = currentConfig.max_messages_per_hour ? ` / ${currentConfig.max_messages_per_hour}` : '';++ document.getElementById('stat-new-contacts').textContent = currentStats.new_contacts_today || 0;+ document.getElementById('stat-new-contacts-limit').textContent = currentConfig.max_new_contacts_per_day ? ` / ${currentConfig.max_new_contacts_per_day}` : '';++ document.getElementById('stat-response-rate').textContent = ((currentStats.response_rate || 0) * 100).toFixed(1);++ // Pause status+ const pauseAlert = document.getElementById('pause-alert');+ if (currentStats.is_paused) {+ pauseAlert.classList.remove('hidden');+ document.getElementById('pause-reason').textContent = currentStats.pause_reason || 'Unknown reason';+ } else {+ pauseAlert.classList.add('hidden');+ }++ // Timing info+ document.getElementById('info-last-message').textContent = currentStats.last_message_time ? formatTime(currentStats.last_message_time) : 'Never';+ document.getElementById('info-next-allowed').textContent = currentStats.next_allowed_time ? formatTime(currentStats.next_allowed_time) : '-';+ document.getElementById('info-messages-today').textContent = currentStats.messages_sent_today || 0;+ document.getElementById('info-responses').textContent = currentStats.responses_received || 0;+}++function updateConfigForm() {+ document.getElementById('config-enabled').checked = currentConfig.enabled !== false;+ document.getElementById('config-min-delay').value = currentConfig.min_delay_ms || 3000;+ document.getElementById('config-max-delay').value = currentConfig.max_delay_ms || 8000;+ document.getElementById('config-typing-delay').value = currentConfig.typing_delay_ms || 2000;+ document.getElementById('config-link-delay').value = currentConfig.link_extra_delay_ms || 5000;+ document.getElementById('config-per-minute').value = currentConfig.max_messages_per_minute || 10;+ document.getElementById('config-per-hour').value = currentConfig.max_messages_per_hour || 60;+ document.getElementById('config-new-contacts').value = currentConfig.max_new_contacts_per_day || 20;+ document.getElementById('config-simulate-typing').checked = currentConfig.simulate_typing !== false;+ document.getElementById('config-randomize').checked = currentConfig.randomize_delays !== false;+ document.getElementById('config-pause-low-response').checked = currentConfig.pause_on_low_response === true;+ document.getElementById('config-response-threshold').value = (currentConfig.response_rate_threshold || 0.3) * 100;+}++async function saveConfiguration(e) {+ e.preventDefault();++ const config = {+ enabled: document.getElementById('config-enabled').checked,+ min_delay_ms: parseInt(document.getElementById('config-min-delay').value) || 3000,+ max_delay_ms: parseInt(document.getElementById('config-max-delay').value) || 8000,+ typing_delay_ms: parseInt(document.getElementById('config-typing-delay').value) || 2000,+ link_extra_delay_ms: parseInt(document.getElementById('config-link-delay').value) || 5000,+ max_messages_per_minute: parseInt(document.getElementById('config-per-minute').value) || 0,+ max_messages_per_hour: parseInt(document.getElementById('config-per-hour').value) || 0,+ max_new_contacts_per_day: parseInt(document.getElementById('config-new-contacts').value) || 0,+ simulate_typing: document.getElementById('config-simulate-typing').checked,+ randomize_delays: document.getElementById('config-randomize').checked,+ pause_on_low_response: document.getElementById('config-pause-low-response').checked,+ response_rate_threshold: (parseInt(document.getElementById('config-response-threshold').value) || 30) / 100+ };++ try {+ const response = await fetch('/api/rate-limit', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(config)+ });++ const result = await response.json();++ if (result.success) {+ currentConfig = result.data.config;+ showAlert('Configuration saved successfully', 'success');+ updateUI();+ } else {+ showAlert('Failed to save configuration: ' + result.error, 'error');+ }+ } catch (error) {+ showAlert('Error saving configuration: ' + error.message, 'error');+ }+}++async function unpauseRateLimiting() {+ try {+ const response = await fetch('/api/rate-limit/unpause', { method: 'POST' });+ const result = await response.json();++ if (result.success) {+ currentStats = result.data.stats;+ showAlert('Rate limiting unpaused', 'success');+ updateStats();+ } else {+ showAlert('Failed to unpause: ' + result.error, 'error');+ }+ } catch (error) {+ showAlert('Error unpausing: ' + error.message, 'error');+ }+}++function resetToDefaults() {+ document.getElementById('config-enabled').checked = true;+ document.getElementById('config-min-delay').value = 3000;+ document.getElementById('config-max-delay').value = 8000;+ document.getElementById('config-typing-delay').value = 2000;+ document.getElementById('config-link-delay').value = 5000;+ document.getElementById('config-per-minute').value = 10;+ document.getElementById('config-per-hour').value = 60;+ document.getElementById('config-new-contacts').value = 20;+ document.getElementById('config-simulate-typing').checked = true;+ document.getElementById('config-randomize').checked = true;+ document.getElementById('config-pause-low-response').checked = false;+ document.getElementById('config-response-threshold').value = 30;+}++function formatTime(isoString) {+ if (!isoString || isoString === '0001-01-01T00:00:00Z') return 'Never';+ const date = new Date(isoString);+ if (isNaN(date.getTime())) return '-';+ return date.toLocaleTimeString();+}++function showAlert(message, type) {+ const alertDiv = document.getElementById('status-alert');+ const bgColor = type === 'success' ? 'bg-green-100 border-green-400 text-green-700' : 'bg-red-100 border-red-400 text-red-700';+ alertDiv.className = `${bgColor} border px-4 py-3 rounded-lg mb-4`;+ alertDiv.textContent = message;+ alertDiv.classList.remove('hidden');++ setTimeout(() => {+ alertDiv.classList.add('hidden');+ }, 5000);+}+</script>+{% endblock %}diff --git a/tests/android/check_android_errors.py b/tests/android/check_android_errors.pynew file mode 100644index 00000000..fc82b8a3--- /dev/null+++ b/tests/android/check_android_errors.py@@ -0,0 +1,62 @@+#!/usr/bin/env python3+"""Check Android service responses for errors"""++import requests+import json++API_URL = "http://localhost:3010/api/workflow/execute-node"++SERVICES = [+ ("batteryMonitor", "battery", "status"),+ ("networkMonitor", "network", "status"),+ ("systemInfo", "system_info", "status"),+ ("location", "location", "status"),+ ("appLauncher", "app_launcher", "launch"),+ ("appList", "app_list", "status"),+ ("wifiAutomation", "wifi_automation", "status"),+ ("bluetoothAutomation", "bluetooth_automation", "status"),+ ("audioAutomation", "audio_automation", "status"),+ ("deviceStateAutomation", "device_state_automation", "status"),+ ("screenControlAutomation", "screen_control_automation", "status"),+ ("airplaneModeControl", "airplane_mode_control", "status"),+ ("motionDetection", "motion_detection", "status"),+ ("environmentalSensors", "environmental_sensors", "status"),+ ("cameraControl", "camera_control", "status"),+ ("mediaControl", "media_control", "status"),+]++errors_found = []++for node_type, service_id, action in SERVICES:+ payload = {+ "node_id": f"check-{node_type}",+ "node_type": node_type,+ "parameters": {+ "service_id": service_id,+ "action": action+ }+ }++ response = requests.post(API_URL, json=payload)+ result = response.json()++ # Check if there's an error in the data+ if result.get('success') and result.get('result'):+ data = result['result'].get('data', {})+ if 'error' in data:+ errors_found.append({+ 'node_type': node_type,+ 'service_id': service_id,+ 'action': action,+ 'error': data['error']+ })+ print(f"ERROR in {node_type} ({service_id}/{action}):")+ print(f" {data['error']}")+ print()++if errors_found:+ print(f"\nFound {len(errors_found)} services with errors:")+ for err in errors_found:+ print(f" - {err['node_type']}: {err['error']}")+else:+ print("\nNo errors found in any service responses!")diff --git a/tests/android/test_android_nodes.py b/tests/android/test_android_nodes.pynew file mode 100644index 00000000..8ea8b8ac--- /dev/null+++ b/tests/android/test_android_nodes.py@@ -0,0 +1,141 @@+#!/usr/bin/env python3+"""+Android Service Nodes Integration Test+Tests all 16 individual Android service nodes+"""++import requests+import json+import time+from typing import Dict, Any++API_URL = "http://localhost:3010/api/workflow/execute-node"++# Service definitions: (node_type, service_id, action, category)+SERVICES = [+ # System Monitoring (4)+ ("batteryMonitor", "battery", "status", "System Monitoring"),+ ("networkMonitor", "network", "status", "System Monitoring"),+ ("systemInfo", "system_info", "info", "System Monitoring"), # Fixed: info not status+ ("location", "location", "current", "System Monitoring"), # Fixed: current not status++ # App Management (2)+ ("appLauncher", "app_launcher", "launch", "App Management"),+ ("appList", "app_list", "list", "App Management"), # Fixed: list not status++ # Device Automation (6)+ ("wifiAutomation", "wifi_automation", "status", "Device Automation"),+ ("bluetoothAutomation", "bluetooth_automation", "status", "Device Automation"),+ ("audioAutomation", "audio_automation", "get_volume", "Device Automation"), # Fixed: get_volume+ ("deviceStateAutomation", "device_state_automation", "status", "Device Automation"),+ ("screenControlAutomation", "screen_control_automation", "status", "Device Automation"),+ ("airplaneModeControl", "airplane_mode_control", "status", "Device Automation"),++ # Sensors (2)+ ("motionDetection", "motion_detection", "current_motion", "Sensors"), # Fixed: current_motion+ ("environmentalSensors", "environmental_sensors", "ambient_conditions", "Sensors"), # Fixed: ambient_conditions++ # Media (2)+ ("cameraControl", "camera_control", "camera_info", "Media"), # Fixed: camera_info+ ("mediaControl", "media_control", "volume_control", "Media"), # Fixed: volume_control+]++def test_service(node_type: str, service_id: str, action: str) -> Dict[str, Any]:+ """Test a single Android service node"""+ node_id = f"{node_type}-test-{int(time.time()*1000)}"++ payload = {+ "node_id": node_id,+ "node_type": node_type,+ "parameters": {+ "service_id": service_id,+ "android_host": "localhost",+ "android_port": 8888,+ "action": action,+ "parameters": "{}"+ }+ }++ try:+ response = requests.post(API_URL, json=payload, timeout=10)+ result = response.json()++ success = result.get("success", False)+ exec_time = result.get("execution_time", 0)++ # Check if it's actually calling Android API (not generic execution)+ is_real_call = exec_time > 0.01 # Real Android calls take >10ms++ return {+ "passed": success and is_real_call,+ "exec_time": exec_time,+ "response": result+ }+ except Exception as e:+ return {+ "passed": False,+ "exec_time": 0,+ "error": str(e)+ }++def main():+ print("=" * 60)+ print("Android Service Nodes Integration Test")+ print("=" * 60)+ print()++ results = []+ current_category = None++ for node_type, service_id, action, category in SERVICES:+ # Print category header+ if category != current_category:+ if current_category is not None:+ print()+ print(f"\n{category} ({sum(1 for _, _, _, c in SERVICES if c == category)} nodes)")+ print("-" * 60)+ current_category = category++ print(f"Testing {node_type:25s} ({service_id}/{action})... ", end="", flush=True)++ result = test_service(node_type, service_id, action)+ results.append((node_type, result))++ if result["passed"]:+ exec_time = result["exec_time"]+ print(f"PASS ({exec_time:.3f}s)")+ else:+ exec_time = result.get("exec_time", 0)+ error = result.get("error", "Unknown error")+ print(f"FAIL ({exec_time:.3f}s) - {error}")++ # Summary+ print()+ print("=" * 60)+ print("Test Summary")+ print("=" * 60)++ passed = sum(1 for _, r in results if r["passed"])+ failed = len(results) - passed++ print(f"PASSED: {passed}/16")+ print(f"FAILED: {failed}/16")+ print()++ if failed > 0:+ print("Failed services:")+ for node_type, result in results:+ if not result["passed"]:+ error = result.get("error", "Low execution time")+ print(f" - {node_type}: {error}")+ print()++ if failed == 0:+ print("All Android service nodes working correctly!")+ return 0+ else:+ print(f"{failed} service(s) failed. Check Android device connection.")+ return 1++if __name__ == "__main__":+ exit(main())diff --git a/tests/android/test_android_service_remote.py b/tests/android/test_android_service_remote.pynew file mode 100644index 00000000..0e44dc29--- /dev/null+++ b/tests/android/test_android_service_remote.py@@ -0,0 +1,212 @@+#!/usr/bin/env python3+"""+Test Android Service Nodes with Remote WebSocket Connection+Tests that Android service nodes use WebSocket when remote device is configured+"""+import requests+import json+import time+import os++def test_android_device_setup():+ """Step 1: Setup remote Android device connection"""+ print("=" * 60)+ print("Step 1: Android Device Setup (Remote WebSocket)")+ print("=" * 60)++ url = "http://localhost:3010/api/nodes/execute"+ payload = {+ "nodeId": "android_device_001",+ "nodeType": "androidDeviceSetup",+ "parameters": {+ "connection_type": "remote",+ "websocket_url": os.getenv('WEBSOCKET_URL', ''),+ "port": 8888+ },+ "inputs": {},+ "workflow": {"nodes": [], "edges": []}+ }++ try:+ response = requests.post(url, json=payload, timeout=10)++ if response.status_code == 200:+ result = response.json()+ if result.get('success'):+ print("\nDevice Setup: SUCCESS")+ print(f" Connection Type: {result['result'].get('connection_type')}")+ print(f" WebSocket URL: {result['result'].get('websocket_url')}")+ print(f" Client ID: {result['result'].get('client_id')}")+ print(f" Status: {result['result'].get('status')}")+ return True+ else:+ print(f"\nDevice Setup: FAILED - {result.get('error')}")+ return False+ else:+ print(f"\nDevice Setup: HTTP {response.status_code}")+ return False++ except Exception as e:+ print(f"\nDevice Setup: ERROR - {e}")+ return False+++def test_battery_monitor_service():+ """Step 2: Test Battery Monitor service via WebSocket"""+ print("\n" + "=" * 60)+ print("Step 2: Battery Monitor Service (via WebSocket)")+ print("=" * 60)++ url = "http://localhost:3010/api/nodes/execute"+ payload = {+ "nodeId": "battery_node_001",+ "nodeType": "batteryMonitor",+ "parameters": {+ "service_id": "battery",+ "action": "status",+ "parameters": {}+ },+ "inputs": {},+ "workflow": {"nodes": [], "edges": []}+ }++ try:+ response = requests.post(url, json=payload, timeout=15)++ if response.status_code == 200:+ result = response.json()+ print(f"\nResponse:")+ print(json.dumps(result, indent=2))++ if result.get('success'):+ service_result = result.get('result', {})+ data = service_result.get('data', {})++ print("\nBattery Monitor: SUCCESS")+ print(f" Connection Type: {service_result.get('connection_type')}")+ print(f" Battery Level: {data.get('level')}%")+ print(f" Charging: {data.get('charging')}")+ print(f" Temperature: {data.get('temperature')}°C")+ print(f" Health: {data.get('health')}")++ if service_result.get('connection_type') == 'remote_websocket':+ print("\n[OK] Service used WebSocket connection!")+ return True+ else:+ print("\n[ERROR] Service did NOT use WebSocket connection")+ return False+ else:+ print(f"\nBattery Monitor: FAILED - {result.get('error')}")+ return False+ else:+ print(f"\nBattery Monitor: HTTP {response.status_code}")+ print(response.text)+ return False++ except Exception as e:+ print(f"\nBattery Monitor: ERROR - {e}")+ import traceback+ traceback.print_exc()+ return False+++def test_location_service():+ """Step 3: Test Location service via WebSocket"""+ print("\n" + "=" * 60)+ print("Step 3: Location Service (via WebSocket)")+ print("=" * 60)++ url = "http://localhost:3010/api/nodes/execute"+ payload = {+ "nodeId": "location_node_001",+ "nodeType": "location",+ "parameters": {+ "service_id": "location",+ "action": "current",+ "parameters": {}+ },+ "inputs": {},+ "workflow": {"nodes": [], "edges": []}+ }++ try:+ response = requests.post(url, json=payload, timeout=15)++ if response.status_code == 200:+ result = response.json()++ if result.get('success'):+ service_result = result.get('result', {})+ data = service_result.get('data', {})++ print("\nLocation Service: SUCCESS")+ print(f" Connection Type: {service_result.get('connection_type')}")+ print(f" Latitude: {data.get('latitude')}")+ print(f" Longitude: {data.get('longitude')}")+ print(f" Accuracy: {data.get('accuracy')}m")+ print(f" Provider: {data.get('provider')}")++ if service_result.get('connection_type') == 'remote_websocket':+ print("\n[OK] Service used WebSocket connection!")+ return True+ else:+ print("\n[ERROR] Service did NOT use WebSocket connection")+ return False+ else:+ print(f"\nLocation Service: FAILED - {result.get('error')}")+ return False+ else:+ print(f"\nLocation Service: HTTP {response.status_code}")+ return False++ except Exception as e:+ print(f"\nLocation Service: ERROR - {e}")+ import traceback+ traceback.print_exc()+ return False+++if __name__ == "__main__":+ print("\n" + "=" * 60)+ print("Android Service Remote WebSocket Test")+ print("=" * 60)+ print("\nPrerequisite: Android device simulator must be running")+ print("Run: python test_android_simulator.py\n")++ time.sleep(2)++ # Test sequence+ results = []++ # Step 1: Setup remote connection+ results.append(("Device Setup", test_android_device_setup()))++ if results[0][1]:+ # Give WebSocket time to stabilize+ time.sleep(1)++ # Step 2: Test battery service+ results.append(("Battery Monitor", test_battery_monitor_service()))++ # Step 3: Test location service+ results.append(("Location Service", test_location_service()))+ else:+ print("\n[ERROR] Skipping service tests due to setup failure")++ # Summary+ print("\n" + "=" * 60)+ print("Test Summary")+ print("=" * 60)+ for test_name, passed in results:+ status = "PASSED" if passed else "FAILED"+ print(f" {test_name}: {status}")++ all_passed = all(result[1] for result in results)+ print("\n" + "=" * 60)+ if all_passed:+ print("All Tests PASSED!")+ else:+ print("Some Tests FAILED!")+ print("=" * 60)++ exit(0 if all_passed else 1)diff --git a/tests/android/test_android_service_request.py b/tests/android/test_android_service_request.pynew file mode 100644index 00000000..cde32051--- /dev/null+++ b/tests/android/test_android_service_request.py@@ -0,0 +1,131 @@+#!/usr/bin/env python3+"""+Test Android Service Request-Response Pattern+Demonstrates how Android device only responds to specific service requests++Before running: export WEBSOCKET_API_KEY=your-key+"""+import asyncio+import json+import os+import sys+import aiohttp+from aiohttp import ClientWSTimeout++# Load from environment - NO FALLBACK+WEBSOCKET_API_KEY = os.getenv('WEBSOCKET_API_KEY')+WEBSOCKET_URL = os.getenv('WEBSOCKET_URL', '')++if not WEBSOCKET_API_KEY:+ print("ERROR: WEBSOCKET_API_KEY environment variable not set")+ print("Usage: WEBSOCKET_API_KEY=your-key python test_android_service_request.py")+ sys.exit(1)++async def test_service_request():+ """Test requesting specific services from Android device"""++ print("=" * 60)+ print("Android Service Request-Response Test")+ print("=" * 60)++ # Configuration+ url = WEBSOCKET_URL+ web_api_key = WEBSOCKET_API_KEY+ web_client_id = "test_web_requester"++ # Connect as Web client+ print("\n[Web Client] Connecting...")+ session = aiohttp.ClientSession()+ ws = await session.ws_connect(url, timeout=ClientWSTimeout(ws_close=10.0))++ # Wait for welcome+ msg = await asyncio.wait_for(ws.receive(), timeout=5.0)+ welcome = json.loads(msg.data)+ print(f"[Web Client] {welcome.get('message')}")++ # Register+ await ws.send_json({+ "type": "register",+ "clientType": "web",+ "clientId": web_client_id,+ "apiKey": web_api_key+ })++ msg = await asyncio.wait_for(ws.receive(), timeout=5.0)+ register_response = json.loads(msg.data)+ print(f"[Web Client] Registered: {register_response.get('type')}")++ # Request battery status from Android device+ print("\n[Web Client] Requesting battery status from Android device...")+ await ws.send_json({+ "type": "data",+ "payload": {+ "action": "get_battery_status",+ "service": "batteryMonitor"+ }+ })++ # Wait for response from Android+ print("[Web Client] Waiting for Android response...")+ try:+ msg = await asyncio.wait_for(ws.receive(), timeout=10.0)+ if msg.type == aiohttp.WSMsgType.TEXT:+ response = json.loads(msg.data)+ print(f"\n[Web Client] Received response:")+ print(json.dumps(response, indent=2))++ if response.get('type') == 'data':+ payload = response.get('payload', {})+ data = payload.get('data', {})+ print(f"\n[Android Response]")+ print(f" Service: {payload.get('service')}")+ print(f" Battery Level: {data.get('level')}%")+ print(f" Charging: {data.get('charging')}")+ print(f" Temperature: {data.get('temperature')}°C")+ print(f" Health: {data.get('health')}")+ except asyncio.TimeoutError:+ print("[Web Client] No response from Android device (timeout)")+ print("Make sure Android simulator is running")++ # Request location data+ print("\n[Web Client] Requesting location from Android device...")+ await ws.send_json({+ "type": "data",+ "payload": {+ "action": "get_location",+ "service": "location"+ }+ })++ # Wait for response+ print("[Web Client] Waiting for Android response...")+ try:+ msg = await asyncio.wait_for(ws.receive(), timeout=10.0)+ if msg.type == aiohttp.WSMsgType.TEXT:+ response = json.loads(msg.data)++ if response.get('type') == 'data':+ payload = response.get('payload', {})+ data = payload.get('data', {})+ print(f"\n[Android Response]")+ print(f" Service: {payload.get('service')}")+ print(f" Latitude: {data.get('latitude')}")+ print(f" Longitude: {data.get('longitude')}")+ print(f" Accuracy: {data.get('accuracy')}m")+ print(f" Provider: {data.get('provider')}")+ except asyncio.TimeoutError:+ print("[Web Client] No response from Android device (timeout)")++ # Disconnect+ await ws.close()+ await session.close()++ print("\n" + "=" * 60)+ print("Test Complete")+ print("=" * 60)++if __name__ == "__main__":+ try:+ asyncio.run(test_service_request())+ except KeyboardInterrupt:+ print("\n\nTest stopped by user")diff --git a/tests/android/test_android_simulator.py b/tests/android/test_android_simulator.pynew file mode 100644index 00000000..69910cde--- /dev/null+++ b/tests/android/test_android_simulator.py@@ -0,0 +1,524 @@+#!/usr/bin/env python3+"""+Simulated Android Device - Sends dummy data through WebSocket+Simulates battery, location, and other sensor data++Required environment variables:+ WEBSOCKET_URL - WebSocket server URL (required)+ ANDROID_API_KEY - API key for WebSocket authentication+"""+import asyncio+import json+import os+import aiohttp+from aiohttp import ClientWSTimeout+from datetime import datetime+import random++class AndroidDeviceSimulator:+ """Simulates an Android device sending sensor data"""++ def __init__(self, url: str, api_key: str, device_id: str):+ self.url = url+ self.api_key = api_key+ self.device_id = device_id+ self.ws = None+ self.session = None+ self.running = False++ async def connect(self):+ """Connect to WebSocket and register"""+ print(f"[ANDROID DEVICE] Connecting to {self.url}")++ self.session = aiohttp.ClientSession()+ self.ws = await self.session.ws_connect(+ self.url,+ timeout=ClientWSTimeout(ws_close=10.0)+ )++ # Wait for welcome+ msg = await asyncio.wait_for(self.ws.receive(), timeout=5.0)+ welcome = json.loads(msg.data)+ print(f"[ANDROID DEVICE] {welcome.get('message')}")++ # Register as Android device+ register_msg = {+ "type": "register",+ "clientType": "android",+ "clientId": self.device_id,+ "apiKey": self.api_key+ }+ await self.ws.send_json(register_msg)+ print(f"[ANDROID DEVICE] Sent registration")++ # Wait for registration response+ msg = await asyncio.wait_for(self.ws.receive(), timeout=5.0)+ reg_response = json.loads(msg.data)++ if reg_response.get('type') == 'registered':+ print(f"[ANDROID DEVICE] Registered as: {reg_response.get('clientId')}")+ self.running = True+ return True+ else:+ print(f"[ANDROID DEVICE] Registration failed: {reg_response}")+ return False++ async def send_battery_status(self):+ """Send battery status data"""+ battery_level = random.randint(20, 100)+ charging = random.choice([True, False])+ temperature = round(random.uniform(25.0, 45.0), 1)++ data = {+ "type": "data",+ "payload": {+ "service": "battery",+ "action": "status",+ "data": {+ "level": battery_level,+ "charging": charging,+ "temperature": temperature,+ "voltage": round(random.uniform(3.7, 4.2), 2),+ "health": "good",+ "technology": "Li-ion"+ },+ "timestamp": datetime.now().isoformat()+ }+ }++ await self.ws.send_json(data)+ print(f"[ANDROID DEVICE] Sent battery status: {battery_level}% {'(charging)' if charging else ''} {temperature}°C")++ async def send_location_data(self):+ """Send GPS location data"""+ # Simulate location in San Francisco area+ lat = round(37.7749 + random.uniform(-0.1, 0.1), 6)+ lng = round(-122.4194 + random.uniform(-0.1, 0.1), 6)+ accuracy = round(random.uniform(5.0, 20.0), 1)++ data = {+ "type": "data",+ "payload": {+ "service": "location",+ "action": "get_location",+ "data": {+ "latitude": lat,+ "longitude": lng,+ "accuracy": accuracy,+ "altitude": round(random.uniform(0, 100), 1),+ "provider": "gps",+ "speed": round(random.uniform(0, 5), 1)+ },+ "timestamp": datetime.now().isoformat()+ }+ }++ await self.ws.send_json(data)+ print(f"[ANDROID DEVICE] Sent location: {lat}, {lng} (±{accuracy}m)")++ async def send_system_info(self):+ """Send system information"""+ data = {+ "type": "data",+ "payload": {+ "service": "system_info",+ "action": "get_info",+ "data": {+ "android_version": "14",+ "api_level": 34,+ "device_model": "Pixel 8",+ "manufacturer": "Google",+ "total_memory": 8192,+ "available_memory": random.randint(2000, 5000),+ "storage_total": 128000,+ "storage_available": random.randint(40000, 80000)+ },+ "timestamp": datetime.now().isoformat()+ }+ }++ await self.ws.send_json(data)+ print(f"[ANDROID DEVICE] Sent system info: Pixel 8, Android 14")++ async def send_network_status(self):+ """Send network status"""+ network_type = random.choice(["WIFI", "MOBILE"])+ data = {+ "type": "data",+ "payload": {+ "service": "network",+ "action": "get_status",+ "data": {+ "connected": True,+ "type": network_type,+ "internet_available": True,+ "wifi_ssid": "Home-WiFi" if network_type == "WIFI" else None,+ "signal_strength": random.randint(1, 5)+ },+ "timestamp": datetime.now().isoformat()+ }+ }++ await self.ws.send_json(data)+ print(f"[ANDROID DEVICE] Sent network status: {network_type}")++ async def send_app_list(self):+ """Send list of installed applications"""+ apps = [+ {"package": "com.google.android.gms", "name": "Google Play Services", "version": "23.45.12"},+ {"package": "com.android.chrome", "name": "Chrome", "version": "120.0.6099"},+ {"package": "com.whatsapp", "name": "WhatsApp", "version": "2.23.24.9"},+ {"package": "com.spotify.music", "name": "Spotify", "version": "8.8.94.527"},+ {"package": "com.instagram.android", "name": "Instagram", "version": "308.0.0.38.112"}+ ]++ data = {+ "type": "data",+ "payload": {+ "service": "app_list",+ "action": "get_apps",+ "data": {+ "apps": apps,+ "total_count": len(apps)+ },+ "timestamp": datetime.now().isoformat()+ }+ }++ await self.ws.send_json(data)+ print(f"[ANDROID DEVICE] Sent app list: {len(apps)} apps")++ async def send_wifi_status(self):+ """Send WiFi automation status"""+ enabled = random.choice([True, False])+ data = {+ "type": "data",+ "payload": {+ "service": "wifi_automation",+ "action": "get_status",+ "data": {+ "enabled": enabled,+ "connected": enabled,+ "ssid": "Home-WiFi" if enabled else None,+ "ip_address": f"192.168.1.{random.randint(100, 200)}" if enabled else None,+ "signal_strength": random.randint(-70, -30) if enabled else None+ },+ "timestamp": datetime.now().isoformat()+ }+ }++ await self.ws.send_json(data)+ print(f"[ANDROID DEVICE] Sent WiFi status: {'enabled' if enabled else 'disabled'}")++ async def send_bluetooth_status(self):+ """Send Bluetooth automation status"""+ enabled = random.choice([True, False])+ paired_devices = [+ {"name": "AirPods Pro", "address": "00:1A:7D:DA:71:13", "connected": True},+ {"name": "Car Bluetooth", "address": "F8:16:54:A6:01:28", "connected": False}+ ] if enabled else []++ data = {+ "type": "data",+ "payload": {+ "service": "bluetooth_automation",+ "action": "get_status",+ "data": {+ "enabled": enabled,+ "paired_devices": paired_devices,+ "connected_devices": [d for d in paired_devices if d.get("connected")]+ },+ "timestamp": datetime.now().isoformat()+ }+ }++ await self.ws.send_json(data)+ print(f"[ANDROID DEVICE] Sent Bluetooth status: {'enabled' if enabled else 'disabled'}")++ async def send_audio_status(self):+ """Send audio automation status"""+ data = {+ "type": "data",+ "payload": {+ "service": "audio_automation",+ "action": "get_volume",+ "data": {+ "music_volume": random.randint(0, 15),+ "ring_volume": random.randint(0, 7),+ "alarm_volume": random.randint(0, 7),+ "notification_volume": random.randint(0, 7),+ "muted": random.choice([True, False])+ },+ "timestamp": datetime.now().isoformat()+ }+ }++ await self.ws.send_json(data)+ print(f"[ANDROID DEVICE] Sent audio status")++ async def send_device_state(self):+ """Send device state automation status"""+ data = {+ "type": "data",+ "payload": {+ "service": "device_state_automation",+ "action": "get_state",+ "data": {+ "airplane_mode": random.choice([True, False]),+ "screen_on": random.choice([True, False]),+ "power_save_mode": random.choice([True, False]),+ "brightness": random.randint(0, 255),+ "auto_brightness": random.choice([True, False])+ },+ "timestamp": datetime.now().isoformat()+ }+ }++ await self.ws.send_json(data)+ print(f"[ANDROID DEVICE] Sent device state")++ async def send_screen_control(self):+ """Send screen control status"""+ data = {+ "type": "data",+ "payload": {+ "service": "screen_control_automation",+ "action": "get_brightness",+ "data": {+ "brightness": random.randint(0, 255),+ "auto_brightness": random.choice([True, False]),+ "screen_timeout": random.choice([15000, 30000, 60000, 300000]),+ "screen_on": random.choice([True, False])+ },+ "timestamp": datetime.now().isoformat()+ }+ }++ await self.ws.send_json(data)+ print(f"[ANDROID DEVICE] Sent screen control status")++ async def send_motion_data(self):+ """Send motion detection sensor data"""+ data = {+ "type": "data",+ "payload": {+ "service": "motion_detection",+ "action": "get_sensors",+ "data": {+ "accelerometer": {+ "x": round(random.uniform(-10, 10), 3),+ "y": round(random.uniform(-10, 10), 3),+ "z": round(random.uniform(-10, 10), 3)+ },+ "gyroscope": {+ "x": round(random.uniform(-2, 2), 3),+ "y": round(random.uniform(-2, 2), 3),+ "z": round(random.uniform(-2, 2), 3)+ },+ "orientation": random.choice(["portrait", "landscape"]),+ "motion_detected": random.choice([True, False])+ },+ "timestamp": datetime.now().isoformat()+ }+ }++ await self.ws.send_json(data)+ print(f"[ANDROID DEVICE] Sent motion sensor data")++ async def send_environmental_sensors(self):+ """Send environmental sensor data"""+ data = {+ "type": "data",+ "payload": {+ "service": "environmental_sensors",+ "action": "get_sensors",+ "data": {+ "temperature": round(random.uniform(20.0, 30.0), 1),+ "humidity": round(random.uniform(30.0, 70.0), 1),+ "pressure": round(random.uniform(990.0, 1020.0), 1),+ "light_level": random.randint(0, 50000)+ },+ "timestamp": datetime.now().isoformat()+ }+ }++ await self.ws.send_json(data)+ print(f"[ANDROID DEVICE] Sent environmental sensor data")++ async def send_camera_info(self):+ """Send camera control info"""+ data = {+ "type": "data",+ "payload": {+ "service": "camera_control",+ "action": "get_info",+ "data": {+ "camera_count": 3,+ "cameras": [+ {"id": 0, "facing": "back", "megapixels": 50},+ {"id": 1, "facing": "front", "megapixels": 12},+ {"id": 2, "facing": "back", "megapixels": 12, "type": "ultrawide"}+ ],+ "flash_available": True+ },+ "timestamp": datetime.now().isoformat()+ }+ }++ await self.ws.send_json(data)+ print(f"[ANDROID DEVICE] Sent camera info")++ async def send_media_control_status(self):+ """Send media control status"""+ data = {+ "type": "data",+ "payload": {+ "service": "media_control",+ "action": "get_status",+ "data": {+ "playing": random.choice([True, False]),+ "track": "Shape of You - Ed Sheeran",+ "duration": 233000,+ "position": random.randint(0, 233000),+ "volume": random.randint(0, 100)+ },+ "timestamp": datetime.now().isoformat()+ }+ }++ await self.ws.send_json(data)+ print(f"[ANDROID DEVICE] Sent media control status")++ async def listen_for_commands(self):+ """Listen for commands from Web clients"""+ while self.running:+ try:+ msg = await asyncio.wait_for(self.ws.receive(), timeout=2.0)++ if msg.type == aiohttp.WSMsgType.TEXT:+ data = json.loads(msg.data)++ if data.get('type') == 'data':+ payload = data.get('payload', {})+ action = payload.get('action')+ service = payload.get('service')++ print(f"\n[ANDROID DEVICE] Received command: {service}/{action}")++ # Respond based on service and action+ # Official service IDs from androidServiceNodes.ts+ if service == 'battery':+ await self.send_battery_status()+ elif service == 'location':+ await self.send_location_data()+ elif service == 'system_info':+ await self.send_system_info()+ elif service == 'network':+ await self.send_network_status()+ elif service == 'app_list':+ await self.send_app_list()+ elif service == 'app_launcher':+ await self.send_app_list()+ elif service == 'wifi_automation':+ await self.send_wifi_status()+ elif service == 'bluetooth_automation':+ await self.send_bluetooth_status()+ elif service == 'audio_automation':+ await self.send_audio_status()+ elif service == 'device_state_automation':+ await self.send_device_state()+ elif service == 'screen_control_automation':+ await self.send_screen_control()+ elif service == 'airplane_mode_control':+ await self.send_device_state()+ elif service == 'motion_detection':+ await self.send_motion_data()+ elif service == 'environmental_sensors':+ await self.send_environmental_sensors()+ elif service == 'camera_control':+ await self.send_camera_info()+ elif service == 'media_control':+ await self.send_media_control_status()+ else:+ print(f"[ANDROID DEVICE] Unknown service/action: {service}/{action}")++ elif msg.type == aiohttp.WSMsgType.CLOSED:+ print("[ANDROID DEVICE] Connection closed")+ self.running = False+ break++ except asyncio.TimeoutError:+ # No message, continue listening+ continue+ except Exception as e:+ print(f"[ANDROID DEVICE] Error: {e}")+ break++ async def run_service(self):+ """Run as background service - only responds to requests"""+ print("\n[ANDROID DEVICE] Service started")+ print("[ANDROID DEVICE] Simulating all 17 Android service nodes")+ print("[ANDROID DEVICE] Listening for commands - will only send data when requested")+ print("[ANDROID DEVICE] Press Ctrl+C to stop\n")++ try:+ # Run command listener indefinitely+ await self.listen_for_commands()++ except KeyboardInterrupt:+ print("\n[ANDROID DEVICE] Service stopped by user")+ self.running = False++ async def disconnect(self):+ """Disconnect from WebSocket"""+ if self.ws:+ await self.ws.close()+ print("[ANDROID DEVICE] Disconnected")+ if self.session:+ await self.session.close()+++async def main():+ print("=" * 60)+ print("Android Device Simulator - Background Service")+ print("Responds to Android service requests via WebSocket")+ print("=" * 60)++ # Configuration from environment variables+ url = os.getenv("WEBSOCKET_URL")+ android_api_key = os.getenv("ANDROID_API_KEY")++ if not url:+ print("[ERROR] WEBSOCKET_URL environment variable is required")+ print("[ERROR] Set it with: export WEBSOCKET_URL=ws://your-server/ws")+ return++ if not android_api_key:+ print("[ERROR] ANDROID_API_KEY environment variable is required")+ print("[ERROR] Set it with: export ANDROID_API_KEY=your-api-key")+ return+ device_id = f"android_pixel8_{int(datetime.now().timestamp())}"++ # Create simulator+ simulator = AndroidDeviceSimulator(url, android_api_key, device_id)++ # Connect+ if await simulator.connect():+ # Run as background service (runs indefinitely until Ctrl+C)+ await simulator.run_service()+ else:+ print("[ANDROID DEVICE] Failed to connect")++ # Disconnect+ await simulator.disconnect()++ print("\n" + "=" * 60)+ print("Service Stopped")+ print("=" * 60)+++if __name__ == "__main__":+ try:+ asyncio.run(main())+ except KeyboardInterrupt:+ print("\n\nService stopped by user")diff --git a/tests/fixtures/test_battery.json b/tests/fixtures/test_battery.jsonnew file mode 100644index 00000000..60df73c7--- /dev/null+++ b/tests/fixtures/test_battery.json@@ -0,0 +1,10 @@+{+ "node_id": "battery_1",+ "node_type": "batteryMonitor",+ "parameters": {+ "service_id": "battery",+ "action": "status",+ "parameters": {}+ },+ "connected_nodes": {}+}diff --git a/tests/fixtures/test_config.json b/tests/fixtures/test_config.jsonnew file mode 100644index 00000000..23db2df8--- /dev/null+++ b/tests/fixtures/test_config.json@@ -0,0 +1,10 @@+{+ "node_id": "test_setup",+ "node_type": "androidDeviceSetup",+ "parameters": {+ "connection_type": "remote",+ "websocket_url": "",+ "port": 8888+ },+ "connected_nodes": {}+}diff --git a/tests/fixtures/test_setup.json b/tests/fixtures/test_setup.jsonnew file mode 100644index 00000000..829a3fd9--- /dev/null+++ b/tests/fixtures/test_setup.json@@ -0,0 +1,10 @@+{+ "node_id": "setup_1",+ "node_type": "androidDeviceSetup",+ "parameters": {+ "connection_type": "remote",+ "websocket_url": "",+ "port": 8888+ },+ "connected_nodes": {}+}diff --git a/tests/websocket/test_websocket.py b/tests/websocket/test_websocket.pynew file mode 100644index 00000000..3b753a54--- /dev/null+++ b/tests/websocket/test_websocket.py@@ -0,0 +1,348 @@+#!/usr/bin/env python3+"""+Test WebSocket connection for remote Android devices++Before running, set environment variables:+ export WEBSOCKET_API_KEY=your-web-api-key+ export ANDROID_API_KEY=your-android-api-key (optional, for bidirectional test)+ export WEBSOCKET_URL=ws://your-relay-server.com/ws+"""+import asyncio+import json+import os+import sys+import aiohttp++# Load from environment - NO FALLBACK+WEBSOCKET_API_KEY = os.getenv('WEBSOCKET_API_KEY')+ANDROID_API_KEY = os.getenv('ANDROID_API_KEY')+WEBSOCKET_URL = os.getenv('WEBSOCKET_URL', '')++if not WEBSOCKET_API_KEY:+ print("ERROR: WEBSOCKET_API_KEY environment variable not set")+ print("Usage: WEBSOCKET_API_KEY=your-key python test_websocket.py")+ sys.exit(1)++async def test_health_endpoint():+ """Test the WebSocket health endpoint"""+ base = WEBSOCKET_URL.replace('ws://', 'http://').replace('wss://', 'https://').rstrip('/ws')+ url = f"{base}/ws-health"+ print(f"\nTesting health endpoint: {url}")++ try:+ async with aiohttp.ClientSession() as session:+ async with session.get(url, timeout=10) as response:+ print(f"Status: {response.status}")+ content = await response.text()+ print(f"Response: {content}")++ if response.status == 200:+ print("Health check: PASSED")+ return True+ else:+ print("Health check: FAILED")+ return False+ except Exception as e:+ print(f"Health check error: {e}")+ return False++async def test_stats_endpoint():+ """Test the WebSocket stats endpoint"""+ base = WEBSOCKET_URL.replace('ws://', 'http://').replace('wss://', 'https://').rstrip('/ws')+ url = f"{base}/ws-stats"+ print(f"\nTesting stats endpoint: {url}")++ try:+ async with aiohttp.ClientSession() as session:+ async with session.get(url, timeout=10) as response:+ print(f"Status: {response.status}")+ content = await response.text()+ print(f"Response: {content}")++ if response.status == 200:+ print("Stats check: PASSED")+ return True+ else:+ print("Stats check: FAILED")+ return False+ except Exception as e:+ print(f"Stats check error: {e}")+ return False++async def test_websocket_connection():+ """Test WebSocket connection with API key authentication"""+ url = WEBSOCKET_URL+ web_api_key = WEBSOCKET_API_KEY++ print(f"\nTesting WebSocket connection: {url}")+ print(f"Using Web API Key: {web_api_key[:20]}...")++ try:+ async with aiohttp.ClientSession() as session:+ async with session.ws_connect(url, timeout=10) as ws:+ print("WebSocket connection: ESTABLISHED")++ # Wait for initial "connected" message+ try:+ msg = await asyncio.wait_for(ws.receive(), timeout=5.0)+ if msg.type == aiohttp.WSMsgType.TEXT:+ data = json.loads(msg.data)+ print(f"Received welcome: {data}")++ if data.get('type') != 'connected':+ print("Unexpected welcome message")+ return False+ except asyncio.TimeoutError:+ print("No welcome message received")+ return False++ # Now send registration with API key+ register_message = {+ "type": "register",+ "clientType": "web",+ "clientId": "test_client_001",+ "apiKey": web_api_key+ }+ await ws.send_json(register_message)+ print(f"Sent registration: {register_message}")++ # Wait for registration response+ try:+ msg = await asyncio.wait_for(ws.receive(), timeout=5.0)+ print(f"Received: {msg.data}")++ if msg.type == aiohttp.WSMsgType.TEXT:+ data = json.loads(msg.data)+ print(f"Parsed response: {data}")++ if data.get('type') == 'registered':+ print("Registration: SUCCESS")+ print(f"Client ID: {data.get('clientId')}")++ # Test sending data message+ data_message = {+ "type": "data",+ "payload": {+ "action": "test",+ "timestamp": asyncio.get_event_loop().time()+ }+ }+ await ws.send_json(data_message)+ print(f"Sent data message: {data_message}")++ # Wait for any response (timeout is expected if no Android client)+ try:+ msg2 = await asyncio.wait_for(ws.receive(), timeout=3.0)+ if msg2.type == aiohttp.WSMsgType.TEXT:+ response = json.loads(msg2.data)+ print(f"Response to data: {response}")+ except asyncio.TimeoutError:+ print("No response to data message (expected - no Android clients)")++ # Test ping/pong+ ping_message = {"type": "ping"}+ await ws.send_json(ping_message)+ print(f"Sent ping: {ping_message}")++ try:+ msg3 = await asyncio.wait_for(ws.receive(), timeout=3.0)+ if msg3.type == aiohttp.WSMsgType.TEXT:+ pong = json.loads(msg3.data)+ print(f"Received pong: {pong}")+ if pong.get('type') == 'pong':+ print("Ping/Pong: SUCCESS")+ except asyncio.TimeoutError:+ print("No pong response")++ print("WebSocket test: PASSED")+ return True+ elif data.get('type') == 'error':+ print(f"Registration FAILED: {data.get('message')}")+ print("WebSocket test: FAILED")+ return False++ except asyncio.TimeoutError:+ print("No registration response received (timeout)")+ print("WebSocket test: FAILED")+ return False++ except aiohttp.ClientConnectorError as e:+ print(f"Connection error: {e}")+ return False+ except Exception as e:+ print(f"WebSocket error: {e}")+ import traceback+ traceback.print_exc()+ return False++async def test_android_to_web_flow():+ """Test Android -> WebSocket -> Web bidirectional data flow"""+ url = WEBSOCKET_URL+ web_api_key = WEBSOCKET_API_KEY+ android_api_key = ANDROID_API_KEY++ if not android_api_key:+ print(f"\nSkipping Android -> WebSocket -> Web bidirectional flow test")+ print("ANDROID_API_KEY not set in environment")+ return True # Don't fail, just skip++ print(f"\nTesting Android -> WebSocket -> Web bidirectional flow")+ print("=" * 60)++ try:+ async with aiohttp.ClientSession() as session:+ # Step 1: Connect Web client+ print("\n[WEB] Connecting...")+ web_ws = await session.ws_connect(url, timeout=10)+ msg = await asyncio.wait_for(web_ws.receive(), timeout=5.0)+ print(f"[WEB] {json.loads(msg.data).get('message')}")++ # Register Web client+ await web_ws.send_json({+ "type": "register",+ "clientType": "web",+ "clientId": "test_web_001",+ "apiKey": web_api_key+ })++ msg = await asyncio.wait_for(web_ws.receive(), timeout=5.0)+ web_reg = json.loads(msg.data)+ if web_reg.get('type') != 'registered':+ print(f"[WEB] Registration FAILED: {web_reg}")+ return False+ print(f"[WEB] Registered as: {web_reg.get('clientId')}")++ # Step 2: Connect Android client+ print("\n[ANDROID] Connecting...")+ android_ws = await session.ws_connect(url, timeout=10)+ msg = await asyncio.wait_for(android_ws.receive(), timeout=5.0)+ print(f"[ANDROID] {json.loads(msg.data).get('message')}")++ # Register Android client+ await android_ws.send_json({+ "type": "register",+ "clientType": "android",+ "clientId": "test_android_001",+ "apiKey": android_api_key+ })++ msg = await asyncio.wait_for(android_ws.receive(), timeout=5.0)+ android_reg = json.loads(msg.data)+ if android_reg.get('type') != 'registered':+ print(f"[ANDROID] Registration FAILED: {android_reg}")+ return False+ print(f"[ANDROID] Registered as: {android_reg.get('clientId')}")++ # Web should receive join notification+ try:+ msg = await asyncio.wait_for(web_ws.receive(), timeout=3.0)+ notif = json.loads(msg.data)+ if notif.get('type') == 'client_joined':+ print(f"[WEB] Notification: Android client {notif.get('clientId')} joined")+ except asyncio.TimeoutError:+ pass++ # Step 3: Android sends battery data broadcast+ print("\n[ANDROID] Broadcasting battery status...")+ await android_ws.send_json({+ "type": "data",+ "payload": {+ "service": "battery",+ "level": 85,+ "charging": True+ }+ })++ msg = await asyncio.wait_for(web_ws.receive(), timeout=5.0)+ data = json.loads(msg.data)+ if data.get('type') == 'data' and data.get('fromType') == 'android':+ print(f"[WEB] Received from Android: {data.get('payload')}")+ else:+ print(f"[WEB] Unexpected message: {data}")+ return False++ # Step 4: Web sends targeted command to Android+ print("\n[WEB] Sending targeted command to Android...")+ await web_ws.send_json({+ "type": "data",+ "targetId": "test_android_001",+ "payload": {"action": "get_location"}+ })++ msg = await asyncio.wait_for(android_ws.receive(), timeout=5.0)+ cmd = json.loads(msg.data)+ if cmd.get('type') == 'data' and cmd.get('fromType') == 'web':+ print(f"[ANDROID] Received command: {cmd.get('payload')}")+ else:+ print(f"[ANDROID] Unexpected message: {cmd}")+ return False++ # Step 5: Android responds with location+ print("\n[ANDROID] Sending location response...")+ await android_ws.send_json({+ "type": "data",+ "targetId": "test_web_001",+ "payload": {+ "service": "location",+ "lat": 37.7749,+ "lng": -122.4194+ }+ })++ msg = await asyncio.wait_for(web_ws.receive(), timeout=5.0)+ loc = json.loads(msg.data)+ if loc.get('type') == 'data' and loc.get('fromType') == 'android':+ payload = loc.get('payload')+ print(f"[WEB] Received location: {payload.get('lat')}, {payload.get('lng')}")+ print("\nBidirectional flow test: PASSED")+ await web_ws.close()+ await android_ws.close()+ return True++ await web_ws.close()+ await android_ws.close()+ return False++ except Exception as e:+ print(f"Flow test error: {e}")+ import traceback+ traceback.print_exc()+ return False+++async def main():+ print("=" * 60)+ print("WebSocket Connection Test for Remote Android Devices")+ print("=" * 60)++ results = {+ "health": await test_health_endpoint(),+ "stats": await test_stats_endpoint(),+ "websocket": await test_websocket_connection(),+ "android_web_flow": await test_android_to_web_flow()+ }++ print("\n" + "=" * 60)+ print("Test Results Summary")+ print("=" * 60)+ for test_name, result in results.items():+ status = "PASS" if result else "FAIL"+ print(f"{test_name.upper()}: {status}")++ all_passed = all(results.values())+ print("\n" + "=" * 60)+ if all_passed:+ print("Overall: ALL TESTS PASSED")+ else:+ print("Overall: SOME TESTS FAILED")+ print("=" * 60)++ return all_passed++if __name__ == "__main__":+ try:+ result = asyncio.run(main())+ exit(0 if result else 1)+ except KeyboardInterrupt:+ print("\nTest interrupted by user")+ exit(1)diff --git a/tests/websocket/test_workflow_websocket.py b/tests/websocket/test_workflow_websocket.pynew file mode 100644index 00000000..e5d0812c--- /dev/null+++ b/tests/websocket/test_workflow_websocket.py@@ -0,0 +1,90 @@+#!/usr/bin/env python3+"""+Test WebSocket connection from React Flow workflow node+Simulates executing the androidDeviceSetup node with remote connection+"""+import requests+import json+import os++def test_android_device_setup_remote():+ """Test Android Device Setup node with remote WebSocket connection"""++ print("Testing Android Device Setup Node - Remote WebSocket")+ print("=" * 60)++ # Workflow execution endpoint+ url = "http://localhost:3010/api/nodes/execute"++ # Simulate androidDeviceSetup node execution with remote connection+ payload = {+ "nodeId": "test_node_001",+ "nodeType": "androidDeviceSetup",+ "parameters": {+ "connection_type": "remote",+ "websocket_url": os.getenv('WEBSOCKET_URL', ''),+ "port": 8888+ },+ "inputs": {},+ "workflow": {+ "nodes": [],+ "edges": []+ }+ }++ print(f"\nSending request to: {url}")+ print(f"Payload: {json.dumps(payload, indent=2)}")++ try:+ response = requests.post(url, json=payload, timeout=30)++ print(f"\nResponse Status: {response.status_code}")+ print(f"Response Body:")+ print(json.dumps(response.json(), indent=2))++ if response.status_code == 200:+ result = response.json()++ if result.get('success'):+ connection_info = result.get('result', {})+ print("\nWebSocket Connection: SUCCESS")+ print(f" Client ID: {connection_info.get('client_id')}")+ print(f" Status: {connection_info.get('status')}")+ print(f" Registered: {connection_info.get('registered')}")+ print(f" WebSocket URL: {connection_info.get('websocket_url')}")+ print(f" Message: {connection_info.get('message')}")+ return True+ else:+ print(f"\nWebSocket Connection: FAILED")+ print(f" Error: {result.get('error')}")+ return False+ else:+ print(f"\nHTTP Request FAILED: {response.status_code}")+ return False++ except requests.exceptions.ConnectionError:+ print("\nERROR: Cannot connect to backend server")+ print("Make sure the Python backend is running on http://localhost:3010")+ return False+ except Exception as e:+ print(f"\nERROR: {e}")+ import traceback+ traceback.print_exc()+ return False+++if __name__ == "__main__":+ print("\n" + "=" * 60)+ print("React Flow Node WebSocket Test")+ print("=" * 60)++ result = test_android_device_setup_remote()++ print("\n" + "=" * 60)+ if result:+ print("Test Result: PASSED")+ else:+ print("Test Result: FAILED")+ print("=" * 60)++ exit(0 if result else 1)