Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

13.4 KB
Raw Blame
// @vitest-environment node
import { ModelProvider } from 'model-bank';
import type { Mock } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import * as modelParseModule from '../../utils/modelParse';
import { params } from './index';

// Mock external dependencies
vi.mock('../../utils/modelParse');

// Mock console methods
vi.spyOn(console, 'error').mockImplementation(() => {});
vi.spyOn(console, 'debug').mockImplementation(() => {});

describe('ZenMux Runtime', () => {
  let mockFetch: Mock;
  let mockProcessMultiProviderModelList: Mock;

  beforeEach(() => {
    // Setup fetch mock
    mockFetch = vi.fn();
    global.fetch = mockFetch;

    // Setup utility function mocks
    mockProcessMultiProviderModelList = vi.mocked(modelParseModule.processMultiProviderModelList);

    // Clear environment variables
    delete process.env.DEBUG_ZENMUX_CHAT_COMPLETION;
  });

  afterEach(() => {
    vi.clearAllMocks();
    delete process.env.DEBUG_ZENMUX_CHAT_COMPLETION;
  });

  describe('LobeZenMuxAI - custom features', () => {
    describe('Params Export', () => {
      it('should have correct provider ID', () => {
        expect(params.id).toBe(ModelProvider.ZenMux);
      });
    });

    describe('ChatCompletion HandlePayload', () => {
      it('should map reasoning_effort to reasoning.effort', () => {
        const payload = {
          model: 'gpt-4o',
          messages: [],
          reasoning_effort: 'high' as const,
        } as any;

        const result = params.chatCompletion?.handlePayload?.(payload);

        expect(result).toBeDefined();
        expect(result?.reasoning).toBeDefined();
        expect(result?.reasoning?.effort).toBe('high');
        expect(result?.reasoning_effort).toBeUndefined();
      });

      it('should map thinking.budget_tokens to reasoning.max_tokens', () => {
        const payload = {
          model: 'gpt-4o',
          messages: [],
          thinking: { budget_tokens: 2048, type: 'enabled' as const },
        } as any;

        const result = params.chatCompletion?.handlePayload?.(payload);

        expect(result).toBeDefined();
        expect(result?.reasoning).toBeDefined();
        expect(result?.reasoning?.max_tokens).toBe(2048);
        expect(result?.thinking).toBeUndefined();
      });

      it('should map thinking.type=enabled to reasoning.enabled=true', () => {
        const payload = {
          model: 'gpt-4o',
          messages: [],
          thinking: { budget_tokens: 1024, type: 'enabled' as const },
        } as any;

        const result = params.chatCompletion?.handlePayload?.(payload);

        expect(result).toBeDefined();
        expect(result?.reasoning).toBeDefined();
        expect(result?.reasoning?.enabled).toBe(true);
        expect(result?.thinking).toBeUndefined();
      });

      it('should not set reasoning.enabled when thinking.type=disabled', () => {
        const payload = {
          model: 'gpt-4o',
          messages: [],
          thinking: { budget_tokens: 1024, type: 'disabled' as const },
        } as any;

        const result = params.chatCompletion?.handlePayload?.(payload);

        expect(result).toBeDefined();
        // When thinking.type is 'disabled', max_tokens should be mapped and enabled should be false
        expect(result?.reasoning?.max_tokens).toBe(1024);
        expect(result?.reasoning?.enabled).toBe(false);
      });

      it('should map both reasoning_effort and thinking.budget_tokens together', () => {
        const payload = {
          model: 'gpt-4o',
          messages: [],
          reasoning_effort: 'high' as const,
          thinking: { budget_tokens: 2048, type: 'enabled' as const },
        } as any;

        const result = params.chatCompletion?.handlePayload?.(payload);

        expect(result).toBeDefined();
        expect(result?.reasoning).toBeDefined();
        expect(result?.reasoning?.effort).toBe('high');
        expect(result?.reasoning?.max_tokens).toBe(2048);
      });

      it('should preserve existing reasoning properties', () => {
        const payload = {
          model: 'gpt-4o',
          messages: [],
          reasoning: { summary: 'auto' },
          reasoning_effort: 'medium' as const,
        } as any;

        const result = params.chatCompletion?.handlePayload?.(payload);

        expect(result).toBeDefined();
        expect(result?.reasoning).toBeDefined();
        expect(result?.reasoning?.summary).toBe('auto');
        expect(result?.reasoning?.effort).toBe('medium');
      });

      it('should not include reasoning when no reasoning-related properties', () => {
        const payload = {
          model: 'gpt-4o',
          messages: [],
          temperature: 0.7,
        } as any;

        const result = params.chatCompletion?.handlePayload?.(payload);

        expect(result).toBeDefined();
        expect(result?.reasoning).toBeUndefined();
      });

      it('should preserve other payload properties', () => {
        const payload = {
          model: 'gpt-4o',
          messages: [],
          temperature: 0.7,
          top_p: 0.9,
          max_tokens: 1024,
          reasoning_effort: 'high' as const,
        } as any;

        const result = params.chatCompletion?.handlePayload?.(payload);

        expect(result).toBeDefined();
        expect(result?.temperature).toBe(0.7);
        expect(result?.top_p).toBe(0.9);
        expect(result?.max_tokens).toBe(1024);
        expect(result?.reasoning?.effort).toBe('high');
      });
    });

    describe('Routers Configuration', () => {
      it('should configure routers with correct endpoints', () => {
        const mockOptions = { baseURL: 'https://zenmux.ai/api/v1' };
        const routers = params.routers(mockOptions);

        expect(routers).toBeDefined();
        expect(Array.isArray(routers)).toBe(true);

        // Check anthropic router
        const anthropicRouter = routers.find((r) => r.apiType === 'anthropic');
        expect(anthropicRouter).toBeDefined();
        expect(anthropicRouter?.options.baseURL).toContain('/api/anthropic');

        // Check google router
        const googleRouter = routers.find((r) => r.apiType === 'google');
        expect(googleRouter).toBeDefined();
        expect(googleRouter?.options.baseURL).toContain('/api/vertex-ai');

        // Check openai router (default)
        const openaiRouter = routers.find((r) => r.apiType === 'openai');
        expect(openaiRouter).toBeDefined();
        expect(openaiRouter?.options.baseURL).toContain('/api/v1');
      });

      it('should strip version paths from baseURL', () => {
        const mockOptions = { baseURL: 'https://zenmux.ai/v1' };
        const routers = params.routers(mockOptions);

        const anthropicRouter = routers.find((r) => r.apiType === 'anthropic');
        expect(anthropicRouter?.options.baseURL).toBe('https://zenmux.ai/api/anthropic');
      });

      it('should use default baseURL when not provided', () => {
        const mockOptions = {}; // No baseURL provided
        const routers = params.routers(mockOptions);

        const anthropicRouter = routers.find((r) => r.apiType === 'anthropic');
        expect(anthropicRouter?.options.baseURL).toBe('https://zenmux.ai/api/anthropic');

        const googleRouter = routers.find((r) => r.apiType === 'google');
        expect(googleRouter?.options.baseURL).toBe('https://zenmux.ai/api/vertex-ai');

        const openaiRouter = routers.find((r) => r.apiType === 'openai');
        expect(openaiRouter?.options.baseURL).toBe('https://zenmux.ai/api/v1');
      });
    });
    describe('Models Function', () => {
      it('should fetch and process models correctly', async () => {
        const mockClient = {
          apiKey: 'test-key',
          baseURL: 'https://zenmux.ai/api/v1',
          models: {
            list: vi.fn().mockResolvedValue({
              data: [
                {
                  id: 'openai/gpt-4o-mini',
                  object: 'model',
                  created: 1755177025,
                  owned_by: 'openai',
                },
                {
                  id: 'anthropic/claude-3-5-sonnet-20241022',
                  object: 'model',
                  created: 1755177025,
                  owned_by: 'anthropic',
                },
              ],
            }),
          },
        } as any;

        // Mock processMultiProviderModelList to return processed models
        mockProcessMultiProviderModelList.mockResolvedValue([
          {
            id: 'openai/gpt-4o-mini',
            displayName: 'GPT-4o Mini',
            providerId: 'openai',
          },
          {
            id: 'anthropic/claude-3-5-sonnet-20241022',
            displayName: 'Claude 3.5 Sonnet',
            providerId: 'anthropic',
          },
        ] as any);

        const models = await params.models({ client: mockClient });

        expect(models).toBeDefined();
        expect(Array.isArray(models)).toBe(true);
        expect(models.length).toBeGreaterThan(0);
      });

      it('should map ZenMux capability metadata onto model cards before processing', async () => {
        const mockClient = {
          apiKey: 'test-key',
          baseURL: 'https://zenmux.ai/api/v1',
          models: {
            list: vi.fn().mockResolvedValue({
              data: [
                {
                  id: 'dots-studio/dots3-note-prev',
                  object: 'model',
                  created: 1786962877,
                  owned_by: 'dots-studio',
                  display_name: 'Dots Studio: Dots3-Note Preview (Free)',
                  input_modalities: ['text', 'image', 'video', 'audio'],
                  output_modalities: ['text'],
                  capabilities: { reasoning: true },
                  context_length: 393100,
                  pricings: {
                    completion: [{ value: 0, unit: 'perMTokens', currency: 'USD' }],
                    input_cache_read: [{ value: 0, unit: 'perMTokens', currency: 'USD' }],
                    prompt: [{ value: 0, unit: 'perMTokens', currency: 'USD' }],
                  },
                  publish_time: '2026-08-17',
                },
                {
                  id: 'z-ai/glm-5.3',
                  object: 'model',
                  created: 1786609177,
                  owned_by: 'z-ai',
                  input_modalities: ['text'],
                  output_modalities: ['text'],
                  capabilities: { reasoning: true },
                  context_length: 1000000,
                  pricings: {
                    completion: [
                      // tiered pricing: first perMTokens entry is the base tier
                      { value: 4.4, unit: 'perMTokens', currency: 'USD' },
                      { value: 8.8, unit: 'perMTokens', currency: 'USD', conditions: {} },
                    ],
                    prompt: [{ value: 1.4, unit: 'perMTokens', currency: 'USD' }],
                    web_search: [{ value: 0.01, unit: 'perCount', currency: 'USD' }],
                  },
                  publish_time: '2026-08-13',
                },
              ],
            }),
          },
        } as any;

        mockProcessMultiProviderModelList.mockResolvedValue([]);

        await params.models({ client: mockClient });

        expect(mockProcessMultiProviderModelList).toHaveBeenCalledWith(
          [
            expect.objectContaining({
              contextWindowTokens: 393100,
              id: 'dots-studio/dots3-note-prev',
              pricing: expect.objectContaining({ cachedInput: 0, input: 0, output: 0 }),
              reasoning: true,
              releasedAt: '2026-08-17',
              video: true,
              vision: true,
            }),
            expect.objectContaining({
              contextWindowTokens: 1000000,
              id: 'z-ai/glm-5.3',
              pricing: expect.objectContaining({ input: 1.4, output: 4.4 }),
              reasoning: true,
              video: false,
              vision: false,
            }),
          ],
          'zenmux',
        );
      });

      it('should leave capabilities undefined when ZenMux omits metadata fields', async () => {
        const mockClient = {
          apiKey: 'test-key',
          baseURL: 'https://zenmux.ai/api/v1',
          models: {
            list: vi.fn().mockResolvedValue({
              data: [
                {
                  id: 'openai/gpt-4o-mini',
                  object: 'model',
                  created: 1755177025,
                  owned_by: 'openai',
                },
              ],
            }),
          },
        } as any;

        mockProcessMultiProviderModelList.mockResolvedValue([]);

        await params.models({ client: mockClient });

        expect(mockProcessMultiProviderModelList).toHaveBeenCalledWith(
          [
            expect.objectContaining({
              id: 'openai/gpt-4o-mini',
              reasoning: undefined,
              video: undefined,
              vision: undefined,
            }),
          ],
          'zenmux',
        );
      });

      it('should handle empty model list', async () => {
        const mockClient = {
          apiKey: 'test-key',
          baseURL: 'https://zenmux.ai/api/v1',
          models: {
            list: vi.fn().mockResolvedValue({
              data: [],
            }),
          },
        } as any;

        // Mock processMultiProviderModelList
        mockProcessMultiProviderModelList.mockResolvedValue([]);

        const models = await params.models({ client: mockClient });

        expect(models).toBeDefined();
        expect(Array.isArray(models)).toBe(true);
        expect(models.length).toBe(0);
      });
    });
  });
});