feat: cap 503 overload key retries to 1 retry key and split Admin UI into subpages

This commit is contained in:
tyuXX 2026-11-05 19:44:07 +00:00
parent 343208216e
commit 9d44c92b01
15 changed files with 3372 additions and 2997 deletions

View file

@ -36,6 +36,9 @@ RATE_LIMIT_DURATION_MS=60000
# Max consecutive timeouts per model target before tripping circuit breaker (default 0 when fallback tier exists) # Max consecutive timeouts per model target before tripping circuit breaker (default 0 when fallback tier exists)
# MAX_TARGET_TIMEOUT_RETRIES=0 # MAX_TARGET_TIMEOUT_RETRIES=0
# Max key retries per model target on 503 high-demand / overload errors before failing over to next tier (default 1 = max 2 keys tried)
# MAX_TARGET_OVERLOAD_RETRIES=1
# Disable Gemini Content Moderation (injects HarmBlockThreshold.BLOCK_NONE to prevent safety blocks & proxy errors) # Disable Gemini Content Moderation (injects HarmBlockThreshold.BLOCK_NONE to prevent safety blocks & proxy errors)
# DISABLE_GEMINI_MODERATION=true # DISABLE_GEMINI_MODERATION=true

852
src/admin/layout.ts Normal file
View file

