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.

51.6 KB
Raw Blame
// @vitest-environment node
import { SERVER_DEFAULT_HETEROGENEOUS_AGENT_TYPES } from '@lobechat/heterogeneous-agents';
import {
  LobeAnthropicAI,
  LobeAzureOpenAI,
  LobeBedrockAI,
  LobeComfyUI,
  LobeDeepSeekAI,
  LobeGoogleAI,
  LobeGroq,
  LobeMinimaxAI,
  LobeMistralAI,
  LobeMoonshotAI,
  LobeOllamaAI,
  LobeOpenAI,
  LobeOpenRouterAI,
  LobePerplexityAI,
  LobeQwenAI,
  LobeStepfunAI,
  LobeTogetherAI,
  LobeZeroOneAI,
  LobeZhipuAI,
  ModelRuntime,
} from '@lobechat/model-runtime';
import { LobeVertexAI } from '@lobechat/model-runtime/vertexai';
import { ChatErrorType, type ClientSecretPayload } from '@lobechat/types';
import { ModelProvider } from 'model-bank';
import { describe, expect, it, vi } from 'vitest';

import {
  buildPayloadFromKeyVaults,
  describeServerDefaultHeterogeneousModel,
  getServerDefaultHeterogeneousModels,
  initModelRuntimeFromServerConfig,
  initModelRuntimeWithUserPayload,
  resolveServerDefaultHeterogeneousModel,
  resolveServerModel,
} from './index';

const getServerGlobalConfig = vi.hoisted(() => vi.fn());

vi.mock('@/server/globalConfig', () => ({
  getServerAiProviderConfig: async (provider: string) =>
    (await getServerGlobalConfig()).aiProvider[provider],
}));

interface InspectableBedrockRuntime {
  client: {
    config: {
      token?: () => Promise<{ token: string }>;
    };
  };
  region: string;
}

// 模拟依赖项
vi.mock('@/envs/llm', () => ({
  getLLMConfig: vi.fn(() => ({
    // 确保为每个provider提供必要的配置信息
    OPENAI_API_KEY: 'test-openai-key',
    GOOGLE_API_KEY: 'test-google-key',

    AZURE_API_KEY: 'test-azure-key',
    AZURE_ENDPOINT: 'https://test-azure.openai.azure.com',

    ZHIPU_API_KEY: 'test.zhipu-key',
    MOONSHOT_API_KEY: 'test-moonshot-key',
    AWS_SECRET_ACCESS_KEY: 'test-aws-secret',
    AWS_ACCESS_KEY_ID: 'test-aws-id',
    AWS_REGION: 'test-aws-region',
    AWS_SESSION_TOKEN: 'test-aws-session-token',
    OLLAMA_PROXY_URL: 'https://test-ollama-url.local',
    PERPLEXITY_API_KEY: 'test-perplexity-key',
    DEEPSEEK_API_KEY: 'test-deepseek-key',
    ANTHROPIC_API_KEY: 'test-anthropic-key',
    MINIMAX_API_KEY: 'test-minimax-key',
    MISTRAL_API_KEY: 'test-mistral-key',
    OPENROUTER_API_KEY: 'test-openrouter-key',
    TOGETHERAI_API_KEY: 'test-togetherai-key',
    QINIU_API_KEY: 'test-qiniu-key',
    QWEN_API_KEY: 'test-qwen-key',
    STEPFUN_API_KEY: 'test-stepfun-key',
  })),
}));

describe('resolveServerModel', () => {
  it('accepts only an enabled deployment-owned chat model', async () => {
    getServerGlobalConfig.mockResolvedValue({
      aiProvider: {
        openai: {
          enabled: true,
          serverModelLists: [
            { enabled: true, id: 'gpt-server', type: 'chat' },
            { enabled: false, id: 'gpt-disabled', type: 'chat' },
          ],
        },
      },
    });

    await expect(resolveServerModel('openai', 'gpt-server')).resolves.toEqual({
      model: 'gpt-server',
      provider: 'openai',
    });
    await expect(resolveServerModel('openai', 'gpt-disabled')).rejects.toThrow(
      'selected server model is not available',
    );
  });

  it('preserves a deployment-owned model mapping', async () => {
    getServerGlobalConfig.mockResolvedValue({
      aiProvider: {
        azure: {
          enabled: true,
          serverModelLists: [
            {
              config: { deploymentName: 'prod-gpt' },
              enabled: true,
              id: 'gpt-4o',
              type: 'chat',
            },
          ],
        },
      },
    });

    await expect(resolveServerModel('azure', 'gpt-4o')).resolves.toEqual({
      deploymentName: 'prod-gpt',
      model: 'gpt-4o',
      provider: 'azure',
    });
  });
});

