Skip to content

Self-improving AI Employees for everyone

Add Console node with n8n-style debug panel

trohitg4b2e5a3f8bc5
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsx
index 674c87eb..a7265e7f 100644
--- a/client/src/Dashboard.tsx
+++ b/client/src/Dashboard.tsx
@@ -40,6 +40,7 @@ import AndroidSettingsPanel from './components/ui/AndroidSettingsPanel';
import AIResultModal from './components/ui/AIResultModal';
import CredentialsModal from './components/CredentialsModal';
import ErrorBoundary from './components/ui/ErrorBoundary';
+import ConsolePanel from './components/ui/ConsolePanel';
import { useAppTheme } from './hooks/useAppTheme';
import { useWorkflowManagement } from './hooks/useWorkflowManagement';
import { useDragAndDrop } from './hooks/useDragAndDrop';
@@ -327,6 +328,7 @@ const DashboardContent: React.FC = () => {
});
const [settingsOpen, setSettingsOpen] = React.useState(false);
const [credentialsOpen, setCredentialsOpen] = React.useState(false);
+ const [consolePanelOpen, setConsolePanelOpen] = React.useState(false);
// Context menu state for node right-click
const [contextMenu, setContextMenu] = React.useState<{
@@ -1068,7 +1070,13 @@ const DashboardContent: React.FC = () => {
</div>
</div>
</div>
-
+
+ {/* Console Panel - n8n-style debug output at bottom */}
+ <ConsolePanel
+ isOpen={consolePanelOpen}
+ onToggle={() => setConsolePanelOpen(prev => !prev)}
+ />
+
{/* Parameter Panels */}
<ErrorBoundary>
<ParameterPanel />
diff --git a/client/src/components/SquareNode.tsx b/client/src/components/SquareNode.tsx
index d4a30a27..d0d53fa5 100644
--- a/client/src/components/SquareNode.tsx
+++ b/client/src/components/SquareNode.tsx
@@ -23,6 +23,9 @@ const GOOGLE_MAPS_NODE_TYPES = ['createMap', 'addLocations', 'showNearbyPlaces']
// WhatsApp node types
const WHATSAPP_NODE_TYPES = ['whatsappConnect', 'whatsappSend', 'whatsappReceive', 'whatsappChatHistory'];
+// Nodes that should not have output handles (input-only nodes)
+const NO_OUTPUT_NODE_TYPES = ['console'];
+
// AI Model node types with their provider IDs
const AI_MODEL_NODE_TYPES: Record<string, string> = {
'openaiChatModel': 'openai',
@@ -651,26 +654,28 @@ const SquareNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectab
title="Service Input"
/>
- {/* Square Output Handle */}
- <Handle
- id="output-main"
- type="source"
- position={Position.Right}
- isConnectable={isConnectable}
- style={{
- position: 'absolute',
- right: '-6px',
- top: '50%',
- transform: 'translateY(-50%)',
- width: theme.nodeSize.handle,
- height: theme.nodeSize.handle,
- backgroundColor: isConfigured ? nodeColor : theme.colors.textSecondary,
- border: `2px solid ${theme.isDarkMode ? theme.colors.background : '#ffffff'}`,
- borderRadius: '50%',
- zIndex: 20
- }}
- title="Service Output"
- />
+ {/* Square Output Handle - hidden for input-only nodes like console */}
+ {!NO_OUTPUT_NODE_TYPES.includes(type || '') && (
+ <Handle
+ id="output-main"
+ type="source"
+ position={Position.Right}
+ isConnectable={isConnectable}
+ style={{
+ position: 'absolute',
+ right: '-6px',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ width: theme.nodeSize.handle,
+ height: theme.nodeSize.handle,
+ backgroundColor: isConfigured ? nodeColor : theme.colors.textSecondary,
+ border: `2px solid ${theme.isDarkMode ? theme.colors.background : '#ffffff'}`,
+ borderRadius: '50%',
+ zIndex: 20
+ }}
+ title="Service Output"
+ />
+ )}
{/* Top Tool Output Handle - only for Android service nodes that can connect to Toolkit */}
{isToolCapable && (
diff --git a/client/src/components/TriggerNode.tsx b/client/src/components/TriggerNode.tsx
index 62055537..28eb41a8 100644
--- a/client/src/components/TriggerNode.tsx
+++ b/client/src/components/TriggerNode.tsx
@@ -35,11 +35,11 @@ const TriggerNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnecta
const isWhatsAppTrigger = type === 'whatsappReceive';
const whatsappStatus = useWhatsAppStatus();
- // n8n Pattern: Distinguish between waiting (listening) and executing states
- // - waiting: Trigger is listening for events (shows subtle cyan indicator, no glow/animation)
- // - executing: Only used when trigger itself is being executed (rare, used for manual runs)
- const isWaiting = executionStatus === 'waiting';
- const isExecuting = executionStatus === 'executing';
+ // Combine waiting and executing states for glow animation (matching SquareNode pattern)
+ // - waiting: Trigger is listening for events (cron scheduled, webhook listening)
+ // - executing: Trigger is actively running
+ // Both states show the glow animation to indicate active state
+ const isExecuting = executionStatus === 'executing' || executionStatus === 'waiting';
const definition = nodeDefinitions[type as keyof typeof nodeDefinitions];
@@ -99,13 +99,9 @@ const TriggerNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnecta
// Get status indicator color based on execution state
const getStatusIndicatorColor = () => {
- // n8n Pattern: Different colors for different trigger states
+ // Combined executing/waiting state - show purple with glow
if (isExecuting) {
- return theme.dracula.purple; // Actually executing (manual run)
- }
- if (isWaiting) {
- // Waiting/listening for events - show cyan (active listener)
- return theme.dracula.cyan;
+ return theme.dracula.purple;
}
if (executionStatus === 'success') {
return theme.dracula.green;
@@ -214,7 +210,7 @@ const TriggerNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnecta
}}
>
{/* Main Trigger Node */}
- {/* n8n Pattern: Only show glow/animation for actual executing state, not for waiting */}
+ {/* Show glow animation for both executing and waiting states */}
<div
style={{
position: 'relative',
@@ -306,7 +302,7 @@ const TriggerNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnecta
</button>
{/* Execution Status Indicator */}
- {/* n8n Pattern: No glow for waiting, only for actual execution */}
+ {/* Status Indicator - glows for both waiting and executing states */}
<div
style={{
position: 'absolute',
diff --git a/client/src/components/parameterPanel/InputSection.tsx b/client/src/components/parameterPanel/InputSection.tsx
index b50a5485..7fd9d741 100644
--- a/client/src/components/parameterPanel/InputSection.tsx
+++ b/client/src/components/parameterPanel/InputSection.tsx
@@ -173,6 +173,28 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =
sender_name: 'string'
}
},
+ whatsappChatHistory: {
+ // Sample message array structure for schema view
+ messages: [
+ {
+ text: 'string',
+ sender: 'string',
+ sender_phone: 'string',
+ message_type: 'string',
+ timestamp: 'string',
+ message_id: 'string',
+ is_from_me: 'boolean',
+ is_group: 'boolean',
+ push_name: 'string',
+ index: 'number'
+ }
+ ],
+ total: 'number',
+ has_more: 'boolean',
+ count: 'number',
+ chat_type: 'string',
+ timestamp: 'string'
+ },
webhook: {
method: 'string',
path: 'string',
@@ -312,7 +334,8 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =
const nodeTypeLower = nodeType.toLowerCase();
const isAI = !isMemory && (nodeTypeLower.includes('chatmodel') || nodeTypeLower.includes('aiagent'));
const isFile = nodeType.includes('file');
- const isWhatsApp = nodeType.includes('whatsapp') || nodeType.includes('Whatsapp');
+ const isWhatsAppChatHistory = nodeType === 'whatsappChatHistory';
+ const isWhatsApp = !isWhatsAppChatHistory && (nodeType.includes('whatsapp') || nodeType.includes('Whatsapp'));
const isWebhook = nodeType === 'webhookTrigger';
const isHttpRequest = nodeType === 'httpRequest';
const isPython = nodeType.includes('python') || nodeType.includes('Python');
@@ -345,6 +368,7 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =
isMemory ? sampleSchemas.memory :
isAI ? sampleSchemas.ai :
isFile ? sampleSchemas.file :
+ isWhatsAppChatHistory ? sampleSchemas.whatsappChatHistory :
isWhatsApp ? sampleSchemas.whatsapp :
isWebhook ? sampleSchemas.webhook :
isHttpRequest ? sampleSchemas.httpRequest :
@@ -391,10 +415,219 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =
// Render draggable property
// NOTE: sourceNodeId is the unique node ID, used for template variable resolution
- const renderDraggableProperty = (key: string, value: any, sourceNodeId: string, path: string = '', depth: number = 0) => {
+ const renderDraggableProperty = (key: string, value: any, sourceNodeId: string, path: string = '', depth: number = 0, maxArrayItems: number = 3) => {
const currentPath = path ? `${path}.${key}` : key;
const isObject = typeof value === 'object' && value !== null && !Array.isArray(value);
+ const isArray = Array.isArray(value);
+
+ // Handle arrays - show indexed items
+ if (isArray && value.length > 0) {
+ const templateName = getTemplateVariableName(sourceNodeId);
+ const itemsToShow = Math.min(value.length, maxArrayItems);
+
+ return (
+ <div key={currentPath} style={{ marginLeft: depth > 0 ? 16 : 0, marginBottom: 8 }}>
+ <div style={{
+ fontSize: theme.fontSize.xs,
+ fontWeight: theme.fontWeight.medium,
+ color: theme.colors.textMuted,
+ marginBottom: 4,
+ display: 'flex',
+ alignItems: 'center',
+ gap: 6,
+ }}>
+ {key}
+ <span style={{
+ fontSize: '10px',
+ color: theme.dracula.purple,
+ padding: '1px 6px',
+ backgroundColor: theme.dracula.purple + '20',
+ borderRadius: theme.borderRadius.sm,
+ }}>
+ [{value.length} items]
+ </span>
+ </div>
+ <div>
+ {/* Render first N array items with their index */}
+ {value.slice(0, itemsToShow).map((item: any, index: number) => {
+ const indexedPath = `${key}[${index}]`;
+ const fullIndexedPath = path ? `${path}.${indexedPath}` : indexedPath;
+
+ if (typeof item === 'object' && item !== null) {
+ // Object item - render its properties with indexed path
+ return (
+ <div key={`${currentPath}[${index}]`} style={{
+ marginLeft: 8,
+ marginBottom: 8,
+ padding: theme.spacing.xs,
+ backgroundColor: theme.colors.backgroundElevated,
+ borderRadius: theme.borderRadius.sm,
+ border: `1px dashed ${theme.colors.border}`,
+ }}>
+ <div style={{
+ fontSize: theme.fontSize.xs,
+ fontWeight: theme.fontWeight.medium,
+ color: theme.dracula.cyan,
+ marginBottom: 4,
+ }}>
+ [{index}]
+ </div>
+ {Object.entries(item).map(([itemKey, itemValue]) => {
+ const itemPath = `${fullIndexedPath}.${itemKey}`;
+ // For nested objects within array items, render as draggable
+ if (typeof itemValue === 'object' && itemValue !== null && !Array.isArray(itemValue)) {
+ return (
+ <div key={itemPath} style={{ marginLeft: 8, marginBottom: 4 }}>
+ <div style={{
+ fontSize: theme.fontSize.xs,
+ color: theme.colors.textMuted,
+ marginBottom: 2,
+ }}>
+ {itemKey}:
+ </div>
+ {Object.entries(itemValue as Record<string, any>).map(([nestedKey, nestedValue]) => (
+ <div
+ key={`${itemPath}.${nestedKey}`}
+ draggable
+ onDragStart={(e) => handleVariableDragStart(e, sourceNodeId, `${itemPath}.${nestedKey}`, nestedValue)}
+ style={{
+ marginBottom: 4,
+ marginLeft: 8,
+ padding: `${theme.spacing.xs} ${theme.spacing.sm}`,
+ backgroundColor: theme.colors.backgroundAlt,
+ border: `1px solid ${theme.colors.focus}`,
+ borderRadius: theme.borderRadius.sm,
+ cursor: 'grab',
+ fontSize: theme.fontSize.xs,
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = theme.colors.focusRing;
+ e.currentTarget.style.borderColor = theme.dracula.cyan;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = theme.colors.backgroundAlt;
+ e.currentTarget.style.borderColor = theme.colors.focus;
+ }}
+ >
+ <span style={{ color: theme.colors.templateVariable, fontFamily: 'monospace' }}>
+ {`{{${templateName}.${itemPath}.${nestedKey}}}`}
+ </span>
+ </div>
+ ))}
+ </div>
+ );
+ }
+ // Primitive value in array item
+ return (
+ <div
+ key={itemPath}
+ draggable
+ onDragStart={(e) => handleVariableDragStart(e, sourceNodeId, itemPath, itemValue)}
+ style={{
+ marginBottom: 4,
+ marginLeft: 8,
+ padding: `${theme.spacing.xs} ${theme.spacing.sm}`,
+ backgroundColor: theme.colors.backgroundAlt,
+ border: `1px solid ${theme.colors.focus}`,
+ borderRadius: theme.borderRadius.sm,
+ cursor: 'grab',
+ fontSize: theme.fontSize.xs,
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = theme.colors.focusRing;
+ e.currentTarget.style.borderColor = theme.dracula.cyan;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = theme.colors.backgroundAlt;
+ e.currentTarget.style.borderColor = theme.colors.focus;
+ }}
+ >
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <div>
+ <span style={{ color: theme.colors.templateVariable, fontFamily: 'monospace' }}>
+ {`{{${templateName}.${itemPath}}}`}
+ </span>
+ <span style={{ color: theme.colors.textMuted, marginLeft: 8 }}>
+ {itemKey}: {typeof itemValue}
+ </span>
+ </div>
+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke={theme.colors.templateVariable} strokeWidth="2">
+ <line x1="12" y1="5" x2="12" y2="19"/>
+ <polyline points="19 12 12 19 5 12"/>
+ </svg>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ );
+ } else {
+ // Primitive array item
+ return (
+ <div
+ key={`${currentPath}[${index}]`}
+ draggable
+ onDragStart={(e) => handleVariableDragStart(e, sourceNodeId, fullIndexedPath, item)}
+ style={{
+ marginBottom: 4,
+ marginLeft: 8,
+ padding: `${theme.spacing.xs} ${theme.spacing.sm}`,
+ backgroundColor: theme.colors.backgroundAlt,
+ border: `1px solid ${theme.colors.focus}`,
+ borderRadius: theme.borderRadius.sm,
+ cursor: 'grab',
+ fontSize: theme.fontSize.xs,
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = theme.colors.focusRing;
+ e.currentTarget.style.borderColor = theme.dracula.cyan;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = theme.colors.backgroundAlt;
+ e.currentTarget.style.borderColor = theme.colors.focus;
+ }}
+ >
+ <span style={{ color: theme.colors.templateVariable, fontFamily: 'monospace' }}>
+ {`{{${templateName}.${fullIndexedPath}}}`}
+ </span>
+ <span style={{ color: theme.colors.textMuted, marginLeft: 8 }}>
+ [{index}]: {typeof item}
+ </span>
+ </div>
+ );
+ }
+ })}
+ {/* Show "and N more" if array has more items */}
+ {value.length > maxArrayItems && (
+ <div style={{
+ marginLeft: 8,
+ fontSize: theme.fontSize.xs,
+ color: theme.colors.textMuted,
+ fontStyle: 'italic',
+ }}>
+ ... and {value.length - maxArrayItems} more items
+ </div>
+ )}
+ </div>
+ </div>
+ );
+ }
+
+ // Handle empty arrays
+ if (isArray && value.length === 0) {
+ return (
+ <div key={currentPath} style={{ marginLeft: depth > 0 ? 16 : 0, marginBottom: 8 }}>
+ <div style={{
+ fontSize: theme.fontSize.xs,
+ color: theme.colors.textMuted,
+ }}>
+ {key}: <span style={{ fontStyle: 'italic' }}>empty array</span>
+ </div>
+ </div>
+ );
+ }
+ // Handle objects
if (isObject) {
return (
<div key={currentPath} style={{ marginLeft: depth > 0 ? 16 : 0, marginBottom: 8 }}>
diff --git a/client/src/components/ui/ConsolePanel.tsx b/client/src/components/ui/ConsolePanel.tsx
new file mode 100644
index 00000000..f338a312
--- /dev/null
+++ b/client/src/components/ui/ConsolePanel.tsx
@@ -0,0 +1,431 @@
+/**
+ * Console Panel - n8n-style debug output panel
+ *
+ * Displays console log entries from Console nodes during workflow execution.
+ * Shows in a collapsible bottom bar section with clear and filter options.
+ * Supports resizing by dragging the top edge.
+ */
+
+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';
+
+interface ConsolePanelProps {
+ isOpen: boolean;
+ onToggle: () => void;
+ defaultHeight?: number;
+ minHeight?: number;
+ maxHeight?: number;
+}
+
+// Storage key for persisting panel height
+const CONSOLE_HEIGHT_KEY = 'console_panel_height';
+
+const ConsolePanel: React.FC<ConsolePanelProps> = ({
+ isOpen,
+ onToggle,
+ defaultHeight = 250,
+ minHeight = 100,
+ maxHeight = 600
+}) => {
+ const theme = useAppTheme();
+ const { isDarkMode } = useTheme();
+ const { consoleLogs, clearConsoleLogs } = useWebSocket();
+ const [filter, setFilter] = useState('');
+ const [autoScroll, setAutoScroll] = useState(true);
+ const logsEndRef = useRef<HTMLDivElement>(null);
+
+ // Panel height state with localStorage persistence
+ const [panelHeight, setPanelHeight] = useState(() => {
+ try {
+ const saved = localStorage.getItem(CONSOLE_HEIGHT_KEY);
+ if (saved) {
+ const height = parseInt(saved, 10);
+ if (!isNaN(height) && height >= minHeight && height <= maxHeight) {
+ return height;
+ }
+ }
+ } catch {
+ // Ignore localStorage errors
+ }
+ return defaultHeight;
+ });
+
+ // Resize state
+ const [isResizing, setIsResizing] = useState(false);
+ const resizeStartY = useRef(0);
+ const resizeStartHeight = useRef(0);
+
+ // Save height to localStorage when it changes
+ useEffect(() => {
+ try {
+ localStorage.setItem(CONSOLE_HEIGHT_KEY, panelHeight.toString());
+ } catch {
+ // Ignore localStorage errors
+ }
+ }, [panelHeight]);
+
+ // Handle resize start
+ const handleResizeStart = useCallback((e: React.MouseEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setIsResizing(true);
+ resizeStartY.current = e.clientY;
+ resizeStartHeight.current = panelHeight;
+ }, [panelHeight]);
+
+ // Handle resize move
+ useEffect(() => {
+ if (!isResizing) return;
+
+ const handleMouseMove = (e: MouseEvent) => {
+ const delta = resizeStartY.current - e.clientY;
+ const newHeight = Math.min(maxHeight, Math.max(minHeight, resizeStartHeight.current + delta));
+ setPanelHeight(newHeight);
+ };
+
+ const handleMouseUp = () => {
+ setIsResizing(false);
+ };
+
+ document.addEventListener('mousemove', handleMouseMove);
+ document.addEventListener('mouseup', handleMouseUp);
+
+ // Add cursor style to body during resize
+ document.body.style.cursor = 'ns-resize';
+ document.body.style.userSelect = 'none';
+
+ return () => {
+ document.removeEventListener('mousemove', handleMouseMove);
+ document.removeEventListener('mouseup', handleMouseUp);
+ document.body.style.cursor = '';
+ document.body.style.userSelect = '';
+ };
+ }, [isResizing, minHeight, maxHeight]);
+
+ // Filter logs based on search input
+ const filteredLogs = useMemo(() => {
+ if (!filter) return consoleLogs;
+ const lowerFilter = filter.toLowerCase();
+ return consoleLogs.filter(log =>
+ log.label.toLowerCase().includes(lowerFilter) ||
+ log.formatted.toLowerCase().includes(lowerFilter) ||
+ log.node_id.toLowerCase().includes(lowerFilter)
+ );
+ }, [consoleLogs, filter]);
+
+ // Auto-scroll to bottom when new logs arrive
+ useEffect(() => {
+ if (autoScroll && isOpen && logsEndRef.current) {
+ logsEndRef.current.scrollIntoView({ behavior: 'smooth' });
+ }
+ }, [filteredLogs.length, autoScroll, isOpen]);
+
+ const handleClear = useCallback(() => {
+ clearConsoleLogs();
+ }, [clearConsoleLogs]);
+
+ const formatTimestamp = useCallback((timestamp: string) => {
+ try {
+ const date = new Date(timestamp);
+ const timeStr = date.toLocaleTimeString('en-US', {
+ hour12: false,
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit'
+ });
+ // Add milliseconds manually
+ const ms = date.getMilliseconds().toString().padStart(3, '0');
+ return `${timeStr}.${ms}`;
+ } catch {
+ return timestamp;
+ }
+ }, []);
+
+ const getFormatColor = useCallback((format: ConsoleLogEntry['format']) => {
+ switch (format) {
+ case 'json':
+ case 'json_compact':
+ return isDarkMode ? theme.dracula.cyan : '#0891b2';
+ case 'text':
+ return isDarkMode ? theme.dracula.foreground : theme.colors.text;
+ case 'table':
+ return isDarkMode ? theme.dracula.green : '#059669';
+ default:
+ return theme.colors.text;
+ }
+ }, [isDarkMode, theme]);
+
+ // Resize handle style
+ const resizeHandleStyle: React.CSSProperties = {
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ right: 0,
+ height: '6px',
+ cursor: 'ns-resize',
+ backgroundColor: isResizing
+ ? (isDarkMode ? theme.dracula.purple : theme.colors.primary)
+ : 'transparent',
+ transition: isResizing ? 'none' : 'background-color 0.15s ease',
+ zIndex: 10
+ };
+
+ // Panel header with toggle, clear, and filter
+ const panelHeaderStyle: React.CSSProperties = {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ padding: '6px 12px',
+ backgroundColor: isDarkMode ? theme.dracula.currentLine : theme.colors.backgroundPanel,
+ borderTop: `1px solid ${theme.colors.border}`,
+ cursor: 'pointer',
+ userSelect: 'none'
+ };
+
+ const headerLeftStyle: React.CSSProperties = {
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px'
+ };
+
+ const headerRightStyle: React.CSSProperties = {
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px'
+ };
+
+ const titleStyle: React.CSSProperties = {
+ fontSize: theme.fontSize.sm,
+ fontWeight: theme.fontWeight.semibold,
+ color: theme.colors.text,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px'
+ };
+
+ const badgeStyle: React.CSSProperties = {
+ backgroundColor: isDarkMode ? `${theme.dracula.purple}40` : `${theme.colors.primary}20`,
+ color: isDarkMode ? theme.dracula.purple : theme.colors.primary,
+ padding: '1px 6px',
+ borderRadius: '10px',
+ fontSize: theme.fontSize.xs,
+ fontWeight: theme.fontWeight.medium
+ };
+
+ const buttonStyle: React.CSSProperties = {
+ background: 'none',
+ border: 'none',
+ cursor: 'pointer',
+ padding: '4px 8px',
+ borderRadius: '4px',
+ fontSize: theme.fontSize.xs,
+ color: theme.colors.textSecondary,
+ transition: 'background-color 0.15s ease'
+ };
+
+ const filterInputStyle: React.CSSProperties = {
+ padding: '4px 8px',
+ fontSize: theme.fontSize.xs,
+ backgroundColor: isDarkMode ? theme.dracula.background : theme.colors.background,
+ border: `1px solid ${theme.colors.border}`,
+ borderRadius: '4px',
+ color: theme.colors.text,
+ width: '150px',
+ 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',
+ borderBottom: `1px solid ${isDarkMode ? theme.dracula.selection : theme.colors.border}`,
+ gap: '12px',
+ alignItems: 'flex-start'
+ };
+
+ const timestampStyle: React.CSSProperties = {
+ color: isDarkMode ? theme.dracula.comment : theme.colors.textMuted,
+ fontSize: '11px',
+ whiteSpace: 'nowrap',
+ minWidth: '90px'
+ };
+
+ const labelStyle: React.CSSProperties = {
+ color: isDarkMode ? theme.dracula.yellow : theme.colors.warning,
+ fontSize: '12px',
+ fontWeight: theme.fontWeight.medium,
+ minWidth: '80px',
+ maxWidth: '120px',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap'
+ };
+
+ const nodeInfoStyle: React.CSSProperties = {
+ color: isDarkMode ? theme.dracula.pink : '#db2777',
+ fontSize: '11px',
+ fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Monaco, Consolas, monospace',
+ minWidth: '80px',
+ maxWidth: '120px',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ opacity: 0.85
+ };
+
+ const emptyStyle: React.CSSProperties = {
+ padding: '24px',
+ textAlign: 'center',
+ color: theme.colors.textMuted,
+ fontSize: theme.fontSize.sm
+ };
+
+ const chevronStyle: React.CSSProperties = {
+ transform: isOpen ? 'rotate(0deg)' : 'rotate(180deg)',
+ transition: 'transform 0.2s ease',
+ color: theme.colors.textSecondary
+ };
+
+ return (
+ <div style={{ position: 'relative' }}>
+ {/* Resize Handle - Only visible when open */}
+ {isOpen && (
+ <div
+ style={resizeHandleStyle}
+ onMouseDown={handleResizeStart}
+ onMouseEnter={e => {
+ if (!isResizing) {
+ e.currentTarget.style.backgroundColor = isDarkMode
+ ? `${theme.dracula.purple}40`
+ : `${theme.colors.primary}30`;
+ }
+ }}
+ onMouseLeave={e => {
+ if (!isResizing) {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ }
+ }}
+ />
+ )}
+
+ {/* Panel Header - Always visible */}
+ <div
+ style={panelHeaderStyle}
+ onClick={onToggle}
+ >
+ <div style={headerLeftStyle}>
+ <span style={chevronStyle}>
+ <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor">
+ <path d="M2 4L6 8L10 4" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
+ </svg>
+ </span>
+ <span style={titleStyle}>
+ Console
+ {consoleLogs.length > 0 && (
+ <span style={badgeStyle}>{consoleLogs.length}</span>
+ )}
+ </span>
+ </div>
+
+ <div style={headerRightStyle} onClick={e => e.stopPropagation()}>
+ {isOpen && (
+ <>
+ <input
+ type="text"
+ placeholder="Filter logs..."
+ value={filter}
+ onChange={e => setFilter(e.target.value)}
+ style={filterInputStyle}
+ onClick={e => e.stopPropagation()}
+ />
+ <label
+ style={{
+ ...buttonStyle,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ cursor: 'pointer'
+ }}
+ onClick={e => e.stopPropagation()}
+ >
+ <input
+ type="checkbox"
+ checked={autoScroll}
+ onChange={e => setAutoScroll(e.target.checked)}
+ style={{ cursor: 'pointer' }}
+ />
+ Auto-scroll
+ </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>
+ )}
+ <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>
+ );
+};
+
+export default ConsolePanel;
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsx
index cd8fd21b..7721dcf7 100644
--- a/client/src/contexts/WebSocketContext.tsx
+++ b/client/src/contexts/WebSocketContext.tsx
@@ -98,6 +98,21 @@ export interface ApiKeyStatus {
timestamp?: number;
}
+// Console log entry from Console nodes
+export interface ConsoleLogEntry {
+ node_id: string;
+ label: string;
+ timestamp: string;
+ data: any;
+ formatted: string;
+ format: 'json' | 'json_compact' | 'text' | 'table';
+ workflow_id?: string;
+ // Source node info (the node whose output is being logged)
+ source_node_id?: string;
+ source_node_type?: string;
+ source_node_label?: string;
+}
+
// WhatsApp received message structure (from Go service via whatsapp_message_received event)
export interface WhatsAppMessage {
message_id: string;
@@ -146,6 +161,7 @@ interface WebSocketContextValue {
whatsappMessages: WhatsAppMessage[]; // History of received messages
lastWhatsAppMessage: WhatsAppMessage | null; // Most recent message
apiKeyStatuses: Record<string, ApiKeyStatus>;
+ consoleLogs: ConsoleLogEntry[]; // Console node output logs
nodeStatuses: Record<string, NodeStatus>; // Current workflow's node statuses
nodeParameters: Record<string, NodeParameters>;
variables: Record<string, any>;
@@ -160,6 +176,7 @@ interface WebSocketContextValue {
requestStatus: () => void;
clearNodeStatus: (nodeId: string) => Promise<void>;
clearWhatsAppMessages: () => void;
+ clearConsoleLogs: () => void;
// Generic request method
sendRequest: <T = any>(type: string, data?: Record<string, any>) => Promise<T>;
@@ -284,6 +301,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
const [whatsappMessages, setWhatsappMessages] = useState<WhatsAppMessage[]>([]);
const [lastWhatsAppMessage, setLastWhatsAppMessage] = useState<WhatsAppMessage | null>(null);
const [apiKeyStatuses, setApiKeyStatuses] = useState<Record<string, ApiKeyStatus>>({});
+ const [consoleLogs, setConsoleLogs] = useState<ConsoleLogEntry[]>([]);
// 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>>({});
@@ -691,6 +709,38 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
// Keep-alive response, no action needed
break;
+ case 'console_log':
+ // Handle console log entries from Console nodes
+ if (data) {
+ const logEntry: ConsoleLogEntry = {
+ node_id: data.node_id || '',
+ label: data.label || 'Console',
+ timestamp: data.timestamp || new Date().toISOString(),
+ data: data.data,
+ formatted: data.formatted || JSON.stringify(data.data, null, 2),
+ format: data.format || 'json',
+ workflow_id: data.workflow_id,
+ source_node_id: data.source_node_id,
+ source_node_type: data.source_node_type,
+ source_node_label: data.source_node_label
+ };
+ // Add to logs (newest first, limit to 100 entries)
+ setConsoleLogs(prev => {
+ const updated = [logEntry, ...prev];
+ return updated.slice(0, 100);
+ });
+ }
+ break;
+
+ case 'console_logs_cleared':
+ // Handle console logs cleared from server
+ if (message.workflow_id) {
+ setConsoleLogs(prev => prev.filter(log => log.workflow_id !== message.workflow_id));
+ } else {
+ setConsoleLogs([]);
+ }
+ break;
+
case 'workflow_lock':
// Handle workflow lock status updates (per-workflow locking - n8n pattern)
// Only update lock state if it's for the current workflow or if unlocking
@@ -879,6 +929,11 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
setLastWhatsAppMessage(null);
}, []);
+ // Clear console logs
+ const clearConsoleLogs = useCallback(() => {
+ setConsoleLogs([]);
+ }, []);
+
// 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
@@ -1570,6 +1625,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
whatsappMessages,
lastWhatsAppMessage,
apiKeyStatuses,
+ consoleLogs,
nodeStatuses,
nodeParameters,
variables,
@@ -1584,6 +1640,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
requestStatus,
clearNodeStatus,
clearWhatsAppMessages,
+ clearConsoleLogs,
// Generic request method
sendRequest,
diff --git a/client/src/nodeDefinitions/utilityNodes.ts b/client/src/nodeDefinitions/utilityNodes.ts
index 0335ebee..2b08d1e7 100644
--- a/client/src/nodeDefinitions/utilityNodes.ts
+++ b/client/src/nodeDefinitions/utilityNodes.ts
@@ -180,7 +180,72 @@ export const utilityNodes: Record<string, INodeTypeDescription> = {
]
}
]
+ },
+
+ console: {
+ displayName: 'Console',
+ name: 'console',
+ icon: '🖥️',
+ group: ['utility'],
+ version: 1,
+ description: 'Log data to console panel for debugging during execution',
+ defaults: { name: 'Console', color: '#8b5cf6' },
+ inputs: [{ name: 'main', displayName: 'Input', type: 'main' as NodeConnectionType, description: 'Data to log' }],
+ outputs: [{ name: 'main', displayName: 'Output', type: 'main' as NodeConnectionType, description: 'Passes input through unchanged' }],
+ properties: [
+ {
+ displayName: 'Label',
+ name: 'label',
+ type: 'string',
+ default: '',
+ placeholder: 'Debug Point 1',
+ description: 'Optional label to identify this log entry'
+ },
+ {
+ displayName: 'Log Mode',
+ name: 'logMode',
+ type: 'options',
+ default: 'all',
+ options: [
+ { name: 'Log All Input', value: 'all' },
+ { name: 'Log Specific Field', value: 'field' },
+ { name: 'Log Expression', value: 'expression' }
+ ],
+ description: 'What to log from the input data'
+ },
+ {
+ displayName: 'Field Path',
+ name: 'fieldPath',
+ type: 'string',
+ default: '',
+ placeholder: 'data.items[0].name',
+ displayOptions: { show: { logMode: ['field'] } },
+ description: 'Path to specific field to log (e.g., data.items[0].name)'
+ },
+ {
+ displayName: 'Expression',
+ name: 'expression',
+ type: 'string',
+ default: '',
+ placeholder: '{{input.field}}',
+ displayOptions: { show: { logMode: ['expression'] } },
+ description: 'Template expression to evaluate and log'
+ },
+ {
+ displayName: 'Format',
+ name: 'format',
+ type: 'options',
+ default: 'json',
+ options: [
+ { name: 'JSON (Pretty)', value: 'json' },
+ { name: 'JSON (Compact)', value: 'json_compact' },
+ { name: 'Text', value: 'text' },
+ { name: 'Table', value: 'table' }
+ ],
+ description: 'Output format for the log'
+ }
+ ]
}
};
-export const UTILITY_NODE_TYPES = ['httpRequest', 'webhookTrigger', 'webhookResponse'];
+export const UTILITY_NODE_TYPES = ['httpRequest', 'webhookTrigger', 'webhookResponse', 'console'];
diff --git a/client/src/nodeDefinitions/whatsappNodes.ts b/client/src/nodeDefinitions/whatsappNodes.ts
index 111c1157..ac4c2c35 100644
--- a/client/src/nodeDefinitions/whatsappNodes.ts
+++ b/client/src/nodeDefinitions/whatsappNodes.ts
@@ -709,13 +709,13 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {
// ===== MESSAGE TYPE FILTER =====
{
displayName: 'Message Type',
- name: 'textOnly',
+ name: 'messageFilter',
type: 'options',
options: [
- { name: 'All Types', value: 'false' },
- { name: 'Text Only', value: 'true' }
+ { name: 'All Types', value: 'all' },
+ { name: 'Text Only', value: 'text_only' }
],
- default: 'false',
+ default: 'all',
description: 'Filter by message type'
},
@@ -734,9 +734,10 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {
{
displayName: 'Message Position',
name: 'position',
- type: 'number',
- default: 1,
- description: 'Position: positive from newest (1=most recent), negative from oldest (-1=oldest)',
+ 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.',
displayOptions: {
show: { resultMode: ['single'] }
}
diff --git a/server/services/deployment/manager.py b/server/services/deployment/manager.py
index 88a895d9..f99d69c4 100644
--- a/server/services/deployment/manager.py
+++ b/server/services/deployment/manager.py
@@ -51,6 +51,7 @@ class DeploymentManager:
self._active_runs: Dict[str, Dict[str, asyncio.Task]] = {} # workflow_id -> {run_id: task}
self._run_counters: Dict[str, int] = {}
self._status_callbacks: Dict[str, Callable] = {}
+ self._cron_iterations: Dict[str, int] = {} # node_id -> iteration count
self._main_loop: Optional[asyncio.AbstractEventLoop] = None
self._settings = {
@@ -225,15 +226,30 @@ class DeploymentManager:
# Cleanup triggers for this workflow
listener_count = 0
cron_count = 0
+ cron_node_ids = []
if trigger_manager:
+ # Get cron node IDs before teardown (they'll be cleared)
+ cron_node_ids = trigger_manager.get_cron_node_ids()
listener_count = await trigger_manager.teardown_all_listeners()
cron_count = trigger_manager.teardown_all_crons()
+ # Reset cron trigger node statuses to idle
+ for node_id in cron_node_ids:
+ await self._broadcaster.update_node_status(node_id, "idle", {}, workflow_id=workflow_id)
+
+ # Reset listener node statuses to idle
+ for node_id in listener_nodes:
+ await self._broadcaster.update_node_status(node_id, "idle", {}, workflow_id=workflow_id)
+
# Cancel event waiters for nodes in this workflow
waiter_count = 0
for node in state.nodes:
waiter_count += event_waiter.cancel_for_node(node['id'])
+ # Clear cron iteration counters for this workflow's cron nodes
+ for node_id in cron_node_ids:
+ self._cron_iterations.pop(node_id, None)
+
# Clear state for this workflow
self._deployments.pop(workflow_id, None)
self._trigger_managers.pop(workflow_id, None)
@@ -314,13 +330,32 @@ class DeploymentManager:
cron_expr = TriggerManager.build_cron_expression(params)
timezone = params.get('timezone', 'UTC')
+ frequency = params.get('frequency', 'minutes')
+
+ # Initialize iteration counter for this cron node
+ self._cron_iterations[node_id] = 0
+
+ # Build schedule description for output
+ schedule_desc = self._get_schedule_description(params)
def on_tick():
if self._main_loop and self._main_loop.is_running():
+ # Increment iteration counter
+ self._cron_iterations[node_id] = self._cron_iterations.get(node_id, 0) + 1
+ iteration = self._cron_iterations[node_id]
+
trigger_data = {
'node_id': node_id,
'timestamp': datetime.now().isoformat(),
- 'trigger_type': 'cron'
+ 'trigger_type': 'cron',
+ 'event_data': {
+ 'timestamp': datetime.now().isoformat(),
+ 'iteration': iteration,
+ 'frequency': frequency,
+ 'timezone': timezone,
+ 'schedule': schedule_desc,
+ 'cron_expression': cron_expr
+ }
}
asyncio.run_coroutine_threadsafe(
self._spawn_run(node_id, trigger_data, workflow_id=workflow_id),
@@ -332,6 +367,15 @@ class DeploymentManager:
raise RuntimeError(f"No trigger manager for workflow {workflow_id}")
job_id = trigger_manager.setup_cron(node_id, cron_expr, timezone, on_tick)
+
+ # Broadcast waiting status for cron trigger (like event triggers do)
+ await self._broadcaster.update_node_status(node_id, "waiting", {
+ "message": f"Waiting for schedule: {cron_expr}",
+ "cron_expression": cron_expr,
+ "timezone": timezone,
+ "job_id": job_id
+ }, workflow_id=workflow_id)
+
return TriggerInfo(node_id, "cron", job_id=job_id)
async def _fire_start_trigger(self, node: Dict, workflow_id: str) -> TriggerInfo:
@@ -625,3 +669,36 @@ class DeploymentManager:
})
except Exception as e:
logger.warning("Status callback failed", workflow_id=workflow_id, error=str(e))
+
+ @staticmethod
+ def _get_schedule_description(params: Dict[str, Any]) -> str:
+ """Get human-readable schedule description from parameters."""
+ frequency = params.get('frequency', 'minutes')
+
+ match frequency:
+ case 'seconds':
+ interval = params.get('interval', 30)
+ return f"Every {interval} seconds"
+ case 'minutes':
+ interval = params.get('intervalMinutes', 5)
+ return f"Every {interval} minutes"
+ case 'hours':
+ interval = params.get('intervalHours', 1)
+ return f"Every {interval} hours"
+ case 'days':
+ time_str = params.get('dailyTime', '09:00')
+ return f"Daily at {time_str}"
+ case 'weeks':
+ weekday = params.get('weekday', '1')
+ time_str = params.get('weeklyTime', '09:00')
+ days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
+ day_name = days[int(weekday)] if str(weekday).isdigit() else weekday
+ return f"Weekly on {day_name} at {time_str}"
+ case 'months':
+ day = params.get('monthDay', '1')
+ time_str = params.get('monthlyTime', '09:00')
+ return f"Monthly on day {day} at {time_str}"
+ case 'once':
+ return "Once (no repeat)"
+ case _:
+ return "Unknown schedule"
diff --git a/server/services/deployment/triggers.py b/server/services/deployment/triggers.py
index a6ea763c..2369aa4d 100644
--- a/server/services/deployment/triggers.py
+++ b/server/services/deployment/triggers.py
@@ -64,6 +64,10 @@ class TriggerManager:
return True
return False
+ def get_cron_node_ids(self) -> list:
+ """Get node IDs of active cron triggers."""
+ return list(self._active_cron_jobs.keys())
+
def teardown_all_crons(self) -> int:
"""Remove all cron triggers."""
count = 0
diff --git a/server/services/handlers/__init__.py b/server/services/handlers/__init__.py
index e54b6d2b..694e100e 100644
--- a/server/services/handlers/__init__.py
+++ b/server/services/handlers/__init__.py
@@ -53,6 +53,7 @@ from .utility import (
handle_start,
handle_cron_scheduler,
handle_timer,
+ handle_console,
)
# WhatsApp handlers
@@ -94,6 +95,7 @@ __all__ = [
'handle_start',
'handle_cron_scheduler',
'handle_timer',
+ 'handle_console',
# WhatsApp
'handle_whatsapp_send',
'handle_whatsapp_connect',
diff --git a/server/services/handlers/utility.py b/server/services/handlers/utility.py
index 381b783a..cb68d57a 100644
--- a/server/services/handlers/utility.py
+++ b/server/services/handlers/utility.py
@@ -591,3 +591,232 @@ async def handle_timer(
"execution_time": time.time() - start_time,
"timestamp": datetime.now().isoformat()
}
+
+
+# =============================================================================
+# CONSOLE HANDLER
+# =============================================================================
+
+async def handle_console(
+ node_id: str,
+ node_type: str,
+ parameters: Dict[str, Any],
+ context: Dict[str, Any],
+ connected_outputs: Dict[str, Any] = None,
+ source_nodes: list = None
+) -> Dict[str, Any]:
+ """Handle console node execution - logs input data for debugging.
+
+ The console node:
+ 1. Receives input data from connected upstream nodes (via _get_connected_outputs_with_info)
+ 2. Logs the data to the console panel based on log mode
+ 3. Passes the input through unchanged to downstream nodes
+
+ Args:
+ node_id: The node ID
+ node_type: The node type (console)
+ parameters: Resolved parameters including label, logMode, format
+ context: Execution context
+ connected_outputs: Outputs from connected upstream nodes (keyed by node type)
+ source_nodes: List of source node info dicts with id, type, label
+
+ Returns:
+ Execution result dict with logged data and passthrough output
+ """
+ from services.status_broadcaster import get_status_broadcaster
+ start_time = time.time()
+
+ try:
+ label = parameters.get('label', '')
+ log_mode = parameters.get('logMode', 'all')
+ format_type = parameters.get('format', 'json')
+ field_path = parameters.get('fieldPath', '')
+ expression = parameters.get('expression', '')
+
+ # Get input data from connected outputs (passed from _get_connected_outputs_with_info)
+ connected_outputs = connected_outputs or {}
+ source_nodes = source_nodes or []
+
+ logger.debug(f"[Console] connected_outputs keys: {list(connected_outputs.keys())}, count: {len(connected_outputs)}")
+
+ # Merge all connected outputs into a single dict
+ input_data = {}
+ for node_type, output in connected_outputs.items():
+ logger.debug(f"[Console] Processing output from {node_type}: type={type(output).__name__}")
+ if isinstance(output, dict):
+ input_data.update(output)
+ else:
+ input_data['value'] = output
+
+ logger.debug(f"[Console] input_data keys: {list(input_data.keys()) if input_data else 'empty'}")
+
+ # Get first source node info for display
+ source_info = source_nodes[0] if source_nodes else None
+
+ # Determine what to log based on mode
+ logger.debug(f"[Console] log_mode={log_mode}, field_path={field_path[:50] if field_path else 'none'}...")
+ log_value = None
+ match log_mode:
+ case 'all':
+ log_value = input_data
+ case 'field':
+ if field_path:
+ # Check if fieldPath was a template that got resolved (no longer contains {{}})
+ # If it was resolved, use the resolved value directly
+ if '{{' not in field_path and field_path not in input_data:
+ # fieldPath was likely a template like {{aiagent.response}} that got resolved
+ # Use the resolved value directly instead of navigating
+ log_value = field_path
+ logger.debug(f"[Console] Using resolved fieldPath value directly")
+ else:
+ # fieldPath is a literal path like "response" or "data.items[0]"
+ log_value = _navigate_field_path(input_data, field_path)
+ else:
+ log_value = input_data
+ case 'expression':
+ # Expression is already resolved by parameter resolver
+ log_value = expression if expression else input_data
+ case _:
+ log_value = input_data
+
+ # Format the output
+ formatted_output = _format_console_output(log_value, format_type)
+
+ # Get workflow_id for scoped broadcasting
+ workflow_id = context.get('workflow_id')
+
+ # Broadcast console log to frontend
+ broadcaster = get_status_broadcaster()
+ await broadcaster.broadcast_console_log({
+ "node_id": node_id,
+ "label": label or f"Console ({node_id[:8]})",
+ "timestamp": datetime.now().isoformat(),
+ "data": log_value,
+ "formatted": formatted_output,
+ "format": format_type,
+ "workflow_id": workflow_id,
+ "source_node_id": source_info.get('id') if source_info else None,
+ "source_node_type": source_info.get('type') if source_info else None,
+ "source_node_label": source_info.get('label') if source_info else None
+ })
+
+ logger.info("[Console] Logged",
+ node_id=node_id,
+ label=label,
+ format=format_type,
+ data_type=type(log_value).__name__)
+
+ # Return success with the logged data AND pass input through as output
+ return {
+ "success": True,
+ "node_id": node_id,
+ "node_type": "console",
+ "result": {
+ "label": label or f"Console ({node_id[:8]})",
+ "logged_at": datetime.now().isoformat(),
+ "format": format_type,
+ "data": log_value,
+ "formatted": formatted_output,
+ # Pass through original input for downstream nodes
+ **input_data
+ },
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
+ except Exception as e:
+ logger.error("[Console] Failed", node_id=node_id, error=str(e))
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": "console",
+ "error": str(e),
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
+
+def _navigate_field_path(data: Any, path: str) -> Any:
+ """Navigate through nested dict/list using dot notation path.
+
+ Supports:
+ - Dict keys: 'field' -> data['field']
+ - Array indexing: 'items[0]' -> data['items'][0]
+ - Nested paths: 'data.items[0].name' -> data['data']['items'][0]['name']
+ """
+ import re
+
+ if not path:
+ return data
+
+ current = data
+ parts = path.split('.')
+
+ for part in parts:
+ if current is None:
+ return None
+
+ # Check for array index notation: field[index]
+ bracket_match = re.match(r'^(\w+)\[(\d+)\]$', part)
+ if bracket_match:
+ field_name = bracket_match.group(1)
+ index = int(bracket_match.group(2))
+
+ # Navigate to the field first
+ if isinstance(current, dict) and field_name in current:
+ current = current[field_name]
+ else:
+ return None
+
+ # Then access the array index
+ if isinstance(current, list) and 0 <= index < len(current):
+ current = current[index]
+ else:
+ return None
+ else:
+ # Standard dict key navigation
+ if isinstance(current, dict) and part in current:
+ current = current[part]
+ else:
+ return None
+
+ return current
+
+
+def _format_console_output(data: Any, format_type: str) -> str:
+ """Format data for console display based on format type."""
+ match format_type:
+ case 'json':
+ try:
+ return json.dumps(data, indent=2, default=str, ensure_ascii=False)
+ except Exception:
+ return str(data)
+ case 'json_compact':
+ try:
+ return json.dumps(data, default=str, ensure_ascii=False)
+ except Exception:
+ return str(data)
+ case 'text':
+ return str(data)
+ case 'table':
+ # Format as table if data is list of dicts
+ if isinstance(data, list) and data and isinstance(data[0], dict):
+ headers = list(data[0].keys())
+ rows = [[str(row.get(h, '')) for h in headers] for row in data]
+
+ # Calculate column widths
+ widths = [max(len(h), max((len(r[i]) for r in rows), default=0))
+ for i, h in enumerate(headers)]
+
+ # Build table string
+ header_line = ' | '.join(h.ljust(widths[i]) for i, h in enumerate(headers))
+ separator = '-+-'.join('-' * w for w in widths)
+ data_lines = [' | '.join(r[i].ljust(widths[i]) for i in range(len(headers)))
+ for r in rows]
+
+ return '\n'.join([header_line, separator] + data_lines)
+ else:
+ # Fall back to JSON for non-tabular data
+ return json.dumps(data, indent=2, default=str, ensure_ascii=False)
+ case _:
+ return str(data)
diff --git a/server/services/handlers/whatsapp.py b/server/services/handlers/whatsapp.py
index 012551f1..d61bea62 100644
--- a/server/services/handlers/whatsapp.py
+++ b/server/services/handlers/whatsapp.py
@@ -228,7 +228,12 @@ async def handle_whatsapp_chat_history(
# Result mode and pagination
result_mode = parameters.get('resultMode', 'multiple')
- position = parameters.get('position', 1)
+ 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
diff --git a/server/services/node_executor.py b/server/services/node_executor.py
index 8f2ce475..961979ab 100644
--- a/server/services/node_executor.py
+++ b/server/services/node_executor.py
@@ -30,7 +30,7 @@ from services.handlers import (
handle_create_map, handle_add_locations, handle_nearby_places,
handle_text_generator, handle_file_handler,
handle_chat_send, handle_chat_history,
- handle_start, handle_cron_scheduler, handle_timer,
+ handle_start, handle_cron_scheduler, handle_timer, handle_console,
handle_whatsapp_send, handle_whatsapp_connect, handle_whatsapp_chat_history,
)
@@ -123,6 +123,7 @@ class NodeExecutor:
'httpRequest': handle_http_request,
# Android setup
'androidDeviceSetup': partial(handle_android_device_setup, settings=self.settings),
+ # Note: 'console' handled in _dispatch with connected_outputs
}
# Register AI chat models
@@ -246,8 +247,10 @@ class NodeExecutor:
return await handler(node_id, node_type, params, context)
# Special handlers needing connected outputs
- if node_type in ('pythonExecutor', 'javascriptExecutor', 'webhookResponse'):
- outputs = await self._get_connected_outputs(context, node_id)
+ if node_type in ('pythonExecutor', 'javascriptExecutor', 'webhookResponse', 'console'):
+ outputs, source_nodes = await self._get_connected_outputs_with_info(context, node_id)
+ if node_type == 'console':
+ return await handle_console(node_id, node_type, params, context, outputs, source_nodes)
handlers = {
'pythonExecutor': handle_python_executor,
'javascriptExecutor': handle_javascript_executor,
@@ -289,3 +292,69 @@ class NodeExecutor:
result[source.get('type', 'unknown')] = output
return result
+
+ def _get_source_nodes_info(self, context: Dict, node_id: str) -> list:
+ """Get source node info (id, type, label) for edges targeting this node.
+
+ This is used for display purposes (e.g., showing source in Console panel).
+ Does NOT filter by output availability - just returns edge source info.
+ """
+ nodes = context.get('nodes', [])
+ edges = context.get('edges', [])
+ source_nodes = []
+
+ for edge in edges:
+ if edge.get('target') == node_id:
+ source_id = edge.get('source')
+ source = next((n for n in nodes if n.get('id') == source_id), {})
+ source_type = source.get('type', 'unknown')
+ source_data = source.get('data', {})
+ source_label = source_data.get('label') or source_type
+ source_nodes.append({
+ 'id': source_id,
+ 'type': source_type,
+ 'label': source_label
+ })
+
+ return source_nodes
+
+ async def _get_connected_outputs_with_info(self, context: Dict, node_id: str) -> tuple:
+ """Get outputs from connected upstream nodes with source node info.
+
+ Returns:
+ Tuple of (outputs dict, source_nodes list with id/type/label info)
+ """
+ get_output = context.get('get_output_fn')
+ if not get_output:
+ logger.warning(f"[_get_connected_outputs_with_info] No get_output_fn in context for {node_id}")
+ return {}, []
+
+ nodes = context.get('nodes', [])
+ edges = context.get('edges', [])
+ session_id = context.get('session_id', 'default')
+ outputs = {}
+ source_nodes = []
+
+ logger.debug(f"[_get_connected_outputs_with_info] node_id={node_id}, edges={len(edges)}, session={session_id}")
+
+ for edge in edges:
+ if edge.get('target') == node_id:
+ source_id = edge.get('source')
+ logger.debug(f"[_get_connected_outputs_with_info] Found edge from {source_id} to {node_id}")
+ output = await get_output(session_id, source_id, "output_0")
+ logger.debug(f"[_get_connected_outputs_with_info] Output from {source_id}: {'FOUND' if output else 'NOT FOUND'}")
+ if output:
+ source = next((n for n in nodes if n.get('id') == source_id), {})
+ source_type = source.get('type', 'unknown')
+ outputs[source_type] = output
+ # Get label from node data if available
+ source_data = source.get('data', {})
+ source_label = source_data.get('label') or source_type
+ source_nodes.append({
+ 'id': source_id,
+ 'type': source_type,
+ 'label': source_label
+ })
+
+ logger.debug(f"[_get_connected_outputs_with_info] Returning {len(outputs)} outputs, {len(source_nodes)} source_nodes")
+ return outputs, source_nodes
diff --git a/server/services/parameter_resolver.py b/server/services/parameter_resolver.py
index 2b3abd2a..3db6eb44 100644
--- a/server/services/parameter_resolver.py
+++ b/server/services/parameter_resolver.py
@@ -61,7 +61,7 @@ class ParameterResolver:
"""
connected = {}
- logger.debug(f"[ParameterResolver] Gathering outputs for node {node_id}, total nodes in workflow: {len(nodes)}")
+ logger.debug(f"[ParameterResolver] Gathering outputs for node {node_id}, session_id={session_id}, total nodes: {len(nodes)}")
# Gather outputs from ALL nodes (not just directly connected)
# This allows {{nodeName.field}} to reference any previously executed node
@@ -71,17 +71,21 @@ class ParameterResolver:
continue # Skip self
node_type = source_node.get('type', '')
+ node_label = source_node.get('data', {}).get('label', 'NO_LABEL')
node_key = self._get_template_key(source_node)
+ logger.debug(f"[ParameterResolver] Processing node: id={source_id}, type={node_type}, label={node_label}, key={node_key}")
+
# Special handling for start nodes
if node_type == 'start':
data = await self._get_start_node_data(source_id)
else:
data = await self.get_output(session_id, source_id, "output_0")
+ logger.debug(f"[ParameterResolver] Output lookup: session={session_id}, node={source_id}, result={'FOUND' if data else 'NOT_FOUND'}")
if data:
connected[node_key] = data
- logger.debug(f"[ParameterResolver] Found output for {node_key} (type={node_type}): keys={list(data.keys()) if isinstance(data, dict) else type(data)}")
+ logger.debug(f"[ParameterResolver] Stored output for key '{node_key}' (type={node_type}): keys={list(data.keys()) if isinstance(data, dict) else type(data)}")
logger.debug(f"[ParameterResolver] Available data keys for resolution: {list(connected.keys())}")
return connected
@@ -176,10 +180,39 @@ class ParameterResolver:
return result
def _navigate_path(self, data: Any, path: List[str]) -> Any:
- """Navigate through nested dict using path parts."""
+ """Navigate through nested dict/list using path parts.
+
+ Supports:
+ - Dict keys: 'field' -> data['field']
+ - Array indexing: 'items[0]' -> data['items'][0]
+ - Nested paths: 'messages[0].text' -> data['messages'][0]['text']
+ """
current = data
for part in path:
- if not isinstance(current, dict) or part not in current:
+ if current is None:
return None
- current = current[part]
+
+ # Check for array index notation: field[index]
+ bracket_match = re.match(r'^(\w+)\[(\d+)\]$', part)
+ if bracket_match:
+ field_name = bracket_match.group(1)
+ index = int(bracket_match.group(2))
+
+ # Navigate to the field first
+ if isinstance(current, dict) and field_name in current:
+ current = current[field_name]
+ else:
+ return None
+
+ # Then access the array index
+ if isinstance(current, list) and 0 <= index < len(current):
+ current = current[index]
+ else:
+ return None
+ else:
+ # Standard dict key navigation
+ if not isinstance(current, dict) or part not in current:
+ return None
+ current = current[part]
+
return current
diff --git a/server/services/status_broadcaster.py b/server/services/status_broadcaster.py
index d916f202..aa4156bc 100644
--- a/server/services/status_broadcaster.py
+++ b/server/services/status_broadcaster.py
@@ -635,6 +635,73 @@ class StatusBroadcaster:
if lock.get("locked")
}
+ # =========================================================================
+ # Console Log Updates
+ # =========================================================================
+
+ async def broadcast_console_log(self, log_data: Dict[str, Any]):
+ """Broadcast a console log entry to all connected clients.
+
+ Used by Console nodes to send debug output to the frontend console panel.
+
+ Args:
+ log_data: Dict containing:
+ - node_id: The console node ID
+ - label: User-defined label or default
+ - timestamp: ISO timestamp
+ - data: The logged data (any type)
+ - formatted: Pre-formatted string representation
+ - format: Format type (json, json_compact, text, table)
+ - workflow_id: Optional workflow ID for scoping
+ """
+ # Initialize console logs if not present
+ if "console_logs" not in self._status:
+ self._status["console_logs"] = []
+
+ # Add to console log history (keep last 100 entries)
+ self._status["console_logs"].append(log_data)
+ if len(self._status["console_logs"]) > 100:
+ self._status["console_logs"] = self._status["console_logs"][-100:]
+
+ # Broadcast to all clients
+ await self.broadcast({
+ "type": "console_log",
+ "data": log_data
+ })
+
+ logger.debug(f"[StatusBroadcaster] Console log broadcast: label={log_data.get('label')}")
+
+ def get_console_logs(self, workflow_id: Optional[str] = None) -> List[Dict[str, Any]]:
+ """Get console log history, optionally filtered by workflow_id."""
+ if "console_logs" not in self._status:
+ return []
+
+ if workflow_id:
+ return [
+ log for log in self._status["console_logs"]
+ if log.get("workflow_id") == workflow_id
+ ]
+ return list(self._status["console_logs"])
+
+ async def clear_console_logs(self, workflow_id: Optional[str] = None):
+ """Clear console log history."""
+ if "console_logs" not in self._status:
+ self._status["console_logs"] = []
+ return
+
+ if workflow_id:
+ self._status["console_logs"] = [
+ log for log in self._status["console_logs"]
+ if log.get("workflow_id") != workflow_id
+ ]
+ else:
+ self._status["console_logs"] = []
+
+ await self.broadcast({
+ "type": "console_logs_cleared",
+ "workflow_id": workflow_id
+ })
+
# =========================================================================
# Generic Updates
# =========================================================================