Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
Add specialized agents, social nodes, and async agent delegation
trohitgfd94d7800b2a
diff --git a/.env.template b/.env.templateindex 63005231..c5c8432a 100644--- a/.env.template+++ b/.env.template@@ -64,6 +64,10 @@ WEBSOCKET_API_KEY=# WhatsApp Service URLWHATSAPP_SERVICE_URL=http://localhost:5000+# AI Proxy Configuration (Ollama-style proxy for Claude Code CLI)+# Default port for AI proxy servers (e.g., Ollama, Claude Code CLI proxy)+AI_PROXY_DEFAULT_PORT=11434+# External API Keys (managed through UI, these are optional defaults)OPENAI_API_KEY=GOOGLE_MAPS_API_KEY=diff --git a/.gitignore b/.gitignoreindex bea86e09..a78ddb65 100644--- a/.gitignore+++ b/.gitignore@@ -123,13 +123,11 @@ server/.python-version# Claude Code configuration# =============================================================================.claude/-CLAUDE.md-**/CLAUDE.md# =============================================================================-# Documentation (separate repos)+# Documentation (internal docs excluded, public docs tracked)# =============================================================================-docs*/+docs-internal/# =============================================================================# Experiments (work in progress)diff --git a/.npmignore b/.npmignoreindex 74518897..4451fd33 100644--- a/.npmignore+++ b/.npmignore@@ -43,8 +43,8 @@ node_modules/.vite/**/.vite/-# Client build output (users build locally)-client/dist/+# Client build output - INCLUDED in npm package (pre-built)+# client/dist/# IDE & editors.vscode/@@ -87,10 +87,10 @@ server/whatsapp-rpc/.wwebjs_*/server/whatsapp-rpc/session/server/whatsapp-rpc/qr_*.pngserver/whatsapp-rpc/data/-server/whatsapp-rpc/bin/+# server/whatsapp-rpc/bin/ - INCLUDED (pre-built binaries)-# Built binaries (users build locally)-*.exe+# Built binaries - INCLUDED in npm package (pre-built for each platform)+# The bin/ directory has the pre-built binary, exclude the old build locationserver/whatsapp-rpc/serverserver/whatsapp-rpc/server.exediff --git a/CLAUDE.md b/CLAUDE.mdnew file mode 100644index 00000000..34fdb4b2--- /dev/null+++ b/CLAUDE.md@@ -0,0 +1,3615 @@+# MachinaOs - Claude Documentation++## Project Overview+This is a React Flow-based workflow automation platform implementing n8n-inspired architectural patterns. The project has undergone a comprehensive refactoring to implement modern INodeProperties interface system with full TypeScript compliance and code cleanup.++## Documentation Reference++**Always refer to these documentation files for detailed guides:**++| Document | Description |+|----------|-------------|+| **[Node Creation Guide](./docs-internal/node_creation.md)** | Complete guide for creating new nodes (frontend definitions, backend handlers, config nodes, triggers) |+| **[AI Tool Node Guide](./docs-internal/ai_tool_node_creation.md)** | Detailed guide for creating dedicated AI Agent tool nodes (schemas, handlers, toolkits) |+| **[Specialized Agent Guide](./docs-internal/specialized_agent_node_creation.md)** | Guide for creating specialized AI agents (Android, Coding, Web, Social, Task) with full AI configuration |+| **[Dual-Purpose Tool Guide](./docs-internal/dual_purpose_tool_node_creation.md)** | Guide for nodes that work as both workflow nodes AND AI Agent tools (e.g., whatsappSend) |+| **[Workflow Schema](./docs-internal/workflow-schema.md)** | JSON schema for workflows, edge handle conventions, config node architecture |+| **[Execution Engine Design](./docs-internal/DESIGN.md)** | Architecture patterns, design standards, and implementation details for the workflow execution engine |+| **[Execution Roadmap](./docs-internal/ROADMAP.md)** | Implementation status, completed phases, and pending features |+| **[Setup Guide](./docs-internal/SETUP.md)** | Development environment setup and installation instructions |+| **[Scripts Reference](./docs-internal/SCRIPTS.md)** | Available npm/shell scripts and their usage |+| **[Server Documentation](./docs-internal/server-readme.md)** | Python backend architecture and API documentation |+| **[Polyglot Server](../polyglot-server/ARCHITECTURE.md)** | Plugin registry microservice with MCP gateway (optional integration) |++## Design Principles & Standards++**CRITICAL: Always follow these principles when modifying backend execution code:**++### 1. Use Existing Patterns - No Tribal Code+- **Never add ad-hoc workarounds** - Use the established patterns documented in DESIGN.md+- **Conductor Decide Pattern** - All orchestration goes through `_workflow_decide()` loop+- **Fork/Join Parallelism** - Use `asyncio.gather()` for concurrent node execution+- **Prefect Task Caching** - Cache results via `hash_inputs()` and `generate_cache_key()`+- **Distributed Locking** - Use Redis SETNX pattern for concurrent access control++### 2. State Management+- **Isolated Execution Contexts** - Each workflow run has its own `ExecutionContext`+- **No Global State** - Never use module-level variables for execution state+- **Cache Persistence** - Execution state persists to Redis (production) or SQLite (local development)+- **Explicit State Machines** - Tasks follow `TaskStatus` enum, workflows follow `WorkflowStatus`++### 3. Separation of Concerns+- **Models** (`models.py`) - Pure data structures, JSON-serializable, no business logic+- **Cache** (`cache.py`) - Redis persistence abstraction only+- **Executor** (`executor.py`) - Orchestration logic, decide pattern implementation+- **Recovery** (`recovery.py`) - Heartbeat and crash recovery only+- **Conditions** (`conditions.py`) - Edge condition evaluation for runtime branching++### Backend Service Architecture (n8n-inspired)+The workflow backend follows modular architecture patterns from n8n, Temporal, and Conductor:++```+server/services/+├── workflow.py # Facade (~460 lines) - thin coordinator+├── node_executor.py # Single node execution with registry pattern+├── parameter_resolver.py # Template variable resolution+├── deployment/ # Event-driven deployment lifecycle+│ ├── __init__.py+│ ├── state.py # DeploymentState, TriggerInfo dataclasses+│ ├── triggers.py # TriggerManager (cron, event triggers)+│ └── manager.py # DeploymentManager (deploy, cancel, status)+├── execution/ # Parallel workflow orchestration+│ ├── models.py # ExecutionContext, TaskStatus+│ ├── executor.py # WorkflowExecutor with decide pattern+│ ├── cache.py # Cache persistence (Redis/SQLite)+│ └── recovery.py # Crash recovery+└── temporal/ # Distributed workflow execution (optional)+ ├── __init__.py # Exports TemporalExecutor, TemporalClientWrapper+ ├── workflow.py # MachinaWorkflow orchestrator+ ├── activities.py # Class-based activities with connection pooling+ ├── worker.py # TemporalWorkerManager + run_standalone_worker()+ ├── executor.py # TemporalExecutor interface+ ├── client.py # Temporal client wrapper+ └── ws_client.py # WebSocket connection pool++server/core/+├── container.py # Dependency injection container+├── database.py # SQLite database with cache CRUD methods+├── cache.py # CacheService with Redis/SQLite/Memory fallback+└── settings.py # Application configuration++server/models/+├── cache.py # CacheEntry SQLModel for SQLite cache+├── auth.py # User model with bcrypt+└── database.py # ConversationMessage, NodeParameter, ToolSchema, ChatMessage tables+```++### Polyglot Server Integration (Optional)+MachinaOs can optionally integrate with **polyglot-server** - a centralized plugin registry microservice that exposes integrations through REST API, MCP (Model Context Protocol), and WebSocket.++**Architecture:**+```+┌─────────────────────────────────────────────────────────────────┐+│ MachinaOs │+│ ┌────────────────┐ ┌────────────────┐ │+│ │ React Flow │───▶│ FastAPI Backend│ │+│ │ Frontend │ │ (port 3010) │ │+│ └────────────────┘ └───────┬────────┘ │+│ │ │+│ ┌─────────────────┴─────────────────┐ │+│ │ NodeExecutor │ │+│ │ (registry-based dispatch) │ │+│ └─────────────────┬─────────────────┘ │+└────────────────────────────────│────────────────────────────────┘+ │ HTTP (aiohttp)+ ▼+┌─────────────────────────────────────────────────────────────────┐+│ Polyglot Server (port 8080) │+│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │+│ │ REST API │ │ MCP │ │ WebSocket │ │+│ │ Gateway │ │ Server │ │ Handler │ │+│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │+│ └────────────────┼────────────────┘ │+│ ▼ │+│ ┌───────────────────────┐ │+│ │ Plugin Registry │ │+│ │ Discord, Telegram, │ │+│ │ Notion, GitHub, etc. │ │+│ └───────────────────────┘ │+└─────────────────────────────────────────────────────────────────┘+```++**Files:**+```+server/services/+├── polyglot_client.py # HTTP client for polyglot-server+└── handlers/+ └── polyglot.py # Standalone handler (not wired to NodeExecutor)+```++**PolyglotClient** (`server/services/polyglot_client.py`):+```python+class PolyglotClient:+ """HTTP client for polyglot-server plugin registry."""++ async def list_plugins(self) -> List[Dict[str, Any]]:+ """List all available plugins."""++ async def get_schema(self, plugin_name: str) -> Optional[Dict[str, Any]]:+ """Get plugin input/output schema for workflow node integration."""++ async def execute(self, plugin_name: str, action: str, params: Dict) -> Dict:+ """Execute a plugin action."""+```++**Polyglot Handler** (`server/services/handlers/polyglot.py`):+```python+async def handle_polyglot_node(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any],+ polyglot_client, # Injected via functools.partial+) -> Dict[str, Any]:+ """Execute a workflow node via polyglot-server plugin registry."""+ plugin_name = node_type.replace("Node", "").lower()+ result = await polyglot_client.execute(plugin_name, action, params)+ return {"success": True, "result": result.get("result", {}), ...}++# Node types that can be routed to polyglot-server+POLYGLOT_NODE_TYPES = frozenset([+ "discordNode", "telegramNode", "slackNode", "notionNode",+ "todoistNode", "gmailNode", "twitterNode", "githubNode", ...+])+```++**Configuration** (when enabled):+```bash+# In server/.env+POLYGLOT_SERVER_URL=http://localhost:8080 # polyglot-server address+```++**Current Status**: Standalone integration files created. Not wired into NodeExecutor to avoid disturbing existing workflow execution flow. Future integration will add polyglot node types to handler registry via `functools.partial` pattern.++**Key Modules:**++| Module | Responsibility | Pattern |+|--------|---------------|---------|+| `workflow.py` | Facade delegating to specialized modules | Facade Pattern |+| `node_executor.py` | Execute single node via handler registry | Registry + functools.partial |+| `parameter_resolver.py` | Resolve `{{node.field}}` templates | Compiled regex |+| `deployment/manager.py` | Deploy/cancel workflows, spawn runs | n8n Deployment |+| `deployment/triggers.py` | Setup cron/event triggers | Event-driven |+| `deployment/state.py` | Immutable state dataclasses | Dataclass |+| `temporal/executor.py` | Temporal-based distributed execution | Per-node Activities |+| `temporal/workflow.py` | Pure orchestrator (no business logic) | FIRST_COMPLETED |+| `temporal/worker.py` | Worker lifecycle + horizontal scaling | Connection Pooling |++**NodeExecutor Registry Pattern:**+```python+class NodeExecutor:+ def _build_handler_registry(self) -> Dict[str, Callable]:+ return {+ 'start': handle_start,+ 'aiAgent': partial(handle_ai_agent, ai_service=self.ai_service),+ # ... registry-based dispatch instead of if-else chains+ }+```++### 4. Dependency Injection+```python+# Correct: Receive dependencies via constructor+class WorkflowExecutor:+ def __init__(self, cache: ExecutionCache, node_executor: Callable):+ self.cache = cache+ self.node_executor = node_executor++# Wrong: Import and use global singletons+from services.some_service import global_instance+```++### 5. Error Handling & Logging+- **Log at appropriate levels**: DEBUG for routine operations, INFO for significant events, ERROR for failures+- **Never suppress errors silently** - Always log or propagate+- **Use structured logging** - Include context (node_id, execution_id, etc.)+- **Configurable via `.env`**: Set `LOG_LEVEL=DEBUG` for verbose output, `LOG_LEVEL=INFO` for production++#### Logging Configuration+```bash+# In server/.env+LOG_LEVEL=INFO # Default: INFO, DEBUG for verbose+LOG_FORMAT=text # text or json+```++**What logs at each level:**+- `DEBUG`: Template resolution, parameter resolution, node execution details, event waiter registration, downstream traversal+- `INFO`: Workflow completion, deployment start/stop, significant state changes+- `ERROR`: Failures, exceptions, validation errors++### 6. Cleanup & Lifecycle+- **Use existing teardown methods** - e.g., `_teardown_all_cron_triggers()` for cron cleanup+- **Cleanup in finally blocks** - Ensure resources are released even on error+- **No orphan prevention hacks** - Trust the existing lifecycle management++### 7. Cache System Architecture (n8n Pattern)+The cache system follows n8n's pattern with automatic fallback:++```+Production (Docker): Redis → SQLite → Memory+Local Development: SQLite → Memory (Redis disabled)+```++**Configuration** (`server/.env`):+```bash+REDIS_ENABLED=false # Local dev: use SQLite+REDIS_URL=redis://redis:6379 # Production: Docker Redis+```++**CacheService** (`server/core/cache.py`):+```python+class CacheService:+ def __init__(self, database: Database, settings: Settings):+ self._database = database+ self._settings = settings+ self._redis: Optional[Redis] = None+ self._memory_cache: Dict[str, Any] = {}++ async def get(self, key: str) -> Optional[str]:+ # Try Redis first (if enabled)+ if self._redis:+ value = await self._redis.get(key)+ if value: return value+ # Fall back to SQLite+ entry = await self._database.get_cache_entry(key)+ if entry: return entry.value+ # Fall back to memory+ return self._memory_cache.get(key)+```++**SQLite Cache Model** (`server/models/cache.py`):+```python+class CacheEntry(SQLModel, table=True):+ __tablename__ = "cache_entries"+ key: str = Field(primary_key=True)+ value: str+ expires_at: Optional[datetime] = None+ created_at: datetime = Field(default_factory=datetime.utcnow)+```++**Key Methods** (`server/core/database.py`):+- `get_cache_entry(key)` - Get cache entry by key+- `set_cache_entry(key, value, ttl)` - Set with optional TTL+- `delete_cache_entry(key)` - Delete by key+- `cleanup_expired_cache()` - Remove expired entries++## Codebase Summary+- **Hybrid architecture**: Node.js + Python + React TypeScript+- **63 implemented workflow nodes** with clean service separation (6 AI models + 3 AI agents/memory + 5 specialized agents + 10 skills + 4 dedicated tools + 2 dual-purpose tools + 16 Android + 4 WhatsApp + 3 Location + 1 Code + 3 Utility + 6 Document)+- **WebSocket-First Architecture**: WebSocket as primary frontend-backend communication (25 message types)+- **Recent optimizations**: REST APIs replaced with WebSocket, AI endpoints migrated to Python, Android automation integrated++## Architecture Refactoring+The project was completely refactored from schema-based node definitions to explicit INodeProperties interface system inspired by n8n architecture. Key changes:+- **Pure INodeProperties System**: Removed all backward compatibility layers+- **35 Implemented Node Components**: AI models, agents, location services, Android automation, WhatsApp, Python code execution, and HTTP/Webhook utilities with full execution support+- **WebSocket-First Communication**: 25 WebSocket message handlers replace most REST API calls+- **Resource-Operation Pattern**: Organized by functional categories (AI, Location, Android, WhatsApp)+- **TypeScript-First**: Full type safety with proper interface alignment+- **Code Cleanup**: Removed dead code, unused files, and legacy methods+- **Android Integration**: 16 Android service nodes with ADB-based device automation++## Key Files & Components++### Core Types+- `src/types/INodeProperties.ts` - Core interfaces for n8n-inspired node properties system+- `src/types/NodeTypes.ts` - Legacy compatibility types (NodeParameter, NodeOutput)++### Node System+- `src/nodeDefinitions.ts` - Main registry importing modular node definitions+- `src/nodeDefinitions/aiModelNodes.ts` - AI chat model definitions using factory pattern+- `src/nodeDefinitions/aiAgentNodes.ts` - AI agent and processing components+- `src/nodeDefinitions/skillNodes.ts` - Skill node definitions (10 nodes including masterSkill)+- `src/nodeDefinitions/specializedAgentNodes.ts` - Specialized AI agent definitions (5 nodes) with shared AI_AGENT_PROPERTIES+- `src/nodeDefinitions/androidServiceNodes.ts` - 16 Android service nodes (monitoring, apps, automation, sensors, media)+- `src/nodeDefinitions/androidDeviceNodes.ts` - Android device setup and ADB port forwarding+- `src/nodeDefinitions/locationNodes.ts` - Google Maps and location services+- `src/nodeDefinitions/whatsappNodes.ts` - WhatsApp messaging integration+- `src/nodeDefinitions/codeNodes.ts` - Python code execution node with syntax highlighting+- `src/nodeDefinitions/utilityNodes.ts` - HTTP Request and Webhook nodes (httpRequest, webhookTrigger, webhookResponse)+- `src/nodeDefinitions/documentNodes.ts` - Document processing nodes (httpScraper, fileDownloader, documentParser, textChunker, embeddingGenerator, vectorStore)+- `src/factories/baseChatModelFactory.ts` - Factory for creating standardized chat models+- `src/services/executionService.ts` - Node execution engine with routing to Python backend++### UI Components+- `src/components/ParameterRenderer.tsx` - Universal parameter renderer (dual interface support)+- `src/components/parameterPanel/MiddleSection.tsx` - Parameter panel middle section with conditional display logic+- `src/components/OutputPanel.tsx` - Connected node output display with drag mapping+- `src/components/LocationParameterPanel.tsx` - Location-specific parameter handling+- `src/components/AIParameterRenderer.tsx` - AI component configuration+- `src/components/AIAgentNode.tsx` - Config-driven AI agent component supporting both aiAgent and chatAgent via AGENT_CONFIGS+- `src/ParameterPanel.tsx` - Main parameter configuration modal++### AI Chat Model Components+- `src/components/base/BaseChatModelNode.tsx` - Unified circular node design for all AI providers+- `src/components/ClaudeChatModelNode.tsx` - Anthropic Claude model component+- `src/components/OpenAIChatModelNode.tsx` - OpenAI GPT model component+- `src/components/GeminiChatModelNode.tsx` - Google Gemini model component+- `src/components/ModelNode.tsx` - Generic AI model node with provider detection+- `src/services/apiKeyManager.ts` - Secure API key storage and validation with LangChain++### Specialized UI+- `src/components/ui/MapSelector.tsx` - Interactive location picker+- `src/components/ui/OutputDisplayPanel.tsx` - Execution result display+- `src/components/ui/ComponentPalette.tsx` - Searchable component library with emoji icons and dracula-themed category colors. Categories: Workflow, Triggers, AI Agents, AI Models, AI Skills, AI Abilities, AI Tools, Google Maps, Social Media Platforms (merged WhatsApp + Social), Android, Chat, Code Executors+- `src/components/ui/ComponentItem.tsx` - Draggable node items with hover effects and icon rendering+- `src/components/ui/CodeEditor.tsx` - Syntax-highlighted code editor using react-simple-code-editor + prismjs with centralized theming++### Hooks & State+- `src/hooks/useParameterPanel.ts` - Parameter management via WebSocket+- `src/hooks/useExecution.ts` - Node execution via WebSocket+- `src/hooks/useApiKeys.ts` - API key management via WebSocket+- `src/hooks/useAndroidOperations.ts` - Android device operations via WebSocket+- `src/hooks/useWhatsApp.ts` - WhatsApp operations via WebSocket+- `src/hooks/useDragAndDrop.ts` - Drag-and-drop functionality+- `src/hooks/useComponentPalette.ts` - Component palette state with localStorage persistence+- `src/store/useAppStore.ts` - Zustand application state with localStorage persistence for UI settings++### Theme System+- `src/styles/theme.ts` - Unified theme with Solarized + Dracula color palettes+- `src/hooks/useAppTheme.ts` - Dynamic theme hook for dark/light mode+- `src/contexts/ThemeContext.tsx` - Theme context with `isDarkMode` and `toggleTheme`+- `src/index.css` - Global CSS including dark mode scrollbar styles++#### Color Palettes+The theme system uses two complementary color palettes:++**Solarized** (backgrounds and text):+- `theme.colors.*` - Dynamic colors based on light/dark mode+- `theme.accent.*` - Solarized accent colors (blue, cyan, green, yellow, orange, red, magenta, violet)++**Dracula** (vibrant action colors):+- `theme.dracula.green` (#50fa7b) - Run/Success actions+- `theme.dracula.purple` (#bd93f9) - Deploy/Save actions+- `theme.dracula.pink` (#ff79c6) - Cancel/Stop actions+- `theme.dracula.cyan` (#8be9fd) - Info/Alternative actions+- `theme.dracula.red` (#ff5555) - Error/Danger states+- `theme.dracula.orange` (#ffb86c) - Settings/Warning+- `theme.dracula.yellow` (#f1fa8c) - Credentials/Highlight++#### UI Components Using Dracula Theme+- **TopToolbar Action Buttons**: Run (green), Deploy (purple), Stop (pink), Save (cyan)+- **TopToolbar Icon Buttons**: Settings (orange), Credentials (yellow), Theme Toggle (yellow/purple)+- **TopToolbar File Button**: Cyan text with medium font size and semibold weight, colorful dropdown menu items+- **ParameterPanel Buttons**: Run (green), Save (purple), Cancel (pink)+- **React Flow Edges**: Default (cyan), Selected/Executing (purple), Completed (green), Error (red), Pending (cyan)+- **Node Execution Glow**: Purple glow animation during execution++#### File Operations Menu Styling+The File dropdown menu uses per-item Dracula colors:+```typescript+// In TopToolbar.tsx+{[+ { label: 'New Workflow', icon: '...', action: onNew, color: theme.dracula.green },+ { label: 'Open', icon: '...', action: onOpen, color: theme.accent.blue },+ { label: 'Export', icon: '...', action: onExportFile, color: theme.accent.cyan },+ { label: 'Import', icon: '...', action: onImportJSON, color: theme.accent.cyan },+ { label: 'Copy as JSON', icon: '...', action: onExportJSON, color: theme.dracula.purple },+].map(...)}++// File button style+const textButtonStyle: React.CSSProperties = {+ color: theme.dracula.cyan,+ border: `1px solid ${theme.dracula.cyan}40`,+ fontSize: theme.fontSize.md,+ fontWeight: theme.fontWeight.semibold,+ ...+};+```++#### Button Style Pattern+Action buttons use a consistent pattern with Dracula colors:+```typescript+const actionButtonStyle = (color: string, isDisabled = false) => ({+ backgroundColor: isDisabled ? `${theme.colors.primary}15` : `${color}25`,+ color: isDisabled ? theme.colors.primary : color,+ border: `1px solid ${isDisabled ? `${theme.colors.primary}40` : `${color}60`}`,+});+```++#### Edge Styles+React Flow edges use dynamic Dracula colors via `getEdgeStyles(theme.dracula)`:+- Default edges: `theme.dracula.cyan`+- Selected/executing: `theme.dracula.purple` with glow animation+- Completed: `theme.dracula.green`+- Error: `theme.dracula.red`+- Pending: `theme.dracula.cyan` with dash animation++### WebSocket-First Architecture+The project uses WebSocket as the primary communication method between frontend and backend, replacing most REST API calls:+- `src/contexts/WebSocketContext.tsx` - Central WebSocket context with request/response pattern+- `server/routers/websocket.py` - WebSocket endpoint with 25 message handlers+- `server/services/status_broadcaster.py` - Connection management and broadcasting++## Implemented Node Types+The following 58 nodes are currently implemented and functional:++### AI Chat Models (6 nodes)+- **openaiChatModel**: OpenAI GPT models with response format options. O-series models (o1, o3, o4) support reasoning effort parameter.+- **anthropicChatModel**: Claude models with extended thinking support (budget_tokens for claude-3-5-sonnet, claude-3-opus)+- **geminiChatModel**: Google Gemini models with multimodal capabilities, safety settings, and thinking support for 2.5/Flash Thinking models+- **openrouterChatModel**: OpenRouter unified API - access 200+ models from OpenAI, Anthropic, Google, Meta, Mistral, and more through a single API. Features free/paid model grouping in dropdown.+- **groqChatModel**: Groq ultra-fast inference with Llama, Mixtral, Gemma, and reasoning-capable Qwen3/QwQ models+- **cerebrasChatModel**: Cerebras ultra-fast inference on custom AI hardware with Llama and Qwen models++### AI Agents & Memory (3 nodes)+- **aiAgent**: Advanced AI agent with tool calling, memory input handle, and iterative reasoning. Uses LangGraph for structured execution. Parameters: Provider, Model, Prompt, System Message, Options.+- **chatAgent**: Conversational AI agent with memory and skill support for multi-turn chat interactions. Parameters: Provider, Model, Prompt (supports `{{chatTrigger.message}}` template or auto-fallback from connected input), System Message. Behavior extended by connected skills.+- **simpleMemory**: Markdown-based conversation memory with editable UI, window-based trimming, and optional vector DB for long-term semantic retrieval++### Zeenie Skill Nodes (10 nodes)+Skill nodes connect to Zeenie's `input-skill` handle to provide capabilities defined in SKILL.md files following the [Agent Skills specification](https://agentskills.io/specification):+- **masterSkill**: Master Skill (icon: target) - Aggregates multiple skills with enable/disable toggles. Split-panel UI: left panel shows skill list with checkboxes, right panel shows selected skill's markdown editor. Enabled skills are expanded into individual skill entries when the AI Agent executes.+- **claudeSkill**: Assistant Skill (icon: sparkles) - default assistant personality with helpful, harmless, honest responses+- **whatsappSkill**: Send and receive WhatsApp messages via Zeenie+- **memorySkill**: Long-term memory management across conversations+- **mapsSkill**: Location services - geocoding, nearby places, directions via Google Maps+- **httpSkill**: Make HTTP requests to external APIs+- **schedulerSkill**: Task scheduling with timers and cron expressions+- **androidSkill**: Android device control - battery, wifi, bluetooth, apps, location, camera+- **codeSkill**: Execute Python or JavaScript code for calculations and data processing+- **webSearchSkill**: Search the web for current information, news, facts, and real-time data+- **customSkill**: User-created custom skill with configurable capabilities (select from database)++#### Skill Node Architecture+Skills are modular capabilities defined in Markdown files:+```+server/skills/+├── claude-assistant/SKILL.md # Default assistant behavior+├── whatsapp-skill/SKILL.md # WhatsApp messaging+├── memory-skill/SKILL.md # Memory management+├── maps-skill/SKILL.md # Location services+├── http-skill/SKILL.md # HTTP requests+└── scheduler-skill/SKILL.md # Task scheduling+```++**SKILL.md Format:**+```yaml+---+name: skill-name+description: Brief description for LLM visibility+allowed-tools: tool1 tool2+metadata:+ author: machina+ version: "1.0"+---++# Skill Instructions (Markdown)+Detailed instructions loaded when skill is activated.+```++#### Skill Content Editor+Skill nodes display a code editor (markdown syntax highlighting) to view and edit SKILL.md content:+- Instructions loaded automatically when skill node is selected+- Save button writes changes back to SKILL.md file+- Uses `get_skill_content` / `save_skill_content` WebSocket handlers+- **No Input/Output panels**: Skill nodes only show the middle section (parameters + editor) in the parameter panel++**Key Files:**+| File | Description |+|------|-------------|+| `client/src/nodeDefinitions/skillNodes.ts` | Skill node definitions with factory pattern |+| `client/src/hooks/useParameterPanel.ts` | Loads/saves skill content for skill nodes |+| `server/services/skill_loader.py` | SkillLoader for filesystem and database skills |+| `server/routers/websocket.py` | `get_skill_content`, `save_skill_content` handlers |++#### Master Skill Editor+The Master Skill node uses a custom split-panel editor (`MasterSkillEditor.tsx`) instead of standard parameters:++**UI Layout:**+```++----------------------------------------------------------++| Master Skill Editor |++----------------------------------------------------------++| +--------------------+ +--------------------------------+ |+| | SKILLS LIST | | SKILL INSTRUCTIONS | |+| | [Badge: 3 enabled] | | | |+| | [Search skills...] | | # WhatsApp Skill | |+| | | | | |+| | [x] WhatsApp | | This skill provides WhatsApp | |+| | [x] Memory | | messaging capabilities... | |+| | [ ] Android | | | |+| | [x] Maps | | [Reset to Default] | |+| | [ ] HTTP | | | |+| +--------------------+ +--------------------------------+ |++----------------------------------------------------------++```++**Data Structure:**+```typescript+// skillsConfig parameter stored in node parameters+interface MasterSkillConfig {+ [skillName: string]: {+ enabled: boolean; // Whether skill is active+ instructions: string; // Custom or default SKILL.md content+ isCustomized: boolean; // True if user modified instructions+ };+}+```++**Backend Expansion:**+When AI Agent executes with a connected Master Skill node, `_collect_agent_connections()` in `handlers/ai.py` expands the skillsConfig into individual skill entries:+```python+if skill_type == 'masterSkill':+ skills_config = skill_params.get('skillsConfig', {})+ for skill_key, skill_cfg in skills_config.items():+ if skill_cfg.get('enabled', False):+ # Load from customized or skill folder+ instructions = skill_cfg.get('instructions') if skill_cfg.get('isCustomized') else skill_loader.load_skill(skill_key).instructions+ skill_data.append({+ 'node_id': f"{source_node_id}_{skill_key}",+ 'node_type': 'masterSkill',+ 'skill_name': skill_key,+ 'parameters': {'instructions': instructions},+ 'label': skill_key+ })+```++**Key Files:**+| File | Description |+|------|-------------|+| `client/src/components/parameterPanel/MasterSkillEditor.tsx` | Split-panel skill aggregator UI |+| `client/src/nodeDefinitions/skillNodes.ts` | masterSkill node definition |+| `server/services/handlers/ai.py` | Expands masterSkill into individual skills |++### AI Agent Tool Nodes (3 dedicated + 6 dual-purpose)+Tool nodes connect to AI Agent's `input-tools` handle to provide capabilities the agent can invoke during reasoning.++#### Dedicated Tool Nodes (passive, tool-only)+- **calculatorTool**: Mathematical operations (add, subtract, multiply, divide, power, sqrt, mod, abs)+- **currentTimeTool**: Get current date/time with timezone support+- **webSearchTool**: Web search via DuckDuckGo (free, uses `ddgs` library) or Serper API with configurable max results++### Specialized AI Agents (5 nodes)+Specialized agents are AI Agents pre-configured for specific domains. They inherit full AI Agent functionality (provider, model, prompt, system message, thinking/reasoning) while being tailored for specific capabilities. All specialized agents route to `handle_chat_agent` in the backend and support the same input handles.++**Input Handles:**+- `input-main` - Main data input (auto-prompting fallback)+- `input-skill` - Skill nodes (including Master Skill for aggregated skills)+- `input-memory` - Memory node for conversation history+- `input-tools` - Tool nodes for LLM tool calling++**Specialized Agent Types:**+- **android_agent**: Android Control Agent - AI agent for Android device control. Connect Android service nodes (battery, wifi, bluetooth, apps, location, camera, sensors) as tools.+- **coding_agent**: Coding Agent - AI agent for code execution. Connect code executor nodes (Python, JavaScript) as tools.+- **web_agent**: Web Control Agent - AI agent for web automation. Connect web/browser nodes (scraper, HTTP, browser) as tools.+- **task_agent**: Task Management Agent - AI agent for task automation. Connect scheduling nodes (scheduler, reminders) as tools.+- **social_agent**: Social Media Agent - AI agent for social messaging. Connect messaging nodes (WhatsApp, Telegram) as tools.++**Backend Routing:**+Specialized agents are detected by `SPECIALIZED_AGENT_TYPES` and routed to `handle_chat_agent`:+```python+# In node_executor.py+SPECIALIZED_AGENT_TYPES = {'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent'}+```++**Direct Android Service Tools:**+Android service nodes (batteryMonitor, wifiAutomation, etc.) can be connected directly to any agent's `input-tools` handle. The backend maps camelCase node types to snake_case service IDs:+```python+# In handlers/tools.py+service_id_map = {+ 'batteryMonitor': 'battery',+ 'wifiAutomation': 'wifi_automation',+ 'bluetoothAutomation': 'bluetooth_automation',+ # ... etc+}+```++#### Dual-Purpose Tool Nodes (workflow node + AI tool)+Nodes that work BOTH as standalone workflow nodes AND as AI Agent tools. When connected to `input-tools`, the LLM fills the node's parameter schema.+- **whatsappSend**: Send WhatsApp messages (text, media, location, contact). Full schema for all message types.+- **whatsappDb**: Query WhatsApp database - chat history, contacts, groups with filtering and pagination.+- **pythonExecutor**: Execute Python code for calculations, data processing, and automation. Tool name: `python_code`. Available: math, json, datetime, Counter, defaultdict, random.+- **javascriptExecutor**: Execute JavaScript code for calculations, data processing, and JSON manipulation. Tool name: `javascript_code`.+- **gmaps_locations**: Google Maps Geocoding service for address-to-coordinates conversion. Tool name: `geocode`.+- **gmaps_nearby_places**: Google Places API nearbySearch. Tool name: `nearby_places`.++See [Dual-Purpose Tool Node Guide](./docs-internal/dual_purpose_tool_node_creation.md) for implementation details.++### Location Services (3 nodes)+- **gmaps_create**: Google Maps creation with customizable center, zoom, and map type (display only, not a tool)+- **gmaps_locations**: **Dual-purpose** - Google Maps Geocoding service for address-to-coordinates conversion+- **gmaps_nearby_places**: **Dual-purpose** - Google Places API nearbySearch with detailed place information++#### Google Maps API Key Resolution+The MapsSection component fetches the Google Maps API key from backend credentials:+```typescript+// In MapsSection.tsx+const { getStoredApiKey, isConnected } = useApiKeys();+const [apiKey, setApiKey] = useState<string | undefined>(() => getGoogleMapsApiKey()); // Env fallback+const hasFetchedRef = useRef(false);++useEffect(() => {+ if (!isConnected || hasFetchedRef.current) return;+ const fetchApiKey = async () => {+ hasFetchedRef.current = true;+ const storedKey = await getStoredApiKey('google_maps');+ if (storedKey) setApiKey(storedKey);+ };+ fetchApiKey();+}, [isConnected, getStoredApiKey]);+```+- Falls back to environment variable if no stored key+- Uses `hasFetchedRef` to prevent multiple fetches+- Only fetches when WebSocket is connected++### Android Services (16 nodes)+Android device connection is configured via the Credentials Modal (Android panel), not via workflow nodes.++#### System Monitoring (4 nodes)+- **batteryMonitor**: Monitor battery status, level, charging state, temperature, and health+- **networkMonitor**: Monitor network connectivity, type, and internet availability+- **systemInfo**: Get device and OS information including Android version, API level, memory, and hardware details+- **location**: GPS location tracking with latitude, longitude, accuracy, and provider information++#### App Management (2 nodes)+- **appLauncher**: Launch applications by package name+- **appList**: Get list of installed applications with package names, versions, and metadata++#### Device Automation (6 nodes)+- **wifiAutomation**: WiFi control and scanning - enable, disable, get status, scan for networks+- **bluetoothAutomation**: Bluetooth control - enable, disable, get status, and paired devices+- **audioAutomation**: Volume and audio control - get/set volume, mute, unmute+- **deviceStateAutomation**: Device state control - airplane mode, screen on/off, power save mode, brightness+- **screenControlAutomation**: Screen control - brightness adjustment, wake screen, auto-brightness, screen timeout+- **airplaneModeControl**: Airplane mode status monitoring and control++#### Sensors (2 nodes)+- **motionDetection**: Accelerometer and gyroscope data - detect motion, shake gestures, device orientation+- **environmentalSensors**: Environmental sensors - temperature, humidity, pressure, light level++#### Media (2 nodes)+- **cameraControl**: Camera control - get camera info, take photos, camera capabilities+- **mediaControl**: Media playback control - volume control, playback control, play media files++### WhatsApp Nodes (4 nodes)+- **whatsappSend**: **Dual-purpose node** - Send WhatsApp messages (text, image, video, audio, document, sticker, location, contact). Works as workflow node OR AI Agent tool. Group: `['whatsapp', 'tool']`. Full parameter schema for recipient type, message type, media URL, location coordinates, contact vCard.+- **whatsappDb**: **Dual-purpose node** - Comprehensive WhatsApp database query node with 6 operations. Works as workflow node OR AI Agent tool. Group: `['whatsapp', 'tool']`. Operations:+ - `chat_history`: Retrieve messages from individual or group chats with filtering and pagination+ - `search_groups`: Search groups by name+ - `get_group_info`: Get group details with participant names and phone numbers+ - `get_contact_info`: Get full contact info (name, phone, profile picture) for sending/replying+ - `list_contacts`: List all contacts with saved names+ - `check_contacts`: Check WhatsApp registration status for phone numbers+- **whatsappConnect**: Check WhatsApp connection status and device info+- **whatsappReceive**: Event-driven trigger that waits for incoming WhatsApp messages with filters (message type, sender, group, keywords, forwarded status). Marked with `['whatsapp', 'trigger']` group for n8n-style trigger identification. Stores group/sender names alongside JID/phone for display persistence. The Go RPC resolves LIDs to phone numbers before sending events - `sender_phone` field is already resolved. Filter options: All Messages, From Any Contact (Non-Group), From Specific Contact, From Specific Group, Contains Keywords++### Social Nodes (2 nodes)+Unified social messaging nodes for multi-platform communication. Supports WhatsApp, Telegram, Discord, Slack, Signal, SMS, Webchat, Email, Matrix, Teams.++- **socialReceive**: Normalizes messages from platform triggers into unified format. Multiple outputs: Message, Media, Contact, Metadata. Filters by channel, message type, sender.+- **socialSend**: **Dual-purpose node** - Send messages to any supported platform. Works as workflow node OR AI Agent tool. Supports text, image, video, audio, document, sticker, location, contact, poll, buttons, list message types.++### Workflow Nodes (1 node)+- **workflowTrigger**: Manual workflow trigger to start workflow execution++### Code Nodes (2 nodes)+- **pythonExecutor**: **Dual-purpose node** - Execute Python code with syntax-highlighted editor, input_data access, and console output. Works as workflow node OR AI Agent tool (`python_code`). Available libraries: math, json, datetime, timedelta, re, random, Counter, defaultdict.+- **javascriptExecutor**: **Dual-purpose node** - Execute JavaScript code with syntax-highlighted editor and console output. Works as workflow node OR AI Agent tool (`javascript_code`).++### Utility Nodes (3 nodes)+- **httpRequest**: Make HTTP requests to external APIs (GET, POST, PUT, DELETE, PATCH) with configurable headers, body, and timeout+- **webhookTrigger**: Event-driven trigger that waits for incoming HTTP requests at `/webhook/{path}` with method filtering and authentication options+- **webhookResponse**: Send custom response back to webhook caller with configurable status code, body, and content type++### Document Processing Nodes (6 nodes)+RAG pipeline nodes for document ingestion, processing, and vector storage. Supports multiple providers and backends.++- **httpScraper**: Scrape links from web pages with date/page pagination support. Modes: single request, date range iteration, page pagination. Outputs: items array with URLs.+- **fileDownloader**: Download files from URLs in parallel using semaphore-based concurrency. Parameters: output directory, max workers (1-32), skip existing, timeout.+- **documentParser**: Parse documents to text using configurable parsers. Parsers: PyPDF (fast), Marker (GPU OCR), Unstructured (multi-format), BeautifulSoup (HTML).+- **textChunker**: Split text into overlapping chunks for embedding. Strategies: recursive (recommended), markdown, token. Parameters: chunk size (100-8000), overlap (0-1000).+- **embeddingGenerator**: Generate vector embeddings from text chunks. Providers: HuggingFace (local), OpenAI, Ollama. Default model: BAAI/bge-small-en-v1.5.+- **vectorStore**: Store and query vector embeddings. Operations: store, query, delete. Backends: ChromaDB (local), Qdrant (production), Pinecone (cloud).++#### Document Processing Dependencies+```+# Required (in server/requirements.txt)+beautifulsoup4>=4.12.0+langchain-text-splitters>=0.3.0+langchain-huggingface>=0.1.0+chromadb>=0.5.0+qdrant-client>=1.12.0+sentence-transformers>=3.0.0+pypdf>=4.0.0++# Optional (GPU OCR and multi-format parsing)+# marker-pdf>=1.0.0 # Requires CUDA+# unstructured>=0.16.0 # Multi-format document parsing+```++#### Document Node Architecture+```+server/services/handlers/+└── document.py # 6 async handler functions++client/src/nodeDefinitions/+└── documentNodes.ts # 6 node definitions with conditional properties+```++## Backend Services++### Python Backend (FastAPI)+- **Port**: 3010+- **Base URL**: http://localhost:3010+- **Main File**: `server/main.py`++### API Endpoints+#### Android Services (`server/routers/android.py`)+- `GET /api/android/devices` - List connected Android devices via ADB with model and state info+- `POST /api/android/port-forward` - Setup ADB port forwarding for device communication+- `POST /api/android/{service_id}/{action}` - Execute Android service actions with parameters+- `GET /api/android/health` - Android service health check++#### Remote Android WebSocket+- **WebSocket**: Configurable via environment variable - Persistent WebSocket connection for remote Android devices+- **Health Check**: `{relay-url}/ws-health` - WebSocket proxy health status+- **Stats**: `{relay-url}/ws-stats` - Active connection statistics+- **Implementation**: `server/services/websocket_client.py` - Persistent WebSocket client with background tasks+ - Background message receiver continuously queues incoming messages+ - Keepalive loop sends ping every 25 seconds to maintain connection+ - Message queue (asyncio.Queue) for async message handling+ - Connection reuse across multiple API requests+ - Message filtering to skip non-response messages (presence, pong, ping)++#### Webhook Router (`server/routers/webhook.py`)+- `ANY /webhook/{path}` - Dynamic webhook endpoint for incoming HTTP requests (GET, POST, PUT, DELETE, PATCH)+- Dispatches `webhook_received` event via `broadcaster.send_custom_event()` to trigger waiting webhookTrigger nodes+- Returns immediate 200 OK response (responseNode mode planned for future)+- `GET /webhook/` - Webhook endpoint info and usage documentation++#### Workflow Services (`server/services/workflow.py`)+- Node execution handlers for all 27 node types (including httpRequest, webhookResponse)+- Parameter resolution and template variable substitution+- Result formatting and error handling++#### Frontend-Backend WebSocket (`server/routers/websocket.py`)+- **WebSocket Endpoint**: `/ws/status` - Real-time status updates between React and Python+- **REST Endpoint**: `GET /ws/info` - WebSocket connection info and current status+- **Message Types**:+ - `android_status` - Android device connection status updates+ - `node_status` - Individual node execution status+ - `node_output` - Node execution output data+ - `variable_update` - Single variable value change+ - `variables_update` - Batch variable updates+ - `workflow_status` - Workflow execution progress+ - `ping/pong` - Keep-alive messages++### Development Scripts+- `stop.bat` / `stop.sh` - Stops all development servers with duplicate Python process detection and verification+- `restart.bat` / `restart.sh` - Restarts all services cleanly+- `start.bat` / `start.sh` - Starts frontend and backend servers++### Concurrently Process Management Fix+**Problem**: Starting external services (WhatsApp, etc.) after the dev server would kill the frontend client.+- Root cause: `--kill-others` flag in concurrently npm script+- When uvicorn reloads (exit code 1), concurrently kills all processes including frontend++**Fix Applied**:+1. Removed `--kill-others` from `npm run dev` in package.json+2. Added named colored output: `-n client,python -c blue,green`+3. Added uvicorn reload controls: `--reload-dir .` and `--reload-exclude` patterns++**Result**: Frontend and backend run independently, uvicorn reloads don't cascade++### Temporal Distributed Execution (Optional)++When `TEMPORAL_ENABLED=true`, workflows execute via Temporal for durability and horizontal scaling.++**Architecture**: Each workflow node executes as an independent Temporal activity:+- **Per-node retry** - Failed nodes retry independently (up to 3 attempts)+- **Per-node timeout** - Long AI nodes don't block short nodes (10 min default)+- **Horizontal scaling** - Activities distributed across worker pool+- **Connection pooling** - Shared aiohttp session for WebSocket execution++**Configuration** (`.env`):+```env+TEMPORAL_ENABLED=true+TEMPORAL_SERVER_ADDRESS=localhost:7233+TEMPORAL_NAMESPACE=default+TEMPORAL_TASK_QUEUE=machina-tasks+```++**Start Temporal Server**:+```bash+docker run -d --name temporal-sqlite \+ -p 7233:7233 -p 8233:8233 \+ -v "d:/startup/projects/temporal/data:/data" \+ temporalio/temporal:latest server start-dev \+ --ip 0.0.0.0 --db-filename /data/temporal.db+```++**Execution Routing** (`workflow.py`):+1. If `TEMPORAL_ENABLED=true` and Temporal configured → `_execute_temporal()`+2. Else if Redis available → `_execute_parallel()` (local parallel)+3. Else → `_execute_sequential()` (fallback)++**Running with Temporal**:+The launch scripts auto-detect `TEMPORAL_ENABLED` from `.env`:+```bash+npm run start # Auto-starts temporal worker if TEMPORAL_ENABLED=true+npm run start:temporal # Explicit: sets TEMPORAL_ENABLED=true+npm run stop # Also kills Temporal worker processes+```++**Standalone Worker** (horizontal scaling):+```bash+cd server+python -m services.temporal.worker+```++**Key Files**:+- `services/temporal/workflow.py` - MachinaWorkflow orchestrator (FIRST_COMPLETED pattern)+- `services/temporal/activities.py` - Class-based activities with aiohttp pooling+- `services/temporal/worker.py` - TemporalWorkerManager + `run_standalone_worker()`+- `services/temporal/executor.py` - TemporalExecutor interface matching WorkflowExecutor+- `services/temporal/client.py` - Client wrapper with runtime heartbeat disabled++**Runtime Configuration**: Worker heartbeating is disabled via `Runtime(worker_heartbeat_interval=None)` to avoid warnings on older Temporal server versions.++**Temporal UI**: http://localhost:8233++## Development Commands++### CLI Commands (npx or global install)+```bash+npx machinaos start # Start all services+npx machinaos stop # Stop all services+npx machinaos build # Build for production+npx machinaos clean # Clean build artifacts+npx machinaos docker:up # Start with Docker+npx machinaos help # Show all commands+```++### npm Scripts+```bash+# Core+npm run start # Start all services (client, backend, WhatsApp)+npm run start:temporal # Start with Temporal worker+npm run stop # Stop all services+npm run build # Build for production+npm run clean # Clean build artifacts++# Docker (development)+npm run docker:up # Start dev stack+npm run docker:down # Stop dev stack+npm run docker:build # Build images+npm run docker:logs # View logs++# Docker (production)+npm run docker:prod:up # Start production+npm run docker:prod:down # Stop production+npm run deploy # Deploy to server+```++### Cross-Platform Scripts+All scripts in `scripts/` are cross-platform Node.js (Windows, macOS, Linux, WSL, Git Bash):+- `start.js` - Starts services, auto-installs deps, frees ports+- `stop.js` - Kills processes on configured ports+- `build.js` - Full production build (client, Python, WhatsApp)+- `clean.js` - Removes node_modules, dist, .venv+- `docker.js` - Docker Compose wrapper with Redis profile detection++See **[Scripts Reference](./docs-internal/SCRIPTS.md)** for full documentation.++## Current Status+✅ **INodeProperties System**: Fully implemented with 41 functional components+✅ **WebSocket-First Architecture**: 25 message handlers replacing REST APIs+✅ **Code Editor**: Python executor with syntax-highlighted editor (react-simple-code-editor + prismjs) and console output+✅ **Component Palette**: Emoji icons with distinct dracula-themed category colors, localStorage persistence for collapsed sections+✅ **Android Integration**: 16 Android service nodes with ADB automation and remote WebSocket support+✅ **Conditional Parameter Display**: Dynamic UI rendering based on parameter values (displayOptions.show)+✅ **Execution Engine**: Full component execution with result display+✅ **Parameter Mapping**: Drag-and-drop output to parameter connections+✅ **AI Integration**: API key management and model selection+✅ **Location Services**: Interactive map picker with coordinate handling, Google Maps API key fetched from backend credentials+✅ **Code Cleanup**: Dead code removed, unused files deleted+✅ **Process Management**: Robust stop scripts with duplicate process detection+✅ **WhatsApp Integration**: Square node design with QR code viewer, group/sender name persistence, and proper error handling+✅ **Backend Stability**: Fixed dependency injection and error handling preventing crashes+✅ **Development Server**: Running at **http://localhost:3001** (frontend) and **http://localhost:3010** (backend)+✅ **WebSocket Integration**: Persistent WebSocket connections for remote Android devices with background tasks and message queue+✅ **Real-time Status WebSocket**: Frontend-backend WebSocket at `/ws/status` for live Android status, node status, and variable updates+✅ **Event-Driven Trigger Nodes**: WhatsApp Receive and Webhook Trigger with asyncio.Future-based event waiting, filter builders, and cancel support+✅ **Continuous Scheduling Execution**: Temporal/Conductor pattern using `asyncio.wait(FIRST_COMPLETED)` for true parallel pipelines where dependent nodes start immediately when their specific dependency completes+✅ **Event-Driven Deployment**: n8n-style architecture where each trigger event spawns an independent, concurrent execution run (no iteration loop)+✅ **HTTP/Webhook Nodes**: HTTP Request for external APIs, Webhook Trigger for incoming requests, Webhook Response for custom responses+✅ **Theme System**: Solarized + Dracula dual-palette theming with dark mode support, vibrant action buttons, and themed React Flow edges+✅ **Modular Backend Architecture**: workflow.py refactored from 2068 to 460 lines using facade pattern with NodeExecutor, ParameterResolver, and DeploymentManager modules+✅ **Node Rename System**: n8n-style node renaming via F2 keyboard shortcut, double-click on label, or right-click context menu with inline editing+✅ **UI State Persistence**: localStorage persistence for sidebar visibility, component palette visibility, dev mode, and collapsed sections+✅ **Normal/Dev Mode**: Toggle in toolbar to filter Component Palette - Normal mode shows only AI Agents, Models, and Skills; Dev mode shows all categories+✅ **Production Deployment**: Docker Compose deployment (4 containers: Redis, Backend, Frontend, WhatsApp), nginx reverse proxy, and Let's Encrypt SSL+✅ **Authentication System**: n8n-style JWT authentication with HttpOnly cookies, single-owner and multi-user modes+✅ **Cache System**: n8n-pattern cache with Redis (production) / SQLite (local dev) / Memory fallback hierarchy+✅ **AI Thinking/Reasoning**: Extended thinking for Claude, Gemini 2.5/Flash Thinking, Groq Qwen3/QwQ with output available in Input Data & Variables for downstream nodes++## Key Features++### Parameter System+- **Universal Renderer**: Supports both INodeProperties and NodeParameter interfaces+- **Type-Specific Controls**: String, number, boolean, select, slider, file, array types+- **Drag-and-Drop**: Map outputs from connected nodes to parameters+- **Validation**: Required field checking and type constraints+- **Conditional Display**: Dynamic parameter visibility using displayOptions.show pattern+ - Implemented in `MiddleSection.tsx` with `shouldShowParameter()` function+ - Supports array-based conditions (e.g., `messageType: ['text']`)+ - Filters parameters before rendering based on other parameter values++### Node Rename System (n8n-style)+Three methods for renaming nodes, following n8n UX patterns:+- **F2 Keyboard Shortcut**: Press F2 with a node selected to enter rename mode+- **Double-click on Label**: Click the node label twice to edit inline+- **Right-click Context Menu**: "Rename" option in the context menu++#### Architecture+```+Global State (useAppStore) Node Components+├── renamingNodeId: string | null ├── SquareNode.tsx+├── setRenamingNodeId() ├── TriggerNode.tsx+ ↓ ├── GenericNode.tsx+ Coordinates which node └── StartNode.tsx+ is currently being renamed ↓+ Local State:+ ├── isRenaming: boolean+ ├── editLabel: string+ └── inputRef: HTMLInputElement+```++#### Implementation Files+- **`client/src/store/useAppStore.ts`** - Global rename state (`renamingNodeId`, `setRenamingNodeId`)+- **`client/src/components/ui/NodeContextMenu.tsx`** - Right-click menu with Rename, Copy, Delete+- **`client/src/Dashboard.tsx`** - Context menu handler, F2 keyboard handler+- **`client/src/components/SquareNode.tsx`** - Inline rename for square nodes (Android, WhatsApp)+- **`client/src/components/TriggerNode.tsx`** - Inline rename for trigger nodes+- **`client/src/components/GenericNode.tsx`** - Inline rename for generic colored nodes+- **`client/src/components/StartNode.tsx`** - Inline rename with label support (was hardcoded "Start")++#### Key Pattern (shared by all node components)+```typescript+// 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]);++// Handle save - only save if changed and non-empty+const handleSaveRename = useCallback(() => {+ const newLabel = editLabel.trim();+ if (newLabel && newLabel !== originalLabel) {+ updateNodeData(id, { ...data, label: newLabel });+ }+ setIsRenaming(false);+ setRenamingNodeId(null);+}, [...]);+```++#### NodeContextMenu Features+- Rename (F2), Copy (Ctrl+C), Delete (Del) with keyboard shortcuts shown+- Uses existing `useCopyPaste.copySelectedNodes()` for Copy+- Uses existing `onNodesDelete` for Delete+- Keyboard navigation (Arrow keys, Enter)+- Click outside to close+- Dracula-themed styling++### UI State Persistence+The application persists UI state to localStorage for a consistent user experience across sessions:++#### Persisted Settings+| Setting | Storage Key | Default | Location |+|---------|-------------|---------|----------|+| Sidebar visibility | `ui_sidebar_visible` | `true` | `useAppStore.ts` |+| Component palette visibility | `ui_component_palette_visible` | `true` | `useAppStore.ts` |+| Pro mode | `ui_pro_mode` | `false` | `useAppStore.ts` |+| Collapsed palette sections | `component_palette_collapsed_sections` | All collapsed | `useComponentPalette.ts` |++#### Implementation Pattern+```typescript+// In useAppStore.ts+const STORAGE_KEYS = {+ sidebarVisible: 'ui_sidebar_visible',+ componentPaletteVisible: 'ui_component_palette_visible',+};++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;+};++// Initial state loads from localStorage+sidebarVisible: loadBooleanFromStorage(STORAGE_KEYS.sidebarVisible, true),++// Toggle functions save to localStorage+toggleSidebar: () => {+ set((state) => {+ const newValue = !state.sidebarVisible;+ saveBooleanToStorage(STORAGE_KEYS.sidebarVisible, newValue);+ return { sidebarVisible: newValue };+ });+},+```++### Normal/Dev Mode Toggle+The toolbar includes a mode toggle that filters the Component Palette for different user experience levels:++| Mode | Description | Visible Categories |+|------|-------------|-------------------|+| **Normal** (default) | Simplified view for AI-focused workflows | AI Agents, AI Models, AI Skills, AI Abilities, AI Tools |+| **Dev** | Full access to all node types | All categories |++#### Implementation+- **State**: `proMode` boolean in `useAppStore.ts` with localStorage persistence (internal name unchanged for compatibility)+- **Toggle UI**: Segmented control in toolbar with "Normal" and "Dev" labels+- **Filtering**: `ComponentPalette.tsx` filters by `SIMPLE_MODE_CATEGORIES = ['agent', 'model', 'skill', 'tool']`+- **Category Merging**: WhatsApp and social nodes are merged into "Social Media Platforms" category via `SOCIAL_CATEGORIES = ['whatsapp', 'social']`++```typescript+// In ComponentPalette.tsx+const SIMPLE_MODE_CATEGORIES = ['agent', 'model', 'skill', 'tool'];+const SOCIAL_CATEGORIES = ['whatsapp', 'social'];++// Filter nodes based on mode+if (!proMode) { // proMode=false means Normal mode+ const categoryKey = (definition.group?.[0] || '').toLowerCase();+ if (!SIMPLE_MODE_CATEGORIES.includes(categoryKey)) {+ return false;+ }+}++// Merge whatsapp and social categories+if (SOCIAL_CATEGORIES.includes(categoryKey.toLowerCase())) {+ categoryKey = 'social';+}+```++### Console Panel+The Console Panel provides a resizable bottom panel with three sections: Chat (AI conversation), Console (node execution logs), and Terminal (planned).++#### Features+- **Resizable**: Drag handle at top to resize, persisted to localStorage+- **Three Tabs**: Chat, Console, Terminal (placeholder)+- **Chat Section**: Send messages to Chat Trigger nodes, view conversation history+- **Console Section**: View and filter node execution logs++#### Node Selector Dropdowns+When multiple chatTrigger or console nodes exist in the workflow, dropdowns appear to select which node to target:++| Selector | Location | Behavior |+|----------|----------|----------|+| Chat Trigger | Chat section header | Select which chatTrigger node receives messages. "All" broadcasts to all triggers |+| Console | Console section controls | Filter logs to show only output from selected console node |++**Implementation** (`client/src/components/ui/ConsolePanel.tsx`):+```typescript+// Node type constants for filtering+const CHAT_TRIGGER_TYPES = ['chatTrigger'];+const CONSOLE_NODE_TYPES = ['console'];++// Filter workflow nodes+const chatTriggerNodes = useMemo(() =>+ nodes.filter(n => CHAT_TRIGGER_TYPES.includes(n.type || '')),+ [nodes]+);+const consoleNodes = useMemo(() =>+ nodes.filter(n => CONSOLE_NODE_TYPES.includes(n.type || '')),+ [nodes]+);++// State for selected nodes+const [selectedChatTriggerId, setSelectedChatTriggerId] = useState<string>('');+const [selectedConsoleId, setSelectedConsoleId] = useState<string>('');+```++#### Chat Message Persistence+Chat messages are persisted to SQLite database and survive server restarts.++**Database Model** (`server/models/database.py`):+```python+class ChatMessage(SQLModel, table=True):+ __tablename__ = "chat_messages"+ id: Optional[int] = Field(default=None, primary_key=True)+ session_id: str = Field(default="default", index=True, max_length=255)+ role: str = Field(max_length=20) # 'user' or 'assistant'+ message: str = Field(max_length=50000)+ created_at: datetime+```++**WebSocket Handlers** (`server/routers/websocket.py`):+| Handler | Description |+|---------|-------------|+| `send_chat_message` | Send message to chat, optionally targeting specific node via `node_id` |+| `get_chat_messages` | Retrieve chat history for session |+| `clear_chat_messages` | Clear all messages for session |++**Database Methods** (`server/core/database.py`):+- `add_chat_message(session_id, role, message)` - Add message to database+- `get_chat_messages(session_id, limit)` - Get messages with pagination+- `clear_chat_messages(session_id)` - Delete all messages for session++#### Console Log Persistence+Console logs are persisted to SQLite database and loaded on page refresh.++**WebSocket Handlers**:+| Handler | Description |+|---------|-------------|+| `get_console_logs` | Retrieve console logs from database (limit: 100) |+| `clear_console_logs` | Clear all console logs from database |++**Database Methods** (`server/core/database.py`):+- `add_console_log(log_data)` - Add console log to database+- `get_console_logs(limit)` - Get console logs+- `clear_console_logs()` - Delete all console logs++#### Key Files+| File | Description |+|------|-------------|+| `client/src/components/ui/ConsolePanel.tsx` | Main panel component with chat/console/terminal tabs |+| `server/models/database.py` | ChatMessage and ConsoleLog SQLModel definitions |+| `server/core/database.py` | Chat message and console log CRUD methods |+| `server/routers/websocket.py` | WebSocket handlers for chat and console operations |++### Execution System+- **Supported Components**: AI models, location services, Android automation, WhatsApp messaging, HTTP requests, webhooks+- **Android Integration**: ADB-based device control with 17 service nodes across monitoring, apps, automation, sensors, and media+- **Result Display**: Formatted output panel with success/error states+- **Performance Metrics**: Execution time and status tracking+- **Error Handling**: Comprehensive error reporting and logging+- **Dynamic Options**: Load options from backend (e.g., Android device list, service actions)+- **Continuous Scheduling**: Temporal/Conductor pattern using `asyncio.wait(FIRST_COMPLETED)` - dependent nodes start immediately when their specific dependency completes+- **Event-Driven Deployment**: n8n-style architecture where triggers spawn independent concurrent execution runs (no iteration loop)++### Event-Driven Deployment Architecture (n8n Pattern)+The deployment system follows modern workflow engine patterns from n8n, Temporal, and Conductor:++```+deploy_workflow() -> Sets up triggers, returns immediately+ |+ +-> cronScheduler fires -> spawns ExecutionRun 1+ +-> cronScheduler fires -> spawns ExecutionRun 2 (concurrent)+ +-> whatsappReceive fires -> spawns ExecutionRun 3 (concurrent)+ +-> webhookTrigger fires -> spawns ExecutionRun 4 (concurrent)+```++**Key Concepts:**+- **Workflow Template**: The deployed workflow is a template stored in memory+- **Execution Run**: Each trigger event spawns an independent, isolated run+- **Concurrent Runs**: Multiple runs execute simultaneously without interference+- **No Iteration Loop**: Purely event-driven, not polling or sequential iterations+- **Pre-Executed Triggers**: Trigger nodes are marked complete before downstream execution++**Implementation Files:**+- `server/services/workflow.py`: Thin facade (~460 lines) delegating to specialized modules+- `server/services/node_executor.py`: Single node execution with registry-based dispatch+- `server/services/parameter_resolver.py`: Template variable resolution (`{{node.field}}`)+- `server/services/deployment/manager.py`: Deployment lifecycle, spawn runs, cancel+- `server/services/deployment/triggers.py`: Cron and event trigger management+- `server/services/deployment/state.py`: DeploymentState, TriggerInfo dataclasses+- `server/services/execution/models.py`: `ExecutionContext.create()` with `_pre_executed` support+- `server/services/execution/executor.py`: Continuous scheduling with `asyncio.wait(FIRST_COMPLETED)`++### AI Chat Model System (5-Layer Architecture)+- **Visual Components**: Circular node design with real-time status indicators (green/yellow/red)+- **Node Definitions**: Factory pattern using `createBaseChatModel()` with provider configurations+- **Parameter System**: Universal renderer with drag-and-drop template variables (`{{variable}}`)+- **API Key Management**: Secure localStorage with base64 encryption and LangChain validation+- **Execution Engine**: Routes AI nodes to Python Flask backend with auto-injection of API keys++#### Supported AI Providers & Models+- **OpenAI**: GPT-4o, GPT-4 Turbo, GPT-3.5 Turbo with response format options. O-series (o1, o3, o4) with reasoning effort.+- **Anthropic**: Claude 3.5 Sonnet/Haiku, Claude 3 Opus with extended thinking support (thinkingBudget parameter)+- **Google**: Gemini 2.5 Pro/Flash, Gemini 2.0 Flash Thinking with thinking_budget parameter and safety settings+- **Groq**: Ultra-fast Llama, Mixtral, Gemma models. Qwen3/QwQ with reasoning_format parameter.+- **Cerebras**: Ultra-fast Llama and Qwen models on custom AI hardware with thinking support++#### Key Features+- Visual configuration with status indicators and parameter buttons+- Template variable system for dynamic parameter binding from connected nodes+- Provider-specific parameter sets (temperature, max tokens, penalties, safety settings)+- Secure API key validation with automatic model discovery and 30-day expiration+- Execution routing to Python Flask backend for AI model processing+- **Proxy-based authentication** for routing through local servers (Ollama pattern)++#### Proxy-Based Authentication (Ollama Pattern)+AI providers support optional proxy-based authentication, allowing requests to route through a local proxy server that handles authentication. This follows the [Ollama Claude Code integration](https://docs.ollama.com/integrations/claude-code) pattern.++**How it works:**+1. User configures a proxy URL in the Credentials Modal (e.g., `http://localhost:11434`)+2. Requests route through the proxy instead of directly to the provider API+3. Proxy handles authentication (token set to "ollama" automatically)+4. No API key storage needed in MachinaOs - auth delegated to proxy++**Configuration:**+- Proxy URLs stored in database via `{provider}_proxy` pattern (e.g., `anthropic_proxy`, `openai_proxy`)+- Configured in Credentials Modal under each AI provider+- Falls back to direct API key if no proxy configured++**Key Files:**+| File | Description |+|------|-------------|+| `server/services/ai.py` | `create_model()` accepts `proxy_url` parameter, sets `base_url` and token |+| `client/src/components/CredentialsModal.tsx` | Proxy URL input for AI providers |++**Backend Implementation** (`server/services/ai.py`):+```python+def create_model(self, provider: str, api_key: str, model: str,+ temperature: float, max_tokens: int,+ thinking: Optional[ThinkingConfig] = None,+ proxy_url: Optional[str] = None):+ # ...+ if proxy_url:+ kwargs['base_url'] = proxy_url+ kwargs[config.api_key_param] = "ollama" # Ollama-style token+```++**Use Cases:**+- Claude Code CLI proxy for Anthropic models+- Ollama for local model serving+- Custom authentication proxies+- Development/testing with mock servers++## AI Chat Model Implementation Details++### Component Architecture+1. **BaseChatModelNode** (`src/components/base/BaseChatModelNode.tsx`): Unified circular design with provider props+2. **Provider Components**: Thin wrappers passing provider-specific configuration to base component+3. **ModelNode** (`src/components/ModelNode.tsx`): Generic component with automatic provider detection+4. **Factory Pattern**: `createBaseChatModel()` generates standardized node definitions from configs++### API Key Management (`src/services/apiKeyManager.ts`)+- **Validation**: Uses LangChain for real API testing with provider-specific chat models+- **Storage**: localStorage with base64 encryption and key hashing for security+- **Models**: Automatic discovery and caching of available models per provider+- **Expiration**: 30-day validation period with automatic cleanup++### Execution Flow (`src/services/executionService.ts:387`)+- **Detection**: `isAIModelNode()` identifies AI chat models for Python routing+- **Enhancement**: `injectStoredApiKeys()` auto-injects stored credentials and models+- **Routing**: AI nodes → Python Flask backend, other nodes → Node.js backend+- **Logging**: Comprehensive debug output for API key injection and model selection++### Parameter System Integration+- **Template Variables**: Support for `{{nodeId.output}}` syntax in all text parameters+- **Drag-and-Drop**: Visual parameter mapping from connected node outputs+- **Type-Specific**: Provider-specific parameters (OpenAI response format, Gemini safety settings)+- **Validation**: Real-time parameter validation with visual feedback++### AI Thinking/Reasoning System+Extended thinking and reasoning capabilities for supported AI models. When enabled, the model's internal reasoning process is captured and available for downstream nodes.++#### Supported Providers & Configuration++| Provider | Models | Parameter | Notes |+|----------|--------|-----------|-------|+| **Claude** | claude-3-5-sonnet, claude-3-opus | `thinkingBudget` (1024-16000 tokens) | Requires `max_tokens > budget_tokens`. Temperature auto-set to 1. |+| **Gemini** | gemini-2.5-flash, gemini-2.5-pro, gemini-2.0-flash-thinking | `thinkingBudget` (token count) | Uses `thinking_budget` API parameter |+| **Groq** | qwen3-32b, qwq-32b | `reasoningFormat` ('parsed' or 'hidden') | 'parsed' returns reasoning, 'hidden' returns only final answer |+| **OpenAI** | o1, o3, o4 series | `reasoningEffort` (minimal/low/medium/high) | Reasoning summaries require organization verification at platform.openai.com |++#### Frontend Parameters (`client/src/factories/baseChatModelFactory.ts`)+```typescript+STANDARD_PARAMETERS = {+ thinkingEnabled: {+ displayName: 'Thinking/Reasoning Mode',+ name: 'thinkingEnabled',+ type: 'boolean',+ default: false,+ description: 'Enable extended thinking for supported models'+ },+ thinkingBudget: {+ displayName: 'Thinking Budget (Tokens)',+ name: 'thinkingBudget',+ type: 'number',+ default: 2048,+ typeOptions: { minValue: 1024, maxValue: 16000 },+ displayOptions: { show: { thinkingEnabled: [true] } }+ },+ reasoningEffort: {+ displayName: 'Reasoning Effort',+ name: 'reasoningEffort',+ type: 'options',+ options: ['minimal', 'low', 'medium', 'high'],+ default: 'medium',+ displayOptions: { show: { thinkingEnabled: [true] } }+ },+ reasoningFormat: {+ displayName: 'Reasoning Format',+ name: 'reasoningFormat',+ type: 'options',+ options: ['parsed', 'hidden'],+ default: 'parsed',+ displayOptions: { show: { thinkingEnabled: [true] } }+ }+}+```++#### Backend Implementation (`server/services/ai.py`)+The AI service extracts thinking content from LangChain response objects:++```python+def extract_thinking_from_response(response, provider: str) -> Optional[str]:+ """Extract thinking/reasoning from AI response based on provider."""+ # Claude: content_blocks with type='thinking'+ # Gemini: response_metadata.candidates[0].content.parts with thought=True+ # Groq: additional_kwargs.reasoning or response_metadata.reasoning+ # OpenAI o-series: requires organization verification+```++**Response Structure:**+```python+{+ "success": True,+ "result": {+ "response": "The final answer text",+ "thinking": "The model's internal reasoning (if available)",+ "model": "claude-3-5-sonnet-20241022",+ "provider": "anthropic",+ "finish_reason": "stop",+ "timestamp": "2025-01-23T..."+ }+}+```++#### Output Schema for Connected Nodes+The `thinking` field is available in Input Data & Variables for downstream nodes. This schema applies to all AI nodes including chat models and specialized agents.++```typescript+// In InputSection.tsx+const sampleSchemas = {+ ai: {+ response: 'string',+ thinking: 'string', // Available for drag-and-drop mapping+ model: 'string',+ provider: 'string',+ finish_reason: 'string',+ timestamp: 'string'+ }+};++// Node types that use the AI output schema+const aiAgentTypes = [+ 'aiAgent', 'chatAgent',+ 'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent' // Specialized agents+];+const isAI = nodeTypeLower.includes('chatmodel') || aiAgentTypes.includes(nodeType);+```++#### UI Display (`client/src/components/ui/NodeOutputPanel.tsx`)+- **ThinkingBlock Component**: Collapsible display for thinking content+- **Default Expanded**: Thinking block is expanded by default when present+- **Provider-Aware**: Shows appropriate label based on provider (e.g., "Claude Extended Thinking")++#### Limitations+- **OpenAI o-series**: Reasoning summaries are only available to organizations that have completed verification at platform.openai.com. Without verification, `thinking` will be `null`.+- **Claude**: `max_tokens` must be greater than `thinkingBudget`. Temperature is automatically set to 1 when thinking is enabled.+- **Groq**: Only Qwen3 and QwQ models support reasoning. Format 'hidden' suppresses reasoning output.++## AI Agent Node Architecture++### Config-Driven Component Design+The `AIAgentNode.tsx` component uses a configuration-driven pattern to support multiple agent types from a single component.++#### AGENT_CONFIGS Object+```typescript+interface AgentConfig {+ icon: React.ReactNode; // Lucide-style SVG icons+ title: string;+ subtitle: string;+ accentColor: string;+ bottomHandles: Array<{ id: string; label: string; position: string }>;+}++// Lucide-style SVG icons defined as React components+const RobotIcon = ({ size, color }) => <svg>...</svg>; // Robot with antenna+const ZeenieIcon = ({ size, color }) => <svg>...</svg>; // MessageSquare bubble++const AGENT_CONFIGS: Record<string, AgentConfig> = {+ aiAgent: {+ icon: <RobotIcon />,+ title: 'AI Agent',+ subtitle: 'LangGraph Agent',+ accentColor: '#9333EA', // Purple+ bottomHandles: [+ { id: 'input-memory', label: 'Memory', position: '35%' },+ { id: 'input-tools', label: 'Tool', position: '65%' },+ ],+ },+ chatAgent: {+ icon: <ZeenieIcon />,+ title: 'Zeenie',+ subtitle: 'Conversational Agent',+ accentColor: '#3B82F6', // Blue+ bottomHandles: [+ { id: 'input-memory', label: 'Memory', position: '35%' },+ { id: 'input-skill', label: 'Skill', position: '65%' },+ ],+ },+};+```++#### Component Selection+In `Dashboard.tsx`, both agent types map to the same component:+```typescript+} else if (type === 'aiAgent' || type === 'chatAgent') {+ types[type] = AIAgentNode;+}+```++### AI Agent vs Zeenie++| Feature | AI Agent | Zeenie |+|---------|----------|------------|+| Tool Calling | Yes (LangGraph) | Yes (LangGraph) |+| Memory Support | Yes | Yes |+| Skill Support | Yes | Yes |+| Bottom Handles | Skill, Tools | Skill, Tools |+| Left Handles | Input, Memory | Input, Memory |+| Backend Method | `execute_agent()` | `execute_chat_agent()` |+| Async Delegation | Yes (fire-and-forget) | Yes (fire-and-forget) |++### Unified Tool Calling Architecture++Both AI Agent and Zeenie use the **same tool calling pattern**:++1. **Tool Building**: Both use `_build_tool_from_node()` to create schema-only tools+2. **Tool Execution**: Both use `execute_tool()` from `handlers/tools.py`+3. **Supported Tools**: `calculatorTool`, `currentTimeTool`, `webSearchTool`, `androidTool`, `httpRequest`++**Tool Execution Flow:**+```+Tool Node (connected to input-tools)+ ↓+Handler collects tool_data: {node_id, node_type, parameters, label, connected_services}+ ↓+AIService._build_tool_from_node() → creates schema-only StructuredTool+ ↓+LangGraph binds tools to LLM+ ↓+LLM decides to call tool with arguments+ ↓+tool_executor callback → execute_tool() from handlers/tools.py+ ↓+Dispatch to handler: _execute_http_request(), _execute_calculator(), etc.+```++**Key Files:**+| File | Purpose |+|------|---------|+| `server/services/ai.py` | `_build_tool_from_node()` - builds schema-only tools for both agents |+| `server/services/handlers/tools.py` | `execute_tool()` - dispatches to specific handlers |+| `server/services/handlers/ai.py` | Collects `tool_data` from `input-tools` handle |++### Zeenie Input Methods++Zeenie accepts input in two ways:++1. **Template Variable (Explicit)**: Set the Prompt field to `{{chatTrigger.message}}` or `{{whatsappReceive.text}}`+ - Templates are resolved by `ParameterResolver` before handler execution+ - Supports nested paths: `{{nodeName.nested.field}}`++2. **Auto-Fallback (Implicit)**: Leave the Prompt field empty+ - Handler detects nodes connected to `input-main` handle+ - Reads output from `context.get('outputs', {}).get(source_node_id)`+ - Extracts text from `message`, `text`, `content` fields (in order)+ - Falls back to string representation of entire output++**Example Workflow:**+```+Chat Trigger → Zeenie ← HTTP Skill (SKILL.md context)+ ← HTTP Request (tool node)+```++The Zeenie will:+- Load SKILL.md instructions from connected skill nodes+- Build tools from connected tool nodes (httpRequest, calculatorTool, etc.)+- Use LangGraph for tool execution when tools are connected++### Backend Handlers+Both agents have dedicated handlers in `server/services/handlers/ai.py`:+- `handle_ai_agent()` - Collects memory, skill, and tool data from connected nodes+- `handle_chat_agent()` - Collects memory, skill, tool, and input data from connected nodes++Both use the shared `_collect_agent_connections()` base function that:+- Scans edges for nodes connected to `input-memory`, `input-skill`, `input-tools`, `input-main`/`input-chat` handles+- Returns a 4-tuple: `(memory_data, skill_data, tool_data, input_data)`+- Handles MasterSkill expansion into individual skill entries++Both call corresponding AI service methods:+- `AIService.execute_agent()` - Full LangGraph execution with tool binding+- `AIService.execute_chat_agent()` - LangGraph execution with skills providing context + tools++### Async Agent Delegation (Nested Agents)++AI Agents can delegate tasks to other agents connected to their `input-tools` handle. This enables hierarchical agent architectures where a parent agent can spawn child agents that work independently.++**Architecture: Fire-and-Forget Pattern**+```+Parent Agent calls "delegate_to_ai_agent" tool+ |+Tool handler spawns asyncio.Task for Child Agent+ |+Returns immediately: {"status": "delegated", "task_id": "..."}+ |+Parent Agent continues working+ |+Child Agent executes independently in background+ |+Child broadcasts its own status updates (executing, success, error)+```++**How It Works:**+1. Connect a Child Agent (aiAgent/chatAgent) to Parent Agent's `input-tools` handle+2. Parent sees a tool like `delegate_to_ai_agent` with schema `{task: string, context?: string}`+3. When Parent calls the tool, handler spawns Child as `asyncio.create_task()`+4. Tool returns immediately with `{"status": "delegated", "task_id": "..."}`+5. Parent continues without waiting+6. Child executes with its own connected tools, skills, and memory+7. Both agents can execute simultaneously with independent status indicators++**Key Files:**+| File | Purpose |+|------|---------|+| `server/services/ai.py` | `DelegateToAgentSchema` in `_get_tool_schema()`, injects `ai_service`, `database`, `nodes`, `edges` into tool config |+| `server/services/handlers/tools.py` | `_execute_delegated_agent()` - spawns child as background task, `get_delegated_task_status()` utility |+| `server/services/handlers/ai.py` | Passes `context` to `execute_agent()`/`execute_chat_agent()` for nested delegation |++**Design Decisions:**+- **Memory Isolation**: Child uses its own connected memory, not shared with Parent+- **Error Isolation**: Child errors don't propagate to Parent - logged and broadcast independently+- **Task Tracking**: Background tasks tracked in `_delegated_tasks` dict, cleaned up on completion++### Specialized AI Agents++The system supports specialized agent variants that inherit from the base AI Agent architecture:++| Agent Type | Node Type | Purpose | Theme Color |+|------------|-----------|---------|-------------|+| AI Agent | `aiAgent` | General-purpose LangGraph agent | Purple |+| Zeenie | `chatAgent` | Personal assistant with skills | Cyan |+| Android Control | `android_agent` | Device automation | Green |+| Coding Agent | `coding_agent` | Code execution | Cyan |+| Web Control | `web_agent` | Browser automation | Pink |+| Task Management | `task_agent` | Task automation | Purple |+| Social Media | `social_agent` | Social messaging | Green |++All specialized agents share the same handle configuration:+- **Left**: `input-main` (Input), `input-memory` (Memory)+- **Bottom**: `input-skill` (Skill), `input-tools` (Tool)+- **Top**: `output-top` (Output)++The `AIAgentNode.tsx` component uses `AGENT_CONFIGS` to render all agent types with their specific icons, titles, and theme colors.++## Architecture Patterns+- **Resource-Operation Pattern**: Nodes organized by functional resources+- **TypeScript-First**: 90.4% TypeScript coverage with strict typing+- **Component-Driven**: Modular UI components with clear responsibilities+- **State Management**: Zustand for reactive application state+- **Interface Compatibility**: Dual interface support for smooth transitions+- **Execution Pipeline**: Async component execution with result handling++## File Structure Cleanup+**Removed Files:**+- `src/nodeDefinitions.backup.ts` (backup file)+- `src/schemas/` directory (unused schema system)+- `src/utils/schemaParser.ts` (legacy parser)+- `src/utils/nodeSchemaParser.ts` (unused modern parser)+- `src/types/NodeSchema.ts` (legacy schema types)++**Cleaned Code:**+- Removed unused imports and dead functions+- Eliminated legacy NodeDefinition interface+- Streamlined parameter handling logic+- Maintained backward compatibility only where actively used++## Testing & Validation+```bash+# Development server test+curl -I http://localhost:3001++# TypeScript validation+npx tsc --noEmit++# Build verification+npm run build++# Test WebSocket connection for remote Android devices+python test_websocket.py+```++### WebSocket Testing (`test_websocket.py`)+- Tests health endpoint configured via `WEBSOCKET_URL` environment variable+- Tests stats endpoint+- Tests WebSocket connection+- Validates connection establishment and ping/pong messaging+- Comprehensive test results with pass/fail status++## Production Deployment++### Docker Deployment+The project deploys using Docker Compose with nginx reverse proxy.++#### Deploy Script (`deploy.sh`)+```bash+# Deploy to server (configure DEPLOY_HOST in .env)+./deploy.sh [HOST]+```++**Deployment Steps:**+1. Build Docker images locally (`docker-compose -f docker-compose.prod.yml build`)+2. Save and compress images (`docker save | gzip`)+3. Upload to GCP via SCP+4. Deploy on remote (`docker-compose up -d`)+5. Configure nginx reverse proxy with SSL+6. Auto-cleanup dangling Docker images++#### Docker Configuration (4-Container Stack)++**Services:**+| Container | Image | Port | Description |+|-----------|-------|------|-------------|+| redis | redis:7-alpine | 6379 | Cache and pub/sub for workflows |+| backend | machinaos-backend | 3010 | FastAPI Python backend |+| frontend | machinaos-frontend | 3000 | React app via nginx |+| whatsapp | machinaos-whatsapp | 5000 | Go WhatsApp bridge service |++**Frontend (`client/Dockerfile`):**+- Multi-stage build: Node.js builder → nginx:alpine production+- Serves static files via nginx on port 80 (mapped to 3000)+- Size: ~54 MB++**Backend (`server/Dockerfile`):**+- Python 3.12-slim base+- Optimized bytecode compilation (`python -O -m compileall`)+- Health check endpoint on port 3010+- Depends on: redis, whatsapp+- Size: ~528 MB++**WhatsApp (`whatsapp/Dockerfile`):**+- Multi-stage Go build with CGO for SQLite+- whatsmeow library for WhatsApp Web protocol+- Health check endpoint on port 5000+- Size: ~25 MB++**Redis:**+- Official redis:7-alpine image+- Healthcheck: `redis-cli ping`+- Persistent volume: `redis_data`+- No authentication (internal network only)++**Development Compose (`docker-compose.yml`):**+```yaml+services:+ # Redis uses profiles - only starts when REDIS_ENABLED=true+ redis:+ image: redis:7-alpine+ profiles:+ - redis # Only starts with --profile redis flag+ ports: ["${REDIS_PORT:-6379}:6379"]+ healthcheck:+ test: ["CMD", "redis-cli", "ping"]++ backend:+ build: ./server+ ports: ["${PYTHON_BACKEND_PORT:-3010}:${PYTHON_BACKEND_PORT:-3010}"]+ depends_on:+ whatsapp: { condition: service_healthy } # No Redis dependency+ environment:+ - REDIS_ENABLED=${REDIS_ENABLED:-false}+ - REDIS_URL=redis://redis:6379++ frontend:+ build: ./client+ ports: ["${VITE_CLIENT_PORT:-3000}:${VITE_CLIENT_PORT:-3000}"]++ whatsapp:+ build: ./server/whatsapp-rpc+ ports: ["${WHATSAPP_RPC_PORT:-9400}:${WHATSAPP_RPC_PORT:-9400}"]+```++**Docker Scripts Wrapper (`scripts/docker.js`):**+Auto-detects `REDIS_ENABLED` in `.env` and adds `--profile redis` flag when enabled:+```javascript+// Reads .env and checks REDIS_ENABLED value+function isRedisEnabled() {+ const content = readFileSync(resolve(ROOT, '.env'), 'utf8');+ const match = content.match(/^REDIS_ENABLED\s*=\s*(.+)$/m);+ const value = match?.[1].trim().toLowerCase();+ return value === 'true' || value === '1' || value === 'yes';+}++// Adds --profile redis when enabled+if (isRedisEnabled()) {+ composeArgs.push('--profile', 'redis');+}+```++**Production Compose (`docker-compose.prod.yml`):**+```yaml+services:+ redis:+ image: redis:7-alpine+ ports: ["6379:6379"]+ volumes: ["redis_data:/data"]+ healthcheck:+ test: ["CMD", "redis-cli", "ping"]++ whatsapp:+ build: ./whatsapp+ ports: ["5000:5000"]+ healthcheck:+ test: ["CMD", "wget", "-q", "--spider", "http://localhost:5000/health"]++ backend:+ build: ./server+ ports: ["3010:3010"]+ depends_on:+ redis: { condition: service_healthy }+ whatsapp: { condition: service_healthy }+ environment:+ - REDIS_ENABLED=true+ - REDIS_URL=redis://redis:6379++ frontend:+ build: ./client+ ports: ["3000:80"]+```++#### Nginx Configuration+Located at `/etc/nginx/sites-available/flow.zeenie.xyz`:+- Frontend: `/` → `http://127.0.0.1:3000`+- Backend API: `/api/` → `http://127.0.0.1:3010/api/`+- WebSocket: `/ws/` → `http://127.0.0.1:3010/ws/` (with upgrade headers)+- Webhook: `/webhook/` → `http://127.0.0.1:3010/webhook/`+- Health: `/health` → `http://127.0.0.1:3010/health`+- SSL via Let's Encrypt certbot++#### Environment Configuration++**Development** (`server/.env`):+- `DEBUG=true`+- `CORS_ORIGINS` includes localhost ports+- `REDIS_ENABLED=false` (uses SQLite cache for local dev)++**Production** (Docker environment variables):+- `DEBUG=false`+- `CORS_ORIGINS=["https://your-domain.com"]`+- `REDIS_ENABLED=true` (Docker Redis container)+- `REDIS_URL=redis://redis:6379`+- Environment set in `docker-compose.prod.yml`, not `.env` file++#### Frontend API URL Resolution+The frontend automatically detects production vs development:++```typescript+// client/src/config/api.ts+const isProduction = typeof window !== 'undefined' &&+ !window.location.hostname.includes('localhost') &&+ !window.location.hostname.includes('127.0.0.1');++return {+ PYTHON_BASE_URL: isProduction ? '' : 'http://localhost:3010',+};+```++- **Production**: Empty base URL = relative URLs (same origin)+- **Development**: Explicit `http://localhost:3010`++WebSocket URL derived from base URL:+```typescript+// client/src/contexts/WebSocketContext.tsx+if (!baseUrl) {+ // Production: use current origin+ const wsProtocol = window.location.protocol === 'https:' ? 'wss' : 'ws';+ return `${wsProtocol}://${window.location.host}/ws/status`;+}+```++#### Resource Usage (GCP e2-micro)+| Resource | Value |+|----------|-------|+| CPU | 2 cores (Intel Xeon @ 2.20GHz) |+| RAM | 1.9 GB total, ~820 MB used |+| Disk | 14 GB total, ~9.2 GB used |+| Backend Memory | ~144 MB |+| Frontend Memory | ~3.4 MB |++#### Useful Commands+```bash+# View logs (all containers)+ssh $DEPLOY_HOST 'cd /opt/machinaos && docker-compose logs -f'++# View specific service logs+ssh $DEPLOY_HOST 'cd /opt/machinaos && docker-compose logs -f backend'+ssh $DEPLOY_HOST 'cd /opt/machinaos && docker-compose logs -f whatsapp'++# Restart all services+ssh $DEPLOY_HOST 'cd /opt/machinaos && docker-compose restart'++# Restart specific service+ssh $DEPLOY_HOST 'cd /opt/machinaos && docker-compose restart backend'++# Check container status+ssh $DEPLOY_HOST 'docker ps'++# Check resource usage+ssh $DEPLOY_HOST 'docker stats --no-stream'++# Check Redis connection+ssh $DEPLOY_HOST 'docker exec machinaos-redis-1 redis-cli ping'++# Check backend health (shows redis_enabled status)+curl -s https://$DEPLOY_DOMAIN/health | jq++# Clean up Docker resources (if disk full)+ssh $DEPLOY_HOST 'docker system prune -af && docker builder prune -af'+```++### Local Docker Development+For testing the full production stack locally:++```bash+# Build and start all containers+docker-compose -f docker-compose.prod.yml up --build++# Access locally+# Frontend: http://localhost:3000+# Backend API: http://localhost:3010+# WhatsApp: http://localhost:5000+# Redis: localhost:6379++# Stop all containers+docker-compose -f docker-compose.prod.yml down++# Remove volumes (clean slate)+docker-compose -f docker-compose.prod.yml down -v+```++### Local Development Build+```bash+# Create optimized build+npm run build++# Serve built files locally+npm run preview+```++## Authentication System++### Overview+n8n-inspired authentication system with JWT tokens stored in HttpOnly cookies. Authentication can be completely disabled for development or supports two deployment modes for different use cases.++### Authentication Toggle+| Setting | Environment Variable | Description |+|---------|---------------------|-------------|+| **Enabled** | `VITE_AUTH_ENABLED=true` | Require login (default) |+| **Disabled** | `VITE_AUTH_ENABLED=false` | Bypass authentication, anonymous access |++When `VITE_AUTH_ENABLED=false`:+- Frontend skips login page entirely+- User is set to anonymous with owner privileges+- No backend auth API calls are made+- Useful for local development and testing++### Deployment Modes (when auth enabled)+| Mode | Environment Variable | Description |+|------|---------------------|-------------|+| **Single Owner** | `AUTH_MODE=single` | First user becomes owner, registration disabled after |+| **Multi User** | `AUTH_MODE=multi` | Open registration for cloud deployments |++### Architecture+```+Frontend (LoginPage.tsx) → AuthContext → Backend (/api/auth/*) → JWT Cookie+ ↓+ AuthMiddleware+ ↓+ Protected Routes+```++### Backend Implementation++#### User Model (`server/models/auth.py`)+```python+class User(SQLModel, table=True):+ __tablename__ = "users"+ id: Optional[int] = Field(default=None, primary_key=True)+ email: str = Field(unique=True, index=True)+ password_hash: str+ display_name: str+ is_owner: bool = Field(default=False)+ is_active: bool = Field(default=True)+ created_at: datetime+ last_login: Optional[datetime]++ def set_password(self, password: str) -> None:+ # Uses bcrypt for secure hashing++ def verify_password(self, password: str) -> bool:+ # Verifies against bcrypt hash+```++#### Auth Service (`server/services/user_auth.py`)+- `register_user()` - Creates new user, sets as owner if first user in single mode+- `authenticate_user()` - Validates credentials, returns user+- `create_token()` - Generates JWT token+- `verify_token()` - Validates JWT token+- `get_auth_status()` - Returns mode, registration availability, user count++#### Auth Router (`server/routers/auth.py`)+| Endpoint | Method | Description |+|----------|--------|-------------|+| `/api/auth/status` | GET | Get auth mode and registration status |+| `/api/auth/register` | POST | Register new user |+| `/api/auth/login` | POST | Login and set cookie |+| `/api/auth/logout` | POST | Clear auth cookie |+| `/api/auth/me` | GET | Get current user info |++#### Auth Middleware (`server/middleware/auth.py`)+Protects all routes except public paths:+```python+PUBLIC_PATHS = frozenset([+ "/health", "/docs", "/openapi.json", "/redoc",+ "/api/auth/status", "/api/auth/login", "/api/auth/register", "/api/auth/logout",+])+PUBLIC_PREFIXES = ("/webhook/",)+```++### Frontend Implementation++#### Auth Context (`client/src/contexts/AuthContext.tsx`)+```typescript+interface AuthContextValue {+ user: User | null;+ isAuthenticated: boolean;+ isLoading: boolean;+ error: string | null;+ authMode: 'single' | 'multi';+ canRegister: boolean;+ login: (email: string, password: string) => Promise<boolean>;+ register: (email: string, password: string, displayName: string) => Promise<boolean>;+ logout: () => Promise<void>;+ checkAuth: () => Promise<void>;+}+```++#### Protected Route (`client/src/components/auth/ProtectedRoute.tsx`)+Wraps protected content, shows LoginPage if not authenticated:+```typescript+const ProtectedRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {+ const { isAuthenticated, isLoading } = useAuth();+ if (isLoading) return <LoadingSpinner />;+ if (!isAuthenticated) return <LoginPage />;+ return <>{children}</>;+};+```++#### Login Page (`client/src/components/auth/LoginPage.tsx`)+- Dracula-themed login/register form+- Switches between login and register based on `canRegister`+- Displays errors from auth context++### Configuration+Environment variables in `.env`:+```bash+# Authentication Toggle (frontend - Vite)+VITE_AUTH_ENABLED=true # 'true' or 'false' - disable to bypass login++# Authentication Mode (backend)+AUTH_MODE=single # 'single' or 'multi'+JWT_SECRET_KEY=your-secret-key-32 # Min 32 chars+JWT_EXPIRE_MINUTES=10080 # 7 days+JWT_COOKIE_NAME=machina_token+JWT_COOKIE_SECURE=false # true for HTTPS+JWT_COOKIE_SAMESITE=lax+```++### Race Condition Handling+The AuthContext includes retry logic with exponential backoff to handle the case where frontend starts before backend is ready:+- 5 retries with exponential backoff (1s, 2s, 4s, 8s, 16s)+- Shows "Failed to connect to server" only after all retries exhausted+- Prevents false "not authenticated" errors during startup++### Cookie-Based Auth for API Calls+All API calls must include `credentials: 'include'` for HttpOnly cookie:+```typescript+// In workflowApi.ts, all fetch calls include:+fetch(url, { credentials: 'include' })+```++### WebSocket Authentication+WebSocket checks cookie before accepting connection:+```python+# In websocket.py+token = websocket.cookies.get(settings.jwt_cookie_name)+if not token:+ await websocket.close(code=4001, reason="Not authenticated")+ return+```++WebSocketProvider only connects when authenticated:+```typescript+// In WebSocketContext.tsx+const { isAuthenticated, isLoading: authLoading } = useAuth();++useEffect(() => {+ if (authLoading || !isAuthenticated) {+ // Disconnect if logged out+ return;+ }+ connect();+}, [isAuthenticated, authLoading]);+```++### Key Files+| File | Description |+|------|-------------|+| `client/src/config/api.ts` | API config with AUTH_ENABLED toggle |+| `client/src/contexts/AuthContext.tsx` | React auth state with retry logic |+| `client/src/components/auth/LoginPage.tsx` | Login UI |+| `client/src/components/auth/ProtectedRoute.tsx` | Route guard |+| `server/models/auth.py` | User SQLModel with bcrypt |+| `server/services/user_auth.py` | JWT creation/verification |+| `server/routers/auth.py` | REST endpoints |+| `server/middleware/auth.py` | Route protection |+| `server/core/config.py` | Settings with vite_auth_enabled field |++### Dependencies+```+# server/requirements.txt+bcrypt>=4.1.0+python-jose[cryptography]>=3.3.0+email-validator>=2.0.0+```++## AI Chat Model Development Guide++### Adding New AI Providers++Follow these steps to add a new AI provider. OpenRouter is used as a complete example.++#### Step 1: Frontend Node Definition++Create provider config in `client/src/nodeDefinitions/aiModelNodes.ts`:++```typescript+const openrouterConfig: ChatModelConfig = {+ providerId: 'openrouter',+ displayName: 'OpenRouter',+ icon: '🔀',+ color: '#6366F1',+ description: 'OpenRouter unified API - access OpenAI, Claude, Gemini, Llama, and more',+ models: [], // Models fetched dynamically via API+ parameters: [+ STANDARD_PARAMETERS.temperature,+ STANDARD_PARAMETERS.maxTokens,+ STANDARD_PARAMETERS.topP,+ STANDARD_PARAMETERS.frequencyPenalty,+ STANDARD_PARAMETERS.presencePenalty,+ {+ 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'+ }+ ]+};++// Add to exports+export const aiModelNodes = {+ // ... existing configs+ openrouterChatModel: createBaseChatModel(openrouterConfig)+};++export { openrouterConfig };+```++#### Step 2: Backend Provider Configuration++Add to `server/services/ai.py`:++```python+# Header function for API authentication+def _openrouter_headers(api_key: str) -> dict:+ return {+ 'Authorization': f'Bearer {api_key}',+ 'HTTP-Referer': 'http://localhost:3000',+ 'X-Title': 'MachinaOS'+ }++# Add to PROVIDER_CONFIGS dict+'openrouter': ProviderConfig(+ name='openrouter',+ model_class=ChatOpenAI, # OpenRouter uses OpenAI-compatible API+ api_key_param='api_key',+ max_tokens_param='max_tokens',+ detection_patterns=('openrouter',),+ default_model='openai/gpt-4o-mini',+ models_endpoint='https://openrouter.ai/api/v1/models',+ models_header_fn=_openrouter_headers+),+```++Add model fetching in `fetch_models` method:++```python+elif provider == 'openrouter':+ response = await client.get(+ 'https://openrouter.ai/api/v1/models',+ headers=_openrouter_headers(api_key)+ )+ response.raise_for_status()+ data = response.json()++ models = []+ for model in data.get('data', []):+ model_id = model.get('id', '')+ pricing = model.get('pricing', {})+ is_free = pricing.get('prompt') == '0' and pricing.get('completion') == '0'++ # Add [FREE] prefix for free models+ display_id = f'[FREE] {model_id}' if is_free else model_id+ models.append(display_id)++ return sorted(models, key=lambda x: (not x.startswith('[FREE]'), x))+```++Add to `create_model` method for custom base_url:++```python+if provider == 'openrouter':+ # Strip [FREE] prefix before API call+ actual_model = model.replace('[FREE] ', '')+ kwargs['model'] = actual_model+ kwargs['base_url'] = 'https://openrouter.ai/api/v1'+ kwargs['default_headers'] = {+ 'HTTP-Referer': 'http://localhost:3000',+ 'X-Title': 'MachinaOS'+ }+```++#### Step 3: Provider Detection++Add to `server/constants.py`:++```python+AI_CHAT_MODEL_TYPES = (+ 'openaiChatModel', 'anthropicChatModel', 'geminiChatModel', 'openrouterChatModel'+)++def detect_ai_provider(node_type: str, parameters: dict = None) -> str:+ if node_type == 'aiAgent':+ return (parameters or {}).get('provider', 'openai')+ elif 'openrouter' in node_type.lower():+ return 'openrouter'+ elif 'anthropic' in node_type.lower():+ return 'anthropic'+ elif 'gemini' in node_type.lower():+ return 'gemini'+ else:+ return 'openai'+```++#### Step 4: Frontend Credential Mapping++Add to `client/src/components/ModelNode.tsx`:++```typescript+const CREDENTIAL_TO_PROVIDER: Record<string, string> = {+ 'openaiApi': 'openai',+ 'anthropicApi': 'anthropic',+ 'googleAiApi': 'gemini',+ 'openrouterApi': 'openrouter' // Add this+};++// Add fallback detection+if (type?.includes('openrouter')) return 'openrouter';++// Add icon fallback+if (type?.includes('openrouter')) return '🔀';+```++#### Step 5: Dashboard Node Type Mapping++Add to `client/src/Dashboard.tsx`:++```typescript+} else if (type === 'openaiChatModel' || type === 'anthropicChatModel' ||+ type === 'geminiChatModel' || type === 'openrouterChatModel') {+ types[type] = SquareNode; // AI chat models use square design+}+```++#### Step 6: Add Credentials Modal Entry++Add to `client/src/components/CredentialsModal.tsx`:++```typescript+{+ id: 'openrouter',+ name: 'OpenRouter',+ icon: '🔀',+ fields: [{ name: 'apiKey', label: 'API Key', type: 'password', required: true }]+}+```++#### Step 7: Pydantic Validation (Optional)++Add to `server/models/nodes.py`:++```python+class AIChatModelParams(BaseNodeParams):+ type: Literal["openaiChatModel", "anthropicChatModel", "geminiChatModel", "openrouterChatModel"]+```++### Key Implementation Files++| File | Purpose |+|------|---------|+| `client/src/nodeDefinitions/aiModelNodes.ts` | Provider config with ChatModelConfig |+| `client/src/factories/baseChatModelFactory.ts` | Factory function for node definitions |+| `client/src/components/ModelNode.tsx` | Credential mapping and icon detection |+| `client/src/components/CredentialsModal.tsx` | API key entry UI |+| `client/src/Dashboard.tsx` | Node type to component mapping |+| `server/services/ai.py` | Provider configs, model fetching, LangChain integration |+| `server/constants.py` | Provider detection function |+| `server/models/nodes.py` | Pydantic validation (optional) |++### Special Considerations for OpenRouter++- **OpenAI-Compatible API**: Uses LangChain's `ChatOpenAI` with custom `base_url`+- **Model ID Format**: `provider/model-name` (e.g., `openai/gpt-4o`, `anthropic/claude-3.5-sonnet`)+- **Free Models**: API returns pricing info; models with `0` cost get `[FREE]` prefix+- **Dropdown Grouping**: Frontend uses `<optgroup>` for Free/Paid model separation++## Simple Memory System++### Overview+The Simple Memory node provides markdown-based conversation history storage for AI agents. It connects to the AI Agent's `input-memory` handle to provide context from previous conversations. Memory is stored in markdown format, visible and editable directly in the parameter panel, with optional long-term vector storage for semantic retrieval.++### Architecture+```+Simple Memory Node → (memory output) → AI Agent (input-memory handle)+ ↓ ↓+ Markdown editor Parses markdown, saves new exchanges+ (visible in UI) Trims to window, archives to vector DB+```++### Memory Format+Conversation history is stored in markdown format with timestamps:+```markdown+# Conversation History++### **Human** (2025-01-30 14:23:45)+What is the weather like today?++### **Assistant** (2025-01-30 14:23:48)+I don't have access to real-time weather data...+```++### Key Features+- **Editable UI**: Conversation history visible in markdown editor in parameter panel+- **Window-Based Trimming**: Keeps last N message pairs, archives old messages+- **Long-Term Memory**: Optional vector DB storage for semantic retrieval of archived messages+- **Uses LangChain's InMemoryVectorStore**: Per-session vector stores with HuggingFaceEmbeddings (BAAI/bge-small-en-v1.5)++### Key Files+- **Node Definition**: `client/src/nodeDefinitions/aiAgentNodes.ts` - simpleMemory node config+- **Memory Helpers**: `server/services/ai.py` - `_parse_memory_markdown()`, `_append_to_memory_markdown()`, `_trim_markdown_window()`+- **Vector Store**: `server/services/ai.py` - `_get_memory_vector_store()` with InMemoryVectorStore+- **AI Integration**: `server/services/ai.py` - execute_agent with memory_data parameter+- **Handler**: `server/services/handlers/ai.py` - Collects memory parameters from connected node++### Node Properties+| Property | Type | Default | Description |+|----------|------|---------|-------------|+| sessionId | string | 'default' | Unique identifier for conversation session |+| windowSize | number | 10 | Number of message pairs to keep in short-term memory |+| memoryContent | string (markdown) | Initial template | Editable conversation history in markdown format |+| longTermEnabled | boolean | false | Archive old messages to vector DB for semantic retrieval |+| retrievalCount | number | 3 | Number of relevant memories to retrieve from long-term storage (shown when longTermEnabled=true) |++### Memory Flow+1. **Load**: AI Agent reads `memoryContent` markdown from connected Simple Memory node+2. **Parse**: `_parse_memory_markdown()` converts markdown to LangChain messages+3. **Retrieve** (if enabled): Semantic search of vector store for relevant context+4. **Execute**: AI processes prompt with conversation history+5. **Append**: New human/AI messages appended to markdown+6. **Trim**: `_trim_markdown_window()` keeps last N pairs, returns removed texts+7. **Archive**: Removed messages stored in InMemoryVectorStore (if longTermEnabled)+8. **Save**: Updated markdown saved back to node parameters++### Usage Flow+1. Add Simple Memory node to workflow+2. Connect its output to AI Agent's `input-memory` handle (bottom-left diamond)+3. Configure session ID (use different IDs for separate conversations)+4. Optionally enable long-term memory for semantic retrieval+5. Run AI Agent - it automatically reads/updates memory content+6. View/edit conversation history in the markdown editor++### Design Decisions+- **Passive Node**: Memory node has no Run button - AI Agent reads its configuration directly when executed+- **Markdown Storage**: Human-readable format, editable in UI, easy to debug+- **Per-Session Vector Stores**: `_memory_vector_stores` dict keyed by session_id+- **Window + Archive**: Short-term (recent messages) + long-term (semantic retrieval) memory pattern+- **Auto-Save**: AI Agent automatically saves updated markdown content to node parameters++## AI Agent Tool System++### Overview+Tool nodes provide capabilities that AI Agents can invoke during reasoning. Each tool node connects to the AI Agent's `input-tools` handle and defines a schema for the LLM to understand how to call it.++### Architecture+```+Tool Node (calculatorTool) → (tool output) → AI Agent (input-tools handle)+ ↓+ LangGraph builds tools from schemas+ ↓+ LLM decides when to call tools+ ↓+ Tool executor runs handler+ ↓+ Result returned to LLM+```++### Tool Execution Flow+1. **Tool Discovery**: AI Agent scans edges for nodes connected to `input-tools` handle+2. **Schema Building**: `_get_tool_schema()` in `ai.py` creates Pydantic schema for each tool type+3. **Tool Binding**: LangGraph binds tools to the LLM model+4. **LLM Decision**: LLM decides when to call tools based on user query+5. **Status Broadcast**: `executing_tool` status broadcast with tool_name for UI animation+6. **Tool Execution**: `execute_tool()` in `tools.py` dispatches to appropriate handler+7. **Result Return**: Tool result returned to LLM for continued reasoning++### Key Files+| File | Description |+|------|-------------|+| `client/src/nodeDefinitions/toolNodes.ts` | Tool and specialized agent node definitions + AI_AGENT_PROPERTIES |+| `server/services/handlers/tools.py` | Tool execution handlers |+| `server/services/ai.py` | `_get_tool_schema()` - Pydantic schemas for tools |+| `server/services/handlers/ai.py` | Tool discovery from edges |++### Tool Node Definition Pattern+```typescript+// In toolNodes.ts+calculatorTool: {+ displayName: 'Calculator Tool',+ name: 'calculatorTool',+ icon: '...',+ group: ['tool', 'ai'], // 'tool' marks as tool node+ outputs: [{+ name: 'tool',+ type: 'main' as NodeConnectionType,+ description: 'Connect to AI Agent tool handle'+ }],+ properties: [+ { name: 'toolName', type: 'string', default: 'calculator' },+ { name: 'toolDescription', type: 'string', default: '...' }+ ]+}+```++### Specialized Agent Node Definition Pattern+```typescript+// In specializedAgentNodes.ts - uses shared AI_AGENT_PROPERTIES for full AI configuration+android_agent: {+ displayName: 'Android Control Agent',+ name: 'android_agent',+ icon: '📱',+ group: ['agent', 'ai'], // 'agent' for category placement+ inputs: [+ { name: 'main', displayName: 'Input', type: 'main' as NodeConnectionType },+ { name: 'skill', displayName: 'Skill', type: 'main' as NodeConnectionType },+ { name: 'memory', displayName: 'Memory', type: 'main' as NodeConnectionType },+ { name: 'tools', displayName: 'Tool', type: 'main' as NodeConnectionType }+ ],+ outputs: [{ name: 'main', displayName: 'Output', type: 'main' as NodeConnectionType }],+ properties: AI_AGENT_PROPERTIES // Full AI configuration (provider, model, prompt, etc.)+}+```++### Adding New Tools+1. **Frontend**: Add node definition in `toolNodes.ts` with `group: ['tool', 'ai']`+2. **Schema**: Add Pydantic schema in `ai.py` `_get_tool_schema()`+3. **Handler**: Add execution handler in `tools.py` and dispatcher case in `execute_tool()`+4. **TOOL_NODE_TYPES**: Add to array in `toolNodes.ts`++### Adding New Specialized Agents+1. **Frontend Definition**: Add node definition in `specializedAgentNodes.ts` with `group: ['agent', 'ai']` and `properties: AI_AGENT_PROPERTIES`+2. **AIAgentNode Config**: Add config to `AGENT_CONFIGS` in `AIAgentNode.tsx` with icon, title, subtitle, accentColor, bottomHandles+3. **Dashboard Mapping**: `SPECIALIZED_AGENT_TYPES` array automatically maps to `AIAgentNode` component+4. **SPECIALIZED_AGENT_TYPES**: Add to array in `toolNodes.ts`++### Tool Execution Animation+Tool nodes display execution status via the standard node status system:+- Backend broadcasts `executing` status to tool node when AI Agent calls it+- `SquareNode.tsx` uses `getNodeStatus()` from WebSocket context+- Tool nodes show cyan border and pulse animation when `isExecuting` is true+- **Minimum glow duration**: 500ms ensures fast-executing tools are visible (via `isGlowing` state)+- Dual-purpose tools (Python/JavaScript) fall back to node params when LLM returns empty args++### Implemented Tools+| Tool | Schema | Handler | Description |+|------|--------|---------|-------------|+| calculatorTool | CalculatorSchema | `_execute_calculator()` | Math operations |+| currentTimeTool | CurrentTimeSchema | `_execute_current_time()` | Date/time with timezone |+| webSearchTool | WebSearchSchema | `_execute_web_search()` | DuckDuckGo/Serper search |+| androidTool | AndroidToolSchema | `_execute_android_toolkit()` | Android device control via connected services |+| Android service nodes | Per-service schema | `_execute_android_service()` | Direct Android service tools (see below) |++### Direct Android Service Tools+Android service nodes (batteryMonitor, wifiAutomation, etc.) can be connected directly to any agent's `input-tools` handle without using the androidTool aggregator. The `execute_tool()` function detects these via `ANDROID_SERVICE_NODE_TYPES` and routes to `_execute_android_service()`.++**Service ID Mapping** (camelCase node type -> snake_case service ID):+```python+service_id_map = {+ 'batteryMonitor': 'battery',+ 'networkMonitor': 'network',+ 'systemInfo': 'system_info',+ 'location': 'location',+ 'appLauncher': 'app_launcher',+ 'appList': 'app_list',+ 'wifiAutomation': 'wifi_automation',+ 'bluetoothAutomation': 'bluetooth_automation',+ 'audioAutomation': 'audio_automation',+ 'deviceStateAutomation': 'device_state',+ 'screenControlAutomation': 'screen_control',+ 'airplaneModeControl': 'airplane_mode',+ 'motionDetection': 'motion_detection',+ 'environmentalSensors': 'environmental_sensors',+ 'cameraControl': 'camera_control',+ 'mediaControl': 'media_control',+}+```++### Android Toolkit Pattern+The androidTool follows n8n Sub-Node and LangChain Toolkit patterns:+- **Gateway Pattern**: Single tool node aggregates multiple Android service nodes+- **Dynamic Schema**: Schema built at runtime from connected services only+- **Service Routing**: Tool execution routes to appropriate connected Android node++```+[Battery Monitor] --++ +--> [Android Toolkit] --> [AI Agent]+[WiFi Automation] --++```++The AI sees a single `android_device` tool with schema showing only connected services:+- `service_id`: Which service to use (e.g., "battery", "wifi_automation")+- `action`: Action to perform (e.g., "status", "enable", "disable")+- `parameters`: Action-specific parameters++### Tool Schema Editor+The Android Toolkit node includes a schema editor UI for customizing the LLM-visible schema of connected services.++#### Architecture+```+ToolSchemaEditor Component+ ↓+ useToolSchema Hook (WebSocket CRUD)+ ↓+ Database (tool_schemas table)+ ↓+ AI Service reads schemas at execution+```++#### Key Files+| File | Description |+|------|-------------|+| `client/src/components/parameterPanel/ToolSchemaEditor.tsx` | Schema editor UI component |+| `client/src/hooks/useToolSchema.ts` | WebSocket hook for schema CRUD operations |+| `server/models/database.py` | `ToolSchema` SQLModel table definition |+| `server/core/database.py` | Database CRUD methods for tool schemas |+| `server/routers/websocket.py` | WebSocket handlers for schema operations |++#### Database Model+```python+class ToolSchema(SQLModel, table=True):+ __tablename__ = "tool_schemas"+ node_id: str # Service node ID (unique key)+ tool_name: str # Display name (e.g., "Battery Monitor")+ tool_description: str # Description shown to LLM+ schema_config: Dict # Schema fields and types (JSON)+ connected_services: Optional[Dict] # For toolkit aggregation+```++#### UI Features+- **Service Selector**: Dropdown showing only Android service nodes connected to the toolkit+- **Schema Fields Editor**: Add/remove/edit fields with name, type, description, required flag+- **Per-Service Schema**: Each connected service has its own independent schema stored by service node ID+- **Save/Reset**: Changes tracked locally, saved to database on demand++#### WebSocket Messages+| Message Type | Description |+|--------------|-------------|+| `get_tool_schema` | Get schema for a node by ID |+| `save_tool_schema` | Save/update schema for a node |+| `delete_tool_schema` | Delete schema for a node |+| `get_all_tool_schemas` | Get all stored schemas |++#### Default Schema Generation+When no custom schema exists, service-specific defaults are generated:+```typescript+{+ description: `Control ${serviceName} on Android device`,+ fields: {+ action: { type: 'string', description: `Action to perform on ${serviceName}`, required: true },+ parameters: { type: 'object', description: `Parameters for the ${serviceName} action`, required: false }+ }+}+```++### Web Search Implementation+Uses `ddgs` library (renamed from `duckduckgo-search`) for actual web results (not the limited Instant Answer API):+```python+from ddgs import DDGS++def do_search():+ ddgs = DDGS()+ return list(ddgs.text(query, max_results=max_results))++# Run in thread pool to avoid blocking async+search_results = await asyncio.get_event_loop().run_in_executor(None, do_search)+```++## Config Node Architecture++### Overview+Config nodes (memory, tools, models) connect to parent nodes via special "config handles" (e.g., `input-memory`, `input-tools`). These are auxiliary connections for configuration, not main data flow. The UI intelligently handles visibility of connected inputs based on this architecture.++### Config Handle Convention+Config handles follow the pattern `input-<type>` where type is NOT 'main':+- `input-memory` - Memory/context nodes+- `input-tools` - Tool nodes+- `input-model` - Model configuration nodes+- `input-main` - Main data flow (NOT a config handle)++### Config Node Detection+Nodes are identified as config nodes by their `group` array in the node definition:+```typescript+// Config node example (simpleMemory)+group: ['skill', 'memory'] // 'memory' or 'tool' indicates config node+```++### Input Inheritance+Config nodes automatically inherit their parent node's main inputs in the parameter panel:+```+WhatsApp Trigger → AI Agent ← Simple Memory+ ↓ ↑+ main input config handle++When viewing Simple Memory's parameters:+- Shows: "WhatsApp Trigger (via AI Agent)"+- Can drag WhatsApp outputs into Memory's parameters+```++### Filtering Logic+Located in `InputSection.tsx` and `OutputPanel.tsx`:+1. **Parent nodes** (AI Agent): Skip showing config node connections as inputs+2. **Config nodes** (Memory): Inherit parent's main input connections with "(via Parent)" label++### Key Functions+```typescript+// Check if handle is for config nodes (not main data flow)+const isConfigHandle = (handle: string | null | undefined): boolean => {+ if (!handle) return false;+ return handle.startsWith('input-') && handle !== 'input-main';+};++// Check if node is a config/auxiliary node+const isConfigNode = (nodeType: string | undefined): boolean => {+ const definition = nodeDefinitions[nodeType];+ const groups = definition?.group || [];+ return groups.includes('memory') || groups.includes('tool');+};+```++### Adding New Config Node Types+1. Add 'memory' or 'tool' to node's `group` array in definition+2. Use `input-<type>` naming for the target handle on parent node+3. Input inheritance and filtering work automatically++### Toolkit Sub-Node Execution Pattern++Toolkit nodes (like `androidTool`) aggregate sub-nodes that should only execute when called via the toolkit's tool interface, not as independent workflow nodes.++**Problem**: In parallel execution mode, Kahn's algorithm schedules nodes with in-degree 0 first. Sub-nodes connect TO the toolkit (not from it), so they have in-degree 0 and would be incorrectly scheduled in layer 0.++**Solution**: The executor detects and excludes toolkit sub-nodes from execution layers.++**Key Constants** (`server/constants.py`):+```python+# Toolkit node types that aggregate sub-nodes+TOOLKIT_NODE_TYPES: FrozenSet[str] = frozenset([+ 'androidTool', # Aggregates Android service nodes+])++# Config nodes excluded from execution (includes tool nodes)+CONFIG_NODE_TYPES: FrozenSet[str] = (+ AI_MEMORY_TYPES | AI_TOOL_TYPES | AI_CHAT_MODEL_TYPES+)+```++**Detection Logic** (in `ExecutionContext.create()` and `_compute_execution_layers()`):+```python+# Find toolkit sub-nodes (nodes that connect TO a toolkit)+toolkit_node_ids = {n.get("id") for n in nodes if n.get("type") in TOOLKIT_NODE_TYPES}+subnode_ids: set = set()+for edge in edges:+ source = edge.get("source")+ target = edge.get("target")+ # Any node that connects TO a toolkit is a sub-node+ if target in toolkit_node_ids and source:+ subnode_ids.add(source)+```++**Example Workflow**:+```+[WhatsApp Trigger] → [AI Agent] ← [Android Toolkit] ← [Battery Monitor]+ ← [Location]+```+- `Battery Monitor` and `Location` connect TO `Android Toolkit`+- They are detected as sub-nodes and excluded from execution layers+- They only execute when AI Agent calls the toolkit's tool interface++## Android Services Development Guide++### Architecture+Android services use a factory pattern with `createAndroidServiceNode()` for consistent node structure:+- **SquareNode Component**: Visual representation with configuration status indicators+- **Dynamic Actions**: Load available actions from backend via `loadOptionsMethod`+- **ADB Integration**: All services communicate with Android devices via ADB commands+- **Parameter System**: Flexible JSON parameters for service-specific configuration++### Adding New Android Services+1. **Add Node Definition** in `src/nodeDefinitions/androidServiceNodes.ts`:+ ```typescript+ newService: createAndroidServiceNode({+ name: 'newService',+ displayName: 'New Service',+ serviceId: 'new_service',+ icon: '🎯',+ color: '#FF5722',+ group: ['android', 'category'],+ description: 'Service description',+ defaultAction: 'default_action'+ })+ ```++2. **Add to Node Type Array** in same file:+ ```typescript+ export const ANDROID_SERVICE_NODE_TYPES = [+ // ... existing nodes+ 'newService'+ ];+ ```++3. **Implement Backend Handler** in `server/services/workflow.py`:+ - Add execution logic for the new service+ - Handle parameters and return formatted results+ - Use subprocess for ADB commands if needed++4. **Add API Endpoint** (optional) in `server/routers/android.py`:+ - Add endpoints for service-specific operations+ - Implement action handlers with proper error handling++### Key Files+- **Node Factory**: `src/nodeDefinitions/androidServiceNodes.ts` - Creates Android service nodes+- **Backend Router**: `server/routers/android.py` - API endpoints for Android operations+- **Workflow Handler**: `server/services/workflow.py` - Execution logic for all nodes+- **Execution Service**: `src/services/executionService.ts` - Routes Android nodes to Python backend++### Requirements+- **Device Connection**: Configure Android connection via Credentials Modal (Android panel)+- **Permissions**: Android app must have necessary permissions for services++### Android Device Connection+Android device connection is configured via the **Credentials Modal** (Android panel), not via workflow nodes.++**Connection Types:**+1. **Remote Relay** (recommended): Connect to Android device via relay server (QR code pairing)+2. **Local ADB**: Connect via USB with ADB port forwarding++**WebSocket Handlers** (`server/routers/websocket.py`):+- `android_relay_connect` - Connect to relay server, get QR code for pairing+- `android_relay_disconnect` - Disconnect from relay server+- `android_relay_reconnect` - Reconnect to relay server++### Android Relay Client+Located in `server/services/android/`:++**Key Components:**+- `client.py` - RelayWebSocketClient manages persistent connection+- `broadcaster.py` - Status broadcast functions (connected, paired, disconnected)+- `manager.py` - Global client instance management+- `protocol.py` - JSON-RPC 2.0 message handling++**Message Filtering:**+```python+async def receive_message(self, timeout: float = 10.0):+ """Receive response message, skipping non-response types"""+ skip_types = {'presence', 'pong', 'ping', 'connected'}++ while True:+ data = await asyncio.wait_for(self._message_queue.get(), timeout)+ msg_type = data.get('type', '')++ if msg_type in skip_types:+ continue # Skip and wait for next message++ return data # Return actual response+```++**Performance Benefits:**+- Initial connection: ~0.18s (WebSocket handshake + registration)+- Reused connection: ~0.0003s (600x faster)+- Background tasks maintain connection health+- Message queue decouples receiving from service execution++### Android Relay Connection vs Device Pairing++The Android relay system uses a **two-state model** for connection status:++| State | Description | Frontend Indicator |+|-------|-------------|-------------------|+| `connected` | WebSocket connection to relay server is active | N/A (not shown directly) |+| `paired` | Android device has scanned QR and is paired via relay | Green/Red status dot |++**Key Concepts:**+- **Relay Connection**: The WebSocket connection to `wss://relay.zeenie.xyz/ws` - can be active without a device+- **Device Pairing**: An Android device scans the QR code and pairs - required for service execution+- **Android service nodes require pairing**, not just relay connection, to execute++**Status Broadcasting Architecture:**+```+server/services/android/+├── client.py # RelayWebSocketClient - manages WebSocket connection+├── broadcaster.py # Status broadcast functions+├── manager.py # Global client instance management+└── protocol.py # JSON-RPC 2.0 message handling+```++**Broadcast Functions** (`server/services/android/broadcaster.py`):+```python+# Device connected and paired+await broadcast_connected(device_id, device_name)++# Device disconnected but relay still connected (for re-pairing)+await broadcast_device_disconnected(+ relay_connected=True,+ qr_data=qr_data,+ session_token=session_token+)++# Relay connection fully closed+await broadcast_relay_disconnected()++# QR code available for pairing+await broadcast_qr_code(qr_data, session_token)+```++**Frontend Status Indicator** (`client/src/components/SquareNode.tsx`):+```typescript+// Android nodes use 'paired' status, not 'connected'+const isAndroidConnected = isAndroidNode && androidStatus.paired;+```++**Status Flow:**+1. User clicks "Connect" → Relay WebSocket connects → `connected=true, paired=false`+2. QR code displayed → User scans with Android app → `connected=true, paired=true`+3. Android app disconnects → `connected=true, paired=false` (can re-pair)+4. Relay WebSocket closes → `connected=false, paired=false`++**WebSocket Context Interface** (`client/src/contexts/WebSocketContext.tsx`):+```typescript+export interface AndroidStatus {+ connected: boolean; // Relay WebSocket connected+ paired: boolean; // Android device paired+ device_id: string | null;+ device_name: string | null;+ connected_devices: string[];+ connection_type: string | null;+ qr_data: string | null;+ session_token: string | null;+}+```++## WhatsApp Integration++### Overview+WhatsApp nodes use square design with integrated QR code viewing and proper error handling. The integration proxies all requests through the Python backend to the WhatsApp Flask service on port 5000.++### Architecture+```+Frontend (WhatsAppNode.tsx) → Python Backend (/api/whatsapp/*) → WhatsApp Flask Service (localhost:5000)+```++### Key Features+- **Square Node Design**: 80x80px square nodes with status indicators+- **QR Code Viewer**: Embedded QR code display via Python backend proxy+- **Error Handling**: Robust error handling with proper HTTP status codes (503, 504, 410)+- **No Mock Data**: All endpoints return proper errors instead of mock responses+- **Connection Status**: Real-time status display with device ID, session, and service info++### Backend Endpoints (`server/routers/whatsapp.py`)++#### `/api/whatsapp/status` - Get Connection Status+- Returns WhatsApp connection status from Flask service+- Handles ConnectError, TimeoutException with 503/504 status codes+- Safe JSON parsing with error handling++#### `/api/whatsapp/qr` - Get QR Code+- Checks connection status first+- Returns QR code data if not connected+- Returns "Already connected" message if connected+- Handles errors gracefully without crashing++#### `/api/whatsapp/start` - Start Connection+- Proxies start request to Flask service+- Safe JSON parsing and error handling+- Returns proper HTTP errors on failure++#### `/api/whatsapp/send` - Send Message+- Enhanced messaging endpoint+- Comprehensive error handling with specific exception catches+- Never crashes on service unavailability++### Frontend Component (`client/src/components/WhatsAppNode.tsx`)+- **Node Type**: Square (80x80px, borderRadius: 8px)+- **Status Indicators**: Top-right corner indicator (green/yellow/red)+- **Connect Button**: Bottom-left corner for opening modal+- **QR Code Display**: Fetches QR via `fetchQRCode()` from Python backend+- **Connection Details**: Shows device ID, status, session, service, pairing, timestamp+- **Action Buttons**: Start, Restart, Refresh Status, Close (always visible)++### Critical Bug Fixes++#### 1. Missing Dependency Injection Wiring+**Problem**: `main.py` was missing `"routers.whatsapp"` in `container.wire()` modules list+**Impact**: Uvicorn reloader child process crashed with exit code 1, triggering SIGTERM+**Fix**: Added `"routers.whatsapp"` to wiring list in `server/main.py:38`+```python+container.wire(modules=[+ "routers.auth",+ "routers.ai",+ "routers.workflow",+ "routers.database",+ "routers.maps",+ "routers.nodejs_compat",+ "routers.whatsapp", # CRITICAL: This was missing+ "routers.android"+])+```++#### 2. Unhandled JSON Parse Errors+**Problem**: `.json()` calls without error handling raised `JSONDecodeError` when Flask returned HTML errors+**Impact**: Server crashes when WhatsApp service unavailable+**Fix**: Wrapped all `.json()` calls in try-except blocks with proper error responses++#### 3. Unhandled HTTP Status Errors+**Problem**: `response.raise_for_status()` raised `httpx.HTTPStatusError` not caught by specific handlers+**Impact**: Unhandled exceptions crashed the server+**Fix**: Removed `.raise_for_status()`, manually check `response.status_code != 200`++#### 4. Missing HTTPException Re-raise+**Problem**: Generic `Exception` handlers didn't re-raise `HTTPException`+**Impact**: Double exception wrapping and unclear errors+**Fix**: Added `except HTTPException: raise` before generic handler++### Error Handling Pattern+All WhatsApp endpoints follow this pattern:+```python+try:+ response = await client.get(url, timeout=10.0)++ # Check status manually+ if response.status_code != 200:+ raise HTTPException(status_code=503, detail="...")++ # Safe JSON parsing+ try:+ data = response.json()+ return data+ except Exception as json_err:+ logger.error(f"Failed to parse JSON: {json_err}")+ raise HTTPException(status_code=503, detail="Invalid response")++except httpx.ConnectError as e:+ raise HTTPException(status_code=503, detail="Service not running")+except httpx.TimeoutException as e:+ raise HTTPException(status_code=504, detail="Service timeout")+except HTTPException:+ raise # Re-raise HTTPException+except Exception as e:+ logger.error(f"Unexpected error: {e}")+ raise HTTPException(status_code=503, detail="Service unavailable")+```++### Result+- Python backend never crashes when WhatsApp service is down+- Proper HTTP error codes (503, 504, 410) returned+- No SIGTERM crashes+- Frontend receives proper error messages+- QR code viewer works seamlessly+- All mock data removed from production code++### WhatsApp Group/Sender Name Persistence+The WhatsApp Receive node stores human-readable names alongside JIDs/phone numbers:++#### Problem+When reopening the parameter panel, group/sender selectors showed the raw JID (e.g., `[email protected]`) instead of the group name because the name was only fetched when the dropdown was opened.++#### Solution+Store the name as a separate parameter alongside the ID:+- `group_id` + `group_name` - Group JID and display name+- `phone_number` + `sender_name` - Phone number and contact name++#### Implementation+```typescript+// In ParameterRenderer.tsx - GroupIdSelector+<GroupIdSelector+ value={currentValue || ''}+ onChange={onChange}+ onNameChange={(name) => onParameterChange?.('group_name', name)}+ storedName={allParameters?.group_name || ''}+ ...+/>++// GroupIdSelector stores name when selection changes+const handleChange = (value: string, option: any) => {+ onChange(value);+ if (option?.label && onNameChange) {+ onNameChange(option.label);+ }+};++// Display uses storedName when available+const displayLabel = storedName || (value && !loading ? value : '');+```++#### Key Files+- `client/src/components/ParameterRenderer.tsx` - GroupIdSelector and SenderNumberSelector with `onNameChange` and `storedName` props+- `client/src/components/parameterPanel/MiddleSection.tsx` - Passes `onParameterChange` to ParameterRenderer++## Event-Driven Trigger Node System++### Overview+Trigger nodes wait for external events (WhatsApp messages, webhooks, etc.) using Python's asyncio.Future. The backend handles all event waiting logic with the frontend displaying waiting state and providing cancel functionality.++### Architecture+```+User clicks "Run" on Trigger Node+ ↓+Frontend sends execute_node via WebSocket+ ↓+Python backend detects trigger node type (event_waiter.is_trigger_node)+ ↓+Backend registers asyncio.Future waiter with filter+ ↓+Backend broadcasts "waiting" status to frontend+ ↓+External service sends event (e.g., whatsapp_message_received)+ ↓+event_waiter.dispatch() resolves matching waiters+ ↓+Backend returns execution result with event data as output+ ↓+Frontend displays result in output panel+```++### Backend Implementation++#### Event Waiter Service (`server/services/event_waiter.py`)+Generic event waiting using standard asyncio primitives:++```python+@dataclass+class TriggerConfig:+ node_type: str+ event_type: str # e.g., 'whatsapp_message_received'+ display_name: str++TRIGGER_REGISTRY: Dict[str, TriggerConfig] = {+ 'whatsappReceive': TriggerConfig('whatsappReceive', 'whatsapp_message_received', 'WhatsApp Message'),+ 'webhookTrigger': TriggerConfig('webhookTrigger', 'webhook_received', 'Webhook Request'),+ # Future: 'emailTrigger', 'mqttTrigger', 'telegramTrigger', etc.+}++@dataclass+class Waiter:+ id: str+ node_id: str+ node_type: str+ event_type: str+ filter_fn: Callable[[Dict], bool]+ future: asyncio.Future++# Key functions:+def register(node_type: str, node_id: str, params: Dict) -> Waiter+def dispatch(event_type: str, data: Dict) -> int # Returns count resolved+def cancel(waiter_id: str) -> bool+def cancel_for_node(node_id: str) -> int+def get_active_waiters() -> List[Dict]+```++#### Trigger Node Execution (`server/services/workflow.py`)+```python+async def _execute_trigger_node(self, node_id: str, node_type: str, parameters: Dict) -> Dict:+ config = event_waiter.get_trigger_config(node_type)+ waiter = event_waiter.register(node_type, node_id, parameters)++ # Broadcast waiting status+ await broadcaster.update_node_status(node_id, "waiting", {+ "message": f"Waiting for {config.display_name}...",+ "waiter_id": waiter.id+ })++ # Wait indefinitely (user cancels via cancel_event_wait)+ event_data = await waiter.future+ return {"success": True, "result": event_data, ...}+```++#### Filter Builders+Each trigger type has a filter builder that creates a function to match events:++```python+def build_whatsapp_filter(params: Dict) -> Callable[[Dict], bool]:+ """Build filter for WhatsApp messages based on node parameters."""+ msg_type = params.get('messageTypeFilter', 'all')+ sender_filter = params.get('filter', 'all') # all, any_contact, contact, group, keywords+ forwarded_filter = params.get('forwardedFilter', 'all') # all, only_forwarded, ignore_forwarded+ # ... builds closure that checks message fields+```++**Sender Filter Options:**+- `all` - Accept all messages (groups and contacts)+- `any_contact` - Accept only non-group messages (individual chats)+- `contact` - Accept from specific phone number+- `group` - Accept from specific group (optionally filter by sender)+- `keywords` - Accept messages containing specific keywords++### WebSocket Handlers++#### Cancel Event Wait (`server/routers/websocket.py`)+```python+@ws_handler()+async def handle_cancel_event_wait(data: Dict[str, Any], websocket: WebSocket):+ """Cancel by waiter_id or node_id."""+ if waiter_id := data.get("waiter_id"):+ success = event_waiter.cancel(waiter_id)+ elif node_id := data.get("node_id"):+ count = event_waiter.cancel_for_node(node_id)+ return {"success": success, ...}++@ws_handler()+async def handle_get_active_waiters(data: Dict[str, Any], websocket: WebSocket):+ """Get list of active waiters for debugging/UI."""+ return {"waiters": event_waiter.get_active_waiters()}+```++### WhatsApp Receive Node++#### Node Definition (`client/src/nodeDefinitions/whatsappNodes.ts`)+```typescript+whatsappReceive: {+ displayName: 'WhatsApp Receive',+ name: 'whatsappReceive',+ icon: WHATSAPP_RECEIVE_ICON, // Bell with notification dot+ group: ['whatsapp', 'trigger'],+ outputs: [{+ name: 'main',+ displayName: 'Message',+ type: 'main',+ description: 'message_id, sender, chat_id, message_type, text, timestamp, is_group, is_from_me, push_name, group_info'+ }],+ properties: [+ // Message Type Filter: all, text, image, video, audio, document, location, contact+ // Sender Filter: all, contact (specific phone), group (specific group), keywords+ // Ignore Own Messages: boolean (default true)+ // Include Media Data: boolean (default false)+ ]+}+```++#### Output Schema (`client/src/components/parameterPanel/InputSection.tsx`)+Provides draggable variables for downstream nodes:+```typescript+const sampleSchemas = {+ whatsapp: {+ message_id: 'string',+ sender: 'string',+ sender_phone: 'string', // Resolved phone number (Go RPC resolves LIDs before sending event)+ chat_id: 'string',+ message_type: 'string',+ text: 'string',+ timestamp: 'string',+ is_group: 'boolean',+ is_from_me: 'boolean',+ push_name: 'string',+ is_forwarded: 'boolean',+ forwarding_score: 'number',+ media: 'object',+ group_info: {+ group_jid: 'string',+ sender_jid: 'string',+ sender_phone: 'string', // Resolved phone number (Go RPC resolves LIDs)+ sender_name: 'string'+ }+ }+};+```++### Adding New Trigger Types++1. **Add to Registry** in `server/services/event_waiter.py`:+ ```python+ TRIGGER_REGISTRY['emailTrigger'] = TriggerConfig('emailTrigger', 'email_received', 'Email')+ ```++2. **Add Filter Builder**:+ ```python+ def build_email_filter(params: Dict) -> Callable[[Dict], bool]:+ # Build filter based on node parameters+ FILTER_BUILDERS['emailTrigger'] = build_email_filter+ ```++3. **Add Node Definition** in `client/src/nodeDefinitions/`:+ - Define properties for filter configuration+ - Set outputs with expected data structure++4. **Add Output Schema** in `InputSection.tsx`:+ ```typescript+ email: { from: 'string', subject: 'string', body: 'string', ... }+ ```++5. **Dispatch Events** from external service:+ ```python+ from services import event_waiter+ event_waiter.dispatch('email_received', email_data)+ ```++### Key Design Decisions++- **No Timeout**: Trigger nodes wait indefinitely; users cancel via Cancel button+- **Backend-First**: All event waiting logic in Python backend, minimal frontend changes+- **Generic Architecture**: Same execution flow for all trigger types via registry+- **Filter Functions**: Each trigger type builds its own filter from node parameters+- **asyncio.Future**: Simpler than asyncio.Event for single-value resolution++## Real-time Status WebSocket System++### Overview+The frontend and Python backend communicate via WebSocket for real-time status updates. This replaces API polling with push-based updates for Android connection status, node execution status, and variable changes.++### Architecture+```+React Frontend (WebSocketContext.tsx) <--WebSocket--> Python Backend (status_broadcaster.py)+ | |+ v v+ SquareNode.tsx websocket_client.py+ (uses androidStatus) (broadcasts Android status)+```++### Backend Implementation++#### Status Broadcaster (`server/services/status_broadcaster.py`)+Central service for managing WebSocket connections and broadcasting status updates:++```python+class StatusBroadcaster:+ def __init__(self):+ self._connections: Set[WebSocket] = set()+ self._status: Dict[str, Any] = {+ "android": {"connected": False, "device_id": None, "connected_devices": [], "connection_type": None},+ "nodes": {},+ "variables": {},+ "workflow": {"executing": False, "current_node": None}+ }++ async def connect(self, websocket: WebSocket): ...+ async def disconnect(self, websocket: WebSocket): ...+ async def update_android_status(self, connected, device_id, connected_devices, connection_type): ...+ async def update_node_status(self, node_id, status, data): ...+ async def update_variable(self, name, value): ...+ async def update_workflow_status(self, executing, current_node, progress): ...+```++Key methods:+- `connect()` - Accepts WebSocket, adds to connection set, sends initial status+- `update_android_status()` - Updates Android status and broadcasts to all clients+- `update_node_status()` - Updates individual node status with data/output+- `update_variable()` - Updates single variable value+- `_broadcast()` - Sends message to all connected clients++#### WebSocket Router (`server/routers/websocket.py`)+FastAPI WebSocket endpoint:++```python[email protected]("/ws/status")+async def websocket_status_endpoint(websocket: WebSocket):+ broadcaster = get_status_broadcaster()+ await broadcaster.connect(websocket)+ try:+ while True:+ data = await websocket.receive_json()+ if data.get("type") == "ping":+ await websocket.send_json({"type": "pong"})+ elif data.get("type") == "get_status":+ await websocket.send_json({"type": "full_status", "data": broadcaster.get_status()})+ except WebSocketDisconnect:+ await broadcaster.disconnect(websocket)+```++### Frontend Implementation++#### WebSocket Context (`client/src/contexts/WebSocketContext.tsx`)+React context providing WebSocket connection and status state:++```typescript+export interface AndroidStatus {+ connected: boolean;+ device_id: string | null;+ connected_devices: string[];+ connection_type: string | null;+}++export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {+ const [androidStatus, setAndroidStatus] = useState<AndroidStatus>(defaultAndroidStatus);+ const [nodeStatuses, setNodeStatuses] = useState<Record<string, NodeStatus>>({});+ const [variables, setVariables] = useState<Record<string, any>>({});+ // WebSocket connection with auto-reconnect+};++// Hooks for consuming status+export const useWebSocket = (): WebSocketContextValue => { ... }+export const useAndroidStatus = (): AndroidStatus => { ... }+export const useNodeStatus = (nodeId: string): NodeStatus => { ... }+```++Features:+- Auto-connect on mount+- Auto-reconnect after 3 seconds on disconnect+- Ping every 30 seconds to keep connection alive+- Message type handlers for all status update types++#### Usage in Components (`client/src/components/SquareNode.tsx`)+```typescript+const { androidStatus } = useWebSocket();+// Android service nodes use 'paired' status (device must be paired to execute)+const isAndroidConnected = isAndroidNode && androidStatus.paired;+```++### Android Status Broadcasting+The Android relay client (`server/services/android/client.py`) broadcasts status changes via dedicated functions in `broadcaster.py`:++```python+# When device pairs successfully+await broadcast_connected(device_id, device_name)++# When device unpairs (relay may still be connected)+await broadcast_device_disconnected(+ relay_connected=self.is_connected(),+ qr_data=self.qr_data,+ session_token=self.session_token+)++# When relay WebSocket closes unexpectedly+await broadcast_relay_disconnected()+```++**Key distinction:**+- `broadcast_device_disconnected()` - Device unpaired, relay still connected (can re-pair via QR)+- `broadcast_relay_disconnected()` - Full disconnection, need to reconnect++### Real Device Detection+Fixed issue where Android status remained green after device disconnect:++**Problem**: Base name `android_system_services` remained in connected devices set after real device `android_system_services_1764708352672` left.++**Solution**: Added methods to distinguish real devices (with timestamp suffix) from base names:++```python+def _get_discovered_devices(self) -> list:+ """Get list of actual discovered devices (with timestamp suffix)."""+ discovered = []+ for device_id in self._connected_android_devices:+ parts = device_id.rsplit('_', 1)+ if len(parts) == 2 and parts[1].isdigit():+ discovered.append(device_id)+ return discovered++def has_real_android_devices(self) -> bool:+ """Check if there are any real (discovered) Android devices connected."""+ return len(self._get_discovered_devices()) > 0+```++Updated `client_left` and presence handlers use `has_real_android_devices()` instead of checking total device count.++### WebSocket Message Types (28 Handlers)++#### Request/Response Messages (Client -> Server -> Client)+| Message Type | Description |+|--------------|-------------|+| `get_node_parameters` | Get parameters for a single node |+| `get_all_node_parameters` | Get parameters for multiple nodes |+| `save_node_parameters` | Save node parameters to database |+| `delete_node_parameters` | Delete node parameters |+| `execute_node` | Execute a workflow node |+| `cancel_execution` | Cancel running node execution |+| `execute_ai_node` | Execute AI model node |+| `get_ai_models` | Get available models for provider |+| `validate_api_key` | Validate AI provider API key |+| `get_stored_api_key` | Get stored API key for provider |+| `save_api_key` | Save API key to secure storage |+| `delete_api_key` | Delete stored API key |+| `get_android_devices` | List connected Android devices |+| `execute_android_action` | Execute Android service action |+| `setup_android_device` | Setup Android device connection |+| `validate_maps_key` | Validate Google Maps API key |+| `whatsapp_status` | Get WhatsApp connection status |+| `whatsapp_qr` | Get WhatsApp QR code |+| `whatsapp_send` | Send WhatsApp message |+| `whatsapp_start` | Start WhatsApp connection |+| `cancel_event_wait` | Cancel active event waiter (trigger nodes) |+| `get_active_waiters` | Get list of active event waiters |+| `send_chat_message` | Send chat message, optionally to specific node |+| `get_chat_messages` | Get chat history for session |+| `clear_chat_messages` | Clear chat history for session |+| `ping` | Keep-alive request |++#### Broadcast Messages (Server -> All Clients)+| Message Type | Description |+|--------------|-------------|+| `android_status` | Android device connection update |+| `node_status` | Node execution status change |+| `node_output` | Node execution output data |+| `variable_update` | Single variable value change |+| `workflow_status` | Workflow execution progress |+| `api_key_status` | API key validation status |+| `node_parameters_updated` | Node parameters changed by another client |++#### Status Messages+| Message Type | Direction | Description |+|--------------|-----------|-------------|+| `initial_status` | Server -> Client | Full status on connect |+| `full_status` | Server -> Client | Full status response |+| `pong` | Server -> Client | Keep-alive response |+| `error` | Server -> Client | Error response with code and message |++## WebSocket Hooks++### useWhatsApp (`client/src/hooks/useWhatsApp.ts`)+Hook for WhatsApp operations via WebSocket:+```typescript+const { getStatus, getQRCode, sendMessage, startConnection, isLoading, connectionStatus } = useWhatsApp();+```++### useExecution (`client/src/hooks/useExecution.ts`)+Hook for node execution via WebSocket:+```typescript+const { executeNode, cancelExecution, isExecuting, lastResult } = useExecution();+```++### useApiKeys (`client/src/hooks/useApiKeys.ts`)+Hook for API key management via WebSocket:+```typescript+const { validateApiKey, getStoredKey, saveApiKey, deleteApiKey } = useApiKeys();+```++### useAndroidOperations (`client/src/hooks/useAndroidOperations.ts`)+Hook for Android device operations via WebSocket:+```typescript+const { getDevices, executeAction, setupDevice, isConnected, deviceStatus } = useAndroidOperations();+```++### useParameterPanel (`client/src/hooks/useParameterPanel.ts`)+Hook for parameter management via WebSocket:+```typescript+const { parameters, saveParameters, loadParameters, isDirty } = useParameterPanel(nodeId);+```++### Conditional Parameter Display Implementation+Located in `client/src/components/parameterPanel/MiddleSection.tsx`:++```typescript+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;+};+```++This function:+- Checks if parameter has displayOptions.show configuration+- Evaluates all show conditions against current parameter values+- Returns false if any condition fails (parameter hidden)+- Returns true if all conditions pass (parameter visible)+- Applied before rendering: `.filter(param => shouldShowParameter(param, parameters))`++## Planned Features++### Workflow-Level Execution (n8n-style Parallel Workflows)++**Current Limitations:**+- Single workflow execution at a time (global `_deployment_running` flag)+- Nodes fetch status on component mount, not when workflow is selected+- Status broadcasts to all clients without workflow filtering+- No isolation between workflow executions++**Planned Architecture:**++1. **Defer Node Status Checks Until Workflow Selected**+ - Remove eager `getStatus()` calls from WhatsAppNode mount (lines 44-48)+ - Remove eager `checkConfiguration()` from SquareNode mount (lines 46-92)+ - Status should only fetch when workflow containing those nodes is selected+ - Use cached status from WebSocket context instead of per-node fetching++2. **Workflow-Isolated Execution Context**+ ```python+ # server/services/workflow.py+ class ExecutionContext:+ def __init__(self, workflow_id: str, session_id: str):+ self.workflow_id = workflow_id+ self.session_id = session_id+ self.outputs: Dict[str, Any] = {}+ self.iteration = 0+ self.running = False+ self.task: Optional[asyncio.Task] = None++ # Replace single deployment state with:+ self._execution_contexts: Dict[str, ExecutionContext] = {}+ ```++3. **Parallel Workflow Deployment**+ - Each workflow gets unique `workflow_id` in execution requests+ - Backend tracks `_execution_contexts[workflow_id]` instead of single `_deployment_running`+ - Cancel by `workflow_id` instead of globally+ - Status broadcasts include `workflow_id` for client filtering++4. **Frontend Changes**+ - `WebSocketContext`: Add `activeWorkflowId`, filter status by workflow+ - `useAppStore`: Add `runningWorkflows: Set<string>` to track parallel executions+ - `WorkflowSidebar`: Show running indicator next to deployed workflows+ - `Dashboard`: Pass `workflow_id` to all execution calls++**Files to Modify:**+- `client/src/components/WhatsAppNode.tsx` - Remove mount status fetch+- `client/src/components/SquareNode.tsx` - Remove mount config check+- `client/src/contexts/WebSocketContext.tsx` - Add workflow filtering+- `client/src/store/useAppStore.ts` - Track running workflows+- `server/services/workflow.py` - ExecutionContext class, parallel support+- `server/routers/websocket.py` - workflow_id in messages+- `server/services/status_broadcaster.py` - workflow_id filtering++## Notes+- **No Legacy Support**: Pure modern methods only, backward compatibility removed+- **Interface Alignment**: ParameterRenderer supports both interface types seamlessly+- **Execution Ready**: Components can be executed with real-time result display+- **Clean Codebase**: Significant file and code reduction while maintaining full functionality+- **Modular Backend**: workflow.py reduced from 2068 to 460 lines via facade pattern+ - NodeExecutor: Registry-based dispatch with `functools.partial` for dependency injection+ - ParameterResolver: Compiled regex for `{{node.field}}` template resolution+ - DeploymentManager: Handles deploy/cancel lifecycle with TriggerManager for cron/events+ - No global state: `_active_cron_jobs` moved to TriggerManager instance variable+- **Performance**: Fast HMR updates and clean TypeScript compilation+- **AI Architecture**: 5-layer system with factory pattern and secure credential management+- **Android Architecture**: Factory-based node creation with ADB integration for device automation+- **WebSocket-First Architecture**: 25 message handlers replace REST APIs for parameters, execution, API keys, Android, and WhatsApp operations+- **WebSocket Hooks**: Dedicated React hooks (useWhatsApp, useExecution, useApiKeys, useAndroidOperations, useParameterPanel) for clean component integration+- **WebSocket Support**: Persistent remote Android device connections via WebSocket proxy with background tasks+ - Connection stays alive across multiple API requests until switched to local ADB+ - Background message receiver and keepalive loop (25s interval)+ - Message queue for async message handling with filtering logic+ - Connection reuse reduces execution time from 0.18s to 0.0003s+- **Real-time Status WebSocket**: Frontend-backend WebSocket at `/ws/status` for live updates+ - Android connection status broadcasts when devices connect/disconnect+ - Node execution status and output updates+ - Variable value changes+ - Workflow execution progress+ - Replaces API polling with push-based updates+ - Auto-reconnect with 3-second delay on disconnect+ - Real device detection distinguishes actual devices (with timestamp suffix) from base names+ - **Android two-state model**: `connected` (relay WebSocket) vs `paired` (device paired)+ - Android service nodes use `paired` status for indicator (green = paired, red = not paired)+ - Relay can be connected without a device (shows QR for pairing)+ - Device disconnect broadcasts `paired=false` while keeping `connected=true` for re-pairing+- **Conditional Display**: Full implementation of displayOptions.show pattern for dynamic UI rendering+- **Process Management**: Robust stop scripts handle duplicate processes with verification and retry+- **Process Independence**: Removed `--kill-others` from concurrently to prevent cascading crashes when uvicorn reloads+- **WhatsApp Integration**: Square node design with QR code viewer, proper error handling, no crashes+ - Critical fix: Added "routers.whatsapp" to dependency injection wiring+ - All endpoints use safe JSON parsing with comprehensive error handling+ - Backend proxies all requests to WhatsApp Flask service (port 5000)+ - Returns proper HTTP status codes (503, 504, 410) instead of mock data+ - Python server never crashes when WhatsApp service is unavailable+ - WebSocket handlers for status, QR code, send message, and start connection+ - useWhatsApp hook provides clean React component integration+- **Event-Driven Triggers**: Generic trigger node architecture with asyncio.Future+ - `server/services/event_waiter.py` - Waiter registration, dispatch, cancellation+ - TRIGGER_REGISTRY for extensible trigger types (WhatsApp, Webhook, future: Email, MQTT, Telegram)+ - Filter builders create closures from node parameters (whatsapp_filter, webhook_filter)+ - No timeout - wait indefinitely until event or user cancel+ - WebSocket handlers: `cancel_event_wait`, `get_active_waiters`+ - **Trigger State Machine** (n8n pattern):+ - `idle` → `waiting` (on deploy, cyan indicator)+ - `waiting` → `idle` (on event received, graph starts executing, green indicator)+ - `idle` → `waiting` (after graph completes, listening again)+ - Triggers NEVER show `executing` status - only downstream nodes do+ - **Sequential Queue Processing**: Events are queued and processed one at a time via `wait_for_completion=True`+- **HTTP/Webhook Integration**: 3 utility nodes for HTTP communication+ - `httpRequest` - Make outgoing HTTP requests with httpx async client+ - `webhookTrigger` - Receive incoming HTTP requests at `/webhook/{path}`+ - `webhookResponse` - Send custom responses back to webhook callers+ - `server/routers/webhook.py` - Dynamic webhook router using broadcaster.send_custom_event()+ - Output panel shows clean summaries (method, path, body for webhooks; status code for HTTP)+- **n8n-Pattern Cache System**: Automatic fallback hierarchy for different environments+ - Production (Docker): Redis → SQLite → Memory+ - Local Development: SQLite → Memory (Redis disabled via `REDIS_ENABLED=false`)+ - `server/core/cache.py` - CacheService with fallback logic+ - `server/models/cache.py` - CacheEntry SQLModel for SQLite persistence+ - `server/core/database.py` - Cache CRUD methods (get/set/delete/cleanup)+ - Supports TTL expiration and automatic cleanup of expired entries+- **Conditional Redis with Docker Profiles**: Redis container only starts when explicitly enabled+ - Uses Docker Compose profiles: Redis service has `profiles: [redis]`+ - `scripts/docker.js` wrapper auto-adds `--profile redis` when `REDIS_ENABLED=true` in `.env`+ - npm scripts (`docker:up`, `docker:down`, etc.) use the wrapper for seamless handling+ - Backend no longer depends on Redis - depends only on WhatsApp service+- **WebSocket Reconnect Fix**: Fixed rapid reconnect loop caused by React effect cleanup+ - Split effects: connect effect, logout effect, unmount cleanup effect+ - Added `isMountedRef` to prevent connections after unmount+ - Added 100ms delay to avoid React Strict Mode double-connection issues+ - WebSocket now stable without 6-9 second reconnect loops+- **Docker Backend Fix**: Backend container uses Python uvicorn directly+ - Changed from `npm run start` (failed - npm not in Python image) to `python -m uvicorn`+ - CMD: `["python", "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "3010"]`+- **Configurable Authentication**: `VITE_AUTH_ENABLED` environment variable+ - Set to `false` to bypass login entirely (useful for local development)+ - Frontend creates anonymous user with owner privileges when disabled+ - AuthContext includes retry logic (5 retries, exponential backoff) for startup race conditions+ - Pydantic Settings accepts `vite_auth_enabled` field (required due to `extra="forbid"`)+- **npm ci Optimization**: Faster Docker builds and CI/CD+ - `client/Dockerfile` uses `npm ci` instead of `npm install` (2x faster)+ - `package.json` build script uses `npm ci` for root and whatsapp-rpc+ - `client/package-lock.json` generated for npm ci support (workspace child)+- never use emojis in prints\ No newline at end of filediff --git a/bin/cli.js b/bin/cli.jsindex a653689f..010b6212 100644--- a/bin/cli.js+++ b/bin/cli.js@@ -44,6 +44,24 @@ function getVersion(cmd) {}}+// Add common binary paths to PATH (Linux installs uv to ~/.local/bin)+function expandPath() {+ const home = process.env.HOME || process.env.USERPROFILE;+ if (home) {+ const additionalPaths = [+ `${home}/.local/bin`, // uv, cargo installs+ `${home}/.cargo/bin`, // Rust tools+ '/usr/local/bin', // Homebrew on macOS+ ];+ const currentPath = process.env.PATH || '';+ const sep = process.platform === 'win32' ? ';' : ':';+ const newPaths = additionalPaths.filter(p => !currentPath.includes(p));+ if (newPaths.length > 0) {+ process.env.PATH = newPaths.join(sep) + sep + currentPath;+ }+ }+}+function checkDeps() {const errors = [];const warnings = [];@@ -99,6 +117,9 @@ function run(script) {child.on('close', (code) => process.exit(code || 0));}+// Expand PATH to find tools like uv installed in user directories+expandPath();+const cmd = process.argv[2] || 'help';if (cmd === 'help' || cmd === '--help' || cmd === '-h') {diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsxindex d65e3cb0..7c5bcd2a 100644--- a/client/src/Dashboard.tsx+++ b/client/src/Dashboard.tsx@@ -27,8 +27,10 @@ import { CHAT_NODE_TYPES } from './nodeDefinitions/chatNodes';import { CODE_NODE_TYPES } from './nodeDefinitions/codeNodes';import { UTILITY_NODE_TYPES } from './nodeDefinitions/utilityNodes';import { TOOL_NODE_TYPES } from './nodeDefinitions/toolNodes';+import { SPECIALIZED_AGENT_TYPES } from './nodeDefinitions/specializedAgentNodes';import { SKILL_NODE_TYPES } from './nodeDefinitions/skillNodes';import { DOCUMENT_NODE_TYPES } from './nodeDefinitions/documentNodes';+import { SOCIAL_NODE_TYPES } from './nodeDefinitions/socialNodes';import ParameterPanel from './ParameterPanel';import LocationParameterPanel from './components/LocationParameterPanel';import { useAppStore } from './store/useAppStore';@@ -65,6 +67,12 @@ const createNodeTypes = (): Record<string, React.ComponentType<any>> => {// Trigger nodes (no input handles) - check by group or specific typesconst TRIGGER_NODE_TYPES = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive', 'chatTrigger'];+ // Pre-register specialized agent nodes explicitly to ensure they're always available+ // This handles cases where nodeDefinitions iteration order might miss them+ SPECIALIZED_AGENT_TYPES.forEach(type => {+ types[type] = AIAgentNode;+ });+Object.keys(nodeDefinitions).forEach(type => {const definition = nodeDefinitions[type];@@ -98,11 +106,15 @@ const createNodeTypes = (): Record<string, React.ComponentType<any>> => {// Utility nodes (HTTP, Webhooks) use SquareNode component// Note: webhookTrigger is already handled as trigger abovetypes[type] = SquareNode;+ } else if (SPECIALIZED_AGENT_TYPES.includes(type)) {+ // Specialized agent nodes use AIAgentNode (rectangular card with bottom handles)+ types[type] = AIAgentNode;} else if (TOOL_NODE_TYPES.includes(type)) {- // Most tool nodes use circular ModelNode- // Exception: androidTool uses ToolkitNode with top/bottom handles- if (type === 'androidTool') {- types[type] = ToolkitNode;+ // Tool node component mapping:+ // - webSearchTool: SquareNode (square shape like utility nodes)+ // - calculatorTool, currentTimeTool: ModelNode (circular)+ if (type === 'webSearchTool') {+ types[type] = SquareNode;} else {types[type] = ModelNode;}@@ -112,6 +124,9 @@ const createNodeTypes = (): Record<string, React.ComponentType<any>> => {} else if (DOCUMENT_NODE_TYPES.includes(type)) {// Document processing nodes use SquareNode componenttypes[type] = SquareNode;+ } else if (SOCIAL_NODE_TYPES.includes(type)) {+ // Social nodes use AIAgentNode for multiple output handles support+ types[type] = AIAgentNode;} else if (definition?.group?.includes('model')) {// Fallback for other model nodestypes[type] = ModelNode;@@ -293,7 +308,8 @@ const DashboardContent: React.FC = () => {} = useWorkflowManagement();const { collapsedSections, searchQuery, setSearchQuery, toggleSection } = useComponentPalette();- const { saveNodeParameters, executeWorkflow, deployWorkflow, cancelDeployment, nodeStatuses, deploymentStatus, workflowLock } = useWebSocket();+ const { saveNodeParameters, executeWorkflow, deployWorkflow, cancelDeployment, nodeStatuses, deploymentStatus, workflowLock, isConnected, sendRequest } = useWebSocket();+ const applyUIDefaults = useAppStore((state) => state.applyUIDefaults);// Scope deployment and lock to current workflow (n8n pattern)// Only show as "running" or "locked" if it applies to the currently viewed workflow@@ -334,7 +350,10 @@ const DashboardContent: React.FC = () => {});const [settingsOpen, setSettingsOpen] = React.useState(false);const [credentialsOpen, setCredentialsOpen] = React.useState(false);- const [consolePanelOpen, setConsolePanelOpen] = React.useState(false);++ // Console panel visibility from store (database-backed)+ const consolePanelVisible = useAppStore((state) => state.consolePanelVisible);+ const toggleConsolePanelVisible = useAppStore((state) => state.toggleConsolePanelVisible);// Context menu state for node right-clickconst [contextMenu, setContextMenu] = React.useState<{@@ -348,6 +367,40 @@ const DashboardContent: React.FC = () => {localStorage.setItem('workflow_settings', JSON.stringify(settings));}, [settings]);+ // Load UI defaults from database on initial WebSocket connection+ const hasLoadedUIDefaults = React.useRef(false);+ React.useEffect(() => {+ if (!isConnected || hasLoadedUIDefaults.current) return;+ hasLoadedUIDefaults.current = true;++ const loadUIDefaults = async () => {+ try {+ const response = await sendRequest<{ settings: any }>('get_user_settings', {});+ if (response?.settings) {+ applyUIDefaults({+ sidebarDefaultOpen: response.settings.sidebar_default_open,+ componentPaletteDefaultOpen: response.settings.component_palette_default_open,+ consolePanelDefaultOpen: response.settings.console_panel_default_open,+ });+ // Also update local settings state for auto-save preferences+ setSettings(prev => ({+ ...prev,+ autoSave: response.settings.auto_save ?? prev.autoSave,+ autoSaveInterval: response.settings.auto_save_interval ?? prev.autoSaveInterval,+ sidebarDefaultOpen: response.settings.sidebar_default_open ?? prev.sidebarDefaultOpen,+ componentPaletteDefaultOpen: response.settings.component_palette_default_open ?? prev.componentPaletteDefaultOpen,+ consolePanelDefaultOpen: response.settings.console_panel_default_open ?? prev.consolePanelDefaultOpen,+ }));+ console.log('[Dashboard] UI defaults loaded from database');+ }+ } catch (error) {+ console.error('[Dashboard] Failed to load UI defaults:', error);+ }+ };++ loadUIDefaults();+ }, [isConnected, sendRequest, applyUIDefaults]);+// Update nodes with execution status classesconst styledNodes = React.useMemo(() => {return nodes.map(node => {@@ -1140,8 +1193,8 @@ const DashboardContent: React.FC = () => {{/* Console Panel - n8n-style debug output at bottom */}<ConsolePanel- isOpen={consolePanelOpen}- onToggle={() => setConsolePanelOpen(prev => !prev)}+ isOpen={consolePanelVisible}+ onToggle={toggleConsolePanelVisible}nodes={nodes}/>diff --git a/client/src/components/AIAgentNode.tsx b/client/src/components/AIAgentNode.tsxindex 84a5eea2..eebad5f6 100644--- a/client/src/components/AIAgentNode.tsx+++ b/client/src/components/AIAgentNode.tsx@@ -1,10 +1,11 @@-import React, { useState, useEffect } from 'react';+import React, { useState, useEffect, useMemo } 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';+import { dracula } from '../styles/theme';// LangGraph phase icons and labelsconst PHASE_CONFIG: Record<string, { icon: string; label: string; color: string }> = {@@ -19,50 +20,183 @@ const PHASE_CONFIG: Record<string, { icon: string; label: string; color: stringsaving_memory: { icon: '💾', label: 'Saving Memory', color: '#bd93f9' },};+// Theme color keys for accent colors+type ThemeColorKey = 'purple' | 'cyan' | 'green' | 'pink' | 'orange' | 'yellow' | 'red';+// Configuration for different agent typesinterface AgentConfig {icon: React.ReactNode;title: string;subtitle: string;- accentColor: string;+ themeColorKey: ThemeColorKey; // Use theme color key instead of hardcoded colorbottomHandles: Array<{ id: string; label: string; position: string }>;+ leftHandles?: Array<{ id: string; label: string; position: string }>; // For input handles on left side (below main input)+ rightHandles?: Array<{ id: string; label: string; position: string }>; // For nodes with multiple outputs+ topOutputHandle?: { id: string; label: string }; // For nodes with top output (like Android Toolkit)+ skipInputHandle?: boolean; // For passive nodes like tool nodes that don't have left input+ skipRightOutput?: boolean; // Skip right output handle (use top output instead)+ wider?: boolean; // Make node wider (e.g., for Android Control) - 220px+ width?: number; // Custom width in pixels (overrides wider)+ height?: number; // Custom height in pixels (default 120px)}-// Lucide-style SVG icons-const RobotIcon = ({ size = 32, color = 'currentColor' }: { size?: number; color?: string }) => (- <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">- <rect x="3" y="11" width="18" height="10" rx="2" />- <circle cx="12" cy="5" r="2" />- <path d="M12 7v4" />- <line x1="8" y1="16" x2="8" y2="16" />- <line x1="16" y1="16" x2="16" y2="16" />- <circle cx="8" cy="16" r="1" fill={color} />- <circle cx="16" cy="16" r="1" fill={color} />+// Social Receive icon as React component (SVG funnel/filter)+const SocialReceiveIcon = ({ size = 32, color = '#6366F1' }: { size?: number; color?: string }) => (+ <svg width={size} height={size} viewBox="0 0 24 24" fill={color}>+ <path d="M4.25 5.61C6.27 8.2 10 13 10 13v6c0 .55.45 1 1 1h2c.55 0 1-.45 1-1v-6s3.73-4.8 5.75-7.39C20.26 4.95 19.79 4 18.95 4H5.04c-.83 0-1.31.95-.79 1.61z"/></svg>);+// Social Send icon as React component (paper plane with globe)+const SocialSendIcon = ({ size = 32, color = '#6366F1' }: { size?: number; color?: string }) => (+ <svg width={size} height={size} viewBox="0 0 24 24" fill={color}>+ <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>+ <circle cx="18" cy="18" r="4" fill={color} stroke="#fff" strokeWidth="1"/>+ </svg>+);const AGENT_CONFIGS: Record<string, AgentConfig> = {aiAgent: {- icon: <RobotIcon />,+ icon: <span style={{ fontSize: '28px' }}>🤖</span>,title: 'AI Agent',subtitle: 'LangGraph Agent',- accentColor: '#9333EA',+ themeColorKey: 'purple',bottomHandles: [- { id: 'input-memory', label: 'Memory', position: '35%' },- { id: 'input-tools', label: 'Tool', position: '65%' },+ { id: 'input-skill', label: 'Skill', position: '25%' },+ { id: 'input-tools', label: 'Tool', position: '75%' },+ ],+ leftHandles: [+ { id: 'input-memory', label: 'Memory', position: '70%' },],+ topOutputHandle: { id: 'output-top', label: 'Output' },+ width: 260,+ height: 160,},chatAgent: {icon: <span style={{ fontSize: '28px' }}>🧞</span>,title: 'Zeenie',subtitle: 'Your Personal Assistant',- accentColor: '#3B82F6',+ themeColorKey: 'cyan',bottomHandles: [- { id: 'input-memory', label: 'Memory', position: '25%' },- { id: 'input-skill', label: 'Skill', position: '50%' },+ { id: 'input-skill', label: 'Skill', position: '25%' },{ id: 'input-tools', label: 'Tool', position: '75%' },],+ leftHandles: [+ { id: 'input-memory', label: 'Memory', position: '70%' },+ ],+ width: 260,+ height: 160,+ },+ socialReceive: {+ icon: <SocialReceiveIcon />,+ title: 'Social Receive',+ subtitle: 'Normalize Message',+ themeColorKey: 'purple',+ bottomHandles: [],+ rightHandles: [+ { id: 'output-message', label: 'Message', position: '20%' },+ { id: 'output-media', label: 'Media', position: '40%' },+ { id: 'output-contact', label: 'Contact', position: '60%' },+ { id: 'output-metadata', label: 'Metadata', position: '80%' },+ ],+ width: 260,+ height: 160,+ },+ socialSend: {+ icon: <SocialSendIcon />,+ title: 'Social Send',+ subtitle: 'Send Message',+ themeColorKey: 'purple',+ bottomHandles: [],+ skipInputHandle: true, // No main input - use specific handles instead+ leftHandles: [+ { id: 'input-message', label: 'Message', position: '15%' },+ { id: 'input-media', label: 'Media', position: '35%' },+ { id: 'input-contact', label: 'Contact', position: '55%' },+ { id: 'input-metadata', label: 'Metadata', position: '75%' },+ ],+ width: 260,+ height: 160,+ },+ android_agent: {+ icon: <span style={{ fontSize: '28px' }}>📱</span>,+ title: 'Android Control Agent',+ subtitle: 'Device Control',+ themeColorKey: 'green',+ bottomHandles: [+ { id: 'input-skill', label: 'Skill', position: '25%' },+ { id: 'input-tools', label: 'Tool', position: '75%' },+ ],+ leftHandles: [+ { id: 'input-memory', label: 'Memory', position: '70%' },+ ],+ topOutputHandle: { id: 'output-top', label: 'Output' },+ width: 260,+ height: 160,+ },+ coding_agent: {+ icon: <span style={{ fontSize: '28px' }}>💻</span>,+ title: 'Coding Agent',+ subtitle: 'Code Execution',+ themeColorKey: 'cyan',+ bottomHandles: [+ { id: 'input-skill', label: 'Skill', position: '25%' },+ { id: 'input-tools', label: 'Tool', position: '75%' },+ ],+ leftHandles: [+ { id: 'input-memory', label: 'Memory', position: '70%' },+ ],+ topOutputHandle: { id: 'output-top', label: 'Output' },+ width: 260,+ height: 160,+ },+ web_agent: {+ icon: <span style={{ fontSize: '28px' }}>🌐</span>,+ title: 'Web Control Agent',+ subtitle: 'Browser Automation',+ themeColorKey: 'pink',+ bottomHandles: [+ { id: 'input-skill', label: 'Skill', position: '25%' },+ { id: 'input-tools', label: 'Tool', position: '75%' },+ ],+ leftHandles: [+ { id: 'input-memory', label: 'Memory', position: '70%' },+ ],+ topOutputHandle: { id: 'output-top', label: 'Output' },+ width: 260,+ height: 160,+ },+ task_agent: {+ icon: <span style={{ fontSize: '28px' }}>📋</span>,+ title: 'Task Management Agent',+ subtitle: 'Task Automation',+ themeColorKey: 'purple',+ bottomHandles: [+ { id: 'input-skill', label: 'Skill', position: '25%' },+ { id: 'input-tools', label: 'Tool', position: '75%' },+ ],+ leftHandles: [+ { id: 'input-memory', label: 'Memory', position: '70%' },+ ],+ topOutputHandle: { id: 'output-top', label: 'Output' },+ width: 260,+ height: 160,+ },+ social_agent: {+ icon: <span style={{ fontSize: '28px' }}>📱</span>,+ title: 'Social Media Agent',+ subtitle: 'Social Messaging',+ themeColorKey: 'green',+ bottomHandles: [+ { id: 'input-skill', label: 'Skill', position: '25%' },+ { id: 'input-tools', label: 'Tool', position: '75%' },+ ],+ leftHandles: [+ { id: 'input-memory', label: 'Memory', position: '70%' },+ ],+ topOutputHandle: { id: 'output-top', label: 'Output' },+ width: 260,+ height: 160,},};@@ -75,6 +209,12 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnecta// Get config based on node typeconst config = AGENT_CONFIGS[type || 'aiAgent'] || AGENT_CONFIGS.aiAgent;+ // Resolve accent color from theme based on config key+ const accentColor = useMemo(() => {+ // Use dracula colors for vibrant accents (works well in both light and dark modes)+ return dracula[config.themeColorKey] || dracula.purple;+ }, [config.themeColorKey]);+// Get real-time node status from WebSocketconst nodeStatus = useNodeStatus(id);const isExecuting = nodeStatus?.status === 'executing';@@ -106,7 +246,7 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectaconst getBorderColor = () => {if (isExecuting) {if (theme.isDarkMode && phaseConfig) return phaseConfig.color;- return config.accentColor;+ return accentColor;}if (selected) return theme.colors.focus;return theme.colors.border;@@ -117,7 +257,7 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectaif (theme.isDarkMode && phaseConfig) {return `0 0 20px ${phaseConfig.color}80, 0 0 40px ${phaseConfig.color}40`;}- return `0 0 0 3px ${config.accentColor}80, 0 4px 16px ${config.accentColor}60`;+ return `0 0 0 3px ${accentColor}80, 0 4px 16px ${accentColor}60`;}if (selected) {return `0 4px 12px ${theme.colors.focusRing}, 0 0 0 1px ${theme.colors.focusRing}`;@@ -125,15 +265,21 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectareturn `0 2px 4px ${theme.colors.shadow}`;};+ const hasRightHandles = config.rightHandles && config.rightHandles.length > 0;+return (<divstyle={{position: 'relative',padding: theme.spacing.lg,- minWidth: '180px',- minHeight: '120px',+ paddingRight: hasRightHandles ? '60px' : theme.spacing.lg, // Extra space for right labels+ paddingLeft: theme.spacing.lg, // Standard padding (labels positioned absolutely)+ minWidth: config.width ? `${config.width}px` : config.wider ? '220px' : hasRightHandles ? '200px' : '180px',+ minHeight: config.height ? `${config.height}px` : '120px',borderRadius: theme.borderRadius.lg,- background: theme.colors.background,+ background: theme.isDarkMode+ ? `linear-gradient(135deg, ${accentColor}20 0%, ${theme.colors.backgroundAlt} 100%)`+ : `linear-gradient(145deg, #ffffff 0%, ${accentColor}08 100%)`,border: `2px solid ${getBorderColor()}`,color: theme.colors.text,fontSize: theme.fontSize.sm,@@ -151,25 +297,43 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectaanimation: 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"- />+ {/* Input Handle - skip for passive tool nodes */}+ {!config.skipInputHandle && (+ <>+ {/* Input label */}+ <div style={{+ position: 'absolute',+ left: '10px',+ top: '30%',+ transform: 'translateY(-50%)',+ fontSize: theme.fontSize.sm,+ color: theme.colors.text,+ fontWeight: theme.fontWeight.medium,+ pointerEvents: 'none',+ whiteSpace: 'nowrap'+ }}>+ Input+ </div>+ <Handle+ id="input-main"+ type="target"+ position={Position.Left}+ isConnectable={isConnectable}+ style={{+ position: 'absolute',+ left: '-6px',+ top: '30%',+ transform: 'translateY(-50%)',+ width: theme.nodeSize.handle,+ height: theme.nodeSize.handle,+ backgroundColor: theme.colors.background,+ border: `2px solid ${theme.colors.textSecondary}`,+ borderRadius: '50%'+ }}+ title="Input"+ />+ </>+ )}{/* Parameters Button */}<button@@ -198,33 +362,9 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnecta⚙️</button>- {/* Status Indicator */}- <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 ${config.accentColor}80`)- : 'none',- animation: isExecuting ? 'pulse 1s ease-in-out infinite' : 'none',- zIndex: 20- }}- title={isExecuting ? (phaseConfig?.label || 'Executing') : (nodeStatus?.status || 'Idle')}- />{/* Icon */}- <div style={{ lineHeight: '1', marginBottom: theme.spacing.xs, color: config.accentColor }}>+ <div style={{ lineHeight: '1', marginBottom: theme.spacing.xs, color: accentColor }}>{config.icon}</div>@@ -251,6 +391,44 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnecta{isExecuting && phaseConfig ? phaseConfig.label : config.subtitle}</div>+ {/* Left Input Handles (below main input) */}+ {config.leftHandles && config.leftHandles.map(h => (+ <React.Fragment key={h.id}>+ {/* Handle label positioned inside the node, to the right of the handle */}+ <div style={{+ position: 'absolute',+ left: '12px', // Inside the node border, to the right of the handle+ top: h.position,+ transform: 'translateY(-50%)',+ fontSize: theme.fontSize.sm,+ color: theme.colors.text,+ fontWeight: theme.fontWeight.medium,+ pointerEvents: 'none',+ whiteSpace: 'nowrap'+ }}>+ {h.label}+ </div>+ <Handle+ id={h.id}+ type="target"+ position={Position.Left}+ isConnectable={isConnectable}+ style={{+ position: 'absolute',+ left: '-6px',+ top: h.position,+ width: theme.nodeSize.handle,+ height: theme.nodeSize.handle,+ backgroundColor: theme.colors.background,+ border: `2px solid ${theme.colors.textSecondary}`,+ borderRadius: '0',+ transform: 'translateY(-50%) rotate(45deg)'+ }}+ title={h.label}+ />+ </React.Fragment>+ ))}+{/* Bottom Handle Labels */}<div style={{position: 'absolute',@@ -259,9 +437,9 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectaright: '0',display: 'flex',justifyContent: 'space-around',- fontSize: theme.fontSize.xs,- color: theme.colors.textSecondary,- fontWeight: theme.fontWeight.normal+ fontSize: theme.fontSize.sm,+ color: theme.colors.text,+ fontWeight: theme.fontWeight.medium}}>{config.bottomHandles.map(h => <span key={h.id}>{h.label}</span>)}</div>@@ -289,25 +467,91 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnecta/>))}- {/* 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: theme.colors.background,- border: `2px solid ${theme.colors.textSecondary}`,- borderRadius: '50%'- }}- title="Main Output"- />+ {/* Top Output Handle - for nodes like Android Toolkit that connect upward to AI Agent */}+ {config.topOutputHandle && (+ <Handle+ id={config.topOutputHandle.id}+ type="source"+ position={Position.Top}+ isConnectable={isConnectable}+ style={{+ position: 'absolute',+ top: '-6px',+ left: '50%',+ transform: 'translateX(-50%)',+ width: theme.nodeSize.handle,+ height: theme.nodeSize.handle,+ backgroundColor: accentColor,+ border: `2px solid ${theme.isDarkMode ? theme.colors.background : '#ffffff'}`,+ borderRadius: '50%',+ zIndex: 20+ }}+ title={config.topOutputHandle.label}+ />+ )}++ {/* Output Handle(s) - Multiple if rightHandles defined, single otherwise (skip if using top output) */}+ {!config.skipRightOutput && config.rightHandles && config.rightHandles.length > 0 ? (+ <>+ {/* Multiple Output Handles with inline labels */}+ {config.rightHandles.map(h => (+ <React.Fragment key={h.id}>+ {/* Handle label positioned next to handle */}+ <div style={{+ position: 'absolute',+ right: '10px',+ top: h.position,+ transform: 'translateY(-50%)',+ fontSize: theme.fontSize.sm,+ color: theme.colors.text,+ fontWeight: theme.fontWeight.medium,+ pointerEvents: 'none',+ whiteSpace: 'nowrap',+ textAlign: 'right'+ }}>+ {h.label}+ </div>+ <Handle+ id={h.id}+ type="source"+ position={Position.Right}+ isConnectable={isConnectable}+ style={{+ position: 'absolute',+ right: '-6px',+ top: h.position,+ transform: 'translateY(-50%)',+ width: theme.nodeSize.handle,+ height: theme.nodeSize.handle,+ backgroundColor: theme.colors.background,+ border: `2px solid ${theme.colors.textSecondary}`,+ borderRadius: '50%'+ }}+ title={h.label}+ />+ </React.Fragment>+ ))}+ </>+ ) : !config.skipRightOutput ? (+ <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"+ />+ ) : null}</div>);};diff --git a/client/src/components/CredentialsModal.tsx b/client/src/components/CredentialsModal.tsxindex 9805776a..b8700c7a 100644--- a/client/src/components/CredentialsModal.tsx+++ b/client/src/components/CredentialsModal.tsx@@ -5,7 +5,7 @@*/import React, { useState, useEffect, useCallback } from 'react';-import { Button, Tag, Alert, Descriptions, Space, InputNumber, Switch } from 'antd';+import { Button, Tag, Alert, Descriptions, Space, InputNumber, Switch, Input } from 'antd';import {CheckCircleOutlined,SafetyOutlined,@@ -114,10 +114,11 @@ interface Props {const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {const theme = useAppTheme();- const { validateApiKey, saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey, validateGoogleMapsKey } = useApiKeys();+ const { validateApiKey, saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey, validateGoogleMapsKey, isConnected } = useApiKeys();const whatsappStatus = useWhatsAppStatus();const androidStatus = useAndroidStatus();+// Tag style helper - consistent theming for status tagsconst getTagStyle = (type: 'success' | 'error' | 'warning'): React.CSSProperties => {const color = type === 'success' ? theme.dracula.green@@ -134,13 +135,15 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {const [loading, setLoading] = useState<Record<string, boolean>>({});const [models, setModels] = useState<Record<string, string[]>>({});const [keys, setKeys] = useState<Record<string, string>>({});+ const [proxyUrls, setProxyUrls] = useState<Record<string, string>>({});const [selectedItem, setSelectedItem] = useState<CredentialItem | null>(null);- // Load stored keys+ // Load stored keys and proxy URLsconst loadKeys = useCallback(async () => {const allItems = CATEGORIES.flatMap(c => c.items);const newKeys: Record<string, string> = {};const newValid: Record<string, boolean> = {};+ const newProxyUrls: Record<string, string> = {};for (const item of allItems) {if (item.isSpecial) continue;@@ -151,19 +154,28 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {newValid[item.id] = true;}}+ // Load proxy URL for AI providers (stored as {provider}_proxy)+ const proxyKey = `${item.id}_proxy`;+ if (await hasStoredKey(proxyKey)) {+ const proxyUrl = await getStoredApiKey(proxyKey);+ if (proxyUrl) {+ newProxyUrls[item.id] = proxyUrl;+ }+ }}setKeys(newKeys);setValidKeys(newValid);+ setProxyUrls(newProxyUrls);}, [hasStoredKey, getStoredApiKey]);useEffect(() => {- if (visible) {+ if (visible && isConnected) {loadKeys();// Select first item by defaultconst firstItem = CATEGORIES[0]?.items[0];if (firstItem) setSelectedItem(firstItem);}- }, [visible, loadKeys]);+ }, [visible, isConnected, loadKeys]);const handleValidate = async (id: string) => {const key = keys[id];@@ -1096,6 +1108,111 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {/></div>+ {/* Claude Code OAuth - Alternative auth for Anthropic */}+ {item.id === 'anthropic' && (+ <div style={{ marginBottom: theme.spacing.xl }}>+ <label style={{+ display: 'block',+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.text,+ marginBottom: theme.spacing.sm,+ }}>+ Or use Claude Code CLI+ </label>+ <div style={{ display: 'flex', gap: theme.spacing.sm }}>+ <Input+ readOnly+ value="Isolated OAuth session"+ style={{+ flex: 1,+ backgroundColor: theme.colors.background,+ borderColor: theme.colors.border,+ color: theme.colors.textSecondary,+ fontFamily: 'monospace',+ }}+ />+ <Button+ onClick={async () => {+ const result = await sendRequest('claude_oauth_login', {});+ if (result.success) {+ alert('OAuth login started. Complete authentication in the browser window that opened.');+ } else {+ alert(`Failed: ${result.error || 'Unknown error'}`);+ }+ }}+ style={{+ backgroundColor: `${theme.dracula.cyan}25`,+ borderColor: `${theme.dracula.cyan}60`,+ color: theme.dracula.cyan,+ }}+ >+ OAuth Login+ </Button>+ </div>+ <div style={{+ fontSize: theme.fontSize.xs,+ color: theme.colors.textMuted,+ marginTop: theme.spacing.sm,+ }}>+ Opens browser login without affecting your main Claude Code session.+ </div>+ </div>+ )}++ {/* Proxy URL Input - Only for AI providers */}+ {CATEGORIES.find(c => c.key === 'ai')?.items.some(i => i.id === item.id) && (+ <div style={{ marginBottom: theme.spacing.xl }}>+ <label style={{+ display: 'block',+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.text,+ marginBottom: theme.spacing.sm,+ }}>+ Proxy URL <span style={{ fontWeight: theme.fontWeight.normal, color: theme.colors.textMuted }}>(optional)</span>+ </label>+ <Space.Compact style={{ width: '100%' }}>+ <Input+ value={proxyUrls[item.id] || ''}+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setProxyUrls(p => ({ ...p, [item.id]: e.target.value }))}+ placeholder="http://localhost:11434"+ style={{+ fontFamily: 'monospace',+ backgroundColor: theme.colors.background,+ borderColor: theme.colors.border,+ color: theme.colors.text,+ }}+ />+ <Button+ onClick={async () => {+ const proxyUrl = proxyUrls[item.id]?.trim();+ if (proxyUrl) {+ await saveApiKey(`${item.id}_proxy`, proxyUrl);+ } else {+ await removeApiKey(`${item.id}_proxy`);+ setProxyUrls(p => ({ ...p, [item.id]: '' }));+ }+ }}+ style={{+ backgroundColor: `${theme.dracula.purple}25`,+ borderColor: `${theme.dracula.purple}60`,+ color: theme.dracula.purple,+ }}+ >+ {proxyUrls[item.id]?.trim() ? 'Save' : 'Clear'}+ </Button>+ </Space.Compact>+ <div style={{+ fontSize: theme.fontSize.xs,+ color: theme.colors.textMuted,+ marginTop: theme.spacing.sm,+ }}>+ Route requests through a proxy (e.g., Ollama). When set, the proxy handles authentication.+ </div>+ </div>+ )}+{/* Models list */}{models[item.id]?.length > 0 && (<div style={{ marginBottom: theme.spacing.xl }}>diff --git a/client/src/components/GenericNode.tsx b/client/src/components/GenericNode.tsxindex 183df1fd..2e19f7e6 100644--- a/client/src/components/GenericNode.tsx+++ b/client/src/components/GenericNode.tsx@@ -128,7 +128,42 @@ const GenericNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectaconst nodeInputs = getNodeInputs();const nodeOutputs = getNodeOutputs();-++ // Check if string is likely an emoji (contains emoji characters)+ 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 (handles URLs, SVG data URIs, emojis)+ const renderIcon = (icon: string | undefined) => {+ if (!icon) return '📦';++ // Handle image URLs and data URIs (including SVG)+ if (icon.startsWith('http') || icon.startsWith('data:') || icon.startsWith('/')) {+ return (+ <img+ src={icon}+ alt="icon"+ style={{+ width: '24px',+ height: '24px',+ objectFit: 'contain',+ borderRadius: '4px'+ }}+ />+ );+ }++ // If it's already an emoji, return it directly+ if (isEmoji(icon)) {+ return icon;+ }++ // Fallback for unknown formats+ return icon || '📦';+ };+// Helper functions for color managementconst getNodeColor = () => definition.defaults.color || '#9E9E9E';const getBorderColor = () => {@@ -274,7 +309,9 @@ const GenericNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectazIndex: 10,paddingRight: '4px'}}>- <span style={{ fontSize: type === 'aiAgent' ? '18px' : '24px' }}>{definition.icon}</span>+ <span style={{ fontSize: type === 'aiAgent' ? '18px' : '24px', display: 'flex', alignItems: 'center' }}>+ {renderIcon(definition.icon)}+ </span>{isRenaming ? (<inputref={inputRef}diff --git a/client/src/components/LocationParameterPanel.tsx b/client/src/components/LocationParameterPanel.tsxindex db20bd51..4fcd108e 100644--- a/client/src/components/LocationParameterPanel.tsx+++ b/client/src/components/LocationParameterPanel.tsx@@ -35,7 +35,7 @@ const LocationParameterPanel: React.FC = () => {setIsExecuting(true);try {- // Location nodes like createMap typically don't need backend execution+ // Location nodes like gmaps_create typically don't need backend execution// They're configuration nodes that output map instances} catch (error: any) {console.error('Location node execution failed:', error);@@ -52,8 +52,8 @@ const LocationParameterPanel: React.FC = () => {return null;}- // Only show LocationParameterPanel for createMap node- if (nodeDefinition.name !== 'createMap') {+ // Only show LocationParameterPanel for gmaps_create node+ if (nodeDefinition.name !== 'gmaps_create') {return null;}diff --git a/client/src/components/SquareNode.tsx b/client/src/components/SquareNode.tsxindex 33b29daf..a524a4fa 100644--- a/client/src/components/SquareNode.tsx+++ b/client/src/components/SquareNode.tsx@@ -20,7 +20,7 @@ const hasToolGroup = (definition: any): boolean => {};// Google Maps node types-const GOOGLE_MAPS_NODE_TYPES = ['createMap', 'addLocations', 'showNearbyPlaces'];+const GOOGLE_MAPS_NODE_TYPES = ['gmaps_create', 'gmaps_locations', 'gmaps_nearby_places'];// WhatsApp node typesconst WHATSAPP_NODE_TYPES = ['whatsappSend', 'whatsappReceive', 'whatsappDb'];@@ -523,9 +523,9 @@ const SquareNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectab}// Fallback logic based on node type- if (type?.includes('createMap')) return '🗺️';- if (type?.includes('addLocations')) return '🌍';- if (type?.includes('showNearbyPlaces')) return '🔍';+ if (type?.includes('gmaps_create')) return '🗺️';+ if (type?.includes('gmaps_locations')) return '🌍';+ if (type?.includes('gmaps_nearby_places')) return '🔍';return '📍';};@@ -679,7 +679,7 @@ const SquareNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectabtitle="Service Input"/>- {/* Square Output Handle - hidden for input-only nodes like console */}+ {/* Square Output Handle */}{!NO_OUTPUT_NODE_TYPES.includes(type || '') && (<Handleid="output-main"diff --git a/client/src/components/parameterPanel/InputSection.tsx b/client/src/components/parameterPanel/InputSection.tsxindex fd364cf6..05143857 100644--- a/client/src/components/parameterPanel/InputSection.tsx+++ b/client/src/components/parameterPanel/InputSection.tsx@@ -12,7 +12,8 @@ interface InputSectionProps {}interface NodeData {- id: string;+ id: string; // Unique key (includes handle suffix for multi-output)+ sourceNodeId: string; // Original node ID for template variable resolutionname: string;type: string;icon: string;@@ -59,9 +60,10 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =// 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') {+ // Config handles follow pattern: input-<type> where type is not 'main' or 'chat'+ // Examples: input-memory, input-tools, input-model, input-skill+ // Non-config (primary data) handles: input-main, input-chat+ if (handle.startsWith('input-') && handle !== 'input-main' && handle !== 'input-chat') {return true;}return false;@@ -81,17 +83,33 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =const currentNode = nodes.find((node: Node) => node.id === nodeId);const currentNodeType = currentNode?.type;+ // Agent node types that support skills (have input-skill handle)+ const AGENT_WITH_SKILLS_TYPES = [+ 'aiAgent', 'chatAgent', 'android_agent', 'coding_agent',+ 'web_agent', 'task_agent', 'social_agent'+ ];+ // Check if current node is an agent that shows skills in Middle Section+ const isAgentWithSkills = AGENT_WITH_SKILLS_TYPES.includes(currentNodeType || '');+// Collect all edges to process (direct + inherited from parent for config nodes)- interface EdgeWithLabel { edge: Edge; label?: string }+ interface EdgeWithLabel { edge: Edge; label?: string; targetHandleLabel?: 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;+ // 1. Add direct incoming edges to main data handles+ // Skip config handle connections (memory, tools, skill) for agent nodes - they're shown in Middle Section+ const directEdges = edges.filter((edge: Edge) => edge.target === nodeId);+ directEdges.forEach(edge => {+ // Skip config handle edges for agent nodes - they have dedicated UI in Middle Section+ if (isAgentWithSkills && isConfigHandle(edge.targetHandle)) {+ return;+ }+ // Extract target handle name for display (e.g., "input-skill" -> "skill")+ let targetHandleLabel: string | undefined;+ if (edge.targetHandle && edge.targetHandle.startsWith('input-') && edge.targetHandle !== 'input-main') {+ targetHandleLabel = edge.targetHandle.replace('input-', '');+ }+ edgesToProcess.push({ edge, targetHandleLabel });});- directEdges.forEach(edge => edgesToProcess.push({ edge }));// 2. If current node is a config node (memory, tool), inherit parent node's main inputsif (isConfigNode(currentNodeType)) {@@ -118,12 +136,24 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =}}- const nodeDataPromises = edgesToProcess.map(async ({ edge, label }) => {+ const nodeDataPromises = edgesToProcess.map(async ({ edge, label, targetHandleLabel }) => {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');+ // Determine output key from sourceHandle (edge-aware for multi-output nodes)+ let outputKey = 'output_0';+ if (edge.sourceHandle && edge.sourceHandle.startsWith('output-')) {+ const handleName = edge.sourceHandle.replace('output-', '');+ outputKey = `output_${handleName}`;+ }++ let executionData = await getNodeOutput(edge.source, outputKey);++ // Fallback to output_0 if specific handle output not found+ if (!executionData && outputKey !== 'output_0') {+ executionData = await getNodeOutput(edge.source, 'output_0');+ }let inputData: any = null;let outputSchema: Record<string, any>;let hasExecutionData = false;@@ -348,6 +378,62 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =timestamp: 'string',session_id: 'string'},+ // Social nodes schema (4 output handles)+ social: {+ // Output 1: message text for LLM input+ message: 'string',+ // Output 2: media data+ media: {+ url: 'string',+ type: 'string',+ mimetype: 'string',+ caption: 'string',+ size: 'number',+ thumbnail: 'string',+ filename: 'string'+ },+ // Output 3: contact/sender info+ contact: {+ sender: 'string',+ sender_phone: 'string',+ sender_name: 'string',+ sender_username: 'string',+ channel: 'string',+ is_group: 'boolean',+ group_info: 'object',+ chat_title: 'string'+ },+ // Output 4: message metadata+ metadata: {+ message_id: 'string',+ chat_id: 'string',+ timestamp: 'string',+ message_type: 'string',+ is_from_me: 'boolean',+ is_forwarded: 'boolean',+ reply_to: 'object',+ thread_id: 'string'+ },+ // Backwards compatibility - also available at top level+ message_id: 'string',+ sender: 'string',+ sender_phone: 'string',+ sender_name: 'string',+ chat_id: 'string',+ channel: 'string',+ text: 'string',+ timestamp: 'string',+ is_group: 'boolean',+ is_from_me: 'boolean'+ },+ socialSend: {+ success: 'boolean',+ message_id: 'string',+ channel: 'string',+ recipient: 'string',+ message_type: 'string',+ timestamp: 'string'+ },// Document processing schemashttpScraper: {items: 'array',@@ -387,7 +473,9 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =// Node type detectionconst isMemory = nodeType === 'simpleMemory';const nodeTypeLower = nodeType.toLowerCase();- const isAI = !isMemory && (nodeTypeLower.includes('chatmodel') || nodeTypeLower.includes('aiagent') || nodeTypeLower.includes('chatagent'));+ // AI agent types that use the AI output schema+ const aiAgentTypes = ['aiAgent', 'chatAgent', 'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent'];+ const isAI = !isMemory && (nodeTypeLower.includes('chatmodel') || aiAgentTypes.includes(nodeType));const isFile = nodeType.includes('file');const isWhatsAppDb = nodeType === 'whatsappDb';const isWhatsApp = !isWhatsAppDb && (nodeType.includes('whatsapp') || nodeType.includes('Whatsapp'));@@ -398,6 +486,8 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =const isCodeExecutor = isPython || isJavaScript;const isCronScheduler = nodeType === 'cronScheduler';const isChatTrigger = nodeType === 'chatTrigger';+ const isSocialReceive = nodeType === 'socialReceive';+ const isSocialSend = nodeType === 'socialSend';// Document processing node detectionconst documentNodeTypes = ['httpScraper', 'fileDownloader', 'documentParser', 'textChunker', 'embeddingGenerator', 'vectorStore'];@@ -416,7 +506,7 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =// Location nodes (Google Maps, not Android location)const isLocationNode = nodeType.includes('location') && !isAndroidLocation;- const isGoogleMaps = nodeType === 'createMap' || nodeType === 'addLocations' || nodeType === 'showNearbyPlaces';+ const isGoogleMaps = nodeType === 'gmaps_create' || nodeType === 'gmaps_locations' || nodeType === 'gmaps_nearby_places';// Select appropriate schemaif (isAndroidLocation) {@@ -437,15 +527,58 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =isCodeExecutor ? sampleSchemas.python :isCronScheduler ? sampleSchemas.cronScheduler :isChatTrigger ? sampleSchemas.chatTrigger :+ isSocialReceive ? sampleSchemas.social :+ isSocialSend ? sampleSchemas.socialSend :{ data: 'any' };}++ // Filter schema for multi-output nodes based on connected handle+ // When connected via specific output handle, show only that handle's schema+ if (isSocialReceive && edge.sourceHandle && edge.sourceHandle.startsWith('output-')) {+ const handleName = edge.sourceHandle.replace('output-', '');+ const socialSchema = sampleSchemas.social as Record<string, any>;+ if (handleName && socialSchema[handleName]) {+ // Show only the specific output's schema+ outputSchema = typeof socialSchema[handleName] === 'object'+ ? socialSchema[handleName]+ : { [handleName]: socialSchema[handleName] };+ }+ }}}const baseName = sourceNode?.data?.label || nodeDef?.displayName || nodeType;++ // Build display name with handle info for multi-output and multi-input nodes+ let displayName = baseName;+ let handleSuffix = '';++ // Add source handle (output) info: "Node → message"+ if (edge.sourceHandle && edge.sourceHandle.startsWith('output-')) {+ const handleName = edge.sourceHandle.replace('output-', '');+ handleSuffix = handleName;+ displayName = `${baseName} → ${handleName}`;+ }++ // Add target handle (input) info: "Node (skill)" or "Node → message (skill)"+ if (targetHandleLabel) {+ displayName = `${displayName} (${targetHandleLabel})`;+ handleSuffix = handleSuffix ? `${handleSuffix}-${targetHandleLabel}` : targetHandleLabel;+ }++ // Add inherited label: "Node (via Parent)"+ if (label) {+ displayName = `${displayName} (${label})`;+ }++ // Use unique key combining source node ID, source handle, and target handle+ // to avoid duplicate keys when multiple edges connect the same nodes+ const uniqueId = handleSuffix ? `${edge.source}-${handleSuffix}` : edge.source;+return {- id: edge.source,- name: label ? `${baseName} (${label})` : baseName,+ id: uniqueId,+ sourceNodeId: edge.source, // Keep original node ID for template variable resolution+ name: displayName,type: nodeType,icon: nodeDef?.icon || '',inputData,@@ -1046,7 +1179,7 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =<div>{typeof node.outputSchema === 'object' && node.outputSchema !== null? Object.entries(node.outputSchema).map(([key, value]) =>- renderDraggableProperty(key, value, node.id)+ renderDraggableProperty(key, value, node.sourceNodeId || node.id)): (<div style={{diff --git a/client/src/components/parameterPanel/MasterSkillEditor.tsx b/client/src/components/parameterPanel/MasterSkillEditor.tsxnew file mode 100644index 00000000..1f3972fe--- /dev/null+++ b/client/src/components/parameterPanel/MasterSkillEditor.tsx@@ -0,0 +1,434 @@+/**+ * MasterSkillEditor - Editor for Master Skill node+ *+ * Split panel showing available skills with enable/disable toggles on left,+ * and selected skill's markdown instructions on right.+ *+ * Skills are loaded from the skill folder (server/skills/).+ * The skillsConfig uses skillName (folder name) as keys.+ */++import React, { useState, useEffect, useCallback, useMemo } from 'react';+import { Input, Checkbox, Button, Spin, List, Badge, Empty, Tooltip, Alert } from 'antd';+import { SearchOutlined, ReloadOutlined, InfoCircleOutlined } from '@ant-design/icons';+import { useAppTheme } from '../../hooks/useAppTheme';+import { useWebSocket } from '../../contexts/WebSocketContext';+import { skillNodes, SKILL_NODE_TYPES } from '../../nodeDefinitions/skillNodes';+import CodeEditor from '../ui/CodeEditor';++// Skill configuration stored in node parameters+// Key is skillName (folder name like 'whatsapp-skill')+interface SkillConfig {+ enabled: boolean;+ instructions: string;+ isCustomized: boolean;+}++interface MasterSkillConfig {+ [skillName: string]: SkillConfig;+}++interface AvailableSkill {+ type: string; // Node type (e.g., 'whatsappSkill')+ skillName: string; // Skill folder name (e.g., 'whatsapp-skill') - used as config key+ displayName: string;+ icon: string;+ color: string;+ description: string;+}++interface MasterSkillEditorProps {+ skillsConfig: MasterSkillConfig;+ onConfigChange: (config: MasterSkillConfig) => void;+}++// Helper to render icon (handles emojis and SVG data URIs)+const renderSkillIcon = (icon: string, size: number = 16) => {+ if (icon.startsWith('data:') || icon.startsWith('http')) {+ return <img src={icon} alt="icon" style={{ width: size, height: size, objectFit: 'contain' }} />;+ }+ return <span style={{ fontSize: size }}>{icon}</span>;+};++const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({+ skillsConfig,+ onConfigChange+}) => {+ const theme = useAppTheme();+ const { sendRequest } = useWebSocket();+ const [selectedSkillName, setSelectedSkillName] = useState<string | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [defaultInstructions, setDefaultInstructions] = useState<Record<string, string>>({});+ const [searchQuery, setSearchQuery] = useState('');++ // Build list of available skills from node definitions+ const availableSkills = useMemo<AvailableSkill[]>(() => {+ return SKILL_NODE_TYPES+ .filter(type => type !== 'customSkill' && type !== 'masterSkill')+ .map(type => {+ const nodeDef = skillNodes[type];+ if (!nodeDef) return null;++ const skillNameProp = nodeDef.properties?.find(p => p.name === 'skillName');+ const skillName = skillNameProp?.default as string || type;++ return {+ type,+ skillName, // This is the folder name used as config key+ displayName: nodeDef.displayName || type,+ icon: nodeDef.icon || '',+ color: (nodeDef.defaults?.color as string) || '#6366F1',+ description: nodeDef.description || ''+ };+ })+ .filter((s): s is AvailableSkill => s !== null);+ }, []);++ // Filter skills based on search query+ const filteredSkills = useMemo(() => {+ if (!searchQuery.trim()) return availableSkills;+ const query = searchQuery.toLowerCase();+ return availableSkills.filter(skill =>+ skill.displayName.toLowerCase().includes(query) ||+ skill.description.toLowerCase().includes(query)+ );+ }, [availableSkills, searchQuery]);++ // Auto-select first skill+ useEffect(() => {+ if (!selectedSkillName && availableSkills.length > 0) {+ setSelectedSkillName(availableSkills[0].skillName);+ }+ }, [selectedSkillName, availableSkills]);++ // Load skill content from skill folder+ const fetchSkillContent = useCallback(async (skillName: string): Promise<string> => {+ // Already cached+ if (defaultInstructions[skillName]) {+ return defaultInstructions[skillName];+ }++ try {+ setIsLoading(true);+ const response = await sendRequest<{ instructions: string; success: boolean; error?: string }>('get_skill_content', {+ skill_name: skillName+ });++ if (response?.success && response.instructions) {+ setDefaultInstructions(prev => ({ ...prev, [skillName]: response.instructions }));+ return response.instructions;+ } else {+ console.warn('[MasterSkillEditor] No content returned for skill:', skillName, response?.error);+ }+ } catch (error) {+ console.error('[MasterSkillEditor] Failed to load skill content:', error);+ } finally {+ setIsLoading(false);+ }+ return '';+ }, [sendRequest, defaultInstructions]);++ // Load instructions when skill is selected (for preview)+ useEffect(() => {+ if (!selectedSkillName) return;++ // Skip if already cached+ if (defaultInstructions[selectedSkillName]) return;++ // Load skill content for preview+ fetchSkillContent(selectedSkillName);+ }, [selectedSkillName, defaultInstructions, fetchSkillContent]);++ // Toggle skill enabled/disabled+ const handleToggleSkill = useCallback(async (skillName: string, enabled: boolean) => {+ const currentConfig = skillsConfig[skillName];++ if (enabled && !currentConfig?.instructions) {+ // Load default instructions when enabling for first time+ const defaultContent = await fetchSkillContent(skillName);+ onConfigChange({+ ...skillsConfig,+ [skillName]: { enabled: true, instructions: defaultContent, isCustomized: false }+ });+ } else {+ onConfigChange({+ ...skillsConfig,+ [skillName]: {+ enabled,+ instructions: currentConfig?.instructions || '',+ isCustomized: currentConfig?.isCustomized || false+ }+ });+ }+ }, [skillsConfig, onConfigChange, fetchSkillContent]);++ // Update instructions+ const handleUpdateInstructions = useCallback((skillName: string, instructions: string) => {+ const currentConfig = skillsConfig[skillName];+ const defaultContent = defaultInstructions[skillName] || '';+ const isCustomized = instructions !== defaultContent;++ onConfigChange({+ ...skillsConfig,+ [skillName]: {+ enabled: currentConfig?.enabled || false,+ instructions,+ isCustomized+ }+ });+ }, [skillsConfig, onConfigChange, defaultInstructions]);++ // Reset to default from skill folder+ const handleResetToDefault = useCallback(async (skillName: string) => {+ // Clear cache to force reload from skill folder+ setDefaultInstructions(prev => {+ const next = { ...prev };+ delete next[skillName];+ return next;+ });++ const defaultContent = await fetchSkillContent(skillName);+ const currentConfig = skillsConfig[skillName];++ onConfigChange({+ ...skillsConfig,+ [skillName]: { enabled: currentConfig?.enabled || false, instructions: defaultContent, isCustomized: false }+ });+ }, [skillsConfig, onConfigChange, fetchSkillContent]);++ const selectedSkillInfo = availableSkills.find(s => s.skillName === selectedSkillName);+ const selectedSkillConfig = selectedSkillName ? skillsConfig[selectedSkillName] : undefined;+ const enabledCount = Object.values(skillsConfig).filter(c => c?.enabled).length;++ return (+ <div style={{+ display: 'flex',+ height: '100%',+ gap: theme.spacing.md,+ overflow: 'hidden'+ }}>+ {/* Left Panel - Skills List */}+ <div style={{+ flex: '0 0 260px',+ display: 'flex',+ flexDirection: 'column',+ backgroundColor: theme.colors.background,+ borderRadius: theme.borderRadius.md,+ border: `1px solid ${theme.colors.border}`,+ overflow: 'hidden'+ }}>+ {/* Header with count */}+ <div style={{+ padding: theme.spacing.sm,+ borderBottom: `1px solid ${theme.colors.border}`,+ backgroundColor: theme.colors.backgroundAlt,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between'+ }}>+ <span style={{ fontSize: theme.fontSize.sm, fontWeight: theme.fontWeight.semibold, color: theme.colors.text }}>+ Skills+ </span>+ <Badge+ count={enabledCount}+ style={{ backgroundColor: theme.dracula.purple }}+ showZero+ />+ </div>++ {/* Search */}+ <div style={{ padding: theme.spacing.sm, borderBottom: `1px solid ${theme.colors.border}` }}>+ <Input+ placeholder="Search skills..."+ prefix={<SearchOutlined style={{ color: theme.colors.textSecondary }} />}+ value={searchQuery}+ onChange={e => setSearchQuery(e.target.value)}+ allowClear+ style={{+ backgroundColor: theme.colors.background,+ borderColor: theme.colors.border,+ }}+ />+ </div>++ {/* Skills List */}+ <div style={{ flex: 1, overflowY: 'auto' }}>+ {filteredSkills.length === 0 ? (+ <Empty+ image={Empty.PRESENTED_IMAGE_SIMPLE}+ description="No skills found"+ style={{ marginTop: theme.spacing.lg }}+ />+ ) : (+ <List+ size="small"+ dataSource={filteredSkills}+ renderItem={(skill) => {+ const config = skillsConfig[skill.skillName];+ const isSelected = selectedSkillName === skill.skillName;+ const isEnabled = config?.enabled || false;+ const isCustomized = config?.isCustomized || false;++ return (+ <List.Item+ onClick={() => setSelectedSkillName(skill.skillName)}+ style={{+ padding: `${theme.spacing.sm} ${theme.spacing.md}`,+ cursor: 'pointer',+ backgroundColor: isSelected ? `${skill.color}15` : 'transparent',+ borderLeft: isSelected ? `3px solid ${skill.color}` : '3px solid transparent',+ transition: 'all 0.15s ease'+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', gap: theme.spacing.sm, width: '100%' }}>+ <Checkbox+ checked={isEnabled}+ onChange={(e) => {+ e.stopPropagation();+ handleToggleSkill(skill.skillName, e.target.checked);+ }}+ onClick={(e) => e.stopPropagation()}+ />+ {renderSkillIcon(skill.icon, 16)}+ <span style={{+ flex: 1,+ fontSize: theme.fontSize.sm,+ fontWeight: isSelected ? theme.fontWeight.semibold : theme.fontWeight.medium,+ color: isEnabled ? theme.colors.text : theme.colors.textSecondary,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap'+ }}>+ {skill.displayName}+ </span>+ {isCustomized && (+ <Tooltip title="Customized">+ <div style={{+ width: 8,+ height: 8,+ borderRadius: '50%',+ backgroundColor: theme.dracula.orange,+ flexShrink: 0+ }} />+ </Tooltip>+ )}+ </div>+ </List.Item>+ );+ }}+ />+ )}+ </div>+ </div>++ {/* Right Panel - Skill Editor */}+ <div style={{+ flex: 1,+ display: 'flex',+ flexDirection: 'column',+ backgroundColor: theme.colors.background,+ borderRadius: theme.borderRadius.md,+ border: `1px solid ${theme.colors.border}`,+ overflow: 'hidden'+ }}>+ {selectedSkillInfo ? (+ <>+ {/* Skill Header */}+ <div style={{+ padding: theme.spacing.md,+ borderBottom: `1px solid ${theme.colors.border}`,+ backgroundColor: theme.colors.backgroundAlt,+ display: 'flex',+ alignItems: 'center',+ gap: theme.spacing.md+ }}>+ {renderSkillIcon(selectedSkillInfo.icon, 24)}+ <div style={{ flex: 1 }}>+ <div style={{+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.text,+ display: 'flex',+ alignItems: 'center',+ gap: theme.spacing.sm+ }}>+ {selectedSkillInfo.displayName}+ {selectedSkillConfig?.isCustomized && (+ <Badge+ count="Customized"+ style={{+ backgroundColor: `${theme.dracula.orange}20`,+ color: theme.dracula.orange,+ fontSize: theme.fontSize.xs+ }}+ />+ )}+ </div>+ <div style={{ fontSize: theme.fontSize.xs, color: theme.colors.textSecondary, marginTop: 2 }}>+ {selectedSkillInfo.description}+ </div>+ </div>++ {/* Reset Button */}+ {selectedSkillConfig?.isCustomized && (+ <Button+ icon={<ReloadOutlined />}+ size="small"+ onClick={() => handleResetToDefault(selectedSkillName!)}+ loading={isLoading}+ style={{+ backgroundColor: `${theme.dracula.orange}15`,+ borderColor: `${theme.dracula.orange}40`,+ color: theme.dracula.orange,+ }}+ >+ Reset+ </Button>+ )}+ </div>++ {/* Code Editor */}+ <div style={{ flex: 1, padding: theme.spacing.md, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>+ {isLoading ? (+ <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>+ <Spin tip="Loading..." />+ </div>+ ) : (+ <div style={{ flex: 1, minHeight: 0 }}>+ <CodeEditor+ value={selectedSkillConfig?.instructions || defaultInstructions[selectedSkillName!] || ''}+ onChange={(value) => handleUpdateInstructions(selectedSkillName!, value)}+ language="markdown"+ placeholder="Loading skill instructions..."+ />+ </div>+ )}++ {/* Enable hint */}+ {!selectedSkillConfig?.enabled && (+ <Alert+ type="info"+ showIcon+ icon={<InfoCircleOutlined />}+ message="Enable this skill to include it when running the AI Agent."+ style={{+ marginTop: theme.spacing.md,+ backgroundColor: `${theme.dracula.cyan}10`,+ border: `1px solid ${theme.dracula.cyan}30`,+ }}+ />+ )}+ </div>+ </>+ ) : (+ <Empty+ description="Select a skill to view instructions"+ style={{ margin: 'auto' }}+ />+ )}+ </div>+ </div>+ );+};++export default MasterSkillEditor;diff --git a/client/src/components/parameterPanel/MiddleSection.tsx b/client/src/components/parameterPanel/MiddleSection.tsxindex b274a917..2ee48f61 100644--- a/client/src/components/parameterPanel/MiddleSection.tsx+++ b/client/src/components/parameterPanel/MiddleSection.tsx@@ -1,6 +1,7 @@import React, { useState, useEffect } from 'react';import ParameterRenderer from '../ParameterRenderer';import ToolSchemaEditor from './ToolSchemaEditor';+import MasterSkillEditor from './MasterSkillEditor';import { useAppTheme } from '../../hooks/useAppTheme';import { useAppStore } from '../../store/useAppStore';import { useWebSocket } from '../../contexts/WebSocketContext';@@ -8,11 +9,22 @@ import { nodeDefinitions } from '../../nodeDefinitions';import { INodeTypeDescription, INodeProperties } from '../../types/INodeProperties';import { ExecutionResult } from '../../services/executionService';import { Edge } from 'reactflow';-import { SKILL_NODE_TYPES } from '../../nodeDefinitions/skillNodes';+import { SKILL_NODE_TYPES, skillNodes } from '../../nodeDefinitions/skillNodes';// Tool node types that support schema editingconst TOOL_NODE_TYPES = ['androidTool', 'calculatorTool', 'currentTimeTool', 'webSearchTool'];+// Agent node types that support skills (have input-skill handle)+const AGENT_WITH_SKILLS_TYPES = [+ 'aiAgent',+ 'chatAgent',+ 'android_agent',+ 'coding_agent',+ 'web_agent',+ 'task_agent',+ 'social_agent'+];+interface ConnectedSkill {id: string;name: string;@@ -115,7 +127,10 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({const isCodeExecutorNode = nodeDefinition.name === 'pythonExecutor' || nodeDefinition.name === 'javascriptExecutor';// Check if this is a skill node with code editor (needs similar flex layout)- const isSkillNode = SKILL_NODE_TYPES.includes(nodeDefinition.name) && nodeDefinition.name !== 'customSkill';+ const isSkillNode = SKILL_NODE_TYPES.includes(nodeDefinition.name) && nodeDefinition.name !== 'customSkill' && nodeDefinition.name !== 'masterSkill';++ // Check if this is a master skill node (needs split panel layout)+ const isMasterSkillNode = nodeDefinition.name === 'masterSkill';// Check if this is a memory node with markdown editorconst isMemoryNode = nodeDefinition.name === 'simpleMemory';@@ -126,12 +141,16 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({// Check if this is a tool node that supports schema editingconst isToolNode = TOOL_NODE_TYPES.includes(nodeDefinition.name);- // Check if this is a Zeenie node- const isChatAgentNode = nodeDefinition.name === 'chatAgent';+ // Check if this is an agent node that supports skills (has input-skill handle)+ const isAgentWithSkills = AGENT_WITH_SKILLS_TYPES.includes(nodeDefinition.name);++ // State for Master Skill parameters+ const [masterSkillParams, setMasterSkillParams] = useState<Record<string, any>>({});+ const { sendRequest } = useWebSocket();- // Get connected skills for Zeenie nodes+ // Get connected skills for agent nodesuseEffect(() => {- if (!isChatAgentNode || !currentWorkflow) {+ if (!isAgentWithSkills || !currentWorkflow) {setConnectedSkills([]);return;}@@ -144,24 +163,90 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({edge.target === nodeId && edge.targetHandle === 'input-skill');- // Get skill node data- const skills: ConnectedSkill[] = skillEdges.map((edge: Edge) => {+ // Get skill node data - expand Master Skill nodes+ const skills: ConnectedSkill[] = [];++ for (const edge of skillEdges) {const sourceNode = nodes.find((n: any) => n.id === edge.source);const nodeType = sourceNode?.type || '';const nodeDef = nodeDefinitions[nodeType];- return {- id: edge.source,- name: sourceNode?.data?.label || nodeDef?.displayName || nodeType,- type: nodeType,- icon: nodeDef?.icon || '',- description: nodeDef?.description || '',- color: nodeDef?.defaults?.color as string || '#6366F1',- };- });+ // Check if this is a Master Skill node+ if (nodeType === 'masterSkill') {+ // Load Master Skill parameters to get enabled skills+ const loadMasterSkillParams = async () => {+ try {+ const response = await sendRequest<{ parameters: Record<string, any> }>('get_node_parameters', {+ node_id: edge.source+ });+ if (response?.parameters) {+ setMasterSkillParams(prev => ({ ...prev, [edge.source]: response.parameters }));+ }+ } catch (err) {+ console.error('[MiddleSection] Failed to load Master Skill params:', err);+ }+ };+ loadMasterSkillParams();+ } else {+ // Regular skill node+ skills.push({+ id: edge.source,+ name: sourceNode?.data?.label || nodeDef?.displayName || nodeType,+ type: nodeType,+ icon: nodeDef?.icon || '',+ description: nodeDef?.description || '',+ color: nodeDef?.defaults?.color as string || '#6366F1',+ });+ }+ }setConnectedSkills(skills);- }, [nodeId, isChatAgentNode, currentWorkflow]);+ }, [nodeId, isAgentWithSkills, currentWorkflow, sendRequest]);++ // Expand Master Skill enabled skills into connected skills list+ const expandedConnectedSkills = React.useMemo(() => {+ const skills = [...connectedSkills];++ // Get Master Skill node IDs from edges+ const nodes = currentWorkflow?.nodes || [];+ const edges = currentWorkflow?.edges || [];+ const skillEdges = edges.filter((edge: Edge) =>+ edge.target === nodeId && edge.targetHandle === 'input-skill'+ );++ for (const edge of skillEdges) {+ const sourceNode = nodes.find((n: any) => n.id === edge.source);+ if (sourceNode?.type === 'masterSkill') {+ const params = masterSkillParams[edge.source];+ const skillsConfig = params?.skillsConfig || {};++ // Add each enabled skill from Master Skill+ for (const [skillName, config] of Object.entries(skillsConfig as Record<string, any>)) {+ if (!config?.enabled) continue;++ // Find the skill node definition by skillName+ const skillNodeType = SKILL_NODE_TYPES.find(type => {+ const def = skillNodes[type];+ const skillNameProp = def?.properties?.find((p: any) => p.name === 'skillName');+ return skillNameProp?.default === skillName;+ });++ const nodeDef = skillNodeType ? skillNodes[skillNodeType] : null;++ skills.push({+ id: `${edge.source}_${skillName}`,+ name: nodeDef?.displayName || skillName,+ type: skillNodeType || 'masterSkill',+ icon: nodeDef?.icon || '🎯',+ description: nodeDef?.description || `Skill from Master Skill node`,+ color: (nodeDef?.defaults?.color as string) || '#9333EA',+ });+ }+ }+ }++ return skills;+ }, [connectedSkills, masterSkillParams, currentWorkflow, nodeId]);// Extract console output from execution resultsconst getConsoleOutput = (): string => {@@ -197,8 +282,8 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({overflow: 'hidden',position: 'relative'}}>- {/* Description - hide for code editor nodes (Python, Skill) */}- {!needsCodeEditorLayout && (+ {/* Description - hide for code editor nodes (Python, Skill) and masterSkill */}+ {!needsCodeEditorLayout && !isMasterSkillNode && (<div style={{padding: `${theme.spacing.lg} ${theme.spacing.xl} ${theme.spacing.sm}`,borderBottom: `1px solid ${theme.colors.border}`,@@ -218,6 +303,16 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({{/* Main Content Area - Flexible */}<div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0, overflow: 'hidden' }}>+ {/* Master Skill Editor - Full panel for masterSkill nodes */}+ {isMasterSkillNode ? (+ <div style={{ flex: 1, padding: theme.spacing.lg, overflow: 'hidden' }}>+ <MasterSkillEditor+ skillsConfig={parameters.skillsConfig || {}}+ onConfigChange={(config) => onParameterChange('skillsConfig', config)}+ />+ </div>+ ) : (+ <>{/* Parameters */}<div style={{padding: theme.spacing.xl,@@ -535,7 +630,7 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({)}{/* Connected Skills Section - Only for Zeenie nodes */}- {isChatAgentNode && (+ {isAgentWithSkills && (<div style={{marginTop: theme.spacing.lg,backgroundColor: theme.colors.background,@@ -597,20 +692,20 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({</div><span style={{fontSize: theme.fontSize.xs,- color: connectedSkills.length > 0 ? theme.dracula.purple : theme.colors.textMuted,+ color: expandedConnectedSkills.length > 0 ? theme.dracula.purple : theme.colors.textMuted,padding: `2px ${theme.spacing.sm}`,- backgroundColor: connectedSkills.length > 0 ? theme.dracula.purple + '20' : theme.colors.backgroundAlt,+ backgroundColor: expandedConnectedSkills.length > 0 ? theme.dracula.purple + '20' : theme.colors.backgroundAlt,borderRadius: theme.borderRadius.sm,fontWeight: theme.fontWeight.medium}}>- {connectedSkills.length}+ {expandedConnectedSkills.length}</span></div>{/* Skills Content */}{isSkillsExpanded && (<div style={{ padding: theme.spacing.md }}>- {connectedSkills.length === 0 ? (+ {expandedConnectedSkills.length === 0 ? (<div style={{display: 'flex',flexDirection: 'column',@@ -642,7 +737,7 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({</div>) : (<div style={{ display: 'flex', flexDirection: 'column', gap: theme.spacing.sm }}>- {connectedSkills.map((skill) => (+ {expandedConnectedSkills.map((skill) => (<divkey={skill.id}style={{@@ -859,6 +954,8 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({</div></div>)}+ </>+ )}</div></div>);diff --git a/client/src/components/ui/ComponentPalette.tsx b/client/src/components/ui/ComponentPalette.tsxindex 0da4112f..bac57565 100644--- a/client/src/components/ui/ComponentPalette.tsx+++ b/client/src/components/ui/ComponentPalette.tsx@@ -15,7 +15,7 @@ const CATEGORY_EMOJIS: Record<string, string> = {skill: '🎯',tool: '🛠️',location: '📍',- whatsapp: '💬',+ social: '📱',android: '📱',chat: '💭',code: '💻',@@ -23,8 +23,11 @@ const CATEGORY_EMOJIS: Record<string, string> = {util: '🔧',};+// Categories that should be merged into 'social' (Social Media Platforms)+const SOCIAL_CATEGORIES = ['whatsapp', 'social'];+// Categories shown in simple (noob) mode - only AI related-const SIMPLE_MODE_CATEGORIES = ['agent', 'model', 'skill'];+const SIMPLE_MODE_CATEGORIES = ['agent', 'model', 'skill', 'tool'];const ComponentPalette: React.FC<ComponentPaletteProps> = ({nodeDefinitions,@@ -50,7 +53,7 @@ const ComponentPalette: React.FC<ComponentPaletteProps> = ({skill: colors.categorySkill || theme.dracula.green,tool: colors.categoryTool || theme.dracula.green,location: colors.categoryLocation || theme.dracula.red,- whatsapp: colors.categoryWhatsapp || theme.dracula.green,+ social: colors.categorySocial || theme.dracula.green,android: colors.categoryAndroid || theme.dracula.cyan,chat: colors.categoryChat || theme.dracula.yellow,code: colors.categoryCode || theme.dracula.orange,@@ -66,7 +69,7 @@ const ComponentPalette: React.FC<ComponentPaletteProps> = ({skill: 'AI Skills',tool: 'AI Tools',location: 'Google Maps',- whatsapp: 'WhatsApp',+ social: 'Social Media Platforms',android: 'Android',chat: 'Chat',code: 'Code Executors',@@ -112,7 +115,13 @@ const ComponentPalette: React.FC<ComponentPaletteProps> = ({filteredDefinitions.forEach((definition) => {try {- const categoryKey = definition.group?.[0] || 'Uncategorized';+ let categoryKey = definition.group?.[0] || 'Uncategorized';++ // Merge whatsapp and social categories into 'social'+ if (SOCIAL_CATEGORIES.includes(categoryKey.toLowerCase())) {+ categoryKey = 'social';+ }+if (!categories[categoryKey]) {categories[categoryKey] = [];}diff --git a/client/src/components/ui/SettingsPanel.tsx b/client/src/components/ui/SettingsPanel.tsxindex edbf04ed..65b17fa1 100644--- a/client/src/components/ui/SettingsPanel.tsx+++ b/client/src/components/ui/SettingsPanel.tsx@@ -1,15 +1,23 @@-import React from 'react';+import React, { useState, useEffect, useCallback } from 'react';+import { Switch, InputNumber, message } from 'antd';import Modal from './Modal';import { useAppTheme } from '../../hooks/useAppTheme';+import { useWebSocket } from '../../contexts/WebSocketContext';export interface WorkflowSettings {autoSave: boolean;autoSaveInterval: number;+ sidebarDefaultOpen: boolean;+ componentPaletteDefaultOpen: boolean;+ consolePanelDefaultOpen: boolean;}export const defaultSettings: WorkflowSettings = {autoSave: true,autoSaveInterval: 30,+ sidebarDefaultOpen: true,+ componentPaletteDefaultOpen: true,+ consolePanelDefaultOpen: false,};interface SettingsPanelProps {@@ -26,131 +34,248 @@ const SettingsPanel: React.FC<SettingsPanelProps> = ({onSettingsChange,}) => {const theme = useAppTheme();+ const { sendRequest, isConnected } = useWebSocket();+ const [isLoading, setIsLoading] = useState(false);+ const [isSaving, setIsSaving] = useState(false);++ // Load settings from database on open+ useEffect(() => {+ if (isOpen && isConnected) {+ loadSettingsFromDB();+ }+ }, [isOpen, isConnected]);++ const loadSettingsFromDB = useCallback(async () => {+ setIsLoading(true);+ try {+ const response = await sendRequest<{ settings: any }>('get_user_settings', {});+ if (response?.settings) {+ const dbSettings = response.settings;+ onSettingsChange({+ autoSave: dbSettings.auto_save ?? defaultSettings.autoSave,+ autoSaveInterval: dbSettings.auto_save_interval ?? defaultSettings.autoSaveInterval,+ sidebarDefaultOpen: dbSettings.sidebar_default_open ?? defaultSettings.sidebarDefaultOpen,+ componentPaletteDefaultOpen: dbSettings.component_palette_default_open ?? defaultSettings.componentPaletteDefaultOpen,+ consolePanelDefaultOpen: dbSettings.console_panel_default_open ?? defaultSettings.consolePanelDefaultOpen,+ });+ }+ } catch (error) {+ console.error('[SettingsPanel] Failed to load settings:', error);+ } finally {+ setIsLoading(false);+ }+ }, [sendRequest, onSettingsChange]);++ const saveSettingsToDB = useCallback(async (newSettings: WorkflowSettings, showMessage = false) => {+ setIsSaving(true);+ try {+ await sendRequest('save_user_settings', {+ settings: {+ auto_save: newSettings.autoSave,+ auto_save_interval: newSettings.autoSaveInterval,+ sidebar_default_open: newSettings.sidebarDefaultOpen,+ component_palette_default_open: newSettings.componentPaletteDefaultOpen,+ console_panel_default_open: newSettings.consolePanelDefaultOpen,+ }+ });+ if (showMessage) {+ message.success('Settings saved successfully');+ }+ console.log('[SettingsPanel] Settings saved to database');+ } catch (error) {+ console.error('[SettingsPanel] Failed to save settings:', error);+ if (showMessage) {+ message.error('Failed to save settings');+ }+ } finally {+ setIsSaving(false);+ }+ }, [sendRequest]);const handleChange = (key: keyof WorkflowSettings, value: number | boolean) => {- onSettingsChange({+ const newSettings = {...settings,[key]: value,- });+ };+ onSettingsChange(newSettings);+ // Auto-save to database (without message)+ saveSettingsToDB(newSettings, false);};- const handleReset = () => {+ const handleReset = async () => {onSettingsChange(defaultSettings);+ await saveSettingsToDB(defaultSettings, true);};- const handleSave = () => {- // Settings are already persisted to localStorage via onSettingsChange- console.log('[SettingsPanel] Settings saved');- onClose();+ const handleSave = async () => {+ await saveSettingsToDB(settings, true);};- const inputStyle: React.CSSProperties = {- width: '100%',- padding: `${theme.spacing.sm} ${theme.spacing.md}`,- backgroundColor: theme.colors.background,+ // Section card style+ const sectionStyle: React.CSSProperties = {+ marginBottom: theme.spacing.lg,+ padding: theme.spacing.lg,+ backgroundColor: theme.colors.backgroundAlt,+ borderRadius: theme.borderRadius.md,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,+ // Section header style+ const sectionHeaderStyle: React.CSSProperties = {+ display: 'flex',+ alignItems: 'center',+ gap: theme.spacing.sm,+ marginBottom: theme.spacing.lg,+ paddingBottom: theme.spacing.md,+ borderBottom: `1px solid ${theme.colors.border}`,+ };++ const sectionIconStyle: React.CSSProperties = {+ width: '32px',+ height: '32px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ fontSize: '16px',+ backgroundColor: `${theme.dracula.purple}20`,+ borderRadius: theme.borderRadius.md,+ };++ const sectionTitleStyle: React.CSSProperties = {+ fontSize: theme.fontSize.base,+ fontWeight: theme.fontWeight.semibold,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,+ marginTop: '2px',};- const checkboxContainerStyle: React.CSSProperties = {+ const settingRowStyle: React.CSSProperties = {display: 'flex',- alignItems: 'flex-start',- gap: theme.spacing.sm,- marginBottom: theme.spacing.lg,+ alignItems: 'center',+ justifyContent: 'space-between',+ padding: `${theme.spacing.sm} 0`,};- 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 settingLabelStyle: React.CSSProperties = {+ flex: 1,};- const sectionTitleStyle: React.CSSProperties = {- fontSize: theme.fontSize.base,- fontWeight: theme.fontWeight.semibold,+ const labelTextStyle: React.CSSProperties = {+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,color: theme.colors.text,- marginBottom: theme.spacing.lg,+ };++ // Button style helper following ParameterPanel pattern+ const actionButtonStyle = (color: string, isDisabled = false): React.CSSProperties => ({display: 'flex',alignItems: 'center',- gap: theme.spacing.sm,- };+ gap: '6px',+ padding: '6px 12px',+ 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+ // Header actions with title and buttonsconst headerActions = (<div style={{display: 'flex',- gap: '12px',+ gap: '16px',alignItems: 'center'}}>+ {/* Title */}<div style={{display: 'flex',alignItems: 'center',gap: '8px',- fontSize: '16px',- fontWeight: '600',+ fontSize: '15px',+ fontWeight: 600,color: theme.colors.text,fontFamily: 'system-ui, sans-serif'}}>- <span style={{ fontSize: '20px' }}>{'\u2699'}</span>- <span>Workflow Settings</span>+ <span>{'\u2699'}</span>+ <span>Settings</span></div>+ {/* Buttons: Reset, Save, Close */}<div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>+ {/* Reset Button */}<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'- }}+ style={actionButtonStyle(theme.dracula.orange, isSaving)}onClick={handleReset}+ disabled={isSaving}+ title="Reset to default settings"+ onMouseEnter={(e) => {+ if (!isSaving) {+ e.currentTarget.style.backgroundColor = `${theme.dracula.orange}40`;+ }+ }}+ onMouseLeave={(e) => {+ if (!isSaving) {+ e.currentTarget.style.backgroundColor = `${theme.dracula.orange}25`;+ }+ }}>- Reset to Defaults+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">+ <path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/>+ <path d="M3 3v5h5"/>+ </svg>+ Reset</button>+ {/* Save 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'- }}+ style={actionButtonStyle(theme.dracula.green, isSaving)}onClick={handleSave}+ disabled={isSaving}+ title="Save settings"+ onMouseEnter={(e) => {+ if (!isSaving) {+ e.currentTarget.style.backgroundColor = `${theme.dracula.green}40`;+ }+ }}+ onMouseLeave={(e) => {+ if (!isSaving) {+ e.currentTarget.style.backgroundColor = `${theme.dracula.green}25`;+ }+ }}>- 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>+ {isSaving ? 'Saving...' : 'Save'}+ </button>++ {/* Close Button */}+ <button+ style={actionButtonStyle(theme.dracula.pink, false)}+ onClick={onClose}+ title="Close settings"+ 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>+ Close</button></div></div>@@ -166,75 +291,108 @@ const SettingsPanel: React.FC<SettingsPanelProps> = ({headerActions={headerActions}><div style={{- padding: theme.spacing.xl,+ display: 'flex',+ flexDirection: 'column',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>+ {/* Content */}+ <div style={{+ flex: 1,+ overflow: 'auto',+ padding: theme.spacing.lg,+ opacity: isLoading ? 0.6 : 1,+ transition: 'opacity 0.2s ease',+ }}>+ {/* UI Defaults Section */}+ <div style={sectionStyle}>+ <div style={sectionHeaderStyle}>+ <div style={sectionIconStyle}>{'\uD83D\uDDA5'}</div>+ <div style={sectionTitleStyle}>UI Defaults</div>+ </div>++ <div style={settingRowStyle}>+ <div style={settingLabelStyle}>+ <div style={labelTextStyle}>Sidebar Open by Default</div>+ <div style={descriptionStyle}>Show the sidebar panel when the application starts</div>+ </div>+ <Switch+ size="small"+ checked={settings.sidebarDefaultOpen}+ onChange={(checked) => handleChange('sidebarDefaultOpen', checked)}+ disabled={isSaving}+ />+ </div>++ <div style={settingRowStyle}>+ <div style={settingLabelStyle}>+ <div style={labelTextStyle}>Component Palette Open by Default</div>+ <div style={descriptionStyle}>Show the component palette when the application starts</div>+ </div>+ <Switch+ size="small"+ checked={settings.componentPaletteDefaultOpen}+ onChange={(checked) => handleChange('componentPaletteDefaultOpen', checked)}+ disabled={isSaving}+ />+ </div>++ <div style={settingRowStyle}>+ <div style={settingLabelStyle}>+ <div style={labelTextStyle}>Console Panel Open by Default</div>+ <div style={descriptionStyle}>Show the console/chat panel at the bottom when the application starts</div>+ </div>+ <Switch+ size="small"+ checked={settings.consolePanelDefaultOpen}+ onChange={(checked) => handleChange('consolePanelDefaultOpen', checked)}+ disabled={isSaving}+ /></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}+ {/* Auto-save Settings */}+ <div style={sectionStyle}>+ <div style={sectionHeaderStyle}>+ <div style={{ ...sectionIconStyle, backgroundColor: `${theme.dracula.cyan}20` }}>{'\uD83D\uDCBE'}</div>+ <div style={sectionTitleStyle}>Auto-save</div>+ </div>++ <div style={settingRowStyle}>+ <div style={settingLabelStyle}>+ <div style={labelTextStyle}>Enable Auto-save</div>+ <div style={descriptionStyle}>Automatically save the workflow at regular intervals</div>+ </div>+ <Switch+ size="small"+ checked={settings.autoSave}+ onChange={(checked) => handleChange('autoSave', checked)}+ disabled={isSaving}/>- <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>++ {settings.autoSave && (+ <div style={{ ...settingRowStyle, marginTop: theme.spacing.xs }}>+ <div style={settingLabelStyle}>+ <div style={labelTextStyle}>Auto-save Interval</div>+ <div style={descriptionStyle}>How often to auto-save (10-300 seconds)</div>+ </div>+ <InputNumber+ size="small"+ min={10}+ max={300}+ step={5}+ value={settings.autoSaveInterval}+ onChange={(value) => handleChange('autoSaveInterval', value ?? 30)}+ disabled={isSaving}+ style={{ width: 80 }}+ suffix="s"+ />+ </div>+ )}</div></div>+</div></Modal>);diff --git a/client/src/nodeDefinitions.ts b/client/src/nodeDefinitions.tsindex b2bbafb6..879d441f 100644--- a/client/src/nodeDefinitions.ts+++ b/client/src/nodeDefinitions.ts@@ -5,6 +5,7 @@ import { INodeTypeDescription } from './types/INodeProperties';import { aiModelNodes } from './nodeDefinitions/aiModelNodes';import { aiAgentNodes, AI_NODE_TYPES } from './nodeDefinitions/aiAgentNodes';import { toolNodes, TOOL_NODE_TYPES } from './nodeDefinitions/toolNodes';+import { specializedAgentNodes, SPECIALIZED_AGENT_TYPES } from './nodeDefinitions/specializedAgentNodes';import { locationNodes, LOCATION_NODE_TYPES } from './nodeDefinitions/locationNodes';import { whatsappNodes, WHATSAPP_NODE_TYPES } from './nodeDefinitions/whatsappNodes';import { workflowNodes } from './nodeDefinitions/workflowNodes';@@ -15,6 +16,7 @@ import { codeNodes, CODE_NODE_TYPES } from './nodeDefinitions/codeNodes';import { utilityNodes, UTILITY_NODE_TYPES } from './nodeDefinitions/utilityNodes';import { skillNodes, SKILL_NODE_TYPES } from './nodeDefinitions/skillNodes';import { documentNodes, DOCUMENT_NODE_TYPES } from './nodeDefinitions/documentNodes';+import { socialNodes, SOCIAL_NODE_TYPES } from './nodeDefinitions/socialNodes';// ============================================================================// MAIN NODE REGISTRY - Combining all modular definitions@@ -27,6 +29,7 @@ export const nodeDefinitions: Record<string, INodeTypeDescription> = {...aiModelNodes,...aiAgentNodes,...toolNodes,+ ...specializedAgentNodes,...locationNodes,...whatsappNodes,...androidServiceNodes,@@ -34,7 +37,8 @@ export const nodeDefinitions: Record<string, INodeTypeDescription> = {...codeNodes,...utilityNodes,...skillNodes,- ...documentNodes+ ...documentNodes,+ ...socialNodes};// ============================================================================@@ -90,6 +94,10 @@ export const TOOL_NODES = [...TOOL_NODE_TYPES];+export const SPECIALIZED_AGENT_NODES = [+ ...SPECIALIZED_AGENT_TYPES+];+export const SKILL_NODES = [...SKILL_NODE_TYPES];@@ -98,5 +106,9 @@ export const DOCUMENT_NODES = [...DOCUMENT_NODE_TYPES];+export const SOCIAL_NODES = [+ ...SOCIAL_NODE_TYPES+];+// Re-export types and utilities from modular files for external accessexport { createBaseChatModel } from './nodeDefinitions/aiModelNodes';\ No newline at end of filediff --git a/client/src/nodeDefinitions/aiAgentNodes.ts b/client/src/nodeDefinitions/aiAgentNodes.tsindex 0616a5a1..fffc26bd 100644--- a/client/src/nodeDefinitions/aiAgentNodes.ts+++ b/client/src/nodeDefinitions/aiAgentNodes.ts@@ -26,11 +26,23 @@ export const aiAgentNodes: Record<string, INodeTypeDescription> = {type: 'main' as NodeConnectionType,description: 'Agent input'},+ {+ name: 'skill',+ displayName: 'Skill',+ type: 'main' as NodeConnectionType,+ description: 'Skill nodes that provide context and instructions'+ },{name: 'memory',displayName: 'Memory',type: 'main' as NodeConnectionType,- description: 'Memory node connection for conversation history'+ description: 'Memory node for conversation history'+ },+ {+ name: 'tools',+ displayName: 'Tool',+ type: 'main' as NodeConnectionType,+ description: 'Tool nodes for agent capabilities'}],outputs: [{@@ -168,13 +180,7 @@ export const aiAgentNodes: Record<string, INodeTypeDescription> = {name: 'main',displayName: 'Input',type: 'main' as NodeConnectionType,- description: 'Chat input'- },- {- name: 'memory',- displayName: 'Memory',- type: 'main' as NodeConnectionType,- description: 'Memory node for conversation history'+ description: 'Agent input'},{name: 'skill',@@ -182,6 +188,12 @@ export const aiAgentNodes: Record<string, INodeTypeDescription> = {type: 'main' as NodeConnectionType,description: 'Skill nodes that provide context and instructions via SKILL.md'},+ {+ name: 'memory',+ displayName: 'Memory',+ type: 'main' as NodeConnectionType,+ description: 'Memory node for conversation history'+ },{name: 'tools',displayName: 'Tool',diff --git a/client/src/nodeDefinitions/locationNodes.ts b/client/src/nodeDefinitions/locationNodes.tsindex 0cf5e2d4..b5195176 100644--- a/client/src/nodeDefinitions/locationNodes.ts+++ b/client/src/nodeDefinitions/locationNodes.ts@@ -13,16 +13,16 @@ 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',+ // GMaps Create - Initialize Google Maps JavaScript API with coordinates+ gmaps_create: {+ displayName: 'GMaps Create',+ name: 'gmaps_create',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' },+ defaults: { name: 'GMaps Create', color: '#1A73E8' },inputs: [{name: 'main',displayName: 'Map Configuration',@@ -98,16 +98,16 @@ export const locationNodes: Record<string, INodeTypeDescription> = {]},- // Add Locations - Google Maps Geocoding Service (Dual-purpose: workflow node + AI tool)- addLocations: {- displayName: 'Add Locations',- name: 'addLocations',+ // GMaps Locations - Google Maps Geocoding Service (Dual-purpose: workflow node + AI tool)+ gmaps_locations: {+ displayName: 'GMaps Locations',+ name: 'gmaps_locations',icon: '🌍',group: ['location', 'service', 'tool'], // 'tool' enables AI Agent tool callingversion: 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' },+ defaults: { name: 'GMaps Locations', color: '#34A853' },inputs: [{name: 'main',displayName: 'Geocoding Input',@@ -219,16 +219,16 @@ export const locationNodes: Record<string, INodeTypeDescription> = {]},- // Show Nearby Places - Google Maps Places API nearbySearch (Dual-purpose: workflow node + AI tool)- showNearbyPlaces: {- displayName: 'Show Nearby Places',- name: 'showNearbyPlaces',+ // GMaps Nearby Places - Google Maps Places API nearbySearch (Dual-purpose: workflow node + AI tool)+ gmaps_nearby_places: {+ displayName: 'GMaps Nearby Places',+ name: 'gmaps_nearby_places',icon: '🔍',group: ['location', 'service', 'tool'], // 'tool' enables AI Agent tool callingversion: 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' },+ defaults: { name: 'GMaps Nearby Places', color: '#FF6D01' },inputs: [{name: 'main',displayName: 'Search Parameters',@@ -460,4 +460,4 @@ export const locationNodes: Record<string, INodeTypeDescription> = {};// List of Google Maps node types for easy identification-export const LOCATION_NODE_TYPES = ['createMap', 'addLocations', 'showNearbyPlaces'];\ No newline at end of file+export const LOCATION_NODE_TYPES = ['gmaps_create', 'gmaps_locations', 'gmaps_nearby_places'];diff --git a/client/src/nodeDefinitions/skillNodes.ts b/client/src/nodeDefinitions/skillNodes.tsindex d7e772bb..780e5516 100644--- a/client/src/nodeDefinitions/skillNodes.ts+++ b/client/src/nodeDefinitions/skillNodes.ts@@ -172,6 +172,34 @@ export const skillNodes: Record<string, INodeTypeDescription> = {description: 'Search the web for current information, news, facts, and real-time data'}),+ // Master Skill - Aggregates multiple skills with enable/disable toggles+ masterSkill: {+ displayName: 'Master Skill',+ name: 'masterSkill',+ icon: '🎯',+ group: ['skill'],+ version: 1,+ subtitle: 'Skill Aggregator',+ description: 'Combine multiple skills with enable/disable toggles in a single connection',+ defaults: { name: 'Master Skill', color: '#9333EA' },+ inputs: [],+ outputs: [{+ name: 'skill',+ displayName: 'Skills',+ type: 'main' as NodeConnectionType,+ description: 'Connect to AI Agent skill handle'+ }],+ properties: [+ {+ displayName: 'Skills Configuration',+ name: 'skillsConfig',+ type: 'json',+ default: {},+ description: 'Enabled skills and their instructions'+ }+ ]+ },+// Custom Skill - User-created skillcustomSkill: {displayName: 'Custom Skill',@@ -216,6 +244,7 @@ export const SKILL_NODE_TYPES = ['androidSkill','codeSkill','webSearchSkill',+ 'masterSkill','customSkill'];diff --git a/client/src/nodeDefinitions/socialNodes.ts b/client/src/nodeDefinitions/socialNodes.tsnew file mode 100644index 00000000..999dac66--- /dev/null+++ b/client/src/nodeDefinitions/socialNodes.ts@@ -0,0 +1,750 @@+// Social Node Definitions - Unified social platform messaging+// Supports: WhatsApp, Telegram, Discord, Slack, Signal, SMS, Webchat, Email, Matrix, Teams+import {+ INodeTypeDescription,+ NodeConnectionType+} from '../types/INodeProperties';++// ============================================================================+// SOCIAL ICONS (SVG Data URIs)+// ============================================================================++// Social Receive - Funnel/filter icon (normalizes messages from platform triggers)+const SOCIAL_RECEIVE_ICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%236366F1'%3E%3Cpath d='M4.25 5.61C6.27 8.2 10 13 10 13v6c0 .55.45 1 1 1h2c.55 0 1-.45 1-1v-6s3.73-4.8 5.75-7.39C20.26 4.95 19.79 4 18.95 4H5.04c-.83 0-1.31.95-.79 1.61z'/%3E%3C/svg%3E";++// Social Send - Paper plane with globe (multi-platform send)+const SOCIAL_SEND_ICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%236366F1'%3E%3Cpath d='M2.01 21L23 12 2.01 3 2 10l15 2-15 2z'/%3E%3Ccircle cx='18' cy='18' r='4' fill='%236366F1' stroke='%23fff' stroke-width='1'/%3E%3Cpath d='M18 15.5c-1.38 0-2.5 1.12-2.5 2.5s1.12 2.5 2.5 2.5 2.5-1.12 2.5-2.5-1.12-2.5-2.5-2.5zm0 1c.28 0 .5.22.5.5v1h1c.28 0 .5.22.5.5s-.22.5-.5.5h-1v1c0 .28-.22.5-.5.5s-.5-.22-.5-.5v-1h-1c-.28 0-.5-.22-.5-.5s.22-.5.5-.5h1v-1c0-.28.22-.5.5-.5z' fill='%23fff'/%3E%3C/svg%3E";++// ============================================================================+// CHANNEL OPTIONS - All supported platforms+// ============================================================================+const CHANNEL_OPTIONS = [+ { name: 'All Channels', value: 'all' },+ { name: 'WhatsApp', value: 'whatsapp' },+ { name: 'Telegram', value: 'telegram' },+ { name: 'Discord', value: 'discord' },+ { name: 'Slack', value: 'slack' },+ { name: 'Signal', value: 'signal' },+ { name: 'SMS', value: 'sms' },+ { name: 'Webchat', value: 'webchat' },+ { name: 'Email', value: 'email' },+ { name: 'Matrix', value: 'matrix' },+ { name: 'Teams', value: 'teams' }+];++// For send node (no "All Channels" option)+const SEND_CHANNEL_OPTIONS = CHANNEL_OPTIONS.filter(opt => opt.value !== 'all');++// ============================================================================+// MESSAGE TYPE OPTIONS+// ============================================================================+const MESSAGE_TYPE_OPTIONS = [+ { name: 'All Types', value: 'all' },+ { 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' },+ { name: 'Poll', value: 'poll' },+ { name: 'Reaction', value: 'reaction' }+];++// For send node (no "All Types" option, plus buttons/list)+const SEND_MESSAGE_TYPE_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' },+ { name: 'Poll', value: 'poll' },+ { name: 'Buttons', value: 'buttons' },+ { name: 'List', value: 'list' }+];++// ============================================================================+// SOCIAL NODES+// ============================================================================++export const socialNodes: Record<string, INodeTypeDescription> = {+ // Social Receive - Normalizes and filters messages from platform-specific triggers+ socialReceive: {+ displayName: 'Social Receive',+ name: 'socialReceive',+ icon: SOCIAL_RECEIVE_ICON,+ group: ['social'],+ version: 1,+ subtitle: 'Normalize Message',+ description: 'Connects to platform-specific triggers (WhatsApp Receive, etc.) and normalizes messages into unified format. Filters by channel, message type, and sender.',+ defaults: { name: 'Social Receive', color: '#6366F1' },+ inputs: [{+ name: 'main',+ displayName: 'Input',+ type: 'main' as NodeConnectionType,+ description: 'Connect to platform trigger (WhatsApp Receive, Telegram, etc.)'+ }],+ outputs: [+ {+ name: 'message',+ displayName: 'Message',+ type: 'main' as NodeConnectionType,+ description: 'Text message content for LLM input'+ },+ {+ name: 'media',+ displayName: 'Media',+ type: 'main' as NodeConnectionType,+ description: 'Media data: url, type, mimetype, caption, size, thumbnail, filename'+ },+ {+ name: 'contact',+ displayName: 'Contact',+ type: 'main' as NodeConnectionType,+ description: 'Sender info: sender, sender_phone, sender_name, channel, is_group, group_info'+ },+ {+ name: 'metadata',+ displayName: 'Metadata',+ type: 'main' as NodeConnectionType,+ description: 'Message metadata: message_id, chat_id, timestamp, is_forwarded, is_from_me, reply_to'+ }+ ],+ properties: [+ // ===== CHANNEL FILTER =====+ {+ displayName: 'Channel Filter',+ name: 'channelFilter',+ type: 'options',+ options: CHANNEL_OPTIONS,+ default: 'all',+ description: 'Filter messages by source platform'+ },++ // ===== MESSAGE TYPE FILTER =====+ {+ displayName: 'Message Type',+ name: 'messageTypeFilter',+ type: 'options',+ options: MESSAGE_TYPE_OPTIONS,+ default: 'all',+ description: 'Filter by message content type'+ },++ // ===== SENDER FILTER =====+ {+ displayName: 'Sender Filter',+ name: 'senderFilter',+ 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: { senderFilter: ['contact'] }+ },+ placeholder: '1234567890',+ description: 'Phone number to filter messages from (without + prefix)'+ },+ {+ displayName: 'Group ID',+ name: 'groupId',+ type: 'string',+ default: '',+ required: true,+ displayOptions: {+ show: { senderFilter: ['group'] }+ },+ placeholder: '[email protected]',+ description: 'Group identifier to filter messages from'+ },+ {+ displayName: 'Keywords',+ name: 'keywords',+ type: 'string',+ default: '',+ required: true,+ displayOptions: {+ show: { senderFilter: ['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: 'Ignore Bots',+ name: 'ignoreBots',+ type: 'boolean',+ default: false,+ description: 'Do not trigger on messages from bots'+ },+ {+ displayName: 'Include Media Data',+ name: 'includeMediaData',+ type: 'boolean',+ default: false,+ description: 'Include base64 media data in output (increases memory usage)'+ }+ ]+ },++ // Social Send - Unified outbound message (dual-purpose: workflow + AI tool)+ socialSend: {+ displayName: 'Social Send',+ name: 'socialSend',+ icon: SOCIAL_SEND_ICON,+ group: ['social', 'tool'],+ version: 1,+ subtitle: 'Send Message',+ description: 'Send messages to any supported chat platform (WhatsApp, Telegram, Discord, Slack, Signal, SMS, Webchat, Email, Matrix, Teams). Works as workflow node or AI Agent tool.',+ defaults: { name: 'Social Send', color: '#6366F1' },+ inputs: [+ {+ name: 'main',+ displayName: 'Input',+ type: 'main' as NodeConnectionType,+ description: 'Main message input'+ },+ {+ name: 'message',+ displayName: 'Message',+ type: 'main' as NodeConnectionType,+ description: 'Text message content from Social Receive'+ },+ {+ name: 'media',+ displayName: 'Media',+ type: 'main' as NodeConnectionType,+ description: 'Media data: url, type, mimetype, caption, size, thumbnail, filename'+ },+ {+ name: 'contact',+ displayName: 'Contact',+ type: 'main' as NodeConnectionType,+ description: 'Sender info: sender, sender_phone, sender_name, channel, is_group, group_info'+ },+ {+ name: 'metadata',+ displayName: 'Metadata',+ type: 'main' as NodeConnectionType,+ description: 'Message metadata: message_id, chat_id, timestamp, for reply functionality'+ }+ ],+ outputs: [+ {+ name: 'main',+ displayName: 'Output',+ type: 'main' as NodeConnectionType,+ description: 'Message output'+ },+ {+ name: 'tool',+ displayName: 'Tool',+ type: 'main' as NodeConnectionType,+ description: 'Connect to AI Agent tool handle'+ }+ ],+ properties: [+ // ===== CHANNEL SELECTION =====+ {+ displayName: 'Channel',+ name: 'channel',+ type: 'options',+ options: SEND_CHANNEL_OPTIONS,+ default: 'whatsapp',+ description: 'Target chat platform'+ },++ // ===== RECIPIENT =====+ {+ displayName: 'Send To',+ name: 'recipientType',+ type: 'options',+ options: [+ { name: 'Phone Number', value: 'phone' },+ { name: 'Group', value: 'group' },+ { name: 'Channel', value: 'channel' },+ { name: 'User ID', value: 'user' },+ { name: 'Chat ID', value: 'chat' }+ ],+ default: 'phone',+ description: 'Type of recipient'+ },+ {+ displayName: 'Phone Number',+ name: 'phone',+ type: 'string',+ default: '',+ required: true,+ placeholder: '1234567890',+ description: 'Recipient phone number (without + prefix)',+ displayOptions: {+ show: { recipientType: ['phone'] }+ }+ },+ {+ displayName: 'Group ID',+ name: 'groupId',+ type: 'string',+ default: '',+ required: true,+ placeholder: '[email protected]',+ description: 'Group identifier',+ displayOptions: {+ show: { recipientType: ['group'] }+ }+ },+ {+ displayName: 'Channel ID',+ name: 'channelId',+ type: 'string',+ default: '',+ required: true,+ placeholder: 'C01234567',+ description: 'Channel identifier',+ displayOptions: {+ show: { recipientType: ['channel'] }+ }+ },+ {+ displayName: 'User ID',+ name: 'userId',+ type: 'string',+ default: '',+ required: true,+ placeholder: 'U01234567',+ description: 'User identifier',+ displayOptions: {+ show: { recipientType: ['user'] }+ }+ },+ {+ displayName: 'Chat ID',+ name: 'chatId',+ type: 'string',+ default: '',+ required: true,+ placeholder: 'chat_123456',+ description: 'Generic chat identifier',+ displayOptions: {+ show: { recipientType: ['chat'] }+ }+ },+ {+ displayName: 'Thread ID',+ name: 'threadId',+ type: 'string',+ default: '',+ placeholder: 'thread_123',+ description: 'Thread to reply in (optional)'+ },++ // ===== MESSAGE TYPE =====+ {+ displayName: 'Message Type',+ name: 'messageType',+ type: 'options',+ options: SEND_MESSAGE_TYPE_OPTIONS,+ 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'] }+ }+ },+ {+ displayName: 'Format',+ name: 'format',+ type: 'options',+ options: [+ { name: 'Plain Text', value: 'plain' },+ { name: 'Markdown', value: 'markdown' },+ { name: 'HTML', value: 'html' }+ ],+ default: 'plain',+ description: 'Text formatting',+ displayOptions: {+ show: { messageType: ['text'] }+ }+ },++ // ===== MEDIA MESSAGES (image, video, audio, document, sticker) =====+ {+ displayName: 'Media Source',+ name: 'mediaSource',+ type: 'options',+ options: [+ { name: 'URL', value: 'url' },+ { name: 'Base64 Data', value: 'base64' },+ { name: 'File Path', value: 'file' }+ ],+ default: 'url',+ description: 'Source of media data',+ displayOptions: {+ show: { messageType: ['image', 'video', 'audio', 'document', 'sticker'] }+ }+ },+ {+ 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: '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 Path',+ name: 'filePath',+ type: 'string',+ default: '',+ required: true,+ placeholder: '/path/to/file.jpg',+ description: 'Server file path',+ displayOptions: {+ show: { messageType: ['image', 'video', 'audio', 'document', 'sticker'], mediaSource: ['file'] }+ }+ },+ {+ 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 Phone',+ name: 'contactPhone',+ type: 'string',+ default: '',+ placeholder: '+1234567890',+ description: 'Contact phone number',+ displayOptions: {+ show: { messageType: ['contact'] }+ }+ },+ {+ displayName: 'Contact vCard',+ name: 'vcard',+ type: 'string',+ default: '',+ typeOptions: { rows: 4 },+ placeholder: 'BEGIN:VCARD\nVERSION:3.0\nFN:John Doe\nTEL:+1234567890\nEND:VCARD',+ description: 'vCard 3.0 format string (optional if phone provided)',+ displayOptions: {+ show: { messageType: ['contact'] }+ }+ },++ // ===== POLL MESSAGE =====+ {+ displayName: 'Poll Question',+ name: 'pollQuestion',+ type: 'string',+ default: '',+ required: true,+ placeholder: 'What is your favorite color?',+ description: 'Poll question',+ displayOptions: {+ show: { messageType: ['poll'] }+ }+ },+ {+ displayName: 'Poll Options',+ name: 'pollOptions',+ type: 'string',+ default: '',+ required: true,+ placeholder: 'Red, Blue, Green, Yellow',+ description: 'Comma-separated poll options',+ displayOptions: {+ show: { messageType: ['poll'] }+ }+ },+ {+ displayName: 'Allow Multiple',+ name: 'pollAllowMultiple',+ type: 'boolean',+ default: false,+ description: 'Allow multiple selections',+ displayOptions: {+ show: { messageType: ['poll'] }+ }+ },++ // ===== BUTTONS MESSAGE =====+ {+ displayName: 'Button Text',+ name: 'buttonText',+ type: 'string',+ default: '',+ required: true,+ placeholder: 'Choose an option',+ description: 'Text displayed above buttons',+ displayOptions: {+ show: { messageType: ['buttons'] }+ }+ },+ {+ displayName: 'Buttons (JSON)',+ name: 'buttons',+ type: 'string',+ default: '[]',+ required: true,+ typeOptions: { rows: 4 },+ placeholder: '[{"id": "btn1", "text": "Option 1"}, {"id": "btn2", "text": "Option 2"}]',+ description: 'JSON array of button objects with id and text',+ displayOptions: {+ show: { messageType: ['buttons'] }+ }+ },++ // ===== LIST MESSAGE =====+ {+ displayName: 'List Title',+ name: 'listTitle',+ type: 'string',+ default: '',+ required: true,+ placeholder: 'Select an option',+ description: 'Title for the list',+ displayOptions: {+ show: { messageType: ['list'] }+ }+ },+ {+ displayName: 'Button Text',+ name: 'listButtonText',+ type: 'string',+ default: 'View Options',+ required: true,+ description: 'Text for the list button',+ displayOptions: {+ show: { messageType: ['list'] }+ }+ },+ {+ displayName: 'List Sections (JSON)',+ name: 'listSections',+ type: 'string',+ default: '[]',+ required: true,+ typeOptions: { rows: 6 },+ placeholder: '[{"title": "Section 1", "rows": [{"id": "row1", "title": "Row 1", "description": "Description"}]}]',+ description: 'JSON array of sections with rows',+ displayOptions: {+ show: { messageType: ['list'] }+ }+ },++ // ===== REPLY (QUOTE) =====+ {+ displayName: 'Reply To Message',+ name: 'replyToMessage',+ 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: { replyToMessage: [true] }+ }+ },+ {+ displayName: 'Reply To Current',+ name: 'replyToCurrent',+ type: 'boolean',+ default: false,+ description: 'Reply to the message that triggered this workflow',+ displayOptions: {+ show: { replyToMessage: [true] }+ }+ },++ // ===== SEND OPTIONS =====+ {+ displayName: 'Send as Voice Note',+ name: 'audioAsVoice',+ type: 'boolean',+ default: false,+ description: 'Send audio as voice message',+ displayOptions: {+ show: { messageType: ['audio'] }+ }+ },+ {+ displayName: 'Disable Link Preview',+ name: 'disablePreview',+ type: 'boolean',+ default: false,+ description: 'Disable link preview in text messages',+ displayOptions: {+ show: { messageType: ['text'] }+ }+ },+ {+ displayName: 'Silent',+ name: 'silent',+ type: 'boolean',+ default: false,+ description: 'Send without notification sound'+ },+ {+ displayName: 'Protect Content',+ name: 'protectContent',+ type: 'boolean',+ default: false,+ description: 'Prevent forwarding/saving (if supported)'+ }+ ]+ }+};++// ============================================================================+// EXPORTS+// ============================================================================++export const SOCIAL_NODE_TYPES = ['socialReceive', 'socialSend'];diff --git a/client/src/nodeDefinitions/specializedAgentNodes.ts b/client/src/nodeDefinitions/specializedAgentNodes.tsnew file mode 100644index 00000000..bfc92924--- /dev/null+++ b/client/src/nodeDefinitions/specializedAgentNodes.ts@@ -0,0 +1,351 @@+// Specialized Agent Node Definitions - AI Agents with specialized capabilities+import {+ INodeTypeDescription,+ NodeConnectionType,+ INodeProperties+} from '../types/INodeProperties';++// ============================================================================+// SHARED AI AGENT PROPERTIES - Used by Specialized Agent Nodes+// ============================================================================++// Properties shared by AI Agent and all Specialized Agent nodes+export const AI_AGENT_PROPERTIES: INodeProperties[] = [+ {+ displayName: 'AI Provider',+ name: 'provider',+ type: 'options',+ options: [+ { name: 'OpenAI', value: 'openai' },+ { name: 'Anthropic (Claude)', value: 'anthropic' },+ { name: 'Google (Gemini)', value: 'gemini' },+ { name: 'Groq', value: 'groq' },+ { name: 'OpenRouter', value: 'openrouter' }+ ],+ 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'+ },+ {+ displayName: 'Thinking/Reasoning',+ name: 'thinkingEnabled',+ type: 'boolean',+ default: false,+ description: 'Enable extended thinking for supported providers'+ },+ {+ displayName: 'Thinking Budget',+ name: 'thinkingBudget',+ type: 'number',+ default: 2048,+ typeOptions: { minValue: 1024, maxValue: 16000 },+ description: 'Token budget for thinking (Claude, Gemini, Cerebras)',+ displayOptions: { show: { thinkingEnabled: [true] } }+ },+ {+ displayName: 'Reasoning Effort',+ name: 'reasoningEffort',+ type: 'options',+ options: [+ { name: 'Low', value: 'low' },+ { name: 'Medium', value: 'medium' },+ { name: 'High', value: 'high' }+ ],+ default: 'medium',+ description: 'Reasoning effort level (OpenAI o-series, Groq)',+ displayOptions: { show: { thinkingEnabled: [true] } }+ }+ ] as any+ }+];++// ============================================================================+// SPECIALIZED AGENT NODES - AI Agents with domain-specific capabilities+// ============================================================================++export const specializedAgentNodes: Record<string, INodeTypeDescription> = {+ // Android Control Agent - AI Agent with Android device control capabilities+ android_agent: {+ displayName: 'Android Control Agent',+ name: 'android_agent',+ icon: '📱',+ group: ['agent', 'ai'],+ version: 1,+ subtitle: 'Device Control',+ description: 'AI Agent specialized for Android device control. Connect skills, memory, and tool nodes to enable Android automation capabilities.',+ defaults: { name: 'Android Control Agent', color: '#3DDC84' },+ inputs: [+ {+ name: 'main',+ displayName: 'Input',+ type: 'main' as NodeConnectionType,+ description: 'Agent input'+ },+ {+ name: 'skill',+ displayName: 'Skill',+ type: 'main' as NodeConnectionType,+ description: 'Skill nodes that provide context and instructions'+ },+ {+ name: 'memory',+ displayName: 'Memory',+ type: 'main' as NodeConnectionType,+ description: 'Memory node for conversation history'+ },+ {+ name: 'tools',+ displayName: 'Tool',+ type: 'main' as NodeConnectionType,+ description: 'Tool nodes for Android device operations'+ }+ ],+ outputs: [{+ name: 'main',+ displayName: 'Output',+ type: 'main' as NodeConnectionType,+ description: 'Agent output'+ }],+ properties: AI_AGENT_PROPERTIES+ },++ // Coding Agent - AI Agent with code execution capabilities+ coding_agent: {+ displayName: 'Coding Agent',+ name: 'coding_agent',+ icon: '💻',+ group: ['agent', 'ai'],+ version: 1,+ subtitle: 'Code Execution',+ description: 'AI Agent specialized for code execution. Connect skills, memory, and code executor nodes to enable coding capabilities.',+ defaults: { name: 'Coding Agent', color: '#61DAFB' },+ inputs: [+ {+ name: 'main',+ displayName: 'Input',+ type: 'main' as NodeConnectionType,+ description: 'Agent input'+ },+ {+ name: 'skill',+ displayName: 'Skill',+ type: 'main' as NodeConnectionType,+ description: 'Skill nodes that provide context and instructions'+ },+ {+ name: 'memory',+ displayName: 'Memory',+ type: 'main' as NodeConnectionType,+ description: 'Memory node for conversation history'+ },+ {+ name: 'tools',+ displayName: 'Tool',+ type: 'main' as NodeConnectionType,+ description: 'Code executor nodes (Python, JavaScript, etc.)'+ }+ ],+ outputs: [{+ name: 'main',+ displayName: 'Output',+ type: 'main' as NodeConnectionType,+ description: 'Agent output'+ }],+ properties: AI_AGENT_PROPERTIES+ },++ // Web Control Agent - AI Agent with web automation capabilities+ web_agent: {+ displayName: 'Web Control Agent',+ name: 'web_agent',+ icon: '🌐',+ group: ['agent', 'ai'],+ version: 1,+ subtitle: 'Browser Automation',+ description: 'AI Agent specialized for web automation. Connect skills, memory, and web control nodes to enable browser automation and HTTP capabilities.',+ defaults: { name: 'Web Control Agent', color: '#FF6B6B' },+ inputs: [+ {+ name: 'main',+ displayName: 'Input',+ type: 'main' as NodeConnectionType,+ description: 'Agent input'+ },+ {+ name: 'skill',+ displayName: 'Skill',+ type: 'main' as NodeConnectionType,+ description: 'Skill nodes that provide context and instructions'+ },+ {+ name: 'memory',+ displayName: 'Memory',+ type: 'main' as NodeConnectionType,+ description: 'Memory node for conversation history'+ },+ {+ name: 'tools',+ displayName: 'Tool',+ type: 'main' as NodeConnectionType,+ description: 'Web control nodes (browser, scraper, HTTP, etc.)'+ }+ ],+ outputs: [{+ name: 'main',+ displayName: 'Output',+ type: 'main' as NodeConnectionType,+ description: 'Agent output'+ }],+ properties: AI_AGENT_PROPERTIES+ },++ // Task Management Agent - AI Agent with task automation capabilities+ task_agent: {+ displayName: 'Task Management Agent',+ name: 'task_agent',+ icon: '📋',+ group: ['agent', 'ai'],+ version: 1,+ subtitle: 'Task Automation',+ description: 'AI Agent specialized for task management. Connect skills, memory, and task nodes to enable scheduling and reminder capabilities.',+ defaults: { name: 'Task Management Agent', color: '#9B59B6' },+ inputs: [+ {+ name: 'main',+ displayName: 'Input',+ type: 'main' as NodeConnectionType,+ description: 'Agent input'+ },+ {+ name: 'skill',+ displayName: 'Skill',+ type: 'main' as NodeConnectionType,+ description: 'Skill nodes that provide context and instructions'+ },+ {+ name: 'memory',+ displayName: 'Memory',+ type: 'main' as NodeConnectionType,+ description: 'Memory node for conversation history'+ },+ {+ name: 'tools',+ displayName: 'Tool',+ type: 'main' as NodeConnectionType,+ description: 'Task management nodes (scheduler, reminders, etc.)'+ }+ ],+ outputs: [{+ name: 'main',+ displayName: 'Output',+ type: 'main' as NodeConnectionType,+ description: 'Agent output'+ }],+ properties: AI_AGENT_PROPERTIES+ },++ // Social Media Agent - AI Agent with social messaging capabilities+ social_agent: {+ displayName: 'Social Media Agent',+ name: 'social_agent',+ icon: '📱',+ group: ['agent', 'ai'],+ version: 1,+ subtitle: 'Social Messaging',+ description: 'AI Agent specialized for social media. Connect skills, memory, and messaging nodes to enable WhatsApp, Telegram, and other social capabilities.',+ defaults: { name: 'Social Media Agent', color: '#25D366' },+ inputs: [+ {+ name: 'main',+ displayName: 'Input',+ type: 'main' as NodeConnectionType,+ description: 'Agent input'+ },+ {+ name: 'skill',+ displayName: 'Skill',+ type: 'main' as NodeConnectionType,+ description: 'Skill nodes that provide context and instructions'+ },+ {+ name: 'memory',+ displayName: 'Memory',+ type: 'main' as NodeConnectionType,+ description: 'Memory node for conversation history'+ },+ {+ name: 'tools',+ displayName: 'Tool',+ type: 'main' as NodeConnectionType,+ description: 'Social media nodes (WhatsApp, Telegram, etc.)'+ }+ ],+ outputs: [{+ name: 'main',+ displayName: 'Output',+ type: 'main' as NodeConnectionType,+ description: 'Agent output'+ }],+ properties: AI_AGENT_PROPERTIES+ }+};++// ============================================================================+// EXPORTS+// ============================================================================++// List of specialized agent node types for identification+export const SPECIALIZED_AGENT_TYPES = ['android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent'];diff --git a/client/src/nodeDefinitions/toolNodes.ts b/client/src/nodeDefinitions/toolNodes.tsindex 154f854c..36e124b7 100644--- a/client/src/nodeDefinitions/toolNodes.ts+++ b/client/src/nodeDefinitions/toolNodes.ts@@ -1,7 +1,7 @@// Tool Node Definitions - Tool nodes for AI Agent tool callingimport {INodeTypeDescription,- NodeConnectionType+ NodeConnectionType,} from '../types/INodeProperties';// ============================================================================@@ -158,35 +158,6 @@ export const toolNodes: Record<string, INodeTypeDescription> = {description: 'Maximum number of results to return'}]- },-- // Android Toolkit - aggregates Android service nodes for AI Agent- // Follows n8n Sub-Node pattern and LangChain Toolkit pattern- androidTool: {- displayName: 'Android Toolkit',- name: 'androidTool',- icon: '📱',- group: ['tool', 'ai'],- version: 1,- subtitle: 'Device Control',- description: 'Aggregate Android service nodes into a single AI-callable tool. Connect Android nodes to enable those capabilities.',- defaults: { name: 'Android Toolkit', color: '#3DDC84' },- // Input for connecting Android service nodes (uses SquareNode's input-main)- inputs: [{- name: 'main',- displayName: 'Android Services',- type: 'main' as NodeConnectionType,- description: 'Connect Android service nodes (battery, wifi, apps, etc.)'- }],- // Output connects to AI Agent's input-tools handle (uses SquareNode's output-main)- outputs: [{- name: 'main',- displayName: 'Tool Output',- type: 'main' as NodeConnectionType,- description: 'Connect to AI Agent tool handle'- }],- // No properties - schema is managed by ToolSchemaEditor component- properties: []}};@@ -195,4 +166,4 @@ export const toolNodes: Record<string, INodeTypeDescription> = {// ============================================================================// List of tool node types for identification-export const TOOL_NODE_TYPES = ['calculatorTool', 'currentTimeTool', 'webSearchTool', 'androidTool'];+export const TOOL_NODE_TYPES = ['calculatorTool', 'currentTimeTool', 'webSearchTool'];diff --git a/client/src/schemas/workflowSchema.ts b/client/src/schemas/workflowSchema.tsindex 554043ce..86218f9e 100644--- a/client/src/schemas/workflowSchema.ts+++ b/client/src/schemas/workflowSchema.ts@@ -73,9 +73,9 @@ export const WorkflowJSONSchema = {"openaiChatModel","anthropicChatModel","googleChatModel",- "createMap",- "addLocations",- "showNearbyPlaces",+ "gmaps_create",+ "gmaps_locations",+ "gmaps_nearby_places","whatsappSendMessage","whatsappReceiveMessage"]diff --git a/client/src/services/executionService.ts b/client/src/services/executionService.tsindex 93634acd..7302e961 100644--- a/client/src/services/executionService.ts+++ b/client/src/services/executionService.ts@@ -4,6 +4,7 @@ import { SCHEDULER_NODE_TYPES } from '../nodeDefinitions/schedulerNodes';import { CODE_NODE_TYPES } from '../nodeDefinitions/codeNodes';import { UTILITY_NODE_TYPES } from '../nodeDefinitions/utilityNodes';import { DOCUMENT_NODE_TYPES } from '../nodeDefinitions/documentNodes';+import { SPECIALIZED_AGENT_TYPES } from '../nodeDefinitions/specializedAgentNodes';import { Node, Edge } from 'reactflow';import { INodeExecutionData } from '../types/INodeProperties';import { API_CONFIG } from '../config/api';@@ -189,6 +190,8 @@ export class ExecutionService {// AI Nodes'aiAgent','chatAgent',+ // Specialized Agent Nodes (use chatAgent backend handler)+ ...SPECIALIZED_AGENT_TYPES,// Note: simpleMemory is passive - accessed by AI Agent automatically, not executed directly'openaiChatModel','anthropicChatModel',@@ -201,9 +204,9 @@ export class ExecutionService {'ollamaChatModel', // Planned'mistralChatModel', // Planned// Google Maps Nodes- 'createMap',- 'addLocations',- 'showNearbyPlaces',+ 'gmaps_create',+ 'gmaps_locations',+ 'gmaps_nearby_places',// WhatsApp Nodes'whatsappSend','whatsappReceive',diff --git a/client/src/store/useAppStore.ts b/client/src/store/useAppStore.tsindex 3ff61c25..217cd3bb 100644--- a/client/src/store/useAppStore.ts+++ b/client/src/store/useAppStore.ts@@ -40,6 +40,7 @@ interface AppStore {selectedNode: Node | null; // Kept for backward compatibility, derived from workflowUIStatessidebarVisible: boolean;componentPaletteVisible: boolean;+ consolePanelVisible: boolean;proMode: boolean; // false = noob mode (only AI categories), true = pro mode (all categories)renamingNodeId: string | null;@@ -63,6 +64,13 @@ interface AppStore {toggleProMode: () => void;setRenamingNodeId: (nodeId: string | null) => void;+ // UI defaults from database+ setSidebarVisible: (visible: boolean) => void;+ setComponentPaletteVisible: (visible: boolean) => void;+ setConsolePanelVisible: (visible: boolean) => void;+ toggleConsolePanelVisible: () => void;+ applyUIDefaults: (defaults: { sidebarDefaultOpen?: boolean; componentPaletteDefaultOpen?: boolean; consolePanelDefaultOpen?: boolean }) => void;+// Per-workflow UI state actions (n8n pattern)getWorkflowUIState: (workflowId: string) => WorkflowUIState;setWorkflowExecuting: (workflowId: string, isExecuting: boolean) => void;@@ -117,6 +125,7 @@ const migrateNodes = (nodes: Node[]): Node[] => {const STORAGE_KEYS = {sidebarVisible: 'ui_sidebar_visible',componentPaletteVisible: 'ui_component_palette_visible',+ consolePanelVisible: 'ui_console_panel_visible',proMode: 'ui_pro_mode',};@@ -149,6 +158,7 @@ export const useAppStore = create<AppStore>((set, get) => ({selectedNode: null,sidebarVisible: loadBooleanFromStorage(STORAGE_KEYS.sidebarVisible, true),componentPaletteVisible: loadBooleanFromStorage(STORAGE_KEYS.componentPaletteVisible, true),+ consolePanelVisible: loadBooleanFromStorage(STORAGE_KEYS.consolePanelVisible, false),proMode: loadBooleanFromStorage(STORAGE_KEYS.proMode, false), // Default to noob moderenamingNodeId: null,savedWorkflows: [],@@ -368,6 +378,53 @@ export const useAppStore = create<AppStore>((set, get) => ({set({ renamingNodeId: nodeId });},+ // UI defaults setters (for database sync)+ setSidebarVisible: (visible) => {+ saveBooleanToStorage(STORAGE_KEYS.sidebarVisible, visible);+ set({ sidebarVisible: visible });+ },++ setComponentPaletteVisible: (visible) => {+ saveBooleanToStorage(STORAGE_KEYS.componentPaletteVisible, visible);+ set({ componentPaletteVisible: visible });+ },++ setConsolePanelVisible: (visible) => {+ saveBooleanToStorage(STORAGE_KEYS.consolePanelVisible, visible);+ set({ consolePanelVisible: visible });+ },++ toggleConsolePanelVisible: () => {+ set((state) => {+ const newValue = !state.consolePanelVisible;+ saveBooleanToStorage(STORAGE_KEYS.consolePanelVisible, newValue);+ return { consolePanelVisible: newValue };+ });+ },++ applyUIDefaults: (defaults) => {+ const updates: Partial<{ sidebarVisible: boolean; componentPaletteVisible: boolean; consolePanelVisible: boolean }> = {};++ if (defaults.sidebarDefaultOpen !== undefined) {+ updates.sidebarVisible = defaults.sidebarDefaultOpen;+ saveBooleanToStorage(STORAGE_KEYS.sidebarVisible, defaults.sidebarDefaultOpen);+ }++ if (defaults.componentPaletteDefaultOpen !== undefined) {+ updates.componentPaletteVisible = defaults.componentPaletteDefaultOpen;+ saveBooleanToStorage(STORAGE_KEYS.componentPaletteVisible, defaults.componentPaletteDefaultOpen);+ }++ if (defaults.consolePanelDefaultOpen !== undefined) {+ updates.consolePanelVisible = defaults.consolePanelDefaultOpen;+ saveBooleanToStorage(STORAGE_KEYS.consolePanelVisible, defaults.consolePanelDefaultOpen);+ }++ if (Object.keys(updates).length > 0) {+ set(updates);+ }+ },+// Per-workflow UI state management (n8n pattern - isolated execution state per workflow)getWorkflowUIState: (workflowId) => {const { workflowUIStates } = get();diff --git a/client/src/utils/locationUtils.ts b/client/src/utils/locationUtils.tsindex b25b28c2..2cf2b4d6 100644--- a/client/src/utils/locationUtils.ts+++ b/client/src/utils/locationUtils.ts@@ -72,7 +72,7 @@ export const createLocationUpdateHandler = (export const isLocationNode = (nodeDefinition: INodeTypeDescription | null): boolean => {if (!nodeDefinition) return false;- const isCreateMap = nodeDefinition.name === 'createMap';+ const isCreateMap = nodeDefinition.name === 'gmaps_create';const hasLocationGroup = nodeDefinition.group?.includes('location') ?? false;const hasCoordinates = getCoordinateParams(nodeDefinition).latParam !== null;@@ -81,5 +81,5 @@ export const isLocationNode = (nodeDefinition: INodeTypeDescription | null): boo// Check if node should show maps previewexport const shouldShowMapsPreview = (nodeDefinition: INodeTypeDescription | null): boolean => {- return nodeDefinition?.name === 'createMap';+ return nodeDefinition?.name === 'gmaps_create';};\ No newline at end of filediff --git a/client/src/utils/nodeUtils.ts b/client/src/utils/nodeUtils.tsindex 6de83eb9..4ab50825 100644--- a/client/src/utils/nodeUtils.ts+++ b/client/src/utils/nodeUtils.ts@@ -10,9 +10,9 @@ export const getShortNodeName = (nodeType: string): string => {// AI Agents'aiAgent': 'ai',// Location Services- 'createMap': 'map',- 'addLocations': 'location',- 'showNearbyPlaces': 'places'+ 'gmaps_create': 'map',+ 'gmaps_locations': 'location',+ 'gmaps_nearby_places': 'places'};// If we have a specific mapping, use itdiff --git a/package.json b/package.jsonindex 2052effa..5c6425a7 100644--- a/package.json+++ b/package.json@@ -37,6 +37,7 @@"scripts/","client/src/","client/public/",+ "client/dist/","client/*.json","client/*.html","client/*.js",@@ -48,8 +49,9 @@"!server/**/__pycache__/","!server/data/","!server/whatsapp-rpc/node_modules/",- "!server/whatsapp-rpc/bin/","!server/whatsapp-rpc/data/",+ "!server/whatsapp-rpc/server",+ "!server/whatsapp-rpc/server.exe","!**/node_modules/","!**/.vite/",".env.template",diff --git a/scripts/install.js b/scripts/install.jsindex b776c694..27c62201 100644--- a/scripts/install.js+++ b/scripts/install.js@@ -172,39 +172,68 @@ console.log('Installing...');console.log('');try {+ const clientDir = resolve(ROOT, 'client');+ const serverDir = resolve(ROOT, 'server');+ const whatsappDir = resolve(ROOT, 'server/whatsapp-rpc');+ const clientDistExists = existsSync(resolve(clientDir, 'dist', 'index.html'));+ const binPath = resolve(whatsappDir, 'bin', isWindows ? 'whatsapp-rpc-server.exe' : 'whatsapp-rpc-server');+ const binExists = existsSync(binPath);++ // Calculate total steps+ let totalSteps = 1; // .env always+ if (!clientDistExists) totalSteps += 2; // client deps + build+ totalSteps += 1; // Python deps always+ if (!binExists) totalSteps += 1; // WhatsApp setup if no binary+ let step = 0;+// Create .env if needed+ step++;const envPath = resolve(ROOT, '.env');const templatePath = resolve(ROOT, '.env.template');if (!existsSync(envPath) && existsSync(templatePath)) {copyFileSync(templatePath, envPath);- console.log('[1/5] Created .env from template');+ console.log(`[${step}/${totalSteps}] Created .env from template`);} else {- console.log('[1/5] .env exists');+ console.log(`[${step}/${totalSteps}] .env exists`);}- // Install client dependencies- console.log('[2/5] Installing client dependencies...');- run('npm install', resolve(ROOT, 'client'), 600000); // 10 min timeout-- // Build client- console.log('[3/5] Building client...');- run('npm run build', resolve(ROOT, 'client'), 600000); // 10 min timeout+ // Skip client install/build if dist already exists (pre-built in npm package)+ if (clientDistExists) {+ console.log(`[SKIP] Client already built (dist/index.html exists)`);+ } else {+ // Install client dependencies+ step++;+ console.log(`[${step}/${totalSteps}] Installing client dependencies...`);+ run('npm install', clientDir, 600000); // 10 min timeout++ // Build client+ step++;+ console.log(`[${step}/${totalSteps}] Building client...`);+ run('npm run build', clientDir, 600000); // 10 min timeout+ }- // Install Python dependencies- console.log('[4/5] Installing Python dependencies...');- const serverDir = resolve(ROOT, 'server');+ // Install Python dependencies (always needed - venv not included in package)+ step++;+ console.log(`[${step}/${totalSteps}] Installing Python dependencies...`);run('uv venv', serverDir); // 5 min defaultrun('uv sync', serverDir, 600000); // 10 min timeout- // WhatsApp service- console.log('[5/5] Setting up WhatsApp service...');- const whatsappDir = resolve(ROOT, 'server/whatsapp-rpc');- run('npm install', whatsappDir); // 5 min default-- const binPath = resolve(whatsappDir, 'bin', isWindows ? 'whatsapp-rpc-server.exe' : 'whatsapp-rpc-server');- if (!existsSync(binPath) && go) {- console.log(' Building WhatsApp from source...');- run('npm run build', whatsappDir);+ // WhatsApp service - skip if binary already exists (pre-built in npm package)+ if (binExists) {+ console.log(`[SKIP] WhatsApp binary already exists`);+ } else {+ step++;+ console.log(`[${step}/${totalSteps}] Setting up WhatsApp service...`);+ run('npm install', whatsappDir); // 5 min default++ // Try to build from source if Go is available+ if (go) {+ console.log(' Building WhatsApp from source...');+ run('npm run build', whatsappDir);+ } else {+ console.log(' WhatsApp binary not found and Go not available');+ console.log(' WhatsApp features will not work until binary is provided');+ }}console.log('');diff --git a/scripts/serve-client.js b/scripts/serve-client.jsnew file mode 100644index 00000000..733c8ed4--- /dev/null+++ b/scripts/serve-client.js@@ -0,0 +1,67 @@+#!/usr/bin/env node+/**+ * Simple static file server for pre-built client.+ * Used in production mode when client dist exists but node_modules doesn't.+ */+import { createServer } from 'http';+import { readFile } from 'fs';+import { join, extname } from 'path';+import { fileURLToPath } from 'url';+import { dirname, resolve } from 'path';++const __dirname = dirname(fileURLToPath(import.meta.url));+const DIST_DIR = resolve(__dirname, '..', 'client', 'dist');+const PORT = parseInt(process.env.VITE_CLIENT_PORT) || 3000;++const MIME_TYPES = {+ '.html': 'text/html',+ '.js': 'text/javascript',+ '.css': 'text/css',+ '.json': 'application/json',+ '.png': 'image/png',+ '.jpg': 'image/jpeg',+ '.gif': 'image/gif',+ '.svg': 'image/svg+xml',+ '.ico': 'image/x-icon',+ '.woff': 'font/woff',+ '.woff2': 'font/woff2',+ '.ttf': 'font/ttf',+};++const server = createServer((req, res) => {+ let url = req.url === '/' ? '/index.html' : req.url;++ // Remove query string+ url = url.split('?')[0];++ const filePath = join(DIST_DIR, url);++ readFile(filePath, (err, content) => {+ if (err) {+ // SPA fallback - serve index.html for routes+ if (err.code === 'ENOENT' && !extname(url)) {+ readFile(join(DIST_DIR, 'index.html'), (err2, indexContent) => {+ if (err2) {+ res.writeHead(404);+ res.end('Not found');+ } else {+ res.writeHead(200, { 'Content-Type': 'text/html' });+ res.end(indexContent);+ }+ });+ } else {+ res.writeHead(404);+ res.end('Not found');+ }+ } else {+ const ext = extname(filePath);+ const contentType = MIME_TYPES[ext] || 'application/octet-stream';+ res.writeHead(200, { 'Content-Type': contentType });+ res.end(content);+ }+ });+});++server.listen(PORT, '0.0.0.0', () => {+ console.log(`Client: http://localhost:${PORT}`);+});diff --git a/scripts/start.js b/scripts/start.jsindex ad0dafff..4e57fc44 100644--- a/scripts/start.js+++ b/scripts/start.js@@ -195,12 +195,30 @@ if (!allFree) {log('Starting services...');log('Press Ctrl+C to stop (use npm run stop to kill all services)\n');+// Detect if we should run dev mode (vite) or production mode (static serve)+const clientDist = resolve(ROOT, 'client', 'dist', 'index.html');+const clientNodeModules = resolve(ROOT, 'client', 'node_modules');+const isProduction = existsSync(clientDist) && !existsSync(clientNodeModules);++if (isProduction) {+ log('Mode: Production (serving pre-built client)');+} else {+ log('Mode: Development (running vite)');+}+// Build concurrently command based on config-const services = [- 'npm:client:start',- 'npm:python:start',- 'npm:whatsapp:api'-];+const services = [];++// Client: use static server in production, vite in development+if (isProduction) {+ // Use dedicated serve-client.js script+ services.push(`"node ${resolve(ROOT, 'scripts', 'serve-client.js').replace(/\\/g, '/')}"`);+} else {+ services.push('npm:client:start');+}++services.push('npm:python:start');+services.push('npm:whatsapp:api');if (config.temporalEnabled) {services.push('npm:temporal:worker');@@ -209,7 +227,7 @@ if (config.temporalEnabled) {const concurrentlyArgs = ['--raw','--kill-others-on-fail',- ...services.map(s => `"${s}"`)+ ...services];// Use spawn with shell:true for cross-platform compatibilitydiff --git a/server/constants.py b/server/constants.pyindex 8ef5ded6..d59306be 100644--- a/server/constants.py+++ b/server/constants.py@@ -22,6 +22,11 @@ AI_CHAT_MODEL_TYPES: FrozenSet[str] = frozenset([AI_AGENT_TYPES: FrozenSet[str] = frozenset(['aiAgent','chatAgent',+ 'android_agent',+ 'coding_agent',+ 'web_agent',+ 'task_agent',+ 'social_agent',])AI_MEMORY_TYPES: FrozenSet[str] = frozenset([@@ -79,9 +84,9 @@ CONFIG_NODE_TYPES: FrozenSet[str] = (# =============================================================================GOOGLE_MAPS_TYPES: FrozenSet[str] = frozenset([- 'createMap',- 'addLocations',- 'showNearbyPlaces',+ 'gmaps_create',+ 'gmaps_locations',+ 'gmaps_nearby_places',])# =============================================================================@@ -143,6 +148,20 @@ WHATSAPP_TYPES: FrozenSet[str] = frozenset(['whatsappDb',])+# =============================================================================+# SOCIAL NODE TYPES (unified messaging)+# =============================================================================++SOCIAL_NODE_TYPES: FrozenSet[str] = frozenset([+ 'socialReceive',+ 'socialSend',+])++# Dual-purpose social nodes (workflow node + AI tool)+SOCIAL_TOOL_TYPES: FrozenSet[str] = frozenset([+ 'socialSend', # Can be used as AI Agent tool+])+# =============================================================================# CHAT NODE TYPES# =============================================================================diff --git a/server/core/config.py b/server/core/config.pyindex 3cfbc815..fdac22e7 100644--- a/server/core/config.py+++ b/server/core/config.py@@ -62,6 +62,9 @@ class Settings(BaseSettings):# WhatsApp Service URL (Flask service)whatsapp_service_url: str = Field(default="http://localhost:5000", env="WHATSAPP_SERVICE_URL")+ # AI Proxy Configuration (Ollama-style proxy)+ ai_proxy_default_port: int = Field(default=11434, env="AI_PROXY_DEFAULT_PORT")+# WebSocket Configurationwebsocket_url: str = Field(default="", env="WEBSOCKET_URL")websocket_api_key: Optional[str] = Field(default=None, env="WEBSOCKET_API_KEY")diff --git a/server/core/database.py b/server/core/database.pyindex 641509c3..49655a0b 100644--- a/server/core/database.py+++ b/server/core/database.py@@ -5,10 +5,11 @@ from typing import Dict, Any, List, Optionalfrom sqlmodel import SQLModel, select, Sessionfrom sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmakerfrom sqlalchemy.exc import IntegrityError+from sqlalchemy import textfrom contextlib import asynccontextmanagerfrom core.config import Settings-from models.database import NodeParameter, Workflow, Execution, APIKey, APIKeyValidation, NodeOutput, ConversationMessage, ToolSchema, UserSkill, ChatMessage+from models.database import NodeParameter, Workflow, Execution, APIKey, APIKeyValidation, NodeOutput, ConversationMessage, ToolSchema, UserSkill, ChatMessage, UserSettingsfrom models.cache import CacheEntry # SQLite-backed cache for Redis alternativefrom models.auth import User # Import User model to ensure table creationfrom core.logging import get_logger@@ -54,12 +55,31 @@ class Database:async with self.engine.begin() as conn:await conn.run_sync(SQLModel.metadata.create_all)+ # Add missing columns to existing tables (simple migration)+ await self._migrate_user_settings()+logger.info("Database initialized successfully")except Exception as e:logger.error("Database startup failed", error=str(e))raise+ async def _migrate_user_settings(self):+ """Add missing columns to user_settings table."""+ try:+ async with self.engine.begin() as conn:+ # Check if column exists and add if missing+ result = await conn.execute(text("PRAGMA table_info(user_settings)"))+ columns = {row[1] for row in result.fetchall()}++ if "console_panel_default_open" not in columns:+ await conn.execute(text(+ "ALTER TABLE user_settings ADD COLUMN console_panel_default_open BOOLEAN DEFAULT 0"+ ))+ logger.info("Added console_panel_default_open column to user_settings")+ except Exception as e:+ logger.warning(f"Migration check failed (table may not exist yet): {e}")+async def shutdown(self):"""Close database connections."""if self.engine:@@ -1294,4 +1314,75 @@ class Database:"created_by": skill.created_by,"created_at": skill.created_at.isoformat() if skill.created_at else None,"updated_at": skill.updated_at.isoformat() if skill.updated_at else None- }\ No newline at end of file+ }++ # ============================================================================+ # User Settings (UI defaults and preferences)+ # ============================================================================++ async def get_user_settings(self, user_id: str = "default") -> Optional[Dict[str, Any]]:+ """Get user settings. Returns None if not found."""+ try:+ async with self.get_session() as session:+ stmt = select(UserSettings).where(UserSettings.user_id == user_id)+ result = await session.execute(stmt)+ settings = result.scalar_one_or_none()++ if not settings:+ return None++ return {+ "user_id": settings.user_id,+ "auto_save": settings.auto_save,+ "auto_save_interval": settings.auto_save_interval,+ "sidebar_default_open": settings.sidebar_default_open,+ "component_palette_default_open": settings.component_palette_default_open,+ "console_panel_default_open": settings.console_panel_default_open,+ "created_at": settings.created_at.isoformat() if settings.created_at else None,+ "updated_at": settings.updated_at.isoformat() if settings.updated_at else None+ }++ except Exception as e:+ logger.error("Failed to get user settings", user_id=user_id, error=str(e))+ return None++ async def save_user_settings(self, settings_data: Dict[str, Any], user_id: str = "default") -> bool:+ """Save or update user settings."""+ try:+ async with self.get_session() as session:+ # Try to get existing settings+ stmt = select(UserSettings).where(UserSettings.user_id == user_id)+ result = await session.execute(stmt)+ existing = result.scalar_one_or_none()++ if existing:+ # Update existing settings+ if "auto_save" in settings_data:+ existing.auto_save = settings_data["auto_save"]+ if "auto_save_interval" in settings_data:+ existing.auto_save_interval = settings_data["auto_save_interval"]+ if "sidebar_default_open" in settings_data:+ existing.sidebar_default_open = settings_data["sidebar_default_open"]+ if "component_palette_default_open" in settings_data:+ existing.component_palette_default_open = settings_data["component_palette_default_open"]+ if "console_panel_default_open" in settings_data:+ existing.console_panel_default_open = settings_data["console_panel_default_open"]+ else:+ # Create new settings+ existing = UserSettings(+ user_id=user_id,+ auto_save=settings_data.get("auto_save", True),+ auto_save_interval=settings_data.get("auto_save_interval", 30),+ sidebar_default_open=settings_data.get("sidebar_default_open", True),+ component_palette_default_open=settings_data.get("component_palette_default_open", True),+ console_panel_default_open=settings_data.get("console_panel_default_open", False)+ )+ session.add(existing)++ await session.commit()+ logger.info(f"[DB] User settings saved for user_id: {user_id}")+ return True++ except Exception as e:+ logger.error("Failed to save user settings", user_id=user_id, error=str(e))+ return False\ No newline at end of filediff --git a/server/models/database.py b/server/models/database.pyindex b7fe4cdb..c4c43434 100644--- a/server/models/database.py+++ b/server/models/database.py@@ -230,6 +230,32 @@ class UserSkill(SQLModel, table=True):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 UserSettings(SQLModel, table=True):+ """User settings/preferences - persisted across server restarts.++ Database is the source of truth for all application settings.+ Settings apply on browser refresh/app load.+ """++ __tablename__ = "user_settings"++ id: Optional[int] = Field(default=None, primary_key=True)+ user_id: str = Field(default="default", unique=True, index=True, max_length=255) # For future multi-user+ auto_save: bool = Field(default=True)+ auto_save_interval: int = Field(default=30) # seconds+ sidebar_default_open: bool = Field(default=True)+ component_palette_default_open: bool = Field(default=True)+ console_panel_default_open: bool = Field(default=False)+ 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())diff --git a/server/models/nodes.py b/server/models/nodes.pyindex 1d2fed17..2edbb3cd 100644--- a/server/models/nodes.py+++ b/server/models/nodes.py@@ -86,8 +86,8 @@ class SimpleMemoryParams(BaseNodeParams):# =============================================================================class CreateMapParams(BaseNodeParams):- """Parameters for create map node."""- type: Literal["createMap"]+ """Parameters for GMaps Create node."""+ type: Literal["gmaps_create"]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)@@ -95,16 +95,16 @@ class CreateMapParams(BaseNodeParams):api_key: Optional[str] = Field(default=None, alias="apiKey")-class AddLocationsParams(BaseNodeParams):- """Parameters for add locations (geocoding) node."""- type: Literal["addLocations"]+class GmapsLocationsParams(BaseNodeParams):+ """Parameters for GMaps Locations (geocoding) node."""+ type: Literal["gmaps_locations"]address: str = ""api_key: Optional[str] = Field(default=None, alias="apiKey")-class ShowNearbyPlacesParams(BaseNodeParams):- """Parameters for show nearby places node."""- type: Literal["showNearbyPlaces"]+class GmapsNearbyPlacesParams(BaseNodeParams):+ """Parameters for GMaps Nearby Places node."""+ type: Literal["gmaps_nearby_places"]latitude: float = 0.0longitude: float = 0.0radius: int = Field(default=1000, ge=1, le=50000)@@ -270,7 +270,7 @@ AINodeParams = Annotated[# Maps NodesMapsNodeParams = Annotated[- Union[CreateMapParams, AddLocationsParams, ShowNearbyPlacesParams],+ Union[CreateMapParams, GmapsLocationsParams, GmapsNearbyPlacesParams],Field(discriminator="type")]@@ -316,7 +316,7 @@ KnownNodeParams = Annotated[# AIAIChatModelParams, AIAgentParams, ChatAgentParams, SimpleMemoryParams,# Maps- CreateMapParams, AddLocationsParams, ShowNearbyPlacesParams,+ CreateMapParams, GmapsLocationsParams, GmapsNearbyPlacesParams,WhatsAppSendParams, WhatsAppReceiveParams,# Codediff --git a/server/routers/websocket.py b/server/routers/websocket.pyindex 8fd0ee0e..f6bc3446 100644--- a/server/routers/websocket.py+++ b/server/routers/websocket.py@@ -962,7 +962,7 @@ async def handle_execute_ai_node(data: Dict[str, Any], websocket: WebSocket) ->else:await broadcaster.update_node_status(node_id, "error", {"error": result.get("error")}, workflow_id=workflow_id)- return {"node_id": node_id, "result": result.get("result"), "error": result.get("error"),+ 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()}@@ -1026,6 +1026,61 @@ async def handle_delete_api_key(data: Dict[str, Any], websocket: WebSocket) -> Dreturn {"provider": data["provider"]}+# ============================================================================+# Claude OAuth Handlers+# ============================================================================++@ws_handler()+async def handle_claude_oauth_login(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Initiate Claude OAuth in isolated session."""+ from services.claude_oauth import initiate_claude_oauth+ return await initiate_claude_oauth()+++@ws_handler()+async def handle_claude_oauth_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Check Claude OAuth credentials status."""+ from services.claude_oauth import get_claude_credentials+ return get_claude_credentials()+++@ws_handler("url")+async def handle_test_ai_proxy(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Test connectivity to an AI proxy server."""+ import httpx++ url = data["url"].rstrip("/")+ timeout = data.get("timeout", 5.0)++ try:+ async with httpx.AsyncClient(timeout=timeout) as client:+ # Try common health/models endpoints+ for endpoint in ["/v1/models", "/api/tags", "/health", "/"]:+ try:+ response = await client.get(f"{url}{endpoint}")+ if response.status_code < 500:+ return {+ "success": True,+ "url": url,+ "status_code": response.status_code,+ "endpoint": endpoint,+ }+ except httpx.RequestError:+ continue++ return {+ "success": False,+ "url": url,+ "error": "No responding endpoints found",+ }+ except httpx.ConnectError:+ return {"success": False, "url": url, "error": "Connection refused"}+ except httpx.TimeoutException:+ return {"success": False, "url": url, "error": "Connection timeout"}+ except Exception as e:+ return {"success": False, "url": url, "error": str(e)}++# ============================================================================# Android Handlers# ============================================================================@@ -1853,6 +1908,47 @@ async def handle_reset_skill(data: Dict[str, Any], websocket: WebSocket) -> Dict}+# ============================================================================+# User Settings Handlers+# ============================================================================++@ws_handler()+async def handle_get_user_settings(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get user settings from database."""+ database = container.database()+ user_id = data.get("user_id", "default")+ settings = await database.get_user_settings(user_id)++ # Return default settings if none exist+ if settings is None:+ settings = {+ "user_id": user_id,+ "auto_save": True,+ "auto_save_interval": 30,+ "sidebar_default_open": True,+ "component_palette_default_open": True+ }++ return {"settings": settings}+++@ws_handler()+async def handle_save_user_settings(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Save user settings to database."""+ database = container.database()+ user_id = data.get("user_id", "default")+ settings_data = data.get("settings", {})++ success = await database.save_user_settings(settings_data, user_id)++ if success:+ # Fetch the saved settings to return+ settings = await database.get_user_settings(user_id)+ return {"settings": settings}+ else:+ return {"success": False, "error": "Failed to save settings"}++# ============================================================================# Message Router# ============================================================================@@ -1913,6 +2009,10 @@ MESSAGE_HANDLERS: Dict[str, MessageHandler] = {"save_api_key": handle_save_api_key,"delete_api_key": handle_delete_api_key,+ # Claude OAuth operations+ "claude_oauth_login": handle_claude_oauth_login,+ "claude_oauth_status": handle_claude_oauth_status,+# Android operations"get_android_devices": handle_get_android_devices,"execute_android_action": handle_execute_android_action,@@ -1971,6 +2071,10 @@ MESSAGE_HANDLERS: Dict[str, MessageHandler] = {# Memory and Skill Clear/Reset"clear_memory": handle_clear_memory,"reset_skill": handle_reset_skill,++ # User Settings+ "get_user_settings": handle_get_user_settings,+ "save_user_settings": handle_save_user_settings,}diff --git a/server/services/ai.py b/server/services/ai.pyindex 5ffd141a..a7f9fdfa 100644--- a/server/services/ai.py+++ b/server/services/ai.py@@ -810,7 +810,8 @@ class AIService:def create_model(self, provider: str, api_key: str, model: str,temperature: float, max_tokens: int,- thinking: Optional[ThinkingConfig] = None):+ thinking: Optional[ThinkingConfig] = None,+ proxy_url: Optional[str] = None):"""Create LangChain model instance using provider registry.Args:@@ -820,6 +821,7 @@ class AIService:temperature: Sampling temperaturemax_tokens: Maximum response tokensthinking: Optional thinking/reasoning configuration+ proxy_url: Optional proxy URL (Ollama-style auth delegation)Returns:Configured LangChain chat model instance@@ -836,8 +838,14 @@ class AIService:config.max_tokens_param: max_tokens}+ # Proxy mode: route through local proxy that handles auth (Ollama pattern)+ # Proxy URL stored as {provider}_proxy credential+ if proxy_url:+ kwargs['base_url'] = proxy_url+ kwargs[config.api_key_param] = "ollama" # Ollama-style token+ logger.info(f"[AI] Using proxy for {provider}: {proxy_url}")# OpenRouter uses OpenAI-compatible API with custom base_url- if provider == 'openrouter':+ elif provider == 'openrouter':kwargs['base_url'] = 'https://openrouter.ai/api/v1'kwargs['default_headers'] = {'HTTP-Referer': 'http://localhost:3000',@@ -1112,7 +1120,10 @@ class AIService:format=flattened.get('reasoningFormat', 'parsed'),)- chat_model = self.create_model(provider, api_key, model, temperature, max_tokens, thinking_config)+ # Check for proxy URL (stored as {provider}_proxy credential)+ proxy_url = await self.auth.get_api_key(f"{provider}_proxy")++ chat_model = self.create_model(provider, api_key, model, temperature, max_tokens, thinking_config, proxy_url)# Prepare messagesmessages = []@@ -1193,9 +1204,11 @@ class AIService:async def execute_agent(self, node_id: str, parameters: Dict[str, Any],memory_data: Optional[Dict[str, Any]] = None,+ skill_data: Optional[List[Dict[str, Any]]] = None,tool_data: Optional[List[Dict[str, Any]]] = None,broadcaster = None,- workflow_id: Optional[str] = None) -> Dict[str, Any]:+ workflow_id: Optional[str] = None,+ context: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:"""Execute AI Agent using LangGraph state machine.This method uses LangGraph for structured agent execution with:@@ -1209,16 +1222,21 @@ class AIService:parameters: Node parameters including prompt, model, etc.memory_data: Optional memory data from connected simpleMemory nodecontaining session_id, window_size for conversation history+ skill_data: Optional skill configurations from connected skill nodestool_data: Optional list of tool configurations from connected tool nodesbroadcaster: Optional StatusBroadcaster for real-time UI updatesworkflow_id: Optional workflow ID for scoped status broadcasts+ context: Optional execution context with nodes, edges for nested agent delegation"""start_time = time.time()provider = 'unknown'model = 'unknown'# EARLY LOG: Entry point for debugging- logger.info(f"[AIAgent] execute_agent called: node_id={node_id}, workflow_id={workflow_id}, tool_data_count={len(tool_data) if tool_data else 0}")+ logger.info(f"[AIAgent] execute_agent called: node_id={node_id}, workflow_id={workflow_id}, skill_count={len(skill_data) if skill_data else 0}, tool_count={len(tool_data) if tool_data else 0}")+ if skill_data:+ for i, sd in enumerate(skill_data):+ logger.debug(f"[AIAgent] Skill {i}: type={sd.get('node_type')}, label={sd.get('label')}")if tool_data:for i, td in enumerate(tool_data):logger.info(f"[AIAgent] Tool {i}: type={td.get('node_type')}, node_id={td.get('node_id')}")@@ -1237,6 +1255,30 @@ class AIService:prompt = parameters.get('prompt', 'Hello')system_message = parameters.get('systemMessage', 'You are a helpful assistant')+ # Load skills and enhance system message with SKILL.md context+ # Skills provide instructions/context - actual tools come from tool nodes+ if skill_data:+ from services.skill_loader import get_skill_loader++ skill_loader = get_skill_loader()+ skill_loader.scan_skills()++ # Extract skill names from connected skill nodes+ skill_names = []+ for skill_info in skill_data:+ skill_name = skill_info.get('skill_name') or skill_info.get('node_type', '').replace('Skill', '-skill').lower()+ # Convert node type to skill name (e.g., 'whatsappSkill' -> 'whatsapp-skill')+ if skill_name.endswith('skill') and not '-' in skill_name:+ skill_name = skill_name[:-5] + '-skill' # whatsappskill -> whatsapp-skill+ skill_names.append(skill_name)+ logger.debug(f"[AIAgent] Skill detected: {skill_name}")++ # Add skill SKILL.md content to system message+ skill_prompt = skill_loader.get_registry_prompt(skill_names)+ if skill_prompt:+ system_message = f"{system_message}\n\n{skill_prompt}"+ logger.info(f"[AIAgent] Enhanced system message with {len(skill_names)} skill contexts")+# Flatten options collection from frontendoptions = parameters.get('options', {})flattened = {**parameters, **options}@@ -1281,9 +1323,12 @@ class AIService:"model": model})+ # Check for proxy URL (stored as {provider}_proxy credential)+ proxy_url = await self.auth.get_api_key(f"{provider}_proxy")+# Create LLM using the provider from node configurationlogger.debug(f"[LangGraph] Creating {provider} model: {model}")- chat_model = self.create_model(provider, api_key, model, temperature, max_tokens, thinking_config)+ chat_model = self.create_model(provider, api_key, model, temperature, max_tokens, thinking_config, proxy_url)# Build initial messages for stateinitial_messages: List[BaseMessage] = []@@ -1388,6 +1433,14 @@ class AIService:# Include workflow_id in config so tool handlers can broadcast with proper scopingconfig['workflow_id'] = workflow_id+ # For nested agent delegation: inject services and graph context+ # These allow child agents to execute with their own tools+ config['ai_service'] = self+ config['database'] = self.database+ if context:+ config['nodes'] = context.get('nodes', [])+ config['edges'] = context.get('edges', [])+try:result = await execute_tool(tool_name, tool_args, config)@@ -1573,7 +1626,8 @@ class AIService:skill_data: Optional[List[Dict[str, Any]]] = None,tool_data: Optional[List[Dict[str, Any]]] = None,broadcaster=None,- workflow_id: Optional[str] = None) -> Dict[str, Any]:+ workflow_id: Optional[str] = None,+ context: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:"""Execute Chat Agent - conversational AI with memory, skills, and tool calling.Chat Agent supports:@@ -1589,6 +1643,7 @@ class AIService:tool_data: Optional tool configurations from connected tool nodes (httpRequest, etc.)broadcaster: Optional StatusBroadcaster for real-time UI updatesworkflow_id: Optional workflow ID for scoped status broadcasts+ context: Optional execution context with nodes, edges for nested agent delegation"""start_time = time.time()provider = 'unknown'@@ -1701,8 +1756,11 @@ class AIService:"model": model})+ # Check for proxy URL (stored as {provider}_proxy credential)+ proxy_url = await self.auth.get_api_key(f"{provider}_proxy")+# Create chat model- chat_model = self.create_model(provider, api_key, model, temperature, max_tokens, thinking_config)+ chat_model = self.create_model(provider, api_key, model, temperature, max_tokens, thinking_config, proxy_url)# Build messagesmessages: List[BaseMessage] = []@@ -1798,6 +1856,14 @@ class AIService:# This is needed for Android toolkit to broadcast status to connected service nodesconfig['workflow_id'] = workflow_id+ # For nested agent delegation: inject services and graph context+ # These allow child agents to execute with their own tools+ config['ai_service'] = self+ config['database'] = self.database+ if context:+ config['nodes'] = context.get('nodes', [])+ config['edges'] = context.get('edges', [])+try:# Execute via handlers/tools.py - same pattern as AI Agentresult = await execute_tool(tool_name, tool_args, config)@@ -1993,8 +2059,10 @@ class AIService:'androidTool': 'android_device','whatsappSend': 'whatsapp_send','whatsappDb': 'whatsapp_db',- 'addLocations': 'geocode',- 'showNearbyPlaces': 'nearby_places',+ 'gmaps_locations': 'geocode',+ 'gmaps_nearby_places': 'nearby_places',+ 'aiAgent': 'delegate_to_ai_agent',+ 'chatAgent': 'delegate_to_chat_agent',}DEFAULT_TOOL_DESCRIPTIONS = {'calculatorTool': 'Perform mathematical calculations. Operations: add, subtract, multiply, divide, power, sqrt, mod, abs',@@ -2005,8 +2073,10 @@ class AIService:'androidTool': 'Control Android device. Available services are determined by connected nodes.','whatsappSend': 'Send WhatsApp messages to contacts or groups. Supports text, media, location, and contact messages.','whatsappDb': 'Query WhatsApp database - list contacts, search groups, get contact/group info, retrieve chat history.',- 'addLocations': 'Geocode addresses to coordinates or reverse geocode coordinates to addresses using Google Maps.',- 'showNearbyPlaces': 'Search for nearby places (restaurants, hospitals, banks, etc.) using Google Maps Places API.',+ 'gmaps_locations': 'Geocode addresses to coordinates or reverse geocode coordinates to addresses using Google Maps.',+ 'gmaps_nearby_places': 'Search for nearby places (restaurants, hospitals, banks, etc.) using Google Maps Places API.',+ 'aiAgent': 'Delegate a task to another AI Agent. The agent works independently without blocking.',+ 'chatAgent': 'Delegate a task to a Chat Agent. The agent works independently without blocking.',}try:@@ -2276,6 +2346,64 @@ class AIService:return WhatsAppDbSchema+ # Social Send schema (unified messaging to any platform)+ if node_type == 'socialSend':+ class SocialSendSchema(BaseModel):+ """Send messages to any supported chat platform (WhatsApp, Telegram, Discord, Slack, Signal, SMS, Webchat, Email, Matrix, Teams)."""+ channel: str = Field(+ default="whatsapp",+ description="Target platform: 'whatsapp', 'telegram', 'discord', 'slack', 'signal', 'sms', 'webchat', 'email', 'matrix', 'teams'"+ )+ recipient_type: str = Field(+ default="phone",+ description="Recipient type: 'phone', 'group', 'channel', 'user', 'chat'"+ )+ phone: Optional[str] = Field(+ default=None,+ description="Phone number without + prefix (for recipient_type='phone')"+ )+ group_id: Optional[str] = Field(+ default=None,+ description="Group identifier (for recipient_type='group')"+ )+ channel_id: Optional[str] = Field(+ default=None,+ description="Channel identifier (for recipient_type='channel')"+ )+ user_id: Optional[str] = Field(+ default=None,+ description="User identifier (for recipient_type='user')"+ )+ chat_id: Optional[str] = Field(+ default=None,+ description="Generic chat identifier (for recipient_type='chat')"+ )+ message_type: str = Field(+ default="text",+ description="Message type: 'text', 'image', 'video', 'audio', 'document', 'sticker', 'location', 'contact', 'poll'"+ )+ message: Optional[str] = Field(+ default=None,+ description="Text message content (for message_type='text')"+ )+ media_url: Optional[str] = Field(+ default=None,+ description="URL for media (image/video/audio/document/sticker)"+ )+ caption: Optional[str] = Field(+ default=None,+ description="Caption for media messages"+ )+ latitude: Optional[float] = Field(default=None, description="Latitude for location message")+ longitude: Optional[float] = Field(default=None, description="Longitude for location message")+ location_name: Optional[str] = Field(default=None, description="Display name for location")+ address: Optional[str] = Field(default=None, description="Address text for location")+ contact_name: Optional[str] = Field(default=None, description="Contact card display name")+ contact_phone: Optional[str] = Field(default=None, description="Contact phone number")+ vcard: Optional[str] = Field(default=None, description="vCard 3.0 format string for contact")++ return SocialSendSchema+# Android toolkit schema - dynamic based on connected services# Follows LangChain dynamic tool binding patternif node_type == 'androidTool':@@ -2318,9 +2446,9 @@ class AIService:return AndroidToolSchema- # Google Maps Geocoding schema (addLocations node as tool)+ # Google Maps Geocoding schema (gmaps_locations node as tool)# camelCase to match JSON/frontend convention- if node_type == 'addLocations':+ if node_type == 'gmaps_locations':class GeocodingSchema(BaseModel):"""Geocode addresses to coordinates or reverse geocode coordinates to addresses."""service_type: str = Field(@@ -2342,9 +2470,9 @@ class AIService:return GeocodingSchema- # Google Maps Nearby Places schema (showNearbyPlaces node as tool)+ # Google Maps Nearby Places schema (gmaps_nearby_places node as tool)# snake_case to match Python convention- if node_type == 'showNearbyPlaces':+ if node_type == 'gmaps_nearby_places':class NearbyPlacesSchema(BaseModel):"""Search for nearby places using Google Maps Places API."""lat: float = Field(@@ -2368,6 +2496,26 @@ class AIService:return NearbyPlacesSchema+ # AI Agent delegation schema (fire-and-forget async delegation)+ if node_type in ('aiAgent', 'chatAgent'):+ agent_label = params.get('label', node_type)++ class DelegateToAgentSchema(BaseModel):+ """Delegate a task to another AI Agent (non-blocking).++ The child agent will work independently without blocking the parent.+ Use this to assign subtasks to specialized agents.+ """+ task: str = Field(+ description=f"The task/instruction to delegate to '{agent_label}'. Be specific about what you want done."+ )+ context: Optional[str] = Field(+ default=None,+ description="Additional context or data the child agent needs to complete the task"+ )++ return DelegateToAgentSchema+# Generic schema for other nodesclass GenericToolSchema(BaseModel):"""Generic schema for tool arguments."""diff --git a/server/services/claude_oauth.py b/server/services/claude_oauth.pynew file mode 100644index 00000000..7d4755da--- /dev/null+++ b/server/services/claude_oauth.py@@ -0,0 +1,139 @@+"""Claude OAuth Service - Isolated login that doesn't affect user's main session."""++import asyncio+import json+import os+import shutil+import subprocess+import sys+from pathlib import Path+from typing import Dict, Any++from core.logging import get_logger++logger = get_logger(__name__)++# Isolated directories for MachinaOs+MACHINA_CLAUDE_DIR = Path.home() / ".claude-machina"+MACHINA_NPM_DIR = MACHINA_CLAUDE_DIR / "npm"+++def _get_claude_cmd() -> str:+ """Get path to isolated claude CLI, installing if needed."""+ if sys.platform == "win32":+ claude_path = MACHINA_NPM_DIR / "claude.cmd"+ else:+ claude_path = MACHINA_NPM_DIR / "bin" / "claude"++ if claude_path.exists():+ return str(claude_path)++ # Install claude-code in isolated location+ logger.info("Installing Claude Code CLI in isolated environment...")+ MACHINA_NPM_DIR.mkdir(parents=True, exist_ok=True)++ npm_cmd = shutil.which("npm")+ if not npm_cmd:+ raise FileNotFoundError("npm not found")++ result = subprocess.run(+ [npm_cmd, "install", "@anthropic-ai/claude-code", "--prefix", str(MACHINA_NPM_DIR)],+ capture_output=True,+ text=True,+ )++ if result.returncode != 0:+ logger.error(f"npm install failed: {result.stderr}")+ raise RuntimeError(f"Failed to install claude-code: {result.stderr}")++ # Find the installed binary+ if sys.platform == "win32":+ claude_path = MACHINA_NPM_DIR / "node_modules" / ".bin" / "claude.cmd"+ else:+ claude_path = MACHINA_NPM_DIR / "node_modules" / ".bin" / "claude"++ if not claude_path.exists():+ raise FileNotFoundError(f"Claude CLI not found at {claude_path} after install")++ logger.info(f"Claude Code CLI installed at: {claude_path}")+ return str(claude_path)+++async def initiate_claude_oauth() -> Dict[str, Any]:+ """Run claude login in isolated environment with auto-filled prompts."""+ try:+ MACHINA_CLAUDE_DIR.mkdir(exist_ok=True)++ # Get or install claude CLI+ claude_cmd = _get_claude_cmd()++ env = os.environ.copy()+ env["CLAUDE_CONFIG_DIR"] = str(MACHINA_CLAUDE_DIR)++ # Run claude login with stdin to auto-fill prompts+ # Claude login asks: 1) "Do you agree?" (yes) 2) "Open browser?" (yes)+ if sys.platform == "win32":+ # Windows: pipe inputs and let it open browser+ process = subprocess.Popen(+ [claude_cmd, "login"],+ env=env,+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ creationflags=subprocess.CREATE_NO_WINDOW,+ )+ # Send "yes" responses for the prompts+ try:+ process.stdin.write(b"yes\nyes\n")+ process.stdin.flush()+ except:+ pass+ else:+ # Unix: pipe inputs+ process = subprocess.Popen(+ [claude_cmd, "login"],+ env=env,+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ )+ try:+ process.stdin.write(b"yes\nyes\n")+ process.stdin.flush()+ except:+ pass++ logger.info(f"Claude OAuth login started with PID {process.pid}")++ return {+ "success": True,+ "message": "OAuth login started. Browser should open for authentication.",+ "config_dir": str(MACHINA_CLAUDE_DIR),+ "pid": process.pid,+ }+ except FileNotFoundError as e:+ logger.error(f"CLI not found: {e}")+ return {"success": False, "error": str(e)}+ except Exception as e:+ logger.error(f"Failed to start Claude OAuth: {e}")+ return {"success": False, "error": str(e)}+++def get_claude_credentials() -> Dict[str, Any]:+ """Read credentials from isolated config."""+ try:+ creds_path = MACHINA_CLAUDE_DIR / ".credentials.json"+ if not creds_path.exists():+ return {"success": False, "has_token": False}++ with open(creds_path) as f:+ creds = json.load(f)++ return {+ "success": True,+ "has_token": bool(creds.get("accessToken")),+ "access_token": creds.get("accessToken"),+ "expires_at": creds.get("expiresAt"),+ }+ except Exception as e:+ return {"success": False, "error": str(e)}diff --git a/server/services/handlers/__init__.py b/server/services/handlers/__init__.pyindex 7f6a14fd..c7d8c335 100644--- a/server/services/handlers/__init__.py+++ b/server/services/handlers/__init__.py@@ -10,6 +10,7 @@ This package contains all node execution handlers organized by category:- triggers.py: Generic trigger node handler- utility.py: Maps, Text, Chat, Cron, Start- whatsapp.py: WhatsApp Send, WhatsApp DB+- social.py: Social Receive, Social Send (unified messaging)- polyglot.py: Polyglot server integration (standalone, not auto-imported)"""@@ -64,6 +65,12 @@ from .whatsapp import (handle_whatsapp_db,)+# Social handlers (unified messaging)+from .social import (+ handle_social_receive,+ handle_social_send,+)+# Document processing handlersfrom .document import (handle_http_scraper,@@ -110,6 +117,9 @@ __all__ = ['handle_whatsapp_send','handle_whatsapp_db',+ # Social+ 'handle_social_receive',+ 'handle_social_send',# Document processing'handle_http_scraper','handle_file_downloader',diff --git a/server/services/handlers/ai.py b/server/services/handlers/ai.pyindex 6545884c..9914e43d 100644--- a/server/services/handlers/ai.py+++ b/server/services/handlers/ai.py@@ -1,6 +1,6 @@"""AI node handlers - AI Agent, Zeenie, AI Chat Model, Simple Memory."""-from typing import Dict, Any, List, Optional, TYPE_CHECKING+from typing import Dict, Any, List, Optional, Tuple, TYPE_CHECKINGfrom core.logging import get_loggerfrom constants import ANDROID_SERVICE_NODE_TYPES@@ -11,6 +11,217 @@ if TYPE_CHECKING:logger = get_logger(__name__)+async def _collect_agent_connections(+ node_id: str,+ context: Dict[str, Any],+ database: "Database",+ log_prefix: str = "[Agent]"+) -> Tuple[Optional[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]], Optional[Dict[str, Any]]]:+ """Shared logic for collecting memory, skill, tool, and input data from connected nodes.++ Scans edges targeting the given node and collects:+ - Memory data from input-memory handle (simpleMemory nodes)+ - Skill data from input-skill handle (skill nodes)+ - Tool data from input-tools handle (tool nodes, including androidTool Sub-Node pattern)+ - Input data from input-main or input-chat handle (for auto-prompting fallback)++ Args:+ node_id: The agent node ID to collect connections for+ context: Execution context with nodes, edges, outputs+ database: The database instance for fetching node parameters+ log_prefix: Prefix for log messages (e.g., "[AI Agent]" or "[Chat Agent]")++ Returns:+ Tuple of (memory_data, skill_data, tool_data, input_data)+ """+ nodes = context.get('nodes')+ edges = context.get('edges')+ workflow_id = context.get('workflow_id')++ memory_data: Optional[Dict[str, Any]] = None+ skill_data: List[Dict[str, Any]] = []+ tool_data: List[Dict[str, Any]] = []+ input_data: Optional[Dict[str, Any]] = None++ logger.info(f"{log_prefix} Processing node {node_id}, edges={len(edges) if edges else 0}, nodes={len(nodes) if nodes else 0}, workflow_id={workflow_id}")++ if not edges or not nodes:+ return memory_data, skill_data, tool_data, input_data++ # Log incoming edges for debugging+ incoming_edges = [e for e in edges if e.get('target') == node_id]+ logger.info(f"{log_prefix} Incoming edges to {node_id}: {len(incoming_edges)}")+ for e in incoming_edges:+ logger.debug(f"{log_prefix} Edge: source={e.get('source')}, targetHandle={e.get('targetHandle')}")++ # Check for tool edges specifically+ tool_incoming = [e for e in incoming_edges if e.get('targetHandle') == 'input-tools']+ logger.info(f"{log_prefix} Tool edges (input-tools handle): {len(tool_incoming)}")++ for edge in edges:+ if edge.get('target') != node_id:+ continue++ target_handle = edge.get('targetHandle')+ source_node_id = edge.get('source')+ source_node = next((n for n in nodes if n.get('id') == source_node_id), None)++ if not source_node:+ continue++ # Memory detection - load markdown content for editing+ if target_handle == 'input-memory':+ if source_node.get('type') == 'simpleMemory':+ memory_params = await database.get_node_parameters(source_node_id) or {}+ memory_session_id = memory_params.get('sessionId', 'default')+ window_size = int(memory_params.get('windowSize', 10))+ memory_content = memory_params.get('memoryContent', '# Conversation History\n\n*No messages yet.*\n')+ long_term_enabled = memory_params.get('longTermEnabled', False)+ retrieval_count = int(memory_params.get('retrievalCount', 3))++ memory_data = {+ 'node_id': source_node_id,+ 'session_id': memory_session_id,+ 'window_size': window_size,+ 'memory_content': memory_content,+ 'long_term_enabled': long_term_enabled,+ 'retrieval_count': retrieval_count+ }+ logger.debug(f"{log_prefix} Connected memory node: session={memory_session_id}, content_length={len(memory_content)}")++ # Skill detection - nodes connected to input-skill handle+ elif target_handle == 'input-skill':+ skill_type = source_node.get('type')+ skill_params = await database.get_node_parameters(source_node_id) or {}++ # Special handling for masterSkill - expand skillsConfig into individual skills+ if skill_type == 'masterSkill':+ from services.skill_loader import get_skill_loader++ skills_config = skill_params.get('skillsConfig', {})+ logger.debug(f"{log_prefix} Master Skill found with {len(skills_config)} configured skills")++ # Get skill loader to load instructions from SKILL.md files+ skill_loader = get_skill_loader()++ for skill_key, skill_cfg in skills_config.items():+ # Only include enabled skills+ if not skill_cfg.get('enabled', False):+ continue++ # Load instructions: use customized if available, otherwise load from skill folder+ instructions = ''+ if skill_cfg.get('isCustomized', False) and skill_cfg.get('instructions'):+ # Use customized instructions from config+ instructions = skill_cfg.get('instructions', '')+ logger.debug(f"{log_prefix} Using customized instructions for {skill_key}")+ else:+ # Load from skill folder via skill_loader+ try:+ skill = skill_loader.load_skill(skill_key)+ if skill:+ instructions = skill.instructions+ logger.debug(f"{log_prefix} Loaded instructions from skill folder for {skill_key}")+ except Exception as e:+ logger.warning(f"{log_prefix} Failed to load skill {skill_key}: {e}")+ # Fallback to config instructions if available+ instructions = skill_cfg.get('instructions', '')++ # Create a skill entry for each enabled skill in the config+ skill_entry = {+ 'node_id': f"{source_node_id}_{skill_key}",+ 'node_type': 'masterSkill',+ 'skill_name': skill_key,+ 'parameters': {+ 'instructions': instructions,+ 'skillName': skill_key+ },+ 'label': skill_key+ }+ skill_data.append(skill_entry)+ logger.debug(f"{log_prefix} Master Skill enabled: {skill_key}")+ else:+ # Regular skill node+ skill_entry = {+ 'node_id': source_node_id,+ 'node_type': skill_type,+ 'skill_name': skill_params.get('skillName', skill_type),+ 'parameters': skill_params,+ 'label': source_node.get('data', {}).get('label', skill_type)+ }+ skill_data.append(skill_entry)+ logger.debug(f"{log_prefix} Connected skill: {skill_type}")++ # Tool detection - any node connected to input-tools becomes a tool+ elif target_handle == 'input-tools':+ tool_type = source_node.get('type')+ logger.info(f"{log_prefix} Found tool connected via input-tools: type={tool_type}, node_id={source_node_id}")+ tool_params = await database.get_node_parameters(source_node_id) or {}++ # Build base tool entry+ tool_entry = {+ 'node_id': source_node_id,+ 'node_type': tool_type,+ 'parameters': tool_params,+ 'label': source_node.get('data', {}).get('label', tool_type)+ }++ # Special handling for androidTool - discover connected Android services+ # Follows n8n Sub-Node pattern+ if tool_type == 'androidTool':+ connected_services = []++ # Scan edges for Android nodes connected to this toolkit+ for service_edge in edges:+ # Skip if not targeting this androidTool node+ if service_edge.get('target') != source_node_id:+ continue++ service_target_handle = service_edge.get('targetHandle')+ # Accept input-main or no handle (ReactFlow may omit handle for single-input nodes)+ if service_target_handle is not None and service_target_handle != 'input-main':+ logger.debug(f"{log_prefix} Android Toolkit: Skipping edge with targetHandle: {service_target_handle}")+ continue++ android_node_id = service_edge.get('source')+ android_node = next((n for n in nodes if n.get('id') == android_node_id), None)++ if android_node and android_node.get('type') in ANDROID_SERVICE_NODE_TYPES:+ android_params = await database.get_node_parameters(android_node_id) or {}+ connected_services.append({+ 'node_id': android_node_id,+ 'node_type': android_node.get('type'),+ 'service_id': android_params.get('service_id'),+ 'action': android_params.get('action'),+ 'parameters': android_params,+ 'label': android_node.get('data', {}).get('label', android_node.get('type'))+ })+ logger.debug(f"{log_prefix} Android toolkit connected service: {android_params.get('service_id')}")++ tool_entry['connected_services'] = connected_services+ logger.debug(f"{log_prefix} Android toolkit has {len(connected_services)} connected services")++ tool_data.append(tool_entry)+ logger.debug(f"{log_prefix} Connected tool: {tool_type}")++ # Input data detection - nodes connected to input-main or input-chat handle+ # Used for auto-prompting when prompt parameter is empty+ elif target_handle == 'input-main' or target_handle == 'input-chat' or target_handle is None:+ source_output = context.get('outputs', {}).get(source_node_id)+ if source_output:+ input_data = source_output+ logger.debug(f"{log_prefix} Input from {source_node.get('type')}: {list(source_output.keys()) if isinstance(source_output, dict) else type(source_output)}")++ # Log collection results+ logger.info(f"{log_prefix} Collected: {len(skill_data)} skills, {len(tool_data)} tools, memory={'yes' if memory_data else 'no'}, input={'yes' if input_data else 'no'}")+ for sd in skill_data:+ logger.debug(f"{log_prefix} Skill: type={sd.get('node_type')}, label={sd.get('label')}")+ for td in tool_data:+ logger.info(f"{log_prefix} Tool: type={td.get('node_type')}, node_id={td.get('node_id')}")++ return memory_data, skill_data, tool_data, input_data++async def handle_ai_agent(node_id: str,node_type: str,@@ -19,7 +230,7 @@ async def handle_ai_agent(ai_service: "AIService",database: "Database") -> Dict[str, Any]:- """Handle AI agent node execution with memory and tool support.+ """Handle AI agent node execution with memory, skill, and tool support.Args:node_id: The node ID@@ -32,113 +243,23 @@ async def handle_ai_agent(Returns:Execution result dict"""- nodes = context.get('nodes')- edges = context.get('edges')- execution_id = context.get('execution_id', 'unknown')- workflow_id = context.get('workflow_id') # Extract for status broadcasts- memory_data = None- tool_data: List[Dict[str, Any]] = [] # Collect connected tool nodes-- logger.info(f"[AI Agent] Processing node {node_id}, edges={len(edges) if edges else 0}, nodes={len(nodes) if nodes else 0}, workflow_id={workflow_id}")-- if edges and nodes:- # Log all edges targeting this AI Agent for debugging- incoming_edges = [e for e in edges if e.get('target') == node_id]- logger.info(f"[AI Agent] Incoming edges to {node_id}: {len(incoming_edges)}")- for e in incoming_edges:- logger.info(f"[AI Agent] Edge: source={e.get('source')}, targetHandle={e.get('targetHandle')}")-- # Check for tool edges specifically- tool_incoming = [e for e in incoming_edges if e.get('targetHandle') == 'input-tools']- logger.info(f"[AI Agent] Tool edges (input-tools handle): {len(tool_incoming)}")-- for edge in edges:- if edge.get('target') != node_id:- continue-- target_handle = edge.get('targetHandle')- source_node_id = edge.get('source')- source_node = next((n for n in nodes if n.get('id') == source_node_id), None)-- if not source_node:- continue-- # Memory detection - load markdown content for editing- if target_handle == 'input-memory':- if source_node.get('type') == 'simpleMemory':- memory_params = await database.get_node_parameters(source_node_id) or {}- memory_session_id = memory_params.get('sessionId', 'default')- window_size = int(memory_params.get('windowSize', 10))- memory_content = memory_params.get('memoryContent', '# Conversation History\n\n*No messages yet.*\n')- long_term_enabled = memory_params.get('longTermEnabled', False)- retrieval_count = int(memory_params.get('retrievalCount', 3))-- memory_data = {- 'node_id': source_node_id, # For saving updated content- 'session_id': memory_session_id,- 'window_size': window_size,- 'memory_content': memory_content,- 'long_term_enabled': long_term_enabled,- 'retrieval_count': retrieval_count- }- logger.debug("AI Agent connected memory node", memory_session=memory_session_id, content_length=len(memory_content))-- # Tool detection (new) - any node connected to input-tools becomes a tool- elif target_handle == 'input-tools':- tool_type = source_node.get('type')- logger.info(f"[AI Agent] Found tool connected via input-tools: type={tool_type}, node_id={source_node_id}")- tool_params = await database.get_node_parameters(source_node_id) or {}+ workflow_id = context.get('workflow_id')- # Build base tool entry- tool_entry = {- 'node_id': source_node_id,- 'node_type': tool_type,- 'parameters': tool_params,- 'label': source_node.get('data', {}).get('label', tool_type)- }+ # Collect connected memory, skill, tool, and input nodes using shared base function+ memory_data, skill_data, tool_data, input_data = await _collect_agent_connections(+ node_id, context, database, log_prefix="[AI Agent]"+ )- # Special handling for androidTool - discover connected Android services- # Follows n8n Sub-Node pattern- if tool_type == 'androidTool':- connected_services = []-- # Scan edges for Android nodes connected to this toolkit- for service_edge in edges:- # Skip if not targeting this androidTool node- if service_edge.get('target') != source_node_id:- continue-- target_handle = service_edge.get('targetHandle')- # Accept input-main or no handle (ReactFlow may omit handle for single-input nodes)- if target_handle is not None and target_handle != 'input-main':- logger.debug(f"[Android Toolkit] Skipping edge with targetHandle: {target_handle}")- continue-- android_node_id = service_edge.get('source')- android_node = next((n for n in nodes if n.get('id') == android_node_id), None)-- if android_node and android_node.get('type') in ANDROID_SERVICE_NODE_TYPES:- android_params = await database.get_node_parameters(android_node_id) or {}- connected_services.append({- 'node_id': android_node_id,- 'node_type': android_node.get('type'),- 'service_id': android_params.get('service_id'),- 'action': android_params.get('action'), # Default action- 'parameters': android_params,- 'label': android_node.get('data', {}).get('label', android_node.get('type'))- })- logger.debug(f"Android toolkit connected service: {android_params.get('service_id')}")-- tool_entry['connected_services'] = connected_services- logger.debug(f"Android toolkit has {len(connected_services)} connected services")-- tool_data.append(tool_entry)- logger.debug(f"AI Agent connected tool: {tool_type}")-- # Log tool data collection results- logger.info(f"[AI Agent Handler] Collected tools: count={len(tool_data)}, workflow_id={workflow_id}")- for td in tool_data:- logger.info(f"[AI Agent Handler] Tool: type={td.get('node_type')}, node_id={td.get('node_id')}")+ # Auto-use input data if prompt is empty (fallback for trigger nodes)+ if not parameters.get('prompt') and input_data:+ prompt = (+ input_data.get('message') or+ input_data.get('text') or+ input_data.get('content') or+ str(input_data)+ )+ parameters = {**parameters, 'prompt': prompt}+ logger.info(f"[AI Agent] Auto-using input as prompt: {prompt[:100] if len(str(prompt)) > 100 else prompt}...")# Get broadcaster for real-time status updatesfrom services.status_broadcaster import get_status_broadcaster@@ -148,9 +269,11 @@ async def handle_ai_agent(node_id,parameters,memory_data=memory_data,+ skill_data=skill_data if skill_data else None,tool_data=tool_data if tool_data else None,broadcaster=broadcaster,- workflow_id=workflow_id+ workflow_id=workflow_id,+ context=context # Pass context for nested agent delegation)@@ -168,6 +291,7 @@ async def handle_chat_agent(- Memory (input-memory): SimpleMemory node for conversation history- Skills (input-skill): Provide context/instructions via SKILL.md- Tools (input-tools): Tool nodes (httpRequest, etc.) for LangGraph tool calling+ - Input fallback (input-main or input-chat): Auto-use connected node output as promptArgs:node_id: The node ID@@ -180,124 +304,12 @@ async def handle_chat_agent(Returns:Execution result dict"""- nodes = context.get('nodes')- edges = context.get('edges')workflow_id = context.get('workflow_id')- memory_data = None- skill_data: List[Dict[str, Any]] = []- tool_data: List[Dict[str, Any]] = [] # Tools for LangGraph- input_data: Optional[Dict[str, Any]] = None-- logger.info(f"[Chat Agent] Processing node {node_id}, workflow_id={workflow_id}")-- if edges and nodes:- incoming_edges = [e for e in edges if e.get('target') == node_id]- logger.debug(f"[Chat Agent] Incoming edges: {len(incoming_edges)}")-- for edge in edges:- if edge.get('target') != node_id:- continue-- target_handle = edge.get('targetHandle')- source_node_id = edge.get('source')- source_node = next((n for n in nodes if n.get('id') == source_node_id), None)-- if not source_node:- continue-- # Memory detection - load markdown content (same as AI Agent)- if target_handle == 'input-memory':- if source_node.get('type') == 'simpleMemory':- memory_params = await database.get_node_parameters(source_node_id) or {}- memory_session_id = memory_params.get('sessionId', 'default')- window_size = int(memory_params.get('windowSize', 10))- memory_content = memory_params.get('memoryContent', '# Conversation History\n\n*No messages yet.*\n')- long_term_enabled = memory_params.get('longTermEnabled', False)- retrieval_count = int(memory_params.get('retrievalCount', 3))-- memory_data = {- 'node_id': source_node_id,- 'session_id': memory_session_id,- 'window_size': window_size,- 'memory_content': memory_content,- 'long_term_enabled': long_term_enabled,- 'retrieval_count': retrieval_count- }- logger.info(f"[Chat Agent] Connected memory node: session={memory_session_id}, content_length={len(memory_content)}")- # Skill detection - nodes connected to input-skill handle- elif target_handle == 'input-skill':- skill_type = source_node.get('type')- skill_params = await database.get_node_parameters(source_node_id) or {}- skill_entry = {- 'node_id': source_node_id,- 'node_type': skill_type,- 'skill_name': skill_params.get('skillName', skill_type),- 'parameters': skill_params,- 'label': source_node.get('data', {}).get('label', skill_type)- }- skill_data.append(skill_entry)- logger.debug(f"[Chat Agent] Connected skill: {skill_type}")-- # Tool detection - nodes connected to input-tools handle (for LangGraph)- elif target_handle == 'input-tools':- tool_type = source_node.get('type')- tool_params = await database.get_node_parameters(source_node_id) or {}- tool_entry = {- 'node_id': source_node_id,- 'node_type': tool_type,- 'parameters': tool_params,- 'label': source_node.get('data', {}).get('label', tool_type)- }-- # Special handling for androidTool - discover connected Android services- # Follows n8n Sub-Node pattern (same as AI Agent)- if tool_type == 'androidTool':- connected_services = []-- # Scan edges for Android nodes connected to this toolkit- for service_edge in edges:- # Skip if not targeting this androidTool node- if service_edge.get('target') != source_node_id:- continue-- service_target_handle = service_edge.get('targetHandle')- # Accept input-main or no handle (ReactFlow may omit handle for single-input nodes)- if service_target_handle is not None and service_target_handle != 'input-main':- continue-- android_node_id = service_edge.get('source')- android_node = next((n for n in nodes if n.get('id') == android_node_id), None)-- if android_node and android_node.get('type') in ANDROID_SERVICE_NODE_TYPES:- android_params = await database.get_node_parameters(android_node_id) or {}- connected_services.append({- 'node_id': android_node_id,- 'node_type': android_node.get('type'),- 'service_id': android_params.get('service_id'),- 'action': android_params.get('action'),- 'parameters': android_params,- 'label': android_node.get('data', {}).get('label', android_node.get('type'))- })- logger.debug(f"[Chat Agent] Android toolkit connected service: {android_params.get('service_id')}")-- tool_entry['connected_services'] = connected_services- logger.info(f"[Chat Agent] Android toolkit has {len(connected_services)} connected services")-- tool_data.append(tool_entry)- logger.info(f"[Chat Agent] Connected tool: {tool_type} ({tool_entry['label']})")-- # Input data detection - nodes connected to input-main- elif target_handle == 'input-main' or target_handle is None:- source_output = context.get('outputs', {}).get(source_node_id)- if source_output:- input_data = source_output- logger.debug(f"[Chat Agent] Input from {source_node.get('type')}: {list(source_output.keys())}")-- # Log discovered connections- logger.info(f"[Chat Agent] Discovered: memory={'yes' if memory_data else 'no'}, {len(skill_data)} skills, {len(tool_data)} tools")- for td in tool_data:- logger.debug(f"[Chat Agent] Tool: type={td.get('node_type')}, label={td.get('label')}")+ # Collect connected memory, skill, tool, and input nodes using shared base function+ memory_data, skill_data, tool_data, input_data = await _collect_agent_connections(+ node_id, context, database, log_prefix="[Chat Agent]"+ )# Auto-use input data if prompt is empty (fallback for trigger nodes)if not parameters.get('prompt') and input_data:@@ -322,7 +334,8 @@ async def handle_chat_agent(skill_data=skill_data if skill_data else None,tool_data=tool_data if tool_data else None,broadcaster=broadcaster,- workflow_id=workflow_id+ workflow_id=workflow_id,+ context=context # Pass context for nested agent delegation)diff --git a/server/services/handlers/social.py b/server/services/handlers/social.pynew file mode 100644index 00000000..aed269cc--- /dev/null+++ b/server/services/handlers/social.py@@ -0,0 +1,525 @@+"""Social node handlers - Unified messaging across platforms.++socialReceive: Normalizes messages from platform-specific triggers into unified format+socialSend: Routes outbound messages to appropriate platform (also works as AI tool)++Supported platforms: WhatsApp, Telegram, Discord, Slack, Signal, SMS, Webchat, Email, Matrix, Teams+"""++import time+from datetime import datetime+from typing import Dict, Any, Optional+from core.logging import get_logger++logger = get_logger(__name__)++# Platform-specific field mappings to unified format+PLATFORM_FIELD_MAPPINGS = {+ 'whatsapp': {+ 'sender': 'sender',+ 'sender_phone': 'sender_phone',+ 'sender_name': 'push_name',+ 'chat_id': 'chat_id',+ 'text': 'text',+ 'message_type': 'message_type',+ 'is_group': 'is_group',+ 'is_from_me': 'is_from_me',+ 'timestamp': 'timestamp',+ 'message_id': 'message_id',+ },+ # Add more platform mappings as they are integrated+ 'telegram': {},+ 'discord': {},+ 'slack': {},+ 'signal': {},+ 'sms': {},+ 'webchat': {},+ 'email': {},+ 'matrix': {},+ 'teams': {},+}+++def _normalize_to_unified_format(+ input_data: Dict[str, Any],+ source_channel: str+) -> Dict[str, Any]:+ """Normalize platform-specific message data to unified social format.++ Args:+ input_data: Raw message data from platform trigger+ source_channel: Source platform identifier++ Returns:+ Unified message format matching inbound-message.schema.json+ """+ import uuid++ # Generate message_id if not present (e.g., chatTrigger doesn't have one)+ message_id = input_data.get('message_id') or str(uuid.uuid4())[:8]++ # For webchat, use session_id as sender/chat_id if not provided+ session_id = input_data.get('session_id', 'default')+ default_sender = f"webchat_{session_id}" if source_channel == 'webchat' else ''+ default_chat_id = session_id if source_channel == 'webchat' else ''++ # Start with unified structure+ unified = {+ 'message_id': message_id,+ 'channel': source_channel,+ 'sender': input_data.get('sender') or default_sender,+ 'sender_phone': input_data.get('sender_phone', ''),+ 'sender_name': input_data.get('sender_name') or input_data.get('push_name') or ('User' if source_channel == 'webchat' else ''),+ 'sender_username': input_data.get('sender_username', ''),+ 'chat_id': input_data.get('chat_id') or default_chat_id,+ 'chat_title': input_data.get('chat_title', ''),+ 'chat_type': _determine_chat_type(input_data),+ 'message_type': input_data.get('message_type', 'text'),+ 'text': input_data.get('text') or input_data.get('message', ''),+ 'timestamp': input_data.get('timestamp', datetime.now().isoformat()),+ 'is_group': input_data.get('is_group', False),+ 'is_from_me': input_data.get('is_from_me', False),+ 'is_forwarded': input_data.get('is_forwarded', False),+ 'is_bot': input_data.get('is_bot', False),+ 'is_admin': input_data.get('is_admin', False),+ 'thread_id': input_data.get('thread_id'),+ 'account_id': input_data.get('account_id'),+ 'session_id': input_data.get('session_id'),+ }++ # Copy group_info if present+ if input_data.get('group_info'):+ unified['group_info'] = input_data['group_info']++ # Copy media if present+ if input_data.get('media'):+ unified['media'] = input_data['media']++ # Copy location if present+ if input_data.get('location'):+ unified['location'] = input_data['location']++ # Copy contact if present+ if input_data.get('contact'):+ unified['contact'] = input_data['contact']++ # Copy poll if present+ if input_data.get('poll'):+ unified['poll'] = input_data['poll']++ # Copy reaction if present+ if input_data.get('reaction'):+ unified['reaction'] = input_data['reaction']++ # Copy reply_to if present+ if input_data.get('reply_to'):+ unified['reply_to'] = input_data['reply_to']++ # Copy mentions if present+ if input_data.get('mentions'):+ unified['mentions'] = input_data['mentions']++ # Keep raw data for platform-specific access+ unified['raw'] = input_data.get('raw', input_data)++ return unified+++def _determine_chat_type(data: Dict[str, Any]) -> str:+ """Determine chat type from message data."""+ if data.get('chat_type'):+ return data['chat_type']+ if data.get('is_group'):+ return 'group'+ return 'dm'+++def _apply_filters(+ message: Dict[str, Any],+ parameters: Dict[str, Any]+) -> bool:+ """Check if message passes configured filters.++ Args:+ message: Unified message data+ parameters: Node filter parameters++ Returns:+ True if message passes all filters+ """+ # Channel filter+ channel_filter = parameters.get('channelFilter', 'all')+ if channel_filter != 'all' and message.get('channel') != channel_filter:+ return False++ # Message type filter+ type_filter = parameters.get('messageTypeFilter', 'all')+ if type_filter != 'all' and message.get('message_type') != type_filter:+ return False++ # Sender filter+ sender_filter = parameters.get('senderFilter', 'all')++ if sender_filter == 'any_contact':+ # Non-group messages only+ if message.get('is_group'):+ return False++ elif sender_filter == 'contact':+ # Specific contact+ contact_phone = parameters.get('contactPhone', '')+ if contact_phone and message.get('sender_phone') != contact_phone:+ return False++ elif sender_filter == 'group':+ # Specific group+ group_id = parameters.get('groupId', '')+ if group_id and message.get('chat_id') != group_id:+ return False++ elif sender_filter == 'keywords':+ # Keyword matching+ keywords_str = parameters.get('keywords', '')+ if keywords_str:+ keywords = [k.strip().lower() for k in keywords_str.split(',')]+ text = (message.get('text') or '').lower()+ if not any(kw in text for kw in keywords):+ return False++ # Ignore own messages+ if parameters.get('ignoreOwnMessages', True) and message.get('is_from_me'):+ return False++ # Ignore bots+ if parameters.get('ignoreBots', False) and message.get('is_bot'):+ return False++ return True+++async def handle_social_receive(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any],+ outputs: Dict[str, Any] = None,+ source_nodes: list = None+) -> Dict[str, Any]:+ """Handle Social Receive node - normalizes and filters incoming messages.++ This node connects to platform-specific triggers (WhatsApp Receive, etc.)+ and normalizes their output into unified social format.++ Args:+ node_id: The node ID+ node_type: The node type (socialReceive)+ parameters: Node parameters (filters)+ context: Execution context+ outputs: Connected upstream node outputs (passed from node_executor)+ source_nodes: Source node info with id, type, label++ Returns:+ Normalized message in unified format, or filtered out result+ """+ start_time = time.time()++ # Use outputs passed from node_executor, fall back to context for backwards compatibility+ if outputs is None:+ outputs = context.get('outputs', {})+ if source_nodes is None:+ source_nodes = []++ logger.debug(f"[handle_social_receive] Processing with {len(outputs)} outputs from {len(source_nodes)} source nodes")++ try:+ input_data = None+ source_channel = 'unknown'++ # Find message data from connected outputs+ # Outputs are keyed by node type (e.g., 'whatsappReceive') and contain raw data directly+ for source_node in source_nodes:+ source_type = source_node.get('type', '')+ source_output = outputs.get(source_type)++ if source_output and isinstance(source_output, dict):+ # Check if this output has message data (message_id, text, or message field)+ if source_output.get('message_id') or source_output.get('text') or source_output.get('message'):+ input_data = source_output+ # Detect source channel from node type+ if 'whatsapp' in source_type.lower():+ source_channel = 'whatsapp'+ elif 'telegram' in source_type.lower():+ source_channel = 'telegram'+ elif 'discord' in source_type.lower():+ source_channel = 'discord'+ elif 'slack' in source_type.lower():+ source_channel = 'slack'+ elif 'chat' in source_type.lower():+ source_channel = 'webchat'+ elif source_output.get('channel'):+ source_channel = source_output['channel']+ logger.debug(f"[handle_social_receive] Found message from {source_type}, channel={source_channel}")+ break++ # Fallback: iterate through outputs by key if source_nodes didn't match+ if not input_data:+ for upstream_key, upstream_output in outputs.items():+ if isinstance(upstream_output, dict):+ if upstream_output.get('message_id') or upstream_output.get('text') or upstream_output.get('message'):+ input_data = upstream_output+ # Detect source channel from key or data+ if 'whatsapp' in upstream_key.lower() or upstream_output.get('sender', '').endswith('@s.whatsapp.net'):+ source_channel = 'whatsapp'+ elif 'chat' in upstream_key.lower():+ source_channel = 'webchat'+ elif upstream_output.get('channel'):+ source_channel = upstream_output['channel']+ logger.debug(f"[handle_social_receive] Found message via fallback from key={upstream_key}")+ break++ if not input_data:+ logger.warning(f"[handle_social_receive] No message data found. outputs keys={list(outputs.keys())}, source_nodes={source_nodes}")+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "socialReceive",+ "error": f"No message data received from upstream trigger. Available sources: {list(outputs.keys())}",+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ # Normalize to unified format+ unified_message = _normalize_to_unified_format(input_data, source_channel)++ # Apply filters+ if not _apply_filters(unified_message, parameters):+ return {+ "success": True,+ "node_id": node_id,+ "node_type": "socialReceive",+ "result": None, # Filtered out+ "filtered": True,+ "reason": "Message did not pass filters",+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ # Build result with four outputs:+ # - message: Text content for LLM input+ # - media: Media data and metadata+ # - contact: Sender/contact info+ # - metadata: Message-related metadata+ media_data = unified_message.get('media', {})+ result = {+ # Output 1: Just the text message+ "message": unified_message.get('text', ''),++ # Output 2: Media data and related metadata+ "media": {+ "url": media_data.get('url', '') if media_data else '',+ "type": media_data.get('type', '') if media_data else '',+ "mimetype": media_data.get('mimetype', '') if media_data else '',+ "caption": media_data.get('caption', '') if media_data else '',+ "size": media_data.get('size', 0) if media_data else 0,+ "thumbnail": media_data.get('thumbnail', '') if media_data else '',+ "filename": media_data.get('filename', '') if media_data else '',+ } if media_data else {},++ # Output 3: Contact/sender info+ "contact": {+ "sender": unified_message.get('sender'),+ "sender_phone": unified_message.get('sender_phone'),+ "sender_name": unified_message.get('sender_name'),+ "sender_username": unified_message.get('sender_username'),+ "channel": unified_message.get('channel'),+ "is_group": unified_message.get('is_group'),+ "group_info": unified_message.get('group_info'),+ "chat_title": unified_message.get('chat_title'),+ },++ # Output 4: Message-related metadata+ "metadata": {+ "message_id": unified_message.get('message_id'),+ "chat_id": unified_message.get('chat_id'),+ "timestamp": unified_message.get('timestamp'),+ "message_type": unified_message.get('message_type'),+ "is_from_me": unified_message.get('is_from_me'),+ "is_forwarded": unified_message.get('is_forwarded'),+ "reply_to": unified_message.get('reply_to'),+ "thread_id": unified_message.get('thread_id'),+ },++ # Backwards compatibility: include full data at top level+ **unified_message+ }++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "socialReceive",+ "result": result,+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ except Exception as e:+ logger.error("Social receive failed", node_id=node_id, error=str(e))+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "socialReceive",+ "error": str(e),+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+++async def handle_social_send(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any]+) -> Dict[str, Any]:+ """Handle Social Send node - routes outbound messages to platform.++ This node sends messages to the configured platform (WhatsApp, Telegram, etc.)+ Also works as an AI Agent tool.++ Args:+ node_id: The node ID+ node_type: The node type (socialSend)+ parameters: Message parameters (channel, recipient, content)+ context: Execution context++ Returns:+ Send result with message_id and status+ """+ start_time = time.time()++ try:+ channel = parameters.get('channel', 'whatsapp')+ recipient_type = parameters.get('recipientType', 'phone')+ message_type = parameters.get('messageType', 'text')++ # Get recipient based on type+ recipient = None+ if recipient_type == 'phone':+ recipient = parameters.get('phone')+ elif recipient_type == 'group':+ recipient = parameters.get('groupId')+ elif recipient_type == 'channel':+ recipient = parameters.get('channelId')+ elif recipient_type == 'user':+ recipient = parameters.get('userId')+ elif recipient_type == 'chat':+ recipient = parameters.get('chatId')++ if not recipient:+ raise ValueError(f"Recipient ({recipient_type}) is required")++ # Route to platform-specific handler+ if channel == 'whatsapp':+ result = await _send_via_whatsapp(parameters, recipient, recipient_type, message_type)+ else:+ # Stub for other platforms - will be implemented as they are integrated+ result = {+ "success": False,+ "error": f"Platform '{channel}' is not yet implemented",+ "message_id": None+ }++ if not result.get('success'):+ raise Exception(result.get('error', 'Send failed'))++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "socialSend",+ "result": {+ "success": True,+ "message_id": result.get('message_id'),+ "channel": channel,+ "recipient": recipient,+ "recipient_type": recipient_type,+ "message_type": message_type,+ "timestamp": datetime.now().isoformat()+ },+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++ except Exception as e:+ logger.error("Social send failed", node_id=node_id, error=str(e))+ return {+ "success": False,+ "node_id": node_id,+ "node_type": "socialSend",+ "error": str(e),+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+++async def _send_via_whatsapp(+ parameters: Dict[str, Any],+ recipient: str,+ recipient_type: str,+ message_type: str+) -> Dict[str, Any]:+ """Route message to WhatsApp via existing handler.++ Maps socialSend parameters to whatsappSend parameters.+ """+ from routers.whatsapp import handle_whatsapp_send as whatsapp_send_handler++ # Map socialSend params to whatsappSend format+ whatsapp_params = {+ 'recipient_type': recipient_type,+ 'message_type': message_type,+ }++ # Set recipient+ if recipient_type == 'phone':+ whatsapp_params['phone'] = recipient+ else:+ whatsapp_params['group_id'] = recipient++ # Map message content based on type+ if message_type == 'text':+ whatsapp_params['message'] = parameters.get('message', '')++ elif message_type in ('image', 'video', 'audio', 'document', 'sticker'):+ media_source = parameters.get('mediaSource', 'url')+ whatsapp_params['media_source'] = media_source++ if media_source == 'url':+ whatsapp_params['media_url'] = parameters.get('mediaUrl', '')+ elif media_source == 'base64':+ whatsapp_params['media_data'] = parameters.get('mediaData', '')+ elif media_source == 'file':+ whatsapp_params['file_path'] = parameters.get('filePath', '')++ if parameters.get('mimeType'):+ whatsapp_params['mime_type'] = parameters['mimeType']+ if parameters.get('caption'):+ whatsapp_params['caption'] = parameters['caption']+ if parameters.get('filename'):+ whatsapp_params['filename'] = parameters['filename']++ elif message_type == 'location':+ whatsapp_params['latitude'] = parameters.get('latitude', 0)+ whatsapp_params['longitude'] = parameters.get('longitude', 0)+ whatsapp_params['location_name'] = parameters.get('locationName', '')+ whatsapp_params['address'] = parameters.get('address', '')++ elif message_type == 'contact':+ whatsapp_params['contact_name'] = parameters.get('contactName', '')+ whatsapp_params['vcard'] = parameters.get('vcard', '')++ # Reply options+ if parameters.get('replyToMessage'):+ whatsapp_params['is_reply'] = True+ whatsapp_params['reply_message_id'] = parameters.get('replyMessageId', '')++ # Call WhatsApp handler+ return await whatsapp_send_handler(whatsapp_params)diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.pyindex 1be67069..9d82d620 100644--- a/server/services/handlers/tools.py+++ b/server/services/handlers/tools.py@@ -7,11 +7,22 @@ and returns results.import mathimport json-from typing import Dict, Any, Optional+import asyncio+import uuid+from typing import Dict, Any, Optional, TYPE_CHECKING+from core.logging import get_logger+from constants import ANDROID_SERVICE_NODE_TYPES++if TYPE_CHECKING:+ from services.ai import AIService+ from core.database import Databaselogger = get_logger(__name__)+# Track running delegated tasks for status checking+_delegated_tasks: Dict[str, asyncio.Task] = {}+async def execute_tool(tool_name: str, tool_args: Dict[str, Any],config: Dict[str, Any]) -> Dict[str, Any]:@@ -68,14 +79,22 @@ async def execute_tool(tool_name: str, tool_args: Dict[str, Any],if node_type == 'androidTool':return await _execute_android_toolkit(tool_args, config)- # Google Maps Geocoding (addLocations node as tool)- if node_type == 'addLocations':+ # Direct Android service node (connected directly to AI Agent tools handle)+ if node_type in ANDROID_SERVICE_NODE_TYPES:+ return await _execute_android_service(tool_args, config)++ # Google Maps Geocoding (gmaps_locations node as tool)+ if node_type == 'gmaps_locations':return await _execute_geocoding(tool_args, config.get('parameters', {}))- # Google Maps Nearby Places (showNearbyPlaces node as tool)- if node_type == 'showNearbyPlaces':+ # Google Maps Nearby Places (gmaps_nearby_places node as tool)+ if node_type == 'gmaps_nearby_places':return await _execute_nearby_places(tool_args, config.get('parameters', {}))+ # AI Agent delegation (fire-and-forget async delegation)+ if node_type in ('aiAgent', 'chatAgent'):+ return await _execute_delegated_agent(tool_args, config)+# Generic fallback for unknown node typeslogger.warning(f"[Tool] Unknown tool type: {node_type}, using generic handler")return await _execute_generic(tool_args, config)@@ -835,9 +854,129 @@ async def _execute_android_toolkit(args: Dict[str, Any],return {"error": str(e)}+async def _execute_android_service(args: Dict[str, Any],+ config: Dict[str, Any]) -> Dict[str, Any]:+ """Execute a direct Android service node (not via toolkit).++ This handles Android service nodes (batteryMonitor, wifiAutomation, etc.)+ connected directly to the AI Agent's input-tools handle.++ Args:+ args: LLM-provided arguments {action, parameters}+ config: Tool config with node_type, node_id, parameters++ Returns:+ Service execution result+ """+ from services.android_service import AndroidService+ from services.status_broadcaster import get_status_broadcaster++ node_type = config.get('node_type', '')+ node_id = config.get('node_id', '')+ node_params = config.get('parameters', {})+ workflow_id = config.get('workflow_id')++ # Map node type to service_id (convert camelCase to snake_case)+ # e.g., batteryMonitor -> battery, wifiAutomation -> wifi_automation+ service_id_map = {+ 'batteryMonitor': 'battery',+ 'networkMonitor': 'network',+ 'systemInfo': 'system_info',+ 'location': 'location',+ 'appLauncher': 'app_launcher',+ 'appList': 'app_list',+ 'wifiAutomation': 'wifi_automation',+ 'bluetoothAutomation': 'bluetooth_automation',+ 'audioAutomation': 'audio_automation',+ 'deviceStateAutomation': 'device_state',+ 'screenControlAutomation': 'screen_control',+ 'airplaneModeControl': 'airplane_mode',+ 'motionDetection': 'motion_detection',+ 'environmentalSensors': 'environmental_sensors',+ 'cameraControl': 'camera_control',+ 'mediaControl': 'media_control',+ }+ service_id = service_id_map.get(node_type, node_type)++ # Get action from LLM args or fall back to node params or default+ action = args.get('action') or node_params.get('action', 'status')+ parameters = args.get('parameters') or {}++ # Get connection parameters from node+ host = node_params.get('android_host', 'localhost')+ port = int(node_params.get('android_port', 8888))++ logger.info(f"[Android Service] Executing {service_id}.{action} (node: {node_id}, workflow: {workflow_id})")++ # Broadcast executing status+ broadcaster = get_status_broadcaster()+ if node_id:+ await broadcaster.update_node_status(+ node_id,+ "executing",+ {"message": f"Executing {action} via AI Agent"},+ workflow_id=workflow_id+ )++ try:+ # Use AndroidService which handles relay vs local connection automatically+ android_service = AndroidService()+ result = await android_service.execute_service(+ node_id=node_id,+ service_id=service_id,+ action=action,+ parameters=parameters,+ android_host=host,+ android_port=port+ )++ # Broadcast success/error status+ if node_id:+ if result.get('success'):+ await broadcaster.update_node_status(+ node_id,+ "success",+ {"message": f"{action} completed", "result": result.get('result', {})},+ workflow_id=workflow_id+ )+ else:+ await broadcaster.update_node_status(+ node_id,+ "error",+ {"message": result.get('error', 'Unknown error')},+ workflow_id=workflow_id+ )++ # Extract and return the relevant data+ if result.get('success'):+ return {+ "success": True,+ "service": service_id,+ "action": action,+ "data": result.get('result', {}).get('data', result.get('result', {}))+ }+ else:+ return {+ "error": result.get('error', 'Unknown error'),+ "service": service_id,+ "action": action+ }++ except Exception as e:+ logger.error(f"[Android Service] Unexpected error: {e}")+ if node_id:+ await broadcaster.update_node_status(+ node_id,+ "error",+ {"message": str(e)},+ workflow_id=workflow_id+ )+ return {"error": str(e)}++async def _execute_geocoding(args: Dict[str, Any],node_params: Dict[str, Any]) -> Dict[str, Any]:- """Execute Google Maps geocoding (addLocations node as tool).+ """Execute Google Maps geocoding (gmaps_locations node as tool).Args:args: LLM-provided arguments (snake_case: service_type, address, lat, lng)@@ -873,7 +1012,7 @@ async def _execute_geocoding(args: Dict[str, Any],maps_service = container.maps_service()result = await handle_add_locations(node_id="tool_geocoding",- node_type="addLocations",+ node_type="gmaps_locations",parameters=parameters,context={},maps_service=maps_service@@ -891,7 +1030,7 @@ async def _execute_geocoding(args: Dict[str, Any],async def _execute_nearby_places(args: Dict[str, Any],node_params: Dict[str, Any]) -> Dict[str, Any]:- """Execute Google Maps nearby places search (showNearbyPlaces node as tool).+ """Execute Google Maps nearby places search (gmaps_nearby_places node as tool).Args:args: LLM-provided arguments (snake_case: lat, lng, radius, type, keyword)@@ -921,7 +1060,7 @@ async def _execute_nearby_places(args: Dict[str, Any],maps_service = container.maps_service()result = await handle_nearby_places(node_id="tool_nearby_places",- node_type="showNearbyPlaces",+ node_type="gmaps_nearby_places",parameters=parameters,context={},maps_service=maps_service@@ -957,3 +1096,160 @@ async def _execute_generic(args: Dict[str, Any],"node_id": config.get('node_id'),"message": "Generic tool executed - no specific handler for this node type"}+++async def _execute_delegated_agent(args: Dict[str, Any],+ config: Dict[str, Any]) -> Dict[str, Any]:+ """Delegate a task to a child AI Agent (fire-and-forget pattern).++ This spawns the child agent as an asyncio background task and returns+ immediately, allowing the parent agent to continue working.++ Args:+ args: Dict with 'task' and optional 'context'+ config: Tool config with node_id, node_type, parameters, ai_service, database,+ nodes, edges, workflow_id++ Returns:+ Immediate acknowledgment with task_id (child runs in background)+ """+ from services.status_broadcaster import get_status_broadcaster++ node_id = config.get('node_id')+ node_type = config.get('node_type')+ workflow_id = config.get('workflow_id')+ task_description = args.get('task', '')+ task_context = args.get('context', '')++ # Get injected services+ ai_service = config.get('ai_service')+ database = config.get('database')+ nodes = config.get('nodes', [])+ edges = config.get('edges', [])++ if not ai_service or not database:+ return {+ "error": "Agent delegation requires ai_service and database in config",+ "hint": "Ensure nodes/edges are passed to tool config"+ }++ # Generate unique task ID+ task_id = f"delegated_{node_id}_{uuid.uuid4().hex[:8]}"++ # Get child agent parameters from database+ child_params = await database.get_node_parameters(node_id) or {}++ # Build prompt from task + context+ full_prompt = task_description+ if task_context:+ full_prompt = f"{task_description}\n\nContext:\n{task_context}"+ child_params['prompt'] = full_prompt++ # Create execution context for child agent+ child_context = {+ 'nodes': nodes,+ 'edges': edges,+ 'workflow_id': workflow_id,+ 'outputs': {},+ 'parent_task_id': task_id+ }++ broadcaster = get_status_broadcaster()+ agent_label = child_params.get('label', node_type)++ logger.info(f"[Delegated Agent] Starting task {task_id} for '{agent_label}' (node: {node_id})")++ # Define the background coroutine+ async def run_child_agent():+ try:+ # Broadcast that child agent is starting+ await broadcaster.update_node_status(+ node_id,+ "executing",+ {+ "phase": "delegated_task",+ "task_id": task_id,+ "message": f"Working on: {task_description[:100]}..."+ },+ workflow_id=workflow_id+ )++ # Execute the child agent+ if node_type == 'aiAgent':+ from services.handlers.ai import handle_ai_agent+ result = await handle_ai_agent(+ node_id, node_type, child_params, child_context, ai_service, database+ )+ else:+ from services.handlers.ai import handle_chat_agent+ result = await handle_chat_agent(+ node_id, node_type, child_params, child_context, ai_service, database+ )++ logger.info(f"[Delegated Agent] Task {task_id} completed: success={result.get('success')}")++ # Broadcast completion+ response_preview = str(result.get('result', {}).get('response', ''))[:200]+ await broadcaster.update_node_status(+ node_id,+ "success",+ {+ "phase": "delegated_complete",+ "task_id": task_id,+ "result_summary": response_preview+ },+ workflow_id=workflow_id+ )++ return result++ except Exception as e:+ logger.error(f"[Delegated Agent] Task {task_id} failed: {e}")+ await broadcaster.update_node_status(+ node_id,+ "error",+ {+ "phase": "delegated_error",+ "task_id": task_id,+ "error": str(e)+ },+ workflow_id=workflow_id+ )+ return {"success": False, "error": str(e)}++ finally:+ # Cleanup task reference+ _delegated_tasks.pop(task_id, None)++ # Spawn as background task (fire-and-forget)+ task = asyncio.create_task(run_child_agent())+ _delegated_tasks[task_id] = task++ # Return immediately - Parent agent continues working+ return {+ "success": True,+ "status": "delegated",+ "task_id": task_id,+ "agent_node_id": node_id,+ "agent_name": agent_label,+ "message": f"Task delegated to '{agent_label}'. Agent is now working independently on: {task_description[:100]}..."+ }+++def get_delegated_task_status(task_id: str) -> Dict[str, Any]:+ """Check status of a delegated task (optional utility).++ Args:+ task_id: The task_id returned from delegation++ Returns:+ Status dict with task state+ """+ task = _delegated_tasks.get(task_id)++ if task is None:+ return {"status": "not_found_or_completed", "task_id": task_id}+ elif task.done():+ return {"status": "completed", "task_id": task_id}+ else:+ return {"status": "running", "task_id": task_id}diff --git a/server/services/handlers/utility.py b/server/services/handlers/utility.pyindex cb68d57a..4e8cc091 100644--- a/server/services/handlers/utility.py+++ b/server/services/handlers/utility.py@@ -29,7 +29,7 @@ async def handle_create_map(Args:node_id: The node ID- node_type: The node type (createMap)+ node_type: The node type (gmaps_create)parameters: Resolved parameterscontext: Execution contextmaps_service: The maps service instance@@ -37,9 +37,9 @@ async def handle_create_map(Returns:Execution result dict"""- logger.info("[Maps Execution] Executing createMap", node_id=node_id)+ logger.info("[Maps Execution] Executing gmaps_create", node_id=node_id)result = await maps_service.create_map(node_id, parameters)- logger.info("[Maps Execution] createMap result", success=result.get('success'),+ logger.info("[Maps Execution] gmaps_create 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@@ -56,7 +56,7 @@ async def handle_add_locations(Args:node_id: The node ID- node_type: The node type (addLocations)+ node_type: The node type (gmaps_locations)parameters: Resolved parameterscontext: Execution contextmaps_service: The maps service instance@@ -64,9 +64,9 @@ async def handle_add_locations(Returns:Execution result dict"""- logger.info("[Maps Execution] Executing addLocations", node_id=node_id)+ logger.info("[Maps Execution] Executing gmaps_locations", node_id=node_id)result = await maps_service.geocode_location(node_id, parameters)- logger.info("[Maps Execution] addLocations result", success=result.get('success'),+ logger.info("[Maps Execution] gmaps_locations 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@@ -83,7 +83,7 @@ async def handle_nearby_places(Args:node_id: The node ID- node_type: The node type (showNearbyPlaces)+ node_type: The node type (gmaps_nearby_places)parameters: Resolved parameterscontext: Execution contextmaps_service: The maps service instance@@ -91,9 +91,9 @@ async def handle_nearby_places(Returns:Execution result dict"""- logger.info("[Maps Execution] Executing showNearbyPlaces", node_id=node_id)+ logger.info("[Maps Execution] Executing gmaps_nearby_places", node_id=node_id)result = await maps_service.find_nearby_places(node_id, parameters)- logger.info("[Maps Execution] showNearbyPlaces result", success=result.get('success'),+ logger.info("[Maps Execution] gmaps_nearby_places 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 resultdiff --git a/server/services/maps.py b/server/services/maps.pyindex 47b66e20..6d21304f 100644--- a/server/services/maps.py+++ b/server/services/maps.py@@ -64,7 +64,7 @@ class MapsService:return {"success": True,"node_id": node_id,- "node_type": "createMap",+ "node_type": "gmaps_create","operation": "map_initialization","result": result,"execution_time": time.time() - start_time,@@ -76,7 +76,7 @@ class MapsService:return {"success": False,"node_id": node_id,- "node_type": "createMap",+ "node_type": "gmaps_create","error": str(e),"execution_time": time.time() - start_time,"timestamp": datetime.now().isoformat()@@ -130,7 +130,7 @@ class MapsService:return {"success": True,"node_id": node_id,- "node_type": "addLocations",+ "node_type": "gmaps_locations","operation": service_type,"result": result,"execution_time": time.time() - start_time,@@ -142,7 +142,7 @@ class MapsService:return {"success": False,"node_id": node_id,- "node_type": "addLocations",+ "node_type": "gmaps_locations","error": f"Google Maps API error: {str(e)}","execution_time": time.time() - start_time,"timestamp": datetime.now().isoformat()@@ -153,7 +153,7 @@ class MapsService:return {"success": False,"node_id": node_id,- "node_type": "addLocations",+ "node_type": "gmaps_locations","error": str(e),"execution_time": time.time() - start_time,"timestamp": datetime.now().isoformat()@@ -259,7 +259,7 @@ class MapsService:return {"success": True,"node_id": node_id,- "node_type": "showNearbyPlaces",+ "node_type": "gmaps_nearby_places","operation": "nearby_search","result": result,"execution_time": time.time() - start_time,@@ -271,7 +271,7 @@ class MapsService:return {"success": False,"node_id": node_id,- "node_type": "showNearbyPlaces",+ "node_type": "gmaps_nearby_places","error": f"Google Places API error: {str(e)}","execution_time": time.time() - start_time,"timestamp": datetime.now().isoformat()@@ -282,7 +282,7 @@ class MapsService:return {"success": False,"node_id": node_id,- "node_type": "showNearbyPlaces",+ "node_type": "gmaps_nearby_places","error": str(e),"execution_time": time.time() - start_time,"timestamp": datetime.now().isoformat()diff --git a/server/services/node_executor.py b/server/services/node_executor.pyindex 43f3c905..76938002 100644--- a/server/services/node_executor.py+++ b/server/services/node_executor.py@@ -32,6 +32,7 @@ from services.handlers import (handle_chat_send, handle_chat_history,handle_start, handle_cron_scheduler, handle_timer, handle_console,handle_whatsapp_send, handle_whatsapp_db,+ handle_social_receive, handle_social_send,handle_http_scraper, handle_file_downloader, handle_document_parser,handle_text_chunker, handle_embedding_generator, handle_vector_store,)@@ -107,17 +108,26 @@ class NodeExecutor:# AI'aiAgent': partial(handle_ai_agent, ai_service=self.ai_service, database=self.database),'chatAgent': partial(handle_chat_agent, ai_service=self.ai_service, database=self.database),+ # Specialized Agents (use chatAgent handler - same skill/memory/tools architecture)+ 'android_agent': partial(handle_chat_agent, ai_service=self.ai_service, database=self.database),+ 'coding_agent': partial(handle_chat_agent, ai_service=self.ai_service, database=self.database),+ 'web_agent': partial(handle_chat_agent, ai_service=self.ai_service, database=self.database),+ 'task_agent': partial(handle_chat_agent, ai_service=self.ai_service, database=self.database),+ 'social_agent': partial(handle_chat_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),+ 'gmaps_create': partial(handle_create_map, maps_service=self.maps_service),+ 'gmaps_locations': partial(handle_add_locations, maps_service=self.maps_service),+ 'gmaps_nearby_places': 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,'whatsappDb': handle_whatsapp_db,+ # Social (unified messaging)+ # Note: socialReceive handled in _dispatch with connected_outputs+ 'socialSend': handle_social_send,# Chat'chatSend': handle_chat_send,'chatHistory': handle_chat_history,@@ -196,6 +206,17 @@ class NodeExecutor:output_data = {**output_data, **nested_data}logger.debug(f"[NodeExecutor] Flattened Android output for {node_id}: keys={list(output_data.keys())}")+ # For socialReceive, store 4 outputs for different handle connections+ # - output_message: Text for LLM input+ # - output_media: Media data+ # - output_contact: Sender/contact info+ # - output_metadata: Message metadata+ if node_type == 'socialReceive' and isinstance(output_data, dict):+ await self._output_store(session_id, node_id, "output_message", output_data.get('message', ''))+ await self._output_store(session_id, node_id, "output_media", output_data.get('media', {}))+ await self._output_store(session_id, node_id, "output_contact", output_data.get('contact', {}))+ await self._output_store(session_id, node_id, "output_metadata", output_data.get('metadata', {}))+await self._output_store(session_id, node_id, "output_0", output_data)return result@@ -259,10 +280,14 @@ class NodeExecutor:return await handler(node_id, node_type, params, context)# Special handlers needing connected outputs- if node_type in ('pythonExecutor', 'javascriptExecutor', 'webhookResponse', 'console'):+ if node_type in ('pythonExecutor', 'javascriptExecutor', 'webhookResponse', 'console', 'socialReceive'):+ logger.debug(f"[_dispatch] Getting connected outputs for {node_type} node_id={node_id}")outputs, source_nodes = await self._get_connected_outputs_with_info(context, node_id)+ logger.debug(f"[_dispatch] Got {len(outputs)} outputs for {node_type}: keys={list(outputs.keys())}")if node_type == 'console':return await handle_console(node_id, node_type, params, context, outputs, source_nodes)+ if node_type == 'socialReceive':+ return await handle_social_receive(node_id, node_type, params, context, outputs, source_nodes)handlers = {'pythonExecutor': handle_python_executor,'javascriptExecutor': handle_javascript_executor,@@ -285,7 +310,7 @@ class NodeExecutor:}async def _get_connected_outputs(self, context: Dict, node_id: str) -> Dict[str, Any]:- """Get outputs from connected upstream nodes."""+ """Get outputs from connected upstream nodes with handle-aware routing."""get_output = context.get('get_output_fn')if not get_output:return {}@@ -298,7 +323,21 @@ class NodeExecutor: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")+ source_handle = edge.get('sourceHandle')++ # Map sourceHandle to output key+ if source_handle and source_handle.startswith('output-'):+ handle_name = source_handle.replace('output-', '')+ output_key = f"output_{handle_name}"+ else:+ output_key = "output_0"++ output = await get_output(session_id, source_id, output_key)++ # Fallback to output_0 if specific handle output not found+ if output is None and output_key != "output_0":+ 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@@ -347,14 +386,33 @@ class NodeExecutor:outputs = {}source_nodes = []- logger.debug(f"[_get_connected_outputs_with_info] node_id={node_id}, edges={len(edges)}, session={session_id}")+ logger.info(f"[_get_connected_outputs_with_info] node_id={node_id}, edges={len(edges)}, session={session_id}")for edge in edges:+ logger.debug(f"[_get_connected_outputs_with_info] Checking edge: source={edge.get('source')}, target={edge.get('target')}, sourceHandle={edge.get('sourceHandle')}, targetHandle={edge.get('targetHandle')}")if edge.get('target') == node_id:source_id = edge.get('source')- logger.debug(f"[_get_connected_outputs_with_info] Found edge from {source_id} to {node_id}")- output = await get_output(session_id, source_id, "output_0")- logger.debug(f"[_get_connected_outputs_with_info] Output from {source_id}: {'FOUND' if output else 'NOT FOUND'}")+ source_handle = edge.get('sourceHandle')++ # Map sourceHandle to output key+ # Frontend uses "output-<name>", backend stores as "output_<name>"+ if source_handle and source_handle.startswith('output-'):+ handle_name = source_handle.replace('output-', '')+ output_key = f"output_{handle_name}"+ else:+ output_key = "output_0"++ logger.info(f"[_get_connected_outputs_with_info] Found edge from {source_id} to {node_id}, sourceHandle={source_handle}, using output_key={output_key}")+ output = await get_output(session_id, source_id, output_key)+ logger.info(f"[_get_connected_outputs_with_info] First lookup (key={output_key}): {'FOUND' if output else 'NOT_FOUND'}")++ # Fallback to output_0 if specific handle output not found+ if output is None and output_key != "output_0":+ logger.info(f"[_get_connected_outputs_with_info] output_key {output_key} not found, falling back to output_0")+ output = await get_output(session_id, source_id, "output_0")+ logger.info(f"[_get_connected_outputs_with_info] Fallback lookup (output_0): {'FOUND' if output else 'NOT_FOUND'}")++ logger.info(f"[_get_connected_outputs_with_info] Final output from {source_id}: {'FOUND' if output else 'NOT FOUND'}")if output:source = next((n for n in nodes if n.get('id') == source_id), {})source_type = source.get('type', 'unknown')diff --git a/server/services/workflow.py b/server/services/workflow.pyindex e69245a5..dae89672 100644--- a/server/services/workflow.py+++ b/server/services/workflow.py@@ -462,6 +462,7 @@ class WorkflowService:if key not in self._outputs:self._outputs[key] = {}self._outputs[key][output_name] = data+ logger.debug(f"[store_node_output] Stored in memory: key={key}, output_name={output_name}, _outputs keys={list(self._outputs.keys())}")await self.database.save_node_output(node_id, session_id, output_name, data)async def get_node_output(@@ -472,10 +473,13 @@ class WorkflowService:) -> Optional[Dict[str, Any]]:"""Get stored node output."""key = f"{session_id}_{node_id}"+ logger.debug(f"[get_node_output] Looking for: key={key}, output_name={output_name}, _outputs keys={list(self._outputs.keys())}")output = self._outputs.get(key, {}).get(output_name)+ logger.debug(f"[get_node_output] Memory lookup result: {'FOUND' if output else 'NOT_FOUND'}")if output is None:output = await self.database.get_node_output(node_id, session_id, output_name)+ logger.debug(f"[get_node_output] DB lookup result: {'FOUND' if output else 'NOT_FOUND'}")if output:if key not in self._outputs:self._outputs[key] = {}