describe('getServerDefaultHeterogeneousModels', () => {
  it('discovers and resolves new tool-capable models without a deployment opt-in', async () => {
    getServerGlobalConfig.mockResolvedValue({
      aiProvider: {
        lobehub: {
          enabled: true,
          serverModelLists: [
            {
              abilities: { functionCall: true },
              enabled: true,
              id: 'deployment-new-model',
              type: 'chat',
            },
            { abilities: { functionCall: true }, enabled: true, id: 'kimi-k3', type: 'chat' },
          ],
        },
      },
    });
    expect(
      (await getServerDefaultHeterogeneousModels())['kimi-code'].map(({ model }) => model),
    ).toEqual(['deployment-new-model', 'kimi-k3']);
    await expect(
      resolveServerDefaultHeterogeneousModel('kimi-code', 'deployment-new-model'),
    ).resolves.toMatchObject({ model: 'deployment-new-model' });
  });

  it('offers newly enabled tool-capable catalog aliases to Kimi without an ID allowlist', async () => {
    const ids = ['minimax-m3', 'zai-org/GLM-5.2', 'doubao-seed-2-1-pro', 'qwen3.7-plus'];
    getServerGlobalConfig.mockResolvedValue({
      aiProvider: {
        lobehub: {
          enabled: true,
          serverModelLists: ids.map((id) => ({
            abilities: { functionCall: true },
            enabled: true,
            id,
            type: 'chat',
          })),
        },
      },
    });
    const models = await getServerDefaultHeterogeneousModels();
    expect(models['kimi-code'].map(({ model }) => model)).toEqual(ids);
    await expect(
      resolveServerDefaultHeterogeneousModel('kimi-code', ids[0]),
    ).resolves.toMatchObject({ model: ids[0] });
  });

  it('returns enabled chat models only from the LobeHub relay provider', async () => {
    getServerGlobalConfig.mockResolvedValue({
      aiProvider: {
        anthropic: {
          enabled: true,
          serverModelLists: [{ enabled: true, id: 'claude-opus-4-8', type: 'chat' }],
        },
        google: {
          enabled: true,
          serverModelLists: [{ enabled: true, id: 'gemini-server', type: 'chat' }],
        },
        lobehub: {
          enabled: true,
          serverModelLists: [
            { enabled: true, id: 'claude-sonnet-4-6', type: 'chat' },
            { enabled: false, id: 'claude-haiku-4-5', type: 'chat' },
            { enabled: true, id: 'gpt-5.4', type: 'chat' },
            { enabled: true, id: 'gpt-4o', type: 'chat' },
            { enabled: true, id: 'gemini-3.1-pro-preview', type: 'chat' },
            { enabled: true, id: 'claude-image', type: 'image' },
          ],
        },
        openai: {
          enabled: true,
          serverModelLists: [{ enabled: true, id: 'gpt-5.4', type: 'chat' }],
        },
      },
    });

    const models = await getServerDefaultHeterogeneousModels();
    for (const agentType of SERVER_DEFAULT_HETEROGENEOUS_AGENT_TYPES) {
      expect(models[agentType]).toEqual([
        { model: 'claude-sonnet-4-6' },
        { model: 'gpt-5.4' },
        { model: 'gpt-4o' },
        { model: 'gemini-3.1-pro-preview' },
      ]);
    }
  });

  it('offers every enabled chat relay model to every agent, Codex included', async () => {
    getServerGlobalConfig.mockResolvedValue({
      aiProvider: {
        lobehub: {
          enabled: true,
          serverModelLists: [
            { abilities: { functionCall: true }, enabled: true, id: 'kimi-k2.6', type: 'chat' },
            {
              abilities: { functionCall: true },
              enabled: true,
              id: 'deepseek-v4-flash',
              type: 'chat',
            },
            {
              abilities: { functionCall: true },
              enabled: true,
              id: 'deepseek-v4-pro',
              type: 'chat',
            },
            {
              abilities: { functionCall: true },
              enabled: true,
              id: 'glm-5.2',
              type: 'chat',
            },
            {
              abilities: { functionCall: true },
              enabled: true,
              id: 'gemini-3.1-pro-preview',
              type: 'chat',
            },
            { abilities: { reasoning: true }, enabled: true, id: 'no-tools-model', type: 'chat' },
            { abilities: { functionCall: true }, enabled: false, id: 'kimi-k3', type: 'chat' },
            { abilities: { functionCall: true }, enabled: true, id: 'kimi-image', type: 'image' },
          ],
        },
      },
    });

    const models = await getServerDefaultHeterogeneousModels();
    for (const agentType of SERVER_DEFAULT_HETEROGENEOUS_AGENT_TYPES) {
      expect(models[agentType]).toEqual([
        { model: 'kimi-k2.6' },
        { model: 'deepseek-v4-flash' },
        { model: 'deepseek-v4-pro' },
        { model: 'glm-5.2' },
        { model: 'gemini-3.1-pro-preview' },
        { model: 'no-tools-model' },
      ]);
    }
  });

  it('offers tool-capable GPT and Gemini models to Kimi without a profile allowlist', async () => {
    const toolCapableModels = [
      'gpt-5.6-sol',
      'gpt-5.6-terra',
      'gpt-5.6-luna',
      'gpt-5.5',
      'gpt-5.5-pro',
      'gemini-3.7-flash',
      'gemini-3.6-flash',
      'gemini-3.5-flash-lite',
      'gemini-3.1-pro-preview',
    ];
    getServerGlobalConfig.mockResolvedValue({
      aiProvider: {
        lobehub: {
          enabled: true,
          serverModelLists: toolCapableModels.map((id) => ({
            abilities: { functionCall: true },
            enabled: true,
            id,
            type: 'chat',
          })),
        },
      },
    });

    const models = await getServerDefaultHeterogeneousModels();

    expect(models['kimi-code']).toEqual(toolCapableModels.map((model) => ({ model })));
    expect(models['claude-code']).toEqual(toolCapableModels.map((model) => ({ model })));
  });

  it('excludes explicit tool incompatibility regardless of legacy deployment profile metadata', async () => {
    getServerGlobalConfig.mockResolvedValue({
      aiProvider: {
        lobehub: {
          enabled: true,
          serverModelLists: [
            {
              abilities: { functionCall: true },
              agentCompatibility: {
                serverDefaultHeterogeneousProfiles: ['kimi-code/anthropic-v1'],
              },
              enabled: true,
              id: 'private-kimi-model',
              type: 'chat',
            },
            {
              abilities: { functionCall: true },
              agentCompatibility: { serverDefaultHeterogeneousProfiles: [] },
              enabled: true,
              id: 'kimi-k3',
              type: 'chat',
            },
            {
              abilities: { functionCall: false },
              agentCompatibility: {
                serverDefaultHeterogeneousProfiles: ['kimi-code/anthropic-v1'],
              },
              enabled: true,
              id: 'no-tools-model',
              type: 'chat',
            },
          ],
        },
      },
    });

    await expect(getServerDefaultHeterogeneousModels()).resolves.toMatchObject({
      'kimi-code': [{ model: 'private-kimi-model' }, { model: 'kimi-k3' }],
    });
  });

  it('does not advertise hidden runtime-only models', async () => {
    getServerGlobalConfig.mockResolvedValue({
      aiProvider: {
        lobehub: {
          enabled: true,
          serverModelLists: [
            { abilities: { functionCall: true }, enabled: true, id: 'kimi-k3', type: 'chat' },
            {
              abilities: { functionCall: true },
              enabled: true,
              id: 'lobehub-onboarding-v1',
              type: 'chat',
              visible: false,
            },
          ],
        },
      },
    });

    const models = await getServerDefaultHeterogeneousModels();
    for (const agentType of SERVER_DEFAULT_HETEROGENEOUS_AGENT_TYPES) {
      expect(models[agentType]).toEqual([{ model: 'kimi-k3' }]);
    }
  });

  it('accepts arbitrary chat model ids when the relay catalog declares no abilities', async () => {
    getServerGlobalConfig.mockResolvedValue({
      aiProvider: {
        lobehub: {
          enabled: true,
          serverModelLists: [
            { enabled: true, id: 'claude-sonnet-4-6', type: 'chat' },
            { enabled: true, id: 'kimi-k2.6', type: 'chat' },
            { enabled: true, id: 'custom-claude-alias', type: 'chat' },
            { enabled: true, id: 'o3-pro', type: 'chat' },
          ],
        },
      },
    });

    const models = await getServerDefaultHeterogeneousModels();
    for (const agentType of SERVER_DEFAULT_HETEROGENEOUS_AGENT_TYPES) {
      expect(models[agentType]).toEqual([
        { model: 'claude-sonnet-4-6' },
        { model: 'kimi-k2.6' },
        { model: 'custom-claude-alias' },
        { model: 'o3-pro' },
      ]);
    }
  });
});

