Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
Rename whatsappChatHistory to whatsappDb with 6 operations
trohitg1cf900664534
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsxindex 58026c91..6d1787ec 100644--- a/client/src/Dashboard.tsx+++ b/client/src/Dashboard.tsx@@ -80,7 +80,7 @@ const createNodeTypes = (): Record<string, React.ComponentType<any>> => {} else if (type === 'simpleMemory') {// Simple Memory node for AI conversation history - uses circular ModelNode designtypes[type] = ModelNode;- } else if (type === 'whatsappConnect' || type === 'whatsappSend' || type === 'whatsappChatHistory') {+ } else if (type === 'whatsappConnect' || type === 'whatsappSend' || type === 'whatsappDb') {// WhatsApp action nodes use SquareNode (whatsappReceive is a trigger)types[type] = SquareNode;} else if (ANDROID_SERVICE_NODE_TYPES.includes(type) || ANDROID_DEVICE_NODE_TYPES.includes(type)) {diff --git a/client/src/components/SquareNode.tsx b/client/src/components/SquareNode.tsxindex 9d2aaa11..8ec3a54c 100644--- a/client/src/components/SquareNode.tsx+++ b/client/src/components/SquareNode.tsx@@ -27,7 +27,7 @@ const hasToolGroup = (definition: any): boolean => {const GOOGLE_MAPS_NODE_TYPES = ['createMap', 'addLocations', 'showNearbyPlaces'];// WhatsApp node types-const WHATSAPP_NODE_TYPES = ['whatsappConnect', 'whatsappSend', 'whatsappReceive', 'whatsappChatHistory'];+const WHATSAPP_NODE_TYPES = ['whatsappConnect', 'whatsappSend', 'whatsappReceive', 'whatsappDb'];// Nodes that should not have output handles (input-only nodes)const NO_OUTPUT_NODE_TYPES = ['console'];diff --git a/client/src/components/parameterPanel/InputSection.tsx b/client/src/components/parameterPanel/InputSection.tsxindex ce11dfa8..fd364cf6 100644--- a/client/src/components/parameterPanel/InputSection.tsx+++ b/client/src/components/parameterPanel/InputSection.tsx@@ -173,8 +173,10 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =sender_name: 'string'}},- whatsappChatHistory: {- // Sample message array structure for schema view+ whatsappDb: {+ // Output varies by operation - this shows chat_history output+ operation: 'string',+ // chat_history outputmessages: [{text: 'string',@@ -193,6 +195,20 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =has_more: 'boolean',count: 'number',chat_type: 'string',+ // search_groups / list_contacts output+ groups: [{ jid: 'string', name: 'string', participant_count: 'number' }],+ contacts: [{ jid: 'string', phone: 'string', name: 'string', push_name: 'string' }],+ // get_group_info output+ participants: [{ jid: 'string', phone: 'string', name: 'string', is_admin: 'boolean' }],+ // get_contact_info output+ jid: 'string',+ phone: 'string',+ name: 'string',+ push_name: 'string',+ business_name: 'string',+ is_business: 'boolean',+ is_contact: 'boolean',+ profile_pic: 'string',timestamp: 'string'},webhook: {@@ -373,8 +389,8 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =const nodeTypeLower = nodeType.toLowerCase();const isAI = !isMemory && (nodeTypeLower.includes('chatmodel') || nodeTypeLower.includes('aiagent') || nodeTypeLower.includes('chatagent'));const isFile = nodeType.includes('file');- const isWhatsAppChatHistory = nodeType === 'whatsappChatHistory';- const isWhatsApp = !isWhatsAppChatHistory && (nodeType.includes('whatsapp') || nodeType.includes('Whatsapp'));+ const isWhatsAppDb = nodeType === 'whatsappDb';+ const isWhatsApp = !isWhatsAppDb && (nodeType.includes('whatsapp') || nodeType.includes('Whatsapp'));const isWebhook = nodeType === 'webhookTrigger';const isHttpRequest = nodeType === 'httpRequest';const isPython = nodeType.includes('python') || nodeType.includes('Python');@@ -414,7 +430,7 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =isMemory ? sampleSchemas.memory :isAI ? sampleSchemas.ai :isFile ? sampleSchemas.file :- isWhatsAppChatHistory ? sampleSchemas.whatsappChatHistory :+ isWhatsAppDb ? sampleSchemas.whatsappDb :isWhatsApp ? sampleSchemas.whatsapp :isWebhook ? sampleSchemas.webhook :isHttpRequest ? sampleSchemas.httpRequest :diff --git a/client/src/components/ui/ConsolePanel.tsx b/client/src/components/ui/ConsolePanel.tsxindex 56cf693b..26d570f9 100644--- a/client/src/components/ui/ConsolePanel.tsx+++ b/client/src/components/ui/ConsolePanel.tsx@@ -12,6 +12,8 @@ import React, { useState, useCallback, useMemo, useRef, useEffect } from 'react'import { useWebSocket, ConsoleLogEntry } from '../../contexts/WebSocketContext';import { useAppTheme } from '../../hooks/useAppTheme';import { useTheme } from '../../contexts/ThemeContext';+import Prism from 'prismjs';+import 'prismjs/components/prism-json';interface ConsolePanelProps {isOpen: boolean;@@ -39,6 +41,7 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({const [terminalFilter, setTerminalFilter] = useState('');const [terminalLogLevel, setTerminalLogLevel] = useState<'all' | 'error' | 'warning' | 'info' | 'debug'>('all');const [autoScroll, setAutoScroll] = useState(true);+ const [prettyPrint, setPrettyPrint] = useState(true);const [consoleTab, setConsoleTab] = useState<'console' | 'terminal'>('console');const logsEndRef = useRef<HTMLDivElement>(null);const chatEndRef = useRef<HTMLDivElement>(null);@@ -299,6 +302,45 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({}}, [isDarkMode, theme]);+ // Format text for pretty printing - converts escaped newlines and formats JSON+ const formatForDisplay = useCallback((text: string): { formatted: string; isJson: boolean } => {+ if (!prettyPrint) return { formatted: text, isJson: false };++ // Convert escaped newlines to actual newlines+ let formatted = text.replace(/\\n/g, '\n').replace(/\\t/g, '\t');++ // Try to parse and pretty-print JSON+ const trimmed = formatted.trim();+ if ((trimmed.startsWith('{') && trimmed.endsWith('}')) ||+ (trimmed.startsWith('[') && trimmed.endsWith(']'))) {+ try {+ const parsed = JSON.parse(trimmed);+ formatted = JSON.stringify(parsed, null, 2);+ return { formatted, isJson: true };+ } catch {+ // Not valid JSON, return with converted newlines+ }+ }++ return { formatted, isJson: false };+ }, [prettyPrint]);++ // Highlight JSON with Prism+ const highlightJson = useCallback((code: string): string => {+ return Prism.highlight(code, Prism.languages.json, 'json');+ }, []);++ // Prism token styles following CodeEditor.tsx convention+ const prismStyles = `+ .console-json-output .token.string { color: ${theme.dracula.yellow}; }+ .console-json-output .token.number { color: ${theme.dracula.purple}; }+ .console-json-output .token.boolean { color: ${theme.dracula.purple}; }+ .console-json-output .token.null { color: ${theme.dracula.purple}; }+ .console-json-output .token.property { color: ${theme.dracula.cyan}; }+ .console-json-output .token.punctuation { color: ${theme.colors.text}; }+ .console-json-output .token.operator { color: ${theme.dracula.pink}; }+ `;+// Resize handle styleconst resizeHandleStyle: React.CSSProperties = {position: 'absolute',@@ -554,6 +596,9 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({return (<div style={{ position: 'relative' }}>+ {/* Prism syntax highlighting styles for JSON */}+ <style>{prismStyles}</style>+{/* Resize Handle - Only visible when open */}{isOpen && (<div@@ -790,6 +835,32 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({/>Auto</label>+ {consoleTab === 'console' && (+ <label+ style={{+ ...buttonStyle,+ display: 'flex',+ alignItems: 'center',+ gap: '3px',+ cursor: 'pointer',+ fontSize: '10px',+ backgroundColor: prettyPrint+ ? (isDarkMode ? `${theme.dracula.cyan}30` : `${theme.colors.info}20`)+ : 'transparent',+ padding: '2px 6px',+ borderRadius: '4px'+ }}+ title="Format JSON and convert escaped newlines"+ >+ <input+ type="checkbox"+ checked={prettyPrint}+ onChange={e => setPrettyPrint(e.target.checked)}+ style={{ cursor: 'pointer', width: '12px', height: '12px' }}+ />+ Pretty+ </label>+ )}{((consoleTab === 'console' && consoleLogs.length > 0) || (consoleTab === 'terminal' && terminalLogs.length > 0)) && (<buttonstyle={clearButtonStyle}@@ -827,18 +898,35 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({{log.source_node_label}</span>)}- <pre- style={{- margin: 0,- flex: 1,- overflow: 'auto',- color: getFormatColor(log.format),- whiteSpace: log.format === 'json' ? 'pre-wrap' : 'pre',- wordBreak: 'break-word'- }}- >- {log.formatted}- </pre>+ {(() => {+ const { formatted, isJson } = formatForDisplay(log.formatted);+ return isJson && prettyPrint ? (+ <pre+ className="console-json-output"+ style={{+ margin: 0,+ flex: 1,+ overflow: 'auto',+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word'+ }}+ dangerouslySetInnerHTML={{ __html: highlightJson(formatted) }}+ />+ ) : (+ <pre+ style={{+ margin: 0,+ flex: 1,+ overflow: 'auto',+ color: getFormatColor(log.format),+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word'+ }}+ >+ {formatted}+ </pre>+ );+ })()}</div>)))diff --git a/client/src/nodeDefinitions/whatsappNodes.ts b/client/src/nodeDefinitions/whatsappNodes.tsindex c39a6f12..b65df24d 100644--- a/client/src/nodeDefinitions/whatsappNodes.ts+++ b/client/src/nodeDefinitions/whatsappNodes.ts@@ -67,8 +67,8 @@ const WHATSAPP_CONNECT_ICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.or// WhatsApp Receive - Notification bell with dot (trigger node)const WHATSAPP_RECEIVE_ICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%2325D366'%3E%3Cpath d='M12 22c1.1 0 2-.9 2-2h-4c0 1.1.9 2 2 2zm6-6v-5c0-3.07-1.63-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.64 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2zm-2 1H8v-6c0-2.48 1.51-4.5 4-4.5s4 2.02 4 4.5v6z'/%3E%3Ccircle cx='18' cy='6' r='4'/%3E%3C/svg%3E";-// WhatsApp Chat History - Clock icon (retrieve history)-const WHATSAPP_HISTORY_ICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%2325D366'%3E%3Cpath d='M13 3a9 9 0 0 0-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42A8.954 8.954 0 0 0 13 21a9 9 0 0 0 0-18zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z'/%3E%3C/svg%3E";+// WhatsApp DB - Database icon (query contacts, groups, messages)+const WHATSAPP_DB_ICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%2325D366'%3E%3Cpath d='M12 3C7.58 3 4 4.79 4 7v10c0 2.21 3.58 4 8 4s8-1.79 8-4V7c0-2.21-3.58-4-8-4zm0 2c3.87 0 6 1.5 6 2s-2.13 2-6 2-6-1.5-6-2 2.13-2 6-2zm6 12c0 .5-2.13 2-6 2s-6-1.5-6-2v-2.23c1.61.78 3.72 1.23 6 1.23s4.39-.45 6-1.23V17zm0-4c0 .5-2.13 2-6 2s-6-1.5-6-2v-2.23c1.61.78 3.72 1.23 6 1.23s4.39-.45 6-1.23V13zm0-4c0 .5-2.13 2-6 2s-6-1.5-6-2V6.77C7.61 7.55 9.72 8 12 8s4.39-.45 6-1.23V9z'/%3E%3C/svg%3E";// ============================================================================// WHATSAPP NODES@@ -625,17 +625,17 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {}},- // WhatsApp Chat History Node - Retrieve stored messages+ // WhatsApp DB Node - Query contacts, groups, messages// Can be used as workflow node OR as AI Agent tool (group includes 'tool')- whatsappChatHistory: {- displayName: 'WhatsApp Chat History',- name: 'whatsappChatHistory',- icon: WHATSAPP_HISTORY_ICON,+ whatsappDb: {+ displayName: 'WhatsApp DB',+ name: 'whatsappDb',+ icon: WHATSAPP_DB_ICON,group: ['whatsapp', 'tool'],version: 1,- subtitle: 'Get Messages',- description: 'Retrieve chat history from WhatsApp conversations. Messages are synced on first login and stored for later retrieval.',- defaults: { name: 'Chat History', color: '#25D366' },+ subtitle: 'Query WhatsApp',+ description: 'Query WhatsApp database - contacts, groups, messages, contact info',+ defaults: { name: 'WhatsApp DB', color: '#25D366' },inputs: [{name: 'main',displayName: 'Input',@@ -645,9 +645,9 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {outputs: [{name: 'main',- displayName: 'Messages',+ displayName: 'Output',type: 'main' as NodeConnectionType,- description: 'Chat history messages (messages, total, has_more)'+ description: 'Query result'},{name: 'tool',@@ -657,7 +657,24 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {}],properties: [- // ===== CHAT TYPE =====+ // ===== OPERATION SELECTOR =====+ {+ displayName: 'Operation',+ name: 'operation',+ type: 'options',+ options: [+ { name: 'Chat History', value: 'chat_history' },+ { name: 'Search Groups', value: 'search_groups' },+ { name: 'Get Group Info', value: 'get_group_info' },+ { name: 'Get Contact Info', value: 'get_contact_info' },+ { name: 'List Contacts', value: 'list_contacts' },+ { name: 'Check Contacts', value: 'check_contacts' }+ ],+ default: 'chat_history',+ description: 'Operation to perform'+ },++ // ===== CHAT HISTORY PARAMETERS ====={displayName: 'Chat Type',name: 'chatType',@@ -667,10 +684,11 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {{ name: 'Group Chat', value: 'group' }],default: 'individual',- description: 'Type of chat to retrieve history from'+ description: 'Type of chat to retrieve history from',+ displayOptions: {+ show: { operation: ['chat_history'] }+ }},-- // ===== INDIVIDUAL CHAT ====={displayName: 'Phone Number',name: 'phone',@@ -680,11 +698,9 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {placeholder: '1234567890',description: 'Phone number of the contact (without + prefix)',displayOptions: {- show: { chatType: ['individual'] }+ show: { operation: ['chat_history'], chatType: ['individual'] }}},-- // ===== GROUP CHAT ====={displayName: 'Group',name: 'group_id',@@ -692,9 +708,9 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {default: '',required: true,placeholder: '[email protected]',- description: 'Group JID to retrieve messages from',+ description: 'Group JID',displayOptions: {- show: { chatType: ['group'] }+ show: { operation: ['chat_history', 'get_group_info'], chatType: ['group'] }}},{@@ -708,22 +724,20 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {default: 'all',description: 'Filter messages in group',displayOptions: {- show: { chatType: ['group'] }+ show: { operation: ['chat_history'], chatType: ['group'] }}},{- displayName: 'Contact Phone',+ displayName: 'Sender Phone',name: 'senderPhone',type: 'string',default: '',placeholder: '1234567890',description: 'Filter messages from specific group member',displayOptions: {- show: { chatType: ['group'], groupFilter: ['contact'] }+ show: { operation: ['chat_history'], chatType: ['group'], groupFilter: ['contact'] }}},-- // ===== MESSAGE TYPE FILTER ====={displayName: 'Message Type',name: 'messageFilter',@@ -733,34 +747,11 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {{ name: 'Text Only', value: 'text_only' }],default: 'all',- description: 'Filter by message type'- },-- // ===== RESULT MODE =====- {- displayName: 'Result Mode',- name: 'resultMode',- type: 'options',- options: [- { name: 'Multiple Messages', value: 'multiple' },- { name: 'Single Message by Position', value: 'single' }- ],- default: 'multiple',- description: 'Return multiple messages or a single message at specific position'- },- {- displayName: 'Message Position',- name: 'position',- type: 'string',- default: '1',- placeholder: '1 or {{node.index}}',- description: 'Position: positive from newest (1=most recent), negative from oldest (-1=oldest). Supports template variables.',+ description: 'Filter by message type',displayOptions: {- show: { resultMode: ['single'] }+ show: { operation: ['chat_history'] }}},-- // ===== PAGINATION ====={displayName: 'Limit',name: 'limit',@@ -769,7 +760,7 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {typeOptions: { minValue: 1, maxValue: 500 },description: 'Maximum number of messages to retrieve (1-500)',displayOptions: {- show: { resultMode: ['multiple'] }+ show: { operation: ['chat_history'] }}},{@@ -780,7 +771,62 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {typeOptions: { minValue: 0 },description: 'Number of messages to skip (for pagination)',displayOptions: {- show: { resultMode: ['multiple'] }+ show: { operation: ['chat_history'] }+ }+ },++ // ===== SEARCH GROUPS PARAMETERS =====+ {+ displayName: 'Search Query',+ name: 'query',+ type: 'string',+ default: '',+ placeholder: 'Family, Work, etc.',+ description: 'Search groups by name (leave empty for all groups)',+ displayOptions: {+ show: { operation: ['search_groups', 'list_contacts'] }+ }+ },++ // ===== GET GROUP INFO PARAMETERS =====+ {+ displayName: 'Group',+ name: 'groupIdForInfo',+ type: 'string',+ default: '',+ required: true,+ placeholder: '[email protected]',+ description: 'Group JID to get info for',+ displayOptions: {+ show: { operation: ['get_group_info'] }+ }+ },++ // ===== GET CONTACT INFO PARAMETERS =====+ {+ displayName: 'Phone Number',+ name: 'contactPhone',+ type: 'string',+ default: '',+ required: true,+ placeholder: '1234567890',+ description: 'Phone number to get contact info for',+ displayOptions: {+ show: { operation: ['get_contact_info'] }+ }+ },++ // ===== CHECK CONTACTS PARAMETERS =====+ {+ displayName: 'Phone Numbers',+ name: 'phones',+ type: 'string',+ default: '',+ required: true,+ placeholder: '1234567890, 0987654321',+ description: 'Comma-separated phone numbers to check WhatsApp registration',+ displayOptions: {+ show: { operation: ['check_contacts'] }}}],@@ -791,10 +837,9 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {const response = await wsRequest('whatsapp_groups') as { success: boolean; groups?: Array<{ jid: string; name: string; participant_count?: number; is_community?: boolean }> };if (response.success && response.groups) {- // Filter out communities - they don't have regular chat historyconst regularGroups = response.groups.filter((group) => !group.is_community);if (regularGroups.length === 0) {- return [{ name: 'No groups found', value: '', description: 'Only communities found (no chat history)' }];+ return [{ name: 'No groups found', value: '', description: 'Only communities found' }];}return regularGroups.map((group) => ({name: group.name || group.jid,@@ -817,4 +862,4 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {// EXPORTS// ============================================================================-export const WHATSAPP_NODE_TYPES = ['whatsappSend', 'whatsappConnect', 'whatsappReceive', 'whatsappChatHistory'];+export const WHATSAPP_NODE_TYPES = ['whatsappSend', 'whatsappConnect', 'whatsappReceive', 'whatsappDb'];diff --git a/client/src/services/executionService.ts b/client/src/services/executionService.tsindex 040c4f98..d0222ea9 100644--- a/client/src/services/executionService.ts+++ b/client/src/services/executionService.ts@@ -209,7 +209,7 @@ export class ExecutionService {'whatsappSend','whatsappConnect','whatsappReceive',- 'whatsappChatHistory',+ 'whatsappDb',// Text Processing Nodes'textGenerator','fileHandler',diff --git a/server/main.py b/server/main.pyindex 4d0cc764..5815e26c 100644--- a/server/main.py+++ b/server/main.py@@ -11,44 +11,14 @@ try:except ImportError:pass # Windows - uvloop not available, use default asyncio-import signal-import sysimport osfrom datetime import datetimefrom contextlib import asynccontextmanager-# Flag to track if shutdown was requested-_shutdown_requested = False---def handle_signal(signum, frame):- """Handle SIGTERM/SIGINT for clean shutdown.-- Note: We don't call sys.exit() here because it raises SystemExit- in the middle of async operations, causing cascading errors.- Instead, we set a flag and let uvicorn handle the graceful shutdown.- """- global _shutdown_requested- if not _shutdown_requested:- _shutdown_requested = True- print(f"\nReceived signal {signum}, shutting down gracefully...")- # Raise KeyboardInterrupt to trigger uvicorn's graceful shutdown- # This is the proper way to signal shutdown in async context- raise KeyboardInterrupt()---# Register signal handlers for clean shutdown-# Note: uvicorn already handles SIGINT/SIGTERM, but we add our own-# to provide a cleaner message and avoid the "Terminate batch job" prompt on Windows-if sys.platform != 'win32':- # Unix: handle both SIGTERM (docker stop) and SIGINT (Ctrl+C)- signal.signal(signal.SIGTERM, handle_signal)- # Don't override SIGINT on Unix - let uvicorn handle it-else:- # Windows: Don't override signal handlers - let uvicorn handle Ctrl+C- # The "Terminate batch job" prompt is a Windows cmd.exe behavior- # that we can't avoid from Python- pass+# Note: We don't register custom signal handlers.+# uvicorn already handles SIGINT (Ctrl+C) and SIGTERM (docker stop) gracefully.+# Adding custom handlers that raise KeyboardInterrupt causes cascading errors+# during async operations (WebSocket handlers, logging, etc.).from fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarediff --git a/server/routers/websocket.py b/server/routers/websocket.pyindex defa99f9..f8afe601 100644--- a/server/routers/websocket.py+++ b/server/routers/websocket.py@@ -1881,10 +1881,16 @@ async def websocket_status_endpoint(websocket: WebSocket):data = await websocket.receive_json()await message_queue.put(data)except WebSocketDisconnect:- logger.info("[WebSocket] Client disconnected normally")+ # Don't log here - logging during shutdown can raise KeyboardInterruptawait message_queue.put(None) # Signal shutdown+ except asyncio.CancelledError:+ # Task cancelled during shutdown - this is expected+ await message_queue.put(None)+ raiseexcept Exception as e:- logger.error(f"[WebSocket] Receive error: {e}")+ # Only log if it's not a shutdown-related error+ if not isinstance(e, (KeyboardInterrupt, SystemExit)):+ logger.error(f"[WebSocket] Receive error: {e}")await message_queue.put(None)async def process_loop():@@ -1927,10 +1933,14 @@ async def websocket_status_endpoint(websocket: WebSocket):tg.create_task(process_loop())except* WebSocketDisconnect:- logger.info("[WebSocket] Client disconnected (TaskGroup)")+ pass # Normal disconnect - don't log during shutdown+ except* asyncio.CancelledError:+ pass # Task cancelled during shutdown - expected+ except* (KeyboardInterrupt, SystemExit):+ pass # Server shutdown - don't logexcept* Exception as eg:for exc in eg.exceptions:- if not isinstance(exc, WebSocketDisconnect):+ if not isinstance(exc, (WebSocketDisconnect, asyncio.CancelledError, KeyboardInterrupt, SystemExit)):logger.error(f"[WebSocket] TaskGroup error: {exc}")finally:# Cancel any running handler tasks on disconnect@@ -1974,10 +1984,13 @@ async def websocket_internal_endpoint(websocket: WebSocket):data = await websocket.receive_json()await message_queue.put(data)except WebSocketDisconnect:- logger.info("[WebSocket Internal] Client disconnected")await message_queue.put(None)+ except asyncio.CancelledError:+ await message_queue.put(None)+ raiseexcept Exception as e:- logger.error(f"[WebSocket Internal] Receive error: {e}")+ if not isinstance(e, (KeyboardInterrupt, SystemExit)):+ logger.error(f"[WebSocket Internal] Receive error: {e}")await message_queue.put(None)async def process_loop():@@ -2015,10 +2028,14 @@ async def websocket_internal_endpoint(websocket: WebSocket):tg.create_task(process_loop())except* WebSocketDisconnect:- logger.info("[WebSocket Internal] Client disconnected (TaskGroup)")+ pass # Normal disconnect+ except* asyncio.CancelledError:+ pass # Task cancelled during shutdown+ except* (KeyboardInterrupt, SystemExit):+ pass # Server shutdownexcept* Exception as eg:for exc in eg.exceptions:- if not isinstance(exc, WebSocketDisconnect):+ if not isinstance(exc, (WebSocketDisconnect, asyncio.CancelledError, KeyboardInterrupt, SystemExit)):logger.error(f"[WebSocket Internal] TaskGroup error: {exc}")finally:for task in list(handler_tasks):@@ -2028,8 +2045,6 @@ async def websocket_internal_endpoint(websocket: WebSocket):if handler_tasks:await asyncio.gather(*handler_tasks, return_exceptions=True)- logger.info("[WebSocket Internal] Connection closed")-@router.get("/ws/info")async def websocket_info():diff --git a/server/routers/whatsapp.py b/server/routers/whatsapp.pyindex 7ca2fdee..a1567288 100644--- a/server/routers/whatsapp.py+++ b/server/routers/whatsapp.py@@ -733,3 +733,29 @@ async def handle_whatsapp_chat_history(params: dict) -> dict:except Exception as e:logger.error(f"WhatsApp chat_history fetch failed: {e}")return {"success": False, "error": str(e), "messages": [], "total": 0, "has_more": False}+++async def whatsapp_rpc_call(method: str, params: dict = None) -> dict:+ """Generic RPC call to WhatsApp Go service.++ Used by handlers/whatsapp.py for operations like:+ - groups: List all groups+ - group_info: Get group details with participants+ - contacts: List contacts with saved names+ - contact_info: Get full contact info (for send/reply)+ - contact_check: Check WhatsApp registration status++ Args:+ method: RPC method name (e.g., 'groups', 'contact_info')+ params: Method parameters dict++ Returns:+ RPC result dict or error dict+ """+ try:+ client = await get_client()+ result = await client.call(method, params or {})+ return result if isinstance(result, dict) else {"result": result, "success": True}+ except Exception as e:+ logger.error(f"WhatsApp RPC call '{method}' failed: {e}")+ return {"success": False, "error": str(e)}diff --git a/server/services/ai.py b/server/services/ai.pyindex dfd31f08..5d1b8cd5 100644--- a/server/services/ai.py+++ b/server/services/ai.py@@ -1832,12 +1832,16 @@ class AIService:'currentTimeTool': 'get_current_time','webSearchTool': 'web_search','androidTool': 'android_device',+ 'whatsappSend': 'whatsapp_send',+ 'whatsappDb': 'whatsapp_db',}DEFAULT_TOOL_DESCRIPTIONS = {'calculatorTool': 'Perform mathematical calculations. Operations: add, subtract, multiply, divide, power, sqrt, mod, abs','currentTimeTool': 'Get the current date and time. Optionally specify timezone.','webSearchTool': 'Search the web for information. Returns relevant search results.','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.',}try:@@ -2024,30 +2028,62 @@ class AIService:return WhatsAppSendSchema- # WhatsApp chat history schema (existing node used as tool)- if node_type == 'whatsappChatHistory':- class WhatsAppChatHistorySchema(BaseModel):- """Retrieve WhatsApp chat history."""- chat_type: str = Field(- default="individual",- description="Chat type: 'individual' or 'group'"+ # WhatsApp DB schema (existing node used as tool) - query contacts, groups, messages+ if node_type == 'whatsappDb':+ class WhatsAppDbSchema(BaseModel):+ """Query WhatsApp database - contacts, groups, messages.++ Operations:+ - chat_history: Get messages from a chat (requires phone or group_id)+ - search_groups: Search groups by name (optional query)+ - get_group_info: Get group details with participant names (requires group_id)+ - get_contact_info: Get full contact info for sending/replying (requires phone)+ - list_contacts: List contacts with saved names (optional query filter)+ - check_contacts: Check WhatsApp registration (requires phones comma-separated)+ """+ operation: str = Field(+ default="chat_history",+ description="Operation: 'chat_history', 'search_groups', 'get_group_info', 'get_contact_info', 'list_contacts', 'check_contacts'"+ )+ # For chat_history+ chat_type: Optional[str] = Field(+ default=None,+ description="For chat_history: 'individual' or 'group'")phone: Optional[str] = Field(default=None,- description="Phone number without + prefix. Required for chat_type='individual'"+ description="Phone number without + prefix. For chat_history (individual), get_contact_info")group_id: Optional[str] = Field(default=None,- description="Group JID. Required for chat_type='group'"+ description="Group JID. For chat_history (group), get_group_info"+ )+ message_filter: Optional[str] = Field(+ default=None,+ description="For chat_history: 'all' or 'text_only'"+ )+ group_filter: Optional[str] = Field(+ default=None,+ description="For chat_history (group): 'all' or 'contact' to filter by sender"+ )+ sender_phone: Optional[str] = Field(+ default=None,+ description="For chat_history (group with group_filter='contact'): filter messages from this phone")- message_filter: str = Field(- default="all",- description="Filter: 'all' or 'text_only'"+ limit: Optional[int] = Field(default=None, description="For chat_history: max messages (1-500)")+ offset: Optional[int] = Field(default=None, description="For chat_history: pagination offset")+ # For search_groups, list_contacts+ query: Optional[str] = Field(+ default=None,+ description="Search query for search_groups or list_contacts"+ )+ # For check_contacts+ phones: Optional[str] = Field(+ default=None,+ description="For check_contacts: comma-separated phone numbers")- limit: int = Field(default=50, description="Max messages to retrieve (1-500)")- offset: int = Field(default=0, description="Messages to skip for pagination")- return WhatsAppChatHistorySchema+ return WhatsAppDbSchema# Android toolkit schema - dynamic based on connected services# Follows LangChain dynamic tool binding patterndiff --git a/server/services/handlers/__init__.py b/server/services/handlers/__init__.pyindex b5b986fa..dbcf12ec 100644--- a/server/services/handlers/__init__.py+++ b/server/services/handlers/__init__.py@@ -63,7 +63,7 @@ from .utility import (from .whatsapp import (handle_whatsapp_send,handle_whatsapp_connect,- handle_whatsapp_chat_history,+ handle_whatsapp_db,)# Document processing handlers@@ -113,7 +113,7 @@ __all__ = ['handle_whatsapp_send','handle_whatsapp_connect',- 'handle_whatsapp_chat_history',+ 'handle_whatsapp_db',# Document processing'handle_http_scraper','handle_file_downloader',diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.pyindex ef356a07..31039742 100644--- a/server/services/handlers/tools.py+++ b/server/services/handlers/tools.py@@ -56,9 +56,9 @@ async def execute_tool(tool_name: str, tool_args: Dict[str, Any],if node_type == 'whatsappSend':return await _execute_whatsapp_send(tool_args, config.get('parameters', {}))- # WhatsApp chat history (existing node used as tool)- if node_type == 'whatsappChatHistory':- return await _execute_whatsapp_chat_history(tool_args, config.get('parameters', {}))+ # WhatsApp DB (existing node used as tool) - query contacts, groups, messages+ if node_type == 'whatsappDb':+ return await _execute_whatsapp_db(tool_args, config.get('parameters', {}))# Android toolkit - routes to connected service nodesif node_type == 'androidTool':@@ -490,80 +490,99 @@ async def _execute_whatsapp_send(args: Dict[str, Any],return {"error": f"WhatsApp send failed: {str(e)}"}-async def _execute_whatsapp_chat_history(args: Dict[str, Any],- node_params: Dict[str, Any]) -> Dict[str, Any]:- """Retrieve WhatsApp chat history.+async def _execute_whatsapp_db(args: Dict[str, Any],+ node_params: Dict[str, Any]) -> Dict[str, Any]:+ """Query WhatsApp database - contacts, groups, messages.++ Supports 6 operations:+ - chat_history: Retrieve messages from a chat+ - search_groups: Search groups by name+ - get_group_info: Get group details with participant names+ - get_contact_info: Get full contact info (for send/reply)+ - list_contacts: List contacts with saved names+ - check_contacts: Check WhatsApp registration statusArgs:- args: LLM-provided arguments matching WhatsAppChatHistorySchema+ args: LLM-provided arguments matching WhatsAppDbSchemanode_params: Node parameters (used as fallback)Returns:- Dict with messages array and metadata+ Dict with operation-specific results"""- from services.handlers.whatsapp import handle_whatsapp_chat_history+ from services.handlers.whatsapp import handle_whatsapp_db++ operation = args.get('operation', 'chat_history')+ logger.info(f"[WhatsApp DB Tool] Executing operation: {operation}")++ # Build parameters for handler+ parameters = {'operation': operation}++ if operation == 'chat_history':+ parameters.update({+ 'chatType': args.get('chat_type', 'individual'),+ 'phone': args.get('phone', ''),+ 'group_id': args.get('group_id', ''),+ 'messageFilter': args.get('message_filter', 'all'),+ 'groupFilter': args.get('group_filter', 'all'),+ 'senderPhone': args.get('sender_phone', ''),+ 'limit': args.get('limit', 50),+ 'offset': args.get('offset', 0),+ })+ # Validate required fields+ chat_type = parameters['chatType']+ if chat_type == 'individual' and not parameters['phone']:+ return {"error": "Phone number is required for chat_type='individual'"}+ if chat_type == 'group' and not parameters['group_id']:+ return {"error": "Group ID is required for chat_type='group'"}++ elif operation == 'search_groups':+ parameters['query'] = args.get('query', '')++ elif operation == 'get_group_info':+ group_id = args.get('group_id', '')+ if not group_id:+ return {"error": "group_id is required for get_group_info"}+ parameters['groupIdForInfo'] = group_id++ elif operation == 'get_contact_info':+ phone = args.get('phone', '')+ if not phone:+ return {"error": "phone is required for get_contact_info"}+ parameters['contactPhone'] = phone++ elif operation == 'list_contacts':+ parameters['query'] = args.get('query', '')++ elif operation == 'check_contacts':+ phones = args.get('phones', '')+ if not phones:+ return {"error": "phones (comma-separated) is required for check_contacts"}+ parameters['phones'] = phones- # Map LLM args to node parameter format (camelCase for handler)- parameters = {- 'chatType': args.get('chat_type', 'individual'),- 'phone': args.get('phone', ''),- 'group_id': args.get('group_id', ''),- 'messageFilter': args.get('message_filter', 'all'),- 'limit': args.get('limit', 50),- 'offset': args.get('offset', 0),- 'resultMode': 'multiple', # Always return multiple messages for tool use- }-- # Validate required fields based on chat type- chat_type = parameters['chatType']-- if chat_type == 'individual' and not parameters['phone']:- return {"error": "Phone number is required for chat_type='individual'"}- if chat_type == 'group' and not parameters['group_id']:- return {"error": "Group ID is required for chat_type='group'"}-- identifier = parameters['phone'] if chat_type == 'individual' else parameters['group_id']- logger.info(f"[WhatsApp Tool] Getting chat history for {identifier[:15]}...")+ else:+ return {"error": f"Unknown operation: {operation}"}try:- result = await handle_whatsapp_chat_history(- node_id="tool_whatsapp_history",- node_type="whatsappChatHistory",+ result = await handle_whatsapp_db(+ node_id="tool_whatsapp_db",+ node_type="whatsappDb",parameters=parameters,context={})if result.get('success'):- messages = result.get('result', {}).get('messages', [])- total = result.get('result', {}).get('total', 0)- has_more = result.get('result', {}).get('has_more', False)-- # Format messages for LLM consumption- formatted_messages = []- for msg in messages:- formatted_messages.append({- "sender": msg.get('sender', ''),- "text": msg.get('text', ''),- "timestamp": msg.get('timestamp', ''),- "type": msg.get('type', 'text'),- "is_from_me": msg.get('is_from_me', False),- })-+ # Return the result section for LLM consumptionreturn {"success": True,- "chat_type": chat_type,- "identifier": identifier,- "messages": formatted_messages,- "total": total,- "has_more": has_more,- "count": len(formatted_messages)+ "operation": operation,+ **result.get('result', {})}else:return {"error": result.get('error', 'Unknown error')}except Exception as e:- logger.error(f"[WhatsApp Tool] Error: {e}")- return {"error": f"WhatsApp chat history failed: {str(e)}"}+ logger.error(f"[WhatsApp DB Tool] Error: {e}")+ return {"error": f"WhatsApp DB operation failed: {str(e)}"}async def _execute_android_toolkit(args: Dict[str, Any],diff --git a/server/services/handlers/whatsapp.py b/server/services/handlers/whatsapp.pyindex d61bea62..0a1253f4 100644--- a/server/services/handlers/whatsapp.py+++ b/server/services/handlers/whatsapp.py@@ -166,156 +166,265 @@ async def handle_whatsapp_connect(}-async def handle_whatsapp_chat_history(+async def handle_whatsapp_db(node_id: str,node_type: str,parameters: Dict[str, Any],context: Dict[str, Any]) -> Dict[str, Any]:- """Handle WhatsApp chat history - retrieve messages from history store.+ """Handle WhatsApp DB node - query contacts, groups, messages.- Messages are automatically captured from:- - HistorySync event on first login (all past messages)- - Real-time incoming messages+ Operations:+ - chat_history: Retrieve messages from history store+ - search_groups: Search groups by name+ - get_group_info: Get group details with participant names+ - get_contact_info: Get full contact info (name, phone, photo)+ - list_contacts: List contacts with saved names+ - check_contacts: Check WhatsApp registrationArgs:node_id: The node ID- node_type: The node type (whatsappChatHistory)- parameters: Resolved parameters including:- - chatType: 'individual' or 'group'- - phone: Phone number for individual chats- - group_id: Group JID for group chats- - groupFilter: 'all' or 'contact' for group message filtering- - senderPhone: Filter by sender in groups- - messageFilter: 'all' or 'text_only'- - limit: Max messages to return- - offset: Pagination offset+ node_type: The node type (whatsappDb)+ parameters: Resolved parameters including operation and operation-specific paramscontext: Execution contextReturns:- Execution result dict with messages array+ Execution result dict"""- from routers.whatsapp import handle_whatsapp_chat_history as whatsapp_chat_history_handler+ from routers.whatsapp import (+ handle_whatsapp_chat_history as whatsapp_chat_history_handler,+ whatsapp_rpc_call+ )start_time = time.time()try:- chat_type = parameters.get('chatType', 'individual')-- # Build RPC params based on chat type- rpc_params: Dict[str, Any] = {}-- if chat_type == 'individual':- phone = parameters.get('phone')- if not phone:- raise ValueError("Phone number is required for individual chats")- rpc_params['phone'] = phone+ operation = parameters.get('operation', 'chat_history')++ if operation == 'chat_history':+ return await _handle_chat_history(node_id, parameters, start_time, whatsapp_chat_history_handler)+ elif operation == 'search_groups':+ return await _handle_search_groups(node_id, parameters, start_time, whatsapp_rpc_call)+ elif operation == 'get_group_info':+ return await _handle_get_group_info(node_id, parameters, start_time, whatsapp_rpc_call)+ elif operation == 'get_contact_info':+ return await _handle_get_contact_info(node_id, parameters, start_time, whatsapp_rpc_call)+ elif operation == 'list_contacts':+ return await _handle_list_contacts(node_id, parameters, start_time, whatsapp_rpc_call)+ elif operation == 'check_contacts':+ return await _handle_check_contacts(node_id, parameters, start_time, whatsapp_rpc_call)else:- group_id = parameters.get('group_id')- if not group_id:- raise ValueError("Group ID is required for group chats")- rpc_params['group_id'] = group_id-- # Optional sender filter for groups- group_filter = parameters.get('groupFilter', 'all')- if group_filter == 'contact':- sender_phone = parameters.get('senderPhone')- if sender_phone:- rpc_params['sender_phone'] = sender_phone-- # Message type filter- message_filter = parameters.get('messageFilter', 'all')- rpc_params['text_only'] = message_filter == 'text_only'-- # Result mode and pagination- result_mode = parameters.get('resultMode', 'multiple')- position_raw = parameters.get('position', 1)- # Convert position to int (may be string from template variable resolution)- try:- position = int(position_raw) if position_raw else 1- except (ValueError, TypeError):- position = 1-- if result_mode == 'single':- # Single message by position mode- if position > 0:- # Positive: from newest (1=most recent)- rpc_params['limit'] = 1- rpc_params['offset'] = position - 1- else:- # Negative: from oldest (-1=oldest)- # First, get total count with limit=1 to minimize data transfer- rpc_params['limit'] = 1- rpc_params['offset'] = 0- count_data = await whatsapp_chat_history_handler(rpc_params)- total = count_data.get('total', 0)-- if total == 0:- return {- "success": True,- "node_id": node_id,- "node_type": "whatsappChatHistory",- "result": {- "messages": [],- "total": 0,- "has_more": False,- "count": 0,- "chat_type": chat_type,- "timestamp": datetime.now().isoformat()- },- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }-- # Calculate offset from the end: -1 = last (oldest in desc order = total-1)- # Since messages are ordered DESC (newest first), -1 means oldest = offset total-1- offset = total + position # e.g., total=100, pos=-1 -> offset=99- if offset < 0:- offset = 0- rpc_params['offset'] = offset- else:- # Multiple messages mode - use standard pagination- rpc_params['limit'] = parameters.get('limit', 50)- rpc_params['offset'] = parameters.get('offset', 0)-- # Call WhatsApp Go RPC service- data = await whatsapp_chat_history_handler(rpc_params)-- success = data.get('success', False)- if not success:- raise Exception(data.get('error', 'Failed to retrieve chat history'))-- messages = data.get('messages', [])- total = data.get('total', 0)- has_more = data.get('has_more', False)-- # Add index to each message (1-based, from offset)- base_offset = rpc_params.get('offset', 0)- for i, msg in enumerate(messages):- msg['index'] = base_offset + i + 1-- return {- "success": True,- "node_id": node_id,- "node_type": "whatsappChatHistory",- "result": {- "messages": messages,- "total": total,- "has_more": has_more,- "count": len(messages),- "chat_type": chat_type,- "timestamp": datetime.now().isoformat()- },- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }+ raise ValueError(f"Unknown operation: {operation}")except Exception as e:- logger.error("WhatsApp chat history failed", node_id=node_id, error=str(e))+ logger.error("WhatsApp DB failed", node_id=node_id, operation=parameters.get('operation'), error=str(e))return {"success": False,"node_id": node_id,- "node_type": "whatsappChatHistory",+ "node_type": "whatsappDb","error": str(e),"execution_time": time.time() - start_time,"timestamp": datetime.now().isoformat()}+++async def _handle_chat_history(node_id: str, parameters: Dict[str, Any], start_time: float, handler) -> Dict[str, Any]:+ """Handle chat_history operation."""+ chat_type = parameters.get('chatType', 'individual')+ rpc_params: Dict[str, Any] = {}++ if chat_type == 'individual':+ phone = parameters.get('phone')+ if not phone:+ raise ValueError("Phone number is required for individual chats")+ rpc_params['phone'] = phone+ else:+ group_id = parameters.get('group_id')+ if not group_id:+ raise ValueError("Group ID is required for group chats")+ rpc_params['group_id'] = group_id++ group_filter = parameters.get('groupFilter', 'all')+ if group_filter == 'contact':+ sender_phone = parameters.get('senderPhone')+ if sender_phone:+ rpc_params['sender_phone'] = sender_phone++ message_filter = parameters.get('messageFilter', 'all')+ rpc_params['text_only'] = message_filter == 'text_only'+ rpc_params['limit'] = parameters.get('limit', 50)+ rpc_params['offset'] = parameters.get('offset', 0)++ data = await handler(rpc_params)++ if not data.get('success', False):+ raise Exception(data.get('error', 'Failed to retrieve chat history'))++ messages = data.get('messages', [])+ base_offset = rpc_params.get('offset', 0)+ for i, msg in enumerate(messages):+ msg['index'] = base_offset + i + 1++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "whatsappDb",+ "result": {+ "operation": "chat_history",+ "messages": messages,+ "total": data.get('total', 0),+ "has_more": data.get('has_more', False),+ "count": len(messages),+ "chat_type": chat_type,+ "timestamp": datetime.now().isoformat()+ },+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+++async def _handle_search_groups(node_id: str, parameters: Dict[str, Any], start_time: float, rpc_call) -> Dict[str, Any]:+ """Handle search_groups operation."""+ query = parameters.get('query', '')+ data = await rpc_call('groups', {})++ if not data.get('success', True):+ raise Exception(data.get('error', 'Failed to get groups'))++ groups = data if isinstance(data, list) else data.get('result', [])++ # Filter by query if provided+ if query:+ query_lower = query.lower()+ groups = [g for g in groups if query_lower in g.get('name', '').lower()]++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "whatsappDb",+ "result": {+ "operation": "search_groups",+ "groups": groups,+ "total": len(groups),+ "query": query,+ "timestamp": datetime.now().isoformat()+ },+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+++async def _handle_get_group_info(node_id: str, parameters: Dict[str, Any], start_time: float, rpc_call) -> Dict[str, Any]:+ """Handle get_group_info operation."""+ group_id = parameters.get('groupIdForInfo') or parameters.get('group_id')+ if not group_id:+ raise ValueError("Group ID is required")++ data = await rpc_call('group_info', {'group_id': group_id})++ if not data.get('success', True) if isinstance(data, dict) else True:+ raise Exception(data.get('error', 'Failed to get group info') if isinstance(data, dict) else 'Failed')++ result = data if not isinstance(data, dict) or 'result' not in data else data.get('result', data)++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "whatsappDb",+ "result": {+ "operation": "get_group_info",+ **result,+ "timestamp": datetime.now().isoformat()+ },+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+++async def _handle_get_contact_info(node_id: str, parameters: Dict[str, Any], start_time: float, rpc_call) -> Dict[str, Any]:+ """Handle get_contact_info operation."""+ phone = parameters.get('contactPhone') or parameters.get('phone')+ if not phone:+ raise ValueError("Phone number is required")++ data = await rpc_call('contact_info', {'phone': phone})++ if isinstance(data, dict) and not data.get('success', True):+ raise Exception(data.get('error', 'Failed to get contact info'))++ result = data if not isinstance(data, dict) or 'result' not in data else data.get('result', data)++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "whatsappDb",+ "result": {+ "operation": "get_contact_info",+ **result,+ "timestamp": datetime.now().isoformat()+ },+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+++async def _handle_list_contacts(node_id: str, parameters: Dict[str, Any], start_time: float, rpc_call) -> Dict[str, Any]:+ """Handle list_contacts operation."""+ query = parameters.get('query', '')++ data = await rpc_call('contacts', {'query': query})++ if isinstance(data, dict) and not data.get('success', True):+ raise Exception(data.get('error', 'Failed to list contacts'))++ result = data if not isinstance(data, dict) or 'result' not in data else data.get('result', data)+ contacts = result.get('contacts', []) if isinstance(result, dict) else result++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "whatsappDb",+ "result": {+ "operation": "list_contacts",+ "contacts": contacts,+ "total": len(contacts),+ "query": query,+ "timestamp": datetime.now().isoformat()+ },+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+++async def _handle_check_contacts(node_id: str, parameters: Dict[str, Any], start_time: float, rpc_call) -> Dict[str, Any]:+ """Handle check_contacts operation."""+ phones_str = parameters.get('phones', '')+ if not phones_str:+ raise ValueError("Phone numbers are required")++ # Parse comma-separated phones+ phones = [p.strip() for p in phones_str.split(',') if p.strip()]+ if not phones:+ raise ValueError("At least one phone number is required")++ data = await rpc_call('contact_check', {'phones': phones})++ if isinstance(data, dict) and not data.get('success', True):+ raise Exception(data.get('error', 'Failed to check contacts'))++ results = data if isinstance(data, list) else data.get('result', [])++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "whatsappDb",+ "result": {+ "operation": "check_contacts",+ "results": results,+ "total": len(results),+ "timestamp": datetime.now().isoformat()+ },+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++diff --git a/server/services/node_executor.py b/server/services/node_executor.pyindex 6e39c856..ceba9e08 100644--- a/server/services/node_executor.py+++ b/server/services/node_executor.py@@ -31,7 +31,7 @@ from services.handlers import (handle_text_generator, handle_file_handler,handle_chat_send, handle_chat_history,handle_start, handle_cron_scheduler, handle_timer, handle_console,- handle_whatsapp_send, handle_whatsapp_connect, handle_whatsapp_chat_history,+ handle_whatsapp_send, handle_whatsapp_connect, handle_whatsapp_db,handle_http_scraper, handle_file_downloader, handle_document_parser,handle_text_chunker, handle_embedding_generator, handle_vector_store,)@@ -118,7 +118,7 @@ class NodeExecutor:'whatsappSend': handle_whatsapp_send,'whatsappConnect': handle_whatsapp_connect,- 'whatsappChatHistory': handle_whatsapp_chat_history,+ 'whatsappDb': handle_whatsapp_db,# Chat'chatSend': handle_chat_send,'chatHistory': handle_chat_history,diff --git a/server/skills/whatsapp-skill/SKILL.md b/server/skills/whatsapp-skill/SKILL.mdindex 3d8a9bce..e1259fa0 100644--- a/server/skills/whatsapp-skill/SKILL.md+++ b/server/skills/whatsapp-skill/SKILL.md@@ -1,16 +1,16 @@---name: whatsapp-skill-description: Send and receive WhatsApp messages, retrieve chat history. Supports text, images, videos, audio, documents, stickers, location, and contact cards.-allowed-tools: whatsapp_send whatsapp_chat_history+description: Send WhatsApp messages, query contacts/groups, retrieve chat history. Look up contact info by name or phone for sending/replying.+allowed-tools: whatsapp_send whatsapp_dbmetadata:author: machina- version: "2.0"+ version: "3.0"category: messaging---# WhatsApp Messaging Skill-Send and receive WhatsApp messages using connected WhatsApp nodes.+Send and receive WhatsApp messages, query contacts and groups using connected WhatsApp nodes.## Capabilities@@ -18,9 +18,12 @@ Send and receive WhatsApp messages using connected WhatsApp nodes.- Send media messages (images, videos, audio, documents, stickers)- Send location information- Send contact cards (vCard)-- Retrieve chat history from individual chats or groups-- Filter messages by type (all or text only)-- Paginate through message history+- **Query contacts** - List contacts with saved names (e.g., "Mummy", "Dad")+- **Get contact info** - Get full info including phone, name, profile picture URL+- **Search groups** - Find groups by name+- **Get group info** - Get group details with participant names and phone numbers+- **Retrieve chat history** - Messages from individual chats or groups+- **Check WhatsApp registration** - Verify if phone numbers are on WhatsApp## whatsapp_send@@ -90,46 +93,172 @@ Send messages to contacts or groups.}```-**Send contact card:**+## whatsapp_db++Query WhatsApp database - contacts, groups, messages.++### Operations++| Operation | Description |+|-----------|-------------|+| `list_contacts` | List all contacts with saved names |+| `get_contact_info` | Get full info for a contact (for sending/replying) |+| `search_groups` | Search groups by name |+| `get_group_info` | Get group details with participant names |+| `chat_history` | Retrieve message history |+| `check_contacts` | Check WhatsApp registration status |++### list_contacts++List contacts with their saved names. Useful for finding someone by name.++**Parameters:**+| Parameter | Type | Required | Description |+|-----------|------|----------|-------------|+| operation | string | Yes | "list_contacts" |+| query | string | No | Filter by name or phone (empty = all) |++**Example - Find contact by name:**```json{- "recipient_type": "phone",- "phone": "1234567890",- "message_type": "contact",- "contact_name": "John Doe",- "vcard": "BEGIN:VCARD\nVERSION:3.0\nFN:John Doe\nTEL:+1234567890\nEND:VCARD"+ "operation": "list_contacts",+ "query": "mom"}```-## whatsapp_chat_history+**Response:**+```json+{+ "contacts": [+ {"jid": "[email protected]", "phone": "919876543210", "name": "Mummy", "push_name": "Mom"},+ {"jid": "[email protected]", "phone": "918765432109", "name": "Mom Home", "push_name": ""}+ ],+ "total": 2+}+```-Retrieve message history from chats.+### get_contact_info-### Parameters+Get full contact info including profile picture URL. Use this to get phone number from a name for sending messages.++**Parameters:**+| Parameter | Type | Required | Description |+|-----------|------|----------|-------------|+| operation | string | Yes | "get_contact_info" |+| phone | string | Yes | Phone number (without + prefix) |++**Example:**+```json+{+ "operation": "get_contact_info",+ "phone": "919876543210"+}+```++**Response:**+```json+{+ "jid": "[email protected]",+ "phone": "919876543210",+ "name": "Ajay Flatmate",+ "push_name": "Ajay K",+ "business_name": "",+ "is_business": false,+ "is_contact": true,+ "profile_pic": "https://pps.whatsapp.net/v/..."+}+```++### search_groups++Search for groups by name.++**Parameters:**+| Parameter | Type | Required | Description |+|-----------|------|----------|-------------|+| operation | string | Yes | "search_groups" |+| query | string | No | Group name search (empty = all groups) |++**Example:**+```json+{+ "operation": "search_groups",+ "query": "family"+}+```++**Response:**+```json+{+ "groups": [+ {"jid": "[email protected]", "name": "Family Group", "participant_count": 12}+ ],+ "total": 1+}+```++### get_group_info++Get group details including participant names and phone numbers. Use this to find who is in a group and reply to specific members.++**Parameters:**+| Parameter | Type | Required | Description |+|-----------|------|----------|-------------|+| operation | string | Yes | "get_group_info" |+| group_id | string | Yes | Group JID (e.g., [email protected]) |++**Example:**+```json+{+ "operation": "get_group_info",+ "group_id": "[email protected]"+}+```++**Response:**+```json+{+ "jid": "[email protected]",+ "name": "Family Group",+ "participants": [+ {"jid": "[email protected]", "phone": "919876543210", "name": "Dad", "is_admin": true},+ {"jid": "[email protected]", "phone": "919987654321", "name": "Mom", "is_admin": false},+ {"jid": "[email protected]", "phone": "919123456789", "name": "", "is_admin": false}+ ]+}+```++### chat_history+Retrieve message history from chats.++**Parameters:**| Parameter | Type | Required | Description ||-----------|------|----------|-------------|-| chat_type | string | Yes | "individual" for 1:1 chat or "group" for group chat |+| operation | string | Yes | "chat_history" |+| chat_type | string | Yes | "individual" or "group" || phone | string | If individual | Phone number without + prefix |-| group_id | string | If group | Group JID (e.g., [email protected]) |+| group_id | string | If group | Group JID || message_filter | string | No | "all" (default) or "text_only" |-| limit | int | No | Max messages to retrieve (1-500, default 50) |-| offset | int | No | Messages to skip for pagination (default 0) |+| group_filter | string | No | For groups: "all" (default) or "contact" to filter by sender |+| sender_phone | string | No | For groups with group_filter="contact": filter messages from this phone |+| limit | int | No | Max messages (1-500, default 50) |+| offset | int | No | Skip for pagination (default 0) |-### Examples--**Get recent messages from contact:**+**Example - Individual chat:**```json{+ "operation": "chat_history","chat_type": "individual","phone": "1234567890","limit": 20}```-**Get text-only messages from group:**+**Example - Group chat:**```json{+ "operation": "chat_history","chat_type": "group","group_id": "[email protected]","message_filter": "text_only",@@ -137,51 +266,109 @@ Retrieve message history from chats.}```-**Paginate through history:**+**Example - Group chat filtered by sender:**```json{- "chat_type": "individual",- "phone": "1234567890",- "limit": 50,- "offset": 50+ "operation": "chat_history",+ "chat_type": "group",+ "group_id": "[email protected]",+ "group_filter": "contact",+ "sender_phone": "919876543210",+ "limit": 20}```-### Response Format+### check_contacts++Check if phone numbers are registered on WhatsApp.++**Parameters:**+| Parameter | Type | Required | Description |+|-----------|------|----------|-------------|+| operation | string | Yes | "check_contacts" |+| phones | string | Yes | Comma-separated phone numbers |+**Example:**```json{- "success": true,- "chat_type": "individual",- "identifier": "1234567890",- "messages": [- {- "sender": "1234567890",- "text": "Hello!",- "timestamp": "2025-01-27T10:30:00Z",- "type": "text",- "is_from_me": false- }- ],- "total": 150,- "has_more": true,- "count": 50+ "operation": "check_contacts",+ "phones": "1234567890, 0987654321"}```+## Common Workflows++### Send message to someone by name++1. Use `list_contacts` with query to find the person+2. Get their phone number from the result+3. Use `whatsapp_send` with the phone number++```+User: "Send 'Happy Birthday!' to Mom"+1. list_contacts with query="mom" -> finds phone 919876543210+2. whatsapp_send with phone=919876543210, message="Happy Birthday!"+```++### Reply to someone in a group++1. Use `get_group_info` to get participant names and phones+2. Use `whatsapp_send` with recipient_type="phone" and the person's phone++```+User: "Reply to Dad in Family Group saying 'I'll be there'"+1. search_groups with query="family" -> gets group JID+2. get_group_info -> finds Dad's phone 919876543210+3. whatsapp_send with phone=919876543210, message="I'll be there"+```++### Find and message a group++1. Use `search_groups` to find the group by name+2. Use `whatsapp_send` with recipient_type="group" and the group_id++## Using as Workflow Node++The WhatsApp DB node can be used directly in workflows (not just as an AI Agent tool):++1. **Add the node**: Drag "WhatsApp DB" from the Component Palette (WhatsApp category)+2. **Select operation**: Choose from the dropdown (Chat History, Search Groups, etc.)+3. **Configure parameters**: The UI shows only relevant parameters based on operation+4. **Connect**: Wire the node's output to downstream nodes+5. **Run**: Click Run to execute and see results in the Output Panel++### Output Variables++Each operation produces different output variables that can be dragged to downstream nodes:++| Operation | Output Fields |+|-----------|--------------|+| chat_history | `messages[]`, `total`, `has_more`, `count` |+| search_groups | `groups[]`, `total`, `query` |+| get_group_info | `jid`, `name`, `participants[]` |+| get_contact_info | `jid`, `phone`, `name`, `push_name`, `profile_pic` |+| list_contacts | `contacts[]`, `total`, `query` |+| check_contacts | `results[]`, `total` |++### Dual-Purpose Node++This node works both as:+- **Workflow Node**: Configure via UI parameters, outputs connect to other nodes+- **AI Agent Tool**: Connect to AI Agent's "Tool" handle for LLM-driven queries+## Guidelines-1. **Phone numbers**: Always use without + prefix, just digits (e.g., 1234567890)+1. **Phone numbers**: Always use without + prefix, just digits (e.g., 919876543210)2. **Groups**: Use JID format ending in @g.us-3. **Media URLs**: Must be publicly accessible URLs-4. **Location**: Both latitude and longitude are required-5. **Contact cards**: Use vCard 3.0 format-6. **Pagination**: Use offset with limit to page through results-7. **Message filter**: Use "text_only" to exclude media messages+3. **Contact lookup**: Use list_contacts first if you only have a name+4. **Group participants**: Use get_group_info to see who's in a group with their names+5. **Profile pictures**: get_contact_info returns a URL that may expire+6. **Media URLs**: Must be publicly accessible URLs+7. **Pagination**: Use offset with limit to page through chat history## Error Handling-- If recipient info is missing, ask for the phone number or group ID+- If recipient info is missing, use list_contacts or search_groups to find them- If message type requires media URL but none provided, request the URL- If location is requested but coordinates missing, ask for latitude and longitude- If WhatsApp is not connected, inform the user to check connection statusdiff --git a/server/whatsapp-rpc/schema.json b/server/whatsapp-rpc/schema.jsonindex 91924be2..876aa29e 100644--- a/server/whatsapp-rpc/schema.json+++ b/server/whatsapp-rpc/schema.json@@ -359,6 +359,72 @@}}},+ {+ "name": "contacts",+ "summary": "List all contacts with saved names",+ "description": "Returns contacts from the whatsmeow_contacts store with user-saved names",+ "params": [+ {+ "name": "query",+ "description": "Optional search query to filter by name or phone number",+ "schema": { "type": "string" },+ "required": false+ }+ ],+ "result": {+ "name": "ContactsResult",+ "schema": {+ "type": "object",+ "properties": {+ "contacts": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "jid": { "type": "string", "description": "Full JID (e.g., [email protected])" },+ "phone": { "type": "string", "description": "Phone number without @s.whatsapp.net" },+ "name": { "type": "string", "description": "User's saved contact name (e.g., 'Mummy', 'Dad')" },+ "push_name": { "type": "string", "description": "WhatsApp profile name set by user" },+ "is_contact": { "type": "boolean", "description": "Whether this is a saved contact" }+ }+ }+ },+ "total": { "type": "integer", "description": "Total number of contacts returned" }+ },+ "required": ["contacts", "total"]+ }+ }+ },+ {+ "name": "contact_info",+ "summary": "Get full information for a single contact",+ "description": "Returns comprehensive contact info including name, business status, and profile picture URL",+ "params": [+ {+ "name": "phone",+ "description": "Phone number (with or without + prefix)",+ "schema": { "type": "string" },+ "required": true+ }+ ],+ "result": {+ "name": "ContactInfoResult",+ "schema": {+ "type": "object",+ "properties": {+ "jid": { "type": "string", "description": "Full JID for sending messages" },+ "phone": { "type": "string", "description": "Phone number" },+ "name": { "type": "string", "description": "User's saved contact name" },+ "push_name": { "type": "string", "description": "WhatsApp profile name" },+ "business_name": { "type": "string", "description": "Business account verified name" },+ "is_business": { "type": "boolean", "description": "Whether this is a business account" },+ "is_contact": { "type": "boolean", "description": "Whether saved in contacts" },+ "profile_pic": { "type": "string", "description": "Profile picture URL" }+ },+ "required": ["jid", "phone"]+ }+ }+ },{"name": "typing","summary": "Send typing indicator to a chat",diff --git a/server/whatsapp-rpc/src/go/rpc/rpc.go b/server/whatsapp-rpc/src/go/rpc/rpc.goindex 387ff91b..083de96a 100644--- a/server/whatsapp-rpc/src/go/rpc/rpc.go+++ b/server/whatsapp-rpc/src/go/rpc/rpc.go@@ -192,6 +192,37 @@ func (h *RPCHandler) HandleRequest(req *RPCRequest) RPCResponse {resp.Result = result}+ case "contacts":+ var p struct {+ Query string `json:"query"`+ }+ if err := json.Unmarshal(req.Params, &p); err != nil {+ // If params parsing fails, use empty query (list all)+ p.Query = ""+ }+ if contacts, err := h.service.GetContacts(p.Query); err != nil {+ resp.Error = &RPCError{Code: -32000, Message: err.Error()}+ } else {+ resp.Result = map[string]interface{}{+ "contacts": contacts,+ "total": len(contacts),+ }+ }++ case "contact_info":+ var p struct {+ Phone string `json:"phone"`+ }+ if err := json.Unmarshal(req.Params, &p); err != nil {+ resp.Error = &RPCError{Code: -32602, Message: "Invalid params: " + err.Error()}+ } else if p.Phone == "" {+ resp.Error = &RPCError{Code: -32602, Message: "phone is required"}+ } else if info, err := h.service.GetContactInfo(p.Phone); err != nil {+ resp.Error = &RPCError{Code: -32000, Message: err.Error()}+ } else {+ resp.Result = info+ }+case "typing":var p struct {JID string `json:"jid"`diff --git a/server/whatsapp-rpc/src/go/whatsapp/service.go b/server/whatsapp-rpc/src/go/whatsapp/service.goindex c3b0e990..e2960ab3 100644--- a/server/whatsapp-rpc/src/go/whatsapp/service.go+++ b/server/whatsapp-rpc/src/go/whatsapp/service.go@@ -947,6 +947,117 @@ func (s *Service) resolveParticipantPhone(ctx context.Context, p types.GroupPartreturn p.JID.User}+// GetContactName looks up a contact name by phone number+// Prefers user's saved name, falls back to push name+func (s *Service) GetContactName(phone string) string {+ if s.client == nil || s.client.Store == nil || s.client.Store.Contacts == nil {+ return ""+ }++ jid := types.NewJID(phone, types.DefaultUserServer)+ contact, err := s.client.Store.Contacts.GetContact(context.Background(), jid)+ if err != nil {+ return ""+ }++ // Prefer user's saved name, fall back to push name+ if contact.FullName != "" {+ return contact.FullName+ }+ return contact.PushName+}++// GetContacts returns all stored contacts with names+func (s *Service) GetContacts(query string) ([]ContactInfo, error) {+ if !s.client.IsConnected() {+ return nil, fmt.Errorf("WhatsApp not connected")+ }++ ctx := context.Background()+ contacts, err := s.client.Store.Contacts.GetAllContacts(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to get contacts: %w", err)+ }++ result := make([]ContactInfo, 0)+ queryLower := strings.ToLower(query)++ for jid, info := range contacts {+ // Skip non-user JIDs (groups, etc.)+ if jid.Server != types.DefaultUserServer {+ continue+ }++ // Filter by query if provided+ if query != "" {+ nameMatch := strings.Contains(strings.ToLower(info.FullName), queryLower) ||+ strings.Contains(strings.ToLower(info.PushName), queryLower) ||+ strings.Contains(jid.User, query)+ if !nameMatch {+ continue+ }+ }++ result = append(result, ContactInfo{+ JID: jid.String(),+ Phone: jid.User,+ Name: info.FullName,+ PushName: info.PushName,+ IsContact: true,+ })+ }++ s.logger.Infof("Retrieved %d contacts (query: %q)", len(result), query)+ return result, nil+}++// GetContactInfo returns full info for a single contact (for send/reply use case)+func (s *Service) GetContactInfo(phone string) (*ContactInfo, error) {+ if !s.client.IsConnected() {+ return nil, fmt.Errorf("WhatsApp not connected")+ }++ // Clean phone number - remove + prefix if present+ phone = strings.TrimPrefix(phone, "+")++ jid := types.NewJID(phone, types.DefaultUserServer)+ ctx := context.Background()++ result := &ContactInfo{+ JID: jid.String(),+ Phone: jid.User,+ }++ // Get contact details from store (saved names)+ if s.client.Store != nil && s.client.Store.Contacts != nil {+ contact, err := s.client.Store.Contacts.GetContact(ctx, jid)+ if err == nil {+ result.Name = contact.FullName+ result.PushName = contact.PushName+ result.BusinessName = contact.BusinessName+ result.IsContact = true+ }+ }++ // Check WhatsApp registration + business info+ resp, err := s.client.IsOnWhatsApp(ctx, []string{"+" + jid.User})+ if err == nil && len(resp) > 0 {+ if resp[0].VerifiedName != nil {+ result.IsBusiness = true+ result.BusinessName = resp[0].VerifiedName.Details.GetVerifiedName()+ }+ }++ // Get profile photo URL+ picInfo, err := s.client.GetProfilePictureInfo(ctx, jid, &whatsmeow.GetProfilePictureParams{Preview: false})+ if err == nil && picInfo != nil && picInfo.URL != "" {+ result.ProfilePic = picInfo.URL+ }++ s.logger.Infof("Retrieved contact info for %s: name=%q", phone, result.Name)+ return result, nil+}+// generateGroupsJSON fetches all groups and saves to data/groups.json// Called automatically on WhatsApp connection for fast offline accessfunc (s *Service) generateGroupsJSON() error {@@ -1039,6 +1150,7 @@ func (s *Service) GetGroups() ([]GroupInfo, error) {participants = append(participants, GroupParticipant{JID: p.JID.String(),Phone: phone,+ Name: s.GetContactName(phone),IsAdmin: p.IsAdmin,IsSuperAdmin: p.IsSuperAdmin,})@@ -1086,6 +1198,7 @@ func (s *Service) GetGroupInfo(groupJID string) (*GroupInfo, error) {participants = append(participants, GroupParticipant{JID: p.JID.String(),Phone: phone,+ Name: s.GetContactName(phone),IsAdmin: p.IsAdmin,IsSuperAdmin: p.IsSuperAdmin,})