summaryrefslogtreecommitdiff
path: root/api/static/app.js
blob: 0dcbd01b3afc401357681dcdb135f23440ea88f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
/* ==========================================================================
   AI Agent Reasoning Experiment Framework - Web GUI App
   ========================================================================== */

const API_BASE = '';

// State
let eventSource = null;
let isRunning = false;

// ==========================================================================
// DOM Elements
// ==========================================================================

const elements = {
    // Configuration
    scenarioSelect: document.getElementById('scenario-select'),
    modelSelect: document.getElementById('model-select'),
    oversightSelect: document.getElementById('oversight-select'),
    runsInput: document.getElementById('runs-input'),
    
    // Buttons
    runBtn: document.getElementById('run-btn'),
    cancelBtn: document.getElementById('cancel-btn'),
    clearLogsBtn: document.getElementById('clear-logs-btn'),
    
    // Status
    statusBadge: document.getElementById('status-badge'),
    statusTime: document.getElementById('status-time'),
    
    // Logs
    logsContainer: document.getElementById('logs-container'),
    
    // Results
    csvResults: document.getElementById('csv-results'),
    imageResults: document.getElementById('image-results'),
    judgeResults: document.getElementById('judge-results'),
    
    // Tabs
    tabBtns: document.querySelectorAll('.tab-btn'),
    tabContents: document.querySelectorAll('.tab-content'),
};

// ==========================================================================
// Initialization
// ==========================================================================

document.addEventListener('DOMContentLoaded', async () => {
    await loadConfig();
    await loadScenarios();
    await loadModels();
    setupEventListeners();
    startStatusPolling();
});

// ==========================================================================
// API Functions
// ==========================================================================

async function loadConfig() {
    try {
        const response = await fetch(`${API_BASE}/api/config`);
        const config = await response.json();
        
        // Set default values from config
        if (config.defaults?.oversight) {
            elements.oversightSelect.value = config.defaults.oversight;
        }
    } catch (error) {
        console.error('Failed to load config:', error);
    }
}

async function loadScenarios() {
    try {
        const response = await fetch(`${API_BASE}/api/scenarios`);
        const scenarios = await response.json();
        
        elements.scenarioSelect.innerHTML = scenarios.map(s => 
            `<option value="${s.name}">${s.name}</option>`
        ).join('');
        
        // If only one scenario, auto-select it and load oversight levels
        if (scenarios.length === 1) {
            elements.scenarioSelect.value = scenarios[0].name;
            updateOversightLevels(scenarios[0]);
        }
    } catch (error) {
        console.error('Failed to load scenarios:', error);
        elements.scenarioSelect.innerHTML = '<option value="">Error loading scenarios</option>';
    }
}

async function loadModels() {
    try {
        const response = await fetch(`${API_BASE}/api/models`);
        const models = await response.json();
        
        elements.modelSelect.innerHTML = models.map(m => 
            `<option value="${m.id}">${m.id} (${m.provider})</option>`
        ).join('');
    } catch (error) {
        console.error('Failed to load models:', error);
        elements.modelSelect.innerHTML = '<option value="">Error loading models</option>';
    }
}

async function startRun() {
    const scenario = elements.scenarioSelect.value;
    const model = elements.modelSelect.value;
    const oversight = elements.oversightSelect.value;
    const runs = elements.runsInput.value;
    
    if (!scenario || !model) {
        alert('Please select a scenario and model');
        return;
    }
    
    // Show loading state
    elements.runBtn.classList.add('loading');
    elements.runBtn.disabled = true;
    elements.cancelBtn.disabled = false;
    isRunning = true;
    
    // Clear logs
    elements.logsContainer.innerHTML = '';
    appendLog('info', `Starting experiment: ${scenario} with ${model} (oversight: ${oversight}, runs: ${runs})`);
    
    try {
        // TODO: For now, we just trigger the run with current config
        // In the future, we could modify config via API
        const response = await fetch(`${API_BASE}/api/run`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ scenario, model, oversight, runs })
        });
        
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
        }
        
        // Start log streaming
        startLogStream();
        updateStatus('running');
        
    } catch (error) {
        console.error('Failed to start run:', error);
        appendLog('error', `Failed to start: ${error.message}`);
        resetRunState();
    }
}

async function cancelRun() {
    try {
        const response = await fetch(`${API_BASE}/api/run`, {
            method: 'DELETE'
        });
        
        const result = await response.json();
        appendLog('warn', 'Run cancelled by user');
        updateStatus('cancelled');
        
    } catch (error) {
        console.error('Failed to cancel run:', error);
    } finally {
        stopLogStream();
        resetRunState();
    }
}

