Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
Add chatTrigger node with split Chat/Console panel
trohitg71aebfe45c44
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsxindex a7265e7f..7f6c1ca3 100644--- a/client/src/Dashboard.tsx+++ b/client/src/Dashboard.tsx@@ -62,7 +62,7 @@ const createNodeTypes = (): Record<string, React.ComponentType<any>> => {const types: Record<string, React.ComponentType<any>> = {};// Trigger nodes (no input handles) - check by group or specific types- const TRIGGER_NODE_TYPES = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive'];+ const TRIGGER_NODE_TYPES = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive', 'chatTrigger'];Object.keys(nodeDefinitions).forEach(type => {const definition = nodeDefinitions[type];@@ -585,11 +585,11 @@ const DashboardContent: React.FC = () => {if (!currentWorkflow) return;// Check if there's at least one trigger node (workflow entry points)- // Trigger types: start, cronScheduler, webhookTrigger, whatsappReceive, workflowTrigger- const triggerTypes = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive', 'workflowTrigger'];+ // Trigger types: start, cronScheduler, webhookTrigger, whatsappReceive, workflowTrigger, chatTrigger+ const triggerTypes = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive', 'workflowTrigger', 'chatTrigger'];const hasTriggerNode = nodes.some(node => triggerTypes.includes(node.type || ''));if (!hasTriggerNode) {- alert('No trigger node found in workflow.\n\nAdd a trigger node (Cron Scheduler, WhatsApp Receive, Webhook, etc.) to begin deployment.');+ alert('No trigger node found in workflow.\n\nAdd a trigger node (Cron Scheduler, WhatsApp Receive, Webhook, Chat Trigger, etc.) to begin deployment.');return;}diff --git a/client/src/components/parameterPanel/InputSection.tsx b/client/src/components/parameterPanel/InputSection.tsxindex 7fd9d741..d341ed40 100644--- a/client/src/components/parameterPanel/InputSection.tsx+++ b/client/src/components/parameterPanel/InputSection.tsx@@ -326,6 +326,11 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =volume: 'number',is_playing: 'boolean',current_track: 'string'+ },+ chatTrigger: {+ message: 'string',+ timestamp: 'string',+ session_id: 'string'}};@@ -342,6 +347,7 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =const isJavaScript = nodeType.includes('javascript') || nodeType.includes('Javascript');const isCodeExecutor = isPython || isJavaScript;const isCronScheduler = nodeType === 'cronScheduler';+ const isChatTrigger = nodeType === 'chatTrigger';// Android service node detection - check for specific Android node typesconst androidNodeTypes = [@@ -374,6 +380,7 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =isHttpRequest ? sampleSchemas.httpRequest :isCodeExecutor ? sampleSchemas.python :isCronScheduler ? sampleSchemas.cronScheduler :+ isChatTrigger ? sampleSchemas.chatTrigger :{ data: 'any' };}}diff --git a/client/src/components/ui/ConsolePanel.tsx b/client/src/components/ui/ConsolePanel.tsxindex f338a312..40ec06f5 100644--- a/client/src/components/ui/ConsolePanel.tsx+++ b/client/src/components/ui/ConsolePanel.tsx@@ -1,8 +1,10 @@/**- * Console Panel - n8n-style debug output panel+ * Console Panel - n8n-style debug output panel with chat input** Displays console log entries from Console nodes during workflow execution.+ * Includes chat input section for triggering chatTrigger nodes.* Shows in a collapsible bottom bar section with clear and filter options.+ * Chat and Console are split 50/50 side by side.* Supports resizing by dragging the top edge.*/@@ -19,7 +21,7 @@ interface ConsolePanelProps {maxHeight?: number;}-// Storage key for persisting panel height+// Storage keys for persisting stateconst CONSOLE_HEIGHT_KEY = 'console_panel_height';const ConsolePanel: React.FC<ConsolePanelProps> = ({@@ -31,10 +33,16 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({}) => {const theme = useAppTheme();const { isDarkMode } = useTheme();- const { consoleLogs, clearConsoleLogs } = useWebSocket();+ const { consoleLogs, clearConsoleLogs, sendChatMessage, chatMessages, clearChatMessages } = useWebSocket();const [filter, setFilter] = useState('');const [autoScroll, setAutoScroll] = useState(true);const logsEndRef = useRef<HTMLDivElement>(null);+ const chatEndRef = useRef<HTMLDivElement>(null);+ const chatInputRef = useRef<HTMLInputElement>(null);++ // Chat input state+ const [chatInput, setChatInput] = useState('');+ const [isSending, setIsSending] = useState(false);// Panel height state with localStorage persistenceconst [panelHeight, setPanelHeight] = useState(() => {@@ -122,10 +130,45 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({}}, [filteredLogs.length, autoScroll, isOpen]);- const handleClear = useCallback(() => {+ // Auto-scroll chat when new messages arrive+ useEffect(() => {+ if (isOpen && chatEndRef.current) {+ chatEndRef.current.scrollIntoView({ behavior: 'smooth' });+ }+ }, [chatMessages?.length, isOpen]);++ const handleClearConsole = useCallback(() => {clearConsoleLogs();}, [clearConsoleLogs]);+ const handleClearChat = useCallback(() => {+ clearChatMessages();+ }, [clearChatMessages]);++ // Handle chat message send+ const handleSendChat = useCallback(async () => {+ const message = chatInput.trim();+ if (!message || isSending) return;++ setIsSending(true);+ try {+ await sendChatMessage(message);+ setChatInput('');+ } catch (error) {+ console.error('Failed to send chat message:', error);+ } finally {+ setIsSending(false);+ }+ }, [chatInput, isSending, sendChatMessage]);++ // Handle Enter key in chat input+ const handleChatKeyDown = useCallback((e: React.KeyboardEvent) => {+ if (e.key === 'Enter' && !e.shiftKey) {+ e.preventDefault();+ handleSendChat();+ }+ }, [handleSendChat]);+const formatTimestamp = useCallback((timestamp: string) => {try {const date = new Date(timestamp);@@ -172,7 +215,7 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({zIndex: 10};- // Panel header with toggle, clear, and filter+ // Panel header with toggleconst panelHeaderStyle: React.CSSProperties = {display: 'flex',alignItems: 'center',@@ -190,12 +233,6 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({gap: '8px'};- const headerRightStyle: React.CSSProperties = {- display: 'flex',- alignItems: 'center',- gap: '8px'- };-const titleStyle: React.CSSProperties = {fontSize: theme.fontSize.sm,fontWeight: theme.fontWeight.semibold,@@ -214,37 +251,70 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({fontWeight: theme.fontWeight.medium};+ const contentStyle: React.CSSProperties = {+ height: isOpen ? `${panelHeight}px` : '0px',+ overflow: 'hidden',+ backgroundColor: isDarkMode ? theme.dracula.background : theme.colors.background,+ transition: isResizing ? 'none' : 'height 0.2s ease-in-out',+ display: 'flex',+ flexDirection: 'row' // Side by side+ };++ const sectionStyle: React.CSSProperties = {+ flex: 1,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden',+ borderRight: `1px solid ${isDarkMode ? theme.dracula.selection : theme.colors.border}`+ };++ const sectionHeaderStyle: React.CSSProperties = {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ padding: '6px 12px',+ backgroundColor: isDarkMode ? theme.dracula.currentLine : theme.colors.backgroundPanel,+ borderBottom: `1px solid ${isDarkMode ? theme.dracula.selection : theme.colors.border}`,+ minHeight: '32px'+ };++ const sectionTitleStyle: React.CSSProperties = {+ fontSize: theme.fontSize.xs,+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.text,+ display: 'flex',+ alignItems: 'center',+ gap: '6px'+ };+const buttonStyle: React.CSSProperties = {background: 'none',border: 'none',cursor: 'pointer',- padding: '4px 8px',+ padding: '2px 6px',borderRadius: '4px',- fontSize: theme.fontSize.xs,+ fontSize: '10px',color: theme.colors.textSecondary,transition: 'background-color 0.15s ease'};+ const clearButtonStyle: React.CSSProperties = {+ ...buttonStyle,+ backgroundColor: isDarkMode ? `${theme.dracula.red}20` : `${theme.colors.error}15`,+ color: isDarkMode ? theme.dracula.red : theme.colors.error+ };+const filterInputStyle: React.CSSProperties = {- padding: '4px 8px',- fontSize: theme.fontSize.xs,+ padding: '2px 6px',+ fontSize: '10px',backgroundColor: isDarkMode ? theme.dracula.background : theme.colors.background,border: `1px solid ${theme.colors.border}`,borderRadius: '4px',color: theme.colors.text,- width: '150px',+ width: '100px',outline: 'none'};- const contentStyle: React.CSSProperties = {- height: isOpen ? `${panelHeight}px` : '0px',- overflow: isOpen ? 'auto' : 'hidden',- backgroundColor: isDarkMode ? theme.dracula.background : theme.colors.background,- transition: isResizing ? 'none' : 'height 0.2s ease-in-out',- fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Monaco, Consolas, monospace',- fontSize: '12px'- };-const logEntryStyle: React.CSSProperties = {display: 'flex',padding: '4px 12px',@@ -287,7 +357,11 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({padding: '24px',textAlign: 'center',color: theme.colors.textMuted,- fontSize: theme.fontSize.sm+ fontSize: theme.fontSize.xs,+ flex: 1,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center'};const chevronStyle: React.CSSProperties = {@@ -296,6 +370,70 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({color: theme.colors.textSecondary};+ // Chat styles+ const chatMessagesStyle: React.CSSProperties = {+ flex: 1,+ overflow: 'auto',+ padding: '8px 12px'+ };++ const chatInputContainerStyle: React.CSSProperties = {+ display: 'flex',+ gap: '8px',+ padding: '8px 12px',+ borderTop: `1px solid ${isDarkMode ? theme.dracula.selection : theme.colors.border}`,+ backgroundColor: isDarkMode ? theme.dracula.currentLine : theme.colors.backgroundPanel+ };++ const chatInputStyle: React.CSSProperties = {+ flex: 1,+ padding: '6px 10px',+ fontSize: theme.fontSize.sm,+ backgroundColor: isDarkMode ? theme.dracula.background : theme.colors.background,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: '6px',+ color: theme.colors.text,+ outline: 'none'+ };++ const sendButtonStyle: React.CSSProperties = {+ padding: '6px 12px',+ fontSize: theme.fontSize.xs,+ fontWeight: theme.fontWeight.medium,+ backgroundColor: isDarkMode ? theme.dracula.green : theme.colors.success,+ color: isDarkMode ? theme.dracula.background : 'white',+ border: 'none',+ borderRadius: '6px',+ cursor: isSending ? 'not-allowed' : 'pointer',+ opacity: isSending ? 0.7 : 1,+ transition: 'all 0.15s ease'+ };++ const chatMessageStyle = (isUser: boolean): React.CSSProperties => ({+ padding: '6px 10px',+ marginBottom: '6px',+ borderRadius: '8px',+ backgroundColor: isUser+ ? (isDarkMode ? `${theme.dracula.purple}30` : `${theme.colors.primary}15`)+ : (isDarkMode ? theme.dracula.selection : theme.colors.backgroundPanel),+ maxWidth: '85%',+ alignSelf: isUser ? 'flex-end' : 'flex-start',+ wordBreak: 'break-word'+ });++ const chatMessageTextStyle: React.CSSProperties = {+ fontSize: theme.fontSize.xs,+ color: theme.colors.text,+ margin: 0,+ whiteSpace: 'pre-wrap'+ };++ const chatMessageTimeStyle: React.CSSProperties = {+ fontSize: '9px',+ color: theme.colors.textMuted,+ marginTop: '2px'+ };+return (<div style={{ position: 'relative' }}>{/* Resize Handle - Only visible when open */}@@ -330,19 +468,101 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({</svg></span><span style={titleStyle}>- Console- {consoleLogs.length > 0 && (- <span style={badgeStyle}>{consoleLogs.length}</span>+ Chat / Console+ {(consoleLogs.length > 0 || (chatMessages && chatMessages.length > 0)) && (+ <span style={badgeStyle}>+ {consoleLogs.length + (chatMessages?.length || 0)}+ </span>)}</span></div>+ </div>++ {/* Panel Content - Split 50/50 */}+ <div style={contentStyle}>+ {/* Chat Section - Left Half */}+ <div style={sectionStyle}>+ <div style={sectionHeaderStyle}>+ <span style={sectionTitleStyle}>+ Chat+ {chatMessages && chatMessages.length > 0 && (+ <span style={{+ ...badgeStyle,+ backgroundColor: isDarkMode ? `${theme.dracula.green}40` : `${theme.colors.success}20`,+ color: isDarkMode ? theme.dracula.green : theme.colors.success+ }}>+ {chatMessages.length}+ </span>+ )}+ </span>+ {chatMessages && chatMessages.length > 0 && (+ <button+ style={clearButtonStyle}+ onClick={handleClearChat}+ onMouseEnter={e => {+ e.currentTarget.style.backgroundColor = isDarkMode ? `${theme.dracula.red}35` : `${theme.colors.error}25`;+ }}+ onMouseLeave={e => {+ e.currentTarget.style.backgroundColor = isDarkMode ? `${theme.dracula.red}20` : `${theme.colors.error}15`;+ }}+ >+ Clear+ </button>+ )}+ </div>+ <div style={chatMessagesStyle}>+ {(!chatMessages || chatMessages.length === 0) ? (+ <div style={emptyStyle}>+ Send a message to trigger chatTrigger nodes+ </div>+ ) : (+ <div style={{ display: 'flex', flexDirection: 'column' }}>+ {chatMessages.map((msg, index) => (+ <div key={`${msg.timestamp}-${index}`} style={chatMessageStyle(msg.role === 'user')}>+ <p style={chatMessageTextStyle}>{msg.message}</p>+ <div style={chatMessageTimeStyle}>+ {formatTimestamp(msg.timestamp)}+ </div>+ </div>+ ))}+ <div ref={chatEndRef} />+ </div>+ )}+ </div>+ <div style={chatInputContainerStyle}>+ <input+ ref={chatInputRef}+ type="text"+ placeholder="Type a message..."+ value={chatInput}+ onChange={e => setChatInput(e.target.value)}+ onKeyDown={handleChatKeyDown}+ style={chatInputStyle}+ disabled={isSending}+ />+ <button+ style={sendButtonStyle}+ onClick={handleSendChat}+ disabled={isSending || !chatInput.trim()}+ >+ {isSending ? '...' : 'Send'}+ </button>+ </div>+ </div>- <div style={headerRightStyle} onClick={e => e.stopPropagation()}>- {isOpen && (- <>+ {/* Console Section - Right Half */}+ <div style={{ ...sectionStyle, borderRight: 'none' }}>+ <div style={sectionHeaderStyle}>+ <span style={sectionTitleStyle}>+ Console+ {consoleLogs.length > 0 && (+ <span style={badgeStyle}>{consoleLogs.length}</span>+ )}+ </span>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}><inputtype="text"- placeholder="Filter logs..."+ placeholder="Filter..."value={filter}onChange={e => setFilter(e.target.value)}style={filterInputStyle}@@ -353,76 +573,72 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({...buttonStyle,display: 'flex',alignItems: 'center',- gap: '4px',- cursor: 'pointer'+ gap: '3px',+ cursor: 'pointer',+ fontSize: '10px'}}- onClick={e => e.stopPropagation()}><inputtype="checkbox"checked={autoScroll}onChange={e => setAutoScroll(e.target.checked)}- style={{ cursor: 'pointer' }}+ style={{ cursor: 'pointer', width: '12px', height: '12px' }}/>- Auto-scroll+ Auto</label>- <button- style={{- ...buttonStyle,- backgroundColor: isDarkMode ? `${theme.dracula.red}20` : `${theme.colors.error}15`,- color: isDarkMode ? theme.dracula.red : theme.colors.error- }}- onClick={handleClear}- onMouseEnter={e => {- e.currentTarget.style.backgroundColor = isDarkMode ? `${theme.dracula.red}35` : `${theme.colors.error}25`;- }}- onMouseLeave={e => {- e.currentTarget.style.backgroundColor = isDarkMode ? `${theme.dracula.red}20` : `${theme.colors.error}15`;- }}- >- Clear- </button>- </>- )}- </div>- </div>-- {/* Panel Content */}- <div style={contentStyle}>- {filteredLogs.length === 0 ? (- <div style={emptyStyle}>- {consoleLogs.length === 0- ? 'No console output yet. Add a Console node to your workflow to see debug output here.'- : 'No logs match the current filter.'}- </div>- ) : (- filteredLogs.slice().reverse().map((log, index) => (- <div key={`${log.node_id}-${log.timestamp}-${index}`} style={logEntryStyle}>- <span style={timestampStyle}>{formatTimestamp(log.timestamp)}</span>- <span style={labelStyle} title={log.label || log.node_id}>- {log.label || log.node_id}- </span>- {log.source_node_label && (- <span style={nodeInfoStyle} title={`Source: ${log.source_node_type} (${log.source_node_id})`}>- {log.source_node_label}- </span>+ {consoleLogs.length > 0 && (+ <button+ style={clearButtonStyle}+ onClick={handleClearConsole}+ onMouseEnter={e => {+ e.currentTarget.style.backgroundColor = isDarkMode ? `${theme.dracula.red}35` : `${theme.colors.error}25`;+ }}+ onMouseLeave={e => {+ e.currentTarget.style.backgroundColor = isDarkMode ? `${theme.dracula.red}20` : `${theme.colors.error}15`;+ }}+ >+ Clear+ </button>)}- <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></div>- ))- )}- <div ref={logsEndRef} />+ </div>+ <div style={{ flex: 1, overflow: 'auto', fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Monaco, Consolas, monospace', fontSize: '12px' }}>+ {filteredLogs.length === 0 ? (+ <div style={emptyStyle}>+ {consoleLogs.length === 0+ ? 'Add a Console node to see debug output'+ : 'No logs match the filter'}+ </div>+ ) : (+ filteredLogs.slice().reverse().map((log, index) => (+ <div key={`${log.node_id}-${log.timestamp}-${index}`} style={logEntryStyle}>+ <span style={timestampStyle}>{formatTimestamp(log.timestamp)}</span>+ <span style={labelStyle} title={log.label || log.node_id}>+ {log.label || log.node_id}+ </span>+ {log.source_node_label && (+ <span style={nodeInfoStyle} title={`Source: ${log.source_node_type} (${log.source_node_id})`}>+ {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>+ </div>+ ))+ )}+ <div ref={logsEndRef} />+ </div>+ </div></div></div>);diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsxindex 7721dcf7..e6bc085b 100644--- a/client/src/contexts/WebSocketContext.tsx+++ b/client/src/contexts/WebSocketContext.tsx@@ -31,7 +31,7 @@ interface PendingRequest {const REQUEST_TIMEOUT = 30000;// Trigger node types that wait indefinitely for events-const TRIGGER_NODE_TYPES = ['whatsappReceive', 'webhookTrigger', 'cronScheduler'];+const TRIGGER_NODE_TYPES = ['whatsappReceive', 'webhookTrigger', 'cronScheduler', 'chatTrigger'];// Status typesexport interface AndroidStatus {@@ -113,6 +113,14 @@ export interface ConsoleLogEntry {source_node_label?: string;}+// Chat message for chatTrigger nodes+export interface ChatMessage {+ role: 'user' | 'assistant';+ message: string;+ timestamp: string;+ session_id?: string;+}+// WhatsApp received message structure (from Go service via whatsapp_message_received event)export interface WhatsAppMessage {message_id: string;@@ -162,6 +170,7 @@ interface WebSocketContextValue {lastWhatsAppMessage: WhatsAppMessage | null; // Most recent messageapiKeyStatuses: Record<string, ApiKeyStatus>;consoleLogs: ConsoleLogEntry[]; // Console node output logs+ chatMessages: ChatMessage[]; // Chat messages for chatTriggernodeStatuses: Record<string, NodeStatus>; // Current workflow's node statusesnodeParameters: Record<string, NodeParameters>;variables: Record<string, any>;@@ -177,6 +186,8 @@ interface WebSocketContextValue {clearNodeStatus: (nodeId: string) => Promise<void>;clearWhatsAppMessages: () => void;clearConsoleLogs: () => void;+ clearChatMessages: () => void;+ sendChatMessage: (message: string, sessionId?: string) => Promise<void>;// Generic request methodsendRequest: <T = any>(type: string, data?: Record<string, any>) => Promise<T>;@@ -302,6 +313,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chiconst [lastWhatsAppMessage, setLastWhatsAppMessage] = useState<WhatsAppMessage | null>(null);const [apiKeyStatuses, setApiKeyStatuses] = useState<Record<string, ApiKeyStatus>>({});const [consoleLogs, setConsoleLogs] = useState<ConsoleLogEntry[]>([]);+ const [chatMessages, setChatMessages] = useState<ChatMessage[]>([]);// Per-workflow node statuses: workflow_id -> node_id -> NodeStatus (n8n pattern)const [allNodeStatuses, setAllNodeStatuses] = useState<Record<string, Record<string, NodeStatus>>>({});const [nodeParameters, setNodeParameters] = useState<Record<string, NodeParameters>>({});@@ -934,6 +946,11 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chisetConsoleLogs([]);}, []);+ // Clear chat messages+ const clearChatMessages = useCallback(() => {+ setChatMessages([]);+ }, []);+// Derive current workflow's node statuses (n8n pattern)// This provides a flat Record<nodeId, NodeStatus> for the current workflow// IMPORTANT: Use currentWorkflowId state directly, not ref, to ensure re-render on workflow switch@@ -989,6 +1006,36 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi});}, []);+ // =========================================================================+ // Chat Message Operations+ // =========================================================================++ // Send chat message (triggers chatTrigger nodes)+ const sendChatMessageAsync = useCallback(async (message: string, sessionId?: string): Promise<void> => {+ const timestamp = new Date().toISOString();+ const chatMessage: ChatMessage = {+ role: 'user',+ message,+ timestamp,+ session_id: sessionId || 'default'+ };++ // Add to local messages immediately for UI feedback+ setChatMessages(prev => [...prev, chatMessage]);++ // Send to backend to dispatch to chatTrigger nodes+ try {+ await sendRequest('send_chat_message', {+ message,+ session_id: sessionId || 'default',+ timestamp+ });+ } catch (error) {+ console.error('[WebSocket] Failed to send chat message:', error);+ throw error;+ }+ }, [sendRequest]);+// =========================================================================// Node Parameters Operations// =========================================================================@@ -1626,6 +1673,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chilastWhatsAppMessage,apiKeyStatuses,consoleLogs,+ chatMessages,nodeStatuses,nodeParameters,variables,@@ -1641,6 +1689,8 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chiclearNodeStatus,clearWhatsAppMessages,clearConsoleLogs,+ clearChatMessages,+ sendChatMessage: sendChatMessageAsync,// Generic request methodsendRequest,diff --git a/client/src/nodeDefinitions/utilityNodes.ts b/client/src/nodeDefinitions/utilityNodes.tsindex 2b08d1e7..6331ca3b 100644--- a/client/src/nodeDefinitions/utilityNodes.ts+++ b/client/src/nodeDefinitions/utilityNodes.ts@@ -182,6 +182,39 @@ export const utilityNodes: Record<string, INodeTypeDescription> = {]},+ chatTrigger: {+ displayName: 'Chat Trigger',+ name: 'chatTrigger',+ icon: '💬',+ group: ['utility', 'trigger'],+ version: 1,+ description: 'Trigger workflow when user sends a chat message from the console input',+ defaults: { name: 'Chat Trigger', color: '#10b981' },+ inputs: [],+ outputs: [{+ name: 'main',+ displayName: 'Message',+ type: 'main' as NodeConnectionType,+ description: 'message, timestamp, session_id'+ }],+ properties: [+ {+ displayName: 'Session ID',+ name: 'sessionId',+ type: 'string',+ default: 'default',+ description: 'Session identifier for grouping messages'+ },+ {+ displayName: 'Placeholder',+ name: 'placeholder',+ type: 'string',+ default: 'Type a message...',+ description: 'Placeholder text for the chat input'+ }+ ]+ },+console: {displayName: 'Console',name: 'console',@@ -248,4 +281,4 @@ export const utilityNodes: Record<string, INodeTypeDescription> = {}};-export const UTILITY_NODE_TYPES = ['httpRequest', 'webhookTrigger', 'webhookResponse', 'console'];+export const UTILITY_NODE_TYPES = ['httpRequest', 'webhookTrigger', 'webhookResponse', 'chatTrigger', 'console'];diff --git a/server/constants.py b/server/constants.pyindex 126d87b6..0c12af3c 100644--- a/server/constants.py+++ b/server/constants.py@@ -168,6 +168,7 @@ EVENT_TRIGGER_TYPES: FrozenSet[str] = frozenset(['webhookTrigger','whatsappReceive','workflowTrigger',+ 'chatTrigger',])# Legacy alias for backwards compatibility@@ -188,6 +189,7 @@ WORKFLOW_TRIGGER_TYPES: FrozenSet[str] = frozenset(['webhookTrigger','whatsappReceive','workflowTrigger',+ 'chatTrigger',])# =============================================================================diff --git a/server/routers/websocket.py b/server/routers/websocket.pyindex 60cda13a..155bb3e6 100644--- a/server/routers/websocket.py+++ b/server/routers/websocket.py@@ -1386,6 +1386,42 @@ async def handle_delete_workflow(data: Dict[str, Any], websocket: WebSocket) ->return {"success": success, "workflow_id": data["workflow_id"]}+# ============================================================================+# Chat Message Handler (for chatTrigger nodes)+# ============================================================================++@ws_handler("message")+async def handle_send_chat_message(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Handle chat message from console panel - dispatches to chatTrigger nodes.++ This handler receives messages from the frontend chat panel and dispatches+ them as 'chat_message_received' events to any waiting chatTrigger nodes.+ """+ from services import event_waiter++ message = data["message"]+ session_id = data.get("session_id", "default")+ timestamp = data.get("timestamp") or datetime.now().isoformat()++ # Build event data matching chatTrigger output schema+ event_data = {+ "message": message,+ "timestamp": timestamp,+ "session_id": session_id+ }++ # Dispatch to chatTrigger waiters+ resolved = event_waiter.dispatch("chat_message_received", event_data)++ logger.info(f"[ChatMessage] Dispatched message to {resolved} chatTrigger waiter(s)")++ return {+ "success": True,+ "message": "Chat message sent",+ "resolved_count": resolved+ }++# ============================================================================# Message Router# ============================================================================@@ -1472,6 +1508,9 @@ MESSAGE_HANDLERS: Dict[str, MessageHandler] = {"get_workflow": handle_get_workflow,"get_all_workflows": handle_get_all_workflows,"delete_workflow": handle_delete_workflow,++ # Chat message (for chatTrigger nodes)+ "send_chat_message": handle_send_chat_message,}diff --git a/server/services/event_waiter.py b/server/services/event_waiter.pyindex 0b7a2bbe..7a5f5b2d 100644--- a/server/services/event_waiter.py+++ b/server/services/event_waiter.py@@ -197,6 +197,11 @@ TRIGGER_REGISTRY: Dict[str, TriggerConfig] = {event_type='webhook_received',display_name='Webhook Request'),+ 'chatTrigger': TriggerConfig(+ node_type='chatTrigger',+ event_type='chat_message_received',+ display_name='Chat Message'+ ),# Future triggers - just add to registry:# 'emailTrigger': TriggerConfig('emailTrigger', 'email_received', 'Email'),# 'mqttTrigger': TriggerConfig('mqttTrigger', 'mqtt_message', 'MQTT Message'),@@ -357,10 +362,31 @@ def build_webhook_filter(params: Dict) -> Callable[[Dict], bool]:return matches+def build_chat_filter(params: Dict) -> Callable[[Dict], bool]:+ """Build filter function for chat messages from console input.++ Args:+ params: Node parameters with 'sessionId' field++ Returns:+ Filter function that checks if event session_id matches+ """+ session_id = params.get('sessionId', 'default')++ def matches(data: Dict) -> bool:+ event_session = data.get('session_id', 'default')+ if session_id != 'default' and event_session != session_id:+ return False+ return True++ return matches++# Registry of filter builders per trigger typeFILTER_BUILDERS: Dict[str, Callable[[Dict], Callable[[Dict], bool]]] = {'whatsappReceive': build_whatsapp_filter,'webhookTrigger': build_webhook_filter,+ 'chatTrigger': build_chat_filter,}