describe('describeServerDefaultHeterogeneousModel', () => {
  it('describes a compatible model from its card and marks native Responses models', async () => {
    getServerGlobalConfig.mockResolvedValue({
      aiProvider: {
        lobehub: {
          enabled: true,
          serverModelLists: [
            {
              abilities: { functionCall: true, reasoning: true, vision: true },
              contextWindowTokens: 262_144,
              displayName: 'Kimi K3',
              enabled: true,
              id: 'kimi-k3',
              maxOutput: 32_768,
              type: 'chat',
            },
            { enabled: true, id: 'gpt-6-sol', type: 'chat' },
            { abilities: { reasoning: true }, enabled: true, id: 'no-tools-model', type: 'chat' },
          ],
        },
      },
    });

    await expect(describeServerDefaultHeterogeneousModel('codex', 'kimi-k3')).resolves.toEqual({
      abilities: { reasoning: true, vision: true },
      contextWindowTokens: 262_144,
      displayName: 'Kimi K3',
      maxOutput: 32_768,
      model: 'kimi-k3',
      nativeResponses: false,
    });
    await expect(describeServerDefaultHeterogeneousModel('codex', 'gpt-6-sol')).resolves.toEqual({
      abilities: { reasoning: false, vision: false },
      model: 'gpt-6-sol',
      nativeResponses: true,
    });
    await expect(
      describeServerDefaultHeterogeneousModel('codex', 'no-tools-model'),
    ).resolves.toEqual({
      abilities: { reasoning: true, vision: false },
      model: 'no-tools-model',
      nativeResponses: false,
    });
  });
});