// ==========================================================================
// Log Streaming
// ==========================================================================

function startLogStream() {
    stopLogStream(); // Close any existing connection
    
    eventSource = new EventSource(`${API_BASE}/api/logs/stream`);
    
    eventSource.onmessage = (event) => {
        const data = event.data;
        if (data) {
            appendLog('info', data);
        }
    };
    
    eventSource.addEventListener('log', (event) => {
        const data = event.data;
        if (data) {
            appendLog('info', data);
        }
    });
    
    eventSource.addEventListener('done', (event) => {
        appendLog('info', '=== Run Complete ===');
        stopLogStream();
        isRunning = false;
        updateStatus('complete');
        resetRunState();
        loadResults();
    });
    
    eventSource.addEventListener('error', (event) => {
        console.error('SSE Error:', event);
    });
}

function stopLogStream() {
    if (eventSource) {
        eventSource.close();
        eventSource = null;
    }
}

function appendLog(level, message) {
    // Remove empty state if present
    const emptyState = elements.logsContainer.querySelector('.logs-empty');
    if (emptyState) {
        emptyState.remove();
    }
    
    const line = document.createElement('div');
    line.className = 'log-line';
    
    // Color based on content
    let logLevel = 'log-level-3';
    if (message.includes('[ERROR]') || message.includes('error') || message.includes('Error')) {
        logLevel = 'log-level-1';
    } else if (message.includes('[WARN]') || message.includes('warning') || message.includes('Warning')) {
        logLevel = 'log-level-2';
    } else if (message.includes('[DEBUG]') || message.includes('[DEBUG+]')) {
        logLevel = 'log-level-4';
    }
    
    line.classList.add(logLevel);
    line.textContent = message;
    
    elements.logsContainer.appendChild(line);
    
    // Auto-scroll to bottom
    elements.logsContainer.scrollTop = elements.logsContainer.scrollHeight;
}

function clearLogs() {
    elements.logsContainer.innerHTML = '<div class="logs-empty">Run an experiment to see logs...</div>';
}

// ==========================================================================
// Status Polling
// ==========================================================================

let statusPollingInterval = null;

function startStatusPolling() {
    statusPollingInterval = setInterval(async () => {
        try {
            const response = await fetch(`${API_BASE}/api/run/status`);
            const status = await response.json();
            
            if (status.status !== 'idle' && !isRunning) {
                // Something is running but we don't know about it
                isRunning = true;
                elements.runBtn.classList.add('loading');
                elements.runBtn.disabled = true;
                elements.cancelBtn.disabled = false;
                startLogStream();
            }
            
            updateStatusDisplay(status.status, status.start_time);
            
        } catch (error) {
            console.error('Status poll error:', error);
        }
    }, 2000);
}

function updateStatus(status) {
    updateStatusDisplay(status);
    
    if (status === 'running') {
        elements.runBtn.classList.add('loading');
        elements.runBtn.disabled = true;
        elements.cancelBtn.disabled = false;
    }
}

function updateStatusDisplay(status, startTime = null) {
    elements.statusBadge.className = `badge badge-${status}`;
    
    const statusText = {
        'idle': 'Idle',
        'running': 'Running...',
        'complete': 'Complete',
        'error': 'Error',
        'cancelled': 'Cancelled'
    };
    
    elements.statusBadge.textContent = statusText[status] || status;
    
    if (startTime) {
        const date = new Date(startTime);
        elements.statusTime.textContent = `Started: ${date.toLocaleTimeString()}`;
    } else if (status === 'idle') {
        elements.statusTime.textContent = '';
    }
}

function resetRunState() {
    elements.runBtn.classList.remove('loading');
    elements.runBtn.disabled = false;
    elements.cancelBtn.disabled = true;
    isRunning = false;
}

// ==========================================================================
// Results Loading
// ==========================================================================

async function loadResults() {
    await Promise.all([
        loadCSVResults(),
        loadImageResults(),
        loadJudgeResults()
    ]);
}

async function loadCSVResults() {
    try {
        const response = await fetch(`${API_BASE}/api/results`);
        const results = await response.json();
        
        if (Object.keys(results).length === 0) {
            elements.csvResults.innerHTML = '<div class="empty-state">No results yet</div>';
            return;
        }
        
        let html = '';
        
        for (const [filename, data] of Object.entries(results)) {
            if (data.error) {
                html += `<h3>${filename}</h3><p>Error: ${data.error}</p>`;
                continue;
            }
            
            html += `<h3>${filename}.csv</h3>`;
            html += '<div style="overflow-x: auto;"><table class="data-table">';
            
            // Header
            html += '<thead><tr>';
            for (const col of data.columns) {
                html += `<th>${col}</th>`;
            }
            html += '</tr></thead>';
            
            // Body
            html += '<tbody>';
            for (const row of data.data) {
                html += '<tr>';
                for (const col of data.columns) {
                    html += `<td>${row[col] ?? ''}</td>`;
                }
                html += '</tr>';
            }
            html += '</tbody></table></div>';
        }
        
        elements.csvResults.innerHTML = html || '<div class="empty-state">No results yet</div>';
        
    } catch (error) {
        console.error('Failed to load CSV results:', error);
    }
}

