Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

21.6 KB
Raw Blame
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
  ModelFactory,
  cleanUpstreamErrorMessage,
  createCustomFetch,
  describeTransportError,
} from '../model-factory'
import type { ProviderObject } from '@janhq/core'
import { invoke } from '@tauri-apps/api/core'
import { createOpenAICompatible } from '@ai-sdk/openai-compatible'
import { i18n } from '@/i18n/react-i18next-compat'
import { PermissionDispatcher } from '@/lib/extensions/dispatcher'
import { createProviderFetch } from '@/lib/extensions/http'
import { fakeHttp, redirectTo } from '@/lib/extensions/__tests__/fake-http'

const mockGlobalFetch = vi.fn()

// Mock the Tauri invoke function
vi.mock('@tauri-apps/api/core', () => ({
  invoke: vi.fn(),
}))

// Mock the Tauri HTTP plugin
vi.mock('@tauri-apps/plugin-http', () => ({
  fetch: vi.fn(),
}))

// Mock the AI SDK providers
vi.mock('@ai-sdk/openai-compatible', () => {
  const MockChatModel = vi.fn().mockImplementation(() => ({
    type: 'openai-compatible-chat',
    modelId: 'apple/on-device',
  }))
  return {
    createOpenAICompatible: vi.fn(() => ({
      languageModel: vi.fn(() => ({ type: 'openai-compatible' })),
    })),
    OpenAICompatibleChatLanguageModel: MockChatModel,
    MetadataExtractor: vi.fn(),
  }
})

vi.mock('@ai-sdk/anthropic', () => ({
  createAnthropic: vi.fn(() => vi.fn(() => ({ type: 'anthropic' }))),
}))

vi.mock('@ai-sdk/google', () => ({
  createGoogleGenerativeAI: vi.fn((cfg: any) => {
    ;(globalThis as any).__capturedGoogleCfg = cfg
    return vi.fn(() => ({ type: 'google' }))
  }),
}))

vi.mock('ai', () => ({
  wrapLanguageModel: vi.fn(({ model }) => model),
  extractReasoningMiddleware: vi.fn(() => ({})),
}))

const mockStartModel = vi.fn().mockResolvedValue(undefined)

const hostMock = vi.hoisted(() => ({
  providerFetch: vi.fn(),
}))
vi.mock('@/lib/extensions/host', () => ({
  getExtensionHost: () => hostMock,
}))

vi.mock('@/hooks/useServiceHub', () => ({
  useServiceStore: {
    getState: () => ({
      serviceHub: {
        models: () => ({ startModel: mockStartModel }),
      },
    }),
  },
}))

const mockedInvoke = vi.mocked(invoke)
const mockedCreateOpenAICompatible = vi.mocked(createOpenAICompatible)

