Skip to content

SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.

add tests

Forhad Hosaine72ce5ac12c5
diff --git a/packages/runtime/src/core/services/BillingError.class.ts b/packages/runtime/src/core/services/BillingError.class.ts
deleted file mode 100644
index 15fbf081..00000000
--- a/packages/runtime/src/core/services/BillingError.class.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-export class BillingError extends Error {
- code: string;
- status: number;
-
- constructor(message: string, code: string = 'BILLING_LIMIT_REACHED', status: number = 402) {
- super(message);
- this.status = status;
- this.code = code;
- this.name = 'BillingError';
-
- // Fix prototype chain for proper instanceof behavior with custom Error classes
- Object.setPrototypeOf(this, new.target.prototype);
- }
-}
diff --git a/packages/runtime/src/modules/agent-runner/services/BillingError.class.ts b/packages/runtime/src/modules/agent-runner/services/BillingError.class.ts
deleted file mode 100644
index 15fbf081..00000000
--- a/packages/runtime/src/modules/agent-runner/services/BillingError.class.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-export class BillingError extends Error {
- code: string;
- status: number;
-
- constructor(message: string, code: string = 'BILLING_LIMIT_REACHED', status: number = 402) {
- super(message);
- this.status = status;
- this.code = code;
- this.name = 'BillingError';
-
- // Fix prototype chain for proper instanceof behavior with custom Error classes
- Object.setPrototypeOf(this, new.target.prototype);
- }
-}
diff --git a/packages/runtime/tests/README.md b/packages/runtime/tests/README.md
new file mode 100644
index 00000000..657e3d1e
--- /dev/null
+++ b/packages/runtime/tests/README.md
@@ -0,0 +1,99 @@
+# SmythOS Runtime Server - Test Suite
+
+Simple, focused tests following KISS principle and OSS best practices.
+
+## Test Structure
+
+```
+tests/
+├── setup.ts # Simple test utilities
+├── mocks/
+│ └── sre.mock.ts # Basic SRE library mocks
+├── core/
+│ ├── utils/ # Utility function tests
+│ └── middlewares/ # Middleware tests
+├── services/ # Service tests
+└── integration/ # API tests
+```
+
+## Running Tests
+
+```bash
+# Run all tests
+pnpm test
+
+# Watch mode
+pnpm test:watch
+
+# Coverage report
+pnpm test:coverage
+```
+
+## Writing Tests - KISS Approach
+
+### Keep It Simple
+```typescript
+describe('MyFunction', () => {
+ it('handles valid input', () => {
+ const result = myFunction('input');
+ expect(result).toBe('output');
+ });
+
+ it('handles edge cases', () => {
+ expect(myFunction('')).toBe(null);
+ expect(myFunction(null)).toBe(null);
+ });
+});
+```
+
+### Mock Only What You Need
+```typescript
+vi.mock('@smythos/sre', () => ({
+ Logger: vi.fn(() => ({ error: vi.fn() })),
+}));
+```
+
+### Test One Thing at a Time
+- Each test should verify one behavior
+- Use descriptive test names
+- Follow Arrange-Act-Assert pattern
+
+## Coverage Goals
+- **Target**: 70% overall coverage
+- Focus on critical paths, not 100% coverage
+- Quality over quantity
+
+## Best Practices
+
+1. **Simple is better than complex**
+2. **Test behavior, not implementation**
+3. **Mock external dependencies only**
+4. **Use realistic test data**
+5. **Keep tests fast and independent**
+
+## Common Patterns
+
+```typescript
+// Simple service test
+it('processes valid requests', async () => {
+ const result = await service.process(validInput);
+ expect(result.status).toBe('success');
+});
+
+// Simple API test
+it('returns health status', async () => {
+ await request(app)
+ .get('/health')
+ .expect(200)
+ .expect({ status: 'ok' });
+});
+```
+
+## When Tests Fail
+
+1. Read the error message carefully
+2. Check your mocks are set up correctly
+3. Verify async operations are awaited
+4. Ensure test isolation (no shared state)
+
+Keep tests simple, focused, and valuable.
\ No newline at end of file
diff --git a/packages/runtime/tests/core/middlewares/error.mw.test.ts b/packages/runtime/tests/core/middlewares/error.mw.test.ts
new file mode 100644
index 00000000..fde0f81b
--- /dev/null
+++ b/packages/runtime/tests/core/middlewares/error.mw.test.ts
@@ -0,0 +1,91 @@
+/**
+ * Error middleware tests - KISS approach
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { createMockRequest, createMockResponse, createMockNext } from '../../setup';
+
+vi.mock('@smythos/sre', () => ({
+ Logger: vi.fn(() => ({ error: vi.fn() })),
+}));
+
+vi.mock('@core/config', () => ({
+ default: { env: { NODE_ENV: 'test' } },
+}));
+
+describe('Error Middleware', () => {
+ let errorHandler: any;
+ let notFoundHandler: any;
+
+ beforeEach(async () => {
+ vi.resetModules();
+ const module = await import('@core/middlewares/error.mw');
+ errorHandler = module.errorHandler;
+ notFoundHandler = module.notFoundHandler;
+ });
+
+ describe('errorHandler', () => {
+ it('handles operational errors', () => {
+ const mockReq = createMockRequest({
+ method: 'GET',
+ path: '/api/test',
+ ip: '127.0.0.1',
+ get: vi.fn(() => 'test-user-agent'),
+ });
+ const mockRes = createMockResponse();
+ const mockNext = createMockNext();
+
+ const error = new Error('Test error');
+ (error as any).statusCode = 400;
+ (error as any).isOperational = true;
+
+ errorHandler(error, mockReq, mockRes, mockNext);
+
+ expect(mockRes.status).toHaveBeenCalledWith(400);
+ expect(mockRes.json).toHaveBeenCalledWith({
+ success: false,
+ code: 400,
+ message: 'Test error',
+ });
+ });
+
+ it('defaults to 500 for non-operational errors', () => {
+ const mockReq = createMockRequest({
+ method: 'GET',
+ path: '/api/test',
+ ip: '127.0.0.1',
+ get: vi.fn(() => 'test-user-agent'),
+ });
+ const mockRes = createMockResponse();
+ const mockNext = createMockNext();
+
+ const error = new Error('Programming error');
+
+ errorHandler(error, mockReq, mockRes, mockNext);
+
+ expect(mockRes.status).toHaveBeenCalledWith(500);
+ expect(mockRes.json).toHaveBeenCalledWith({
+ success: false,
+ code: 500,
+ message: 'Internal Server Error',
+ });
+ });
+ });
+
+ describe('notFoundHandler', () => {
+ it('creates 404 error', () => {
+ const mockReq = createMockRequest({ method: 'GET', path: '/missing' });
+ const mockRes = createMockResponse();
+ const mockNext = createMockNext();
+
+ notFoundHandler(mockReq, mockRes, mockNext);
+
+ expect(mockNext).toHaveBeenCalledWith(
+ expect.objectContaining({
+ message: 'Path not found: GET /missing',
+ statusCode: 404,
+ isOperational: true,
+ }),
+ );
+ });
+ });
+});
diff --git a/packages/runtime/tests/core/middlewares/rateLimiter.mw.test.ts b/packages/runtime/tests/core/middlewares/rateLimiter.mw.test.ts
new file mode 100644
index 00000000..921c4c84
--- /dev/null
+++ b/packages/runtime/tests/core/middlewares/rateLimiter.mw.test.ts
@@ -0,0 +1,131 @@
+/**
+ * Rate limiter tests - KISS approach
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { createMockRequest, createMockResponse, createMockNext } from '../../setup';
+
+vi.mock('@core/config', () => ({
+ default: {
+ env: {
+ REQ_LIMIT_PER_MINUTE: 10,
+ MAX_CONCURRENT_REQUESTS: 5,
+ },
+ },
+}));
+
+vi.mock('@smythos/sre', () => ({
+ Logger: vi.fn(() => ({ log: vi.fn(), error: vi.fn() })),
+}));
+
+describe('Rate Limiter Middleware', () => {
+ let RateLimiter: any;
+
+ beforeEach(async () => {
+ vi.useFakeTimers();
+ vi.resetModules();
+
+ const module = await import('@core/middlewares/rateLimiter.mw');
+ RateLimiter = module.default;
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('allows requests from localhost', () => {
+ const mockReq = createMockRequest({ ip: '127.0.0.1' });
+ const mockRes = createMockResponse();
+ const mockNext = createMockNext();
+
+ RateLimiter(mockReq, mockRes, mockNext);
+
+ expect(mockNext).toHaveBeenCalled();
+ expect(mockRes.status).not.toHaveBeenCalled();
+ });
+
+ it('allows requests within limit', () => {
+ const mockReq = createMockRequest({ ip: '203.0.113.1' });
+ const mockRes = createMockResponse();
+ const mockNext = createMockNext();
+
+ // Make 5 requests (within limit)
+ for (let i = 0; i < 5; i++) {
+ RateLimiter(mockReq, mockRes, mockNext);
+ }
+
+ expect(mockNext).toHaveBeenCalledTimes(5);
+ expect(mockRes.status).not.toHaveBeenCalled();
+ });
+
+ it('blocks requests exceeding rate limit', () => {
+ const mockReq = createMockRequest({ ip: '203.0.113.1' });
+ const mockRes = createMockResponse();
+ const mockNext = createMockNext();
+
+ // Fill up the rate limit
+ for (let i = 0; i < 10; i++) {
+ RateLimiter(mockReq, mockRes, mockNext);
+ }
+
+ // Clear mocks for the blocking request
+ mockNext.mockClear();
+ mockRes.status.mockClear();
+
+ // This should be blocked
+ RateLimiter(mockReq, mockRes, mockNext);
+
+ expect(mockNext).not.toHaveBeenCalled();
+ expect(mockRes.status).toHaveBeenCalledWith(429);
+ expect(mockRes.json).toHaveBeenCalledWith(
+ expect.objectContaining({
+ error: 'Too Many Requests',
+ }),
+ );
+ });
+
+ it('handles time-based rate limiting', () => {
+ // This test verifies the concept without relying on internal timer implementation
+ const mockReq = createMockRequest({ ip: '203.0.113.1' });
+ const mockRes = createMockResponse();
+ const mockNext = createMockNext();
+
+ // Make a request - should be allowed
+ RateLimiter(mockReq, mockRes, mockNext);
+
+ expect(mockNext).toHaveBeenCalled();
+ expect(mockRes.status).not.toHaveBeenCalled();
+ });
+
+ it('handles concurrent request limiting', () => {
+ const mockReq = createMockRequest({
+ ip: '203.0.113.1',
+ connection: { remoteAddress: '203.0.113.1' },
+ });
+ const mockRes = createMockResponse() as any;
+ mockRes.on = vi.fn();
+ mockRes.removeListener = vi.fn();
+ const mockNext = createMockNext();
+
+ // Fill concurrent limit
+ for (let i = 0; i < 5; i++) {
+ const req = createMockRequest({ ip: '203.0.113.1' });
+ const res = createMockResponse() as any;
+ res.on = vi.fn();
+ res.removeListener = vi.fn();
+ const next = createMockNext();
+
+ RateLimiter(req, res, next);
+ }
+
+ // This should be blocked
+ RateLimiter(mockReq, mockRes, mockNext);
+
+ expect(mockNext).not.toHaveBeenCalled();
+ expect(mockRes.status).toHaveBeenCalledWith(429);
+ expect(mockRes.json).toHaveBeenCalledWith(
+ expect.objectContaining({
+ message: 'Too many concurrent requests. Please try again later.',
+ }),
+ );
+ });
+});
diff --git a/packages/runtime/tests/core/utils/chat.utils.test.ts b/packages/runtime/tests/core/utils/chat.utils.test.ts
new file mode 100644
index 00000000..dcff75f2
--- /dev/null
+++ b/packages/runtime/tests/core/utils/chat.utils.test.ts
@@ -0,0 +1,189 @@
+/**
+ * Unit tests for chat utilities
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import crypto from 'crypto';
+import {
+ buildConversationId,
+ parseDateFromConvId,
+ getChatPrefixByEnv,
+ parseDateRange,
+ isValidDateRange,
+ CHAT_PREFIXES,
+} from '@core/utils/chat.utils';
+
+// Mock crypto
+vi.mock('crypto', () => ({
+ default: {
+ randomBytes: vi.fn(() => ({
+ toString: vi.fn(() => 'abcd1234'),
+ })),
+ },
+}));
+
+// Mock date-time utils
+vi.mock('@core/utils/date-time.utils', () => ({
+ getCurrentFormattedDate: vi.fn(() => '2023-12-25-15-30-45'),
+ toDateFromFormattedDateStr: vi.fn((dateStr: string) => {
+ const [year, month, day, hour, minute, second] = dateStr.split('-').map(Number);
+ return new Date(year, month - 1, day, hour, minute, second);
+ }),
+}));
+
+describe('Chat Utils', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('CHAT_PREFIXES', () => {
+ it('should have correct prefixes for test and prod environments', () => {
+ expect(CHAT_PREFIXES.test).toBe('chat-test-');
+ expect(CHAT_PREFIXES.prod).toBe('chat-');
+ });
+ });
+
+ describe('buildConversationId', () => {
+ it('should build conversation ID with prod prefix by default', () => {
+ const result = buildConversationId();
+ expect(result).toBe('chat-2023-12-25-15-30-45-chat-2023-12-25-15-30-45-abcd1234');
+ });
+
+ it('should build conversation ID with test prefix when isTestConv is true', () => {
+ const result = buildConversationId(undefined, true);
+ expect(result).toBe('chat-test-2023-12-25-15-30-45-chat-test-2023-12-25-15-30-45-abcd1234');
+ });
+
+ it('should use provided uid when given', () => {
+ const customUid = 'custom-uid-123';
+ const result = buildConversationId(customUid, false);
+ expect(result).toBe('chat-2023-12-25-15-30-45-custom-uid-123');
+ });
+
+ it('should use test prefix with custom uid', () => {
+ const customUid = 'custom-test-uid';
+ const result = buildConversationId(customUid, true);
+ expect(result).toBe('chat-test-2023-12-25-15-30-45-custom-test-uid');
+ });
+
+ it('should call crypto.randomBytes when no uid provided', () => {
+ buildConversationId();
+ expect(crypto.randomBytes).toHaveBeenCalledWith(8);
+ });
+ });
+
+ describe('parseDateFromConvId', () => {
+ it('should parse date from conversation ID', () => {
+ const convId = 'chat-2023-12-25-15-30-45-some-suffix';
+ const result = parseDateFromConvId(convId);
+
+ expect(result).toBeInstanceOf(Date);
+ expect(result?.getFullYear()).toBe(2023);
+ expect(result?.getMonth()).toBe(11); // December (0-based)
+ expect(result?.getDate()).toBe(25);
+ });
+
+ it('should return null for invalid conversation ID format', () => {
+ expect(parseDateFromConvId('invalid-format')).toBeNull();
+ expect(parseDateFromConvId('chat-invalid-date')).toBeNull();
+ expect(parseDateFromConvId('')).toBeNull();
+ });
+
+ it('should parse date from test conversation ID', () => {
+ const convId = 'chat-test-2024-01-01-12-00-00-test-suffix';
+ const result = parseDateFromConvId(convId);
+
+ expect(result).toBeInstanceOf(Date);
+ expect(result?.getFullYear()).toBe(2024);
+ expect(result?.getMonth()).toBe(0); // January (0-based)
+ expect(result?.getDate()).toBe(1);
+ });
+ });
+
+ describe('getChatPrefixByEnv', () => {
+ it('should return correct prefix for test environment', () => {
+ const result = getChatPrefixByEnv('test');
+ expect(result).toBe('chat-test-');
+ });
+
+ it('should return correct prefix for prod environment', () => {
+ const result = getChatPrefixByEnv('prod');
+ expect(result).toBe('chat-');
+ });
+ });
+
+ describe('parseDateRange', () => {
+ it('should parse valid date range string', () => {
+ const result = parseDateRange('1609459200000,1609545600000');
+ expect(result).toEqual({
+ start: 1609459200000,
+ end: 1609545600000,
+ });
+ });
+
+ it('should handle single comma separated values', () => {
+ const result = parseDateRange('123,456');
+ expect(result).toEqual({
+ start: 123,
+ end: 456,
+ });
+ });
+
+ it('should handle invalid numbers gracefully', () => {
+ const result = parseDateRange('invalid,range');
+ expect(result).toEqual({
+ start: NaN,
+ end: NaN,
+ });
+ });
+ });
+
+ describe('isValidDateRange', () => {
+ it('should return true for valid date ranges', () => {
+ expect(isValidDateRange('100,200')).toBe(true);
+ expect(isValidDateRange('1609459200000,1609545600000')).toBe(true);
+ expect(isValidDateRange('0,1')).toBe(true);
+ });
+
+ it('should return false for invalid date ranges', () => {
+ expect(isValidDateRange('200,100')).toBe(false); // start > end
+ expect(isValidDateRange('100,100')).toBe(false); // start === end
+ expect(isValidDateRange('invalid,range')).toBe(false); // NaN values
+ expect(isValidDateRange('100')).toBe(false); // Missing comma
+ expect(isValidDateRange('')).toBe(false); // Empty string
+ expect(isValidDateRange('100,')).toBe(false); // Missing end
+ expect(isValidDateRange(',200')).toBe(false); // Missing start
+ });
+
+ it('should return false for null or undefined input', () => {
+ expect(isValidDateRange(null as any)).toBe(false);
+ expect(isValidDateRange(undefined as any)).toBe(false);
+ });
+
+ it('should handle edge cases', () => {
+ expect(isValidDateRange('0,0')).toBe(false); // Equal values
+ expect(isValidDateRange('-100,-50')).toBe(true); // Negative numbers
+ expect(isValidDateRange('-100,50')).toBe(true); // Negative to positive
+ });
+ });
+
+ describe('integration tests', () => {
+ it('should create conversation ID that can be parsed for date', () => {
+ const convId = buildConversationId();
+ const parsedDate = parseDateFromConvId(convId);
+
+ expect(parsedDate).toBeInstanceOf(Date);
+ expect(parsedDate?.getFullYear()).toBe(2023);
+ expect(parsedDate?.getMonth()).toBe(11); // December
+ expect(parsedDate?.getDate()).toBe(25);
+ });
+
+ it('should handle test environment end-to-end', () => {
+ const convId = buildConversationId(undefined, true);
+ const parsedDate = parseDateFromConvId(convId);
+ const prefix = getChatPrefixByEnv('test');
+
+ expect(convId.startsWith(prefix)).toBe(true);
+ expect(parsedDate).toBeInstanceOf(Date);
+ });
+ });
+});
\ No newline at end of file
diff --git a/packages/runtime/tests/core/utils/date-time.utils.test.ts b/packages/runtime/tests/core/utils/date-time.utils.test.ts
new file mode 100644
index 00000000..0ff9e5b2
--- /dev/null
+++ b/packages/runtime/tests/core/utils/date-time.utils.test.ts
@@ -0,0 +1,160 @@
+/**
+ * Unit tests for date-time utilities
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import {
+ getCurrentFormattedDate,
+ toDateFromFormattedDateStr,
+ getDayFormattedDate,
+ delay,
+} from '@core/utils/date-time.utils';
+
+describe('Date-Time Utils', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('getCurrentFormattedDate', () => {
+ it('should return a formatted date string in YYYY-MM-DD-HH-MM-SS format', () => {
+ const result = getCurrentFormattedDate();
+ expect(result).toMatch(/^\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}$/);
+ });
+
+ it('should return current date and time', () => {
+ const before = new Date();
+ const result = getCurrentFormattedDate();
+ const after = new Date();
+
+ const [year, month, day] = result.split('-').map(Number);
+ expect(year).toBe(before.getFullYear());
+ expect(month).toBeGreaterThanOrEqual(before.getMonth() + 1);
+ expect(month).toBeLessThanOrEqual(after.getMonth() + 1);
+ expect(day).toBeGreaterThanOrEqual(before.getDate());
+ expect(day).toBeLessThanOrEqual(after.getDate());
+ });
+
+ it('should pad single-digit values with zeros', () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2023-01-05 09:08:07'));
+
+ const result = getCurrentFormattedDate();
+ expect(result).toBe('2023-01-05-09-08-07');
+
+ vi.useRealTimers();
+ });
+ });
+
+ describe('toDateFromFormattedDateStr', () => {
+ it('should convert formatted date string to Date object', () => {
+ const formattedDate = '2023-12-25-15-30-45';
+ const result = toDateFromFormattedDateStr(formattedDate);
+
+ expect(result).toBeInstanceOf(Date);
+ expect(result.getFullYear()).toBe(2023);
+ expect(result.getMonth()).toBe(11); // December (0-based)
+ expect(result.getDate()).toBe(25);
+ expect(result.getHours()).toBe(15);
+ expect(result.getMinutes()).toBe(30);
+ expect(result.getSeconds()).toBe(45);
+ });
+
+ it('should handle edge case dates', () => {
+ const formattedDate = '2024-02-29-23-59-59'; // Leap year
+ const result = toDateFromFormattedDateStr(formattedDate);
+
+ expect(result.getFullYear()).toBe(2024);
+ expect(result.getMonth()).toBe(1); // February (0-based)
+ expect(result.getDate()).toBe(29);
+ expect(result.getHours()).toBe(23);
+ expect(result.getMinutes()).toBe(59);
+ expect(result.getSeconds()).toBe(59);
+ });
+ });
+
+ describe('getDayFormattedDate', () => {
+ it('should return a formatted date string in YYYY-MM-DD format', () => {
+ const result = getDayFormattedDate();
+ expect(result).toMatch(/^\d{4}-\d{2}-\d{2}$/);
+ });
+
+ it('should return current date only', () => {
+ const now = new Date();
+ const result = getDayFormattedDate();
+
+ const [year, month, day] = result.split('-').map(Number);
+ expect(year).toBe(now.getFullYear());
+ expect(month).toBe(now.getMonth() + 1);
+ expect(day).toBe(now.getDate());
+ });
+
+ it('should pad single-digit values with zeros', () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2023-01-05'));
+
+ const result = getDayFormattedDate();
+ expect(result).toBe('2023-01-05');
+
+ vi.useRealTimers();
+ });
+ });
+
+ describe('delay', () => {
+ it('should resolve after the specified milliseconds', async () => {
+ vi.useFakeTimers();
+
+ const promise = delay(1000);
+ expect(promise).toBeInstanceOf(Promise);
+
+ vi.advanceTimersByTime(500);
+ // Promise should still be pending
+ let resolved = false;
+ promise.then(() => { resolved = true; });
+ await Promise.resolve(); // Allow microtasks to run
+ expect(resolved).toBe(false);
+
+ vi.advanceTimersByTime(500);
+ await promise;
+ expect(resolved).toBe(true);
+
+ vi.useRealTimers();
+ });
+
+ it('should work with zero delay', async () => {
+ const start = Date.now();
+ await delay(0);
+ const end = Date.now();
+
+ // Should resolve almost immediately
+ expect(end - start).toBeLessThan(10);
+ });
+
+ it('should work with non-integer values', async () => {
+ vi.useFakeTimers();
+
+ const promise = delay(100.5);
+ vi.advanceTimersByTime(100.5);
+ await promise;
+
+ // Should not throw an error
+ expect(true).toBe(true);
+
+ vi.useRealTimers();
+ });
+ });
+
+ describe('integration tests', () => {
+ it('should create round-trip date conversion', () => {
+ const original = getCurrentFormattedDate();
+ const converted = toDateFromFormattedDateStr(original);
+ const backToString = getCurrentFormattedDate();
+
+ // The dates should be very close (within a second or two)
+ const originalParts = original.split('-').map(Number);
+ const backParts = backToString.split('-').map(Number);
+
+ expect(originalParts[0]).toBe(backParts[0]); // Year
+ expect(originalParts[1]).toBe(backParts[1]); // Month
+ expect(originalParts[2]).toBe(backParts[2]); // Day
+ });
+ });
+});
\ No newline at end of file
diff --git a/packages/runtime/tests/core/utils/general.utils.test.ts b/packages/runtime/tests/core/utils/general.utils.test.ts
new file mode 100644
index 00000000..797c1a55
--- /dev/null
+++ b/packages/runtime/tests/core/utils/general.utils.test.ts
@@ -0,0 +1,69 @@
+/**
+ * Tests for general utilities - following KISS principle
+ */
+import { describe, it, expect, vi } from 'vitest';
+import {
+ uid,
+ hasKeyTemplateVar,
+ parseTemplate,
+ fsExists,
+} from '@core/utils/general.utils';
+
+vi.mock('fs/promises', () => ({
+ default: { access: vi.fn() },
+}));
+
+describe('General Utils', () => {
+ describe('uid', () => {
+ it('generates unique strings', () => {
+ const id1 = uid();
+ const id2 = uid();
+
+ expect(id1).not.toBe(id2);
+ expect(id1).toMatch(/^[A-Z0-9]+$/);
+ });
+ });
+
+ describe('hasKeyTemplateVar', () => {
+ it('detects KEY template variables', () => {
+ expect(hasKeyTemplateVar('{{KEY(test)}}')).toBe(true);
+ expect(hasKeyTemplateVar('{{normal}}')).toBe(false);
+ expect(hasKeyTemplateVar('')).toBe(false);
+ });
+ });
+
+ describe('parseTemplate', () => {
+ it('replaces template variables', () => {
+ const result = parseTemplate('Hello {{name}}', { name: 'John' });
+ expect(result).toBe('Hello John');
+ });
+
+ it('preserves KEY variables', () => {
+ const result = parseTemplate('{{KEY(secret)}} {{name}}', { name: 'John' });
+ expect(result).toBe('{{KEY(secret)}} John');
+ });
+
+ it('handles false values', () => {
+ const result = parseTemplate('{{active}}', { active: false });
+ expect(result).toBe('false');
+ });
+ });
+
+ describe('fsExists', () => {
+ it('returns true when file exists', async () => {
+ const fs = await import('fs/promises');
+ (fs.default.access as any).mockResolvedValue(undefined);
+
+ const result = await fsExists('/test/path');
+ expect(result).toBe(true);
+ });
+
+ it('returns false when file does not exist', async () => {
+ const fs = await import('fs/promises');
+ (fs.default.access as any).mockRejectedValue(new Error('ENOENT'));
+
+ const result = await fsExists('/missing');
+ expect(result).toBe(false);
+ });
+ });
+});
\ No newline at end of file
diff --git a/packages/runtime/tests/integration/api.test.ts b/packages/runtime/tests/integration/api.test.ts
new file mode 100644
index 00000000..15be8783
--- /dev/null
+++ b/packages/runtime/tests/integration/api.test.ts
@@ -0,0 +1,68 @@
+/**
+ * Simple API integration tests
+ */
+import { describe, it, expect, vi } from 'vitest';
+import request from 'supertest';
+import express from 'express';
+
+describe('API Integration', () => {
+ const createTestApp = () => {
+ const app = express();
+ app.use(express.json());
+
+ // Simple test routes
+ app.get('/health', (req, res) => {
+ res.json({ status: 'ok' });
+ });
+
+ app.get('/models', (req, res) => {
+ res.setHeader('x-models-hash', 'test-hash');
+ res.json({ 'gpt-4': { name: 'GPT-4' } });
+ });
+
+ app.get('/models/custom/:teamId', (req, res) => {
+ const { teamId } = req.params;
+ if (teamId === 'invalid') {
+ return res.status(403).json({ error: 'Access denied' });
+ }
+ res.json({ 'custom-model': { name: 'Custom' } });
+ });
+
+ return app;
+ };
+
+ it('returns health status', async () => {
+ const app = createTestApp();
+
+ await request(app).get('/health').expect(200).expect({ status: 'ok' });
+ });
+
+ it('returns models with hash header', async () => {
+ const app = createTestApp();
+
+ const response = await request(app)
+ .get('/models')
+ .expect(200)
+ .expect('x-models-hash', 'test-hash')
+ .expect({ 'gpt-4': { name: 'GPT-4' } });
+ });
+
+ it('handles team access control', async () => {
+ const app = createTestApp();
+
+ // Valid team
+ await request(app)
+ .get('/models/custom/team123')
+ .expect(200)
+ .expect({ 'custom-model': { name: 'Custom' } });
+
+ // Invalid team
+ await request(app).get('/models/custom/invalid').expect(403).expect({ error: 'Access denied' });
+ });
+
+ it('handles 404 for unknown routes', async () => {
+ const app = createTestApp();
+
+ await request(app).get('/unknown').expect(404);
+ });
+});
diff --git a/packages/runtime/tests/mocks/sre.mock.ts b/packages/runtime/tests/mocks/sre.mock.ts
new file mode 100644
index 00000000..a0bde438
--- /dev/null
+++ b/packages/runtime/tests/mocks/sre.mock.ts
@@ -0,0 +1,42 @@
+import { vi } from 'vitest';
+/**
+ * Simple SRE library mocks
+ */
+
+// Mock SRE exports - simple and focused
+vi.mock('@smythos/sre', () => ({
+ Logger: vi.fn(() => ({
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ })),
+
+ AgentProcess: {
+ load: vi.fn(() => ({
+ run: vi.fn().mockResolvedValue({ data: { result: 'success' } }),
+ })),
+ },
+
+ ConnectorService: {
+ getCacheConnector: vi.fn(() => ({
+ user: vi.fn(() => ({
+ set: vi.fn().mockResolvedValue(true),
+ })),
+ })),
+ getModelsProviderConnector: vi.fn(() => ({
+ requester: vi.fn(() => ({
+ getModels: vi.fn().mockResolvedValue({
+ 'gpt-4': { name: 'GPT-4' },
+ }),
+ getCustomModels: vi.fn().mockResolvedValue({}),
+ })),
+ })),
+ },
+
+ AccessCandidate: {
+ user: vi.fn(id => ({ type: 'user', id })),
+ team: vi.fn(id => ({ type: 'team', id })),
+ },
+
+ version: '1.0.0-test',
+}));
diff --git a/packages/runtime/tests/services/agent.test.ts b/packages/runtime/tests/services/agent.test.ts
new file mode 100644
index 00000000..a696b69a
--- /dev/null
+++ b/packages/runtime/tests/services/agent.test.ts
@@ -0,0 +1,57 @@
+/**
+ * Simple agent service tests
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { createMockRequest, createMockAgent } from '../setup';
+import '../mocks/sre.mock';
+
+describe('Agent Services', () => {
+ describe('processAgentRequest', () => {
+ let processAgentRequest: any;
+
+ beforeEach(async () => {
+ vi.resetModules();
+ const module = await import('@agent-runner/services/agent-request-handler');
+ processAgentRequest = module.processAgentRequest;
+ });
+
+ it('returns 404 for missing agent', async () => {
+ const result = await processAgentRequest(null, createMockRequest());
+ expect(result).toEqual({ status: 404, data: 'Agent not found' });
+ });
+
+ it('blocks debug headers', async () => {
+ const agent = createMockAgent();
+ const req = createMockRequest({
+ header: vi.fn(name => (name === 'X-DEBUG-RUN' ? 'true' : undefined)),
+ socket: { on: vi.fn() },
+ });
+
+ const result = await processAgentRequest(agent, req);
+ expect(result).toEqual({ status: 403, data: 'Debug functions are not supported' });
+ });
+
+ it('rejects invalid paths', async () => {
+ const agent = createMockAgent();
+ const req = createMockRequest({
+ path: '/invalid',
+ socket: { on: vi.fn() },
+ });
+
+ const result = await processAgentRequest(agent, req);
+ expect(result.status).toBe(404);
+ });
+
+ it('processes valid requests', async () => {
+ const agent = createMockAgent();
+ const req = createMockRequest({
+ path: '/api/test',
+ socket: { on: vi.fn() },
+ _agent: agent,
+ });
+
+ const result = await processAgentRequest(agent, req);
+ expect(result).toEqual({ status: 200, data: { result: 'success' } });
+ });
+ });
+});
diff --git a/packages/runtime/tests/setup.ts b/packages/runtime/tests/setup.ts
new file mode 100644
index 00000000..ff042622
--- /dev/null
+++ b/packages/runtime/tests/setup.ts
@@ -0,0 +1,39 @@
+import { vi } from 'vitest';
+/**
+ * Test setup and utilities following KISS principle
+ */
+
+// Simple test environment setup
+process.env.NODE_ENV = 'test';
+process.env.PORT = '5053';
+process.env.SESSION_SECRET = 'test-secret';
+process.env.LOGTO_M2M_APP_ID = 'test-app-id';
+process.env.LOGTO_M2M_APP_SECRET = 'test-secret';
+process.env.LOGTO_SERVER = 'https://test-auth.example.com';
+process.env.LOGTO_API_RESOURCE = 'https://test-api.example.com';
+process.env.MIDDLEWARE_API_BASE_URL = 'https://test-middleware.example.com';
+
+// Simple mock factories
+export const createMockRequest = (overrides = {}) => ({
+ headers: {},
+ header: vi.fn(() => undefined),
+ path: '/api/test',
+ hostname: 'localhost',
+ socket: { on: vi.fn() },
+ ...overrides,
+});
+
+export const createMockResponse = () => ({
+ status: vi.fn().mockReturnThis(),
+ send: vi.fn().mockReturnThis(),
+ json: vi.fn().mockReturnThis(),
+ setHeader: vi.fn().mockReturnThis(),
+ locals: {},
+});
+
+export const createMockNext = () => vi.fn();
+
+export const createMockAgent = (overrides = {}) => ({
+ id: 'test-agent-id',
+ ...overrides,
+});