async function loadImageResults() {
    try {
        const response = await fetch(`${API_BASE}/api/results/images`);
        const images = await response.json();
        
        if (images.length === 0) {
            elements.imageResults.innerHTML = '<div class="empty-state">No visualizations yet</div>';
            return;
        }
        
        elements.imageResults.innerHTML = images.map(img => `
            <div class="image-card">
                <img src="${API_BASE}/api/results/images/${img.name}" alt="${img.name}">
                <div class="image-title">${img.name}</div>
            </div>
        `).join('');
        
    } catch (error) {
        console.error('Failed to load images:', error);
    }
}

async function loadJudgeResults() {
    try {
        const response = await fetch(`${API_BASE}/api/judge/results`);
        const results = await response.json();
        
        if (results.message || Object.keys(results).length === 0) {
            elements.judgeResults.innerHTML = '<div class="empty-state">No judge results yet</div>';
            return;
        }
        
        let html = '';
        
        for (const [filename, data] of Object.entries(results)) {
            if (data.type === 'csv') {
                html += `<h3>${filename}</h3>`;
                html += '<div style="overflow-x: auto;"><table class="data-table">';
                
                html += '<thead><tr>';
                for (const col of data.columns) {
                    html += `<th>${col}</th>`;
                }
                html += '</tr></thead><tbody>';
                
                for (const row of data.data) {
                    html += '<tr>';
                    for (const col of data.columns) {
                        html += `<td>${row[col] ?? ''}</td>`;
                    }
                    html += '</tr>';
                }
                html += '</tbody></table></div>';
            } else {
                html += `<h3>${filename}</h3><pre>${JSON.stringify(data.data, null, 2)}</pre>`;
            }
        }
        
        elements.judgeResults.innerHTML = html || '<div class="empty-state">No judge results</div>';
        
    } catch (error) {
        console.error('Failed to load judge results:', error);
    }
}

// ==========================================================================
// Event Listeners
// ==========================================================================

function setupEventListeners() {
    // Run button
    elements.runBtn.addEventListener('click', startRun);
    
    // Cancel button
    elements.cancelBtn.addEventListener('click', cancelRun);
    
    // Clear logs button
    elements.clearLogsBtn.addEventListener('click', clearLogs);
    
    // Scenario selection - update oversight levels
    elements.scenarioSelect.addEventListener('change', async (e) => {
        const scenarioName = e.target.value;
        if (!scenarioName) return;
        
        try {
            const response = await fetch(`${API_BASE}/api/scenarios/${scenarioName}`);
            const scenario = await response.json();
            updateOversightLevels(scenario);
        } catch (error) {
            console.error('Failed to load scenario details:', error);
        }
    });
    
    // Tab switching
    elements.tabBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            const tabId = btn.dataset.tab;
            
            // Update active tab button
            elements.tabBtns.forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            
            // Update active tab content
            elements.tabContents.forEach(content => {
                content.classList.remove('active');
                if (content.id === `tab-${tabId}`) {
                    content.classList.add('active');
                }
            });
            
            // Load results if switching to results tab
            if (tabId === 'csv' || tabId === 'images' || tabId === 'judge') {
                loadResults();
            }
        });
    });
    
    // Keyboard shortcuts
    document.addEventListener('keydown', (e) => {
        // Ctrl/Cmd + Enter to run
        if ((e.ctrlKey || e.metaKey) && e.key === 'Enter' && !isRunning) {
            startRun();
        }
    });
}

function updateOversightLevels(scenario) {
    const oversightSelect = elements.oversightSelect;
    const levels = scenario.oversight_levels || [];
    
    if (levels.length === 0) {
        // No scenario-specific oversight, use global levels
        oversightSelect.innerHTML = `
            <option value="low">Low</option>
            <option value="mid">Mid</option>
            <option value="high">High</option>
        `;
    } else {
        oversightSelect.innerHTML = levels.map(level => 
            `<option value="${level}">${level.charAt(0).toUpperCase() + level.slice(1)}</option>`
        ).join('');
    }
}