All files / web/src/composables/execution useSingleNodeExecution.ts

0% Statements 0/222
0% Branches 0/1
0% Functions 0/1
0% Lines 0/222

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
import { ref } from 'vue'
import { useNodeOperations } from '@/composables/node/useNodeOperations'
import { testNodeExecution } from '@/api/tasks'
import type { Node } from '@vue-flow/core'
import { NODE_TYPE, TRIGGER_NODE_TYPES, ERROR_MESSAGES, VALIDATION_MESSAGES } from '@/constants'
import { useExecutionStore } from '@/stores/executionStore'
 
export function useSingleNodeExecution() {
  const { getNodeById, getIncomingEdges, updateNodeData } = useNodeOperations()
  const executionStore = useExecutionStore()
 
  const isExecuting = ref(false)
  const executionResult = ref<any>(null)
  const executionError = ref<string | null>(null)
 
  const executeSingleNode = async (nodeId: string, testInput?: any) => {
    isExecuting.value = true
    executionResult.value = null
    executionError.value = null
 
    const startTime = Date.now()
 
    try {
      const node = getNodeById(nodeId)
      if (!node) {
        throw new Error(ERROR_MESSAGES.NOT_FOUND('Node'))
      }
 
      const nodeType = node.type ?? NODE_TYPE.MANUAL_TRIGGER
 
      let input = testInput
      if (!input) {
        const incomingEdges = getIncomingEdges(nodeId)
        if (incomingEdges.length > 0 && incomingEdges[0]) {
          const sourceNodeId = incomingEdges[0].source
          const sourceNode = getNodeById(sourceNodeId)
          if (sourceNode?.data?.lastExecutionResult) {
            input = sourceNode.data.lastExecutionResult
          }
        }
      }
 
      executionStore.setNodeResult(nodeId, {
        nodeId,
        status: 'Running',
        input: input || {},
        output: undefined,
        error: undefined,
        startTime,
        endTime: undefined,
        executionTime: undefined
      })
 
      const testRequest = {
        id: `test-${Date.now()}`,
        name: `Test ${nodeType} Node`,
        nodes: [{
          id: node.id,
          node_type: mapNodeTypeToBackend(nodeType),
          config: extractNodeConfig(node)
        }],
        edges: [],
        input: input || {}
      }
 
      const result = await testNodeExecution<any>(testRequest)
      executionResult.value = result
 
      const endTime = Date.now()
      const executionTime = endTime - startTime
 
      executionStore.setNodeResult(nodeId, {
        nodeId,
        status: 'Completed',
        input: input || {},
        output: executionResult.value,
        startTime,
        endTime,
        executionTime
      })
 
      updateNodeData(nodeId, {
        lastExecutionInput: input || {},
        lastExecutionResult: executionResult.value,
        lastExecutionTime: new Date().toISOString()
      }, false)
 
      return executionResult.value
    } catch (error: any) {
      const errorMessage =
        error?.response?.data?.error ||
        error?.response?.data?.message ||
        error?.message ||
        ERROR_MESSAGES.NODE_EXECUTION_FAILED
 
      const endTime = Date.now()
      const executionTime = endTime - startTime
 
      executionStore.setNodeResult(nodeId, {
        nodeId,
        status: 'Failed',
        error: errorMessage,
        startTime,
        endTime,
        executionTime
      })
 
      executionError.value = errorMessage
      throw new Error(errorMessage)
    } finally {
      isExecuting.value = false
    }
  }
 
  const executeMultipleNodes = async (nodeIds: string[]) => {
    const results: Record<string, any> = {}
    const errors: Record<string, string> = {}
 
    for (const nodeId of nodeIds) {
      try {
        const result = await executeSingleNode(nodeId)
        results[nodeId] = result
      } catch (error: any) {
        errors[nodeId] = error.message
      }
    }
 
    return { results, errors }
  }
 
  const validateNodeConfig = async (nodeId: string) => {
    const node = getNodeById(nodeId)
    if (!node) {
      return { valid: false, errors: [ERROR_MESSAGES.NOT_FOUND('Node')] }
    }
 
    const errors: string[] = []
 
    switch (node.type) {
      case NODE_TYPE.AGENT:
        if (!node.data.model) {
          errors.push(VALIDATION_MESSAGES.SELECT_MODEL)
        }
        if (!node.data.prompt && !node.data.input) {
          errors.push(VALIDATION_MESSAGES.ENTER_PROMPT)
        }
        break
 
      case NODE_TYPE.HTTP_REQUEST:
        if (!node.data.url) {
          errors.push(VALIDATION_MESSAGES.ENTER_URL)
        }
        if (!node.data.method) {
          errors.push(VALIDATION_MESSAGES.REQUIRED_SELECT('request method'))
        }
        break
 
      case NODE_TYPE.WEBHOOK_TRIGGER:
        if (!node.data.path) {
          errors.push(VALIDATION_MESSAGES.SET_WEBHOOK_PATH)
        }
        break
    }
 
    if (!TRIGGER_NODE_TYPES.has(node.type as any)) {
      const incomingEdges = getIncomingEdges(nodeId)
      if (incomingEdges.length === 0) {
        errors.push(ERROR_MESSAGES.NODE_INPUT_REQUIRED)
      }
    }
 
    return {
      valid: errors.length === 0,
      errors
    }
  }
 
  const getMockInput = (nodeId: string) => {
    const node = getNodeById(nodeId)
    if (!node) return {}
 
    switch (node.type) {
      case 'agentNode':
        return {
          message: 'This is a test message',
          context: {
            user: 'test_user',
            session: 'test_session'
          }
        }
 
      case 'httpNode':
        return {
          data: {
            test: true,
            timestamp: new Date().toISOString()
          }
        }
 
      default:
        return {
          test: true,
          value: 'mock_value'
        }
    }
  }
 
  return {
    isExecuting,
    executionResult,
    executionError,
    executeSingleNode,
    executeMultipleNodes,
    validateNodeConfig,
    getMockInput
  }
}
 
function mapNodeTypeToBackend(nodeType: string): string {
  const validTypes = Object.values(NODE_TYPE)
  if (validTypes.includes(nodeType as any)) {
    return nodeType
  }
 
  return nodeType
}
 
function extractNodeConfig(node: Node): any {
  const { label, ...config } = node.data
 
  switch (node.type) {
    case NODE_TYPE.AGENT:
      return {
        model: config.model,
        prompt: config.prompt,
        temperature: config.temperature,
        tools: config.tools,
        input: config.input,
        api_key_config: config.api_key_config
      }
 
    case NODE_TYPE.HTTP_REQUEST:
      return {
        url: config.url,
        method: config.method,
        headers: config.headers,
        body: config.body,
        auth: config.auth
      }
 
    case NODE_TYPE.WEBHOOK_TRIGGER:
      return {
        path: config.path,
        method: config.method || 'POST'
      }
 
    case NODE_TYPE.MANUAL_TRIGGER:
      return config
 
    default:
      return config
  }
}