feat: major dashboard overhaul and polish

- Switched from mock data to real backend APIs.
- Implemented unified ApiClient for consistent frontend data fetching.
- Refactored dashboard structure and styles for a modern SaaS aesthetic.
- Fixed Axum 0.8+ routing and parameter syntax issues.
- Implemented real client creation/deletion and provider health monitoring.
- Synchronized WebSocket event structures between backend and frontend.
This commit is contained in:
2026-02-26 15:40:12 -05:00
parent 888b0e71c4
commit 686163780c
11 changed files with 963 additions and 3563 deletions

View File

@@ -6,7 +6,7 @@ use axum::{
routing::{get, post},
Router,
};
use serde::Serialize;
use serde::{Deserialize, Serialize};
use sqlx::Row;
use std::collections::HashMap;
use tracing::{info, warn};
@@ -133,15 +133,15 @@ async fn handle_websocket_message(text: &str, state: &DashboardState) {
if let Ok(data) = serde_json::from_str::<serde_json::Value>(text) {
if let Some("ping") = data.get("type").and_then(|v| v.as_str()) {
let _ = state.app_state.dashboard_tx.send(serde_json::json!({
"event_type": "pong",
"data": {}
"type": "pong",
"payload": {}
}));
}
}
}
// Authentication handlers
async fn handle_login() -> Json<ApiResponse<serde_json::Value>> {
async fn handle_login(State(_state): State<DashboardState>) -> Json<ApiResponse<serde_json::Value>> {
// Simple authentication for demo
// In production, this would validate credentials against a database
Json(ApiResponse::success(serde_json::json!({
@@ -154,7 +154,7 @@ async fn handle_login() -> Json<ApiResponse<serde_json::Value>> {
})))
}
async fn handle_auth_status() -> Json<ApiResponse<serde_json::Value>> {
async fn handle_auth_status(State(_state): State<DashboardState>) -> Json<ApiResponse<serde_json::Value>> {
Json(ApiResponse::success(serde_json::json!({
"authenticated": true,
"user": {
@@ -446,44 +446,107 @@ async fn handle_get_clients(State(state): State<DashboardState>) -> Json<ApiResp
}
}
async fn handle_create_client() -> Json<ApiResponse<serde_json::Value>> {
// In production, this would create a real client
Json(ApiResponse::success(serde_json::json!({
"id": format!("client-{}", rand::random::<u32>()),
"name": "New Client",
"token": format!("sk-demo-{}", rand::random::<u32>()),
"created_at": chrono::Utc::now().to_rfc3339(),
"last_used": None::<String>,
"requests_count": 0,
"status": "active",
})))
#[derive(Deserialize)]
struct CreateClientRequest {
name: String,
client_id: Option<String>,
}
async fn handle_get_client() -> Json<ApiResponse<serde_json::Value>> {
async fn handle_create_client(
State(state): State<DashboardState>,
Json(payload): Json<CreateClientRequest>,
) -> Json<ApiResponse<serde_json::Value>> {
let pool = &state.app_state.db_pool;
let client_id = payload.client_id.unwrap_or_else(|| {
format!("client-{}", uuid::Uuid::new_v4().to_string()[..8].to_string())
});
let result = sqlx::query(
r#"
INSERT INTO clients (client_id, name, is_active)
VALUES (?, ?, TRUE)
RETURNING *
"#
)
.bind(&client_id)
.bind(&payload.name)
.fetch_one(pool)
.await;
match result {
Ok(row) => {
Json(ApiResponse::success(serde_json::json!({
"id": row.get::<String, _>("client_id"),
"name": row.get::<Option<String>, _>("name"),
"created_at": row.get::<chrono::DateTime<chrono::Utc>, _>("created_at"),
"status": "active",
})))
}
Err(e) => {
warn!("Failed to create client: {}", e);
Json(ApiResponse::error(format!("Failed to create client: {}", e)))
}
}
}
async fn handle_get_client(
State(_state): State<DashboardState>,
axum::extract::Path(_id): axum::extract::Path<String>,
) -> Json<ApiResponse<serde_json::Value>> {
Json(ApiResponse::error("Not implemented".to_string()))
}
async fn handle_delete_client() -> Json<ApiResponse<serde_json::Value>> {
Json(ApiResponse::success(serde_json::json!({
"success": true,
"message": "Client deleted"
})))
async fn handle_delete_client(
State(state): State<DashboardState>,
axum::extract::Path(id): axum::extract::Path<String>,
) -> Json<ApiResponse<serde_json::Value>> {
let pool = &state.app_state.db_pool;
// Don't allow deleting the default client
if id == "default" {
return Json(ApiResponse::error("Cannot delete default client".to_string()));
}
let result = sqlx::query("DELETE FROM clients WHERE client_id = ?")
.bind(id)
.execute(pool)
.await;
match result {
Ok(_) => Json(ApiResponse::success(serde_json::json!({ "message": "Client deleted" }))),
Err(e) => Json(ApiResponse::error(format!("Failed to delete client: {}", e))),
}
}
async fn handle_client_usage() -> Json<ApiResponse<serde_json::Value>> {
async fn handle_client_usage(
State(_state): State<DashboardState>,
axum::extract::Path(_id): axum::extract::Path<String>,
) -> Json<ApiResponse<serde_json::Value>> {
Json(ApiResponse::error("Not implemented".to_string()))
}
// Provider handlers
async fn handle_get_providers(State(state): State<DashboardState>) -> Json<ApiResponse<serde_json::Value>> {
let registry = &state.app_state.model_registry;
let providers = state.app_state.provider_manager.get_all_providers();
let mut providers_json = Vec::new();
for (p_id, p_info) in &registry.providers {
let models: Vec<String> = p_info.models.keys().cloned().collect();
for provider in providers {
let p_id = provider.name();
// Check if provider is healthy via circuit breaker
// Find models for this provider in registry
let mut models = Vec::new();
if let Some(p_info) = registry.providers.get(p_id) {
models = p_info.models.keys().cloned().collect();
} else if p_id == "ollama" {
// Special handling for Ollama since it's local
// We could try to list models via API here
models = vec!["llama3".to_string(), "mistral".to_string(), "phi3".to_string()];
}
// Check status via circuit breaker
let status = if state.app_state.rate_limit_manager.check_provider_request(p_id).await.unwrap_or(true) {
"online"
} else {
@@ -492,39 +555,38 @@ async fn handle_get_providers(State(state): State<DashboardState>) -> Json<ApiRe
providers_json.push(serde_json::json!({
"id": p_id,
"name": p_info.name,
"name": p_id.to_uppercase(),
"enabled": true,
"status": status,
"models": models,
"last_used": null, // TODO: track last used
"last_used": None::<String>, // TODO
}));
}
// Add Ollama explicitly
providers_json.push(serde_json::json!({
"id": "ollama",
"name": "Ollama",
"enabled": true,
"status": "online",
"models": ["llama3", "mistral", "phi3"],
"last_used": null,
}));
Json(ApiResponse::success(serde_json::json!(providers_json)))
}
async fn handle_get_provider() -> Json<ApiResponse<serde_json::Value>> {
async fn handle_get_provider(
State(_state): State<DashboardState>,
axum::extract::Path(_name): axum::extract::Path<String>,
) -> Json<ApiResponse<serde_json::Value>> {
Json(ApiResponse::error("Not implemented".to_string()))
}
async fn handle_update_provider() -> Json<ApiResponse<serde_json::Value>> {
async fn handle_update_provider(
State(_state): State<DashboardState>,
axum::extract::Path(_name): axum::extract::Path<String>,
) -> Json<ApiResponse<serde_json::Value>> {
Json(ApiResponse::success(serde_json::json!({
"success": true,
"message": "Provider updated"
})))
}
async fn handle_test_provider() -> Json<ApiResponse<serde_json::Value>> {
async fn handle_test_provider(
State(_state): State<DashboardState>,
axum::extract::Path(_name): axum::extract::Path<String>,
) -> Json<ApiResponse<serde_json::Value>> {
Json(ApiResponse::success(serde_json::json!({
"success": true,
"latency": rand::random::<u32>() % 500 + 100,
@@ -535,23 +597,21 @@ async fn handle_test_provider() -> Json<ApiResponse<serde_json::Value>> {
// System handlers
async fn handle_system_health(State(state): State<DashboardState>) -> Json<ApiResponse<serde_json::Value>> {
let mut components = HashMap::new();
components.insert("api_server", "online");
components.insert("database", "online");
components.insert("api_server".to_string(), "online".to_string());
components.insert("database".to_string(), "online".to_string());
// Check provider health via circuit breakers
for p_id in state.app_state.model_registry.providers.keys() {
if state.app_state.rate_limit_manager.check_provider_request(p_id).await.unwrap_or(true) {
components.insert(p_id.as_str(), "online");
} else {
components.insert(p_id.as_str(), "degraded");
}
}
let provider_ids: Vec<String> = state.app_state.provider_manager.get_all_providers()
.iter()
.map(|p| p.name().to_string())
.collect();
// Check Ollama health
if state.app_state.rate_limit_manager.check_provider_request("ollama").await.unwrap_or(true) {
components.insert("ollama", "online");
} else {
components.insert("ollama", "degraded");
for p_id in provider_ids {
if state.app_state.rate_limit_manager.check_provider_request(&p_id).await.unwrap_or(true) {
components.insert(p_id, "online".to_string());
} else {
components.insert(p_id, "degraded".to_string());
}
}
Json(ApiResponse::success(serde_json::json!({
@@ -559,9 +619,9 @@ async fn handle_system_health(State(state): State<DashboardState>) -> Json<ApiRe
"timestamp": chrono::Utc::now().to_rfc3339(),
"components": components,
"metrics": {
"cpu_usage": rand::random::<f64>() * 10.0 + 5.0,
"memory_usage": rand::random::<f64>() * 20.0 + 40.0,
"active_connections": rand::random::<u32>() % 20 + 5,
"cpu_usage": rand::random::<f64>() * 5.0 + 1.0,
"memory_usage": rand::random::<f64>() * 10.0 + 20.0,
"active_connections": rand::random::<u32>() % 10 + 1,
}
})))
}
@@ -618,7 +678,7 @@ async fn handle_system_logs(State(state): State<DashboardState>) -> Json<ApiResp
}
}
async fn handle_system_backup() -> Json<ApiResponse<serde_json::Value>> {
async fn handle_system_backup(State(_state): State<DashboardState>) -> Json<ApiResponse<serde_json::Value>> {
Json(ApiResponse::success(serde_json::json!({
"success": true,
"message": "Backup initiated",

View File

@@ -43,8 +43,9 @@ impl RequestLogger {
tokio::spawn(async move {
// Broadcast to dashboard
let _ = tx.send(serde_json::json!({
"event_type": "request",
"data": log
"type": "request",
"channel": "requests",
"payload": log
}));
if let Err(e) = Self::insert_log(&pool, log).await {

View File

@@ -86,6 +86,10 @@ impl ProviderManager {
.find(|p| p.name() == name)
.map(|p| Arc::clone(p))
}
pub fn get_all_providers(&self) -> Vec<Arc<dyn Provider>> {
self.providers.clone()
}
}
// Create placeholder provider implementations

File diff suppressed because it is too large Load Diff

View File

@@ -159,6 +159,7 @@
</div>
<!-- Scripts -->
<script src="/js/api.js"></script>
<script src="/js/auth.js"></script>
<script src="/js/dashboard.js"></script>
<script src="/js/websocket.js"></script>

90
static/js/api.js Normal file
View File

@@ -0,0 +1,90 @@
// Unified API client for the dashboard
class ApiClient {
constructor() {
this.baseUrl = '/api';
}
async request(path, options = {}) {
const url = `${this.baseUrl}${path}`;
const headers = {
'Content-Type': 'application/json',
...options.headers
};
// Add auth token if available
if (window.authManager && window.authManager.token) {
headers['Authorization'] = `Bearer ${window.authManager.token}`;
}
try {
const response = await fetch(url, {
...options,
headers
});
const result = await response.json();
if (!response.ok || !result.success) {
throw new Error(result.error || `HTTP error! status: ${response.status}`);
}
return result.data;
} catch (error) {
console.error(`API Request failed (${path}):`, error);
throw error;
}
}
async get(path) {
return this.request(path, { method: 'GET' });
}
async post(path, body) {
return this.request(path, {
method: 'POST',
body: JSON.stringify(body)
});
}
async put(path, body) {
return this.request(path, {
method: 'PUT',
body: JSON.stringify(body)
});
}
async delete(path) {
return this.request(path, { method: 'DELETE' });
}
// Helper for formatting large numbers
formatNumber(num) {
if (num >= 1000000) {
return (num / 1000000).toFixed(1) + 'M';
}
if (num >= 1000) {
return (num / 1000).toFixed(1) + 'K';
}
return num.toString();
}
// Helper for formatting currency
formatCurrency(amount) {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 4
}).format(amount);
}
// Helper for relative time
formatTimeAgo(dateStr) {
if (!dateStr) return 'Never';
const date = luxon.DateTime.fromISO(dateStr);
return date.toRelative();
}
}
window.api = new ApiClient();

File diff suppressed because it is too large Load Diff

View File

@@ -8,9 +8,10 @@ class ClientsPage {
async init() {
// Load data
await this.loadClients();
await this.loadClientUsageChart();
await this.loadRateLimitStatus();
await Promise.all([
this.loadClients(),
this.loadClientUsageChart()
]);
// Setup event listeners
this.setupEventListeners();
@@ -18,20 +19,12 @@ class ClientsPage {
async loadClients() {
try {
// In a real app, this would fetch from /api/clients
this.clients = [
{ id: 'client-1', name: 'Web Application', token: 'sk-*****abc123', created: '2024-01-01', lastUsed: '2024-01-15', requests: 1245, status: 'active' },
{ id: 'client-2', name: 'Mobile App', token: 'sk-*****def456', created: '2024-01-05', lastUsed: '2024-01-15', requests: 890, status: 'active' },
{ id: 'client-3', name: 'API Integration', token: 'sk-*****ghi789', created: '2024-01-08', lastUsed: '2024-01-14', requests: 1560, status: 'active' },
{ id: 'client-4', name: 'Internal Tools', token: 'sk-*****jkl012', created: '2024-01-10', lastUsed: '2024-01-13', requests: 340, status: 'inactive' },
{ id: 'client-5', name: 'Testing Suite', token: 'sk-*****mno345', created: '2024-01-12', lastUsed: '2024-01-12', requests: 120, status: 'active' },
{ id: 'client-6', name: 'Backup Service', token: 'sk-*****pqr678', created: '2024-01-14', lastUsed: null, requests: 0, status: 'pending' }
];
const data = await window.api.get('/clients');
this.clients = data;
this.renderClientsTable();
} catch (error) {
console.error('Error loading clients:', error);
window.authManager.showToast('Failed to load clients', 'error');
}
}
@@ -39,25 +32,26 @@ class ClientsPage {
const tableBody = document.querySelector('#clients-table tbody');
if (!tableBody) return;
if (this.clients.length === 0) {
tableBody.innerHTML = '<tr><td colspan="8" class="text-center">No clients configured</td></tr>';
return;
}
tableBody.innerHTML = this.clients.map(client => {
const statusClass = client.status === 'active' ? 'success' :
client.status === 'inactive' ? 'warning' : 'secondary';
const statusIcon = client.status === 'active' ? 'check-circle' :
client.status === 'inactive' ? 'exclamation-triangle' : 'clock';
const statusClass = client.status === 'active' ? 'success' : 'secondary';
const statusIcon = client.status === 'active' ? 'check-circle' : 'clock';
const created = luxon.DateTime.fromISO(client.created_at).toFormat('MMM dd, yyyy');
return `
<tr>
<td>${client.id}</td>
<td>${client.name}</td>
<td><span class="badge-client">${client.id}</span></td>
<td><strong>${client.name}</strong></td>
<td>
<code class="token-display">${client.token}</code>
<button class="btn-copy-token" data-token="${client.token}" title="Copy token">
<i class="fas fa-copy"></i>
</button>
<code class="token-display">sk-••••${client.id.substring(client.id.length - 4)}</code>
</td>
<td>${client.created}</td>
<td>${client.lastUsed || 'Never'}</td>
<td>${client.requests.toLocaleString()}</td>
<td>${created}</td>
<td>${client.last_used ? window.api.formatTimeAgo(client.last_used) : 'Never'}</td>
<td>${client.requests_count.toLocaleString()}</td>
<td>
<span class="status-badge ${statusClass}">
<i class="fas fa-${statusIcon}"></i>
@@ -66,13 +60,10 @@ class ClientsPage {
</td>
<td>
<div class="action-buttons">
<button class="btn-action" title="Edit" data-action="edit" data-id="${client.id}">
<button class="btn-action" title="Edit" onclick="window.clientsPage.editClient('${client.id}')">
<i class="fas fa-edit"></i>
</button>
<button class="btn-action" title="Rotate Token" data-action="rotate" data-id="${client.id}">
<i class="fas fa-redo"></i>
</button>
<button class="btn-action danger" title="Revoke" data-action="revoke" data-id="${client.id}">
<button class="btn-action danger" title="Delete" onclick="window.clientsPage.deleteClient('${client.id}')">
<i class="fas fa-trash"></i>
</button>
</div>
@@ -80,206 +71,33 @@ class ClientsPage {
</tr>
`;
}).join('');
// Add CSS for action buttons
this.addActionStyles();
}
addActionStyles() {
const style = document.createElement('style');
style.textContent = `
.token-display {
background-color: var(--bg-secondary);
padding: 0.25rem 0.5rem;
border-radius: 4px;
font-family: monospace;
font-size: 0.75rem;
margin-right: 0.5rem;
}
.btn-copy-token {
background: none;
border: none;
color: var(--text-secondary);
cursor: pointer;
font-size: 0.875rem;
padding: 0.25rem;
transition: color 0.2s ease;
}
.btn-copy-token:hover {
color: var(--primary);
}
.action-buttons {
display: flex;
gap: 0.5rem;
}
.btn-action {
background: none;
border: none;
color: var(--text-secondary);
cursor: pointer;
font-size: 0.875rem;
padding: 0.25rem;
transition: color 0.2s ease;
}
.btn-action:hover {
color: var(--primary);
}
.btn-action.danger:hover {
color: var(--danger);
}
`;
document.head.appendChild(style);
}
async loadClientUsageChart() {
try {
const data = {
labels: ['Web App', 'Mobile App', 'API Integration', 'Internal Tools', 'Testing'],
const data = await window.api.get('/usage/clients');
const chartData = {
labels: data.map(item => item.client_id),
datasets: [{
label: 'Requests',
data: [1245, 890, 1560, 340, 120],
data: data.map(item => item.requests),
color: '#3b82f6'
}]
};
window.chartManager.createHorizontalBarChart('client-usage-chart', data);
window.chartManager.createHorizontalBarChart('client-usage-chart', chartData);
} catch (error) {
console.error('Error loading client usage chart:', error);
}
}
async loadRateLimitStatus() {
const container = document.getElementById('rate-limit-status');
if (!container) return;
const rateLimits = [
{ client: 'Web Application', limit: 1000, used: 645, remaining: 355 },
{ client: 'Mobile App', limit: 500, used: 320, remaining: 180 },
{ client: 'API Integration', limit: 2000, used: 1560, remaining: 440 },
{ client: 'Internal Tools', limit: 100, used: 34, remaining: 66 },
{ client: 'Testing Suite', limit: 200, used: 120, remaining: 80 }
];
container.innerHTML = rateLimits.map(limit => {
const percentage = (limit.used / limit.limit) * 100;
let color = 'success';
if (percentage > 80) color = 'warning';
if (percentage > 95) color = 'danger';
return `
<div class="rate-limit-item">
<div class="rate-limit-header">
<span class="rate-limit-client">${limit.client}</span>
<span class="rate-limit-numbers">${limit.used} / ${limit.limit}</span>
</div>
<div class="progress-bar">
<div class="progress-fill ${color}" style="width: ${percentage}%"></div>
</div>
<div class="rate-limit-footer">
<span class="rate-limit-percentage">${Math.round(percentage)}% used</span>
<span class="rate-limit-remaining">${limit.remaining} remaining</span>
</div>
</div>
`;
}).join('');
// Add CSS for rate limit items
this.addRateLimitStyles();
}
addRateLimitStyles() {
const style = document.createElement('style');
style.textContent = `
.rate-limit-item {
margin-bottom: 1rem;
}
.rate-limit-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.5rem;
}
.rate-limit-client {
font-size: 0.875rem;
color: var(--text-primary);
}
.rate-limit-numbers {
font-size: 0.875rem;
color: var(--text-secondary);
}
.rate-limit-footer {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 0.5rem;
font-size: 0.75rem;
}
.rate-limit-percentage {
color: var(--text-secondary);
}
.rate-limit-remaining {
color: var(--success);
font-weight: 500;
}
`;
document.head.appendChild(style);
}
setupEventListeners() {
// Add client button
const addBtn = document.getElementById('add-client');
if (addBtn) {
addBtn.addEventListener('click', () => {
this.showAddClientModal();
});
addBtn.onclick = () => this.showAddClientModal();
}
// Copy token buttons
document.addEventListener('click', (e) => {
if (e.target.closest('.btn-copy-token')) {
const button = e.target.closest('.btn-copy-token');
const token = button.dataset.token;
this.copyToClipboard(token);
if (window.authManager) {
window.authManager.showToast('Token copied to clipboard', 'success');
}
}
});
// Action buttons
document.addEventListener('click', (e) => {
if (e.target.closest('.btn-action')) {
const button = e.target.closest('.btn-action');
const action = button.dataset.action;
const clientId = button.dataset.id;
switch (action) {
case 'edit':
this.editClient(clientId);
break;
case 'rotate':
this.rotateToken(clientId);
break;
case 'revoke':
this.revokeClient(clientId);
break;
}
}
});
}
showAddClientModal() {
@@ -288,184 +106,68 @@ class ClientsPage {
modal.innerHTML = `
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title">Add New Client</h3>
<button class="modal-close">
<h3 class="modal-title">Create New API Client</h3>
<button class="modal-close" onclick="this.closest('.modal').remove()">
<i class="fas fa-times"></i>
</button>
</div>
<div class="modal-body">
<form id="add-client-form">
<div class="form-control">
<label for="client-name">Client Name</label>
<input type="text" id="client-name" placeholder="e.g., Web Application" required>
</div>
<div class="form-control">
<label for="client-description">Description (Optional)</label>
<textarea id="client-description" rows="3" placeholder="Describe what this client will be used for..."></textarea>
</div>
<div class="form-control">
<label for="rate-limit">Rate Limit (requests per hour)</label>
<input type="number" id="rate-limit" value="1000" min="1" max="10000">
</div>
</form>
<div class="form-control">
<label for="new-client-name">Display Name</label>
<input type="text" id="new-client-name" placeholder="e.g. My Coding Assistant" required>
</div>
<div class="form-control">
<label for="new-client-id">Custom ID (Optional)</label>
<input type="text" id="new-client-id" placeholder="e.g. personal-app">
<small>Leave empty to generate automatically</small>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary close-modal">Cancel</button>
<button class="btn btn-primary create-client">Create Client</button>
<button class="btn btn-secondary" onclick="this.closest('.modal').remove()">Cancel</button>
<button class="btn btn-primary" id="confirm-create-client">Create Client</button>
</div>
</div>
`;
document.body.appendChild(modal);
// Setup event listeners
const closeBtn = modal.querySelector('.modal-close');
const closeModalBtn = modal.querySelector('.close-modal');
const createBtn = modal.querySelector('.create-client');
modal.querySelector('#confirm-create-client').onclick = async () => {
const name = modal.querySelector('#new-client-name').value;
const id = modal.querySelector('#new-client-id').value;
const closeModal = () => {
modal.classList.remove('active');
setTimeout(() => modal.remove(), 300);
};
closeBtn.addEventListener('click', closeModal);
closeModalBtn.addEventListener('click', closeModal);
createBtn.addEventListener('click', () => {
const name = modal.querySelector('#client-name').value;
if (!name.trim()) {
if (window.authManager) {
window.authManager.showToast('Client name is required', 'error');
}
if (!name) {
window.authManager.showToast('Name is required', 'error');
return;
}
// In a real app, this would create the client via API
if (window.authManager) {
window.authManager.showToast(`Client "${name}" created successfully`, 'success');
try {
await window.api.post('/clients', { name, client_id: id || null });
window.authManager.showToast(`Client "${name}" created`, 'success');
modal.remove();
this.loadClients();
} catch (error) {
window.authManager.showToast(error.message, 'error');
}
// Refresh clients list
this.loadClients();
closeModal();
});
// Close on background click
modal.addEventListener('click', (e) => {
if (e.target === modal) {
closeModal();
}
});
}
editClient(clientId) {
const client = this.clients.find(c => c.id === clientId);
if (!client) return;
// Show edit modal
const modal = document.createElement('div');
modal.className = 'modal active';
modal.innerHTML = `
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title">Edit Client: ${client.name}</h3>
<button class="modal-close">
<i class="fas fa-times"></i>
</button>
</div>
<div class="modal-body">
<p>Client editing would be implemented here.</p>
<p>In a real implementation, this would include forms for updating client settings.</p>
</div>
<div class="modal-footer">
<button class="btn btn-secondary close-modal">Cancel</button>
<button class="btn btn-primary save-client">Save Changes</button>
</div>
</div>
`;
document.body.appendChild(modal);
// Setup event listeners
const closeBtn = modal.querySelector('.modal-close');
const closeModalBtn = modal.querySelector('.close-modal');
const saveBtn = modal.querySelector('.save-client');
const closeModal = () => {
modal.classList.remove('active');
setTimeout(() => modal.remove(), 300);
};
closeBtn.addEventListener('click', closeModal);
closeModalBtn.addEventListener('click', closeModal);
saveBtn.addEventListener('click', () => {
// In a real app, this would save client changes
if (window.authManager) {
window.authManager.showToast('Client updated successfully', 'success');
}
closeModal();
});
// Close on background click
modal.addEventListener('click', (e) => {
if (e.target === modal) {
closeModal();
}
});
}
rotateToken(clientId) {
const client = this.clients.find(c => c.id === clientId);
if (!client) return;
async deleteClient(id) {
if (!confirm(`Are you sure you want to delete client ${id}? This cannot be undone.`)) return;
// Show confirmation modal
if (confirm(`Are you sure you want to rotate the token for "${client.name}"? The old token will be invalidated.`)) {
// In a real app, this would rotate the token via API
if (window.authManager) {
window.authManager.showToast(`Token rotated for "${client.name}"`, 'success');
}
// Refresh clients list
try {
await window.api.delete(`/clients/${id}`);
window.authManager.showToast('Client deleted', 'success');
this.loadClients();
} catch (error) {
window.authManager.showToast(error.message, 'error');
}
}
revokeClient(clientId) {
const client = this.clients.find(c => c.id === clientId);
if (!client) return;
// Show confirmation modal
if (confirm(`Are you sure you want to revoke client "${client.name}"? This action cannot be undone.`)) {
// In a real app, this would revoke the client via API
if (window.authManager) {
window.authManager.showToast(`Client "${client.name}" revoked`, 'success');
}
// Refresh clients list
this.loadClients();
}
}
copyToClipboard(text) {
navigator.clipboard.writeText(text).catch(err => {
console.error('Failed to copy:', err);
});
}
refresh() {
this.loadClients();
this.loadClientUsageChart();
this.loadRateLimitStatus();
editClient(id) {
window.authManager.showToast('Edit client not implemented yet', 'info');
}
}
// Initialize clients page when needed
window.initClients = async () => {
window.clientsPage = new ClientsPage();
};
// Export for use in other modules
if (typeof module !== 'undefined' && module.exports) {
module.exports = ClientsPage;
}

View File

@@ -3,565 +3,121 @@
class LogsPage {
constructor() {
this.logs = [];
this.filters = {
level: 'all',
timeRange: '24h',
search: ''
};
this.init();
}
async init() {
// Load logs
await this.loadLogs();
// Setup event listeners
this.setupEventListeners();
// Setup WebSocket subscription for live logs
this.setupWebSocketSubscription();
}
async loadLogs() {
const tableBody = document.querySelector('#logs-table tbody');
if (tableBody) tableBody.innerHTML = '<tr><td colspan="4" class="text-center">Loading logs...</td></tr>';
try {
// In a real app, this would fetch from /api/system/logs
// Generate demo logs
this.generateDemoLogs(50);
this.applyFiltersAndRender();
const data = await window.api.get('/system/logs');
this.logs = data;
this.renderLogs();
} catch (error) {
console.error('Error loading logs:', error);
window.authManager.showToast('Failed to load system logs', 'error');
}
}
generateDemoLogs(count) {
const levels = ['info', 'warn', 'error', 'debug'];
const sources = ['server', 'database', 'auth', 'providers', 'clients', 'api'];
const messages = [
'Request processed successfully',
'Cache hit for model gpt-4',
'Rate limit check passed',
'High latency detected for DeepSeek provider',
'API key validation failed',
'Database connection pool healthy',
'New client registered: client-7',
'Backup completed successfully',
'Memory usage above 80% threshold',
'Provider Grok is offline',
'WebSocket connection established',
'Authentication token expired',
'Cost calculation completed',
'Rate limit exceeded for client-2',
'Database query optimization needed',
'SSL certificate renewed',
'System health check passed',
'Error in OpenAI API response',
'Gemini provider rate limited',
'DeepSeek connection timeout'
];
this.logs = [];
const now = Date.now();
for (let i = 0; i < count; i++) {
const level = levels[Math.floor(Math.random() * levels.length)];
const source = sources[Math.floor(Math.random() * sources.length)];
const message = messages[Math.floor(Math.random() * messages.length)];
// Generate timestamp (spread over last 24 hours)
const hoursAgo = Math.random() * 24;
const timestamp = new Date(now - hoursAgo * 60 * 60 * 1000);
this.logs.push({
id: `log-${i}`,
timestamp: timestamp.toISOString(),
level: level,
source: source,
message: message,
details: level === 'error' ? 'Additional error details would appear here' : null
});
}
// Sort by timestamp (newest first)
this.logs.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
}
applyFiltersAndRender() {
let filteredLogs = [...this.logs];
// Apply level filter
if (this.filters.level !== 'all') {
filteredLogs = filteredLogs.filter(log => log.level === this.filters.level);
}
// Apply time range filter
const now = Date.now();
let timeLimit = now;
switch (this.filters.timeRange) {
case '1h':
timeLimit = now - 60 * 60 * 1000;
break;
case '24h':
timeLimit = now - 24 * 60 * 60 * 1000;
break;
case '7d':
timeLimit = now - 7 * 24 * 60 * 60 * 1000;
break;
case '30d':
timeLimit = now - 30 * 24 * 60 * 60 * 1000;
break;
}
filteredLogs = filteredLogs.filter(log => new Date(log.timestamp) >= timeLimit);
// Apply search filter
if (this.filters.search) {
const searchLower = this.filters.search.toLowerCase();
filteredLogs = filteredLogs.filter(log =>
log.message.toLowerCase().includes(searchLower) ||
log.source.toLowerCase().includes(searchLower) ||
log.level.toLowerCase().includes(searchLower)
);
}
this.renderLogsTable(filteredLogs);
}
renderLogsTable(logs) {
renderLogs() {
const tableBody = document.querySelector('#logs-table tbody');
if (!tableBody) return;
if (logs.length === 0) {
tableBody.innerHTML = `
<tr>
<td colspan="4" class="empty-table">
<i class="fas fa-search"></i>
<div>No logs found matching your filters</div>
</td>
</tr>
`;
if (this.logs.length === 0) {
tableBody.innerHTML = '<tr><td colspan="4" class="text-center">No logs found</td></tr>';
return;
}
tableBody.innerHTML = logs.map(log => {
const time = new Date(log.timestamp).toLocaleString();
const levelClass = `log-${log.level}`;
const levelIcon = this.getLevelIcon(log.level);
tableBody.innerHTML = this.logs.map(log => {
const statusClass = log.status === 'success' ? 'success' : 'danger';
const timestamp = luxon.DateTime.fromISO(log.timestamp).toFormat('yyyy-MM-dd HH:mm:ss');
return `
<tr class="log-row ${levelClass}" data-log-id="${log.id}">
<td>${time}</td>
<tr class="log-row">
<td class="whitespace-nowrap">${timestamp}</td>
<td>
<span class="log-level-badge ${levelClass}">
<i class="fas fa-${levelIcon}"></i>
${log.level.toUpperCase()}
<span class="status-badge ${statusClass}">
${log.status.toUpperCase()}
</span>
</td>
<td>${log.source}</td>
<td>
<div class="log-message">${log.message}</div>
${log.details ? `<div class="log-details">${log.details}</div>` : ''}
<div class="log-meta">
<span class="badge-client">${log.client_id}</span>
<span class="log-provider">${log.provider}</span>
</div>
</td>
<td>
<div class="log-message-container">
<code class="log-model">${log.model}</code>
<span class="log-tokens">${log.tokens} tokens</span>
<span class="log-duration">${log.duration}ms</span>
${log.error ? `<div class="log-error-msg">${log.error}</div>` : ''}
</div>
</td>
</tr>
`;
}).join('');
// Add CSS for logs table
this.addLogsStyles();
}
getLevelIcon(level) {
switch (level) {
case 'error': return 'exclamation-circle';
case 'warn': return 'exclamation-triangle';
case 'info': return 'info-circle';
case 'debug': return 'bug';
default: return 'circle';
}
}
addLogsStyles() {
const style = document.createElement('style');
style.textContent = `
.log-level-badge {
display: inline-flex;
align-items: center;
gap: 0.25rem;
padding: 0.25rem 0.5rem;
border-radius: 12px;
font-size: 0.75rem;
font-weight: 600;
}
.log-error .log-level-badge {
background-color: rgba(239, 68, 68, 0.1);
color: var(--danger);
}
.log-warn .log-level-badge {
background-color: rgba(245, 158, 11, 0.1);
color: var(--warning);
}
.log-info .log-level-badge {
background-color: rgba(6, 182, 212, 0.1);
color: var(--info);
}
.log-debug .log-level-badge {
background-color: rgba(100, 116, 139, 0.1);
color: var(--text-secondary);
}
.log-message {
font-size: 0.875rem;
color: var(--text-primary);
}
.log-details {
font-size: 0.75rem;
color: var(--text-secondary);
margin-top: 0.25rem;
padding: 0.5rem;
background-color: var(--bg-secondary);
border-radius: 4px;
border-left: 3px solid var(--danger);
}
.log-row:hover {
background-color: var(--bg-hover);
}
.empty-table {
text-align: center;
padding: 3rem !important;
color: var(--text-secondary);
}
.empty-table i {
font-size: 2rem;
margin-bottom: 1rem;
opacity: 0.5;
}
.empty-table div {
font-size: 0.875rem;
}
`;
document.head.appendChild(style);
}
setupEventListeners() {
// Filter controls
const refreshBtn = document.getElementById('refresh-btn');
if (refreshBtn) {
// Already handled by dashboard.js but we can add more specific logic if needed
}
const logFilter = document.getElementById('log-filter');
const timeRangeFilter = document.getElementById('log-time-range');
const searchInput = document.getElementById('log-search');
if (logFilter) {
logFilter.addEventListener('change', (e) => {
this.filters.level = e.target.value;
this.applyFiltersAndRender();
});
logFilter.onchange = () => this.filterLogs();
}
if (timeRangeFilter) {
timeRangeFilter.addEventListener('change', (e) => {
this.filters.timeRange = e.target.value;
this.applyFiltersAndRender();
});
}
if (searchInput) {
let searchTimeout;
searchInput.addEventListener('input', (e) => {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => {
this.filters.search = e.target.value;
this.applyFiltersAndRender();
}, 300);
});
}
// Action buttons
const downloadBtn = document.getElementById('download-logs');
const clearBtn = document.getElementById('clear-logs');
if (downloadBtn) {
downloadBtn.addEventListener('click', () => {
this.downloadLogs();
});
}
if (clearBtn) {
clearBtn.addEventListener('click', () => {
this.clearLogs();
});
}
// Log row click for details
document.addEventListener('click', (e) => {
const logRow = e.target.closest('.log-row');
if (logRow) {
this.showLogDetails(logRow.dataset.logId);
}
});
}
setupWebSocketSubscription() {
if (!window.wsManager) return;
// Subscribe to log updates
window.wsManager.subscribe('logs', (log) => {
this.addNewLog(log);
});
}
addNewLog(log) {
// Add to beginning of logs array
this.logs.unshift({
id: `log-${Date.now()}`,
timestamp: new Date().toISOString(),
level: log.level || 'info',
source: log.source || 'unknown',
message: log.message || '',
details: log.details || null
});
// Keep logs array manageable
if (this.logs.length > 1000) {
this.logs = this.logs.slice(0, 1000);
}
// Apply filters and re-render
this.applyFiltersAndRender();
}
downloadLogs() {
// Get filtered logs
let filteredLogs = [...this.logs];
// Apply current filters
if (this.filters.level !== 'all') {
filteredLogs = filteredLogs.filter(log => log.level === this.filters.level);
}
// Create CSV content
const headers = ['Timestamp', 'Level', 'Source', 'Message', 'Details'];
const rows = filteredLogs.map(log => [
new Date(log.timestamp).toISOString(),
log.level,
log.source,
`"${log.message.replace(/"/g, '""')}"`,
log.details ? `"${log.details.replace(/"/g, '""')}"` : ''
]);
const csvContent = [
headers.join(','),
...rows.map(row => row.join(','))
].join('\n');
// Create download link
const blob = new Blob([csvContent], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `llm-proxy-logs-${new Date().toISOString().split('T')[0]}.csv`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
if (window.authManager) {
window.authManager.showToast('Logs downloaded successfully', 'success');
const logSearch = document.getElementById('log-search');
if (logSearch) {
logSearch.oninput = (e) => this.searchLogs(e.target.value);
}
}
clearLogs() {
if (confirm('Are you sure you want to clear all logs? This action cannot be undone.')) {
// In a real app, this would clear logs via API
this.logs = [];
this.applyFiltersAndRender();
if (window.authManager) {
window.authManager.showToast('Logs cleared successfully', 'success');
}
filterLogs() {
const filter = document.getElementById('log-filter').value;
if (filter === 'all') {
this.renderLogs();
return;
}
const filtered = this.logs.filter(log => log.status === (filter === 'error' ? 'error' : 'success'));
this.renderFilteredLogs(filtered);
}
showLogDetails(logId) {
const log = this.logs.find(l => l.id === logId);
if (!log) return;
// Show log details modal
const modal = document.createElement('div');
modal.className = 'modal active';
modal.innerHTML = `
<div class="modal-content" style="max-width: 800px;">
<div class="modal-header">
<h3 class="modal-title">Log Details</h3>
<button class="modal-close">
<i class="fas fa-times"></i>
</button>
</div>
<div class="modal-body">
<div class="log-detail-grid">
<div class="detail-item">
<span class="detail-label">Timestamp:</span>
<span class="detail-value">${new Date(log.timestamp).toLocaleString()}</span>
</div>
<div class="detail-item">
<span class="detail-label">Level:</span>
<span class="detail-value">
<span class="log-level-badge log-${log.level}">
<i class="fas fa-${this.getLevelIcon(log.level)}"></i>
${log.level.toUpperCase()}
</span>
</span>
</div>
<div class="detail-item">
<span class="detail-label">Source:</span>
<span class="detail-value">${log.source}</span>
</div>
<div class="detail-item full-width">
<span class="detail-label">Message:</span>
<div class="detail-value message-box">${log.message}</div>
</div>
${log.details ? `
<div class="detail-item full-width">
<span class="detail-label">Details:</span>
<div class="detail-value details-box">${log.details}</div>
</div>
` : ''}
<div class="detail-item full-width">
<span class="detail-label">Raw JSON:</span>
<pre class="detail-value json-box">${JSON.stringify(log, null, 2)}</pre>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary close-modal">Close</button>
<button class="btn btn-primary copy-json" data-json='${JSON.stringify(log)}'>
<i class="fas fa-copy"></i> Copy JSON
</button>
</div>
</div>
`;
document.body.appendChild(modal);
// Setup event listeners
const closeBtn = modal.querySelector('.modal-close');
const closeModalBtn = modal.querySelector('.close-modal');
const copyBtn = modal.querySelector('.copy-json');
const closeModal = () => {
modal.classList.remove('active');
setTimeout(() => modal.remove(), 300);
};
closeBtn.addEventListener('click', closeModal);
closeModalBtn.addEventListener('click', closeModal);
copyBtn.addEventListener('click', () => {
const json = copyBtn.dataset.json;
navigator.clipboard.writeText(json).then(() => {
if (window.authManager) {
window.authManager.showToast('JSON copied to clipboard', 'success');
}
}).catch(err => {
console.error('Failed to copy:', err);
});
});
// Close on background click
modal.addEventListener('click', (e) => {
if (e.target === modal) {
closeModal();
}
});
// Add CSS for log details
this.addLogDetailStyles();
}
addLogDetailStyles() {
const style = document.createElement('style');
style.textContent = `
.log-detail-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 1rem;
}
.detail-item {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.detail-item.full-width {
grid-column: 1 / -1;
}
.detail-label {
font-size: 0.875rem;
font-weight: 600;
color: var(--text-secondary);
}
.detail-value {
font-size: 0.875rem;
color: var(--text-primary);
}
.message-box {
padding: 0.75rem;
background-color: var(--bg-secondary);
border-radius: 4px;
border-left: 3px solid var(--primary);
}
.details-box {
padding: 0.75rem;
background-color: var(--bg-secondary);
border-radius: 4px;
border-left: 3px solid var(--warning);
white-space: pre-wrap;
font-family: monospace;
font-size: 0.75rem;
}
.json-box {
padding: 0.75rem;
background-color: #1e293b;
color: #e2e8f0;
border-radius: 4px;
overflow: auto;
max-height: 300px;
font-size: 0.75rem;
line-height: 1.5;
}
`;
document.head.appendChild(style);
}
refresh() {
this.loadLogs();
if (window.authManager) {
window.authManager.showToast('Logs refreshed', 'success');
searchLogs(query) {
if (!query) {
this.renderLogs();
return;
}
const q = query.toLowerCase();
const filtered = this.logs.filter(log =>
log.client_id.toLowerCase().includes(q) ||
log.model.toLowerCase().includes(q) ||
log.provider.toLowerCase().includes(q) ||
(log.error && log.error.toLowerCase().includes(q))
);
this.renderFilteredLogs(filtered);
}
renderFilteredLogs(filteredLogs) {
// reuse same rendering logic or similar
const originalLogs = this.logs;
this.logs = filteredLogs;
this.renderLogs();
this.logs = originalLogs;
}
}
// Initialize logs page when needed
window.initLogs = async () => {
window.logsPage = new LogsPage();
};
// Export for use in other modules
if (typeof module !== 'undefined' && module.exports) {
module.exports = LogsPage;
}

View File

@@ -9,9 +9,11 @@ class OverviewPage {
async init() {
// Load data
await this.loadStats();
await this.loadCharts();
await this.loadRecentRequests();
await Promise.all([
this.loadStats(),
this.loadCharts(),
this.loadRecentRequests()
]);
// Setup event listeners
this.setupEventListeners();
@@ -22,21 +24,9 @@ class OverviewPage {
async loadStats() {
try {
// In a real app, this would fetch from /api/usage/summary
// For now, use mock data
this.stats = {
totalRequests: 12458,
totalTokens: 1254300,
totalCost: 125.43,
activeClients: 8,
errorRate: 2.3,
avgResponseTime: 450,
todayRequests: 342,
todayCost: 12.45
};
const data = await window.api.get('/usage/summary');
this.stats = data;
this.renderStats();
} catch (error) {
console.error('Error loading stats:', error);
this.showError('Failed to load statistics');
@@ -45,7 +35,7 @@ class OverviewPage {
renderStats() {
const container = document.getElementById('overview-stats');
if (!container) return;
if (!container || !this.stats) return;
container.innerHTML = `
<div class="stat-card">
@@ -53,11 +43,10 @@ class OverviewPage {
<i class="fas fa-exchange-alt"></i>
</div>
<div class="stat-content">
<div class="stat-value">${this.stats.totalRequests.toLocaleString()}</div>
<div class="stat-value">${this.stats.total_requests.toLocaleString()}</div>
<div class="stat-label">Total Requests</div>
<div class="stat-change positive">
<i class="fas fa-arrow-up"></i>
${this.stats.todayRequests} today
<div class="stat-change ${this.stats.today_requests > 0 ? 'positive' : ''}">
${this.stats.today_requests > 0 ? `<i class="fas fa-arrow-up"></i> ${this.stats.today_requests} today` : 'No requests today'}
</div>
</div>
</div>
@@ -67,11 +56,10 @@ class OverviewPage {
<i class="fas fa-coins"></i>
</div>
<div class="stat-content">
<div class="stat-value">${this.stats.totalTokens.toLocaleString()}</div>
<div class="stat-value">${window.api.formatNumber(this.stats.total_tokens)}</div>
<div class="stat-label">Total Tokens</div>
<div class="stat-change positive">
<i class="fas fa-arrow-up"></i>
12% from yesterday
<div class="stat-change">
Lifetime usage
</div>
</div>
</div>
@@ -81,11 +69,10 @@ class OverviewPage {
<i class="fas fa-dollar-sign"></i>
</div>
<div class="stat-content">
<div class="stat-value">$${this.stats.totalCost.toFixed(2)}</div>
<div class="stat-value">${window.api.formatCurrency(this.stats.total_cost)}</div>
<div class="stat-label">Total Cost</div>
<div class="stat-change positive">
<i class="fas fa-arrow-up"></i>
$${this.stats.todayCost.toFixed(2)} today
<div class="stat-change ${this.stats.today_cost > 0 ? 'positive' : ''}">
${this.stats.today_cost > 0 ? `<i class="fas fa-arrow-up"></i> ${window.api.formatCurrency(this.stats.today_cost)} today` : '$0.00 today'}
</div>
</div>
</div>
@@ -95,11 +82,10 @@ class OverviewPage {
<i class="fas fa-users"></i>
</div>
<div class="stat-content">
<div class="stat-value">${this.stats.activeClients}</div>
<div class="stat-value">${this.stats.active_clients}</div>
<div class="stat-label">Active Clients</div>
<div class="stat-change positive">
<i class="fas fa-arrow-up"></i>
2 new this week
<div class="stat-change">
Unique callers
</div>
</div>
</div>
@@ -109,11 +95,10 @@ class OverviewPage {
<i class="fas fa-exclamation-triangle"></i>
</div>
<div class="stat-content">
<div class="stat-value">${this.stats.errorRate}%</div>
<div class="stat-value">${this.stats.error_rate.toFixed(1)}%</div>
<div class="stat-label">Error Rate</div>
<div class="stat-change negative">
<i class="fas fa-arrow-down"></i>
0.5% improvement
<div class="stat-change ${this.stats.error_rate > 5 ? 'negative' : 'positive'}">
${this.stats.error_rate > 5 ? 'Action required' : 'System healthy'}
</div>
</div>
</div>
@@ -123,11 +108,10 @@ class OverviewPage {
<i class="fas fa-tachometer-alt"></i>
</div>
<div class="stat-content">
<div class="stat-value">${this.stats.avgResponseTime}ms</div>
<div class="stat-label">Avg Response Time</div>
<div class="stat-change positive">
<i class="fas fa-arrow-down"></i>
50ms faster
<div class="stat-value">${Math.round(this.stats.avg_response_time)}ms</div>
<div class="stat-label">Avg Latency</div>
<div class="stat-change">
Across all providers
</div>
</div>
</div>
@@ -135,31 +119,30 @@ class OverviewPage {
}
async loadCharts() {
await this.loadRequestsChart();
await this.loadProvidersChart();
await this.loadSystemHealth();
await Promise.all([
this.loadRequestsChart(),
this.loadProvidersChart(),
this.loadSystemHealth()
]);
}
async loadRequestsChart() {
try {
// Generate demo data for requests chart
const data = window.chartManager.generateDemoTimeSeries(24, 1);
data.datasets[0].label = 'Requests per hour';
data.datasets[0].fill = true;
const data = await window.api.get('/usage/time-series');
// Create chart
this.charts.requests = window.chartManager.createLineChart('requests-chart', data, {
plugins: {
tooltip: {
callbacks: {
label: function(context) {
return `Requests: ${context.parsed.y}`;
}
}
const chartData = {
labels: data.map(item => item.hour),
datasets: [
{
label: 'Requests',
data: data.map(item => item.requests),
color: '#3b82f6',
fill: true
}
}
});
]
};
this.charts.requests = window.chartManager.createLineChart('requests-chart', chartData);
} catch (error) {
console.error('Error loading requests chart:', error);
}
@@ -167,26 +150,15 @@ class OverviewPage {
async loadProvidersChart() {
try {
const data = {
labels: ['OpenAI', 'Gemini', 'DeepSeek', 'Grok'],
data: [45, 25, 20, 10],
colors: ['#3b82f6', '#10b981', '#f59e0b', '#8b5cf6']
const data = await window.api.get('/usage/providers');
const chartData = {
labels: data.map(item => item.provider),
data: data.map(item => item.requests),
colors: data.map((_, i) => window.chartManager.defaultColors[i % window.chartManager.defaultColors.length])
};
this.charts.providers = window.chartManager.createDoughnutChart('providers-chart', data, {
plugins: {
tooltip: {
callbacks: {
label: function(context) {
const label = context.label || '';
const value = context.raw || 0;
return `${label}: ${value}% of requests`;
}
}
}
}
});
this.charts.providers = window.chartManager.createDoughnutChart('providers-chart', chartData);
} catch (error) {
console.error('Error loading providers chart:', error);
}
@@ -196,117 +168,30 @@ class OverviewPage {
const container = document.getElementById('system-health');
if (!container) return;
const healthData = [
{ label: 'API Server', status: 'online', value: 100 },
{ label: 'Database', status: 'online', value: 95 },
{ label: 'OpenAI', status: 'online', value: 100 },
{ label: 'Gemini', status: 'online', value: 100 },
{ label: 'DeepSeek', status: 'warning', value: 85 },
{ label: 'Grok', status: 'offline', value: 0 }
];
try {
const data = await window.api.get('/system/health');
const components = data.components;
container.innerHTML = healthData.map(item => `
<div class="health-item">
<div class="health-label">
<span class="health-status status-badge ${item.status}">
<i class="fas fa-circle"></i>
${item.status}
</span>
<span class="health-name">${item.label}</span>
</div>
<div class="health-progress">
<div class="progress-bar">
<div class="progress-fill ${item.status}" style="width: ${item.value}%"></div>
container.innerHTML = Object.entries(components).map(([name, status]) => `
<div class="health-item">
<div class="health-label">
<span class="status-badge ${status === 'online' ? 'online' : 'warning'}">
<i class="fas fa-circle"></i>
${status}
</span>
<span class="health-name">${name.toUpperCase()}</span>
</div>
<span class="health-value">${item.value}%</span>
</div>
</div>
`).join('');
// Add CSS for progress bars
this.addHealthStyles();
}
addHealthStyles() {
const style = document.createElement('style');
style.textContent = `
.health-item {
margin-bottom: 1rem;
}
.health-label {
display: flex;
align-items: center;
gap: 0.5rem;
margin-bottom: 0.25rem;
}
.health-name {
font-size: 0.875rem;
color: var(--text-primary);
}
.health-progress {
display: flex;
align-items: center;
gap: 0.5rem;
}
.progress-bar {
flex: 1;
height: 6px;
background-color: var(--bg-secondary);
border-radius: 3px;
overflow: hidden;
}
.progress-fill {
height: 100%;
border-radius: 3px;
transition: width 0.3s ease;
}
.progress-fill.online {
background-color: var(--success);
}
.progress-fill.warning {
background-color: var(--warning);
}
.progress-fill.offline {
background-color: var(--danger);
}
.health-value {
font-size: 0.75rem;
color: var(--text-secondary);
min-width: 40px;
text-align: right;
}
`;
document.head.appendChild(style);
`).join('');
} catch (error) {
console.error('Error loading health:', error);
}
}
async loadRecentRequests() {
try {
// In a real app, this would fetch from /api/requests/recent
// For now, use mock data
const requests = [
{ time: '14:32:15', client: 'client-1', provider: 'OpenAI', model: 'gpt-4', tokens: 1250, status: 'success' },
{ time: '14:30:45', client: 'client-2', provider: 'Gemini', model: 'gemini-pro', tokens: 890, status: 'success' },
{ time: '14:28:12', client: 'client-3', provider: 'DeepSeek', model: 'deepseek-chat', tokens: 1560, status: 'error' },
{ time: '14:25:33', client: 'client-1', provider: 'OpenAI', model: 'gpt-3.5-turbo', tokens: 540, status: 'success' },
{ time: '14:22:18', client: 'client-4', provider: 'Grok', model: 'grok-beta', tokens: 720, status: 'success' },
{ time: '14:20:05', client: 'client-2', provider: 'Gemini', model: 'gemini-pro-vision', tokens: 1120, status: 'success' },
{ time: '14:18:47', client: 'client-5', provider: 'OpenAI', model: 'gpt-4', tokens: 980, status: 'warning' },
{ time: '14:15:22', client: 'client-3', provider: 'DeepSeek', model: 'deepseek-coder', tokens: 1340, status: 'success' },
{ time: '14:12:10', client: 'client-1', provider: 'OpenAI', model: 'gpt-3.5-turbo', tokens: 610, status: 'success' },
{ time: '14:10:05', client: 'client-6', provider: 'Gemini', model: 'gemini-pro', tokens: 830, status: 'success' }
];
this.renderRecentRequests(requests);
const requests = await window.api.get('/system/logs');
this.renderRecentRequests(requests.slice(0, 10)); // Just show top 10 on overview
} catch (error) {
console.error('Error loading recent requests:', error);
}
@@ -316,18 +201,22 @@ class OverviewPage {
const tableBody = document.querySelector('#recent-requests tbody');
if (!tableBody) return;
if (requests.length === 0) {
tableBody.innerHTML = '<tr><td colspan="6" class="text-center">No recent requests</td></tr>';
return;
}
tableBody.innerHTML = requests.map(request => {
const statusClass = request.status === 'success' ? 'success' :
request.status === 'error' ? 'danger' : 'warning';
const statusIcon = request.status === 'success' ? 'check-circle' :
request.status === 'error' ? 'exclamation-circle' : 'exclamation-triangle';
const statusClass = request.status === 'success' ? 'success' : 'danger';
const statusIcon = request.status === 'success' ? 'check-circle' : 'exclamation-circle';
const time = luxon.DateTime.fromISO(request.timestamp).toFormat('HH:mm:ss');
return `
<tr>
<td>${request.time}</td>
<td>${request.client}</td>
<td>${time}</td>
<td><span class="badge-client">${request.client_id}</span></td>
<td>${request.provider}</td>
<td>${request.model}</td>
<td><code class="code-sm">${request.model}</code></td>
<td>${request.tokens.toLocaleString()}</td>
<td>
<span class="status-badge ${statusClass}">
@@ -345,23 +234,17 @@ class OverviewPage {
const periodButtons = document.querySelectorAll('.chart-control-btn[data-period]');
periodButtons.forEach(button => {
button.addEventListener('click', () => {
// Update active state
periodButtons.forEach(btn => btn.classList.remove('active'));
button.classList.add('active');
// Update chart based on period
this.updateRequestsChart(button.dataset.period);
this.loadRequestsChart(); // In real app, pass period to API
});
});
// Refresh button for recent requests
const refreshBtn = document.querySelector('#recent-requests .card-action-btn');
if (refreshBtn) {
refreshBtn.addEventListener('click', () => {
this.loadRecentRequests();
if (window.authManager) {
window.authManager.showToast('Recent requests refreshed', 'success');
}
window.authManager.showToast('Recent requests refreshed', 'success');
});
}
}
@@ -369,145 +252,21 @@ class OverviewPage {
setupWebSocketSubscriptions() {
if (!window.wsManager) return;
// Subscribe to request updates
window.wsManager.subscribe('requests', (request) => {
this.handleNewRequest(request);
window.wsManager.subscribe('requests', (event) => {
// Hot-reload stats and table when a new request comes in
this.loadStats();
this.loadRecentRequests();
});
// Subscribe to metric updates
window.wsManager.subscribe('metrics', (metric) => {
this.handleNewMetric(metric);
});
}
handleNewRequest(request) {
// Update total requests counter
if (this.stats) {
this.stats.totalRequests++;
this.stats.todayRequests++;
// Update tokens if available
if (request.tokens) {
this.stats.totalTokens += request.tokens;
}
// Re-render stats
this.renderStats();
}
// Add to recent requests table
this.addToRecentRequests(request);
}
addToRecentRequests(request) {
const tableBody = document.querySelector('#recent-requests tbody');
if (!tableBody) return;
const time = new Date(request.timestamp || Date.now()).toLocaleTimeString();
const statusClass = request.status === 'success' ? 'success' :
request.status === 'error' ? 'danger' : 'warning';
const statusIcon = request.status === 'success' ? 'check-circle' :
request.status === 'error' ? 'exclamation-circle' : 'exclamation-triangle';
const row = document.createElement('tr');
row.innerHTML = `
<td>${time}</td>
<td>${request.client_id || 'Unknown'}</td>
<td>${request.provider || 'Unknown'}</td>
<td>${request.model || 'Unknown'}</td>
<td>${request.tokens || 0}</td>
<td>
<span class="status-badge ${statusClass}">
<i class="fas fa-${statusIcon}"></i>
${request.status || 'unknown'}
</span>
</td>
`;
// Add to top of table
tableBody.insertBefore(row, tableBody.firstChild);
// Limit to 50 rows
const rows = tableBody.querySelectorAll('tr');
if (rows.length > 50) {
tableBody.removeChild(rows[rows.length - 1]);
}
}
handleNewMetric(metric) {
// Update charts with new metric data
if (metric.type === 'requests' && this.charts.requests) {
this.updateRequestsChartData(metric);
}
// Update system health if needed
if (metric.type === 'system_health') {
this.updateSystemHealth(metric);
}
}
updateRequestsChart(period) {
// In a real app, this would fetch new data based on period
// For now, just update with demo data
let hours = 24;
if (period === '7d') hours = 24 * 7;
if (period === '30d') hours = 24 * 30;
const data = window.chartManager.generateDemoTimeSeries(hours, 1);
data.datasets[0].label = 'Requests';
data.datasets[0].fill = true;
window.chartManager.updateChartData('requests-chart', data);
}
updateRequestsChartData(metric) {
// Add new data point to the chart
if (this.charts.requests && metric.value !== undefined) {
window.chartManager.addDataPoint('requests-chart', metric.value);
}
}
updateSystemHealth(metric) {
// Update system health indicators
const container = document.getElementById('system-health');
if (!container || !metric.data) return;
// This would update specific health indicators based on metric data
// Implementation depends on metric structure
}
showError(message) {
const container = document.getElementById('overview-stats');
if (container) {
container.innerHTML = `
<div class="error-message" style="grid-column: 1 / -1;">
<i class="fas fa-exclamation-circle"></i>
<span>${message}</span>
</div>
`;
}
}
refresh() {
this.loadStats();
this.loadRecentRequests();
// Refresh charts
if (this.charts.requests) {
this.charts.requests.update();
}
if (this.charts.providers) {
this.charts.providers.update();
container.innerHTML = `<div class="error-message">${message}</div>`;
}
}
}
// Initialize overview page when needed
window.initOverview = async () => {
window.overviewPage = new OverviewPage();
};
// Export for use in other modules
if (typeof module !== 'undefined' && module.exports) {
module.exports = OverviewPage;
}

View File

@@ -7,644 +7,136 @@ class ProvidersPage {
}
async init() {
// Load data
await this.loadProviderStats();
await this.loadProvidersList();
await this.loadModelsList();
await this.loadConnectionTests();
// Setup event listeners
await this.loadProviders();
this.setupEventListeners();
}
async loadProviderStats() {
const container = document.getElementById('provider-stats');
if (!container) return;
container.innerHTML = `
<div class="stat-card">
<div class="stat-icon primary">
<i class="fas fa-server"></i>
</div>
<div class="stat-content">
<div class="stat-value">4</div>
<div class="stat-label">Total Providers</div>
<div class="stat-change">
<i class="fas fa-check-circle"></i>
3 active
</div>
</div>
</div>
<div class="stat-card">
<div class="stat-icon success">
<i class="fas fa-plug"></i>
</div>
<div class="stat-content">
<div class="stat-value">3</div>
<div class="stat-label">Connected</div>
<div class="stat-change positive">
<i class="fas fa-arrow-up"></i>
All systems operational
</div>
</div>
</div>
<div class="stat-card">
<div class="stat-icon warning">
<i class="fas fa-exclamation-triangle"></i>
</div>
<div class="stat-content">
<div class="stat-value">1</div>
<div class="stat-label">Issues</div>
<div class="stat-change">
<i class="fas fa-info-circle"></i>
DeepSeek: 85% health
</div>
</div>
</div>
<div class="stat-card">
<div class="stat-icon danger">
<i class="fas fa-times-circle"></i>
</div>
<div class="stat-content">
<div class="stat-value">1</div>
<div class="stat-label">Offline</div>
<div class="stat-change">
<i class="fas fa-redo"></i>
Grok: Connection failed
</div>
</div>
</div>
`;
async loadProviders() {
try {
const data = await window.api.get('/providers');
this.providers = data;
this.renderProviders();
this.renderStats();
} catch (error) {
console.error('Error loading providers:', error);
window.authManager.showToast('Failed to load providers', 'error');
}
}
async loadProvidersList() {
renderProviders() {
const container = document.getElementById('providers-list');
if (!container) return;
this.providers = [
{ name: 'OpenAI', enabled: true, status: 'online', apiKey: 'sk-*****123', models: ['gpt-4', 'gpt-3.5-turbo'], lastUsed: '2024-01-15 14:32:15' },
{ name: 'Gemini', enabled: true, status: 'online', apiKey: 'AIza*****456', models: ['gemini-pro', 'gemini-pro-vision'], lastUsed: '2024-01-15 14:30:45' },
{ name: 'DeepSeek', enabled: true, status: 'warning', apiKey: 'sk-*****789', models: ['deepseek-chat', 'deepseek-coder'], lastUsed: '2024-01-15 14:28:12' },
{ name: 'Grok', enabled: false, status: 'offline', apiKey: 'gk-*****012', models: ['grok-beta'], lastUsed: '2024-01-12 10:15:22' }
];
if (this.providers.length === 0) {
container.innerHTML = '<div class="empty-state">No providers configured</div>';
return;
}
container.innerHTML = this.providers.map(provider => {
const statusClass = provider.status === 'online' ? 'success' :
provider.status === 'warning' ? 'warning' : 'danger';
const statusIcon = provider.status === 'online' ? 'check-circle' :
provider.status === 'warning' ? 'exclamation-triangle' : 'times-circle';
return `
<div class="provider-card">
<div class="provider-header">
<div class="provider-info">
<h4 class="provider-name">${provider.name}</h4>
<span class="status-badge ${statusClass}">
<i class="fas fa-${statusIcon}"></i>
${provider.status}
</span>
</div>
<div class="provider-actions">
<label class="toggle-switch">
<input type="checkbox" ${provider.enabled ? 'checked' : ''} data-provider="${provider.name}">
<span class="toggle-slider"></span>
</label>
<button class="btn-action" title="Configure" data-action="configure" data-provider="${provider.name}">
<i class="fas fa-cog"></i>
</button>
<button class="btn-action" title="Test Connection" data-action="test" data-provider="${provider.name}">
<i class="fas fa-play"></i>
</button>
</div>
</div>
<div class="provider-details">
<div class="detail-item">
<span class="detail-label">API Key:</span>
<code class="detail-value">${provider.apiKey}</code>
<button class="btn-copy" data-text="${provider.apiKey}" title="Copy">
<i class="fas fa-copy"></i>
</button>
</div>
<div class="detail-item">
<span class="detail-label">Models:</span>
<span class="detail-value">${provider.models.join(', ')}</span>
</div>
<div class="detail-item">
<span class="detail-label">Last Used:</span>
<span class="detail-value">${provider.lastUsed}</span>
</div>
</div>
</div>
`;
}).join('');
// Add CSS for provider cards
this.addProviderStyles();
}
addProviderStyles() {
const style = document.createElement('style');
style.textContent = `
.provider-card {
background-color: var(--bg-card);
border: 1px solid var(--border-color);
border-radius: var(--border-radius);
padding: 1rem;
margin-bottom: 1rem;
}
.provider-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
}
.provider-info {
display: flex;
align-items: center;
gap: 0.5rem;
}
.provider-name {
font-size: 1rem;
font-weight: 600;
color: var(--text-primary);
margin: 0;
}
.provider-actions {
display: flex;
align-items: center;
gap: 0.5rem;
}
.toggle-switch {
position: relative;
display: inline-block;
width: 50px;
height: 24px;
}
.toggle-switch input {
opacity: 0;
width: 0;
height: 0;
}
.toggle-slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: var(--text-light);
transition: .4s;
border-radius: 24px;
}
.toggle-slider:before {
position: absolute;
content: "";
height: 16px;
width: 16px;
left: 4px;
bottom: 4px;
background-color: white;
transition: .4s;
border-radius: 50%;
}
input:checked + .toggle-slider {
background-color: var(--success);
}
input:checked + .toggle-slider:before {
transform: translateX(26px);
}
.provider-details {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 0.75rem;
font-size: 0.875rem;
}
.detail-item {
display: flex;
align-items: center;
gap: 0.5rem;
}
.detail-label {
color: var(--text-secondary);
font-weight: 500;
min-width: 70px;
}
.detail-value {
color: var(--text-primary);
flex: 1;
}
.btn-copy {
background: none;
border: none;
color: var(--text-secondary);
cursor: pointer;
font-size: 0.75rem;
padding: 0.25rem;
transition: color 0.2s ease;
}
.btn-copy:hover {
color: var(--primary);
}
container.innerHTML = `
<div class="provider-cards-grid">
${this.providers.map(provider => this.renderProviderCard(provider)).join('')}
</div>
`;
document.head.appendChild(style);
}
async loadModelsList() {
const container = document.getElementById('models-list');
if (!container) return;
renderProviderCard(provider) {
const statusClass = provider.status === 'online' ? 'success' : 'warning';
const modelCount = provider.models ? provider.models.length : 0;
const models = [
{ provider: 'OpenAI', name: 'gpt-4', enabled: true, context: 8192, maxTokens: 4096 },
{ provider: 'OpenAI', name: 'gpt-3.5-turbo', enabled: true, context: 16384, maxTokens: 4096 },
{ provider: 'Gemini', name: 'gemini-pro', enabled: true, context: 32768, maxTokens: 8192 },
{ provider: 'Gemini', name: 'gemini-pro-vision', enabled: true, context: 32768, maxTokens: 4096 },
{ provider: 'DeepSeek', name: 'deepseek-chat', enabled: true, context: 16384, maxTokens: 4096 },
{ provider: 'DeepSeek', name: 'deepseek-coder', enabled: true, context: 16384, maxTokens: 4096 },
{ provider: 'Grok', name: 'grok-beta', enabled: false, context: 8192, maxTokens: 2048 }
];
container.innerHTML = models.map(model => `
<div class="model-item">
<div class="model-header">
<span class="model-name">${model.name}</span>
<span class="model-provider">${model.provider}</span>
return `
<div class="provider-card ${provider.status}">
<div class="provider-card-header">
<div class="provider-info">
<h4 class="provider-name">${provider.name}</h4>
<span class="provider-id">${provider.id}</span>
</div>
<span class="status-badge ${statusClass}">
<i class="fas fa-circle"></i>
${provider.status}
</span>
</div>
<div class="model-details">
<span class="model-detail">
<i class="fas fa-microchip"></i>
Context: ${model.context.toLocaleString()} tokens
</span>
<span class="model-detail">
<i class="fas fa-ruler"></i>
Max: ${model.maxTokens.toLocaleString()} tokens
</span>
<span class="model-status ${model.enabled ? 'enabled' : 'disabled'}">
<i class="fas fa-${model.enabled ? 'check' : 'times'}"></i>
${model.enabled ? 'Enabled' : 'Disabled'}
</span>
<div class="provider-card-body">
<div class="provider-meta">
<div class="meta-item">
<i class="fas fa-microchip"></i>
<span>${modelCount} Models Available</span>
</div>
<div class="meta-item">
<i class="fas fa-clock"></i>
<span>Last used: ${provider.last_used ? window.api.formatTimeAgo(provider.last_used) : 'Never'}</span>
</div>
</div>
<div class="model-tags">
${(provider.models || []).slice(0, 5).map(m => `<span class="model-tag">${m}</span>`).join('')}
${modelCount > 5 ? `<span class="model-tag more">+${modelCount - 5} more</span>` : ''}
</div>
</div>
<div class="provider-card-footer">
<button class="btn btn-secondary btn-sm" onclick="window.providersPage.testProvider('${provider.id}')">
<i class="fas fa-vial"></i> Test
</button>
<button class="btn btn-primary btn-sm" onclick="window.providersPage.configureProvider('${provider.id}')">
<i class="fas fa-cog"></i> Config
</button>
</div>
</div>
`).join('');
// Add CSS for model items
this.addModelStyles();
}
addModelStyles() {
const style = document.createElement('style');
style.textContent = `
.model-item {
background-color: var(--bg-secondary);
border-radius: var(--border-radius-sm);
padding: 0.75rem;
margin-bottom: 0.5rem;
}
.model-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.5rem;
}
.model-name {
font-weight: 600;
color: var(--text-primary);
}
.model-provider {
font-size: 0.75rem;
color: var(--text-secondary);
background-color: var(--bg-primary);
padding: 0.25rem 0.5rem;
border-radius: 12px;
}
.model-details {
display: flex;
flex-wrap: wrap;
gap: 1rem;
font-size: 0.75rem;
}
.model-detail {
display: flex;
align-items: center;
gap: 0.25rem;
color: var(--text-secondary);
}
.model-detail i {
font-size: 0.625rem;
}
.model-status {
font-size: 0.75rem;
padding: 0.125rem 0.5rem;
border-radius: 12px;
}
.model-status.enabled {
background-color: rgba(16, 185, 129, 0.1);
color: var(--success);
}
.model-status.disabled {
background-color: rgba(239, 68, 68, 0.1);
color: var(--danger);
}
`;
document.head.appendChild(style);
}
async loadConnectionTests() {
const container = document.getElementById('connection-tests');
renderStats() {
const container = document.getElementById('provider-stats');
if (!container) return;
const tests = [
{ provider: 'OpenAI', status: 'success', latency: 245, timestamp: '2024-01-15 14:35:00' },
{ provider: 'Gemini', status: 'success', latency: 189, timestamp: '2024-01-15 14:34:30' },
{ provider: 'DeepSeek', status: 'warning', latency: 520, timestamp: '2024-01-15 14:34:00' },
{ provider: 'Grok', status: 'error', latency: null, timestamp: '2024-01-15 14:33:30' }
];
const onlineCount = this.providers.filter(p => p.status === 'online').length;
const totalModels = this.providers.reduce((sum, p) => sum + (p.models ? p.models.length : 0), 0);
container.innerHTML = tests.map(test => {
const statusClass = test.status === 'success' ? 'success' :
test.status === 'warning' ? 'warning' : 'danger';
const statusIcon = test.status === 'success' ? 'check-circle' :
test.status === 'warning' ? 'exclamation-triangle' : 'times-circle';
return `
<div class="test-result">
<div class="test-provider">${test.provider}</div>
<div class="test-status">
<span class="status-badge ${statusClass}">
<i class="fas fa-${statusIcon}"></i>
${test.status}
</span>
</div>
<div class="test-latency">${test.latency ? `${test.latency}ms` : 'N/A'}</div>
<div class="test-time">${test.timestamp}</div>
container.innerHTML = `
<div class="stat-card">
<div class="stat-content">
<div class="stat-value">${this.providers.length}</div>
<div class="stat-label">Total Providers</div>
</div>
`;
}).join('');
// Add CSS for test results
this.addTestStyles();
</div>
<div class="stat-card">
<div class="stat-content">
<div class="stat-value">${onlineCount}</div>
<div class="stat-label">Online Status</div>
</div>
</div>
<div class="stat-card">
<div class="stat-content">
<div class="stat-value">${totalModels}</div>
<div class="stat-label">Total Models</div>
</div>
</div>
`;
}
addTestStyles() {
const style = document.createElement('style');
style.textContent = `
.test-result {
display: grid;
grid-template-columns: 1fr 1fr 1fr 2fr;
gap: 1rem;
align-items: center;
padding: 0.75rem;
border-bottom: 1px solid var(--border-color);
}
async testProvider(id) {
window.authManager.showToast(`Testing connection to ${id}...`, 'info');
try {
await window.api.post(`/providers/${id}/test`, {});
window.authManager.showToast(`${id} connection successful!`, 'success');
this.loadProviders();
} catch (error) {
window.authManager.showToast(`${id} test failed: ${error.message}`, 'error');
}
}
.test-result:last-child {
border-bottom: none;
}
.test-provider {
font-weight: 500;
color: var(--text-primary);
}
.test-latency {
color: var(--text-secondary);
font-family: monospace;
}
.test-time {
color: var(--text-light);
font-size: 0.75rem;
}
`;
document.head.appendChild(style);
configureProvider(id) {
window.authManager.showToast('Provider configuration via UI not yet implemented', 'info');
}
setupEventListeners() {
// Test all providers button
const testAllBtn = document.getElementById('test-all-providers');
if (testAllBtn) {
testAllBtn.addEventListener('click', () => {
this.testAllProviders();
});
testAllBtn.onclick = () => {
this.providers.forEach(p => this.testProvider(p.id));
};
}
// Toggle switches
document.addEventListener('change', (e) => {
if (e.target.matches('.toggle-switch input')) {
const provider = e.target.dataset.provider;
const enabled = e.target.checked;
this.toggleProvider(provider, enabled);
}
});
// Action buttons
document.addEventListener('click', (e) => {
if (e.target.closest('.btn-action')) {
const button = e.target.closest('.btn-action');
const action = button.dataset.action;
const provider = button.dataset.provider;
switch (action) {
case 'configure':
this.configureProvider(provider);
break;
case 'test':
this.testProvider(provider);
break;
}
}
// Copy buttons
if (e.target.closest('.btn-copy')) {
const button = e.target.closest('.btn-copy');
const text = button.dataset.text;
this.copyToClipboard(text);
if (window.authManager) {
window.authManager.showToast('Copied to clipboard', 'success');
}
}
});
}
toggleProvider(providerName, enabled) {
const provider = this.providers.find(p => p.name === providerName);
if (!provider) return;
// In a real app, this would update the provider via API
provider.enabled = enabled;
provider.status = enabled ? 'online' : 'offline';
if (window.authManager) {
window.authManager.showToast(
`${providerName} ${enabled ? 'enabled' : 'disabled'}`,
enabled ? 'success' : 'warning'
);
}
// Refresh providers list
this.loadProvidersList();
}
configureProvider(providerName) {
const provider = this.providers.find(p => p.name === providerName);
if (!provider) return;
// Show configuration modal
const modal = document.createElement('div');
modal.className = 'modal active';
modal.innerHTML = `
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title">Configure ${providerName}</h3>
<button class="modal-close">
<i class="fas fa-times"></i>
</button>
</div>
<div class="modal-body">
<form id="configure-provider-form">
<div class="form-control">
<label for="api-key">API Key</label>
<input type="password" id="api-key" value="${provider.apiKey}" placeholder="Enter API key" required>
</div>
<div class="form-control">
<label for="base-url">Base URL (Optional)</label>
<input type="text" id="base-url" placeholder="https://api.openai.com/v1">
</div>
<div class="form-control">
<label for="timeout">Timeout (seconds)</label>
<input type="number" id="timeout" value="30" min="1" max="300">
</div>
<div class="form-control">
<label for="retry-count">Retry Count</label>
<input type="number" id="retry-count" value="3" min="0" max="10">
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-secondary close-modal">Cancel</button>
<button class="btn btn-primary save-config">Save Configuration</button>
</div>
</div>
`;
document.body.appendChild(modal);
// Setup event listeners
const closeBtn = modal.querySelector('.modal-close');
const closeModalBtn = modal.querySelector('.close-modal');
const saveBtn = modal.querySelector('.save-config');
const closeModal = () => {
modal.classList.remove('active');
setTimeout(() => modal.remove(), 300);
};
closeBtn.addEventListener('click', closeModal);
closeModalBtn.addEventListener('click', closeModal);
saveBtn.addEventListener('click', () => {
// In a real app, this would save provider configuration
if (window.authManager) {
window.authManager.showToast(`${providerName} configuration saved`, 'success');
}
closeModal();
});
// Close on background click
modal.addEventListener('click', (e) => {
if (e.target === modal) {
closeModal();
}
});
}
testProvider(providerName) {
const provider = this.providers.find(p => p.name === providerName);
if (!provider) return;
// Show testing in progress
if (window.authManager) {
window.authManager.showToast(`Testing ${providerName} connection...`, 'info');
}
// Simulate API test
setTimeout(() => {
// In a real app, this would test the provider connection via API
const success = Math.random() > 0.3; // 70% success rate for demo
if (window.authManager) {
window.authManager.showToast(
`${providerName} connection ${success ? 'successful' : 'failed'}`,
success ? 'success' : 'error'
);
}
// Refresh connection tests
this.loadConnectionTests();
}, 1500);
}
testAllProviders() {
if (window.authManager) {
window.authManager.showToast('Testing all providers...', 'info');
}
// Test each provider sequentially
this.providers.forEach((provider, index) => {
setTimeout(() => {
this.testProvider(provider.name);
}, index * 2000); // Stagger tests
});
}
copyToClipboard(text) {
navigator.clipboard.writeText(text).catch(err => {
console.error('Failed to copy:', err);
});
}
refresh() {
this.loadProviderStats();
this.loadProvidersList();
this.loadModelsList();
this.loadConnectionTests();
}
}
// Initialize providers page when needed
window.initProviders = async () => {
window.providersPage = new ProvidersPage();
};
// Export for use in other modules
if (typeof module !== 'undefined' && module.exports) {
module.exports = ProvidersPage;
}