import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import type { FastifyInstance } from 'fastify'; import { db } from '../models/db.js'; import { getStoredResponsesFile } from '../config/config-loader.js'; import { clearLog, logPath, maxLogEntries } from './logger.js'; import { loadStoredResponses } from './stored-responses.js'; import { readRuleFile, ruleFiles } from './response-rules.js'; import { describeActiveRules, getFileRules } from './runtime-rules.js'; import { getDelay } from './runtime-settings.js'; import { getChaosConfig, getChaosStats } from './chaos.js'; import { adminApiEnabled } from './admin-api.js'; import { currentLlmspyRoute } from './llmspy.js'; import { responsesPaths } from './build-responses-response.js'; import { describeRecording } from './recordings.js'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const uiDistDir = path.resolve(__dirname, '../../ui/dist'); // Version of the llmock package this server is running from, null if its // package.json can't be read. function readPackageVersion(): string | null { try { const packageJson = JSON.parse( fs.readFileSync( path.resolve(__dirname, '../../package.json'), 'utf8', ), ) as { version?: unknown }; return typeof packageJson.version === 'string' ? packageJson.version : null; } catch { return null; } } const version = readPackageVersion(); // The pool `responseType: "stored"` picks from: the preset's own file if // configured, otherwise the bundled texts. Throws if that file can't be used. function readStoredResponses(): string[] { const { file, baseDir } = getStoredResponsesFile(); if (!file) return db.llm.getAll().map((item) => item.content); return loadStoredResponses(file, baseDir); } // Size of that pool, 0 if the file can't be used. function countStoredResponses(): number { try { return readStoredResponses().length; } catch { return 0; } } export type UiTheme = 'dark' | 'light'; // The dashboard's colours: dark unless UI_THEME is "light" export const getUiTheme = (): UiTheme => process.env?.UI_THEME?.toLowerCase() === 'light' ? 'light' : 'dark'; /** * Names the theme on the page's element, which is what the dashboard's * stylesheet goes by. Done as the page is served so it is drawn in the right * colours from the start, rather than switching once the settings have loaded. */ export const withUiTheme = (html: string, theme: UiTheme): string => html.replace(/ Mock LLM Server Dashboard

Mock LLM Server

ERROR: Please build dashboard UI - use 'npm run compile-ui'

