Skip to content

Self-improving AI Employees for everyone

Add Tool Calling Functionality for the android nodes.

trohitgc118519576c5
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsx
index 7661dee4..e954be23 100644
--- a/client/src/Dashboard.tsx
+++ b/client/src/Dashboard.tsx
@@ -17,6 +17,7 @@ import AIAgentNode from './components/AIAgentNode';
import ModelNode from './components/ModelNode';
import SquareNode from './components/SquareNode';
import TriggerNode from './components/TriggerNode';
+import ToolkitNode from './components/ToolkitNode';
import ConditionalEdge from './components/ConditionalEdge';
import NodeContextMenu from './components/ui/NodeContextMenu';
import { nodeDefinitions } from './nodeDefinitions';
@@ -96,8 +97,13 @@ const createNodeTypes = (): Record<string, React.ComponentType<any>> => {
// Note: webhookTrigger is already handled as trigger above
types[type] = SquareNode;
} else if (TOOL_NODE_TYPES.includes(type)) {
- // Tool nodes (Calculator, etc.) use circular ModelNode like Simple Memory
- types[type] = ModelNode;
+ // Most tool nodes use circular ModelNode
+ // Exception: androidTool uses ToolkitNode with top/bottom handles
+ if (type === 'androidTool') {
+ types[type] = ToolkitNode;
+ } else {
+ types[type] = ModelNode;
+ }
} else if (definition?.group?.includes('model')) {
// Fallback for other model nodes
types[type] = ModelNode;
@@ -588,6 +594,23 @@ const DashboardContent: React.FC = () => {
try {
// Settings are already synced to backend via WebSocket from SettingsPanel
// Backend will use the stored settings
+
+ // DEBUG: Log edges being sent to deployment
+ console.log('[Dashboard] Deploying with edges:', {
+ edgeCount: edges.length,
+ edges: edges.map(e => ({
+ id: e.id,
+ source: e.source,
+ target: e.target,
+ sourceHandle: e.sourceHandle,
+ targetHandle: e.targetHandle
+ })),
+ // Check for toolkit connections specifically
+ toolkitEdges: edges.filter(e =>
+ e.target?.includes('androidTool') || e.source?.includes('androidTool')
+ )
+ });
+
const result = await deployWorkflow(currentWorkflow.id, nodes, edges, 'default');
if (!result.success) {
@@ -705,6 +728,12 @@ const DashboardContent: React.FC = () => {
// and when backend executes nodes (NodeExecutor._prepare_parameters)
useEffect(() => {
if (currentWorkflow && currentWorkflow.id) {
+ console.log('[Dashboard] Sync Store -> ReactFlow', {
+ workflowId: currentWorkflow.id,
+ storeEdgeCount: (currentWorkflow.edges || []).length,
+ storeEdges: (currentWorkflow.edges || []).map(e => ({ id: e.id, source: e.source, target: e.target })),
+ lastModified: currentWorkflow.lastModified
+ });
const workflowNodes = currentWorkflow.nodes || [];
setNodes(workflowNodes);
setEdges(currentWorkflow.edges || []);
@@ -717,22 +746,27 @@ const DashboardContent: React.FC = () => {
// Sync ReactFlow state → workflow state (debounced for performance)
useEffect(() => {
if (!currentWorkflow || !currentWorkflow.id) return;
-
+
const timeoutId = setTimeout(() => {
try {
const currentNodesStr = JSON.stringify(sanitizeNodesForComparison(nodes));
const currentEdgesStr = JSON.stringify(sanitizeEdgesForComparison(edges));
const workflowNodesStr = JSON.stringify(sanitizeNodesForComparison(currentWorkflow.nodes || []));
const workflowEdgesStr = JSON.stringify(sanitizeEdgesForComparison(currentWorkflow.edges || []));
-
+
if (currentNodesStr !== workflowNodesStr || currentEdgesStr !== workflowEdgesStr) {
+ console.log('[Dashboard] Syncing ReactFlow -> Store', {
+ reactFlowEdgeCount: edges.length,
+ storeEdgeCount: (currentWorkflow.edges || []).length,
+ newEdges: edges.filter(e => !(currentWorkflow.edges || []).find(we => we.id === e.id))
+ });
updateWorkflow({ nodes, edges });
}
} catch (error) {
console.warn('Failed to sync workflow state:', error);
}
}, theme.constants.debounceDelay.workflowUpdate);
-
+
return () => clearTimeout(timeoutId);
}, [nodes, edges, currentWorkflow?.id, updateWorkflow]);
diff --git a/client/src/components/SquareNode.tsx b/client/src/components/SquareNode.tsx
index 0af1657c..9a4850a4 100644
--- a/client/src/components/SquareNode.tsx
+++ b/client/src/components/SquareNode.tsx
@@ -14,6 +14,9 @@ import { PlayCircleFilled, ScheduleOutlined } from '@ant-design/icons';
// All Android node types combined
const ALL_ANDROID_NODE_TYPES = [...ANDROID_SERVICE_NODE_TYPES, ...ANDROID_DEVICE_NODE_TYPES];
+// Android service nodes that can connect to Android Toolkit as tools
+const ANDROID_TOOL_CAPABLE_NODES = ANDROID_SERVICE_NODE_TYPES;
+
// Google Maps node types
const GOOGLE_MAPS_NODE_TYPES = ['createMap', 'addLocations', 'showNearbyPlaces'];
@@ -59,6 +62,9 @@ const SquareNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectab
// Check if this is an Android node
const isAndroidNode = type ? ALL_ANDROID_NODE_TYPES.includes(type) : false;
+ // Check if this node can be used as a tool (connects to Android Toolkit)
+ const isToolCapable = type ? ANDROID_TOOL_CAPABLE_NODES.includes(type) : false;
+
// Android connection status from WebSocket (real-time updates)
// Service nodes need a paired device to execute, not just relay connection
const isAndroidConnected = isAndroidNode && androidStatus.paired;
@@ -566,6 +572,36 @@ const SquareNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectab
</div>
)}
+ {/* Animated Border - shows when tool-capable node is being executed via toolkit */}
+ {isExecuting && isToolCapable && (
+ <div
+ style={{
+ position: 'absolute',
+ top: -3,
+ left: -3,
+ right: -3,
+ bottom: -3,
+ borderRadius: `calc(${theme.borderRadius.lg} + 1px)`,
+ border: `2px solid ${theme.dracula.purple}`,
+ animation: 'toolPulse 0.8s ease-in-out infinite',
+ zIndex: 50,
+ pointerEvents: 'none',
+ }}
+ />
+ )}
+ <style>{`
+ @keyframes toolPulse {
+ 0%, 100% {
+ border-color: ${theme.dracula.cyan};
+ box-shadow: 0 0 8px ${theme.dracula.cyan}80, inset 0 0 4px ${theme.dracula.cyan}40;
+ }
+ 50% {
+ border-color: ${theme.dracula.purple};
+ box-shadow: 0 0 12px ${theme.dracula.purple}80, inset 0 0 6px ${theme.dracula.purple}40;
+ }
+ }
+ `}</style>
+
{/* Service Icon */}
{getServiceIcon()}
@@ -665,6 +701,29 @@ const SquareNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectab
title="Service Output"
/>
+ {/* Top Tool Output Handle - only for Android service nodes that can connect to Toolkit */}
+ {isToolCapable && (
+ <Handle
+ id="output-tool"
+ type="source"
+ position={Position.Top}
+ isConnectable={isConnectable}
+ style={{
+ position: 'absolute',
+ top: '-6px',
+ left: '50%',
+ transform: 'translateX(-50%)',
+ width: theme.nodeSize.handle,
+ height: theme.nodeSize.handle,
+ backgroundColor: '#3DDC84', // Android green to match Toolkit
+ border: `2px solid ${theme.isDarkMode ? theme.colors.background : '#ffffff'}`,
+ borderRadius: '50%',
+ zIndex: 20
+ }}
+ title="Connect to Android Toolkit"
+ />
+ )}
+
{/* Output Data Indicator - shows when node has execution output */}
{executionStatus === 'success' && nodeStatus?.data && (
<div
diff --git a/client/src/components/ToolkitNode.tsx b/client/src/components/ToolkitNode.tsx
new file mode 100644
index 00000000..db1c649b
--- /dev/null
+++ b/client/src/components/ToolkitNode.tsx
@@ -0,0 +1,326 @@
+/**
+ * ToolkitNode - A node component with top/bottom connectors for aggregating services.
+ * Used by Android Toolkit to receive Android service nodes from bottom and output to AI Agent from top.
+ *
+ * Based on SquareNode but with vertical handle layout:
+ * - Input handle at BOTTOM (receives from Android service nodes)
+ * - Output handle at TOP (connects to AI Agent's input-tools)
+ */
+
+import React, { useState, useEffect, useRef, useCallback } from 'react';
+import { Handle, Position, NodeProps } from 'reactflow';
+import { NodeData } from '../types/NodeTypes';
+import { useAppStore } from '../store/useAppStore';
+import { nodeDefinitions } from '../nodeDefinitions';
+import { useAppTheme } from '../hooks/useAppTheme';
+import { useWebSocket } from '../contexts/WebSocketContext';
+
+const ToolkitNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectable, selected }) => {
+ const theme = useAppTheme();
+ const { setSelectedNode, renamingNodeId, setRenamingNodeId, updateNodeData } = useAppStore();
+
+ // Inline rename state
+ const [isRenaming, setIsRenaming] = useState(false);
+ const [editLabel, setEditLabel] = useState('');
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ // Get node status from WebSocket context
+ const { getNodeStatus } = useWebSocket();
+ const nodeStatus = getNodeStatus(id);
+ const executionStatus = nodeStatus?.status || 'idle';
+
+ const definition = nodeDefinitions[type as keyof typeof nodeDefinitions];
+
+ // Execution state
+ const isExecuting = executionStatus === 'executing' || executionStatus === 'waiting';
+
+ // Sync with global renaming state
+ useEffect(() => {
+ if (renamingNodeId === id) {
+ setIsRenaming(true);
+ setEditLabel(data?.label || definition?.displayName || type || '');
+ } else {
+ setIsRenaming(false);
+ }
+ }, [renamingNodeId, id, data?.label, definition?.displayName, type]);
+
+ // Focus and select input when entering rename mode
+ useEffect(() => {
+ if (isRenaming && inputRef.current) {
+ inputRef.current.focus();
+ inputRef.current.select();
+ }
+ }, [isRenaming]);
+
+ // Handle save rename
+ const handleSaveRename = useCallback(() => {
+ const newLabel = editLabel.trim();
+ const originalLabel = data?.label || definition?.displayName || type || '';
+
+ if (newLabel && newLabel !== originalLabel) {
+ updateNodeData(id, { ...data, label: newLabel });
+ }
+
+ setIsRenaming(false);
+ setRenamingNodeId(null);
+ }, [editLabel, data, definition?.displayName, type, id, updateNodeData, setRenamingNodeId]);
+
+ // Handle cancel rename
+ const handleCancelRename = useCallback(() => {
+ setIsRenaming(false);
+ setRenamingNodeId(null);
+ }, [setRenamingNodeId]);
+
+ // Handle double-click to rename
+ const handleLabelDoubleClick = useCallback(() => {
+ setRenamingNodeId(id);
+ }, [id, setRenamingNodeId]);
+
+ // Handle parameters click
+ const handleParametersClick = (e: React.MouseEvent) => {
+ e.stopPropagation();
+ setSelectedNode({ id, type, data, position: { x: 0, y: 0 } });
+ };
+
+ // Get the node color from definition or use Android green
+ const nodeColor = definition?.defaults?.color || '#3DDC84';
+
+ // Get icon from definition
+ const getIcon = () => {
+ if (definition?.icon) {
+ return definition.icon;
+ }
+ return '📱'; // Default Android icon
+ };
+
+ // Get status indicator color
+ const getStatusIndicatorColor = () => {
+ if (isExecuting) return theme.dracula.cyan;
+ if (executionStatus === 'success') return theme.dracula.green;
+ if (executionStatus === 'error') return theme.dracula.red;
+ return theme.dracula.green; // Toolkit is always ready
+ };
+
+ return (
+ <div
+ style={{
+ position: 'relative',
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ fontFamily: 'system-ui, -apple-system, sans-serif',
+ fontSize: '11px',
+ cursor: 'pointer',
+ }}
+ >
+ {/* Main Square Node */}
+ <div
+ style={{
+ position: 'relative',
+ width: theme.nodeSize.square,
+ height: theme.nodeSize.square,
+ borderRadius: theme.borderRadius.lg,
+ background: theme.isDarkMode
+ ? `linear-gradient(135deg, ${nodeColor}25 0%, ${theme.colors.background} 100%)`
+ : `linear-gradient(145deg, #ffffff 0%, ${nodeColor}08 100%)`,
+ border: `2px solid ${isExecuting
+ ? (theme.isDarkMode ? theme.dracula.cyan : '#2563eb')
+ : selected
+ ? theme.colors.focus
+ : theme.isDarkMode ? nodeColor + '80' : `${nodeColor}40`}`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ color: theme.colors.text,
+ fontSize: theme.nodeSize.squareIcon,
+ fontWeight: '600',
+ transition: 'all 0.2s ease',
+ boxShadow: isExecuting
+ ? theme.isDarkMode
+ ? `0 4px 12px ${theme.dracula.cyan}66, 0 0 0 3px ${theme.dracula.cyan}4D`
+ : `0 0 0 3px rgba(37, 99, 235, 0.5), 0 4px 16px rgba(37, 99, 235, 0.35)`
+ : selected
+ ? `0 4px 12px ${theme.colors.focusRing}, 0 0 0 1px ${theme.colors.focusRing}`
+ : theme.isDarkMode
+ ? `0 2px 8px ${nodeColor}40`
+ : `0 2px 8px ${nodeColor}20, 0 4px 12px rgba(0,0,0,0.06)`,
+ animation: isExecuting ? 'pulse 1.5s ease-in-out infinite' : 'none',
+ }}
+ >
+ {/* Service Icon */}
+ {getIcon()}
+
+ {/* Parameters Button */}
+ <button
+ onClick={handleParametersClick}
+ style={{
+ position: 'absolute',
+ top: '-8px',
+ right: '-8px',
+ width: theme.nodeSize.paramButton,
+ height: theme.nodeSize.paramButton,
+ borderRadius: theme.borderRadius.sm,
+ backgroundColor: theme.isDarkMode ? theme.colors.backgroundAlt : '#ffffff',
+ border: `1px solid ${theme.isDarkMode ? theme.colors.border : '#d1d5db'}`,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ fontSize: theme.fontSize.xs,
+ color: theme.colors.textSecondary,
+ fontWeight: '400',
+ transition: theme.transitions.fast,
+ zIndex: 30,
+ boxShadow: theme.isDarkMode
+ ? `0 1px 3px ${theme.colors.shadow}`
+ : '0 1px 4px rgba(0,0,0,0.1)'
+ }}
+ title="Edit Toolkit Parameters"
+ >
+ ⚙️
+ </button>
+
+ {/* Status Indicator */}
+ <div
+ style={{
+ position: 'absolute',
+ top: '-4px',
+ left: '-4px',
+ width: theme.nodeSize.statusIndicator,
+ height: theme.nodeSize.statusIndicator,
+ borderRadius: '50%',
+ backgroundColor: getStatusIndicatorColor(),
+ border: `2px solid ${theme.isDarkMode ? theme.colors.background : '#ffffff'}`,
+ boxShadow: isExecuting
+ ? theme.isDarkMode
+ ? `0 0 6px ${theme.dracula.cyan}80`
+ : '0 0 4px rgba(37, 99, 235, 0.5)'
+ : theme.isDarkMode
+ ? `0 1px 2px ${theme.colors.shadow}`
+ : '0 1px 3px rgba(0,0,0,0.15)',
+ zIndex: 30,
+ animation: isExecuting ? 'pulse 1s ease-in-out infinite' : 'none',
+ }}
+ title={isExecuting ? 'Executing...' : 'Toolkit ready'}
+ />
+
+ {/* TOP Output Handle - connects to AI Agent */}
+ <Handle
+ id="output-main"
+ type="source"
+ position={Position.Top}
+ isConnectable={isConnectable}
+ style={{
+ position: 'absolute',
+ top: '-6px',
+ left: '50%',
+ transform: 'translateX(-50%)',
+ width: theme.nodeSize.handle,
+ height: theme.nodeSize.handle,
+ backgroundColor: nodeColor,
+ border: `2px solid ${theme.isDarkMode ? theme.colors.background : '#ffffff'}`,
+ borderRadius: '50%',
+ zIndex: 20
+ }}
+ title="Connect to AI Agent's tool input"
+ />
+
+ {/* BOTTOM Input Handle - receives from Android nodes */}
+ <Handle
+ id="input-main"
+ type="target"
+ position={Position.Bottom}
+ isConnectable={isConnectable}
+ style={{
+ position: 'absolute',
+ bottom: '-6px',
+ left: '50%',
+ transform: 'translateX(-50%)',
+ width: theme.nodeSize.handle,
+ height: theme.nodeSize.handle,
+ backgroundColor: theme.isDarkMode ? theme.colors.background : '#ffffff',
+ border: `2px solid ${theme.isDarkMode ? theme.colors.textSecondary : '#6b7280'}`,
+ borderRadius: '50%',
+ zIndex: 20
+ }}
+ title="Connect Android service nodes here"
+ />
+
+ {/* Output Data Indicator */}
+ {executionStatus === 'success' && nodeStatus?.data && (
+ <div
+ style={{
+ position: 'absolute',
+ bottom: '-4px',
+ right: '-4px',
+ width: theme.nodeSize.outputBadge,
+ height: theme.nodeSize.outputBadge,
+ borderRadius: theme.borderRadius.sm,
+ backgroundColor: theme.dracula.green,
+ border: `1px solid ${theme.isDarkMode ? theme.colors.background : '#ffffff'}`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ fontSize: theme.fontSize.xs,
+ color: 'white',
+ fontWeight: 'bold',
+ zIndex: 30,
+ boxShadow: theme.isDarkMode
+ ? '0 1px 3px rgba(0,0,0,0.2)'
+ : '0 1px 3px rgba(0,0,0,0.15)',
+ }}
+ title="Output data available"
+ >
+ <span style={{ lineHeight: 1 }}>D</span>
+ </div>
+ )}
+ </div>
+
+ {/* Node Name Below */}
+ {isRenaming ? (
+ <input
+ ref={inputRef}
+ type="text"
+ value={editLabel}
+ onChange={(e) => setEditLabel(e.target.value)}
+ onBlur={handleSaveRename}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') handleSaveRename();
+ if (e.key === 'Escape') handleCancelRename();
+ }}
+ style={{
+ marginTop: theme.spacing.sm,
+ fontSize: theme.fontSize.sm,
+ fontWeight: theme.fontWeight.medium,
+ color: theme.colors.text,
+ backgroundColor: theme.colors.background,
+ border: `1px solid ${theme.colors.focus}`,
+ borderRadius: theme.borderRadius.sm,
+ padding: '2px 6px',
+ textAlign: 'center',
+ width: '100px',
+ outline: 'none',
+ }}
+ />
+ ) : (
+ <div
+ onDoubleClick={handleLabelDoubleClick}
+ style={{
+ marginTop: theme.spacing.sm,
+ fontSize: theme.fontSize.sm,
+ fontWeight: theme.fontWeight.medium,
+ color: theme.colors.text,
+ lineHeight: '1.2',
+ textAlign: 'center',
+ maxWidth: '120px',
+ cursor: 'text',
+ }}
+ >
+ {data?.label || definition?.displayName}
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default ToolkitNode;
diff --git a/client/src/hooks/useReactFlowNodes.ts b/client/src/hooks/useReactFlowNodes.ts
index 06cf96d1..d8b0bf7e 100644
--- a/client/src/hooks/useReactFlowNodes.ts
+++ b/client/src/hooks/useReactFlowNodes.ts
@@ -127,7 +127,7 @@ export const useReactFlowNodes = ({ setNodes, setEdges }: UseReactFlowNodesProps
(params: Edge | Connection) => {
const { currentWorkflow } = useAppStore.getState();
const nodes = currentWorkflow?.nodes || [];
-
+
// Convert Edge to Connection format for validation
const connection: Connection = {
source: params.source,
@@ -135,7 +135,15 @@ export const useReactFlowNodes = ({ setNodes, setEdges }: UseReactFlowNodesProps
sourceHandle: params.sourceHandle ?? null,
targetHandle: params.targetHandle ?? null
};
-
+
+ // Debug: Log all connection attempts
+ console.log('[onConnect] Connection attempt:', {
+ source: params.source,
+ target: params.target,
+ sourceHandle: params.sourceHandle,
+ targetHandle: params.targetHandle
+ });
+
// Validate connection before adding
if (!isValidConnection(connection, nodes)) {
// Show user feedback for rejected connection (non-blocking)
@@ -146,7 +154,8 @@ export const useReactFlowNodes = ({ setNodes, setEdges }: UseReactFlowNodesProps
}, 0);
return;
}
-
+
+ console.log('[onConnect] Connection accepted, adding edge');
// Add the connection
setEdges((eds) => addEdge(params, eds));
},
diff --git a/client/src/nodeDefinitions/androidServiceNodes.ts b/client/src/nodeDefinitions/androidServiceNodes.ts
index 738f6ed3..8279813c 100644
--- a/client/src/nodeDefinitions/androidServiceNodes.ts
+++ b/client/src/nodeDefinitions/androidServiceNodes.ts
@@ -48,12 +48,20 @@ function createAndroidServiceNode(config: {
description: 'Service trigger',
required: false
}],
- outputs: [{
- name: 'main',
- displayName: 'Output',
- type: 'main' as NodeConnectionType,
- description: 'Service execution result'
- }],
+ outputs: [
+ {
+ name: 'main',
+ displayName: 'Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Service execution result'
+ },
+ {
+ name: 'tool',
+ displayName: 'Tool Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to Android Toolkit (top handle)'
+ }
+ ],
properties: [
// Hidden service_id - automatically set based on node type
{
diff --git a/client/src/nodeDefinitions/toolNodes.ts b/client/src/nodeDefinitions/toolNodes.ts
index 3e5f6398..d06f7bc6 100644
--- a/client/src/nodeDefinitions/toolNodes.ts
+++ b/client/src/nodeDefinitions/toolNodes.ts
@@ -158,6 +158,51 @@ export const toolNodes: Record<string, INodeTypeDescription> = {
description: 'Maximum number of results to return'
}
]
+ },
+
+ // Android Toolkit - aggregates Android service nodes for AI Agent
+ // Follows n8n Sub-Node pattern and LangChain Toolkit pattern
+ androidTool: {
+ displayName: 'Android Toolkit',
+ name: 'androidTool',
+ icon: '📱',
+ group: ['ai', 'tool'],
+ version: 1,
+ subtitle: 'Device Control',
+ description: 'Aggregate Android service nodes into a single AI-callable tool. Connect Android nodes to enable those capabilities.',
+ defaults: { name: 'Android Toolkit', color: '#3DDC84' },
+ // Input for connecting Android service nodes (uses SquareNode's input-main)
+ inputs: [{
+ name: 'main',
+ displayName: 'Android Services',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect Android service nodes (battery, wifi, apps, etc.)'
+ }],
+ // Output connects to AI Agent's input-tools handle (uses SquareNode's output-main)
+ outputs: [{
+ name: 'main',
+ displayName: 'Tool Output',
+ type: 'main' as NodeConnectionType,
+ description: 'Connect to AI Agent tool handle'
+ }],
+ properties: [
+ {
+ displayName: 'Tool Name',
+ name: 'toolName',
+ type: 'string',
+ default: 'android_device',
+ required: true,
+ description: 'Name the AI will use to call this tool'
+ },
+ {
+ displayName: 'Description',
+ name: 'toolDescription',
+ type: 'string',
+ default: 'Control Android device. Available services are determined by connected nodes.',
+ typeOptions: { rows: 2 },
+ description: 'Base description (connected services auto-appended)'
+ }
+ ]
}
};
@@ -166,4 +211,4 @@ export const toolNodes: Record<string, INodeTypeDescription> = {
// ============================================================================
// List of tool node types for identification
-export const TOOL_NODE_TYPES = ['calculatorTool', 'currentTimeTool', 'webSearchTool'];
+export const TOOL_NODE_TYPES = ['calculatorTool', 'currentTimeTool', 'webSearchTool', 'androidTool'];
diff --git a/server/constants.py b/server/constants.py
index 60c66e1b..fa39777e 100644
--- a/server/constants.py
+++ b/server/constants.py
@@ -29,6 +29,7 @@ AI_TOOL_TYPES: FrozenSet[str] = frozenset([
'calculatorTool',
'currentTimeTool',
'webSearchTool',
+ 'androidTool',
])
# All AI-related node types (for API key injection)
diff --git a/server/routers/websocket.py b/server/routers/websocket.py
index 1d84642c..ba10a6a2 100644
--- a/server/routers/websocket.py
+++ b/server/routers/websocket.py
@@ -560,6 +560,14 @@ async def handle_deploy_workflow(data: Dict[str, Any], websocket: WebSocket) ->
edges = data.get("edges", [])
session_id = data.get("session_id", "default")
+ # DEBUG: Log received edges to trace toolkit connection issues
+ logger.info(f"[Deploy] Received {len(edges)} edges for workflow {workflow_id}")
+ toolkit_edges = [e for e in edges if 'androidTool' in (e.get('source', '') + e.get('target', ''))]
+ if toolkit_edges:
+ logger.info(f"[Deploy] Android Toolkit edges: {toolkit_edges}")
+ else:
+ logger.info(f"[Deploy] No Android Toolkit edges found. All edges: {edges}")
+
if not nodes:
return {"success": False, "error": "No nodes provided"}
diff --git a/server/services/ai.py b/server/services/ai.py
index cdc9baf3..a2c7049c 100644
--- a/server/services/ai.py
+++ b/server/services/ai.py
@@ -617,6 +617,8 @@ class AIService:
logger.info(f"[LangGraph] broadcast_status completed for executing_tool: {tool_name}")
config = tool_configs.get(tool_name, {})
+ # Include workflow_id in config so tool handlers can broadcast with proper scoping
+ config['workflow_id'] = workflow_id
result = await execute_tool(tool_name, tool_args, config)
await broadcast_status("tool_completed", {
@@ -743,7 +745,7 @@ class AIService:
"""Convert a node configuration into a LangChain StructuredTool.
Args:
- tool_info: Dict containing node_id, node_type, parameters, label
+ tool_info: Dict containing node_id, node_type, parameters, label, connected_services (for androidTool)
Returns:
Tuple of (StructuredTool, config_dict) or (None, None) on failure
@@ -753,11 +755,13 @@ class AIService:
'calculatorTool': 'calculator',
'currentTimeTool': 'get_current_time',
'webSearchTool': 'web_search',
+ 'androidTool': 'android_device',
}
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.',
}
try:
@@ -765,6 +769,7 @@ class AIService:
node_params = tool_info.get('parameters', {})
node_label = tool_info.get('label', node_type)
node_id = tool_info.get('node_id', '')
+ connected_services = tool_info.get('connected_services', [])
# Get tool name from params, then type-specific default, then generic fallback
tool_name = (
@@ -778,12 +783,20 @@ class AIService:
f"Execute {node_label} node"
)
+ # For androidTool, enhance description with connected services
+ if node_type == 'androidTool' and connected_services:
+ service_names = [s.get('label') or s.get('service_id', 'unknown') for s in connected_services]
+ tool_description = f"{tool_description} Connected: {', '.join(service_names)}"
+
# Clean tool name (LangChain requires alphanumeric + underscores)
import re
tool_name = re.sub(r'[^a-zA-Z0-9_]', '_', tool_name)
- # Build schema based on node type
- schema = self._get_tool_schema(node_type, node_params)
+ # Build schema based on node type - pass connected_services for androidTool
+ schema_params = dict(node_params)
+ if connected_services:
+ schema_params['connected_services'] = connected_services
+ schema = self._get_tool_schema(node_type, schema_params)
# Create StructuredTool - the func is a placeholder, actual execution via tool_executor
def placeholder_func(**kwargs):
@@ -796,11 +809,13 @@ class AIService:
args_schema=schema
)
+ # Build config dict - include connected_services for toolkit nodes
config = {
'node_type': node_type,
'node_id': node_id,
'parameters': node_params,
- 'label': node_label
+ 'label': node_label,
+ 'connected_services': connected_services # Pass through for execution
}
logger.info(f"[LangGraph] Built tool '{tool_name}' from node type '{node_type}'")
@@ -878,6 +893,48 @@ class AIService:
return WhatsAppSendSchema
+ # Android toolkit schema - dynamic based on connected services
+ # Follows LangChain dynamic tool binding pattern
+ if node_type == 'androidTool':
+ connected_services = params.get('connected_services', [])
+
+ if not connected_services:
+ # No services connected - minimal schema with helpful error
+ class EmptyAndroidSchema(BaseModel):
+ """Android toolkit with no connected services."""
+ query: str = Field(
+ default="status",
+ description="No Android services connected. Connect Android nodes to the toolkit."
+ )
+ return EmptyAndroidSchema
+
+ # Build dynamic service list for schema description
+ from services.android_service import SERVICE_ACTIONS
+
+ service_info = []
+ for svc in connected_services:
+ svc_id = svc.get('service_id') or svc.get('node_type', 'unknown')
+ actions = SERVICE_ACTIONS.get(svc_id, [])
+ action_list = [a['value'] for a in actions] if actions else ['status']
+ service_info.append(f"{svc_id}: {'/'.join(action_list)}")
+
+ services_description = "; ".join(service_info)
+
+ class AndroidToolSchema(BaseModel):
+ """Schema for Android device control via connected services."""
+ service_id: str = Field(
+ description=f"Service to use. Connected: {services_description}"
+ )
+ action: str = Field(
+ description="Action to perform (see service list for available actions)"
+ )
+ parameters: Optional[Dict[str, Any]] = Field(
+ default=None,
+ description="Action parameters. Examples: {package_name: 'com.app'} for app_launcher, {volume: 50} for audio"
+ )
+
+ return AndroidToolSchema
+
# Generic schema for other nodes
class GenericToolSchema(BaseModel):
"""Generic schema for tool arguments."""
diff --git a/server/services/deployment/manager.py b/server/services/deployment/manager.py
index 5a8d0a8f..4928f6c1 100644
--- a/server/services/deployment/manager.py
+++ b/server/services/deployment/manager.py
@@ -495,6 +495,7 @@ class DeploymentManager:
# Build filtered graph
run_filter = {trigger_node_id} | {n['id'] for n in downstream}
+ logger.info(f"[Run] run_filter has {len(run_filter)} nodes: {[n.get('type') for n in state.nodes if n['id'] in run_filter]}")
filtered_nodes = []
for node in state.nodes:
@@ -510,6 +511,7 @@ class DeploymentManager:
e for e in state.edges
if e.get('source') in run_filter and e.get('target') in run_filter
]
+ logger.info(f"[Run] filtered_edges: {len(filtered_edges)} edges (from {len(state.edges)} total)")
# Execute filtered graph with deployment's workflow_id for scoped status
status_callback = self._status_callbacks.get(workflow_id)
@@ -569,6 +571,18 @@ class DeploymentManager:
if is_config and target in downstream_ids and source not in downstream_ids:
downstream_ids.add(source)
+ # Include sub-nodes connected to toolkit nodes (n8n Sub-Node pattern)
+ # Android service nodes connect to androidTool's input-main, not config handles
+ # These need to be included so the toolkit can discover its connected services
+ toolkit_node_ids = {n['id'] for n in nodes if n.get('type') == 'androidTool' and n['id'] in downstream_ids}
+ for edge in edges:
+ target = edge.get('target')
+ source = edge.get('source')
+ # Include nodes that connect to toolkit nodes
+ if target in toolkit_node_ids and source not in downstream_ids:
+ downstream_ids.add(source)
+ logger.debug(f"[Deployment] Including sub-node {source} connected to toolkit {target}")
+
return [n for n in nodes if n['id'] in downstream_ids]
# =========================================================================
diff --git a/server/services/handlers/ai.py b/server/services/handlers/ai.py
index 847a2c96..d6f582b6 100644
--- a/server/services/handlers/ai.py
+++ b/server/services/handlers/ai.py
@@ -2,6 +2,7 @@
from typing import Dict, Any, List, TYPE_CHECKING
from core.logging import get_logger
+from constants import ANDROID_SERVICE_NODE_TYPES
if TYPE_CHECKING:
from services.ai import AIService
@@ -38,6 +39,12 @@ async def handle_ai_agent(
memory_data = None
tool_data: List[Dict[str, Any]] = [] # Collect connected tool nodes
+ # DEBUG: Log what we're working with
+ logger.info(f"[AI Agent] Processing node {node_id}, context has {len(edges) if edges else 0} edges, {len(nodes) if nodes else 0} nodes")
+ if edges:
+ toolkit_edges = [e for e in edges if 'androidTool' in str(e)]
+ logger.info(f"[AI Agent] Toolkit-related edges: {toolkit_edges}")
+
if edges and nodes:
for edge in edges:
if edge.get('target') != node_id:
@@ -69,12 +76,61 @@ async def handle_ai_agent(
elif target_handle == 'input-tools':
tool_type = source_node.get('type')
tool_params = await database.get_node_parameters(source_node_id) or {}
- tool_data.append({
+
+ # Build base tool entry
+ tool_entry = {
'node_id': source_node_id,
'node_type': tool_type,
'parameters': tool_params,
'label': source_node.get('data', {}).get('label', tool_type)
- })
+ }
+
+ # Special handling for androidTool - discover connected Android services
+ # Follows n8n Sub-Node pattern
+ if tool_type == 'androidTool':
+ connected_services = []
+
+ # Debug: log all edges to understand the structure
+ logger.info(f"[Android Toolkit] Looking for edges targeting toolkit node: {source_node_id}")
+ logger.info(f"[Android Toolkit] Total edges in context: {len(edges)}")
+ for i, e in enumerate(edges):
+ logger.info(f"[Android Toolkit] Edge {i}: source={e.get('source')}, target={e.get('target')}, sourceHandle={e.get('sourceHandle')}, targetHandle={e.get('targetHandle')}")
+
+ toolkit_edges = [e for e in edges if e.get('target') == source_node_id]
+ logger.info(f"[Android Toolkit] Edges targeting toolkit {source_node_id}: {toolkit_edges}")
+
+ # Scan edges for Android nodes connected to this toolkit
+ for service_edge in edges:
+ # Skip if not targeting this androidTool node
+ if service_edge.get('target') != source_node_id:
+ continue
+
+ target_handle = service_edge.get('targetHandle')
+ # Accept input-main or no handle (ReactFlow may omit handle for single-input nodes)
+ if target_handle is not None and target_handle != 'input-main':
+ logger.debug(f"[Android Toolkit] Skipping edge with targetHandle: {target_handle}")
+ continue
+
+ android_node_id = service_edge.get('source')
+ android_node = next((n for n in nodes if n.get('id') == android_node_id), None)
+
+ if android_node and android_node.get('type') in ANDROID_SERVICE_NODE_TYPES:
+ android_params = await database.get_node_parameters(android_node_id) or {}
+ connected_services.append({
+ 'node_id': android_node_id,
+ 'node_type': android_node.get('type'),
+ 'service_id': android_params.get('service_id'),
+ 'action': android_params.get('action'), # Default action
+ 'parameters': android_params,
+ 'label': android_node.get('data', {}).get('label', android_node.get('type'))
+ })
+ logger.debug(f"Android toolkit connected service: {android_params.get('service_id')}")
+
+ tool_entry['connected_services'] = connected_services
+ logger.info(f"Android toolkit has {len(connected_services)} connected services",
+ node_id=source_node_id, services=[s.get('service_id') for s in connected_services])
+
+ tool_data.append(tool_entry)
logger.info("AI Agent connected tool node", node_id=node_id, execution_id=execution_id,
tool_type=tool_type, tool_node_id=source_node_id)
diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.py
index 936eb723..a6216243 100644
--- a/server/services/handlers/tools.py
+++ b/server/services/handlers/tools.py
@@ -56,6 +56,10 @@ 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', {}))
+ # Android toolkit - routes to connected service nodes
+ if node_type == 'androidTool':
+ return await _execute_android_toolkit(tool_args, config)
+
# Generic fallback for unknown node types
logger.warning(f"[Tool] Unknown tool type: {node_type}, using generic handler")
return await _execute_generic(tool_args, config)
@@ -453,6 +457,139 @@ async def _execute_whatsapp_send(args: Dict[str, Any],
return {"error": f"WhatsApp send failed: {str(e)}"}
+async def _execute_android_toolkit(args: Dict[str, Any],
+ config: Dict[str, Any]) -> Dict[str, Any]:
+ """Execute Android toolkit by routing to connected service.
+
+ Follows n8n Sub-Node execution pattern - the toolkit routes
+ to the appropriate connected Android service node.
+
+ Uses the existing AndroidService which handles both relay (remote)
+ and local HTTP connections automatically.
+
+ Args:
+ args: LLM-provided arguments {service_id, action, parameters}
+ config: Toolkit config with connected_services list
+
+ Returns:
+ Service execution result
+ """
+ from services.android_service import AndroidService
+ from services.status_broadcaster import get_status_broadcaster
+
+ service_id = args.get('service_id', '')
+ action = args.get('action', '')
+ parameters = args.get('parameters') or {}
+
+ connected_services = config.get('connected_services', [])
+
+ # Validate service_id provided
+ if not service_id:
+ available = [s.get('service_id') or s.get('node_type') for s in connected_services]
+ return {
+ "error": "No service_id provided",
+ "hint": f"Available services: {', '.join(available)}" if available else "No services connected"
+ }
+
+ # Find matching connected service
+ target_service = None
+ for svc in connected_services:
+ svc_id = svc.get('service_id') or svc.get('node_type')
+ if svc_id == service_id:
+ target_service = svc
+ break
+
+ if not target_service:
+ available = [s.get('service_id') or s.get('node_type') for s in connected_services]
+ return {
+ "error": f"Service '{service_id}' not connected to toolkit",
+ "available_services": available
+ }
+
+ # Get connection parameters from connected Android node
+ svc_params = target_service.get('parameters', {})
+ host = svc_params.get('android_host', 'localhost')
+ port = int(svc_params.get('android_port', 8888))
+
+ # Use provided action, or fall back to node's default action
+ if not action:
+ action = svc_params.get('action') or target_service.get('action', 'status')
+
+ # Get the connected service's node_id for status broadcast
+ service_node_id = target_service.get('node_id')
+ # Get workflow_id from config for proper status scoping
+ workflow_id = config.get('workflow_id')
+
+ logger.info(f"[Android Toolkit] Executing {service_id}.{action} via '{target_service.get('label')}' (node: {service_node_id}, workflow: {workflow_id})")
+
+ # Broadcast executing status for the connected Android service node
+ # This makes the SquareNode show the animation
+ broadcaster = get_status_broadcaster()
+ if service_node_id:
+ await broadcaster.update_node_status(
+ service_node_id,
+ "executing",
+ {"message": f"Executing {action} via AI Agent toolkit"},
+ workflow_id=workflow_id
+ )
+
+ try:
+ # Use AndroidService which handles relay vs local connection automatically
+ android_service = AndroidService()
+ result = await android_service.execute_service(
+ node_id=config.get('node_id', 'toolkit'),
+ service_id=service_id,
+ action=action,
+ parameters=parameters,
+ android_host=host,
+ android_port=port
+ )
+
+ # Broadcast success/error status for the connected service node
+ if service_node_id:
+ if result.get('success'):
+ await broadcaster.update_node_status(
+ service_node_id,
+ "success",
+ {"message": f"{action} completed", "result": result.get('result', {})},
+ workflow_id=workflow_id
+ )
+ else:
+ await broadcaster.update_node_status(
+ service_node_id,
+ "error",
+ {"message": result.get('error', 'Unknown error')},
+ workflow_id=workflow_id
+ )
+
+ # Extract and return the relevant data
+ if result.get('success'):
+ return {
+ "success": True,
+ "service": service_id,
+ "action": action,
+ "data": result.get('result', {}).get('data', result.get('result', {}))
+ }
+ else:
+ return {
+ "error": result.get('error', 'Unknown error'),
+ "service": service_id,
+ "action": action
+ }
+
+ except Exception as e:
+ logger.error(f"[Android Toolkit] Unexpected error: {e}")
+ # Broadcast error status for the connected service node
+ if service_node_id:
+ await broadcaster.update_node_status(
+ service_node_id,
+ "error",
+ {"message": str(e)},
+ workflow_id=workflow_id
+ )
+ return {"error": str(e)}
+
+
async def _execute_generic(args: Dict[str, Any],
config: Dict[str, Any]) -> Dict[str, Any]:
"""Execute a generic tool (fallback handler).