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 vision API support and fix output saving
Adam Eivy556c7cee54c0
diff --git a/client/src/pages/DevTools.jsx b/client/src/pages/DevTools.jsxindex c22f6921d3..c814d530d2 100644--- a/client/src/pages/DevTools.jsx+++ b/client/src/pages/DevTools.jsx@@ -589,13 +589,15 @@ export function RunsHistoryPage() {</div></div>- {/* Output - show for successful runs with output OR for failed runs */}- {(expandedDetails[run.id]?.output || run.success === false) && (+ {/* Output - show for all completed runs */}+ {run.success !== null && (<div><div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Output</div><div className="bg-port-card border border-port-border rounded-lg p-3 max-h-64 overflow-auto"><pre className="text-xs text-gray-300 font-mono whitespace-pre-wrap break-all">- {expandedDetails[run.id]?.output || (run.success === false ? 'Loading output...' : '')}+ {expandedDetails[run.id]?.output !== undefined+ ? (expandedDetails[run.id].output || '(no output)')+ : 'Loading output...'}</pre></div></div>@@ -851,7 +853,8 @@ ${prompt.trim()}`;prompt: finalPrompt,workspacePath: workspacePath || undefined,workspaceName: apps.find(a => a.repoPath === workspacePath)?.name,- timeout: timeout * 60 * 1000 // Convert minutes to milliseconds+ timeout: timeout * 60 * 1000, // Convert minutes to milliseconds+ screenshots: screenshots.map(s => s.path) // Include screenshot paths}).catch(err => ({ error: err.message }));if (result.error) {diff --git a/server/routes/runs.js b/server/routes/runs.jsindex 9447513451..bd7a500882 100644--- a/server/routes/runs.js+++ b/server/routes/runs.js@@ -17,8 +17,8 @@ router.get('/', asyncHandler(async (req, res, next) => {// POST /api/runs - Create and execute a new runrouter.post('/', asyncHandler(async (req, res, next) => {- const { providerId, model, prompt, workspacePath, workspaceName, timeout } = req.body;- console.log(`🚀 POST /api/runs - provider: ${providerId}, model: ${model}, workspace: ${workspaceName}, timeout: ${timeout}ms`);+ const { providerId, model, prompt, workspacePath, workspaceName, timeout, screenshots } = req.body;+ console.log(`🚀 POST /api/runs - provider: ${providerId}, model: ${model}, workspace: ${workspaceName}, timeout: ${timeout}ms, screenshots: ${screenshots?.length || 0}`);if (!providerId) {throw new ServerError('providerId is required', {@@ -40,7 +40,8 @@ router.post('/', asyncHandler(async (req, res, next) => {prompt,workspacePath,workspaceName,- timeout+ timeout,+ screenshots});const { runId, provider, metadata, timeout: effectiveTimeout } = runData;@@ -73,6 +74,7 @@ router.post('/', asyncHandler(async (req, res, next) => {model,prompt,workspacePath,+ screenshots,(data) => {io?.emit(`run:${runId}:data`, data);},diff --git a/server/services/runner.js b/server/services/runner.jsindex e2b33bcaef..54c186e854 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -1,6 +1,6 @@import { mkdir, writeFile, readFile, readdir, rm } from 'fs/promises';import { existsSync } from 'fs';-import { join, dirname } from 'path';+import { join, dirname, extname, resolve } from 'path';import { fileURLToPath } from 'url';import { v4 as uuidv4 } from 'uuid';import { getProviderById } from './providers.js';@@ -20,6 +20,37 @@ const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);const DATA_DIR = join(__dirname, '../../data');const RUNS_DIR = join(DATA_DIR, 'runs');+const SCREENSHOTS_DIR = resolve(__dirname, '../../data/screenshots');++/**+ * Get MIME type from file extension+ */+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+ */+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')}`;+}/*** Safe JSON parse with fallback to empty object@@ -418,7 +449,7 @@ export async function executeCliRun(runId, provider, prompt, workspacePath, onDareturn runId;}-export async function executeApiRun(runId, provider, model, prompt, workspacePath, onData, onComplete) {+export async function executeApiRun(runId, provider, model, prompt, workspacePath, screenshots, onData, onComplete) {const runDir = join(RUNS_DIR, runId);const outputPath = join(runDir, 'output.txt');const metadataPath = join(runDir, 'metadata.json');@@ -436,13 +467,47 @@ export async function executeApiRun(runId, provider, model, prompt, workspacePatconst controller = new AbortController();activeRuns.set(runId, controller);+ // Build message content - if screenshots are provided, use vision format+ let messageContent;+ if (screenshots && screenshots.length > 0) {+ console.log(`📸 Loading ${screenshots.length} screenshots for vision API`);+ const contentParts = [];++ // Add images first+ for (const screenshotPath of screenshots) {+ const imageDataUrl = await loadImageAsBase64(screenshotPath).catch(err => {+ console.error(`❌ Failed to load screenshot ${screenshotPath}: ${err.message}`);+ return null;+ });+ if (imageDataUrl) {+ contentParts.push({+ type: 'image_url',+ image_url: {+ url: imageDataUrl+ }+ });+ }+ }++ // Add text prompt+ contentParts.push({+ type: 'text',+ text: prompt+ });++ messageContent = contentParts;+ } else {+ // No screenshots, just text+ messageContent = prompt;+ }+const response = await fetch(`${provider.endpoint}/chat/completions`, {method: 'POST',headers,signal: controller.signal,body: JSON.stringify({model: model || provider.defaultModel,- messages: [{ role: 'user', content: prompt }],+ messages: [{ role: 'user', content: messageContent }],stream: true})}).catch(err => ({ ok: false, error: err.message }));@@ -544,12 +609,21 @@ export async function executeApiRun(runId, provider, model, prompt, workspacePatprocessStream().catch(async (err) => {activeRuns.delete(runId);++ // Write partial output if any was captured before error+ if (output) {+ await writeFile(outputPath, output).catch(writeErr => {+ console.error(`❌ Failed to write partial output: ${writeErr.message}`);+ });+ }+const metadata = safeJsonParse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));metadata.endTime = new Date().toISOString();metadata.duration = Date.now() - startTime;metadata.success = false;metadata.error = err.message;metadata.errorDetails = err.message;+ metadata.outputSize = Buffer.byteLength(output);const { category, suggestion } = categorizeError(err.message, -1);metadata.errorCategory = category;metadata.suggestedFix = suggestion;