describe('resolveServerDefaultHeterogeneousModel', () => {
  it.each([
    { abilities: { functionCall: true }, id: 'new-tool-model', supported: true },
    { id: 'kimi-k3', supported: true },
    { id: 'custom-claude-alias', supported: true },
    { id: 'o3-pro', supported: true },
    { abilities: { functionCall: false }, id: 'deepseek-v4-pro', supported: false },
    { abilities: { functionCall: false }, id: 'claude-sonnet-4-6', supported: false },
    { abilities: { functionCall: false }, id: 'o3-pro', supported: false },
    { abilities: { functionCall: true }, enabled: false, id: 'disabled-model', supported: false },
    { abilities: { functionCall: true }, id: 'hidden-model', supported: false, visible: false },
    { abilities: { functionCall: true }, id: 'image-model', supported: false, type: 'image' },
  ])(
    'uses the same chat model policy for discovery, resolution and description: $id',
    async ({ supported, ...model }) => {
      getServerGlobalConfig.mockResolvedValue({
        aiProvider: {
          lobehub: {
            enabled: true,
            serverModelLists: [{ enabled: true, type: 'chat', ...model }],
          },
        },
      });

      const models = await getServerDefaultHeterogeneousModels();
      for (const agentType of SERVER_DEFAULT_HETEROGENEOUS_AGENT_TYPES) {
        expect(models[agentType]).toEqual(supported ? [{ model: model.id }] : []);

        if (supported) {
          await expect(
            resolveServerDefaultHeterogeneousModel(agentType, model.id),
          ).resolves.toMatchObject({
            model: model.id,
            provider: 'lobehub',
          });
          await expect(
            describeServerDefaultHeterogeneousModel(agentType, model.id),
          ).resolves.toMatchObject({
            model: model.id,
          });
        } else {
          await expect(resolveServerDefaultHeterogeneousModel(agentType, model.id)).rejects.toThrow(
            /not available|not compatible/,
          );
          await expect(
            describeServerDefaultHeterogeneousModel(agentType, model.id),
          ).rejects.toThrow(/not available|not compatible/);
        }
      }
    },
  );

  it('accepts chat models from the LobeHub relay provider regardless of ingress protocol', async () => {
    getServerGlobalConfig.mockResolvedValue({
      aiProvider: {
        anthropic: {
          enabled: true,
          serverModelLists: [{ enabled: true, id: 'claude-sonnet-4-6', type: 'chat' }],
        },
        lobehub: {
          enabled: true,
          serverModelLists: [
            { enabled: true, id: 'claude-sonnet-4-6', type: 'chat' },
            { enabled: true, id: 'gpt-5.4', type: 'chat' },
            { enabled: true, id: 'gpt-4o', type: 'chat' },
          ],
        },
        openai: {
          enabled: true,
          serverModelLists: [{ enabled: true, id: 'gpt-5.4', type: 'chat' }],
        },
      },
    });

    await expect(
      resolveServerDefaultHeterogeneousModel('claude-code', 'claude-sonnet-4-6'),
    ).resolves.toMatchObject({ model: 'claude-sonnet-4-6', provider: 'lobehub' });
    await expect(resolveServerDefaultHeterogeneousModel('codex', 'gpt-5.4')).resolves.toMatchObject(
      { model: 'gpt-5.4', provider: 'lobehub' },
    );
    await expect(
      resolveServerDefaultHeterogeneousModel('codex', 'claude-sonnet-4-6'),
    ).resolves.toMatchObject({ model: 'claude-sonnet-4-6', provider: 'lobehub' });

    await expect(
      resolveServerDefaultHeterogeneousModel('claude-code', 'gpt-5.4'),
    ).resolves.toMatchObject({ model: 'gpt-5.4', provider: 'lobehub' });
    await expect(
      resolveServerDefaultHeterogeneousModel('kimi-code', 'gpt-5.4'),
    ).resolves.toMatchObject({ model: 'gpt-5.4', provider: 'lobehub' });
    await expect(resolveServerDefaultHeterogeneousModel('codex', 'gpt-4o')).resolves.toMatchObject({
      model: 'gpt-4o',
      provider: 'lobehub',
    });
  });

  it('accepts a tool-capable third-party relay model for Kimi without attestation', async () => {
    getServerGlobalConfig.mockResolvedValue({
      aiProvider: {
        lobehub: {
          enabled: true,
          serverModelLists: [
            {
              abilities: { functionCall: true },
              enabled: true,
              id: 'kimi-k2.6',
              maxOutput: 65_536,
              type: 'chat',
            },
            { abilities: { reasoning: true }, enabled: true, id: 'no-tools-model', type: 'chat' },
          ],
        },
      },
    });

    await expect(
      resolveServerDefaultHeterogeneousModel('claude-code', 'kimi-k2.6'),
    ).resolves.toEqual({
      maxOutput: 65_536,
      model: 'kimi-k2.6',
      provider: 'lobehub',
      supportsAdaptiveThinking: false,
    });
    await expect(
      resolveServerDefaultHeterogeneousModel('kimi-code', 'kimi-k2.6'),
    ).resolves.toMatchObject({ maxOutput: 65_536, model: 'kimi-k2.6', provider: 'lobehub' });
    await expect(resolveServerDefaultHeterogeneousModel('pi', 'kimi-k2.6')).resolves.toMatchObject({
      model: 'kimi-k2.6',
      provider: 'lobehub',
    });
    await expect(
      resolveServerDefaultHeterogeneousModel('grok-build', 'kimi-k2.6'),
    ).resolves.toMatchObject({ model: 'kimi-k2.6', provider: 'lobehub' });
    await expect(
      resolveServerDefaultHeterogeneousModel('trae', 'kimi-k2.6'),
    ).resolves.toMatchObject({ model: 'kimi-k2.6', provider: 'lobehub' });

    await expect(
      resolveServerDefaultHeterogeneousModel('codex', 'kimi-k2.6'),
    ).resolves.toMatchObject({ model: 'kimi-k2.6', provider: 'lobehub' });
    await expect(
      resolveServerDefaultHeterogeneousModel('codex', 'no-tools-model'),
    ).resolves.toMatchObject({ model: 'no-tools-model', provider: 'lobehub' });
    await expect(
      resolveServerDefaultHeterogeneousModel('claude-code', 'no-tools-model'),
    ).resolves.toMatchObject({ model: 'no-tools-model', provider: 'lobehub' });
  });

  it('keeps hidden runtime aliases resolvable but rejects them for heterogeneous agents', async () => {
    getServerGlobalConfig.mockResolvedValue({
      aiProvider: {
        lobehub: {
          enabled: true,
          serverModelLists: [
            {
              abilities: { functionCall: true },
              enabled: true,
              id: 'lobehub-onboarding-v1',
              type: 'chat',
              visible: false,
            },
          ],
        },
      },
    });

    await expect(resolveServerModel('lobehub', 'lobehub-onboarding-v1')).resolves.toEqual({
      model: 'lobehub-onboarding-v1',
      provider: 'lobehub',
    });
    await expect(
      resolveServerDefaultHeterogeneousModel('claude-code', 'lobehub-onboarding-v1'),
    ).rejects.toThrow('not compatible with this heterogeneous agent');
  });

  it('preserves the deployment model mapping for a relay selection', async () => {
    getServerGlobalConfig.mockResolvedValue({
      aiProvider: {
        lobehub: {
          enabled: true,
          serverModelLists: [
            {
              abilities: { functionCall: true },
              config: { deploymentName: 'kimi-prod' },
              enabled: true,
              id: 'kimi-k2.6',
              type: 'chat',
            },
          ],
        },
      },
    });

    await expect(
      resolveServerDefaultHeterogeneousModel('claude-code', 'kimi-k2.6'),
    ).resolves.toEqual({
      deploymentName: 'kimi-prod',
      model: 'kimi-k2.6',
      provider: 'lobehub',
      supportsAdaptiveThinking: false,
    });
  });
});

describe('initModelRuntimeFromServerConfig', () => {
  it('initializes the LobeHub router directly without protocol-provider credentials', async () => {
    const runtime = {} as ModelRuntime;
    const initialize = vi.spyOn(ModelRuntime, 'initializeWithProvider').mockReturnValue(runtime);

    await expect(
      initModelRuntimeFromServerConfig({ actorUserId: 'user-1', workspaceId: 'workspace-1' }),
    ).resolves.toBe(runtime);

    expect(initialize).toHaveBeenCalledWith(
      ModelProvider.LobeHub,
      { userId: 'user-1', workspaceId: 'workspace-1' },
      expect.anything(),
    );
    initialize.mockRestore();
  });
});

/**
 * Test cases for function initModelRuntimeWithUserPayload
 * this method will use ModelRuntime from `@lobechat/model-runtime`
 * and method `getLlmOptionsFromPayload` to initialize runtime
 * with user payload. Test case below will test both the methods
 */