`; // The built dashboard page with the theme in use named on it const themedPage = (uiIndex: { data: Buffer }): string => withUiTheme(uiIndex.data.toString('utf8'), getUiTheme()); function serverPage(app: FastifyInstance, _apiPaths: string[]) { // UI meta endpoint for the compiled Svelte dashboard app.get('/ui-meta', async (_request, reply) => { const storedActive = process.env.MOCK_LLM_RESPONSE_TYPE === 'stored'; const storedResponsesCount = storedActive ? countStoredResponses() : null; // Configured path as written in the config; null means the bundled texts const storedResponsesFile = storedActive ? (getStoredResponsesFile().file ?? null) : null; // Rules in the order they are matched (first match wins): the ones // added through the admin API, then the config file's const responseRules = describeActiveRules(); const { min: responseDelayMinMs, max: responseDelayMaxMs } = getDelay(); const delayStatus = responseDelayMinMs > 0 || responseDelayMaxMs > 0 ? 'ENABLED' : 'DISABLED'; const streamingStatus = process.env?.STREAM?.toLowerCase() === 'true' ? 'ENABLED' : 'DISABLED'; const embeddingsEnabled = process.env?.ENABLE_EMBEDDINGS_MOCK?.toLowerCase() !== 'false'; const embeddingDimension = Number(process.env?.EMBEDDING_DIMENSION) || 128; const chaos = getChaosConfig(); // Create unique API links to avoid Svelte duplicate key errors const apiLinksSet = new Set(); // Add main API endpoint // Read per request: startServer sets it after this module has loaded apiLinksSet.add(`/${process.env?.LLM_URL_ENDPOINT ?? ''}`); // The Responses API, served beside the chat route by openai presets for (const route of responsesPaths()) apiLinksSet.add(`/${route}`); // Add embeddings endpoint link if enabled if (embeddingsEnabled) { apiLinksSet.add('/v1/embeddings'); } // Convert Set to array of objects const apiLinks = Array.from(apiLinksSet).map((href) => ({ href: href, label: href, })); return reply.send({ version, serverPort: Number(process.env?.SERVER_PORT ?? '') || null, llmUrlEndpoint: process.env?.LLM_URL_ENDPOINT ?? '', llmName: process.env?.LLM_NAME ?? '', llmModel: process.env?.LLM_MODEL ?? 'NONE DEFINED', mockResponseType: process.env?.MOCK_LLM_RESPONSE_TYPE ?? '', maxLoremParas: process.env.MOCK_LLM_RESPONSE_TYPE === 'lorem' ? Number(process.env?.MAX_LOREM_PARAS ?? '') || null : null, storedResponsesCount, storedResponsesFile, responseRules, validateRequests: process.env?.VALIDATE_REQUESTS ?? '', logRequests: process.env?.LOG_REQUESTS ?? '', maxLoggedRequests: maxLogEntries(), debugMode: process.env.DEBUG === '*' ? 'ON' : 'OFF', responseDelayMinMs, responseDelayMaxMs, delayStatus, streamingStatus, chaosStatus: chaos.enabled ? 'ENABLED' : 'DISABLED', chaosFrequency: chaos.frequency, chaosMode: chaos.mode, chaosErrorStatus: chaos.status, chaosKind: chaos.kind, chaosAfterChunks: chaos.afterChunks, chaosInjected: getChaosStats().injected, embeddingsEnabled: embeddingsEnabled ? 'ENABLED' : 'DISABLED', embeddingDimension, adminApi: adminApiEnabled() ? 'ENABLED' : 'DISABLED', uiTheme: getUiTheme(), // How to put this server behind LLMSpy, null when llmspy is off llmspy: currentLlmspyRoute(), // Recording real replies, or replaying them recording: describeRecording(), apiLinks, }); }); // Texts of the stored responses pool, for the dashboard viewer app.get('/ui-stored-responses', async (_request, reply) => { const file = getStoredResponsesFile().file ?? null; try { return reply.send({ file, responses: readStoredResponses() }); } catch (error) { return reply.code(500).send({ error: (error as Error).message }); } }); // Contents of one response rule fixture, for the dashboard viewer. Files // are addressed by position (?rule=0&file=0), never by path, so only // configured fixtures can be read. `rule` counts the config file's rules // only: they are the ones with files, and their positions stay the same // as rules are added and removed through the admin API. app.get('/ui-rule-file', async (request, reply) => { const query = request.query as { rule?: string; file?: string }; // The config file's rules, then the recorded ones const { rules, baseDir } = getFileRules(); const rule = rules[Number(query.rule ?? 0)]; const file = rule && ruleFiles(rule)[Number(query.file ?? 0)]; if (!rule || !file) { return reply .code(404) .send({ error: 'No such response rule file' }); } try { return reply.send({ match: rule.match, file, content: readRuleFile(rule, file, baseDir), }); } catch (error) { return reply.code(500).send({ error: (error as Error).message }); } }); // The most recent validated requests, newest first, for the dashboard // viewer. `log` is null when no request has been logged yet. app.get('/ui-request-log', async (_request, reply) => { let log: unknown = null; try { log = JSON.parse(fs.readFileSync(logPath, 'utf8')); // A log written under a higher limit is only trimmed on the // next request if (Array.isArray(log)) log = log.slice(0, maxLogEntries()); } catch { // No log file yet, or one that is mid-write } return reply.send({ file: logPath, log }); }); // Empties the request log, for the dashboard's "Clear logs" button app.delete('/ui-request-log', async (_request, reply) => { try { clearLog(); } catch (error) { return reply.code(500).send({ error: (error as Error).message }); } return reply.send({ file: logPath, log: null }); }); // Home page route app.get('/', async (_request, reply) => { const uiIndex = tryReadUiDistFile('index.html'); if (uiIndex) return reply.type('text/html').send(themedPage(uiIndex)); return reply.type('text/html').send(fallbackHtmlString); }); // Ping endpoint for status check app.get('/ping', async (_request, reply) => { return reply.send({ response: 'server is running' }); }); // Serve built Vite assets when present app.get('/assets/*', async (request, reply) => { const star = (request.params as Record | undefined)?.['*'] ?? ''; const file = tryReadUiDistFile(path.join('assets', star)); if (!file) return reply.code(404).send(); return reply.type(contentTypeForPath(file.absPath)).send(file.data); }); // Serve any built root-level file (favicon, manifest, etc.) app.get('/:file', async (request, reply) => { const fileName = (request.params as { file: string }).file; if (!fileName.includes('.')) return reply.code(404).send(); const file = tryReadUiDistFile(fileName); if (!file) return reply.code(404).send(); // The dashboard page asked for by name gets its theme too if (fileName === 'index.html') { return reply.type('text/html').send(themedPage(file)); } return reply.type(contentTypeForPath(file.absPath)).send(file.data); }); } export default serverPage;