describe('ModelFactory', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    mockStartModel.mockResolvedValue(undefined)
    mockGlobalFetch.mockResolvedValue(new Response('{}'))
    vi.stubGlobal('fetch', mockGlobalFetch)
  })

  describe('createModel', () => {
    it('should create an Anthropic model for anthropic provider', async () => {
      const provider: ProviderObject = {
        provider: 'anthropic',
        api_key: 'test-api-key',
        base_url: 'https://api.anthropic.com/v1',
        models: [],
        settings: [],
        active: true,
        custom_header: [
          { header: 'anthropic-version', value: '2023-06-01' },
        ],
      }

      const model = await ModelFactory.createModel('claude-3-opus', provider)
      expect(model).toBeDefined()
      expect(model.type).toBe('anthropic')
    })

    it('routes a custom provider with api_type="anthropic" through the Anthropic SDK', async () => {
      const { createAnthropic } = await import('@ai-sdk/anthropic')
      vi.mocked(createAnthropic).mockClear()
      const provider: ProviderObject = {
        provider: 'my-claude-proxy',
        api_type: 'anthropic',
        api_key: 'sk-proxy',
        base_url: 'https://proxy.example.com/v1',
        models: [],
        settings: [],
        active: true,
      }

      const model = await ModelFactory.createModel('claude-3-haiku', provider)
      expect(model).toBeDefined()
      expect(model.type).toBe('anthropic')
      expect(createAnthropic).toHaveBeenCalledWith(
        expect.objectContaining({
          apiKey: 'sk-proxy',
          baseURL: 'https://proxy.example.com/v1',
        })
      )
    })

    it('routes google and gemini through the native @ai-sdk/google client and strips the /openai suffix', async () => {
      const { createGoogleGenerativeAI } = await import('@ai-sdk/google')
      for (const name of ['google', 'gemini'] as const) {
        vi.mocked(createGoogleGenerativeAI).mockClear()
        const provider: ProviderObject = {
          provider: name,
          api_key: 'test-api-key',
          base_url: 'https://generativelanguage.googleapis.com/v1beta/openai',
          models: [],
          settings: [],
          active: true,
        }

        const model = await ModelFactory.createModel('gemini-2.5-flash', provider)
        expect(model).toEqual({ type: 'google' })
        expect(createGoogleGenerativeAI).toHaveBeenCalledWith(
          expect.objectContaining({
            apiKey: 'test-api-key',
            baseURL: 'https://generativelanguage.googleapis.com/v1beta',
          })
        )
      }
    })

    it('should create an OpenAI-compatible model for openai provider', async () => {
      const provider: ProviderObject = {
        provider: 'openai',
        api_key: 'test-api-key',
        base_url: 'https://api.openai.com/v1',
        models: [],
        settings: [],
        active: true,
      }

      const model = await ModelFactory.createModel('gpt-4', provider)
      expect(model).toBeDefined()
    })

    it('should create an OpenAI-compatible model for groq provider', async () => {
      const provider: ProviderObject = {
        provider: 'groq',
        api_key: 'test-api-key',
        base_url: 'https://api.groq.com/openai/v1',
        models: [],
        settings: [],
        active: true,
      }

      const model = await ModelFactory.createModel('llama-3', provider)
      expect(model).toBeDefined()
      expect(model.type).toBe('openai-compatible')
    })

    it('should create an OpenAI-compatible model for minimax provider', async () => {
      const provider: ProviderObject = {
        provider: 'minimax',
        api_key: 'test-api-key',
        base_url: 'https://api.minimax.io/v1',
        models: [],
        settings: [],
        active: true,
      }

      const model = await ModelFactory.createModel('MiniMax-M2.7', provider)
      expect(model).toBeDefined()
      expect(model.type).toBe('openai-compatible')
    })

    it('should handle custom headers for OpenAI-compatible providers', async () => {
      const provider: ProviderObject = {
        provider: 'custom',
        api_key: 'test-api-key',
        base_url: 'https://custom.api.com/v1',
        models: [],
        settings: [],
        active: true,
        custom_header: [
          { header: 'X-Custom-Header', value: 'custom-value' },
        ],
      }

      const model = await ModelFactory.createModel('custom-model', provider)
      expect(model).toBeDefined()
      expect(model.type).toBe('openai-compatible')
    })
  })

})

describe('cleanUpstreamErrorMessage', () => {
  it('extracts the final "Error:" line from a Jinja stack trace', () => {
    const raw =
      "\n------------\nWhile executing CallExpression at line 1, column 226 in source:\n...op.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user...\n                                           ^\nError: Jinja Exception: Conversation roles must alternate user/assistant/user/assistant/..."
    expect(cleanUpstreamErrorMessage(raw)).toBe(
      'Jinja Exception: Conversation roles must alternate user/assistant/user/assistant/...'
    )
  })

  it('passes through a clean message unchanged', () => {
    const raw =
      'Unable to generate parser for this template. Automatic parser generation failed: JSON schema conversion failed: Unrecognized schema: "string"'
    expect(cleanUpstreamErrorMessage(raw)).toBe(raw)
  })

  it('strips a leading rule and "While executing" prelude when no Error: line exists', () => {
    const raw =
      '------------\nWhile executing X at line 1:\n bad stuff here\n         ^\nsomething broke'
    expect(cleanUpstreamErrorMessage(raw)).toBe('something broke')
  })

  it('returns non-string inputs as-is', () => {
    // @ts-expect-error intentional misuse
    expect(cleanUpstreamErrorMessage(null)).toBe(null)
  })
})