describe('initModelRuntimeWithUserPayload method', () => {
  describe('should initialize with options correctly', () => {
    it('OpenAI provider: with apikey and endpoint', async () => {
      const jwtPayload: ClientSecretPayload = {
        apiKey: 'user-openai-key',
        baseURL: 'https://user-endpoint.test/v1',
      };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.OpenAI, jwtPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeOpenAI);
      expect(runtime['_runtime'].baseURL).toBe(jwtPayload.baseURL);
    });

    it('rejects an invalid user baseURL as a bad request before SDK initialization', () => {
      let thrownError: unknown;

      try {
        initModelRuntimeWithUserPayload(ModelProvider.OpenAI, {
          apiKey: 'user-openai-key',
          baseURL: 'https://api.example.com /v1/chat/completions',
        });
      } catch (error) {
        thrownError = error;
      }

      expect(thrownError).toEqual({
        error: { message: 'Invalid provider baseURL' },
        errorType: ChatErrorType.BadRequest,
      });
    });

    it('Azure AI provider: with apikey, endpoint and apiversion', async () => {
      const jwtPayload: ClientSecretPayload = {
        apiKey: 'user-azure-key',
        baseURL: 'https://user-azure.openai.azure.com',
        azureApiVersion: '2024-06-01',
      };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Azure, jwtPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeAzureOpenAI);
      expect(runtime['_runtime'].baseURL).toBe('https://user-azure.openai.azure.com/openai/v1');
    });

    it('Custom provider should use runtimeProvider to init', async () => {
      const jwtPayload: ClientSecretPayload = {
        apiKey: 'user-azure-key',
        azureApiVersion: '2024-06-01',
        baseURL: 'https://user-azure.openai.azure.com',
        runtimeProvider: ModelProvider.Azure,
      };
      const runtime = await initModelRuntimeWithUserPayload('custom-provider', jwtPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeAzureOpenAI);
      expect(runtime['_runtime'].baseURL).toBe('https://user-azure.openai.azure.com/openai/v1');
    });

    it('ZhiPu AI provider: with apikey', async () => {
      const jwtPayload: ClientSecretPayload = { apiKey: 'zhipu.user-key' };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.ZhiPu, jwtPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeZhipuAI);
    });

    it('Google provider: with apikey', async () => {
      const jwtPayload: ClientSecretPayload = { apiKey: 'user-google-key' };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Google, jwtPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeGoogleAI);
    });

    it('Moonshot AI provider: with apikey', async () => {
      const jwtPayload: ClientSecretPayload = { apiKey: 'user-moonshot-key' };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Moonshot, jwtPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeMoonshotAI);
    });

    it('Qwen AI provider: with apikey and default endpoint', async () => {
      const jwtPayload: ClientSecretPayload = { apiKey: 'user-qwen-key' };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Qwen, jwtPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeQwenAI);
      expect(runtime['_runtime'].baseURL).toBe('https://dashscope.aliyuncs.com/compatible-mode/v1');
    });

    it('Vertex AI provider: with service account json', async () => {
      const credentials = {
        client_email: '[email protected]',
        private_key: '-----BEGIN PRIVATE KEY-----\nTEST\n-----END PRIVATE KEY-----\n',
        project_id: 'test-project',
        type: 'service_account',
      };
      const payload: ClientSecretPayload = { apiKey: JSON.stringify(credentials) };
      const initSpy = vi
        .spyOn(LobeVertexAI, 'initFromVertexAI')
        .mockImplementation((options: any) => {
          expect(options.project).toBe('test-project');
          expect(options.googleAuthOptions?.credentials?.private_key).toContain('TEST');

          return new LobeGoogleAI({
            apiKey: 'avoid-error',
            client: {} as any,
            isVertexAi: true,
          });
        });

      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.VertexAI, payload);

      expect(initSpy).toHaveBeenCalledTimes(1);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeGoogleAI);

      initSpy.mockRestore();
    });

    it('Bedrock AI provider: with apikey, awsAccessKeyId, awsSecretAccessKey, awsRegion', async () => {
      const jwtPayload: ClientSecretPayload = {
        apiKey: 'user-bedrock-key',
        awsAccessKeyId: 'user-aws-id',
        awsSecretAccessKey: 'user-aws-secret',
        awsRegion: 'user-aws-region',
      };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Bedrock, jwtPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeBedrockAI);
    });

    it('Bedrock AI provider: with API key only', async () => {
      const jwtPayload: ClientSecretPayload = {
        apiKey: 'user-bedrock-api-key',
        awsRegion: 'us-east-1',
      };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Bedrock, jwtPayload);

      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeBedrockAI);
    });

    it('Bedrock AI provider: picks one API key with server key selection', async () => {
      const apiKey = 'user-bedrock-api-key-a,user-bedrock-api-key-b';
      const jwtPayload: ClientSecretPayload = {
        apiKey,
        awsRegion: 'us-east-1',
      };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Bedrock, jwtPayload);
      const bedrockRuntime = runtime['_runtime'] as unknown as InspectableBedrockRuntime;
      const token = await bedrockRuntime.client.config.token?.();

      expect(apiKey.split(',')).toContain(token?.token);
    });

    it('Bedrock AI provider: with legacy AWS credentials only', async () => {
      const jwtPayload: ClientSecretPayload = {
        awsAccessKeyId: 'user-aws-id',
        awsSecretAccessKey: 'user-aws-secret',
        awsRegion: 'user-aws-region',
      };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Bedrock, jwtPayload);

      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeBedrockAI);
    });

    it('Bedrock AI provider: falls back to env credentials when only region is provided', async () => {
      const jwtPayload: ClientSecretPayload = {
        awsRegion: 'custom-aws-region',
      };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Bedrock, jwtPayload);

      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeBedrockAI);
      expect((runtime['_runtime'] as unknown as InspectableBedrockRuntime).region).toBe(
        'custom-aws-region',
      );
    });

    it('Ollama provider: with endpoint', async () => {
      const jwtPayload: ClientSecretPayload = { baseURL: 'http://user-ollama-url' };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Ollama, jwtPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeOllamaAI);
      expect(runtime['_runtime']['baseURL']).toEqual(jwtPayload.baseURL);
    });

    it('Perplexity AI provider: with apikey', async () => {
      const jwtPayload: ClientSecretPayload = { apiKey: 'user-perplexity-key' };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Perplexity, jwtPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobePerplexityAI);
    });

    it('Anthropic AI provider: with apikey', async () => {
      const jwtPayload: ClientSecretPayload = { apiKey: 'user-anthropic-key' };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Anthropic, jwtPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeAnthropicAI);
    });

    it('Minimax AI provider: with apikey', async () => {
      const jwtPayload: ClientSecretPayload = { apiKey: 'user-minimax-key' };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Minimax, jwtPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeMinimaxAI);
    });

    it('Mistral AI provider: with apikey', async () => {
      const jwtPayload: ClientSecretPayload = { apiKey: 'user-mistral-key' };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Mistral, jwtPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeMistralAI);
    });

    it('OpenRouter AI provider: with apikey', async () => {
      const jwtPayload: ClientSecretPayload = { apiKey: 'user-openrouter-key' };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.OpenRouter, jwtPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeOpenRouterAI);
    });

    it('DeepSeek AI provider: with apikey', async () => {
      const jwtPayload: ClientSecretPayload = { apiKey: 'user-deepseek-key' };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.DeepSeek, jwtPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeDeepSeekAI);
    });

    it('Together AI provider: with apikey', async () => {
      const jwtPayload: ClientSecretPayload = { apiKey: 'user-togetherai-key' };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.TogetherAI, jwtPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeTogetherAI);
    });

    it('ZeroOne AI provider: with apikey', async () => {
      const jwtPayload = { apiKey: 'user-zeroone-key' };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.ZeroOne, jwtPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeZeroOneAI);
    });

    it('Groq AI provider: with apikey', async () => {
      const jwtPayload = { apiKey: 'user-zeroone-key' };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Groq, jwtPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeGroq);
    });

    it('Stepfun AI provider: with apikey', async () => {
      const jwtPayload = { apiKey: 'user-stepfun-key' };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Stepfun, jwtPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeStepfunAI);
    });

    it('ComfyUI provider: with multiple auth types', async () => {
      // Test basic auth
      const basicAuthPayload: ClientSecretPayload = {
        authType: 'basic',
        username: 'test-user',
        password: 'test-pass',
        baseURL: 'http://localhost:8188',
      };
      let runtime = await initModelRuntimeWithUserPayload(ModelProvider.ComfyUI, basicAuthPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeComfyUI);
      expect(runtime['_runtime'].baseURL).toBe(basicAuthPayload.baseURL);

      // Test bearer auth
      const bearerAuthPayload: ClientSecretPayload = {
        authType: 'bearer',
        apiKey: 'test-token',
        baseURL: 'http://localhost:8188',
      };
      runtime = await initModelRuntimeWithUserPayload(ModelProvider.ComfyUI, bearerAuthPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeComfyUI);

      // Test custom auth
      const customAuthPayload: ClientSecretPayload = {
        authType: 'custom',
        customHeaders: { 'X-API-Key': 'secret123' },
        baseURL: 'http://localhost:8188',
      };
      runtime = await initModelRuntimeWithUserPayload(ModelProvider.ComfyUI, customAuthPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeComfyUI);

      // Test none auth
      const noAuthPayload: ClientSecretPayload = {
        authType: 'none',
        baseURL: 'http://localhost:8188',
      };
      runtime = await initModelRuntimeWithUserPayload(ModelProvider.ComfyUI, noAuthPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeComfyUI);
    });

    it('Unknown Provider: with apikey and endpoint, should initialize to OpenAi', async () => {
      const jwtPayload: ClientSecretPayload = {
        apiKey: 'user-unknown-key',
        baseURL: 'https://user-unknown-endpoint.test/v1',
      };
      const runtime = await initModelRuntimeWithUserPayload('unknown', jwtPayload);
      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeOpenAI);
      expect(runtime['_runtime'].baseURL).toBe(jwtPayload.baseURL);
    });
  });

  describe('should initialize without some options', () => {
    it('OpenAI provider: without apikey', async () => {
      const jwtPayload: ClientSecretPayload = {};
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.OpenAI, jwtPayload);
      expect(runtime['_runtime']).toBeInstanceOf(LobeOpenAI);
    });

    it('Azure AI Provider: without apikey', async () => {
      const jwtPayload: ClientSecretPayload = {
        azureApiVersion: 'test-azure-api-version',
      };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Azure, jwtPayload);

      expect(runtime['_runtime']).toBeInstanceOf(LobeAzureOpenAI);
    });

    it('ZhiPu AI provider: without apikey', async () => {
      const jwtPayload: ClientSecretPayload = {};
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.ZhiPu, jwtPayload);

      // 假设 LobeZhipuAI 是 ZhiPu 提供者的实现类
      expect(runtime['_runtime']).toBeInstanceOf(LobeZhipuAI);
    });

    it('Google provider: without apikey', async () => {
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Google, {});

      // 假设 LobeGoogleAI 是 Google 提供者的实现类
      expect(runtime['_runtime']).toBeInstanceOf(LobeGoogleAI);
    });

    it('Moonshot AI provider: without apikey', async () => {
      const jwtPayload: ClientSecretPayload = {};
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Moonshot, jwtPayload);

      // 假设 LobeMoonshotAI 是 Moonshot 提供者的实现类
      expect(runtime['_runtime']).toBeInstanceOf(LobeMoonshotAI);
    });

    it('Qwen AI provider: without apikey', async () => {
      const jwtPayload: ClientSecretPayload = {};
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Qwen, jwtPayload);

      // 假设 LobeQwenAI 是 Qwen 提供者的实现类
      expect(runtime['_runtime']).toBeInstanceOf(LobeQwenAI);
    });

    it('Bedrock AI provider: without apikey', async () => {
      const jwtPayload = {};
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Bedrock, jwtPayload);

      // 假设 LobeBedrockAI 是 Bedrock 提供者的实现类
      expect(runtime['_runtime']).toBeInstanceOf(LobeBedrockAI);
    });

    it('Ollama provider: without endpoint', async () => {
      const jwtPayload = {};
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Ollama, jwtPayload);

      // 假设 LobeOllamaAI 是 Ollama 提供者的实现类
      expect(runtime['_runtime']).toBeInstanceOf(LobeOllamaAI);
    });

    it('Perplexity AI provider: without apikey', async () => {
      const jwtPayload = {};
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Perplexity, jwtPayload);

      // 假设 LobePerplexityAI 是 Perplexity 提供者的实现类
      expect(runtime['_runtime']).toBeInstanceOf(LobePerplexityAI);
    });

    it('Anthropic AI provider: without apikey', async () => {
      const jwtPayload = {};
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Anthropic, jwtPayload);

      // 假设 LobeAnthropicAI 是 Anthropic 提供者的实现类
      expect(runtime['_runtime']).toBeInstanceOf(LobeAnthropicAI);
    });

    it('Minimax AI provider: without apikey', async () => {
      const jwtPayload = {};
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Minimax, jwtPayload);

      // 假设 LobeMistralAI 是 Mistral 提供者的实现类
      expect(runtime['_runtime']).toBeInstanceOf(LobeMinimaxAI);
    });

    it('Mistral AI provider: without apikey', async () => {
      const jwtPayload = {};
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Mistral, jwtPayload);

      // 假设 LobeMistralAI 是 Mistral 提供者的实现类
      expect(runtime['_runtime']).toBeInstanceOf(LobeMistralAI);
    });

    it('OpenRouter AI provider: without apikey', async () => {
      const jwtPayload = {};
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.OpenRouter, jwtPayload);

      // 假设 LobeOpenRouterAI 是 OpenRouter 提供者的实现类
      expect(runtime['_runtime']).toBeInstanceOf(LobeOpenRouterAI);
    });

    it('DeepSeek AI provider: without apikey', async () => {
      const jwtPayload = {};
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.DeepSeek, jwtPayload);

      // 假设 LobeDeepSeekAI 是 DeepSeek 提供者的实现类
      expect(runtime['_runtime']).toBeInstanceOf(LobeDeepSeekAI);
    });

    it('Stepfun AI provider: without apikey', async () => {
      const jwtPayload = {};
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Stepfun, jwtPayload);

      // 假设 LobeDeepSeekAI 是 DeepSeek 提供者的实现类
      expect(runtime['_runtime']).toBeInstanceOf(LobeStepfunAI);
    });

    it('Together AI provider: without apikey', async () => {
      const jwtPayload = {};
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.TogetherAI, jwtPayload);

      // 假设 LobeTogetherAI 是 TogetherAI 提供者的实现类
      expect(runtime['_runtime']).toBeInstanceOf(LobeTogetherAI);
    });

    it('OpenAI provider: without apikey with OPENAI_PROXY_URL', async () => {
      process.env.OPENAI_PROXY_URL = 'https://proxy.example.com/v1';

      const jwtPayload: ClientSecretPayload = {};
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.OpenAI, jwtPayload);
      expect(runtime['_runtime']).toBeInstanceOf(LobeOpenAI);
      // 应返回 OPENAI_PROXY_URL
      expect(runtime['_runtime'].baseURL).toBe('https://proxy.example.com/v1');
    });

    it('Qwen AI provider: without apiKey and endpoint with OPENAI_PROXY_URL', async () => {
      process.env.OPENAI_PROXY_URL = 'https://proxy.example.com/v1';

      const jwtPayload: ClientSecretPayload = {};
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Qwen, jwtPayload);

      // 假设 LobeQwenAI 是 Qwen 提供者的实现类
      expect(runtime['_runtime']).toBeInstanceOf(LobeQwenAI);
      // endpoint 不存在,应返回 DEFAULT_BASE_URL
      expect(runtime['_runtime'].baseURL).toBe('https://dashscope.aliyuncs.com/compatible-mode/v1');
    });

    it('ComfyUI provider: without user payload (using environment variables)', async () => {
      const jwtPayload: ClientSecretPayload = {};
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.ComfyUI, jwtPayload);

      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeComfyUI);
      // Should use environment variable defaults
      expect(runtime['_runtime'].baseURL).toBe('http://127.0.0.1:8000');
    });

    it('ComfyUI provider: partial payload (mixed with env vars)', async () => {
      const jwtPayload: ClientSecretPayload = {
        baseURL: 'http://custom-comfyui:8188',
        // authType, username, password will come from env vars
      };
      const runtime = await initModelRuntimeWithUserPayload(ModelProvider.ComfyUI, jwtPayload);

      expect(runtime).toBeInstanceOf(ModelRuntime);
      expect(runtime['_runtime']).toBeInstanceOf(LobeComfyUI);
      expect(runtime['_runtime'].baseURL).toBe('http://custom-comfyui:8188');
    });

    it('Unknown Provider: requires user credentials', () => {
      expect(() => initModelRuntimeWithUserPayload('unknown', {})).toThrow();
    });
  });
});