@ -0,0 +1,852 @@
export type AdminPageId = 'models' | 'providers' | 'playground' | 'telemetry' | 'live_logs';
export interface AdminLayoutOptions {
activePage: AdminPageId;
pageTitle: string;
bodyHtml: string;
modalsHtml?: string;
pageScript: string;
extraStyles?: string;
}
export function renderAdminLayout(options: AdminLayoutOptions): string {
const { activePage, pageTitle, bodyHtml, modalsHtml = '', pageScript, extraStyles = '' } = options;
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GeminiRevolver — Admin Console & Model Orchestrator (${pageTitle})</title>
<link rel="icon" type="image/svg+xml" href="/favicon.ico">
<link rel="stylesheet" href="https://storage.gsdistance.org/store/icons/css/all.min.css">
<style>
:root {
--primary-color: #bb86fc;
--primary-hover: #cf9eff;
--background-dark: #121212;
--background-light: #ffffff;
--text-dark: #e0e0e0;
--text-light: #121212;
--card-dark: #1f1b24;
--card-light: #f5f5f5;
--border-dark: rgba(187, 134, 252, 0.12);
--border-light: rgba(187, 134, 252, 0.22);
--muted-dark: #9e9e9e;
--muted-light: #616161;
--nav-bg-dark: rgba(18, 18, 18, 0.95);
--nav-bg-light: rgba(255, 255, 255, 0.95);
--accent-success: #03dac6;
--accent-warning: #ffb74d;
--accent-danger: #cf6679;
--accent-info: #64b5f6;
}
body.light-theme {
--accent-success: #00897b;
--accent-warning: #f57c00;
--accent-danger: #d32f2f;
--accent-info: #1976d2;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
background-color: var(--background-dark);
color: var(--text-dark);
min-height: 100vh;
display: flex;
flex-direction: column;
transition: background-color 0.3s ease, color 0.3s ease;
}
body.light-theme {
background-color: var(--background-light);
color: var(--text-light);
}
header {
background-color: var(--nav-bg-dark);
border-bottom: 1px solid var(--border-dark);
padding: 1rem 1.5rem;
position: sticky;
top: 0;
z-index: 100;
backdrop-filter: blur(10px);
transition: background-color 0.3s ease, border-color 0.3s ease;
}
body.light-theme header {
background-color: var(--nav-bg-light);
border-bottom-color: var(--border-light);
}
.header-content {
max-width: 1400px;
margin: 0 auto;
display: flex;
justify-content: space-between;
align-items: center;
gap: 1rem;
flex-wrap: wrap;
}
.logo-container {
display: flex;
align-items: center;
gap: 0.75rem;
text-decoration: none;
color: inherit;
}
.logo-icon {
font-size: 1.5rem;
color: var(--primary-color);
animation: spin 20s linear infinite;
}
@keyframes spin {
100% { transform: rotate(360deg); }
}
.logo-title {
font-size: 1.25rem;
font-weight: 700;
letter-spacing: -0.5px;
}
.logo-badge {
font-size: 0.7rem;
text-transform: uppercase;
background: rgba(187, 134, 252, 0.15);
color: var(--primary-color);
padding: 2px 8px;
border-radius: 12px;
font-weight: 600;
border: 1px solid var(--primary-color);
}
.nav-actions {
display: flex;
align-items: center;
gap: 0.75rem;
}
.nav-btn {
background: rgba(187, 134, 252, 0.1);
border: 1px solid var(--border-dark);
color: inherit;
padding: 0.5rem 0.9rem;
border-radius: 8px;
cursor: pointer;
font-size: 0.85rem;
font-weight: 500;
display: flex;
align-items: center;
gap: 0.5rem;
text-decoration: none;
transition: all 0.2s ease;
}
.nav-btn:hover {
background: rgba(187, 134, 252, 0.2);
border-color: var(--primary-color);
color: var(--primary-color);
}
.nav-btn.primary {
background: var(--primary-color);
color: #121212;
border-color: var(--primary-color);
font-weight: 600;
}
.nav-btn.primary:hover {
background: var(--primary-hover);
}
.nav-btn.danger {
background: rgba(207, 102, 121, 0.15);
border-color: rgba(207, 102, 121, 0.3);
color: var(--accent-danger);
}
.nav-btn.danger:hover {
background: rgba(207, 102, 121, 0.3);
}
.nav-btn.warning {
background: rgba(255, 183, 77, 0.15);
border-color: rgba(255, 183, 77, 0.3);
color: var(--accent-warning);
}
main {
flex: 1;
max-width: 1400px;
width: 100%;
margin: 0 auto;
padding: 2rem 1.5rem;
}
/* Subpage Navigation Bar */
.tabs-nav {
display: flex;
gap: 0.5rem;
border-bottom: 1px solid var(--border-dark);
margin-bottom: 2rem;
overflow-x: auto;
}
body.light-theme .tabs-nav {
border-bottom-color: var(--border-light);
}
.tab-btn {
background: transparent;
border: none;
border-bottom: 2px solid transparent;
color: var(--muted-dark);
padding: 0.75rem 1.25rem;
font-size: 0.95rem;
font-weight: 600;
cursor: pointer;
display: flex;
align-items: center;
gap: 0.5rem;
transition: all 0.2s ease;
white-space: nowrap;
text-decoration: none;
}
body.light-theme .tab-btn {
color: var(--muted-light);
}
.tab-btn:hover {
color: var(--text-dark);
}
body.light-theme .tab-btn:hover {
color: var(--text-light);
}
.tab-btn.active {
color: var(--primary-color);
border-bottom-color: var(--primary-color);
}
.page-content {
animation: fadeIn 0.2s ease;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(4px); }
to { opacity: 1; transform: translateY(0); }
}
/* Section Cards */
.section-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1.5rem;
flex-wrap: wrap;
gap: 1rem;
}
.section-title {
font-size: 1.25rem;
font-weight: 600;
display: flex;
align-items: center;
gap: 0.5rem;
}
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(360px, 1fr));
gap: 1.5rem;
}
.card {
background-color: var(--card-dark);
border: 1px solid var(--border-dark);
border-radius: 12px;
padding: 1.5rem;
transition: all 0.2s ease;
display: flex;
flex-direction: column;
position: relative;
}
body.light-theme .card {
background-color: var(--card-light);
border-color: var(--border-light);
}
.card:hover {
border-color: rgba(187, 134, 252, 0.4);
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
}
.card-top {
display: flex;
justify-content: space-between;
align-items: flex-start;
margin-bottom: 1rem;
}
.card-title {
font-size: 1.1rem;
font-weight: 600;
margin-bottom: 0.25rem;
display: flex;
align-items: center;
gap: 0.5rem;
}
.card-subtitle {
font-size: 0.8rem;
color: var(--muted-dark);
}
body.light-theme .card-subtitle {
color: var(--muted-light);
}
.card-actions {
display: flex;
gap: 0.5rem;
}
.icon-btn {
background: transparent;
border: 1px solid var(--border-dark);
color: var(--muted-dark);
border-radius: 6px;
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: all 0.2s ease;
}
.icon-btn:hover {
color: var(--primary-color);
border-color: var(--primary-color);
}
.icon-btn.delete:hover {
color: var(--accent-danger);
border-color: var(--accent-danger);
}
.badge {
font-size: 0.7rem;
font-weight: 600;
padding: 2px 8px;
border-radius: 10px;
text-transform: uppercase;
display: inline-flex;
align-items: center;
gap: 4px;
}
.badge-primary {
background: rgba(187, 134, 252, 0.15);
color: var(--primary-color);
border: 1px solid rgba(187, 134, 252, 0.3);
}
.badge-success {
background: rgba(3, 218, 198, 0.15);
color: var(--accent-success);
border: 1px solid rgba(3, 218, 198, 0.3);
}
.badge-warning {
background: rgba(255, 183, 77, 0.15);
color: var(--accent-warning);
border: 1px solid rgba(255, 183, 77, 0.3);
}
.badge-info {
background: rgba(100, 181, 246, 0.15);
color: var(--accent-info);
border: 1px solid rgba(100, 181, 246, 0.3);
}
.badge-danger {
background: rgba(207, 102, 121, 0.15);
color: var(--accent-danger);
border: 1px solid rgba(207, 102, 121, 0.3);
}
/* Modal / Dialog */
.modal-overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0, 0.75);
backdrop-filter: blur(4px);
z-index: 1000;
align-items: center;
justify-content: center;
padding: 1rem;
}
.modal-overlay.active {
display: flex;
}
.modal-content {
background: var(--card-dark);
border: 1px solid var(--border-dark);
border-radius: 14px;
max-width: 650px;
width: 100%;
max-height: 90vh;
overflow-y: auto;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
display: flex;
flex-direction: column;
}
body.light-theme .modal-content {
background: var(--card-light);
border-color: var(--border-light);
}
.modal-header {
padding: 1.25rem 1.5rem;
border-bottom: 1px solid var(--border-dark);
display: flex;
justify-content: space-between;
align-items: center;
}
.modal-title {
font-size: 1.15rem;
font-weight: 600;
display: flex;
align-items: center;
gap: 0.5rem;
}
.modal-body {
padding: 1.5rem;
display: flex;
flex-direction: column;
gap: 1.25rem;
}
.modal-footer {
padding: 1.25rem 1.5rem;
border-top: 1px solid var(--border-dark);
display: flex;
justify-content: flex-end;
gap: 0.75rem;
}
/* Forms */
.form-group {
display: flex;
flex-direction: column;
gap: 0.4rem;
}
.form-label {
font-size: 0.85rem;
font-weight: 600;
color: var(--text-dark);
display: flex;
align-items: center;
justify-content: space-between;
}
body.light-theme .form-label {
color: var(--text-light);
}
.form-hint {
font-size: 0.75rem;
color: var(--muted-dark);
font-weight: normal;
}
.form-input, .form-select, .form-textarea {
background: rgba(0, 0, 0, 0.3);
border: 1px solid var(--border-dark);
color: inherit;
padding: 0.65rem 0.85rem;
border-radius: 8px;
font-size: 0.9rem;
font-family: inherit;
outline: none;
transition: border-color 0.2s ease;
}
body.light-theme .form-input,
body.light-theme .form-select,
body.light-theme .form-textarea {
background: #ffffff;
border-color: var(--border-light);
}
.form-input:focus, .form-select:focus, .form-textarea:focus {
border-color: var(--primary-color);
}
.form-textarea {
min-height: 100px;
font-family: monospace;
font-size: 0.85rem;
resize: vertical;
}
.checkbox-label {
display: flex;
align-items: center;
gap: 0.5rem;
cursor: pointer;
font-size: 0.9rem;
font-weight: 500;
}
/* Auth lock screen */
.auth-gate {
max-width: 420px;
margin: 4rem auto;
text-align: center;
}
/* Toasts */
#toast-container {
position: fixed;
bottom: 1.5rem;
right: 1.5rem;
display: flex;
flex-direction: column;
gap: 0.5rem;
z-index: 2000;
}
.toast {
background: var(--card-dark);
border: 1px solid var(--border-dark);
border-radius: 8px;
padding: 0.75rem 1.25rem;
font-size: 0.85rem;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
display: flex;
align-items: center;
gap: 0.5rem;
animation: slideIn 0.2s ease;
}
@keyframes slideIn {
from { transform: translateX(20px); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
.toast.success { border-left: 4px solid var(--accent-success); }
.toast.error { border-left: 4px solid var(--accent-danger); }
.toast.info { border-left: 4px solid var(--accent-info); }
.toast.warning { border-left: 4px solid var(--accent-warning); }
.detail-table {
width: 100%;
border-collapse: collapse;
font-size: 0.82rem;
}
.detail-table td {
padding: 0.4rem 0.5rem;
border-bottom: 1px solid var(--border-dark);
}
body.light-theme .detail-table td {
border-bottom-color: var(--border-light);
}
.detail-table td:first-child {
color: var(--muted-dark);
width: 180px;
font-weight: 500;
}
${extraStyles}
</style>
</head>
<body>
<header>
<div class="header-content">
<a href="/admin/models" class="logo-container">
<i class="fas fa-microchip logo-icon"></i>
<div>
<span class="logo-title">GeminiRevolver</span>
<span class="logo-badge">Admin</span>
</div>
</a>
<div class="nav-actions">
<a href="/" class="nav-btn">
<i class="fas fa-chart-line"></i>
<span>Telemetry Stats</span>
</a>
<button id="theme-toggle" class="nav-btn" title="Toggle Theme">
<i class="fas fa-moon"></i>
</button>
<button id="logout-btn" class="nav-btn danger" style="display: none;" title="Lock Session">
<i class="fas fa-lock"></i>
<span>Lock</span>
</button>
</div>
</div>
</header>
<main>
<!-- Auth Gate (Shown if unauthenticated) -->
<div id="auth-gate-section" class="auth-gate card">
<div style="font-size: 2.5rem; color: var(--primary-color); margin-bottom: 1rem;">
<i class="fas fa-shield-alt"></i>
</div>
<h2 style="margin-bottom: 0.5rem;">Admin Access</h2>
<p style="color: var(--muted-dark); font-size: 0.85rem; margin-bottom: 1.5rem;">
Enter your master API password to configure providers, API keys, and custom model fallback revolvers.
</p>
<form id="auth-form" class="form-group" style="text-align: left;">
<label class="form-label" for="admin-key-input">Master API Password</label>
<input type="password" id="admin-key-input" class="form-input" placeholder="Enter API_PASSWORD..." required autofocus>
<button type="submit" class="nav-btn primary" style="margin-top: 1rem; justify-content: center; padding: 0.75rem;">
<i class="fas fa-key"></i>
<span>Authenticate</span>
</button>
</form>
</div>
<!-- Authenticated Dashboard -->
<div id="dashboard-section" style="display: none;">
<nav class="tabs-nav" aria-label="Admin Subpages">
<a href="/admin/models" class="tab-btn ${activePage === 'models' ? 'active' : ''}">
<i class="fas fa-layer-group"></i>
<span>Custom Models & Revolver</span>
</a>
<a href="/admin/providers" class="tab-btn ${activePage === 'providers' ? 'active' : ''}">
<i class="fas fa-server"></i>
<span>API Providers</span>
</a>
<a href="/admin/playground" class="tab-btn ${activePage === 'playground' ? 'active' : ''}">
<i class="fas fa-play-circle"></i>
<span>Revolver Playground</span>
</a>
<a href="/admin/telemetry" class="tab-btn ${activePage === 'telemetry' ? 'active' : ''}">
<i class="fas fa-heartbeat"></i>
<span>Live Key Telemetry</span>
</a>
<a href="/admin/live_logs" class="tab-btn ${activePage === 'live_logs' ? 'active' : ''}">
<i class="fas fa-satellite-dish"></i>
<span>Live Logs</span>
<span id="nav-live-badge" class="badge" style="margin-left: 0.35rem; font-size: 0.65rem; padding: 2px 6px; background: rgba(255,255,255,0.1);">OFF</span>
</a>
</nav>
<div class="page-content">
${bodyHtml}
</div>
</div>
</main>
${modalsHtml}
<!-- Toast Notification Container -->
<div id="toast-container"></div>
<script>
// Shared Admin State
let activeKey = localStorage.getItem('revolver_admin_key') || sessionStorage.getItem('revolver_admin_key') || '';
if (activeKey) {
localStorage.setItem('revolver_admin_key', activeKey);
sessionStorage.setItem('revolver_admin_key', activeKey);
}
function setStoredAdminKey(key) {
activeKey = key || '';
if (activeKey) {
localStorage.setItem('revolver_admin_key', activeKey);
sessionStorage.setItem('revolver_admin_key', activeKey);
} else {
localStorage.removeItem('revolver_admin_key');
sessionStorage.removeItem('revolver_admin_key');
}
}
const defaultUrls = {
gemini: 'https://generativelanguage.googleapis.com',
groq: 'https://api.groq.com/openai/v1',
openai: 'https://api.openai.com/v1',
custom: 'https://api.openai.com/v1'
};
const authGateSection = document.getElementById('auth-gate-section');
const dashboardSection = document.getElementById('dashboard-section');
const authForm = document.getElementById('auth-form');
const adminKeyInput = document.getElementById('admin-key-input');
const logoutBtn = document.getElementById('logout-btn');
const themeToggle = document.getElementById('theme-toggle');
function showToast(message, type = 'info') {
const container = document.getElementById('toast-container');
const toast = document.createElement('div');
toast.className = 'toast ' + type;
const icon = type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : type === 'warning' ? 'exclamation-triangle' : 'info-circle';
toast.innerHTML = '<i class="fas fa-' + icon + '"></i><span>' + message + '</span>';
container.appendChild(toast);
setTimeout(() => {
toast.style.opacity = '0';
toast.style.transform = 'translateY(10px)';
setTimeout(() => toast.remove(), 300);
}, 4000);
}
function escapeHtml(str) {
if (str === null || str === undefined) return '';
return String(str)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
// Theme Management
function initTheme() {
const savedTheme = localStorage.getItem('theme');
if (savedTheme === 'light') {
document.body.classList.add('light-theme');
themeToggle.innerHTML = '<i class="fas fa-sun"></i>';
}
}
themeToggle.addEventListener('click', () => {
document.body.classList.toggle('light-theme');
const isLight = document.body.classList.contains('light-theme');
localStorage.setItem('theme', isLight ? 'light' : 'dark');
themeToggle.innerHTML = isLight ? '<i class="fas fa-sun"></i>' : '<i class="fas fa-moon"></i>';
});
// API Client with Auth
async function apiRequest(endpoint, options = {}) {
const headers = options.headers || {};
headers['Authorization'] = 'Bearer ' + activeKey;
if (options.body && typeof options.body === 'object') {
headers['Content-Type'] = 'application/json';
options.body = JSON.stringify(options.body);
}
options.headers = headers;
const res = await fetch(endpoint, options);
if (res.status === 401) {
setStoredAdminKey('');
renderAuthView();
throw new Error('Unauthorized: Invalid or expired API password.');
}
return res;
}
// Modals handler
function openModal(modalId) {
const el = document.getElementById(modalId);
if (el) el.classList.add('active');
}
function closeModal(modalId) {
const el = document.getElementById(modalId);
if (el) el.classList.remove('active');
}
document.querySelectorAll('.close-modal').forEach(btn => {
btn.addEventListener('click', () => {
closeModal(btn.getAttribute('data-modal'));
});
});
async function syncNavWatcherBadge() {
try {
const res = await apiRequest('/api/admin/live-logs/state');
if (!res.ok) return;
const data = await res.json();
const navBadge = document.getElementById('nav-live-badge');
if (navBadge) {
navBadge.textContent = data.active ? 'LIVE' : 'OFF';
navBadge.style.background = data.active ? 'var(--accent-success)' : 'rgba(255,255,255,0.1)';
navBadge.style.color = data.active ? '#000' : 'inherit';
}
} catch (err) {
// Ignore badge sync errors
}
}
// Auth Form Submit
authForm.addEventListener('submit', async (e) => {
e.preventDefault();
const enteredKey = adminKeyInput.value.trim();
if (!enteredKey) return;
try {
const res = await fetch('/api/admin/verify', {
headers: { 'Authorization': 'Bearer ' + enteredKey }
});
if (res.ok) {
setStoredAdminKey(enteredKey);
showToast('Authenticated successfully!', 'success');
renderDashboardView();
} else {
showToast('Invalid API password. Access denied.', 'error');
}
} catch (err) {
showToast('Connection error: ' + err.message, 'error');
}
});
logoutBtn.addEventListener('click', () => {
setStoredAdminKey('');
showToast('Logged out of admin session.', 'info');
renderAuthView();
});
function renderAuthView() {
authGateSection.style.display = 'block';
dashboardSection.style.display = 'none';
logoutBtn.style.display = 'none';
adminKeyInput.value = '';
}
function renderDashboardView() {
authGateSection.style.display = 'none';
dashboardSection.style.display = 'block';
logoutBtn.style.display = 'flex';
syncNavWatcherBadge();
if (typeof initPage === 'function') {
initPage();
}
}
${pageScript}
// Initialize Theme & Session
initTheme();
if (activeKey) {
renderDashboardView();
} else {
renderAuthView();
}
</script>
</body>
</html>`;
}

882
src/admin/liveLogsPage.ts Normal file
View file

@ -0,0 +1,882 @@
import { renderAdminLayout } from './layout';
export function renderLiveLogsPage(): string {
const extraStyles = `
.log-row-item {
padding: 0.65rem 0.75rem;
border-radius: 8px;
border: 1px solid var(--border-dark);
background: rgba(0, 0, 0, 0.15);
cursor: pointer;
transition: all 0.15s ease;
display: flex;
flex-direction: column;
gap: 0.3rem;
}
body.light-theme .log-row-item {
background: rgba(0, 0, 0, 0.02);
border-color: var(--border-light);
}
.log-row-item:hover {
background: rgba(187, 134, 252, 0.08);
border-color: rgba(187, 134, 252, 0.4);
}
.log-row-item.active {
border-color: var(--primary-color);
background: rgba(187, 134, 252, 0.15);
box-shadow: 0 0 10px rgba(187, 134, 252, 0.2);
}
.code-box {
background: #0d0d0d;
color: #f1f1f1;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 8px;
padding: 0.75rem;
font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, monospace;
font-size: 0.8rem;
overflow-x: auto;
white-space: pre-wrap;
word-break: break-word;
line-height: 1.45;
}
body.light-theme .code-box {
background: #f8f9fa;
color: #212529;
border-color: #dee2e6;
}
.chat-bubble {
border-radius: 8px;
padding: 0.65rem 0.85rem;
margin-bottom: 0.6rem;
font-size: 0.82rem;
line-height: 1.45;
}
.chat-bubble.user {
background: rgba(100, 181, 246, 0.12);
border-left: 3px solid var(--accent-info);
}
.chat-bubble.assistant {
background: rgba(3, 218, 198, 0.12);
border-left: 3px solid var(--accent-success);
}
.chat-bubble.system {
background: rgba(255, 183, 77, 0.12);
border-left: 3px solid var(--accent-warning);
}
/* Dedicated Inspector Sub-tabs (isolated from page navigation) */
.insp-tabs-bar {
display: flex;
gap: 0.5rem;
border-bottom: 1px solid var(--border-dark);
margin-bottom: 0.75rem;
overflow-x: auto;
}
body.light-theme .insp-tabs-bar {
border-bottom-color: var(--border-light);
}
.insp-tab-btn {
background: transparent;
border: none;
border-bottom: 2px solid transparent;
color: var(--muted-dark);
padding: 0.6rem 1.1rem;
font-size: 0.88rem;
font-weight: 600;
cursor: pointer;
display: flex;
align-items: center;
gap: 0.45rem;
transition: all 0.2s ease;
white-space: nowrap;
}
body.light-theme .insp-tab-btn {
color: var(--muted-light);
}
.insp-tab-btn:hover {
color: var(--text-dark);
}
body.light-theme .insp-tab-btn:hover {
color: var(--text-light);
}
.insp-tab-btn.active {
color: var(--primary-color);
border-bottom-color: var(--primary-color);
}
`;
const bodyHtml = `
<section id="live-logs-page">
<div class="section-header">
<div>
<h2 class="section-title">
<i class="fas fa-satellite-dish"></i>
<span>Live Request Log Watcher</span>
</h2>
<p class="card-subtitle">
Inspect live incoming + served requests in RAM (input, output, metadata, debug data). Flushes from memory when toggled off.
</p>
</div>
<div style="display: flex; gap: 0.75rem; align-items: center; flex-wrap: wrap;">
<div style="display: flex; align-items: center; gap: 0.5rem; background: rgba(0,0,0,0.25); border: 1px solid var(--border-dark); padding: 0.35rem 0.75rem; border-radius: 8px;">
<span style="font-size: 0.85rem; font-weight: 500;">Watcher:</span>
<button id="watcher-toggle-btn" class="nav-btn" style="padding: 0.35rem 0.85rem; font-size: 0.8rem;">
<i class="fas fa-play"></i> <span>Start Watching</span>
</button>
</div>
<div id="ram-badge" class="badge badge-info" style="font-size: 0.8rem; padding: 0.4rem 0.75rem;">
<i class="fas fa-memory"></i> <span id="ram-count-text">0 / 250 in RAM (0 KB)</span>
</div>
<button id="flush-watcher-btn" class="nav-btn" title="Flush all buffered requests from RAM">
<i class="fas fa-trash-alt"></i> <span>Flush Memory</span>
</button>
</div>
</div>
<!-- Filter bar -->
<div class="card" style="margin-bottom: 1rem; padding: 0.75rem 1rem;">
<div style="display: flex; gap: 1rem; align-items: center; flex-wrap: wrap;">
<div style="flex: 1; min-width: 220px; position: relative;">
<input type="text" id="live-search-input" class="form-input" placeholder="Search prompts, responses, request IDs..." style="padding-left: 2.2rem; margin: 0; width: 100%;">
<i class="fas fa-search" style="position: absolute; left: 0.85rem; top: 50%; transform: translateY(-50%); color: var(--muted-dark); font-size: 0.85rem;"></i>
</div>
<div style="display: flex; gap: 0.5rem; align-items: center;">
<label style="font-size: 0.8rem; color: var(--muted-dark);">Status:</label>
<select id="live-status-filter" class="form-select" style="width: auto; padding: 0.4rem 0.75rem; margin: 0;">
<option value="all">All Statuses</option>
<option value="completed">Success (Direct)</option>
<option value="fallback_completed">Success (Fallback)</option>
<option value="streaming">Streaming</option>
<option value="failed">Failed</option>
<option value="cancelled">Cancelled</option>
</select>
</div>
<div style="display: flex; gap: 0.5rem; align-items: center;">
<label style="font-size: 0.8rem; color: var(--muted-dark);">Model:</label>
<select id="live-model-filter" class="form-select" style="width: auto; padding: 0.4rem 0.75rem; margin: 0;">
<option value="all">All Models</option>
</select>
</div>
<button id="live-auto-scroll-btn" class="nav-btn" style="font-size: 0.75rem; padding: 0.4rem 0.75rem;" title="Auto-scroll to latest requests">
<i class="fas fa-arrow-down"></i> <span>Auto-Scroll: ON</span>
</button>
</div>
</div>
<!-- Split layout: Request List (left) + Detail Inspector (right) -->
<div style="display: grid; grid-template-columns: 380px 1fr; gap: 1rem; min-height: 600px;">
<!-- Request Stream List -->
<div class="card" style="padding: 0.75rem; display: flex; flex-direction: column;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem; padding-bottom: 0.5rem; border-bottom: 1px solid var(--border-dark);">
<span style="font-size: 0.85rem; font-weight: 600;">Captured Requests (<span id="live-displayed-count">0</span>)</span>
<span id="live-connection-status" class="badge badge-warning" style="font-size: 0.7rem;"><i class="fas fa-circle-notch fa-spin"></i> Disconnected</span>
</div>
<div id="live-requests-list" style="overflow-y: auto; max-height: 650px; display: flex; flex-direction: column; gap: 0.5rem;">
<p id="live-empty-hint" style="color: var(--muted-dark); font-size: 0.85rem; text-align: center; padding: 2rem 1rem;">
Live Watcher is currently idle. Toggle Watcher ON to begin capturing requests in RAM.
</p>
</div>
</div>
<!-- Detail Inspector -->
<div class="card" style="padding: 1rem; display: flex; flex-direction: column;">
<div id="inspector-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.75rem; padding-bottom: 0.5rem; border-bottom: 1px solid var(--border-dark);">
<div>
<h3 style="font-size: 1rem; font-weight: 600; display: flex; align-items: center; gap: 0.5rem;">
<span id="inspector-title">Request Inspector</span>
<span id="inspector-status-badge"></span>
</h3>
<span id="inspector-subtitle" style="font-size: 0.8rem; color: var(--muted-dark);">Select a request from the list to inspect full RAM data</span>
</div>
<div id="inspector-actions" style="display: none; gap: 0.5rem;">
<button id="copy-log-json-btn" class="nav-btn" style="font-size: 0.75rem; padding: 0.35rem 0.65rem;" title="Copy entire inspection payload as JSON">
<i class="fas fa-copy"></i> <span>Copy JSON</span>
</button>
<button id="export-log-json-btn" class="nav-btn" style="font-size: 0.75rem; padding: 0.35rem 0.65rem;" title="Download JSON file">
<i class="fas fa-download"></i> <span>Export</span>
</button>
</div>
</div>
<!-- Inspector Sub-tabs (isolated class .insp-tab-btn, no .tab-btn overlap) -->
<div id="inspector-tabs" class="insp-tabs-bar" style="display: none;">
<button type="button" class="insp-tab-btn active" data-insp-tab="insp-input">
<i class="fas fa-sign-in-alt"></i> <span>Input</span>
</button>
<button type="button" class="insp-tab-btn" data-insp-tab="insp-output">
<i class="fas fa-sign-out-alt"></i> <span>Output</span>
</button>
<button type="button" class="insp-tab-btn" data-insp-tab="insp-metadata">
<i class="fas fa-info-circle"></i> <span>Metadata</span>
</button>
<button type="button" class="insp-tab-btn" data-insp-tab="insp-debug">
<i class="fas fa-bug"></i> <span>Debug &amp; Failover Trace</span>
</button>
</div>
<!-- Inspector Content Pane -->
<div id="inspector-content" style="flex: 1; overflow-y: auto; max-height: 560px;">
<div id="inspector-empty-state" style="text-align: center; padding: 4rem 1rem; color: var(--muted-dark);">
<i class="fas fa-microscope" style="font-size: 2.5rem; margin-bottom: 1rem; opacity: 0.5;"></i>
<p>No request selected.</p>
<p style="font-size: 0.8rem; margin-top: 0.5rem;">Toggle Watcher ON and select an incoming request from the stream to inspect.</p>
</div>
<div id="insp-input" class="insp-pane" style="display: none;"></div>
<div id="insp-output" class="insp-pane" style="display: none;"></div>
<div id="insp-metadata" class="insp-pane" style="display: none;"></div>
<div id="insp-debug" class="insp-pane" style="display: none;"></div>
</div>
</div>
</div>
</section>
`;
const pageScript = `
let currentConfig = { providers: [], customModels: [] };
let isWatcherActive = false;
let liveLogs = [];
let selectedLog = null;
let activeInspectorTab = 'insp-input';
let autoScroll = true;
let liveLogsEventSource = null;
let liveSearchQuery = '';
let liveStatusFilter = 'all';
let liveModelFilter = 'all';
async function initPage() {
try {
const cfgRes = await apiRequest('/api/admin/config');
if (cfgRes.ok) {
currentConfig = await cfgRes.json();
}
} catch (err) {}
await updateWatcherStatus();
connectLiveLogsSSE();
updateModelFilterOptions();
}
async function updateWatcherStatus() {
try {
const res = await apiRequest('/api/admin/live-logs/state');
if (!res.ok) return;
const data = await res.json();
isWatcherActive = !!data.active;
const navBadge = document.getElementById('nav-live-badge');
if (navBadge) {
navBadge.textContent = isWatcherActive ? 'LIVE' : 'OFF';
navBadge.style.background = isWatcherActive ? 'var(--accent-success)' : 'rgba(255,255,255,0.1)';
navBadge.style.color = isWatcherActive ? '#000' : 'inherit';
}
const ramText = document.getElementById('ram-count-text');
if (ramText) {
ramText.textContent = data.bufferCount + ' / ' + data.maxCapacity + ' in RAM (' + data.memoryEstimateKb + ' KB)';
}
const toggleBtn = document.getElementById('watcher-toggle-btn');
if (toggleBtn) {
if (isWatcherActive) {
toggleBtn.className = 'nav-btn danger';
toggleBtn.innerHTML = '<i class="fas fa-stop"></i> <span>Stop Watching</span>';
} else {
toggleBtn.className = 'nav-btn primary';
toggleBtn.innerHTML = '<i class="fas fa-play"></i> <span>Start Watching</span>';
}
}
if (isWatcherActive && liveLogs.length === 0) {
const entriesRes = await apiRequest('/api/admin/live-logs/entries?limit=100');
if (entriesRes.ok) {
const entData = await entriesRes.json();
liveLogs = entData.entries || [];
if (selectedLog) {
const refreshed = liveLogs.find(l => l.id === selectedLog.id);
if (refreshed) selectedLog = refreshed;
}
renderLiveLogsList();
renderInspector();
updateModelFilterOptions();
}
}
} catch (err) {
console.error('Failed to update watcher status:', err);
}
}
async function toggleWatcher() {
const targetState = !isWatcherActive;
try {
const res = await apiRequest('/api/admin/live-logs/toggle', {
method: 'POST',
body: { enabled: targetState }
});
if (!res.ok) throw new Error('Failed to toggle watcher');
const data = await res.json();
isWatcherActive = !!data.active;
if (!isWatcherActive) {
liveLogs = [];
selectedLog = null;
renderLiveLogsList();
renderInspector();
showToast('Live Watcher stopped. All request logs flushed from RAM.', 'info');
} else {
showToast('Live Watcher started! Now capturing requests in RAM.', 'success');
}
await updateWatcherStatus();
} catch (err) {
showToast('Error toggling watcher: ' + err.message, 'error');
}
}
async function flushWatcher() {
try {
const res = await apiRequest('/api/admin/live-logs/flush', { method: 'POST' });
if (!res.ok) throw new Error('Failed to flush watcher logs');
liveLogs = [];
selectedLog = null;
renderLiveLogsList();
renderInspector();
await updateWatcherStatus();
showToast('RAM request logs purged successfully.', 'info');
} catch (err) {
showToast('Error flushing watcher: ' + err.message, 'error');
}
}
function connectLiveLogsSSE() {
if (liveLogsEventSource) return;
try {
liveLogsEventSource = new EventSource('/api/admin/live-logs/stream?api_key=' + encodeURIComponent(activeKey));
liveLogsEventSource.onopen = function() {
const statusElem = document.getElementById('live-connection-status');
if (statusElem) {
statusElem.className = 'badge badge-success';
statusElem.innerHTML = '<i class="fas fa-circle"></i> Connected';
}
};
liveLogsEventSource.onmessage = function(e) {
try {
const msg = JSON.parse(e.data);
handleLiveLogSSEMessage(msg);
} catch (err) {
console.error('Failed to parse live log SSE:', err);
}
};
liveLogsEventSource.onerror = function() {
const statusElem = document.getElementById('live-connection-status');
if (statusElem) {
statusElem.className = 'badge badge-warning';
statusElem.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Reconnecting...';
}
};
} catch (err) {
console.error('Live logs SSE error:', err);
}
}
function handleLiveLogSSEMessage(msg) {
if (msg.type === 'snapshot') {
if (msg.state) {
isWatcherActive = msg.state.active;
}
if (Array.isArray(msg.entries)) {
liveLogs = msg.entries;
if (selectedLog) {
const refreshed = liveLogs.find(l => l.id === selectedLog.id);
if (refreshed) {
selectedLog = refreshed;
renderInspector();
}
}
renderLiveLogsList();
updateModelFilterOptions();
}
updateWatcherStatus();
} else if (msg.type === 'watcher_status') {
isWatcherActive = msg.data.active;
updateWatcherStatus();
} else if (msg.type === 'watcher_flushed') {
liveLogs = [];
selectedLog = null;
renderLiveLogsList();
renderInspector();
updateWatcherStatus();
} else if (msg.type === 'request_started') {
liveLogs.unshift(msg.data);
if (liveLogs.length > 250) liveLogs.length = 250;
renderLiveLogsList();
updateModelFilterOptions();
updateWatcherStatus();
} else if (msg.type === 'stream_chunk') {
const item = liveLogs.find(l => l.id === msg.requestId);
if (item) {
item.output.completionText = (item.output.completionText || '') + msg.chunkText;
item.durationMs = msg.durationMs || item.durationMs;
if (selectedLog && selectedLog.id === msg.requestId) {
selectedLog = item;
const outText = document.getElementById('insp-output-text');
if (outText) {
outText.textContent = item.output.completionText;
} else {
renderInspectorOutputPane(selectedLog);
}
}
}
} else if (msg.type === 'candidate_step') {
const item = liveLogs.find(l => l.id === msg.requestId);
if (item) {
item.debug.stepTraces.push(msg.data);
item.metadata.totalCandidatesAttempted = item.debug.stepTraces.length;
if (item.debug.stepTraces.length > 1) item.metadata.fallbackOccurred = true;
if (selectedLog && selectedLog.id === msg.requestId) {
selectedLog = item;
renderInspectorMetadataPane(item);
renderInspectorDebugPane(item);
}
}
} else if (msg.type === 'request_completed' || msg.type === 'request_failed' || msg.type === 'request_cancelled') {
const updated = msg.data;
const idx = liveLogs.findIndex(l => l.id === updated.id);
if (idx !== -1) {
liveLogs[idx] = updated;
} else {
liveLogs.unshift(updated);
}
renderLiveLogsList();
if (selectedLog && selectedLog.id === updated.id) {
selectedLog = updated;
renderInspector();
}
updateWatcherStatus();
}
}
function updateModelFilterOptions() {
const select = document.getElementById('live-model-filter');
if (!select) return;
const currentVal = select.value;
const models = new Set();
liveLogs.forEach(l => {
if (l.input && (l.input.requestedModel || l.input.model)) {
models.add(l.input.requestedModel || l.input.model);
}
});
if (currentConfig && Array.isArray(currentConfig.customModels)) {
currentConfig.customModels.forEach(m => models.add(m.name));
}
let opts = '<option value="all">All Models</option>';
models.forEach(m => {
opts += '<option value="' + escapeHtml(m) + '">' + escapeHtml(m) + '</option>';
});
select.innerHTML = opts;
select.value = currentVal || 'all';
}
function renderLiveLogsList() {
const container = document.getElementById('live-requests-list');
const countElem = document.getElementById('live-displayed-count');
if (!container) return;
const prevScrollTop = container.scrollTop;
let filtered = [...liveLogs];
if (liveStatusFilter !== 'all') {
filtered = filtered.filter(l => l.status === liveStatusFilter);
}
if (liveModelFilter !== 'all') {
filtered = filtered.filter(l => {
const reqM = (l.input && (l.input.requestedModel || l.input.model)) || '';
return reqM.toLowerCase() === liveModelFilter.toLowerCase();
});
}
if (liveSearchQuery.trim() !== '') {
const q = liveSearchQuery.toLowerCase().trim();
filtered = filtered.filter(l => {
if (l.id.toLowerCase().includes(q)) return true;
const reqM = (l.input && (l.input.requestedModel || l.input.model)) || '';
if (reqM.toLowerCase().includes(q)) return true;
if ((l.output && l.output.completionText || '').toLowerCase().includes(q)) return true;
if (Array.isArray(l.input?.messages)) {
for (const m of l.input.messages) {
const str = typeof m.content === 'string' ? m.content : JSON.stringify(m.content || '');
if (str.toLowerCase().includes(q)) return true;
}
}
return false;
});
}
if (countElem) countElem.textContent = filtered.length;
container.innerHTML = '';
if (filtered.length === 0) {
container.innerHTML = '<p style="color: var(--muted-dark); font-size: 0.82rem; text-align: center; padding: 2rem 1rem;">' +
(liveLogs.length === 0
? 'No requests captured yet. Toggle Watcher ON and send API requests.'
: 'No requests match the current search/filter criteria.') +
'</p>';
return;
}
filtered.forEach(item => {
const row = document.createElement('div');
row.className = 'log-row-item' + (selectedLog && selectedLog.id === item.id ? ' active' : '');
let statusBadge = '';
if (item.status === 'streaming') {
statusBadge = '<span class="badge badge-info"><i class="fas fa-spinner fa-spin"></i> Stream</span>';
} else if (item.status === 'completed') {
statusBadge = '<span class="badge badge-success"><i class="fas fa-check"></i> ' + (item.statusCode || 200) + '</span>';
} else if (item.status === 'fallback_completed') {
statusBadge = '<span class="badge badge-primary"><i class="fas fa-random"></i> Fallback</span>';
} else if (item.status === 'failed') {
statusBadge = '<span class="badge badge-danger"><i class="fas fa-times"></i> ' + (item.statusCode || 500) + '</span>';
} else {
statusBadge = '<span class="badge badge-warning"><i class="fas fa-ban"></i> Cancel</span>';
}
const modelName = item.input.requestedModel || item.input.model || 'unknown-model';
const tokCount = item.output?.tokens?.totalTokens ? item.output.tokens.totalTokens + ' tok' : '';
row.innerHTML = '<div style="display: flex; justify-content: space-between; align-items: center;">' +
'<span><strong><code>' + escapeHtml(item.id.slice(0, 16)) + '...</code></strong></span>' +
statusBadge +
'</div>' +
'<div style="display: flex; justify-content: space-between; align-items: center; font-size: 0.78rem; color: var(--muted-dark);">' +
'<span>' + escapeHtml(modelName) + '</span>' +
'<span>' + item.durationMs + ' ms</span>' +
'</div>' +
'<div style="display: flex; justify-content: space-between; align-items: center; font-size: 0.72rem; color: var(--muted-dark);">' +
'<span>' + new Date(item.timestamp).toLocaleTimeString() + '</span>' +
'<span>' + tokCount + '</span>' +
'</div>';
row.addEventListener('click', () => {
selectedLog = item;
document.querySelectorAll('.log-row-item').forEach(r => r.classList.remove('active'));
row.classList.add('active');
renderInspector();
});
container.appendChild(row);
});
if (autoScroll && !selectedLog) {
container.scrollTop = 0;
} else {
container.scrollTop = prevScrollTop;
}
}
function renderInspector() {
const emptyState = document.getElementById('inspector-empty-state');
const tabs = document.getElementById('inspector-tabs');
const actions = document.getElementById('inspector-actions');
const title = document.getElementById('inspector-title');
const subtitle = document.getElementById('inspector-subtitle');
const badge = document.getElementById('inspector-status-badge');
if (!selectedLog) {
if (emptyState) emptyState.style.display = 'block';
if (tabs) tabs.style.display = 'none';
if (actions) actions.style.display = 'none';
if (title) title.textContent = 'Request Inspector';
if (subtitle) subtitle.textContent = 'Select a request from the list to inspect full RAM data';
if (badge) badge.innerHTML = '';
document.querySelectorAll('.insp-pane').forEach(p => p.style.display = 'none');
return;
}
if (emptyState) emptyState.style.display = 'none';
if (tabs) tabs.style.display = 'flex';
if (actions) actions.style.display = 'flex';
if (title) title.textContent = selectedLog.method + ' ' + selectedLog.path;
if (subtitle) subtitle.textContent = selectedLog.id + ' • ' + new Date(selectedLog.timestamp).toLocaleString() + ' • ' + selectedLog.durationMs + ' ms';
let statusBadge = '';
if (selectedLog.status === 'streaming') {
statusBadge = '<span class="badge badge-info"><i class="fas fa-spinner fa-spin"></i> Streaming</span>';
} else if (selectedLog.status === 'completed') {
statusBadge = '<span class="badge badge-success"><i class="fas fa-check"></i> 200 OK</span>';
} else if (selectedLog.status === 'fallback_completed') {
statusBadge = '<span class="badge badge-primary"><i class="fas fa-random"></i> Fallback Served</span>';
} else if (selectedLog.status === 'failed') {
statusBadge = '<span class="badge badge-danger"><i class="fas fa-times"></i> Error ' + (selectedLog.statusCode || 500) + '</span>';
} else {
statusBadge = '<span class="badge badge-warning"><i class="fas fa-ban"></i> Cancelled</span>';
}
if (badge) badge.innerHTML = statusBadge;
renderInspectorInputPane(selectedLog);
renderInspectorOutputPane(selectedLog);
renderInspectorMetadataPane(selectedLog);
renderInspectorDebugPane(selectedLog);
// Activate currently selected inspector sub-tab
document.querySelectorAll('.insp-tab-btn').forEach(b => {
b.classList.toggle('active', b.getAttribute('data-insp-tab') === activeInspectorTab);
});
document.querySelectorAll('.insp-pane').forEach(p => p.style.display = 'none');
const activePane = document.getElementById(activeInspectorTab);
if (activePane) activePane.style.display = 'block';
}
function renderInspectorInputPane(item) {
const pane = document.getElementById('insp-input');
if (!pane) return;
let messagesHtml = '';
if (Array.isArray(item.input.messages) && item.input.messages.length > 0) {
item.input.messages.forEach((msg, idx) => {
const role = (msg.role || 'user').toLowerCase();
const bubbleClass = 'chat-bubble ' + (role === 'assistant' ? 'assistant' : (role === 'system' ? 'system' : 'user'));
const roleBadgeClass = role === 'assistant' ? 'badge-success' : (role === 'system' ? 'badge-warning' : 'badge-info');
const content = typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content, null, 2);
messagesHtml += '<div class="' + bubbleClass + '">' +
'<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.35rem;">' +
'<span class="badge ' + roleBadgeClass + '" style="font-size: 0.68rem;">' + escapeHtml(role.toUpperCase()) + '</span>' +
'<span style="font-size: 0.7rem; color: var(--muted-dark);">#' + (idx + 1) + '</span>' +
'</div>' +
'<div style="white-space: pre-wrap; word-break: break-word;">' + escapeHtml(content) + '</div>' +
'</div>';
});
} else {
messagesHtml = '<p style="color: var(--muted-dark);">No messages array present in request payload.</p>';
}
pane.innerHTML = '<div style="margin-bottom: 1rem; background: rgba(0,0,0,0.15); border: 1px solid var(--border-dark); border-radius: 8px; padding: 0.75rem;">' +
'<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 0.75rem; font-size: 0.8rem;">' +
'<div><span style="color: var(--muted-dark);">Model:</span> <strong>' + escapeHtml(item.input.requestedModel || item.input.model || 'N/A') + '</strong></div>' +
'<div><span style="color: var(--muted-dark);">Stream:</span> <strong>' + (item.isStreaming ? 'Yes (SSE)' : 'No (JSON)') + '</strong></div>' +
'<div><span style="color: var(--muted-dark);">Temperature:</span> <strong>' + (item.input.temperature ?? 'default') + '</strong></div>' +
'<div><span style="color: var(--muted-dark);">Max Tokens:</span> <strong>' + (item.input.maxTokens ?? 'unlimited') + '</strong></div>' +
'<div><span style="color: var(--muted-dark);">Client IP:</span> <strong>' + escapeHtml(item.clientIp || '127.0.0.1') + '</strong></div>' +
'</div>' +
'</div>' +
'<h4 style="font-size: 0.85rem; font-weight: 600; margin-bottom: 0.5rem;"><i class="fas fa-comments"></i> Prompt Messages (' + (item.input.messages ? item.input.messages.length : 0) + ')</h4>' +
'<div>' + messagesHtml + '</div>';
}
function renderInspectorOutputPane(item) {
const pane = document.getElementById('insp-output');
if (!pane) return;
let contentHtml = '';
if (item.status === 'failed' || item.output.error) {
const errObj = item.output.error || {};
contentHtml = '<div style="background: rgba(207,102,121,0.12); border: 1px solid rgba(207,102,121,0.4); border-radius: 8px; padding: 1rem; color: var(--accent-danger); margin-bottom: 1rem;">' +
'<div style="font-weight: 600; margin-bottom: 0.4rem;"><i class="fas fa-exclamation-triangle"></i> Error Response (' + (item.statusCode || 500) + ')</div>' +
'<div style="font-size: 0.85rem; white-space: pre-wrap; font-family: monospace;">' + escapeHtml(errObj.message || JSON.stringify(errObj, null, 2)) + '</div>' +
'</div>';
} else if (item.output.completionText) {
contentHtml = '<div class="chat-bubble assistant">' +
'<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.35rem;">' +
'<span class="badge badge-success"><i class="fas fa-robot"></i> Assistant Response</span>' +
'<span style="font-size: 0.72rem; color: var(--muted-dark);">' + (item.output.finishReason ? 'finish: ' + item.output.finishReason : '') + '</span>' +
'</div>' +
'<div id="insp-output-text" style="white-space: pre-wrap; word-break: break-word; font-family: inherit;">' + escapeHtml(item.output.completionText) + '</div>' +
'</div>';
} else {
contentHtml = '<p style="color: var(--muted-dark); padding: 1.5rem 0;">' +
(item.status === 'streaming' ? 'Streaming response bytes in real time...' : 'No output text returned.') +
'</p>';
}
const tok = item.output?.tokens;
const tokBar = tok ? '<div style="background: rgba(0,0,0,0.15); border: 1px solid var(--border-dark); border-radius: 8px; padding: 0.6rem 0.75rem; margin-bottom: 0.75rem; display: flex; gap: 1.5rem; font-size: 0.8rem;">' +
'<div><span style="color: var(--muted-dark);">Prompt Tokens:</span> <strong>' + tok.promptTokens + '</strong></div>' +
'<div><span style="color: var(--muted-dark);">Completion Tokens:</span> <strong>' + tok.completionTokens + '</strong></div>' +
'<div><span style="color: var(--muted-dark);">Total Tokens:</span> <strong>' + tok.totalTokens + '</strong></div>' +
'</div>' : '';
pane.innerHTML = tokBar + contentHtml;
}
function renderInspectorMetadataPane(item) {
const pane = document.getElementById('insp-metadata');
if (!pane) return;
const served = item.metadata.servedBy;
const servedStr = served
? 'Tier ' + served.tierIndex + ' (' + escapeHtml(served.tierName) + ') • ' + escapeHtml(served.providerName) + ' (' + escapeHtml(served.providerType) + ') • ' + escapeHtml(served.model) + ' [Key: ' + escapeHtml(served.maskedKey) + ']'
: 'N/A';
pane.innerHTML = '<table class="detail-table">' +
'<tbody>' +
'<tr><td>Request ID</td><td><code>' + escapeHtml(item.id) + '</code></td></tr>' +
'<tr><td>Timestamp</td><td>' + new Date(item.timestamp).toISOString() + ' (' + new Date(item.timestamp).toLocaleString() + ')</td></tr>' +
'<tr><td>Total Latency</td><td><strong>' + item.durationMs + ' ms</strong></td></tr>' +
'<tr><td>Status Code</td><td>' + (item.statusCode || 200) + ' (' + escapeHtml(item.status) + ')</td></tr>' +
'<tr><td>Method / Path</td><td><code>' + item.method + ' ' + item.path + '</code></td></tr>' +
'<tr><td>Streaming Mode</td><td>' + (item.isStreaming ? 'Yes (SSE transfer)' : 'No (standard JSON)') + '</td></tr>' +
'<tr><td>Client IP Address</td><td>' + escapeHtml(item.clientIp || '127.0.0.1') + '</td></tr>' +
'<tr><td>Client User-Agent</td><td><small style="color: var(--muted-dark); word-break: break-word;">' + escapeHtml(item.userAgent || 'None') + '</small></td></tr>' +
'<tr><td>Requested Model</td><td><strong>' + escapeHtml(item.input.requestedModel || item.input.model || 'None') + '</strong></td></tr>' +
'<tr><td>Resolved Custom Model</td><td>' + escapeHtml(item.metadata.resolvedCustomModelName || item.metadata.resolvedCustomModelId || 'Direct Fallback') + '</td></tr>' +
'<tr><td>Fallback Occurred</td><td>' + (item.metadata.fallbackOccurred ? '<span class="badge badge-warning">YES</span>' : '<span class="badge badge-success">NO (Direct)</span>') + '</td></tr>' +
'<tr><td>Total Hops Tried</td><td>' + item.metadata.totalCandidatesAttempted + '</td></tr>' +
'<tr><td>Final Serving Key</td><td>' + servedStr + '</td></tr>' +
'</tbody>' +
'</table>';
}
function renderInspectorDebugPane(item) {
const pane = document.getElementById('insp-debug');
if (!pane) return;
let stepsHtml = '';
if (Array.isArray(item.debug.stepTraces) && item.debug.stepTraces.length > 0) {
stepsHtml += '<h4 style="font-size: 0.85rem; font-weight: 600; margin-bottom: 0.5rem;"><i class="fas fa-route"></i> Candidate Attempts &amp; Failover Cascade</h4>' +
'<table class="detail-table" style="margin-bottom: 1rem;">' +
'<thead>' +
'<tr style="color: var(--muted-dark); text-align: left; font-size: 0.72rem;">' +
'<th>Hop</th><th>Tier / Provider</th><th>Model / Key</th><th>Duration</th><th>Result</th><th>Next Action</th>' +
'</tr>' +
'</thead>' +
'<tbody>';
item.debug.stepTraces.forEach(st => {
const statusCol = st.status === 'success' ? 'var(--accent-success)' : (st.status === 'rate_limited' ? 'var(--accent-warning)' : 'var(--accent-danger)');
stepsHtml += '<tr>' +
'<td>#' + st.stepIndex + '</td>' +
'<td>Tier ' + st.tierIndex + ' (' + escapeHtml(st.tierName) + ')<br><small style="color: var(--muted-dark);">' + escapeHtml(st.providerName) + '</small></td>' +
'<td>' + escapeHtml(st.model) + '<br><small style="color: var(--muted-dark);">' + escapeHtml(st.maskedKey) + '</small></td>' +
'<td>' + st.durationMs + ' ms</td>' +
'<td style="color: ' + statusCol + ';"><strong>' + (st.statusCode ? st.statusCode + ' ' : '') + escapeHtml(st.status) + '</strong>' + (st.errorMessage ? '<br><small style="font-size: 0.7rem;">' + escapeHtml(st.errorMessage) + '</small>' : '') + '</td>' +
'<td style="font-size: 0.72rem; color: var(--primary-color);">' + escapeHtml(st.nextAction || '') + '</td>' +
'</tr>';
});
stepsHtml += '</tbody></table>';
}
let eventsHtml = '';
if (Array.isArray(item.debug.events) && item.debug.events.length > 0) {
eventsHtml += '<h4 style="font-size: 0.85rem; font-weight: 600; margin-bottom: 0.5rem;"><i class="fas fa-list-ul"></i> Server Execution Events</h4>' +
'<div class="code-box" style="max-height: 200px;">';
item.debug.events.forEach(ev => {
const lvlColor = ev.level === 'error' ? 'var(--accent-danger)' : (ev.level === 'warn' ? 'var(--accent-warning)' : 'var(--accent-info)');
eventsHtml += '<div style="margin-bottom: 0.25rem;">' +
'<span style="color: var(--muted-dark); font-size: 0.72rem;">[' + new Date(ev.time).toLocaleTimeString() + ']</span> ' +
'<span style="color: ' + lvlColor + '; font-weight: 600; font-size: 0.72rem;">[' + ev.level.toUpperCase() + ']</span> ' +
'<span>' + escapeHtml(ev.message) + '</span>' +
'</div>';
});
eventsHtml += '</div>';
}
const keepaliveSummary = '<div style="background: rgba(0,0,0,0.15); border: 1px solid var(--border-dark); border-radius: 8px; padding: 0.6rem 0.75rem; margin-bottom: 0.75rem; display: flex; gap: 1.5rem; font-size: 0.8rem;">' +
'<div><span style="color: var(--muted-dark);">SSE Keep-Alive Pings:</span> <strong>' + (item.debug.keepAlivePingsCount || 0) + '</strong></div>' +
'<div><span style="color: var(--muted-dark);">Whitespace Keep-Alives:</span> <strong>' + (item.debug.nonStreamingWhitespaceCount || 0) + '</strong></div>' +
'</div>';
pane.innerHTML = keepaliveSummary + stepsHtml + eventsHtml;
}
// Inspector Sub-tab navigation (strictly scoped to .insp-tab-btn and .insp-pane)
document.querySelectorAll('.insp-tab-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
const targetId = btn.getAttribute('data-insp-tab');
if (!targetId) return;
activeInspectorTab = targetId;
document.querySelectorAll('.insp-tab-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.insp-pane').forEach(p => p.style.display = 'none');
btn.classList.add('active');
const targetPane = document.getElementById(targetId);
if (targetPane) targetPane.style.display = 'block';
});
});
// Copy / Export Handlers
const copyBtn = document.getElementById('copy-log-json-btn');
if (copyBtn) {
copyBtn.addEventListener('click', () => {
if (!selectedLog) return;
navigator.clipboard.writeText(JSON.stringify(selectedLog, null, 2))
.then(() => showToast('Full request inspection copied to clipboard!', 'success'))
.catch(() => showToast('Failed to copy to clipboard', 'error'));
});
}
const exportBtn = document.getElementById('export-log-json-btn');
if (exportBtn) {
exportBtn.addEventListener('click', () => {
if (!selectedLog) return;
const blob = new Blob([JSON.stringify(selectedLog, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'request-' + selectedLog.id + '.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
showToast('Exported request inspection as JSON.', 'success');
});
}
const toggleBtn = document.getElementById('watcher-toggle-btn');
if (toggleBtn) {
toggleBtn.addEventListener('click', toggleWatcher);
}
const flushBtn = document.getElementById('flush-watcher-btn');
if (flushBtn) {
flushBtn.addEventListener('click', flushWatcher);
}
const searchInput = document.getElementById('live-search-input');
if (searchInput) {
searchInput.addEventListener('input', (e) => {
liveSearchQuery = e.target.value;
renderLiveLogsList();
});
}
const statusFilterSelect = document.getElementById('live-status-filter');
if (statusFilterSelect) {
statusFilterSelect.addEventListener('change', (e) => {
liveStatusFilter = e.target.value;
renderLiveLogsList();
});
}
const modelFilterSelect = document.getElementById('live-model-filter');
if (modelFilterSelect) {
modelFilterSelect.addEventListener('change', (e) => {
liveModelFilter = e.target.value;
renderLiveLogsList();
});
}
const autoScrollBtn = document.getElementById('live-auto-scroll-btn');
if (autoScrollBtn) {
autoScrollBtn.addEventListener('click', () => {
autoScroll = !autoScroll;
autoScrollBtn.innerHTML = autoScroll
? '<i class="fas fa-arrow-down"></i> <span>Auto-Scroll: ON</span>'
: '<i class="fas fa-pause"></i> <span>Auto-Scroll: OFF</span>';
autoScrollBtn.className = autoScroll ? 'nav-btn' : 'nav-btn warning';
});
}
`;
return renderAdminLayout({
activePage: 'live_logs',
pageTitle: 'Live Logs',
bodyHtml,
pageScript,
extraStyles
});
}

471
src/admin/modelsPage.ts Normal file
View file

@ -0,0 +1,471 @@
import { renderAdminLayout } from './layout';
export function renderModelsPage(): string {
const extraStyles = `
.pipeline-view {
margin: 1rem 0;
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.pipeline-step {
background: rgba(0, 0, 0, 0.2);
border: 1px solid var(--border-dark);
border-radius: 8px;
padding: 0.75rem;
position: relative;
}
body.light-theme .pipeline-step {
background: rgba(0, 0, 0, 0.04);
border-color: var(--border-light);
}
.pipeline-step-header {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 0.75rem;
font-weight: 700;
color: var(--primary-color);
margin-bottom: 0.4rem;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.pipeline-targets {
display: flex;
flex-wrap: wrap;
gap: 0.4rem;
}
.pipeline-target-chip {
background: rgba(187, 134, 252, 0.1);
border: 1px solid rgba(187, 134, 252, 0.2);
border-radius: 6px;
padding: 3px 8px;
font-size: 0.8rem;
display: flex;
align-items: center;
gap: 4px;
}
.pipeline-arrow {
text-align: center;
color: var(--muted-dark);
font-size: 0.8rem;
margin: -0.25rem 0;
}
.tier-box {
border: 1px solid var(--border-dark);
border-radius: 10px;
padding: 1rem;
margin-bottom: 0.75rem;
background: rgba(0, 0, 0, 0.15);
}
body.light-theme .tier-box {
background: rgba(0, 0, 0, 0.03);
}
.tier-box-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.75rem;
}
.tier-box-title {
font-size: 0.85rem;
font-weight: 700;
color: var(--primary-color);
display: flex;
align-items: center;
gap: 0.5rem;
}
.target-row {
display: flex;
gap: 0.5rem;
margin-bottom: 0.5rem;
align-items: center;
}
.target-row select {
flex: 1;
}
.target-row input {
flex: 1;
}
`;
const bodyHtml = `
<section id="models-page">
<div class="section-header">
<div>
<h2 class="section-title">
<i class="fas fa-cubes"></i>
<span>Configured Custom Models</span>
</h2>
<p class="card-subtitle">
Custom models define the model identifier passed by clients and their fallback tiers [Main &rarr; Fallback 1 &rarr; Fallback 2...].
</p>
</div>
<button id="add-model-btn" class="nav-btn primary">
<i class="fas fa-plus"></i>
<span>New Custom Model</span>
</button>
</div>
<div id="models-list" class="grid-container">
<!-- Model cards injected via JS -->
</div>
</section>
`;
const modalsHtml = `
<!-- Custom Model Modal -->
<div id="model-modal" class="modal-overlay">
<div class="modal-content" style="max-width: 750px;">
<div class="modal-header">
<h3 id="model-modal-title" class="modal-title">
<i class="fas fa-layer-group"></i>
<span>Configure Custom Model</span>
</h3>
<button class="icon-btn close-modal" data-modal="model-modal">
<i class="fas fa-times"></i>
</button>
</div>
<form id="model-form">
<input type="hidden" id="model-id">
<div class="modal-body">
<div class="form-group">
<label class="form-label" for="model-name">
<span>Model Identifier</span>
<span class="form-hint">What clients request in <code>model: "..."</code></span>
</label>
<input type="text" id="model-name" class="form-input" placeholder="e.g. gemini-flash-lite-latest or smart-agent" required>
</div>
<div class="form-group">
<label class="form-label" for="model-desc">Description (Optional)</label>
<input type="text" id="model-desc" class="form-input" placeholder="e.g. Fast Gemini with Groq Llama fallback">
</div>
<div class="form-group">
<label class="checkbox-label">
<input type="checkbox" id="model-is-default">
<span>Set as Default Model (Used if client leaves model unspecified)</span>
</label>
</div>
<div style="border-top: 1px solid var(--border-dark); padding-top: 1rem;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.75rem;">
<div>
<strong style="font-size: 0.95rem;">Fallback Tiers Pipeline</strong>
<p class="card-subtitle">Tier 0 (Main) is executed first; if its keys/providers fail or overload, it cascades to Tier 1, then Tier 2...</p>
</div>
<button type="button" id="add-tier-btn" class="nav-btn" style="font-size: 0.75rem;">
<i class="fas fa-plus"></i>
<span>Add Fallback Tier</span>
</button>
</div>
<div id="tiers-builder-container">
<!-- Tier boxes injected here -->
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="nav-btn close-modal" data-modal="model-modal">Cancel</button>
<button type="submit" class="nav-btn primary">Save Custom Model</button>
</div>
</form>
</div>
</div>
`;
const pageScript = `
let currentConfig = { providers: [], customModels: [] };
let currentTiers = [];
async function initPage() {
await loadConfiguration();
}
async function loadConfiguration() {
try {
const res = await apiRequest('/api/admin/config?include_keys=true');
if (!res.ok) throw new Error('Failed to load configuration');
currentConfig = await res.json();
renderModelsList();
} catch (err) {
showToast(err.message, 'error');
}
}
function renderModelsList() {
const container = document.getElementById('models-list');
container.innerHTML = '';
if (!currentConfig.customModels || currentConfig.customModels.length === 0) {
container.innerHTML = '<div style="grid-column: 1/-1; padding: 3rem; text-align: center; color: var(--muted-dark); background: var(--card-dark); border-radius: 12px; border: 1px dashed var(--border-dark);"><i class="fas fa-layer-group" style="font-size: 2rem; margin-bottom: 1rem; opacity: 0.5;"></i><p>No custom models configured yet. Click "New Custom Model" to create one.</p></div>';
return;
}
currentConfig.customModels.forEach(model => {
const card = document.createElement('div');
card.className = 'card';
let pipelineHtml = '';
const sortedTiers = [...(model.tiers || [])].sort((a, b) => a.tierIndex - b.tierIndex);
sortedTiers.forEach((tier, idx) => {
if (idx > 0) {
pipelineHtml += '<div class="pipeline-arrow"><i class="fas fa-arrow-down"></i> <span style="font-size: 0.7rem; font-style: italic;">if exhausted / fails</span></div>';
}
const targetChips = tier.targets.map(t => {
const prov = currentConfig.providers.find(p => p.id === t.providerId);
const provName = prov ? prov.name : 'Unknown';
return '<div class="pipeline-target-chip"><i class="fas fa-microchip" style="color: var(--primary-color);"></i><strong>' + escapeHtml(provName) + ':</strong> ' + escapeHtml(t.model) + '</div>';
}).join('');
pipelineHtml += '<div class="pipeline-step"><div class="pipeline-step-header"><span>' + escapeHtml(tier.name || 'Tier ' + tier.tierIndex) + '</span><span>' + tier.targets.length + ' Target(s)</span></div><div class="pipeline-targets">' + (targetChips || '<span style="color: var(--muted-dark); font-size: 0.75rem;">No targets assigned</span>') + '</div></div>';
});
card.innerHTML = \`
<div class="card-top">
<div>
<div class="card-title">
<span>\${escapeHtml(model.name)}</span>
\${model.isDefault ? '<span class="badge badge-primary"><i class="fas fa-star"></i> Default</span>' : ''}
</div>
<div class="card-subtitle">\${escapeHtml(model.description || 'Custom Revolver Model')}</div>
</div>
<div class="card-actions">
<button class="icon-btn edit-model-btn" data-id="\${escapeHtml(model.id)}" title="Edit Model">
<i class="fas fa-edit"></i>
</button>
<button class="icon-btn delete delete-model-btn" data-id="\${escapeHtml(model.id)}" title="Delete Model">
<i class="fas fa-trash"></i>
</button>
</div>
</div>
<div class="pipeline-view">\${pipelineHtml}</div>
\`;
container.appendChild(card);
});
document.querySelectorAll('.edit-model-btn').forEach(btn => {
btn.addEventListener('click', () => editModel(btn.getAttribute('data-id')));
});
document.querySelectorAll('.delete-model-btn').forEach(btn => {
btn.addEventListener('click', () => deleteModel(btn.getAttribute('data-id')));
});
}
document.getElementById('add-model-btn').addEventListener('click', () => {
if (currentConfig.providers.length === 0) {
showToast('Please add at least one Provider on the API Providers page first before configuring Custom Models.', 'warning');
return;
}
document.getElementById('model-modal-title').innerHTML = '<i class="fas fa-layer-group"></i><span>Create Custom Model</span>';
document.getElementById('model-id').value = '';
document.getElementById('model-name').value = '';
document.getElementById('model-desc').value = '';
document.getElementById('model-is-default').checked = currentConfig.customModels.length === 0;
currentTiers = [
{
tierIndex: 0,
name: 'Main Tier',
targets: [{ providerId: currentConfig.providers[0].id, model: 'gemini-flash-lite-latest' }]
}
];
renderTiersBuilder();
openModal('model-modal');
});
function renderTiersBuilder() {
const container = document.getElementById('tiers-builder-container');
container.innerHTML = '';
currentTiers.forEach((tier, tIdx) => {
const box = document.createElement('div');
box.className = 'tier-box';
const tierHeader = document.createElement('div');
tierHeader.className = 'tier-box-header';
tierHeader.innerHTML = \`
<span class="tier-box-title">
<i class="fas \${tIdx === 0 ? 'fa-star' : 'fa-shield-alt'}"></i>
<span>\${tIdx === 0 ? 'Tier 0 (Main Model)' : 'Tier ' + tIdx + ' (Fallback Tier)'}</span>
</span>
<div style="display: flex; gap: 0.4rem;">
<button type="button" class="nav-btn add-target-btn" data-tidx="\${tIdx}" style="padding: 2px 8px; font-size: 0.75rem;">
<i class="fas fa-plus"></i> Add Target
</button>
\${tIdx > 0 ? \`<button type="button" class="icon-btn delete remove-tier-btn" data-tidx="\${tIdx}" title="Remove Tier"><i class="fas fa-trash"></i></button>\` : ''}
</div>
\`;
box.appendChild(tierHeader);
const targetsContainer = document.createElement('div');
tier.targets.forEach((target, targetIdx) => {
const row = document.createElement('div');
row.className = 'target-row';
const provOptions = currentConfig.providers.map(p =>
\`<option value="\${escapeHtml(p.id)}" \${p.id === target.providerId ? 'selected' : ''}>\${escapeHtml(p.name)} (\${escapeHtml(p.type)})</option>\`
).join('');
row.innerHTML = \`
<select class="form-select target-provider-select" data-tidx="\${tIdx}" data-tgidx="\${targetIdx}">
\${provOptions}
</select>
<input type="text" class="form-input target-model-input" data-tidx="\${tIdx}" data-tgidx="\${targetIdx}" placeholder="Model ID (e.g. gemini-2.0-flash)" value="\${escapeHtml(target.model)}" required>
\${tier.targets.length > 1 ? \`<button type="button" class="icon-btn delete remove-target-btn" data-tidx="\${tIdx}" data-tgidx="\${targetIdx}" title="Remove Target"><i class="fas fa-times"></i></button>\` : ''}
\`;
targetsContainer.appendChild(row);
});
box.appendChild(targetsContainer);
container.appendChild(box);
});
container.querySelectorAll('.target-provider-select').forEach(sel => {
sel.addEventListener('change', (e) => {
const tIdx = parseInt(e.target.getAttribute('data-tidx'));
const tgIdx = parseInt(e.target.getAttribute('data-tgidx'));
currentTiers[tIdx].targets[tgIdx].providerId = e.target.value;
});
});
container.querySelectorAll('.target-model-input').forEach(inp => {
inp.addEventListener('input', (e) => {
const tIdx = parseInt(e.target.getAttribute('data-tidx'));
const tgIdx = parseInt(e.target.getAttribute('data-tgidx'));
currentTiers[tIdx].targets[tgIdx].model = e.target.value.trim();
});
});
container.querySelectorAll('.add-target-btn').forEach(btn => {
btn.addEventListener('click', () => {
const tIdx = parseInt(btn.getAttribute('data-tidx'));
currentTiers[tIdx].targets.push({
providerId: currentConfig.providers[0].id,
model: ''
});
renderTiersBuilder();
});
});
container.querySelectorAll('.remove-target-btn').forEach(btn => {
btn.addEventListener('click', () => {
const tIdx = parseInt(btn.getAttribute('data-tidx'));
const tgIdx = parseInt(btn.getAttribute('data-tgidx'));
currentTiers[tIdx].targets.splice(tgIdx, 1);
renderTiersBuilder();
});
});
container.querySelectorAll('.remove-tier-btn').forEach(btn => {
btn.addEventListener('click', () => {
const tIdx = parseInt(btn.getAttribute('data-tidx'));
currentTiers.splice(tIdx, 1);
currentTiers.forEach((t, i) => t.tierIndex = i);
renderTiersBuilder();
});
});
}
document.getElementById('add-tier-btn').addEventListener('click', () => {
const nextIdx = currentTiers.length;
currentTiers.push({
tierIndex: nextIdx,
name: 'Fallback Tier ' + nextIdx,
targets: [{ providerId: currentConfig.providers[0].id, model: '' }]
});
renderTiersBuilder();
});
function editModel(id) {
const m = currentConfig.customModels.find(mod => mod.id === id);
if (!m) return;
document.getElementById('model-modal-title').innerHTML = '<i class="fas fa-layer-group"></i><span>Edit Custom Model</span>';
document.getElementById('model-id').value = m.id;
document.getElementById('model-name').value = m.name;
document.getElementById('model-desc').value = m.description || '';
document.getElementById('model-is-default').checked = !!m.isDefault;
currentTiers = JSON.parse(JSON.stringify(m.tiers || []));
if (currentTiers.length === 0 && currentConfig.providers.length > 0) {
currentTiers = [{ tierIndex: 0, name: 'Main Tier', targets: [{ providerId: currentConfig.providers[0].id, model: '' }] }];
}
renderTiersBuilder();
openModal('model-modal');
}
document.getElementById('model-form').addEventListener('submit', async (e) => {
e.preventDefault();
const id = document.getElementById('model-id').value;
const name = document.getElementById('model-name').value.trim();
const description = document.getElementById('model-desc').value.trim();
const isDefault = document.getElementById('model-is-default').checked;
for (const t of currentTiers) {
if (!t.targets || t.targets.length === 0) {
showToast('Every tier must contain at least one target.', 'error');
return;
}
for (const tg of t.targets) {
if (!tg.model) {
showToast('Please provide a Model ID for all targets.', 'error');
return;
}
}
}
try {
const res = await apiRequest('/api/admin/models', {
method: 'POST',
body: {
id: id || undefined,
name,
description,
isDefault,
tiers: currentTiers
}
});
if (!res.ok) {
const err = await res.json();
throw new Error(err.error || 'Failed to save model');
}
showToast('Custom model saved successfully!', 'success');
closeModal('model-modal');
await loadConfiguration();
} catch (err) {
showToast(err.message, 'error');
}
});
async function deleteModel(id) {
if (!confirm('Are you sure you want to delete this custom model?')) return;
try {
const res = await apiRequest('/api/admin/models/' + id, { method: 'DELETE' });
if (!res.ok) throw new Error('Failed to delete custom model');
showToast('Custom model deleted.', 'info');
await loadConfiguration();
} catch (err) {
showToast(err.message, 'error');
}
}
`;
return renderAdminLayout({
activePage: 'models',
pageTitle: 'Custom Models & Revolver',
bodyHtml,
modalsHtml,
pageScript,
extraStyles
});
}

195
src/admin/playgroundPage.ts Normal file
View file

@ -0,0 +1,195 @@
import { renderAdminLayout } from './layout';
export function renderPlaygroundPage(): string {
const extraStyles = `
.playground-container {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1.5rem;
}
@media (max-width: 900px) {
.playground-container {
grid-template-columns: 1fr;
}
}
.trace-card {
background: rgba(0, 0, 0, 0.25);
border: 1px solid var(--border-dark);
border-radius: 8px;
padding: 1rem;
margin-bottom: 1rem;
}
.trace-item {
display: flex;
justify-content: space-between;
font-size: 0.85rem;
padding: 0.3rem 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}
`;
const bodyHtml = `
<section id="playground-page">
<div class="section-header">
<div>
<h2 class="section-title">
<i class="fas fa-flask"></i>
<span>Revolver Playground</span>
</h2>
<p class="card-subtitle">
Test your models live. Observe key rotation and fallback cascade execution in real time.
</p>
</div>
</div>
<div class="playground-container">
<div class="card">
<h3 style="margin-bottom: 1rem; font-size: 1rem;">Test Input</h3>
<div class="form-group" style="margin-bottom: 1rem;">
<label class="form-label" for="test-model-select">Select Custom Model</label>
<select id="test-model-select" class="form-select"></select>
</div>
<div class="form-group" style="margin-bottom: 1.25rem;">
<label class="form-label" for="test-prompt-input">Test Prompt</label>
<textarea id="test-prompt-input" class="form-textarea" placeholder="Enter a test prompt (e.g. Say hello in three words)...">Say hello in three words.</textarea>
</div>
<button id="run-test-btn" class="nav-btn primary" style="justify-content: center; padding: 0.75rem;">
<i class="fas fa-paper-plane"></i>
<span>Run Test Completion</span>
</button>
</div>
<div class="card">
<h3 style="margin-bottom: 1rem; font-size: 1rem;">Diagnostic Trace &amp; Output</h3>
<div id="test-trace-container" style="display: none;">
<div class="trace-card">
<div class="trace-item">
<span style="color: var(--muted-dark);">Execution Tier:</span>
<strong id="trace-tier" style="color: var(--primary-color);"></strong>
</div>
<div class="trace-item">
<span style="color: var(--muted-dark);">Resolved Provider:</span>
<span id="trace-provider"></span>
</div>
<div class="trace-item">
<span style="color: var(--muted-dark);">Underlying Model:</span>
<code id="trace-model"></code>
</div>
<div class="trace-item">
<span style="color: var(--muted-dark);">Key Selected:</span>
<code id="trace-key"></code>
</div>
<div class="trace-item">
<span style="color: var(--muted-dark);">Duration:</span>
<span id="trace-duration"></span>
</div>
<div class="trace-item" style="border: none;">
<span style="color: var(--muted-dark);">Token Usage:</span>
<span id="trace-tokens"></span>
</div>
</div>
</div>
<div class="form-group">
<label class="form-label">Response Text</label>
<div id="test-response-output" style="background: rgba(0, 0, 0, 0.3); border: 1px solid var(--border-dark); border-radius: 8px; padding: 1rem; min-height: 120px; font-family: monospace; white-space: pre-wrap; font-size: 0.85rem; color: var(--text-dark);">Awaiting test execution...</div>
</div>
</div>
</div>
</section>
`;
const pageScript = `
let currentConfig = { providers: [], customModels: [] };
async function initPage() {
await loadConfiguration();
}
async function loadConfiguration() {
try {
const res = await apiRequest('/api/admin/config');
if (!res.ok) throw new Error('Failed to load configuration');
currentConfig = await res.json();
populatePlaygroundSelect();
} catch (err) {
showToast(err.message, 'error');
}
}
function populatePlaygroundSelect() {
const select = document.getElementById('test-model-select');
select.innerHTML = '';
(currentConfig.customModels || []).forEach(m => {
const opt = document.createElement('option');
opt.value = m.id;
opt.textContent = m.name + (m.isDefault ? ' (Default)' : '');
select.appendChild(opt);
});
}
document.getElementById('run-test-btn').addEventListener('click', async () => {
const modelId = document.getElementById('test-model-select').value;
const prompt = document.getElementById('test-prompt-input').value.trim();
if (!modelId) {
showToast('No model selected. Configure a Custom Model first.', 'error');
return;
}
if (!prompt) {
showToast('Prompt is required.', 'error');
return;
}
const runBtn = document.getElementById('run-test-btn');
const outputBox = document.getElementById('test-response-output');
const traceContainer = document.getElementById('test-trace-container');
runBtn.disabled = true;
runBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Running Revolver Pipeline...';
outputBox.textContent = 'Contacting provider and executing prompt...';
try {
const res = await apiRequest('/api/admin/test-run', {
method: 'POST',
body: { customModelId: modelId, prompt }
});
const data = await res.json();
if (!res.ok) {
throw new Error(data.error?.message || 'Test run failed');
}
outputBox.textContent = data.content || JSON.stringify(data.fullResponse, null, 2);
if (data.trace) {
traceContainer.style.display = 'block';
document.getElementById('trace-tier').textContent = data.trace.tierName + ' (Index: ' + data.trace.tierIndex + ')';
document.getElementById('trace-provider').textContent = data.trace.providerName + ' [' + data.trace.providerType + ']';
document.getElementById('trace-model').textContent = data.trace.model;
document.getElementById('trace-key').textContent = data.trace.maskedKey + ' (Key #' + (data.trace.keyIndex + 1) + ')';
document.getElementById('trace-duration').textContent = data.trace.durationMs + ' ms';
const tok = data.trace.tokens;
document.getElementById('trace-tokens').textContent = tok ? tok.promptTokens + ' in / ' + tok.completionTokens + ' out (' + tok.totalTokens + ' total)' : 'N/A';
}
showToast('Revolver pipeline executed successfully!', 'success');
} catch (err) {
outputBox.textContent = '[ERROR]: ' + err.message;
traceContainer.style.display = 'none';
showToast('Test failed: ' + err.message, 'error');
} finally {
runBtn.disabled = false;
runBtn.innerHTML = '<i class="fas fa-paper-plane"></i> <span>Run Test Completion</span>';
}
});
`;
return renderAdminLayout({
activePage: 'playground',
pageTitle: 'Revolver Playground',
bodyHtml,
pageScript,
extraStyles
});
}

325
src/admin/providersPage.ts Normal file
View file

@ -0,0 +1,325 @@
import { renderAdminLayout } from './layout';
export function renderProvidersPage(): string {
const bodyHtml = `
<section id="providers-page">
<div class="section-header">
<div>
<h2 class="section-title">
<i class="fas fa-network-wired"></i>
<span>API Providers & Key Pools</span>
</h2>
<p class="card-subtitle">
Configure Google AI Studio (Gemini), Groq Cloud, OpenAI, or any Custom OpenAI-compatible provider with rotating keys.
</p>
</div>
<button id="add-provider-btn" class="nav-btn primary">
<i class="fas fa-plus"></i>
<span>Add Provider</span>
</button>
</div>
<div id="providers-list" class="grid-container">
<!-- Provider cards injected via JS -->
</div>
</section>
`;
const modalsHtml = `
<!-- Provider Modal -->
<div id="provider-modal" class="modal-overlay">
<div class="modal-content">
<div class="modal-header">
<h3 id="provider-modal-title" class="modal-title">
<i class="fas fa-server"></i>
<span>Add Provider</span>
</h3>
<button class="icon-btn close-modal" data-modal="provider-modal">
<i class="fas fa-times"></i>
</button>
</div>
<form id="provider-form">
<input type="hidden" id="provider-id">
<div class="modal-body">
<div class="form-group">
<label class="form-label" for="provider-name">Provider Name</label>
<input type="text" id="provider-name" class="form-input" placeholder="e.g. Google AI Studio, Groq Work, OpenAI Main" required>
</div>
<div class="form-group">
<label class="form-label" for="provider-type">Provider Type</label>
<select id="provider-type" class="form-select">
<option value="gemini">Google AI Studio (Gemini SDK)</option>
<option value="groq">Groq Cloud (OpenAI-compatible)</option>
<option value="openai">OpenAI (Official Endpoint)</option>
<option value="custom">Custom (OpenAI-compatible / Proxy / Ollama / DeepSeek)</option>
</select>
</div>
<div class="form-group">
<label class="form-label" for="provider-url">
<span>Base URL</span>
<span class="form-hint">Endpoint root (auto-populated by type)</span>
</label>
<input type="text" id="provider-url" class="form-input" placeholder="https://api.openai.com/v1">
</div>
<div class="form-group">
<label class="form-label" for="provider-keys">
<span>API Keys (One per line)</span>
<span class="form-hint">The revolver rotates through these keys</span>
</label>
<textarea id="provider-keys" class="form-textarea" placeholder="Paste keys here, one per line:&#10;key1&#10;key2&#10;key3" required></textarea>
</div>
<div class="form-group" id="provider-moderation-group" style="display: flex; align-items: flex-start; gap: 0.6rem; margin-top: 0.75rem; background: rgba(0,0,0,0.15); padding: 0.75rem; border-radius: 8px; border: 1px solid var(--border-dark);">
<input type="checkbox" id="provider-disable-moderation" checked style="margin-top: 3px; accent-color: var(--primary-color); width: 16px; height: 16px; cursor: pointer;">
<label for="provider-disable-moderation" style="font-size: 0.85rem; cursor: pointer; user-select: none;">
<strong>Disable Gemini Content Moderation (BLOCK_NONE)</strong>
<span class="form-hint" style="display: block; font-size: 0.75rem; color: var(--muted-dark); margin-top: 2px;">
Injects official API safety thresholds (HarmBlockThreshold.BLOCK_NONE) to prevent upstream safety blocks &amp; "Unknown response" errors
</span>
</label>
</div>
<div id="provider-test-area" style="display: none; border-top: 1px solid var(--border-dark); padding-top: 1rem;">
<div class="form-label">
<span>Verify Keys Live</span>
<span class="form-hint">Send a quick ping to test credentials</span>
</div>
<div id="provider-test-keys-list" style="display: flex; flex-direction: column; gap: 0.5rem; margin-top: 0.5rem;"></div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="nav-btn close-modal" data-modal="provider-modal">Cancel</button>
<button type="submit" class="nav-btn primary">Save Provider</button>
</div>
</form>
</div>
</div>
`;
const pageScript = `
let currentConfig = { providers: [], customModels: [] };
async function initPage() {
await loadConfiguration();
}
async function loadConfiguration() {
try {
const res = await apiRequest('/api/admin/config?include_keys=true');
if (!res.ok) throw new Error('Failed to load configuration');
currentConfig = await res.json();
renderProvidersList();
} catch (err) {
showToast(err.message, 'error');
}
}
function renderProvidersList() {
const container = document.getElementById('providers-list');
container.innerHTML = '';
if (!currentConfig.providers || currentConfig.providers.length === 0) {
container.innerHTML = '<div style="grid-column: 1/-1; padding: 3rem; text-align: center; color: var(--muted-dark); background: var(--card-dark); border-radius: 12px; border: 1px dashed var(--border-dark);"><i class="fas fa-server" style="font-size: 2rem; margin-bottom: 1rem; opacity: 0.5;"></i><p>No providers configured yet. Click "Add Provider" to add your API credentials.</p></div>';
return;
}
currentConfig.providers.forEach(p => {
const card = document.createElement('div');
card.className = 'card';
const typeBadge = p.type === 'gemini' ? 'badge-primary' : p.type === 'groq' ? 'badge-warning' : p.type === 'openai' ? 'badge-success' : 'badge-info';
const keysCount = p.keys ? p.keys.length : 0;
const totalRequests = p.keys ? p.keys.reduce((sum, k) => sum + (k.requestCount || 0), 0) : 0;
card.innerHTML = \`
<div class="card-top">
<div>
<div class="card-title">
<span>\${escapeHtml(p.name)}</span>
<span class="badge \${typeBadge}">\${escapeHtml(p.type)}</span>
</div>
<div class="card-subtitle" style="word-break: break-all;">\${escapeHtml(p.baseUrl || defaultUrls[p.type])}</div>
</div>
<div class="card-actions">
<button class="icon-btn edit-provider-btn" data-id="\${escapeHtml(p.id)}" title="Edit Provider">
<i class="fas fa-edit"></i>
</button>
<button class="icon-btn delete delete-provider-btn" data-id="\${escapeHtml(p.id)}" title="Delete Provider">
<i class="fas fa-trash"></i>
</button>
</div>
</div>
<div style="margin: 1rem 0; font-size: 0.85rem; display: flex; flex-direction: column; gap: 0.4rem;">
<div style="display: flex; justify-content: space-between;">
<span style="color: var(--muted-dark);">Configured Keys:</span>
<strong>\${keysCount} key(s) in pool</strong>
</div>
<div style="display: flex; justify-content: space-between;">
<span style="color: var(--muted-dark);">Total Requests Routed:</span>
<strong>\${totalRequests}</strong>
</div>
</div>
<button class="nav-btn test-provider-btn" data-id="\${escapeHtml(p.id)}" style="width: 100%; justify-content: center; margin-top: auto;">
<i class="fas fa-vial"></i>
<span>Test Provider Keys</span>
</button>
\`;
container.appendChild(card);
});
document.querySelectorAll('.edit-provider-btn').forEach(btn => {
btn.addEventListener('click', () => editProvider(btn.getAttribute('data-id')));
});
document.querySelectorAll('.delete-provider-btn').forEach(btn => {
btn.addEventListener('click', () => deleteProvider(btn.getAttribute('data-id')));
});
document.querySelectorAll('.test-provider-btn').forEach(btn => {
btn.addEventListener('click', () => editProvider(btn.getAttribute('data-id'), true));
});
}
const providerForm = document.getElementById('provider-form');
const providerTypeSelect = document.getElementById('provider-type');
const providerUrlInput = document.getElementById('provider-url');
providerTypeSelect.addEventListener('change', () => {
const type = providerTypeSelect.value;
providerUrlInput.value = defaultUrls[type] || '';
});
document.getElementById('add-provider-btn').addEventListener('click', () => {
document.getElementById('provider-modal-title').innerHTML = '<i class="fas fa-server"></i><span>Add Provider</span>';
document.getElementById('provider-id').value = '';
document.getElementById('provider-name').value = '';
providerTypeSelect.value = 'gemini';
providerUrlInput.value = defaultUrls.gemini;
document.getElementById('provider-keys').value = '';
document.getElementById('provider-disable-moderation').checked = true;
document.getElementById('provider-test-area').style.display = 'none';
openModal('provider-modal');
});
function editProvider(id, focusTest = false) {
const p = currentConfig.providers.find(prov => prov.id === id);
if (!p) return;
document.getElementById('provider-modal-title').innerHTML = '<i class="fas fa-server"></i><span>Edit Provider</span>';
document.getElementById('provider-id').value = p.id;
document.getElementById('provider-name').value = p.name;
providerTypeSelect.value = p.type;
providerUrlInput.value = p.baseUrl || defaultUrls[p.type];
document.getElementById('provider-keys').value = (p.keys || []).map(k => k.key).join('\\n');
document.getElementById('provider-disable-moderation').checked = p.disableModeration !== false;
const testArea = document.getElementById('provider-test-area');
const testList = document.getElementById('provider-test-keys-list');
testList.innerHTML = '';
testArea.style.display = 'block';
(p.keys || []).forEach((k, idx) => {
const row = document.createElement('div');
row.style.display = 'flex';
row.style.justifyContent = 'space-between';
row.style.alignItems = 'center';
row.style.background = 'rgba(0,0,0,0.2)';
row.style.padding = '0.5rem';
row.style.borderRadius = '6px';
row.style.fontSize = '0.8rem';
const mask = k.key.length > 8 ? k.key.slice(0, 4) + '...' + k.key.slice(-4) : '****';
row.innerHTML = \`
<span><strong>Key \${idx + 1}:</strong> <code>\${escapeHtml(mask)}</code></span>
<button type="button" class="nav-btn test-single-key-btn" data-key="\${escapeHtml(k.key)}" style="padding: 3px 8px; font-size: 0.75rem;">
<i class="fas fa-bolt"></i> Test
</button>
\`;
testList.appendChild(row);
});
testList.querySelectorAll('.test-single-key-btn').forEach(btn => {
btn.addEventListener('click', async () => {
const keyToTest = btn.getAttribute('data-key');
btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
btn.disabled = true;
try {
const res = await apiRequest('/api/admin/providers/' + p.id + '/test-key', {
method: 'POST',
body: { key: keyToTest }
});
const result = await res.json();
if (result.success) {
btn.className = 'nav-btn primary';
btn.innerHTML = '<i class="fas fa-check"></i> ' + result.latencyMs + 'ms';
showToast(result.message, 'success');
} else {
btn.className = 'nav-btn danger';
btn.innerHTML = '<i class="fas fa-times"></i> Failed';
showToast(result.message, 'error');
}
} catch (err) {
btn.className = 'nav-btn danger';
btn.innerHTML = '<i class="fas fa-times"></i>';
showToast('Test failed: ' + err.message, 'error');
} finally {
btn.disabled = false;
}
});
});
openModal('provider-modal');
}
providerForm.addEventListener('submit', async (e) => {
e.preventDefault();
const id = document.getElementById('provider-id').value;
const name = document.getElementById('provider-name').value.trim();
const type = providerTypeSelect.value;
const baseUrl = providerUrlInput.value.trim();
const rawKeys = document.getElementById('provider-keys').value.split('\\n').map(k => k.trim()).filter(Boolean);
const disableModeration = document.getElementById('provider-disable-moderation').checked;
if (rawKeys.length === 0) {
showToast('Please provide at least one API key.', 'error');
return;
}
try {
const res = await apiRequest('/api/admin/providers', {
method: 'POST',
body: { id: id || undefined, name, type, baseUrl, keys: rawKeys, disableModeration }
});
if (!res.ok) {
const err = await res.json();
throw new Error(err.error || 'Failed to save provider');
}
showToast('Provider saved successfully!', 'success');
closeModal('provider-modal');
await loadConfiguration();
} catch (err) {
showToast(err.message, 'error');
}
});
async function deleteProvider(id) {
if (!confirm('Are you sure you want to delete this provider? Any custom model targets referencing it will also be removed.')) return;
try {
const res = await apiRequest('/api/admin/providers/' + id, { method: 'DELETE' });
if (!res.ok) throw new Error('Failed to delete provider');
showToast('Provider deleted.', 'info');
await loadConfiguration();
} catch (err) {
showToast(err.message, 'error');
}
}
`;
return renderAdminLayout({
activePage: 'providers',
pageTitle: 'API Providers',
bodyHtml,
modalsHtml,
pageScript
});
}

438
src/admin/telemetryPage.ts Normal file
View file

@ -0,0 +1,438 @@
import { renderAdminLayout } from './layout';
export function renderTelemetryPage(): string {
const extraStyles = `
.journey-card {
background: var(--card-dark);
border: 1px solid var(--border-dark);
border-radius: 10px;
padding: 1rem 1.25rem;
margin-bottom: 0.75rem;
transition: all 0.2s ease;
}
body.light-theme .journey-card {
background: var(--card-light);
border-color: var(--border-light);
}
.journey-card:hover {
border-color: var(--primary-color);
}
.journey-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.75rem;
flex-wrap: wrap;
gap: 0.5rem;
}
.breadcrumb-cascade {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.4rem;
background: rgba(0, 0, 0, 0.2);
border: 1px solid var(--border-dark);
border-radius: 8px;
padding: 0.6rem 0.75rem;
}
body.light-theme .breadcrumb-cascade {
background: rgba(0, 0, 0, 0.03);
border-color: var(--border-light);
}
.cascade-hop {
display: inline-flex;
align-items: center;
gap: 0.35rem;
font-size: 0.75rem;
padding: 3px 8px;
border-radius: 6px;
border: 1px solid transparent;
}
.cascade-hop.success {
background: rgba(3, 218, 198, 0.12);
color: var(--accent-success);
border-color: rgba(3, 218, 198, 0.3);
}
.cascade-hop.failed {
background: rgba(207, 102, 121, 0.12);
color: var(--accent-danger);
border-color: rgba(207, 102, 121, 0.3);
}
.cascade-hop.rate-limited {
background: rgba(255, 183, 77, 0.12);
color: var(--accent-warning);
border-color: rgba(255, 183, 77, 0.3);
}
.cascade-arrow {
color: var(--muted-dark);
font-size: 0.75rem;
}
`;
const bodyHtml = `
<section id="telemetry-page">
<div class="section-header">
<div>
<h2 class="section-title">
<i class="fas fa-tachometer-alt"></i>
<span>Live Provider &amp; Key Health</span>
</h2>
<p class="card-subtitle">
Real-time health, request counts, success rates, and rate-limit cooldown timers across all keys.
</p>
</div>
<div style="display: flex; gap: 0.75rem; align-items: center;">
<span id="telemetry-sse-indicator" class="badge badge-success" style="font-size: 0.75rem; padding: 0.4rem 0.65rem;">
<i class="fas fa-satellite"></i> <span>Live Stream Active</span>
</span>
<button id="refresh-telemetry-btn" class="nav-btn">
<i class="fas fa-sync-alt"></i>
<span>Refresh</span>
</button>
</div>
</div>
<!-- Key & Provider Health Matrix -->
<div id="telemetry-list" class="grid-container" style="margin-bottom: 2rem;">
<!-- Live status cards injected via JS -->
</div>
<!-- Recent Model Fallback Journeys -->
<div class="section-header" style="margin-top: 1rem;">
<div>
<h2 class="section-title">
<i class="fas fa-random"></i>
<span>Recent Model Fallback &amp; Failover Journeys</span>
</h2>
<p class="card-subtitle">
Visual tracking of where and why models failed, how the revolver cascaded across keys and tiers, and what happened next.
</p>
</div>
</div>
<div id="telemetry-journeys-list">
<p style="color: var(--muted-dark); font-size: 0.85rem;">Listening for live fallback journeys...</p>
</div>
</section>
`;
const pageScript = `
let telemetryEventSource = null;
let cachedJourneys = [];
let cachedKeys = [];
async function initPage() {
await loadTelemetry();
connectTelemetrySSE();
}
async function loadTelemetry() {
try {
const res = await apiRequest('/api/admin/telemetry/fallback-traces');
if (!res.ok) throw new Error('Failed to fetch telemetry data');
const data = await res.json();
cachedKeys = data.keys || [];
cachedJourneys = data.journeys || [];
renderTelemetryKeys(cachedKeys, data.circuitBreakers);
renderTelemetryJourneys(cachedJourneys);
} catch (err) {
showToast('Telemetry load failed: ' + err.message, 'error');
}
}
function connectTelemetrySSE() {
if (telemetryEventSource) return;
try {
telemetryEventSource = new EventSource('/api/admin/telemetry/stream?api_key=' + encodeURIComponent(activeKey));
telemetryEventSource.onopen = function() {
const indicator = document.getElementById('telemetry-sse-indicator');
if (indicator) {
indicator.className = 'badge badge-success';
indicator.innerHTML = '<i class="fas fa-satellite"></i> <span>Live Stream Active</span>';
}
};
telemetryEventSource.onmessage = function(e) {
try {
const msg = JSON.parse(e.data);
if (msg.type === 'snapshot') {
cachedKeys = msg.keys || [];
cachedJourneys = msg.journeys || [];
renderTelemetryKeys(cachedKeys, msg.circuitBreakers);
renderTelemetryJourneys(cachedJourneys);
} else if (msg.type === 'key_status_update') {
cachedKeys = msg.keys || [];
renderTelemetryKeys(cachedKeys, msg.circuitBreakers);
} else if (msg.type === 'fallback_journey') {
cachedJourneys.unshift(msg.data);
if (cachedJourneys.length > 50) cachedJourneys.length = 50;
renderTelemetryJourneys(cachedJourneys);
}
} catch (err) {
console.error('Failed to parse telemetry SSE message:', err);
}
};
telemetryEventSource.onerror = function() {
const indicator = document.getElementById('telemetry-sse-indicator');
if (indicator) {
indicator.className = 'badge badge-warning';
indicator.innerHTML = '<i class="fas fa-exclamation-triangle"></i> <span>Reconnecting...</span>';
}
};
} catch (err) {
console.error('Telemetry SSE error:', err);
}
}
function renderTelemetryKeys(keys, circuitBreakers) {
const container = document.getElementById('telemetry-list');
if (!container) return;
container.innerHTML = '';
if (circuitBreakers && circuitBreakers.length > 0) {
const cbCard = document.createElement('div');
cbCard.className = 'card';
cbCard.style.borderColor = 'rgba(255, 183, 77, 0.4)';
let cbRows = '';
circuitBreakers.forEach(cb => {
const inCooldown = cb.status === 'cooldown';
const badge = inCooldown
? '<span class="badge badge-warning"><i class="fas fa-fire"></i> Cooldown (' + cb.cooldownRemainingSeconds + 's remaining)</span>'
: (cb.status === 'half_open'
? '<span class="badge badge-info"><i class="fas fa-stethoscope"></i> Probing (Half-Open)</span>'
: '<span class="badge badge-success"><i class="fas fa-check"></i> Healthy</span>');
cbRows += '<div style="background: rgba(0,0,0,0.2); border: 1px solid var(--border-dark); border-radius: 8px; padding: 0.6rem 0.75rem; margin-top: 0.5rem; font-size: 0.8rem; display: flex; justify-content: space-between; align-items: center;">' +
'<div>' +
'<strong><code>' + escapeHtml(cb.model) + '</code></strong> <span style="color: var(--muted-dark); font-size: 0.75rem;">(' + escapeHtml(cb.providerId) + ')</span>' +
(cb.lastError ? '<div style="font-size: 0.72rem; color: var(--accent-danger); margin-top: 0.2rem; max-width: 400px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">' + escapeHtml(cb.lastError) + '</div>' : '') +
'</div>' +
'<div>' + badge + '</div>' +
'</div>';
});
cbCard.innerHTML = '<div class="card-title" style="display: flex; justify-content: space-between; align-items: center;">' +
'<span><i class="fas fa-shield-alt" style="color: var(--accent-warning); margin-right: 0.5rem;"></i> Model Circuit Breakers (Overload Protection)</span>' +
'<button id="reset-cb-btn" class="nav-btn" style="font-size: 0.72rem; padding: 0.2rem 0.5rem;"><i class="fas fa-undo"></i> Reset All</button>' +
'</div>' +
'<div style="margin-top: 0.5rem;">' + cbRows + '</div>';
container.appendChild(cbCard);
const resetBtn = cbCard.querySelector('#reset-cb-btn');
if (resetBtn) {
resetBtn.onclick = async function() {
try {
const res = await apiRequest('/api/admin/circuit-breaker/reset', { method: 'POST' });
if (res.ok) {
showToast('Circuit breakers reset successfully.', 'success');
loadTelemetry();
}
} catch (err) {
showToast('Failed to reset circuit breakers: ' + err.message, 'error');
}
};
}
}
if (!keys || keys.length === 0) {
if (!circuitBreakers || circuitBreakers.length === 0) {
container.innerHTML = '<p style="color: var(--muted-dark);">No provider keys configured.</p>';
}
return;
}
const grouped = {};
keys.forEach(k => {
if (!grouped[k.providerId]) {
grouped[k.providerId] = {
name: k.providerName,
type: k.providerType,
keys: []
};
}
grouped[k.providerId].keys.push(k);
});
Object.keys(grouped).forEach(pid => {
const prov = grouped[pid];
const card = document.createElement('div');
card.className = 'card';
let keysHtml = '';
prov.keys.forEach(k => {
const statusBadge = k.isRateLimited
? '<span class="badge badge-danger"><i class="fas fa-ban"></i> Rate Limited (' + k.cooldownRemainingSeconds + 's)</span>'
: '<span class="badge badge-success"><i class="fas fa-check"></i> Active</span>';
const rateColor = k.successRatePercent >= 90 ? 'var(--accent-success)' : (k.successRatePercent >= 60 ? 'var(--accent-warning)' : 'var(--accent-danger)');
keysHtml += '<div style="background: rgba(0,0,0,0.2); border: 1px solid var(--border-dark); border-radius: 8px; padding: 0.75rem; margin-top: 0.5rem; font-size: 0.8rem;">' +
'<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.4rem;">' +
'<span><strong>Key ' + (k.keyIndex + 1) + ':</strong> <code>' + escapeHtml(k.maskedKey) + '</code></span>' +
statusBadge +
'</div>' +
'<div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 0.5rem; margin-top: 0.4rem; color: var(--muted-dark); font-size: 0.75rem;">' +
'<div>Reqs: <strong style="color: var(--text-dark);">' + k.requestCount + '</strong></div>' +
'<div>OK: <strong style="color: var(--accent-success);">' + k.successCount + '</strong></div>' +
'<div>Errors: <strong style="color: var(--accent-danger);">' + k.errorCount + '</strong></div>' +
'<div>Rate: <strong style="color: ' + rateColor + ';">' + k.successRatePercent + '%</strong></div>' +
'</div>' +
'<div style="margin-top: 0.35rem; color: var(--muted-dark); font-size: 0.72rem;">' +
'Last used: ' + (k.lastUsed ? new Date(k.lastUsed).toLocaleTimeString() : 'Never') +
'</div>' +
'</div>';
});
card.innerHTML = '<div class="card-title">' +
'<span>' + escapeHtml(prov.name) + '</span>' +
'<span class="badge badge-info">' + escapeHtml(prov.type) + '</span>' +
'</div>' +
'<div style="margin-top: 0.5rem;">' + keysHtml + '</div>';
container.appendChild(card);
});
}
function renderTelemetryJourneys(journeys) {
const container = document.getElementById('telemetry-journeys-list');
if (!container) return;
container.innerHTML = '';
if (!journeys || journeys.length === 0) {
container.innerHTML = '<p style="color: var(--muted-dark); font-size: 0.85rem; padding: 1.5rem 0;">No model fallback journeys captured yet. Requests sent to custom models will display their key and tier cascade live here.</p>';
return;
}
journeys.forEach(j => {
const card = document.createElement('div');
card.className = 'journey-card';
let statusBadge = '';
if (j.finalStatus === 'success_direct') {
statusBadge = '<span class="badge badge-success"><i class="fas fa-check"></i> Direct Success</span>';
} else if (j.finalStatus === 'success_fallback') {
const tierStr = j.finalServedBy ? ' (Tier ' + j.finalServedBy.tierIndex + ')' : '';
statusBadge = '<span class="badge badge-primary"><i class="fas fa-random"></i> Fallback Served' + tierStr + '</span>';
} else if (j.finalStatus === 'all_tiers_exhausted') {
statusBadge = '<span class="badge badge-danger"><i class="fas fa-times-circle"></i> All Tiers Exhausted</span>';
} else {
statusBadge = '<span class="badge badge-warning"><i class="fas fa-ban"></i> Cancelled</span>';
}
let cascadeHtml = '';
if (Array.isArray(j.steps)) {
j.steps.forEach((step, idx) => {
const isLast = idx === j.steps.length - 1;
let hopClass = 'cascade-hop';
let icon = 'fa-check';
if (step.status === 'success') {
hopClass += ' success';
icon = 'fa-check';
} else if (step.status === 'rate_limited') {
hopClass += ' rate-limited';
icon = 'fa-ban';
} else {
hopClass += ' failed';
icon = 'fa-exclamation-triangle';
}
const stepLabel = 'Tier ' + step.tierIndex + ' (' + escapeHtml(step.model) + ' / Key #' + (step.keyIndex + 1) + ')';
const statusDetail = step.status === 'success' ? '200 OK (' + step.durationMs + 'ms)' : (step.statusCode ? step.statusCode + ' ' : '') + step.status + ' (' + step.durationMs + 'ms)';
cascadeHtml += '<span class="' + hopClass + '" title="' + escapeHtml(step.nextAction || '') + '">' +
'<i class="fas ' + icon + '"></i> ' +
'<strong>' + stepLabel + '</strong>: ' + escapeHtml(statusDetail) +
'</span>';
if (!isLast) {
cascadeHtml += '<i class="fas fa-arrow-right cascade-arrow"></i>';
}
});
}
let detailRows = '';
if (Array.isArray(j.steps)) {
j.steps.forEach(step => {
const statusColor = step.status === 'success' ? 'var(--accent-success)' : (step.status === 'rate_limited' ? 'var(--accent-warning)' : 'var(--accent-danger)');
detailRows += '<tr>' +
'<td><strong>Hop #' + step.stepIndex + '</strong></td>' +
'<td>Tier ' + step.tierIndex + ' (' + escapeHtml(step.tierName) + ')<br><small style="color: var(--muted-dark);">' + escapeHtml(step.providerName) + ' (' + escapeHtml(step.providerType) + ')</small></td>' +
'<td><code>' + escapeHtml(step.model) + '</code><br><small style="color: var(--muted-dark);">Key #' + (step.keyIndex + 1) + ' (' + escapeHtml(step.maskedKey) + ')</small></td>' +
'<td>' + step.durationMs + ' ms</td>' +
'<td style="color: ' + statusColor + ';"><strong>' + (step.statusCode ? step.statusCode + ' ' : '') + escapeHtml(step.status) + '</strong>' + (step.cooldownSeconds ? '<br><small>Cooldown: ' + step.cooldownSeconds + 's</small>' : '') + '</td>' +
'<td style="font-size: 0.75rem; max-width: 200px; word-break: break-word;">' + escapeHtml(step.errorMessage || 'None') + '</td>' +
'<td style="font-size: 0.75rem; color: var(--primary-color);">' + escapeHtml(step.nextAction || 'None') + '</td>' +
'</tr>';
});
}
const tableDrawerId = 'journey-table-' + j.requestId;
const toggleBtnId = 'journey-toggle-btn-' + j.requestId;
card.innerHTML = '<div class="journey-header">' +
'<div>' +
'<span style="font-weight: 600; font-size: 0.9rem; margin-right: 0.5rem;"><code>' + escapeHtml(j.requestId) + '</code></span>' +
'<span style="color: var(--muted-dark); font-size: 0.78rem;">' + new Date(j.timestamp).toLocaleTimeString() + '</span>' +
'<span style="margin-left: 0.5rem; font-size: 0.8rem;">Model: <strong>' + escapeHtml(j.requestedModel) + '</strong>' +
(j.resolvedModelName !== j.requestedModel ? ' <span style="color: var(--muted-dark);">&rarr; ' + escapeHtml(j.resolvedModelName) + '</span>' : '') +
'</span>' +
'</div>' +
'<div style="display: flex; gap: 0.5rem; align-items: center;">' +
'<span style="font-size: 0.75rem; color: var(--muted-dark);"><i class="fas fa-clock"></i> ' + j.totalDurationMs + ' ms</span>' +
(j.tokens ? '<span style="font-size: 0.75rem; color: var(--muted-dark);"><i class="fas fa-coins"></i> ' + j.tokens.totalTokens + ' tok</span>' : '') +
statusBadge +
'</div>' +
'</div>' +
'<div class="breadcrumb-cascade">' + cascadeHtml + '</div>' +
'<div style="display: flex; justify-content: flex-end; margin-top: 0.5rem;">' +
'<button id="' + toggleBtnId + '" class="nav-btn" style="font-size: 0.72rem; padding: 0.25rem 0.5rem;">' +
'<i class="fas fa-chevron-down"></i> <span>Step Details (' + (j.steps ? j.steps.length : 0) + ' hops)</span>' +
'</button>' +
'</div>' +
'<div id="' + tableDrawerId + '" style="display: none; margin-top: 0.75rem; border-top: 1px solid var(--border-dark); padding-top: 0.75rem; overflow-x: auto;">' +
'<table class="detail-table">' +
'<thead>' +
'<tr style="color: var(--muted-dark); text-align: left; font-size: 0.75rem;">' +
'<th style="padding: 0.3rem 0.5rem;">Hop</th>' +
'<th style="padding: 0.3rem 0.5rem;">Tier / Provider</th>' +
'<th style="padding: 0.3rem 0.5rem;">Model / Key</th>' +
'<th style="padding: 0.3rem 0.5rem;">Latency</th>' +
'<th style="padding: 0.3rem 0.5rem;">Result</th>' +
'<th style="padding: 0.3rem 0.5rem;">Error Details</th>' +
'<th style="padding: 0.3rem 0.5rem;">Action Taken</th>' +
'</tr>' +
'</thead>' +
'<tbody>' + detailRows + '</tbody>' +
'</table>' +
'</div>';
container.appendChild(card);
const toggleBtn = card.querySelector('#' + toggleBtnId);
const tableDrawer = card.querySelector('#' + tableDrawerId);
if (toggleBtn && tableDrawer) {
toggleBtn.addEventListener('click', () => {
const isHidden = tableDrawer.style.display === 'none';
tableDrawer.style.display = isHidden ? 'block' : 'none';
toggleBtn.innerHTML = isHidden
? '<i class="fas fa-chevron-up"></i> <span>Hide Step Details</span>'
: '<i class="fas fa-chevron-down"></i> <span>Step Details (' + (j.steps ? j.steps.length : 0) + ' hops)</span>';
});
}
});
}
document.getElementById('refresh-telemetry-btn').addEventListener('click', loadTelemetry);
`;
return renderAdminLayout({
activePage: 'telemetry',
pageTitle: 'Live Key Telemetry',
bodyHtml,
pageScript,
extraStyles
});
}

File diff suppressed because it is too large Load diff

View file

@ -20,6 +20,7 @@ export const config = {
streamFirstTokenTimeoutMs: parseInt(process.env.STREAM_FIRST_TOKEN_TIMEOUT_MS || '15000', 10), streamFirstTokenTimeoutMs: parseInt(process.env.STREAM_FIRST_TOKEN_TIMEOUT_MS || '15000', 10),
modelCooldownDurationMs: parseInt(process.env.MODEL_COOLDOWN_MS || '60000', 10), modelCooldownDurationMs: parseInt(process.env.MODEL_COOLDOWN_MS || '60000', 10),
maxTargetTimeoutRetries: parseInt(process.env.MAX_TARGET_TIMEOUT_RETRIES || '0', 10), maxTargetTimeoutRetries: parseInt(process.env.MAX_TARGET_TIMEOUT_RETRIES || '0', 10),
maxTargetOverloadRetries: parseInt(process.env.MAX_TARGET_OVERLOAD_RETRIES || '1', 10),
// Gemini Content Moderation // Gemini Content Moderation
disableGeminiModeration: process.env.DISABLE_GEMINI_MODERATION !== 'false' disableGeminiModeration: process.env.DISABLE_GEMINI_MODERATION !== 'false'
}; };

View file

@ -19,6 +19,7 @@ interface TargetHealthInternal {
status: 'healthy' | 'cooldown' | 'half_open'; status: 'healthy' | 'cooldown' | 'half_open';
consecutiveFailures: number; consecutiveFailures: number;
consecutiveTimeouts: number; consecutiveTimeouts: number;
consecutiveOverloads: number;
cooldownUntil: number | null; cooldownUntil: number | null;
lastError: string | null; lastError: string | null;
lastFailedAt: number | null; lastFailedAt: number | null;
@ -44,6 +45,7 @@ export class ModelCircuitBreaker {
status: 'healthy', status: 'healthy',
consecutiveFailures: 0, consecutiveFailures: 0,
consecutiveTimeouts: 0, consecutiveTimeouts: 0,
consecutiveOverloads: 0,
cooldownUntil: null, cooldownUntil: null,
lastError: null, lastError: null,
lastFailedAt: null, lastFailedAt: null,
@ -72,6 +74,7 @@ export class ModelCircuitBreaker {
if (target.cooldownUntil && now >= target.cooldownUntil) { if (target.cooldownUntil && now >= target.cooldownUntil) {
// Cooldown has expired: allow 1 half_open probe request // Cooldown has expired: allow 1 half_open probe request
target.status = 'half_open'; target.status = 'half_open';
target.consecutiveOverloads = 0;
target.probeInFlight = true; target.probeInFlight = true;
target.probeStartedAt = now; target.probeStartedAt = now;
return true; return true;
@ -126,14 +129,16 @@ export class ModelCircuitBreaker {
/** /**
* Record a model target failure. * Record a model target failure.
* If error is 503 or model overload, trips immediately into cooldown. * If error is 503 or model overload, increments consecutiveOverloads and trips into cooldown
* once threshold (1 retry key = 2 attempts, or 1 if only 1 key exists) is reached.
* If timeout, increments consecutive timeouts and trips if threshold reached. * If timeout, increments consecutive timeouts and trips if threshold reached.
*/ */
public recordFailure( public recordFailure(
providerId: string, providerId: string,
model: string, model: string,
error: any, error: any,
isTimeout = false isTimeout = false,
providerKeyCount = 2
): { tripped: boolean; cooldownSeconds: number; reason: string } { ): { tripped: boolean; cooldownSeconds: number; reason: string } {
const target = this.getOrCreate(providerId, model); const target = this.getOrCreate(providerId, model);
const now = Date.now(); const now = Date.now();
@ -147,13 +152,24 @@ export class ModelCircuitBreaker {
} }
const isOverload = this.isModelOverloadOrUnavailable(error); const isOverload = this.isModelOverloadOrUnavailable(error);
if (isOverload) {
target.consecutiveOverloads++;
}
const overloadThreshold = Math.min(
config.maxTargetOverloadRetries + 1,
Math.max(1, providerKeyCount)
);
const isOverloadTrip = isOverload && target.consecutiveOverloads >= overloadThreshold;
const timeoutThreshold = config.maxTargetTimeoutRetries === 0 ? 1 : config.maxTargetTimeoutRetries + 1; const timeoutThreshold = config.maxTargetTimeoutRetries === 0 ? 1 : config.maxTargetTimeoutRetries + 1;
const isConsecutiveTimeoutTrip = isTimeout && target.consecutiveTimeouts >= timeoutThreshold; const isConsecutiveTimeoutTrip = isTimeout && target.consecutiveTimeouts >= timeoutThreshold;
if (isOverload || isConsecutiveTimeoutTrip || target.status === 'half_open') { if (isOverloadTrip || isConsecutiveTimeoutTrip || (!isOverload && target.status === 'half_open')) {
const cooldownMs = config.modelCooldownDurationMs; const cooldownMs = config.modelCooldownDurationMs;
target.status = 'cooldown'; target.status = 'cooldown';
target.cooldownUntil = now + cooldownMs; target.cooldownUntil = now + cooldownMs;
target.consecutiveOverloads = 0;
const reason = isOverload const reason = isOverload
? `Model overload/unavailable (${error?.status || 503}): ${error?.message || 'High demand'}` ? `Model overload/unavailable (${error?.status || 503}): ${error?.message || 'High demand'}`
@ -225,6 +241,7 @@ export class ModelCircuitBreaker {
target.status = 'healthy'; target.status = 'healthy';
target.consecutiveFailures = 0; target.consecutiveFailures = 0;
target.consecutiveTimeouts = 0; target.consecutiveTimeouts = 0;
target.consecutiveOverloads = 0;
target.cooldownUntil = null; target.cooldownUntil = null;
target.lastError = null; target.lastError = null;
target.lastSuccessAt = Date.now(); target.lastSuccessAt = Date.now();

View file

@ -428,6 +428,8 @@ export class RevolverEngine {
console.log(`[REVOLVER] Attempting Tier ${tier.tierIndex} ('${tier.name || 'Tier ' + tier.tierIndex}') with ${candidates.length} candidate(s)...`); console.log(`[REVOLVER] Attempting Tier ${tier.tierIndex} ('${tier.name || 'Tier ' + tier.tierIndex}') with ${candidates.length} candidate(s)...`);
const targetOverloadAttempts = new Map<string, number>();
// Try candidates in this tier // Try candidates in this tier
for (let cIdx = 0; cIdx < candidates.length; cIdx++) { for (let cIdx = 0; cIdx < candidates.length; cIdx++) {
const candidate = candidates[cIdx]; const candidate = candidates[cIdx];
@ -631,6 +633,19 @@ export class RevolverEngine {
const isTimeout = this.isTimeoutError(err); const isTimeout = this.isTimeoutError(err);
const isModelOverload = modelCircuitBreaker.isModelOverloadOrUnavailable(err); const isModelOverload = modelCircuitBreaker.isModelOverloadOrUnavailable(err);
const targetKey = `${candidate.target.providerId}:::${candidate.target.model}`;
let overloadAttempts = targetOverloadAttempts.get(targetKey) || 0;
if (isModelOverload) {
overloadAttempts++;
targetOverloadAttempts.set(targetKey, overloadAttempts);
}
const maxOverloadAttempts = Math.min(
config.maxTargetOverloadRetries + 1,
Math.max(1, candidate.provider.keys.length)
);
const hasReachedOverloadLimit = isModelOverload && overloadAttempts >= maxOverloadAttempts;
let tripResult = { tripped: false, cooldownSeconds: 0, reason: '' }; let tripResult = { tripped: false, cooldownSeconds: 0, reason: '' };
if (allPairsOnCooldown) { if (allPairsOnCooldown) {
// When all pairs were on cooldown, emergency probe failed: put target and key back on cooldown immediately // When all pairs were on cooldown, emergency probe failed: put target and key back on cooldown immediately
@ -640,12 +655,20 @@ export class RevolverEngine {
incrementError: true incrementError: true
}); });
} else if (isModelOverload || isTimeout) { } else if (isModelOverload || isTimeout) {
tripResult = modelCircuitBreaker.recordFailure(candidate.provider.id, candidate.target.model, err, isTimeout); tripResult = modelCircuitBreaker.recordFailure(
candidate.provider.id,
candidate.target.model,
err,
isTimeout,
candidate.provider.keys.length
);
} }
// Zero-tolerance policy: skip remaining keys for this target immediately on 503/overload or timeout // On 503 high-demand/overload, only try 1 more key (up to maxOverloadAttempts = 2 keys total) before skipping remaining keys for this target.
// (Only when NOT in allPairsOnCooldown mode, where every key-model pair in line is given its sequential turn) // Enforce this cap in ALL modes (normal and allPairsOnCooldown emergency mode).
const shouldFastFailTarget = !allPairsOnCooldown && (isModelOverload || (isTimeout && config.maxTargetTimeoutRetries === 0) || tripResult.tripped); const shouldFastFailTarget =
hasReachedOverloadLimit ||
(!allPairsOnCooldown && ((isTimeout && config.maxTargetTimeoutRetries === 0) || tripResult.tripped));
let skippedRemainingCount = 0; let skippedRemainingCount = 0;
if (shouldFastFailTarget) { if (shouldFastFailTarget) {
@ -654,7 +677,7 @@ export class RevolverEngine {
).length; ).length;
if (skippedRemainingCount > 0) { if (skippedRemainingCount > 0) {
console.warn(`[REVOLVER] Fast-failover on '${candidate.target.model}'. Skipping ${skippedRemainingCount} remaining key(s) for this target in Tier ${tier.tierIndex}.`); console.warn(`[REVOLVER] Fast-failover on '${candidate.target.model}' after ${overloadAttempts || 1} attempt(s). Skipping ${skippedRemainingCount} remaining key(s) for this target in Tier ${tier.tierIndex}.`);
candidates = candidates.filter((c, idx) => candidates = candidates.filter((c, idx) =>
idx <= cIdx || c.target.providerId !== candidate.target.providerId || c.target.model !== candidate.target.model idx <= cIdx || c.target.providerId !== candidate.target.providerId || c.target.model !== candidate.target.model
); );
@ -665,7 +688,7 @@ export class RevolverEngine {
const nextTier = !isLastTier ? sortedTiers[tIdx + 1] : null; const nextTier = !isLastTier ? sortedTiers[tIdx + 1] : null;
let nextAction = ''; let nextAction = '';
if (allPairsOnCooldown) { if (allPairsOnCooldown && !shouldFastFailTarget) {
if (!isLastCandidateInTier) { if (!isLastCandidateInTier) {
const nextCandidate = candidates[cIdx + 1]; const nextCandidate = candidates[cIdx + 1];
nextAction = `Emergency probe failed. Put back on cooldown. Revoking cooldown for next key-model pair in line (${nextCandidate.target.model} Key ${nextCandidate.keyIndex + 1})`; nextAction = `Emergency probe failed. Put back on cooldown. Revoking cooldown for next key-model pair in line (${nextCandidate.target.model} Key ${nextCandidate.keyIndex + 1})`;
@ -686,6 +709,14 @@ export class RevolverEngine {
} else { } else {
nextAction = `${isModelOverload ? 'Model overloaded (503)' : 'Target timeout'} — all tiers and candidates exhausted`; nextAction = `${isModelOverload ? 'Model overloaded (503)' : 'Target timeout'} — all tiers and candidates exhausted`;
} }
} else if (isModelOverload) {
if (!isLastCandidateInTier) {
nextAction = `Model overloaded (503) — retrying 1 more key for ${candidate.target.model} in Tier ${tier.tierIndex} before failing over`;
} else if (nextTier) {
nextAction = `Model overloaded (503) — Tier ${tier.tierIndex} exhausted. Cascading to Fallback Tier ${nextTier.tierIndex} (${nextTier.name || 'Tier ' + nextTier.tierIndex})`;
} else {
nextAction = 'Model overloaded (503) — all tiers and candidates exhausted';
}
} else { } else {
if (!isLastCandidateInTier) { if (!isLastCandidateInTier) {
nextAction = `Rotating to next key in Tier ${tier.tierIndex}`; nextAction = `Rotating to next key in Tier ${tier.tierIndex}`;
@ -1469,9 +1500,22 @@ export class RevolverEngine {
const sortedTiers = [...customModel.tiers].sort((a, b) => a.tierIndex - b.tierIndex); const sortedTiers = [...customModel.tiers].sort((a, b) => a.tierIndex - b.tierIndex);
let lastError: any = null; let lastError: any = null;
let hasAvailableCandidateAcrossTiers = false;
for (const t of sortedTiers) {
if (this.getCandidatesForTier(t, customModel.id, false, false).length > 0) {
hasAvailableCandidateAcrossTiers = true;
break;
}
}
const allPairsOnCooldown = this.areAllKeyModelPairsOnCooldown(customModel);
const allowProbes = !hasAvailableCandidateAcrossTiers || allPairsOnCooldown;
for (const tier of sortedTiers) { for (const tier of sortedTiers) {
const candidates = this.getCandidatesForTier(tier, customModel.id); let candidates = this.getCandidatesForTier(tier, customModel.id, allowProbes);
for (const candidate of candidates) { const targetOverloadAttempts = new Map<string, number>();
for (let cIdx = 0; cIdx < candidates.length; cIdx++) {
const candidate = candidates[cIdx];
const candidateStart = Date.now(); const candidateStart = Date.now();
try { try {
const testRequest: OpenAIChatRequest = { const testRequest: OpenAIChatRequest = {
@ -1519,8 +1563,28 @@ export class RevolverEngine {
const isOverload = modelCircuitBreaker.isModelOverloadOrUnavailable(err); const isOverload = modelCircuitBreaker.isModelOverloadOrUnavailable(err);
const isTimeout = this.isTimeoutError(err); const isTimeout = this.isTimeoutError(err);
const targetKey = `${candidate.target.providerId}:::${candidate.target.model}`;
let overloadAttempts = targetOverloadAttempts.get(targetKey) || 0;
if (isOverload) {
overloadAttempts++;
targetOverloadAttempts.set(targetKey, overloadAttempts);
}
const maxOverloadAttempts = Math.min(
config.maxTargetOverloadRetries + 1,
Math.max(1, candidate.provider.keys.length)
);
const hasReachedOverloadLimit = isOverload && overloadAttempts >= maxOverloadAttempts;
let tripResult = { tripped: false, cooldownSeconds: 0, reason: '' };
if (isOverload || isTimeout) { if (isOverload || isTimeout) {
modelCircuitBreaker.recordFailure(candidate.provider.id, candidate.target.model, err, isTimeout); tripResult = modelCircuitBreaker.recordFailure(
candidate.provider.id,
candidate.target.model,
err,
isTimeout,
candidate.provider.keys.length
);
} }
if (isRateLimit) { if (isRateLimit) {
@ -1533,6 +1597,12 @@ export class RevolverEngine {
incrementError: true incrementError: true
}); });
} }
if (hasReachedOverloadLimit || (isTimeout && config.maxTargetTimeoutRetries === 0) || tripResult.tripped) {
candidates = candidates.filter((c, idx) =>
idx <= cIdx || c.target.providerId !== candidate.target.providerId || c.target.model !== candidate.target.model
);
}
} }
} }
} }

View file

@ -6,7 +6,13 @@ import { configStore } from './configStore';
import { revolverEngine } from './revolverEngine'; import { revolverEngine } from './revolverEngine';
import { authenticateApiKey } from './auth'; import { authenticateApiKey } from './auth';
import adminRoutes from './adminRoutes'; import adminRoutes from './adminRoutes';
import { renderAdminHtml } from './adminView'; import {
renderModelsPage,
renderProvidersPage,
renderPlaygroundPage,
renderTelemetryPage,
renderLiveLogsPage
} from './adminView';
import { liveWatcher } from './liveWatcher'; import { liveWatcher } from './liveWatcher';
import { import {
OpenAIChatRequest, OpenAIChatRequest,
@ -18,10 +24,38 @@ const router = Router();
// Mount Admin API routes with authentication // Mount Admin API routes with authentication
router.use('/api/admin', authenticateApiKey, adminRoutes); router.use('/api/admin', authenticateApiKey, adminRoutes);
// Admin Web UI Console // Admin Web UI Console & Subpages
router.get('/admin', (req: Request, res: Response) => { router.get('/admin', (req: Request, res: Response) => {
res.redirect('/admin/models');
});
router.get('/admin/models', (req: Request, res: Response) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.send(renderAdminHtml()); res.send(renderModelsPage());
});
router.get('/admin/providers', (req: Request, res: Response) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.send(renderProvidersPage());
});
router.get('/admin/playground', (req: Request, res: Response) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.send(renderPlaygroundPage());
});
router.get('/admin/telemetry', (req: Request, res: Response) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.send(renderTelemetryPage());
});
router.get('/admin/live_logs', (req: Request, res: Response) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.send(renderLiveLogsPage());
});
router.get('/admin/live-logs', (req: Request, res: Response) => {
res.redirect('/admin/live_logs');
}); });
// POST /v1/chat/completions // POST /v1/chat/completions

View file

@ -117,16 +117,17 @@ async function runTests() {
try { try {
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
// TEST 1: Zero-Tolerance 503 Overload Fast-Failover // TEST 1: 1-Retry-Key (Max 2 Keys) 503 Overload Fast-Failover with 10 Keys
// Tier 0 has 3 keys for 'mock-overloaded-model'. // Tier 0 has 10 keys for 'mock-overloaded-model'.
// Tier 1 has 1 key for 'mock-healthy-tier1-model'. // Tier 1 has 1 key for 'mock-healthy-tier1-model'.
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
console.log('1. Testing Zero-Tolerance 503 Overload Fast-Failover...'); console.log('1. Testing 1-Retry-Key (Max 2 Keys) 503 Overload Fast-Failover across 10 Keys...');
const tenOverloadedKeys = Array.from({ length: 10 }, (_, i) => `key-overloaded-${i + 1}`);
const provOverloaded = configStore.saveProvider({ const provOverloaded = configStore.saveProvider({
name: 'Google AI Studio Mock (Overloaded)', name: 'Google AI Studio Mock (Overloaded 10 Keys)',
type: 'custom', type: 'custom',
baseUrl: upstreamBaseUrl, baseUrl: upstreamBaseUrl,
keys: ['key-overloaded-1', 'key-overloaded-2', 'key-overloaded-3'] keys: tenOverloadedKeys
}); });
const provHealthy = configStore.saveProvider({ const provHealthy = configStore.saveProvider({
@ -138,7 +139,7 @@ async function runTests() {
const testModelOverload = configStore.saveCustomModel({ const testModelOverload = configStore.saveCustomModel({
name: testModelOverloadName, name: testModelOverloadName,
description: 'Testing 503 zero-tolerance skip and fast-cascade', description: 'Testing 503 1-retry-key skip and fast-cascade',
tiers: [ tiers: [
{ {
tierIndex: 0, tierIndex: 0,
@ -170,25 +171,27 @@ async function runTests() {
const data1 = (await res1.json()) as any; const data1 = (await res1.json()) as any;
assert.strictEqual(data1.choices[0].message.content, 'Tier 1 fallback served instantly.'); assert.strictEqual(data1.choices[0].message.content, 'Tier 1 fallback served instantly.');
// Verify upstream only received 1 request for the overloaded model (NOT 3 keys!) // Verify upstream only received 2 requests for the overloaded model (Key 1 + 1 retry key = 2, NOT all 10 keys!)
assert.strictEqual(requestCount503, 1, 'Upstream should only be hit ONCE on 503 before cascading'); assert.strictEqual(requestCount503, 2, 'Upstream should only be hit TWICE (1 initial + 1 retry key) on 503 before cascading');
// Verify telemetry recorded the skip and nextAction // Verify telemetry recorded the retry, skip of remaining 8 keys, and nextAction
const recentJourneys = telemetryTracker.getRecentJourneys(5); const recentJourneys = telemetryTracker.getRecentJourneys(5);
const j1 = recentJourneys.find(j => j.requestedModel === testModelOverload.name); const j1 = recentJourneys.find(j => j.requestedModel === testModelOverload.name);
assert.ok(j1, 'Journey must be recorded'); assert.ok(j1, 'Journey must be recorded');
assert.strictEqual(j1.totalHops, 2, 'Should only have 2 hops: Hop 1 (503) -> Hop 2 (Tier 1 200 OK)'); assert.strictEqual(j1.totalHops, 3, 'Should have 3 hops: Hop 1 (503) -> Hop 2 (503 retry) -> Hop 3 (Tier 1 200 OK)');
assert.strictEqual(j1.finalStatus, 'success_fallback'); assert.strictEqual(j1.finalStatus, 'success_fallback');
assert.strictEqual(j1.steps[0].status, 'server_error'); assert.strictEqual(j1.steps[0].status, 'server_error');
assert.ok(j1.steps[0].nextAction?.includes('Model overloaded (503) — skipped 2 remaining key(s)')); assert.ok(j1.steps[0].nextAction?.includes('Model overloaded (503) — retrying 1 more key'));
assert.strictEqual(j1.steps[1].status, 'success'); assert.strictEqual(j1.steps[1].status, 'server_error');
assert.ok(j1.steps[1].nextAction?.includes('Model overloaded (503) — skipped 8 remaining key(s)'));
assert.strictEqual(j1.steps[2].status, 'success');
// Verify individual keys were NOT marked rate-limited (key quota preserved!) // Verify individual keys were NOT marked rate-limited (key quota preserved!)
const updatedProvOverloaded = configStore.getProviderById(provOverloaded.id)!; const updatedProvOverloaded = configStore.getProviderById(provOverloaded.id)!;
for (const k of updatedProvOverloaded.keys) { for (const k of updatedProvOverloaded.keys) {
assert.strictEqual(k.rateLimitedUntil, null, '503 must NEVER mark individual keys rate-limited'); assert.strictEqual(k.rateLimitedUntil, null, '503 must NEVER mark individual keys rate-limited');
} }
console.log(' ✓ Zero-tolerance 503 fast-failover skipped remaining keys and preserved key quota.'); console.log(' ✓ 503 fast-failover tried 1 retry key (2 total), skipped remaining 8 keys, and preserved key quota.');
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
// TEST 2: Circuit Breaker Bypasses Tier 0 Instantly on Subsequent Requests // TEST 2: Circuit Breaker Bypasses Tier 0 Instantly on Subsequent Requests
@ -211,8 +214,8 @@ async function runTests() {
const data2 = (await res2.json()) as any; const data2 = (await res2.json()) as any;
assert.strictEqual(data2.choices[0].message.content, 'Tier 1 fallback served instantly.'); assert.strictEqual(data2.choices[0].message.content, 'Tier 1 fallback served instantly.');
// Request 503 count should STILL be 1 (Tier 0 was bypassed with 0ms delay!) // Request 503 count should STILL be 2 (Tier 0 was bypassed with 0ms delay!)
assert.strictEqual(requestCount503, 1, 'Overloaded model must be bypassed completely while in cooldown'); assert.strictEqual(requestCount503, 2, 'Overloaded model must be bypassed completely while in cooldown');
assert.ok(req2Duration < 150, `Subsequent request should complete instantly without Tier 0 hops (took ${req2Duration}ms)`); assert.ok(req2Duration < 150, `Subsequent request should complete instantly without Tier 0 hops (took ${req2Duration}ms)`);
const j2 = telemetryTracker.getRecentJourneys(5)[0]; const j2 = telemetryTracker.getRecentJourneys(5)[0];

View file

@ -13,15 +13,34 @@ async function runIntegrationTests() {
const validKey = config.apiPassword!; const validKey = config.apiPassword!;
try { try {
// 1. GET /admin UI // 1. GET /admin UI & Subpages
console.log('1. Testing GET /admin page load...'); console.log('1. Testing GET /admin redirect and dedicated subpages...');
const adminRes = await fetch(`${baseUrl}/admin`); const adminRedirectRes = await fetch(`${baseUrl}/admin`, { redirect: 'manual' });
assert.strictEqual(adminRes.status, 200); assert.strictEqual(adminRedirectRes.status, 302, 'GET /admin should redirect to /admin/models');
const adminHtml = await adminRes.text(); assert.ok(adminRedirectRes.headers.get('location')?.endsWith('/admin/models'));
assert.ok(adminHtml.includes('GeminiRevolver — Admin Console'));
assert.ok(adminHtml.includes('Admin Access')); const subpages = [
assert.ok(adminHtml.includes('auth-gate-section')); { path: '/admin/models', marker: 'Configured Custom Models' },
console.log(' ✓ Admin UI served successfully with auth gate.'); { path: '/admin/providers', marker: 'API Providers & Key Pools' },
{ path: '/admin/playground', marker: 'Revolver Playground' },
{ path: '/admin/telemetry', marker: 'Live Provider &amp; Key Health' },
{ path: '/admin/live_logs', marker: 'Live Request Log Watcher' }
];
for (const sp of subpages) {
const spRes = await fetch(`${baseUrl}${sp.path}`);
assert.strictEqual(spRes.status, 200, `Subpage ${sp.path} should return 200`);
const spHtml = await spRes.text();
assert.ok(spHtml.includes('GeminiRevolver — Admin Console'), `${sp.path} should render Admin Console layout`);
assert.ok(spHtml.includes('auth-gate-section'), `${sp.path} should include auth gate`);
assert.ok(spHtml.includes(sp.marker), `${sp.path} should include page marker '${sp.marker}'`);
}
// Verify Live Logs inspector tabs do NOT have the .tab-btn class collision
const liveLogsHtml = await (await fetch(`${baseUrl}/admin/live_logs`)).text();
assert.ok(liveLogsHtml.includes('class="insp-tab-btn active" data-insp-tab="insp-input"'), 'Inspector tabs must use isolated .insp-tab-btn class');
assert.ok(!liveLogsHtml.includes('tab-btn active insp-tab-btn'), 'Inspector tabs must not collide with .tab-btn');
console.log(' ✓ Admin root redirect and all 5 subpages (/admin/models, /admin/providers, /admin/playground, /admin/telemetry, /admin/live_logs) verified.');
// 2. Auth tests on /api/admin/verify // 2. Auth tests on /api/admin/verify
console.log('\n2. Testing /api/admin/verify authentication...'); console.log('\n2. Testing /api/admin/verify authentication...');

View file

@ -114,7 +114,7 @@ async function runTests() {
name: 'Emergency Provider Tier 0', name: 'Emergency Provider Tier 0',
type: 'custom', type: 'custom',
baseUrl: upstreamBaseUrl, baseUrl: upstreamBaseUrl,
keys: ['key-t0-1', 'key-t0-2'] keys: ['key-t0-1', 'key-t0-2', 'key-t0-3', 'key-t0-4', 'key-t0-5']
}); });
const pT1 = configStore.saveProvider({ const pT1 = configStore.saveProvider({
@ -146,8 +146,9 @@ async function runTests() {
modelCircuitBreaker.tripCooldown(pT1.id, 'mock-t1-model', 'Simulated 503 outage'); modelCircuitBreaker.tripCooldown(pT1.id, 'mock-t1-model', 'Simulated 503 outage');
// Also mark keys rate-limited // Also mark keys rate-limited
configStore.updateKeyStats(pT0.id, 'key-t0-1', { rateLimitedUntil: Date.now() + 60000 }); for (const k of pT0.keys) {
configStore.updateKeyStats(pT0.id, 'key-t0-2', { rateLimitedUntil: Date.now() + 60000 }); configStore.updateKeyStats(pT0.id, k.key, { rateLimitedUntil: Date.now() + 60000 });
}
configStore.updateKeyStats(pT1.id, 'key-t1-1', { rateLimitedUntil: Date.now() + 60000 }); configStore.updateKeyStats(pT1.id, 'key-t1-1', { rateLimitedUntil: Date.now() + 60000 });
// Verify all key-model pairs are detected as on cooldown // Verify all key-model pairs are detected as on cooldown
@ -174,11 +175,11 @@ async function runTests() {
const data = (await response.json()) as any; const data = (await response.json()) as any;
assert.strictEqual(data.choices[0].message.content, 'Emergency probe saved the request!'); assert.strictEqual(data.choices[0].message.content, 'Emergency probe saved the request!');
// Verify candidates were attempted sequentially: Candidate 1 -> Candidate 2 -> Candidate 3 // Verify candidates were attempted sequentially, skipping keys 3..5 after 2nd 503: Candidate 1 -> Candidate 2 -> Candidate 3 (Tier 1)
assert.strictEqual(candidateAttempts.length, 3); assert.strictEqual(candidateAttempts.length, 3, 'Should only try 2 keys on Tier 0 before skipping remaining 3 keys and failing over to Tier 1');
assert.strictEqual(candidateAttempts[0], 'mock-t0-model:key-t0-1', 'Candidate 1 must be attempted first with revoked cooldown'); assert.strictEqual(candidateAttempts[0], 'mock-t0-model:key-t0-1', 'Candidate 1 must be attempted first with revoked cooldown');
assert.strictEqual(candidateAttempts[1], 'mock-t0-model:key-t0-2', 'Candidate 2 must be attempted next with revoked cooldown'); assert.strictEqual(candidateAttempts[1], 'mock-t0-model:key-t0-2', 'Candidate 2 (1 retry key) must be attempted next with revoked cooldown');
assert.strictEqual(candidateAttempts[2], 'mock-t1-model:key-t1-1', 'Candidate 3 must be attempted next and succeed'); assert.strictEqual(candidateAttempts[2], 'mock-t1-model:key-t1-1', 'Candidate 3 in Tier 1 must be attempted next (skipping keys 3..5 of Tier 0) and succeed');
// Verify Candidate 1 and Candidate 2 were put back on cooldown upon failure // Verify Candidate 1 and Candidate 2 were put back on cooldown upon failure
assert.strictEqual(modelCircuitBreaker.isTargetInCooldown(pT0.id, 'mock-t0-model'), true, 'Tier 0 target must be back in cooldown after failing'); assert.strictEqual(modelCircuitBreaker.isTargetInCooldown(pT0.id, 'mock-t0-model'), true, 'Tier 0 target must be back in cooldown after failing');