import { existsSync } from 'fs'; import { describe, expect, test } from 'vitest'; import { applyConfigDefaults, DEFAULT_STOP_PORT, LLMSPY_DEFAULT_URL, llmspyAddress, llmspyRoute, parseCliArgs, parseListeningPids, reachableUrl, resolveModelName, serverEnv, tsxCliPath, } from '../../../bin/process-utils.js'; describe('reachableUrl', () => { test.each([ ['0.0.0.0', 'http://127.0.0.1:8001'], ['::', 'http://127.0.0.1:8001'], ['127.0.0.1', 'http://127.0.0.1:8001'], ['localhost', 'http://localhost:8001'], ['::1', 'http://[::1]:8001'], ])('%s is reached at %s', (host, url) => { expect(reachableUrl(host, 8001)).toBe(url); }); }); test('stop with no --port stops DEFAULT_STOP_PORT', () => { expect(parseCliArgs(['stop']).stopPort).toBe(DEFAULT_STOP_PORT); }); describe('tsxCliPath', () => { test('points at an existing tsx cli script', () => { const path = tsxCliPath(); expect(path).toMatch(/tsx[\\/]dist[\\/]cli\.mjs$/); expect(existsSync(path)).toBe(true); }); }); describe('resolveModelName', () => { test('the --model flag wins over the config default', () => { expect(resolveModelName('gemini', { defaultModel: 'claude' })).toBe( 'gemini', ); }); test('uses the config defaultModel when no flag is given', () => { expect(resolveModelName(undefined, { defaultModel: 'claude' })).toBe( 'claude', ); }); test('falls back to chatgpt when neither is set', () => { expect(resolveModelName(undefined, {})).toBe('chatgpt'); }); }); describe('parseCliArgs', () => { test('defaults to start with no arguments', () => { expect(parseCliArgs([])).toMatchObject({ command: 'start', modelName: undefined, customSettings: {}, foregroundMode: false, }); }); test('reads options after the start command', () => { const parsed = parseCliArgs([ 'start', '--model=claude', '--port', '3000', ]); expect(parsed.command).toBe('start'); expect(parsed.modelName).toBe('claude'); expect(parsed.customSettings).toEqual({ port: '3000' }); }); test('keeps the first option when the command is omitted', () => { expect(parseCliArgs(['--model=claude']).modelName).toBe('claude'); expect(parseCliArgs(['--model', 'gemini']).modelName).toBe('gemini'); expect(parseCliArgs(['--foreground', '--stream=true'])).toMatchObject({ command: 'start', foregroundMode: true, customSettings: { stream: 'true' }, }); }); test('reads the chaos options', () => { expect( parseCliArgs([ '--chaos=true', '--chaosFrequency', '3', '--chaosMode=random', '--chaosStatus=429', '--chaosKind=stream-stall', '--chaosAfterChunks', '0', ]).customSettings, ).toEqual({ chaos: 'true', chaosFrequency: '3', chaosMode: 'random', chaosStatus: '429', chaosKind: 'stream-stall', chaosAfterChunks: '0', }); }); test('stop takes its port from --port', () => { expect(parseCliArgs(['stop'])).toMatchObject({ command: 'stop', stopPort: 8001, }); expect(parseCliArgs(['stop', '--port=3000']).stopPort).toBe(3000); expect(parseCliArgs(['stop', '--port', '3000']).stopPort).toBe(3000); }); test('config accepts --model', () => { expect(parseCliArgs(['config', '--model=claude'])).toMatchObject({ showConfig: true, modelName: 'claude', }); }); test('help ignores other arguments', () => { for (const flag of ['help', '--help', '-h']) { expect(parseCliArgs([flag, '--model=claude'])).toMatchObject({ showHelp: true, modelName: undefined, }); } }); }); describe('applyConfigDefaults', () => { test('fills in the optional settings of a short preset', () => { const config = applyConfigDefaults( { models: { claude: { name: 'claude', endpoint: 'v1/messages', stream: true, responseDelay: { min: 300 }, }, }, }, 'claude', ); expect(config.models.claude).toEqual({ name: 'claude', model: 'mock-model', endpoint: 'v1/messages', responseType: 'lorem', maxLoremParas: 8, validateRequests: false, logRequests: false, maxLoggedRequests: 10, debug: false, stream: true, responseDelay: { min: 300, max: 0 }, embeddings: { enabled: false, dimensions: 128 }, chaos: { enabled: false, frequency: 1, mode: 'every', status: 500, kind: 'http', afterChunks: 2, }, }); expect(config.server).toEqual({ port: 8001, host: '0.0.0.0' }); }); const withChaos = (chaos: Record) => applyConfigDefaults( { models: { a: { name: 'openai', endpoint: 'chat', chaos } } }, 'a', ); test('fills in the chaos settings that are left out', () => { expect( withChaos({ enabled: true, frequency: 3 }).models.a.chaos, ).toEqual({ enabled: true, frequency: 3, mode: 'every', status: 500, kind: 'http', afterChunks: 2, }); expect( withChaos({ kind: 'stream-error', afterChunks: 0 }).models.a.chaos, ).toMatchObject({ kind: 'stream-error', afterChunks: 0 }); }); test.each([ [{ frequency: 0 }, 'chaos.frequency'], [{ frequency: 2.5 }, 'chaos.frequency'], [{ frequency: '3' }, 'chaos.frequency'], [{ mode: 'sometimes' }, 'chaos.mode'], [{ status: 200 }, 'chaos.status'], [{ status: 600 }, 'chaos.status'], [{ kind: 'stream' }, 'chaos.kind'], [{ kind: 'STREAM-DROP' }, 'chaos.kind'], [{ kind: 3 }, 'chaos.kind'], [{ afterChunks: -1 }, 'chaos.afterChunks'], [{ afterChunks: 1.5 }, 'chaos.afterChunks'], [{ afterChunks: '2' }, 'chaos.afterChunks'], [{ afterChunks: null }, 'chaos.afterChunks'], ])('rejects a chaos setting of %o', (chaos, setting) => { expect(() => withChaos(chaos)).toThrow(setting); }); test('keeps values that are set', () => { const config = applyConfigDefaults( { models: { chatgpt: { name: 'openai', endpoint: 'chat', validateRequests: true, embeddings: { enabled: true, dimensions: 64 }, }, }, server: { port: 3000 }, }, 'chatgpt', ); expect(config.models.chatgpt.validateRequests).toBe(true); expect(config.models.chatgpt.embeddings).toEqual({ enabled: true, dimensions: 64, }); expect(config.server).toEqual({ port: 3000, host: '0.0.0.0' }); }); test('rejects a preset without a name or endpoint', () => { expect(() => applyConfigDefaults({ models: { a: { name: 'openai' } } }, 'a'), ).toThrow('"endpoint"'); expect(() => applyConfigDefaults({ models: { a: { endpoint: 'chat' } } }, 'a'), ).toThrow('"name"'); }); }); describe('parseListeningPids', () => { const netstat = [ 'Active Connections', '', ' Proto Local Address Foreign Address State PID', ' TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 1032', ' TCP 0.0.0.0:8001 0.0.0.0:0 LISTENING 4242', ' TCP [::]:8001 [::]:0 LISTENING 4242', ' TCP 0.0.0.0:80010 0.0.0.0:0 LISTENING 5555', ' TCP 127.0.0.1:8001 127.0.0.1:64287 ESTABLISHED 9001', ' TCP 127.0.0.1:64287 127.0.0.1:8001 ESTABLISHED 9002', ' TCP [::1]:64282 [::1]:8001 SYN_SENT 9003', ' UDP 0.0.0.0:8001 *:* 7777', ].join('\r\n'); test('returns each process listening on the port once', () => { expect(parseListeningPids(netstat, 8001)).toEqual(['4242']); }); test('ignores clients connected to the port', () => { const pids = parseListeningPids(netstat, 8001); expect(pids).not.toContain('9001'); expect(pids).not.toContain('9002'); expect(pids).not.toContain('9003'); }); test('does not match ports that merely start with the number', () => { expect(parseListeningPids(netstat, 8001)).not.toContain('5555'); expect(parseListeningPids(netstat, 80010)).toEqual(['5555']); }); test('does not depend on the state text being English', () => { const german = ' TCP 0.0.0.0:8001 0.0.0.0:0 ABHÖREN 4242'; expect(parseListeningPids(german, 8001)).toEqual(['4242']); }); test('accepts the port as a string', () => { expect(parseListeningPids(netstat, '8001')).toEqual(['4242']); }); test('returns nothing for empty output or an unused port', () => { expect(parseListeningPids('', 8001)).toEqual([]); expect(parseListeningPids(netstat, 9999)).toEqual([]); }); }); describe('serverEnv', () => { const config = applyConfigDefaults( { models: { claude: { name: 'claude', endpoint: 'v1/messages', stream: false, chaos: { enabled: true }, }, }, server: { port: 8001, host: '0.0.0.0' }, }, 'claude', ); test('takes the preset and server settings from the config', () => { const env = serverEnv(config, 'claude'); expect(env).toMatchObject({ LLM_MODEL_NAME: 'claude', SERVER_PORT: '8001', SERVER_HOST: '0.0.0.0', ADMIN_API: 'true', LLM_NAME: 'claude', LLM_URL_ENDPOINT: 'v1/messages', STREAM: 'false', CHAOS_ENABLED: 'true', }); expect(env).not.toHaveProperty('CONFIG_PATH'); }); test('settings win over the config, numbers and booleans included', () => { const env = serverEnv( config, 'claude', { port: 0, stream: true, chaos: false, admin: 'off', delayMin: 5 }, '/x/.llmockrc.json', ); expect(env).toMatchObject({ SERVER_PORT: '0', STREAM: 'true', CHAOS_ENABLED: 'false', ADMIN_API: 'false', RESPONSE_DELAY_MIN: '5', CONFIG_PATH: '/x/.llmockrc.json', }); }); test.each([ [1, 'true'], ['1', 'true'], ['on', 'true'], ['YES', 'true'], [' True ', 'true'], [0, 'false'], ['off', 'false'], ['no', 'false'], ['nonsense', 'false'], ])('an on/off setting of %j reads as %s', (value, expected) => { const env = serverEnv(config, 'claude', { stream: value, chaos: value, embeddings: value, }); expect(env.STREAM).toBe(expected); expect(env.CHAOS_ENABLED).toBe(expected); expect(env.ENABLE_EMBEDDINGS_MOCK).toBe(expected); }); test('an endpoint under /admin is refused while the admin API is on', () => { expect(() => serverEnv(config, 'claude', { endpoint: 'admin/chat' }), ).toThrow(/belong to the admin API/); }); }); describe('llmspy', () => { test('--llmspy alone turns it on, and takes a following address', () => { expect(parseCliArgs(['start', '--llmspy']).customSettings.llmspy).toBe( 'true', ); expect( parseCliArgs(['start', '--llmspy', '--port=3000']).customSettings, ).toEqual({ llmspy: 'true', port: '3000' }); expect( parseCliArgs(['--llmspy', 'http://127.0.0.1:9090']).customSettings .llmspy, ).toBe('http://127.0.0.1:9090'); expect(parseCliArgs(['--llmspy=false']).customSettings.llmspy).toBe( 'false', ); }); test.each([ [undefined, null], [false, null], ['off', null], ['', null], [true, LLMSPY_DEFAULT_URL], ['yes', LLMSPY_DEFAULT_URL], ['http://localhost:9090/', 'http://localhost:9090'], ['https://spy.example:8443/some/path', 'https://spy.example:8443'], ])('llmspyAddress(%s) is %s', (value, address) => { expect(llmspyAddress(value)).toBe(address); }); test('llmspyAddress rejects a value that is neither on/off nor a URL', () => { expect(() => llmspyAddress('8080')).toThrow(/llmspy must be/); expect(() => llmspyAddress('ftp://host')).toThrow(/llmspy must be/); }); const route = (llmName: string, endpoint: string, modelName = 'claude') => llmspyRoute({ llmspy: LLMSPY_DEFAULT_URL, modelName, llmName, endpoint, host: '0.0.0.0', port: 8001, }); test('claude: the SDK base URL is the upstream prefix', () => { expect(route('claude', 'v1/messages')).toEqual({ name: 'llmock-claude', upstream: 'http://127.0.0.1:8001', entry: 'llmock-claude=http://127.0.0.1:8001', baseUrl: 'http://127.0.0.1:8080/llmock-claude', endpointUrl: 'http://127.0.0.1:8080/llmock-claude/v1/messages', }); }); test('openai: the base URL keeps the path before chat/completions', () => { const r = route('openai', 'chatgpt/chat/completions', 'chatgpt'); expect(r.entry).toBe('llmock-chatgpt=http://127.0.0.1:8001'); expect(r.baseUrl).toBe('http://127.0.0.1:8080/llmock-chatgpt/chatgpt'); }); test('a port other than 8001 is part of the name', () => { const r = llmspyRoute({ llmspy: LLMSPY_DEFAULT_URL, modelName: 'chatgpt', llmName: 'openai', endpoint: 'chatgpt/chat/completions', host: '0.0.0.0', port: '8002', }); expect(r.entry).toBe('llmock-chatgpt-8002=http://127.0.0.1:8002'); expect(r.baseUrl).toBe( 'http://127.0.0.1:8080/llmock-chatgpt-8002/chatgpt', ); }); test('a format with no known SDK path has only the endpoint URL', () => { const r = route( 'gemini', 'v1beta/models/gemini-pro:generateContent', 'gemini', ); expect(r.baseUrl).toBeNull(); expect(r.endpointUrl).toBe( 'http://127.0.0.1:8080/llmock-gemini/v1beta/models/gemini-pro:generateContent', ); }); test('a preset name is made into a name LLMSpy accepts', () => { expect(route('claude', 'v1/messages', 'My_Claude Preset').name).toBe( 'llmock-my-claude-preset', ); }); test('serverEnv: the flag wins over server.llmspy, empty when off', () => { const config = applyConfigDefaults( { models: { claude: { name: 'claude', endpoint: 'v1/messages' } }, server: { port: 8001, host: '0.0.0.0', llmspy: true }, }, 'claude', ); expect(serverEnv(config, 'claude').LLMSPY_URL).toBe(LLMSPY_DEFAULT_URL); expect( serverEnv(config, 'claude', { llmspy: 'false' }).LLMSPY_URL, ).toBe(''); expect( serverEnv(config, 'claude', { llmspy: 'http://127.0.0.1:9090' }) .LLMSPY_URL, ).toBe('http://127.0.0.1:9090'); }); });