/**
 * Test cases for buildPayloadFromKeyVaults function
 * This function builds ClientSecretPayload based on runtimeProvider (sdkType)
 * to ensure provider-specific fields are correctly forwarded
 */
describe('buildPayloadFromKeyVaults', () => {
  describe('should build payload with correct fields based on runtimeProvider', () => {
    it('OpenAI compatible: returns apiKey, baseURL and runtimeProvider', () => {
      const keyVaults = {
        apiKey: 'test-api-key',
        baseURL: 'https://custom-endpoint.com/v1',
      };
      const payload = buildPayloadFromKeyVaults(keyVaults, ModelProvider.OpenAI);

      expect(payload).toEqual({
        apiKey: 'test-api-key',
        baseURL: 'https://custom-endpoint.com/v1',
        runtimeProvider: ModelProvider.OpenAI,
      });
    });

    it('ChatGPT: returns the OAuth access token and account id', () => {
      const keyVaults = {
        oauthAccessToken: 'oauth-access-token',
        oauthAccountId: 'chatgpt-account-id',
      };
      const payload = buildPayloadFromKeyVaults(keyVaults, ModelProvider.ChatGPT);

      expect(payload).toEqual({
        apiKey: 'oauth-access-token',
        chatgptAccountId: 'chatgpt-account-id',
        runtimeProvider: ModelProvider.ChatGPT,
      });
    });

    it('Azure: returns apiKey, baseURL and runtimeProvider', () => {
      const keyVaults = {
        apiKey: 'azure-api-key',
        baseURL: 'https://my-azure.openai.azure.com',
        apiVersion: '2024-06-01',
        endpoint: 'https://fallback-endpoint.com',
      };
      const payload = buildPayloadFromKeyVaults(keyVaults, ModelProvider.Azure);

      expect(payload).toEqual({
        apiKey: 'azure-api-key',
        baseURL: 'https://my-azure.openai.azure.com',
        runtimeProvider: ModelProvider.Azure,
      });
    });

    it('Azure: uses endpoint as fallback when baseURL is not provided', () => {
      const keyVaults = {
        apiKey: 'azure-api-key',
        endpoint: 'https://fallback-endpoint.com',
        apiVersion: '2024-06-01',
      };
      const payload = buildPayloadFromKeyVaults(keyVaults, ModelProvider.Azure);

      expect(payload.baseURL).toBe('https://fallback-endpoint.com');
    });

    it('Cloudflare: returns apiKey, cloudflareBaseURLOrAccountID and runtimeProvider', () => {
      const keyVaults = {
        apiKey: 'cloudflare-api-key',
        baseURLOrAccountID: 'my-account-id',
      };
      const payload = buildPayloadFromKeyVaults(keyVaults, ModelProvider.Cloudflare);

      expect(payload).toEqual({
        apiKey: 'cloudflare-api-key',
        cloudflareBaseURLOrAccountID: 'my-account-id',
        runtimeProvider: ModelProvider.Cloudflare,
      });
    });

    it('Bedrock: returns AWS credentials and runtimeProvider', () => {
      const keyVaults = {
        accessKeyId: 'aws-access-key',
        secretAccessKey: 'aws-secret-key',
        region: 'us-east-1',
        sessionToken: 'session-token',
      };
      const payload = buildPayloadFromKeyVaults(keyVaults, ModelProvider.Bedrock);

      expect(payload).toEqual({
        apiKey: undefined,
        awsAccessKeyId: 'aws-access-key',
        awsRegion: 'us-east-1',
        awsSecretAccessKey: 'aws-secret-key',
        awsSessionToken: 'session-token',
        runtimeProvider: ModelProvider.Bedrock,
      });
    });

    it('Bedrock: returns API key and runtimeProvider', () => {
      const keyVaults = {
        apiKey: 'bedrock-api-key',
        region: 'us-east-1',
      };
      const payload = buildPayloadFromKeyVaults(keyVaults, ModelProvider.Bedrock);

      expect(payload).toEqual({
        apiKey: 'bedrock-api-key',
        awsAccessKeyId: undefined,
        awsRegion: 'us-east-1',
        awsSecretAccessKey: undefined,
        awsSessionToken: undefined,
        runtimeProvider: ModelProvider.Bedrock,
      });
    });

    it('Ollama: returns baseURL and runtimeProvider', () => {
      const keyVaults = {
        baseURL: 'http://localhost:11434',
      };
      const payload = buildPayloadFromKeyVaults(keyVaults, ModelProvider.Ollama);

      expect(payload).toEqual({
        baseURL: 'http://localhost:11434',
        runtimeProvider: ModelProvider.Ollama,
      });
    });

    it('VertexAI: returns apiKey, baseURL, vertexAIRegion and runtimeProvider', () => {
      const keyVaults = {
        apiKey: 'vertex-credentials-json',
        baseURL: 'https://vertex-endpoint.com',
        region: 'us-central1',
      };
      const payload = buildPayloadFromKeyVaults(keyVaults, ModelProvider.VertexAI);

      expect(payload).toEqual({
        apiKey: 'vertex-credentials-json',
        baseURL: 'https://vertex-endpoint.com',
        runtimeProvider: ModelProvider.VertexAI,
        vertexAIRegion: 'us-central1',
      });
    });

    it('ComfyUI: returns all auth fields and runtimeProvider', () => {
      const keyVaults = {
        apiKey: 'comfyui-api-key',
        authType: 'bearer',
        baseURL: 'http://localhost:8188',
        customHeaders: { 'X-Custom': 'header' },
        password: 'pass',
        username: 'user',
      } as const;
      const payload = buildPayloadFromKeyVaults(keyVaults, ModelProvider.ComfyUI);

      expect(payload).toEqual({
        apiKey: 'comfyui-api-key',
        authType: 'bearer',
        baseURL: 'http://localhost:8188',
        customHeaders: { 'X-Custom': 'header' },
        password: 'pass',
        runtimeProvider: ModelProvider.ComfyUI,
        username: 'user',
      });
    });

    it('Unknown provider: falls back to default with apiKey, baseURL and runtimeProvider', () => {
      const keyVaults = {
        apiKey: 'unknown-api-key',
        baseURL: 'https://unknown-endpoint.com',
      };
      const payload = buildPayloadFromKeyVaults(keyVaults, 'unknown-provider');

      expect(payload).toEqual({
        apiKey: 'unknown-api-key',
        baseURL: 'https://unknown-endpoint.com',
        runtimeProvider: 'unknown-provider',
      });
    });
  });

  describe('custom provider with sdkType should include provider-specific fields', () => {
    it('custom provider with Azure sdkType keeps apiKey and baseURL only', () => {
      const keyVaults = {
        apiKey: 'custom-azure-key',
        baseURL: 'https://custom-azure.openai.azure.com',
        apiVersion: '2024-06-01',
      };
      // Simulates a custom provider where runtimeProvider is resolved to 'azure'
      const payload = buildPayloadFromKeyVaults(keyVaults, ModelProvider.Azure);

      expect(payload.apiKey).toBe('custom-azure-key');
      expect(payload.baseURL).toBe('https://custom-azure.openai.azure.com');
      expect(payload.runtimeProvider).toBe(ModelProvider.Azure);
    });

    it('custom provider with Cloudflare sdkType includes cloudflareBaseURLOrAccountID', () => {
      const keyVaults = {
        apiKey: 'custom-cloudflare-key',
        baseURLOrAccountID: 'custom-account-id',
      };
      // Simulates a custom provider where runtimeProvider is resolved to 'cloudflare'
      const payload = buildPayloadFromKeyVaults(keyVaults, ModelProvider.Cloudflare);

      expect(payload.cloudflareBaseURLOrAccountID).toBe('custom-account-id');
      expect(payload.runtimeProvider).toBe(ModelProvider.Cloudflare);
    });

    it('custom provider with Bedrock sdkType includes AWS credentials', () => {
      const keyVaults = {
        accessKeyId: 'custom-aws-id',
        secretAccessKey: 'custom-aws-secret',
        region: 'eu-west-1',
      };
      // Simulates a custom provider where runtimeProvider is resolved to 'bedrock'
      const payload = buildPayloadFromKeyVaults(keyVaults, ModelProvider.Bedrock);

      expect(payload.awsAccessKeyId).toBe('custom-aws-id');
      expect(payload.awsSecretAccessKey).toBe('custom-aws-secret');
      expect(payload.awsRegion).toBe('eu-west-1');
      expect(payload.runtimeProvider).toBe(ModelProvider.Bedrock);
    });

    it('custom provider with Ollama sdkType includes baseURL', () => {
      const keyVaults = {
        baseURL: 'http://custom-ollama:11434',
      };
      // Simulates a custom provider where runtimeProvider is resolved to 'ollama'
      const payload = buildPayloadFromKeyVaults(keyVaults, ModelProvider.Ollama);

      expect(payload.baseURL).toBe('http://custom-ollama:11434');
      expect(payload.runtimeProvider).toBe(ModelProvider.Ollama);
    });

    it('custom provider with VertexAI sdkType includes vertexAIRegion', () => {
      const keyVaults = {
        apiKey: 'custom-vertex-creds',
        region: 'asia-northeast1',
      };
      // Simulates a custom provider where runtimeProvider is resolved to 'vertexai'
      const payload = buildPayloadFromKeyVaults(keyVaults, ModelProvider.VertexAI);

      expect(payload.vertexAIRegion).toBe('asia-northeast1');
      expect(payload.runtimeProvider).toBe(ModelProvider.VertexAI);
    });
  });
});