describe('describeTransportError', () => {
  it('maps reqwest "error sending request" to a connection message', () => {
    const msg = describeTransportError(
      new Error('error sending request for url (https://x/v1/chat/completions)')
    )
    expect(msg).toMatch(/connection failed|couldn't reach/i)
  })

  it('maps DNS failures to an address-resolution message', () => {
    const msg = describeTransportError(new Error('dns error: failed to lookup address'))
    expect(msg).toMatch(/could not be resolved/i)
  })

  it('maps timeouts to a timeout message', () => {
    expect(describeTransportError(new Error('operation timed out'))).toMatch(/timed out/i)
  })

  it('maps TLS errors to a secure-connection message', () => {
    expect(describeTransportError(new Error('invalid certificate'))).toMatch(/secure connection/i)
  })

  it('returns null for non-transport errors (HTTP/app errors)', () => {
    expect(describeTransportError(new Error('400 Bad Request: invalid model'))).toBeNull()
  })
})

describe('createCustomFetch — transport error wrapping', () => {
  it('rethrows transport failures with a friendly message and the url', async () => {
    const baseFetch: typeof globalThis.fetch = (async () => {
      throw new Error('error sending request for url (https://up/v1/chat/completions)')
    }) as typeof globalThis.fetch
    const wrapped = createCustomFetch(baseFetch, {}, true)
    await expect(
      wrapped('https://up/v1/chat/completions', { method: 'POST', body: '{}' })
    ).rejects.toThrow(/couldn't reach the provider.*https:\/\/up/i)
  })

  it('rethrows non-transport errors unchanged', async () => {
    const baseFetch: typeof globalThis.fetch = (async () => {
      throw new Error('boom unexpected')
    }) as typeof globalThis.fetch
    const wrapped = createCustomFetch(baseFetch, {}, true)
    await expect(
      wrapped('https://up/v1/chat/completions', { method: 'POST', body: '{}' })
    ).rejects.toThrow('boom unexpected')
  })
})

describe('ModelFactory — missing API key guard', () => {
  it('throws an actionable error instead of sending an empty credential', async () => {
    const provider = {
      provider: 'anthropic',
      base_url: 'https://api.anthropic.com/v1',
      api_key: '',
      models: [],
    } as unknown as ProviderObject
    await expect(
      ModelFactory.createModel('claude-opus-4-8', provider)
    ).rejects.toThrow(/No API key configured for anthropic/)
  })
})

describe('ModelFactory - extension providers', () => {
  const provider = {
    provider: 'acme.evil/chat',
    active: true,
    base_url: 'http://127.0.0.1:11999/v1',
    api_key: 'k',
    settings: [],
    models: [],
    source: { extensionId: 'acme.evil' },
  } as unknown as ProviderObject

  beforeEach(() => {
    vi.clearAllMocks()
    vi.stubGlobal('fetch', mockGlobalFetch)
  })

  it("runs inference on the extension's checked fetch, which refuses a 307 to the local API server", async () => {
    // What a hostile baseUrl would answer: a 307 that keeps the POST body
    // and lands on Jan's own server, which proxies with the user's keys.
    const server = fakeHttp(({ url }) =>
      url.includes(':11999')
        ? redirectTo(307, 'http://127.0.0.1:1337/v1/chat/completions')
        : { chunks: ['proxied'] }
    )
    const dispatcher = new PermissionDispatcher(() => 1337)
    dispatcher.grant('acme.evil', ['network:127.0.0.1'])
    hostMock.providerFetch.mockImplementation((extensionId: string) =>
      createProviderFetch({
        extensionId,
        http: server.http,
        checkUrl: (url) => dispatcher.checkUrl(extensionId, url),
      })
    )

    await ModelFactory.createModel('m', provider)
    expect(hostMock.providerFetch).toHaveBeenCalledWith('acme.evil', 'stream')
    const config = mockedCreateOpenAICompatible.mock.calls[0][0]
    expect(config.baseURL).toBe('http://127.0.0.1:11999/v1')
    await expect(
      config.fetch!('http://127.0.0.1:11999/v1/chat/completions', {
        method: 'POST',
        headers: { Authorization: 'Bearer k' },
        body: '{"model":"m","messages":[]}',
      })
    ).rejects.toMatchObject({ code: 'E_PERMISSION' })
    expect(server.urls()).toEqual(['http://127.0.0.1:11999/v1/chat/completions'])
    expect(server.headers().every((h) => h.cookie === undefined)).toBe(true)
    const { fetch: httpFetch } = await import('@tauri-apps/plugin-http')
    expect(httpFetch).not.toHaveBeenCalled()
    expect(mockGlobalFetch).not.toHaveBeenCalled()
  })

  it('refuses a provider whose extension has no network path', async () => {
    hostMock.providerFetch.mockReturnValue(undefined)
    await expect(ModelFactory.createModel('m', provider)).rejects.toThrow(
      i18n.t('model-errors:extensionProviderUnavailable', {
        provider: 'acme.evil/chat',
      })
    )
    expect(mockedCreateOpenAICompatible).not.toHaveBeenCalled()
  })
})

describe('createCustomFetch — named SSE event filtering scope', () => {
  const NAMED_EVENT_STREAM = [
    'event: message_start',
    'data: {"type":"message_start"}',
    '',
    'event: content_block_delta',
    'data: {"type":"content_block_delta"}',
    '',
  ].join('\n')

  function sseFetch(): typeof globalThis.fetch {
    return (async () =>
      new Response(NAMED_EVENT_STREAM, {
        status: 200,
        headers: { 'content-type': 'text/event-stream' },
      })) as typeof globalThis.fetch
  }

  it('passes named SSE events through untouched by default (native protocols)', async () => {
    const wrapped = createCustomFetch(sseFetch(), {})
    const res = await wrapped('https://api.anthropic.com/v1/messages', {
      method: 'POST',
      body: '{}',
    })
    expect(await res.text()).toBe(NAMED_EVENT_STREAM)
  })

  it('strips named SSE events when filterNamedSseEvents is enabled', async () => {
    const wrapped = createCustomFetch(sseFetch(), {}, false, undefined, true)
    const res = await wrapped('http://localhost:1337/v1/chat/completions', {
      method: 'POST',
      body: '{}',
    })
    expect(await res.text()).not.toContain('message_start')
  })
})

describe('createCustomFetch — max_tokens coercion', () => {
  async function captureSentBody(
    parameters: Record<string, unknown>,
    keepLlamacppOnly: boolean,
    bodyIn: Record<string, unknown>
  ): Promise<Record<string, unknown>> {
    const seen: { body?: string } = {}
    const baseFetch: typeof globalThis.fetch = (async (
      _input: RequestInfo | URL,
      init?: RequestInit
    ) => {
      seen.body = typeof init?.body === 'string' ? init.body : ''
      return new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } })
    }) as typeof globalThis.fetch
    const wrapped = createCustomFetch(baseFetch, parameters, keepLlamacppOnly)
    await wrapped('http://test/v1/chat/completions', {
      method: 'POST',
      body: JSON.stringify(bodyIn),
    })
    return JSON.parse(seen.body ?? '{}') as Record<string, unknown>
  }

  it('coerces max_tokens=0 to -1 when keepLlamacppOnly is true', async () => {
    const sent = await captureSentBody({}, true, { max_tokens: 0 })
    expect(sent.max_tokens).toBe(-1)
  })

  it('does not coerce when keepLlamacppOnly is false (non-llamacpp providers)', async () => {
    const sent = await captureSentBody({}, false, { max_tokens: 0 })
    expect(sent.max_tokens).toBe(0)
  })

  it('sets timings_per_token when keepLlamacppOnly and streaming', async () => {
    const sent = await captureSentBody({}, true, { stream: true })
    expect(sent.timings_per_token).toBe(true)
    expect(sent.return_progress).toBe(true)
  })

  it('does not set timings_per_token when not streaming', async () => {
    const sent = await captureSentBody({}, true, { stream: false })
    expect(sent.timings_per_token).toBeUndefined()
  })

  it('does not set timings_per_token for non-llamacpp providers', async () => {
    const sent = await captureSentBody({}, false, { stream: true })
    expect(sent.timings_per_token).toBeUndefined()
  })

  it('sets cache_prompt=true when keepLlamacppOnly is true', async () => {
    const sent = await captureSentBody({}, true, {})
    expect(sent.cache_prompt).toBe(true)
  })

  it('does not set cache_prompt for non-llamacpp providers', async () => {
    const sent = await captureSentBody({}, false, {})
    expect(sent.cache_prompt).toBeUndefined()
  })

  // The whole cross-session prompt cache depends on this field surviving the
  // trip to the engine; a filter that dropped it would disable the feature
  // silently, with nothing failing.
  it('passes thread_id through to the request body', async () => {
    const sent = await captureSentBody({ thread_id: 'thread-42' }, true, {})
    expect(sent.thread_id).toBe('thread-42')
  })

  it('preserves an explicit id_slot passed via parameters (title-gen path)', async () => {
    const sent = await captureSentBody({ id_slot: 3 }, true, {})
    expect(sent.id_slot).toBe(3)
  })

  it('leaves non-zero max_tokens alone', async () => {
    const sent = await captureSentBody({}, true, { max_tokens: 512 })
    expect(sent.max_tokens).toBe(512)
  })

  it('coerces max_tokens=0 even when it comes from injected parameters via max_output_tokens', async () => {
    const sent = await captureSentBody(
      { max_output_tokens: 0 },
      true,
      { messages: [] }
    )
    expect(sent.max_tokens).toBe(-1)
  })

  it('coerces string numeric params (text input) back to numbers', async () => {
    const sent = await captureSentBody(
      { max_output_tokens: '2048', dry_penalty_last_n: '-1' },
      true,
      { messages: [] }
    )
    expect(sent.max_tokens).toBe(2048)
    expect(sent.dry_penalty_last_n).toBe(-1)
  })

  it('coerces string "0" so the max_tokens=-1 rule still fires', async () => {
    const sent = await captureSentBody({ max_output_tokens: '0' }, true, {
      messages: [],
    })
    expect(sent.max_tokens).toBe(-1)
  })

  it('leaves non-numeric string params untouched', async () => {
    const sent = await captureSentBody({ max_output_tokens: '' }, false, {
      messages: [],
    })
    expect(sent.max_tokens).toBe('')
  })

  it('remaps dynatemp_exp to the llama-server wire name dynatemp_exponent', async () => {
    const sent = await captureSentBody({ dynatemp_exp: 1.5 }, true, {
      messages: [],
    })
    expect(sent.dynatemp_exponent).toBe(1.5)
    expect(sent.dynatemp_exp).toBeUndefined()
  })

  it('splits the samplers string param into an array on the wire', async () => {
    const sent = await captureSentBody(
      { samplers: 'top_k, typ_p ;top_p' },
      true,
      { messages: [] }
    )
    expect(sent.samplers).toEqual(['top_k', 'typ_p', 'top_p'])
  })

  it('omits samplers entirely when the string is empty', async () => {
    const sent = await captureSentBody({ samplers: '' }, true, {
      messages: [],
    })
    expect(sent.samplers).toBeUndefined()
  })

  it('forwards repeat_last_n, backend_sampling, and thinking_budget_tokens as-is', async () => {
    const sent = await captureSentBody(
      {
        repeat_last_n: 128,
        backend_sampling: true,
        thinking_budget_tokens: 4096,
      },
      true,
      { messages: [] }
    )
    expect(sent.repeat_last_n).toBe(128)
    expect(sent.backend_sampling).toBe(true)
    expect(sent.thinking_budget_tokens).toBe(4096)
  })
})

