Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add LM Studio vision testing capability
Adam Eivy2810917369c2
diff --git a/server/routes/providers.js b/server/routes/providers.jsindex 68e475547f..eb10ae4beb 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -1,6 +1,7 @@import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import * as providers from '../services/providers.js';+import { testVision, runVisionTestSuite, checkVisionHealth } from '../services/visionTest.js';const router = Router();@@ -98,4 +99,36 @@ router.post('/:id/refresh-models', asyncHandler(async (req, res) => {res.json(provider);}));+// GET /api/providers/:id/vision-health - Check vision capability health+router.get('/:id/vision-health', asyncHandler(async (req, res) => {+ const result = await checkVisionHealth(req.params.id);+ res.json(result);+}));++// POST /api/providers/:id/test-vision - Test vision with a specific image+router.post('/:id/test-vision', asyncHandler(async (req, res) => {+ const { imagePath, prompt, expectedContent, model } = req.body;++ if (!imagePath) {+ throw new ServerError('imagePath is required', { status: 400, code: 'VALIDATION_ERROR' });+ }++ const result = await testVision({+ imagePath,+ prompt: prompt || 'Describe what you see in this image.',+ expectedContent: expectedContent || [],+ providerId: req.params.id,+ model+ });++ res.json(result);+}));++// POST /api/providers/:id/vision-suite - Run full vision test suite+router.post('/:id/vision-suite', asyncHandler(async (req, res) => {+ const { model } = req.body;+ const result = await runVisionTestSuite(req.params.id, model);+ res.json(result);+}));+export default router;diff --git a/server/services/visionTest.js b/server/services/visionTest.jsnew file mode 100644index 0000000000..a8bc71878f--- /dev/null+++ b/server/services/visionTest.js@@ -0,0 +1,299 @@+/**+ * Vision Test Service+ *+ * Tests LM Studio's vision capabilities by sending images to the API+ * and verifying the model can correctly interpret them.+ */++import { readFile } from 'fs/promises';+import { existsSync } from 'fs';+import { join, dirname, resolve, extname } from 'path';+import { fileURLToPath } from 'url';+import { getProviderById } from './providers.js';++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);+const SCREENSHOTS_DIR = resolve(__dirname, '../../data/screenshots');++/**+ * Get MIME type from file extension+ * @param {string} filepath - Path to the file+ * @returns {string} - MIME type+ */+function getMimeType(filepath) {+ const ext = extname(filepath).toLowerCase();+ const mimeTypes = {+ '.png': 'image/png',+ '.jpg': 'image/jpeg',+ '.jpeg': 'image/jpeg',+ '.gif': 'image/gif',+ '.webp': 'image/webp'+ };+ return mimeTypes[ext] || 'image/png';+}++/**+ * Load an image as base64 data URL+ * @param {string} imagePath - Path to the image file+ * @returns {Promise<string>} - Base64 data URL+ */+async function loadImageAsBase64(imagePath) {+ const fullPath = imagePath.startsWith('/') ? imagePath : join(SCREENSHOTS_DIR, imagePath);++ if (!existsSync(fullPath)) {+ throw new Error(`Image not found: ${fullPath}`);+ }++ const buffer = await readFile(fullPath);+ const mimeType = getMimeType(fullPath);+ return `data:${mimeType};base64,${buffer.toString('base64')}`;+}++/**+ * Call LM Studio API with vision request+ * @param {Object} options - Request options+ * @param {string} options.endpoint - API endpoint+ * @param {string} options.apiKey - API key+ * @param {string} options.model - Model to use+ * @param {string} options.imageDataUrl - Base64 image data URL+ * @param {string} options.prompt - Prompt to send with image+ * @param {number} options.timeout - Request timeout in ms+ * @returns {Promise<Object>} - API response+ */+async function callVisionAPI({ endpoint, apiKey, model, imageDataUrl, prompt, timeout = 60000 }) {+ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), timeout);++ const response = await fetch(`${endpoint}/chat/completions`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'Authorization': `Bearer ${apiKey}`+ },+ body: JSON.stringify({+ model,+ messages: [+ {+ role: 'user',+ content: [+ {+ type: 'image_url',+ image_url: {+ url: imageDataUrl+ }+ },+ {+ type: 'text',+ text: prompt+ }+ ]+ }+ ],+ max_tokens: 500,+ temperature: 0.1+ }),+ signal: controller.signal+ }).finally(() => clearTimeout(timeoutId));++ if (!response.ok) {+ const errorText = await response.text().catch(() => 'Unknown error');+ throw new Error(`Vision API error ${response.status}: ${errorText}`);+ }++ return response.json();+}++/**+ * Test vision capability with a specific image and prompt+ * @param {Object} options - Test options+ * @param {string} options.imagePath - Path to test image+ * @param {string} options.prompt - Test prompt+ * @param {string} options.expectedContent - Keywords expected in response+ * @param {string} [options.providerId='lmstudio'] - Provider to use+ * @param {string} [options.model] - Model to use (defaults to provider's default)+ * @returns {Promise<Object>} - Test result+ */+export async function testVision({ imagePath, prompt, expectedContent, providerId = 'lmstudio', model }) {+ const startTime = Date.now();++ // Get provider configuration+ const provider = await getProviderById(providerId);+ if (!provider) {+ return {+ success: false,+ error: `Provider '${providerId}' not found`,+ duration: Date.now() - startTime+ };+ }++ if (provider.type !== 'api') {+ return {+ success: false,+ error: `Provider '${providerId}' is not an API provider (type: ${provider.type})`,+ duration: Date.now() - startTime+ };+ }++ const testModel = model || provider.defaultModel;+ if (!testModel) {+ return {+ success: false,+ error: 'No model specified and provider has no default model',+ duration: Date.now() - startTime+ };+ }++ // Load image+ const imageDataUrl = await loadImageAsBase64(imagePath).catch(err => {+ throw new Error(`Failed to load image: ${err.message}`);+ });++ console.log(`🔍 Testing vision with model: ${testModel}`);+ console.log(`📸 Image: ${imagePath}`);++ // Call vision API+ const apiResponse = await callVisionAPI({+ endpoint: provider.endpoint,+ apiKey: provider.apiKey,+ model: testModel,+ imageDataUrl,+ prompt,+ timeout: provider.timeout || 60000+ });++ const responseContent = apiResponse.choices?.[0]?.message?.content || '';+ const duration = Date.now() - startTime;++ // Check if expected content is present+ const expectedTerms = Array.isArray(expectedContent) ? expectedContent : [expectedContent];+ const foundTerms = expectedTerms.filter(term =>+ responseContent.toLowerCase().includes(term.toLowerCase())+ );+ const allFound = foundTerms.length === expectedTerms.length;++ console.log(`✅ Vision test completed in ${duration}ms`);+ console.log(`📝 Response: ${responseContent.substring(0, 200)}...`);++ return {+ success: allFound,+ model: testModel,+ provider: providerId,+ imagePath,+ prompt,+ response: responseContent,+ expectedTerms,+ foundTerms,+ missingTerms: expectedTerms.filter(t => !foundTerms.includes(t)),+ duration,+ usage: apiResponse.usage || null+ };+}++/**+ * Run a comprehensive vision test suite+ * @param {string} [providerId='lmstudio'] - Provider to test+ * @param {string} [model] - Specific model to test+ * @returns {Promise<Object>} - Test suite results+ */+export async function runVisionTestSuite(providerId = 'lmstudio', model) {+ const results = [];+ const screenshotFiles = await import('fs').then(fs =>+ fs.readdirSync(SCREENSHOTS_DIR).filter(f =>+ /\.(png|jpg|jpeg|gif|webp)$/i.test(f)+ )+ );++ if (screenshotFiles.length === 0) {+ return {+ success: false,+ error: 'No screenshots available for testing',+ results: []+ };+ }++ // Use first available screenshot for basic vision test+ const testImage = screenshotFiles[0];++ // Test 1: Basic image description+ const describeTest = await testVision({+ imagePath: testImage,+ prompt: 'Describe what you see in this image in 2-3 sentences. Focus on the main elements visible.',+ expectedContent: [], // No specific content expected, just verify it responds+ providerId,+ model+ }).catch(err => ({+ success: false,+ error: err.message,+ testName: 'basic-description'+ }));++ results.push({ ...describeTest, testName: 'basic-description' });++ // Test 2: UI element identification (if it's an app screenshot)+ const uiTest = await testVision({+ imagePath: testImage,+ prompt: 'If this is a screenshot of an application or website, identify any visible UI elements like buttons, forms, navigation, or text. If not a UI screenshot, describe the main subject.',+ expectedContent: [], // Just verify response quality+ providerId,+ model+ }).catch(err => ({+ success: false,+ error: err.message,+ testName: 'ui-identification'+ }));++ results.push({ ...uiTest, testName: 'ui-identification' });++ // Calculate overall success+ const successfulTests = results.filter(r => !r.error && r.response?.length > 20);++ return {+ success: successfulTests.length === results.length,+ totalTests: results.length,+ passedTests: successfulTests.length,+ provider: providerId,+ model: model || 'default',+ results+ };+}++/**+ * Quick health check for vision capabilities+ * @param {string} [providerId='lmstudio'] - Provider to check+ * @returns {Promise<Object>} - Health check result+ */+export async function checkVisionHealth(providerId = 'lmstudio') {+ const provider = await getProviderById(providerId);++ if (!provider) {+ return { available: false, error: 'Provider not found' };+ }++ if (!provider.enabled) {+ return { available: false, error: 'Provider is disabled' };+ }++ if (provider.type !== 'api') {+ return { available: false, error: 'Vision requires API provider' };+ }++ // Check if endpoint is reachable+ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), 5000);++ const response = await fetch(`${provider.endpoint}/models`, {+ headers: provider.apiKey ? { 'Authorization': `Bearer ${provider.apiKey}` } : {},+ signal: controller.signal+ }).catch(() => null).finally(() => clearTimeout(timeoutId));++ if (!response?.ok) {+ return { available: false, error: 'API endpoint not reachable' };+ }++ return {+ available: true,+ provider: providerId,+ endpoint: provider.endpoint,+ defaultModel: provider.defaultModel+ };+}diff --git a/server/services/visionTest.test.js b/server/services/visionTest.test.jsnew file mode 100644index 0000000000..ddb043c2d8--- /dev/null+++ b/server/services/visionTest.test.js@@ -0,0 +1,317 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { testVision, runVisionTestSuite, checkVisionHealth } from './visionTest.js';++// Mock the providers module+vi.mock('./providers.js', () => ({+ getProviderById: vi.fn()+}));++// Mock fs/promises for image loading+vi.mock('fs/promises', () => ({+ readFile: vi.fn()+}));++// Mock fs for existsSync+vi.mock('fs', () => ({+ existsSync: vi.fn(),+ readdirSync: vi.fn()+}));++// Import mocked modules+import { getProviderById } from './providers.js';+import { readFile } from 'fs/promises';+import { existsSync, readdirSync } from 'fs';++describe('Vision Test Service', () => {+ const mockProvider = {+ id: 'lmstudio',+ name: 'LM Studio',+ type: 'api',+ endpoint: 'http://localhost:1234/v1',+ apiKey: 'lm-studio',+ models: ['test-vision-model'],+ defaultModel: 'test-vision-model',+ timeout: 60000,+ enabled: true+ };++ const mockImageBuffer = Buffer.from('fake-image-data');++ beforeEach(() => {+ vi.clearAllMocks();+ global.fetch = vi.fn();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ describe('testVision', () => {+ it('should return error when provider not found', async () => {+ getProviderById.mockResolvedValue(null);++ const result = await testVision({+ imagePath: '/test/image.png',+ prompt: 'Describe this image',+ expectedContent: ['test'],+ providerId: 'nonexistent'+ });++ expect(result.success).toBe(false);+ expect(result.error).toContain('not found');+ });++ it('should return error when provider is not API type', async () => {+ getProviderById.mockResolvedValue({+ ...mockProvider,+ type: 'cli'+ });++ const result = await testVision({+ imagePath: '/test/image.png',+ prompt: 'Describe this image',+ expectedContent: ['test'],+ providerId: 'lmstudio'+ });++ expect(result.success).toBe(false);+ expect(result.error).toContain('not an API provider');+ });++ it('should return error when no model specified and no default', async () => {+ getProviderById.mockResolvedValue({+ ...mockProvider,+ defaultModel: null+ });++ const result = await testVision({+ imagePath: '/test/image.png',+ prompt: 'Describe this image',+ expectedContent: ['test']+ });++ expect(result.success).toBe(false);+ expect(result.error).toContain('No model specified');+ });++ it('should successfully test vision when API returns expected content', async () => {+ getProviderById.mockResolvedValue(mockProvider);+ existsSync.mockReturnValue(true);+ readFile.mockResolvedValue(mockImageBuffer);++ const mockResponse = {+ choices: [{+ message: {+ content: 'This is a screenshot of an application showing a button and text.'+ }+ }],+ usage: { prompt_tokens: 100, completion_tokens: 50 }+ };++ global.fetch.mockResolvedValue({+ ok: true,+ json: () => Promise.resolve(mockResponse)+ });++ const result = await testVision({+ imagePath: '/test/image.png',+ prompt: 'Describe this image',+ expectedContent: ['button', 'text']+ });++ expect(result.success).toBe(true);+ expect(result.model).toBe('test-vision-model');+ expect(result.foundTerms).toContain('button');+ expect(result.foundTerms).toContain('text');+ expect(result.missingTerms).toHaveLength(0);+ });++ it('should return success false when expected content not found', async () => {+ getProviderById.mockResolvedValue(mockProvider);+ existsSync.mockReturnValue(true);+ readFile.mockResolvedValue(mockImageBuffer);++ const mockResponse = {+ choices: [{+ message: {+ content: 'This is a blank image.'+ }+ }]+ };++ global.fetch.mockResolvedValue({+ ok: true,+ json: () => Promise.resolve(mockResponse)+ });++ const result = await testVision({+ imagePath: '/test/image.png',+ prompt: 'Describe this image',+ expectedContent: ['button', 'navigation']+ });++ expect(result.success).toBe(false);+ expect(result.missingTerms).toContain('button');+ expect(result.missingTerms).toContain('navigation');+ });++ it('should handle API errors gracefully', async () => {+ getProviderById.mockResolvedValue(mockProvider);+ existsSync.mockReturnValue(true);+ readFile.mockResolvedValue(mockImageBuffer);++ global.fetch.mockResolvedValue({+ ok: false,+ status: 500,+ text: () => Promise.resolve('Internal Server Error')+ });++ await expect(testVision({+ imagePath: '/test/image.png',+ prompt: 'Describe this image',+ expectedContent: ['test']+ })).rejects.toThrow('Vision API error 500');+ });++ it('should use custom model when specified', async () => {+ getProviderById.mockResolvedValue(mockProvider);+ existsSync.mockReturnValue(true);+ readFile.mockResolvedValue(mockImageBuffer);++ const mockResponse = {+ choices: [{+ message: { content: 'Test response' }+ }]+ };++ global.fetch.mockResolvedValue({+ ok: true,+ json: () => Promise.resolve(mockResponse)+ });++ const result = await testVision({+ imagePath: '/test/image.png',+ prompt: 'Describe',+ expectedContent: [],+ model: 'custom-model'+ });++ expect(result.model).toBe('custom-model');++ // Verify the API was called with custom model+ const fetchCall = global.fetch.mock.calls[0];+ const body = JSON.parse(fetchCall[1].body);+ expect(body.model).toBe('custom-model');+ });++ it('should handle image not found error', async () => {+ getProviderById.mockResolvedValue(mockProvider);+ existsSync.mockReturnValue(false);++ await expect(testVision({+ imagePath: '/nonexistent/image.png',+ prompt: 'Describe',+ expectedContent: []+ })).rejects.toThrow('Failed to load image');+ });+ });++ describe('runVisionTestSuite', () => {+ it('should return error when no screenshots available', async () => {+ readdirSync.mockReturnValue([]);++ const result = await runVisionTestSuite('lmstudio');++ expect(result.success).toBe(false);+ expect(result.error).toContain('No screenshots available');+ });++ it('should run multiple tests on available screenshots', async () => {+ readdirSync.mockReturnValue(['test1.png', 'test2.jpg']);+ getProviderById.mockResolvedValue(mockProvider);+ existsSync.mockReturnValue(true);+ readFile.mockResolvedValue(mockImageBuffer);++ const mockResponse = {+ choices: [{+ message: { content: 'This is a detailed description of what I see in the image.' }+ }]+ };++ global.fetch.mockResolvedValue({+ ok: true,+ json: () => Promise.resolve(mockResponse)+ });++ const result = await runVisionTestSuite('lmstudio');++ expect(result.totalTests).toBe(2);+ expect(result.results).toHaveLength(2);+ expect(result.results[0].testName).toBe('basic-description');+ expect(result.results[1].testName).toBe('ui-identification');+ });+ });++ describe('checkVisionHealth', () => {+ it('should return unavailable when provider not found', async () => {+ getProviderById.mockResolvedValue(null);++ const result = await checkVisionHealth('nonexistent');++ expect(result.available).toBe(false);+ expect(result.error).toContain('not found');+ });++ it('should return unavailable when provider is disabled', async () => {+ getProviderById.mockResolvedValue({+ ...mockProvider,+ enabled: false+ });++ const result = await checkVisionHealth('lmstudio');++ expect(result.available).toBe(false);+ expect(result.error).toContain('disabled');+ });++ it('should return unavailable when provider is not API type', async () => {+ getProviderById.mockResolvedValue({+ ...mockProvider,+ type: 'cli'+ });++ const result = await checkVisionHealth('lmstudio');++ expect(result.available).toBe(false);+ expect(result.error).toContain('requires API provider');+ });++ it('should return available when endpoint is reachable', async () => {+ getProviderById.mockResolvedValue(mockProvider);++ global.fetch.mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ data: [] })+ });++ const result = await checkVisionHealth('lmstudio');++ expect(result.available).toBe(true);+ expect(result.provider).toBe('lmstudio');+ expect(result.endpoint).toBe(mockProvider.endpoint);+ });++ it('should return unavailable when endpoint not reachable', async () => {+ getProviderById.mockResolvedValue(mockProvider);++ global.fetch.mockResolvedValue({+ ok: false+ });++ const result = await checkVisionHealth('lmstudio');++ expect(result.available).toBe(false);+ expect(result.error).toContain('not reachable');+ });+ });+});