task-engine-ai-core
Version:
Revolutionary AI-driven task management system with complete transformation trilogy: Frontend v0.1.0, Backend v0.2.0, CLI v0.3.0 - Enterprise-grade performance with 95% improvements
413 lines (350 loc) • 12.9 kB
JavaScript
/**
* Frontend Rework Test
*
* Test the new frontend architecture with active agent detection
* and MCP communication layer.
*/
import { taskEngineFrontendService, initializeService, createTask, getTasks } from '../core/task-engine-frontend-service.js';
import { activeAgentDetector } from '../core/active-agent-detector.js';
import { mcpCommunicationLayer } from '../core/mcp-communication-layer.js';
import { logger } from '../utils/logger-utils.js';
/**
* Test Configuration
*/
const TEST_CONFIG = {
projectRoot: 'C:\\Users\\visual-code\\Task-engine',
enableLogging: true,
testTimeout: 30000
};
/**
* Mock MCP Session for testing
*/
const mockSession = {
id: 'test-session-123',
clientCapabilities: {
sampling: {
enabled: true
},
roots: {
listChanged: true
}
},
capabilities: {
tools: true,
resources: true
},
clientInfo: {
name: 'test-client',
version: '1.0.0'
}
};
/**
* Test Suite for Frontend Rework
*/
class FrontendReworkTestSuite {
constructor() {
this.testResults = [];
this.startTime = Date.now();
}
/**
* Run all tests
*/
async runAllTests() {
console.log('🚀 Starting Frontend Rework Test Suite...\n');
try {
await this.testActiveAgentDetection();
await this.testMCPCommunicationLayer();
await this.testTaskOperationRouting();
await this.testFrontendServiceIntegration();
await this.testEndToEndWorkflow();
this.printTestSummary();
} catch (error) {
console.error('❌ Test suite failed:', error.message);
process.exit(1);
}
}
/**
* Test Active Agent Detection
*/
async testActiveAgentDetection() {
console.log('🔍 Testing Active Agent Detection...');
try {
// Test with active agent session
const detectionResult = await activeAgentDetector.detectActiveAgent(
mockSession,
{ prompt: 'Create a comprehensive test task' }
);
this.assert(
detectionResult.success,
'Active agent detection should succeed'
);
this.assert(
detectionResult.result === 'active_agent_present',
'Should detect active agent presence'
);
this.assert(
detectionResult.strategy === 'active_agent',
'Should use active agent strategy'
);
this.assert(
detectionResult.confidence > 0.7,
'Should have high confidence in detection'
);
// Test without active agent
const noAgentResult = await activeAgentDetector.detectActiveAgent(
null,
{ prompt: 'Simple task' }
);
this.assert(
noAgentResult.result === 'no_agent_detected',
'Should detect no agent when session is null'
);
this.recordTestResult('Active Agent Detection', true);
console.log('✅ Active Agent Detection tests passed\n');
} catch (error) {
this.recordTestResult('Active Agent Detection', false, error.message);
console.log('❌ Active Agent Detection tests failed:', error.message, '\n');
}
}
/**
* Test MCP Communication Layer
*/
async testMCPCommunicationLayer() {
console.log('📡 Testing MCP Communication Layer...');
try {
// Test basic tool call
const toolResult = await mcpCommunicationLayer.callTool(
'get_tasks_task-engine-ai',
{ projectRoot: TEST_CONFIG.projectRoot },
mockSession
);
this.assert(
toolResult.success,
'MCP tool call should succeed'
);
this.assert(
toolResult.result === 'success',
'Tool call should return success result'
);
this.assert(
toolResult.metadata && toolResult.metadata.requestId,
'Should include request metadata'
);
// Test parameter validation
try {
await mcpCommunicationLayer.callTool(
'add_task_task-engine-ai',
{}, // Missing required parameters
mockSession
);
this.assert(false, 'Should fail with missing parameters');
} catch (validationError) {
this.assert(
validationError.message.includes('projectRoot'),
'Should validate required parameters'
);
}
// Test statistics
const stats = mcpCommunicationLayer.getStats();
this.assert(
stats.totalRequests > 0,
'Should track request statistics'
);
this.recordTestResult('MCP Communication Layer', true);
console.log('✅ MCP Communication Layer tests passed\n');
} catch (error) {
this.recordTestResult('MCP Communication Layer', false, error.message);
console.log('❌ MCP Communication Layer tests failed:', error.message, '\n');
}
}
/**
* Test Task Operation Routing
*/
async testTaskOperationRouting() {
console.log('🔀 Testing Task Operation Routing...');
try {
// Import router here to avoid circular dependencies
const { taskOperationRouter, OPERATION_TYPES } = await import('../core/task-operation-router.js');
// Test task creation routing with active agent
const createResult = await taskOperationRouter.routeOperation(
OPERATION_TYPES.CREATE_TASK,
{
projectRoot: TEST_CONFIG.projectRoot,
prompt: 'Create a test task for routing validation'
},
mockSession,
{ testMode: true }
);
this.assert(
createResult.success,
'Task creation routing should succeed'
);
this.assert(
createResult.routingInfo && createResult.routingInfo.strategy,
'Should include routing information'
);
// Test get tasks routing
const getResult = await taskOperationRouter.routeOperation(
OPERATION_TYPES.GET_TASKS,
{ projectRoot: TEST_CONFIG.projectRoot },
mockSession
);
this.assert(
getResult.success,
'Get tasks routing should succeed'
);
// Test routing statistics
const routingStats = taskOperationRouter.getRoutingStats();
this.assert(
routingStats.totalOperations > 0,
'Should track routing statistics'
);
this.recordTestResult('Task Operation Routing', true);
console.log('✅ Task Operation Routing tests passed\n');
} catch (error) {
this.recordTestResult('Task Operation Routing', false, error.message);
console.log('❌ Task Operation Routing tests failed:', error.message, '\n');
}
}
/**
* Test Frontend Service Integration
*/
async testFrontendServiceIntegration() {
console.log('🏗️ Testing Frontend Service Integration...');
try {
// Initialize service
const initResult = await initializeService(mockSession, {
projectRoot: TEST_CONFIG.projectRoot
});
this.assert(
initResult.success,
'Service initialization should succeed'
);
this.assert(
initResult.state === 'ready',
'Service should be in ready state'
);
// Test service status
const status = await taskEngineFrontendService.getStatus();
this.assert(
status.state === 'ready',
'Service status should show ready state'
);
this.assert(
status.projectRoot === TEST_CONFIG.projectRoot,
'Should have correct project root'
);
this.recordTestResult('Frontend Service Integration', true);
console.log('✅ Frontend Service Integration tests passed\n');
} catch (error) {
this.recordTestResult('Frontend Service Integration', false, error.message);
console.log('❌ Frontend Service Integration tests failed:', error.message, '\n');
}
}
/**
* Test End-to-End Workflow
*/
async testEndToEndWorkflow() {
console.log('🔄 Testing End-to-End Workflow...');
try {
// Test task creation through the service
const createResult = await createTask({
title: 'End-to-End Test Task',
description: 'This task validates the complete frontend rework workflow',
details: 'Implementation details for the test task',
testStrategy: 'Verify all components work together seamlessly',
priority: 'high'
});
this.assert(
createResult.success,
'End-to-end task creation should succeed'
);
this.assert(
createResult.routingInfo,
'Should include routing information'
);
// Test getting tasks
const tasksResult = await getTasks();
this.assert(
tasksResult.success,
'End-to-end get tasks should succeed'
);
// Test service statistics after operations
const finalStatus = await taskEngineFrontendService.getStatus();
this.assert(
finalStatus.stats.operationsCompleted > 0,
'Should track completed operations'
);
this.recordTestResult('End-to-End Workflow', true);
console.log('✅ End-to-End Workflow tests passed\n');
} catch (error) {
this.recordTestResult('End-to-End Workflow', false, error.message);
console.log('❌ End-to-End Workflow tests failed:', error.message, '\n');
}
}
/**
* Assert a condition
* @param {boolean} condition - Condition to test
* @param {string} message - Error message if condition fails
*/
assert(condition, message) {
if (!condition) {
throw new Error(`Assertion failed: ${message}`);
}
}
/**
* Record test result
* @param {string} testName - Name of the test
* @param {boolean} passed - Whether test passed
* @param {string} error - Error message if failed
*/
recordTestResult(testName, passed, error = null) {
this.testResults.push({
name: testName,
passed,
error,
timestamp: Date.now()
});
}
/**
* Print test summary
*/
printTestSummary() {
const totalTests = this.testResults.length;
const passedTests = this.testResults.filter(r => r.passed).length;
const failedTests = totalTests - passedTests;
const duration = Date.now() - this.startTime;
console.log('📊 Test Summary');
console.log('================');
console.log(`Total Tests: ${totalTests}`);
console.log(`Passed: ${passedTests} ✅`);
console.log(`Failed: ${failedTests} ❌`);
console.log(`Duration: ${duration}ms`);
console.log('');
if (failedTests > 0) {
console.log('Failed Tests:');
this.testResults
.filter(r => !r.passed)
.forEach(test => {
console.log(` ❌ ${test.name}: ${test.error}`);
});
console.log('');
}
if (failedTests === 0) {
console.log('🎉 All tests passed! Frontend rework is working correctly.');
} else {
console.log('⚠️ Some tests failed. Please review the implementation.');
}
}
}
/**
* Run tests if this file is executed directly
*/
if (import.meta.url === `file://${process.argv[1]}`) {
const testSuite = new FrontendReworkTestSuite();
testSuite.runAllTests().catch(error => {
console.error('Test suite execution failed:', error);
process.exit(1);
});
}
export { FrontendReworkTestSuite };