describe('createCustomFetch — llamacpp 500 handling', () => {
  function fetchReturning(
    status: number,
    body: string,
    contentType = 'application/json'
  ): typeof globalThis.fetch {
    return (async () =>
      new Response(body, {
        status,
        statusText: status === 500 ? 'Internal Server Error' : 'OK',
        headers: { 'content-type': contentType },
      })) as typeof globalThis.fetch
  }

  it('synthesizes an llamacpp error body when llamacpp returns 500 with empty body', async () => {
    const onErr = vi.fn()
    const wrapped = createCustomFetch(
      fetchReturning(500, '', 'text/plain'),
      {},
      true,
      onErr
    )
    const res = await wrapped('http://test/v1/chat/completions', {
      method: 'POST',
      body: '{}',
    })
    expect(res.status).toBe(500)
    expect(res.headers.get('content-type')).toBe('application/json')
    const parsed = await res.json()
    expect(parsed.error.message).toMatch(/model crashed and is being reloaded/i)
    expect(parsed.error.message).not.toMatch(/500|Internal Server Error|llama-server/i)
    expect(parsed.error.type).toBe('llamacpp_server_error')
    expect(onErr).toHaveBeenCalledTimes(1)
  })

  it('does not trigger reload on llamacpp 500 carrying a JSON error body (child alive, not a crash)', async () => {
    const onErr = vi.fn()
    const body = JSON.stringify({
      error: { code: 500, message: 'some inner error', type: 'server_error' },
    })
    const wrapped = createCustomFetch(fetchReturning(500, body), {}, true, onErr)
    await wrapped('http://test/v1/chat/completions', {
      method: 'POST',
      body: '{}',
    })
    expect(onErr).not.toHaveBeenCalled()
  })

  it('does not trigger the reload callback or synthesize a body for non-llamacpp 500', async () => {
    const onErr = vi.fn()
    const wrapped = createCustomFetch(
      fetchReturning(500, '', 'text/plain'),
      {},
      false,
      onErr
    )
    const res = await wrapped('http://test/v1/chat/completions', {
      method: 'POST',
      body: '{}',
    })
    expect(onErr).not.toHaveBeenCalled()
    expect(res.headers.get('content-type')).toBe('text/plain')
  })

  it('does not trigger the reload callback on llamacpp non-500 errors (e.g. 400)', async () => {
    const onErr = vi.fn()
    const body = JSON.stringify({
      error: { code: 400, message: 'bad request', type: 'invalid_request' },
    })
    const wrapped = createCustomFetch(fetchReturning(400, body), {}, true, onErr)
    await wrapped('http://test/v1/chat/completions', {
      method: 'POST',
      body: '{}',
    })
    expect(onErr).not.toHaveBeenCalled()
  })
})