feat: Add Web UI for account and quota management
## Summary Add an optional Web UI for managing accounts and monitoring quotas. WebUI is implemented as a modular plugin with minimal changes to server.js (only 5 lines added). ## New Features - Dashboard: Real-time model quota visualization with Chart.js - Accounts: OAuth-based account management (add/enable/disable/refresh/remove) - Logs: Live server log streaming via SSE with search and level filtering - Settings: System configuration with 4 tabs - Interface: Language (EN/zh_CN), polling interval, log buffer size, display options - Claude CLI: Proxy connection config, model selection, alias overrides (~/.claude.json) - Models: Model visibility and ordering management - Server Info: Runtime info and account config reload ## Technical Changes - Add src/webui/index.js as modular plugin (all WebUI routes encapsulated) - Add src/config.js for centralized configuration (~/.config/antigravity-proxy/config.json) - Add authMiddleware for optional password protection (WEBUI_PASSWORD env var) - Enhance logger with EventEmitter for SSE log streaming - Make constants configurable via config.json - Merge with main v1.2.6 (model fallback, cross-model thinking) - server.js changes: only 5 lines added to import and mount WebUI module ## Bug Fixes - Fix Alpine.js $watch error in settings-store.js (not supported in store init) - Fix "OK" label to "SUCCESS" in logs filter - Add saveSettings() calls to settings toggles for proper persistence - Improve Claude CLI config robustness (handle empty/invalid JSON files) - Add safety check for empty config.env in claude-config component - Improve config.example.json instructions with clear Windows/macOS/Linux paths ## New Files - src/webui/index.js - WebUI module with all API routes - public/ - Complete Web UI frontend (Alpine.js + TailwindCSS + DaisyUI) - src/config.js - Configuration management - src/utils/claude-config.js - Claude CLI settings helper - tests/frontend/ - Frontend test suite ## API Endpoints Added - GET/POST /api/config - Server configuration - GET/POST /api/claude/config - Claude CLI configuration - POST /api/models/config - Model alias/hidden settings - GET /api/accounts - Account list with status - POST /api/accounts/:email/toggle - Enable/disable account - POST /api/accounts/:email/refresh - Refresh account token - DELETE /api/accounts/:email - Remove account - GET /api/logs - Log history - GET /api/logs/stream - Live log streaming (SSE) - GET /api/auth/url - OAuth URL generation - GET /oauth/callback - OAuth callback handler ## Backward Compatibility - Default port remains 8080 - All existing CLI/API functionality unchanged - WebUI is entirely optional - Can be disabled by removing mountWebUI() call
This commit is contained in:
106
public/js/app-init.js
Normal file
106
public/js/app-init.js
Normal file
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* App Initialization (Non-module version)
|
||||
* This must load BEFORE Alpine initializes
|
||||
*/
|
||||
|
||||
document.addEventListener('alpine:init', () => {
|
||||
console.log('Registering app component...');
|
||||
|
||||
// Main App Controller
|
||||
Alpine.data('app', () => ({
|
||||
// Re-expose store properties for easier access in navbar
|
||||
get connectionStatus() {
|
||||
return Alpine.store('data').connectionStatus;
|
||||
},
|
||||
get loading() {
|
||||
return Alpine.store('data').loading;
|
||||
},
|
||||
|
||||
init() {
|
||||
console.log('App component initializing...');
|
||||
|
||||
// Theme setup
|
||||
document.documentElement.setAttribute('data-theme', 'black');
|
||||
document.documentElement.classList.add('dark');
|
||||
|
||||
// Chart Defaults
|
||||
if (typeof Chart !== 'undefined') {
|
||||
Chart.defaults.color = '#71717a';
|
||||
Chart.defaults.borderColor = '#27272a';
|
||||
Chart.defaults.font.family = '"JetBrains Mono", monospace';
|
||||
}
|
||||
|
||||
// Start Data Polling
|
||||
this.startAutoRefresh();
|
||||
document.addEventListener('refresh-interval-changed', () => this.startAutoRefresh());
|
||||
|
||||
// Initial Fetch
|
||||
Alpine.store('data').fetchData();
|
||||
},
|
||||
|
||||
refreshTimer: null,
|
||||
|
||||
fetchData() {
|
||||
Alpine.store('data').fetchData();
|
||||
},
|
||||
|
||||
startAutoRefresh() {
|
||||
if (this.refreshTimer) clearInterval(this.refreshTimer);
|
||||
const interval = parseInt(Alpine.store('settings').refreshInterval);
|
||||
if (interval > 0) {
|
||||
this.refreshTimer = setInterval(() => Alpine.store('data').fetchData(), interval * 1000);
|
||||
}
|
||||
},
|
||||
|
||||
// Translation helper for modal (not in a component scope)
|
||||
t(key) {
|
||||
return Alpine.store('global').t(key);
|
||||
},
|
||||
|
||||
// Add account handler for modal
|
||||
async addAccountWeb(reAuthEmail = null) {
|
||||
const password = Alpine.store('global').webuiPassword;
|
||||
try {
|
||||
const urlPath = reAuthEmail
|
||||
? `/api/auth/url?email=${encodeURIComponent(reAuthEmail)}`
|
||||
: '/api/auth/url';
|
||||
|
||||
const { response, newPassword } = await window.utils.request(urlPath, {}, password);
|
||||
if (newPassword) Alpine.store('global').webuiPassword = newPassword;
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.status === 'ok') {
|
||||
const width = 600;
|
||||
const height = 700;
|
||||
const left = (screen.width - width) / 2;
|
||||
const top = (screen.height - height) / 2;
|
||||
|
||||
window.open(
|
||||
data.url,
|
||||
'google_oauth',
|
||||
`width=${width},height=${height},top=${top},left=${left},scrollbars=yes`
|
||||
);
|
||||
|
||||
const messageHandler = (event) => {
|
||||
if (event.data?.type === 'oauth-success') {
|
||||
const action = reAuthEmail ? 're-authenticated' : 'added';
|
||||
Alpine.store('global').showToast(`Account ${event.data.email} ${action} successfully`, 'success');
|
||||
Alpine.store('data').fetchData();
|
||||
|
||||
const modal = document.getElementById('add_account_modal');
|
||||
if (modal) modal.close();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('message', messageHandler);
|
||||
setTimeout(() => window.removeEventListener('message', messageHandler), 300000);
|
||||
} else {
|
||||
Alpine.store('global').showToast(data.error || 'Failed to get auth URL', 'error');
|
||||
}
|
||||
} catch (e) {
|
||||
Alpine.store('global').showToast('Failed to start OAuth flow: ' + e.message, 'error');
|
||||
}
|
||||
}
|
||||
}));
|
||||
});
|
||||
104
public/js/components/account-manager.js
Normal file
104
public/js/components/account-manager.js
Normal file
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* Account Manager Component
|
||||
* Registers itself to window.Components for Alpine.js to consume
|
||||
*/
|
||||
window.Components = window.Components || {};
|
||||
|
||||
window.Components.accountManager = () => ({
|
||||
async refreshAccount(email) {
|
||||
Alpine.store('global').showToast(`Refreshing ${email}...`, 'info');
|
||||
const password = Alpine.store('global').webuiPassword;
|
||||
try {
|
||||
const { response, newPassword } = await window.utils.request(`/api/accounts/${encodeURIComponent(email)}/refresh`, { method: 'POST' }, password);
|
||||
if (newPassword) Alpine.store('global').webuiPassword = newPassword;
|
||||
|
||||
const data = await response.json();
|
||||
if (data.status === 'ok') {
|
||||
Alpine.store('global').showToast(`Refreshed ${email}`, 'success');
|
||||
Alpine.store('data').fetchData();
|
||||
} else {
|
||||
Alpine.store('global').showToast(data.error || 'Refresh failed', 'error');
|
||||
}
|
||||
} catch (e) {
|
||||
Alpine.store('global').showToast('Refresh failed: ' + e.message, 'error');
|
||||
}
|
||||
},
|
||||
|
||||
async toggleAccount(email, enabled) {
|
||||
const password = Alpine.store('global').webuiPassword;
|
||||
try {
|
||||
const { response, newPassword } = await window.utils.request(`/api/accounts/${encodeURIComponent(email)}/toggle`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ enabled })
|
||||
}, password);
|
||||
if (newPassword) Alpine.store('global').webuiPassword = newPassword;
|
||||
|
||||
const data = await response.json();
|
||||
if (data.status === 'ok') {
|
||||
Alpine.store('global').showToast(`Account ${email} ${enabled ? 'enabled' : 'disabled'}`, 'success');
|
||||
Alpine.store('data').fetchData();
|
||||
} else {
|
||||
Alpine.store('global').showToast(data.error || 'Toggle failed', 'error');
|
||||
}
|
||||
} catch (e) {
|
||||
Alpine.store('global').showToast('Toggle failed: ' + e.message, 'error');
|
||||
}
|
||||
},
|
||||
|
||||
async fixAccount(email) {
|
||||
Alpine.store('global').showToast(`Re-authenticating ${email}...`, 'info');
|
||||
const password = Alpine.store('global').webuiPassword;
|
||||
try {
|
||||
const urlPath = `/api/auth/url?email=${encodeURIComponent(email)}`;
|
||||
const { response, newPassword } = await window.utils.request(urlPath, {}, password);
|
||||
if (newPassword) Alpine.store('global').webuiPassword = newPassword;
|
||||
|
||||
const data = await response.json();
|
||||
if (data.status === 'ok') {
|
||||
window.open(data.url, 'google_oauth', 'width=600,height=700,scrollbars=yes');
|
||||
} else {
|
||||
Alpine.store('global').showToast(data.error || 'Failed to get auth URL', 'error');
|
||||
}
|
||||
} catch (e) {
|
||||
Alpine.store('global').showToast('Failed: ' + e.message, 'error');
|
||||
}
|
||||
},
|
||||
|
||||
async deleteAccount(email) {
|
||||
if (!confirm(Alpine.store('global').t('confirmDelete'))) return;
|
||||
const password = Alpine.store('global').webuiPassword;
|
||||
try {
|
||||
const { response, newPassword } = await window.utils.request(`/api/accounts/${encodeURIComponent(email)}`, { method: 'DELETE' }, password);
|
||||
if (newPassword) Alpine.store('global').webuiPassword = newPassword;
|
||||
|
||||
const data = await response.json();
|
||||
if (data.status === 'ok') {
|
||||
Alpine.store('global').showToast(`Deleted ${email}`, 'success');
|
||||
Alpine.store('data').fetchData();
|
||||
} else {
|
||||
Alpine.store('global').showToast(data.error || 'Delete failed', 'error');
|
||||
}
|
||||
} catch (e) {
|
||||
Alpine.store('global').showToast('Delete failed: ' + e.message, 'error');
|
||||
}
|
||||
},
|
||||
|
||||
async reloadAccounts() {
|
||||
const password = Alpine.store('global').webuiPassword;
|
||||
try {
|
||||
const { response, newPassword } = await window.utils.request('/api/accounts/reload', { method: 'POST' }, password);
|
||||
if (newPassword) Alpine.store('global').webuiPassword = newPassword;
|
||||
|
||||
const data = await response.json();
|
||||
if (data.status === 'ok') {
|
||||
Alpine.store('global').showToast('Accounts reloaded', 'success');
|
||||
Alpine.store('data').fetchData();
|
||||
} else {
|
||||
Alpine.store('global').showToast(data.error || 'Reload failed', 'error');
|
||||
}
|
||||
} catch (e) {
|
||||
Alpine.store('global').showToast('Reload failed: ' + e.message, 'error');
|
||||
}
|
||||
}
|
||||
});
|
||||
54
public/js/components/claude-config.js
Normal file
54
public/js/components/claude-config.js
Normal file
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* Claude Config Component
|
||||
* Registers itself to window.Components for Alpine.js to consume
|
||||
*/
|
||||
window.Components = window.Components || {};
|
||||
|
||||
window.Components.claudeConfig = () => ({
|
||||
config: { env: {} },
|
||||
models: [],
|
||||
loading: false,
|
||||
|
||||
init() {
|
||||
this.fetchConfig();
|
||||
this.$watch('$store.data.models', (val) => {
|
||||
this.models = val || [];
|
||||
});
|
||||
this.models = Alpine.store('data').models || [];
|
||||
},
|
||||
|
||||
async fetchConfig() {
|
||||
const password = Alpine.store('global').webuiPassword;
|
||||
try {
|
||||
const { response, newPassword } = await window.utils.request('/api/claude/config', {}, password);
|
||||
if (newPassword) Alpine.store('global').webuiPassword = newPassword;
|
||||
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
const data = await response.json();
|
||||
this.config = data.config || {};
|
||||
if (!this.config.env) this.config.env = {};
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch Claude config:', e);
|
||||
}
|
||||
},
|
||||
|
||||
async saveClaudeConfig() {
|
||||
this.loading = true;
|
||||
const password = Alpine.store('global').webuiPassword;
|
||||
try {
|
||||
const { response, newPassword } = await window.utils.request('/api/claude/config', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(this.config)
|
||||
}, password);
|
||||
if (newPassword) Alpine.store('global').webuiPassword = newPassword;
|
||||
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
Alpine.store('global').showToast('Claude config saved!', 'success');
|
||||
} catch (e) {
|
||||
Alpine.store('global').showToast('Failed to save config: ' + e.message, 'error');
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
122
public/js/components/dashboard.js
Normal file
122
public/js/components/dashboard.js
Normal file
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* Dashboard Component
|
||||
* Registers itself to window.Components for Alpine.js to consume
|
||||
*/
|
||||
window.Components = window.Components || {};
|
||||
|
||||
window.Components.dashboard = () => ({
|
||||
stats: { total: 0, active: 0, limited: 0, overallHealth: 0 },
|
||||
charts: { quotaDistribution: null },
|
||||
|
||||
init() {
|
||||
// Update stats when dashboard becomes active
|
||||
this.$watch('$store.global.activeTab', (val) => {
|
||||
if (val === 'dashboard') {
|
||||
this.$nextTick(() => {
|
||||
this.updateStats();
|
||||
this.updateCharts();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Watch for data changes
|
||||
this.$watch('$store.data.accounts', () => {
|
||||
if (this.$store.global.activeTab === 'dashboard') {
|
||||
this.updateStats();
|
||||
this.$nextTick(() => this.updateCharts());
|
||||
}
|
||||
});
|
||||
|
||||
// Initial update if already on dashboard
|
||||
if (this.$store.global.activeTab === 'dashboard') {
|
||||
this.$nextTick(() => {
|
||||
this.updateStats();
|
||||
this.updateCharts();
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
updateStats() {
|
||||
const accounts = Alpine.store('data').accounts;
|
||||
let active = 0, limited = 0;
|
||||
accounts.forEach(acc => {
|
||||
if (acc.status === 'ok') {
|
||||
const hasQuota = Object.values(acc.limits || {}).some(l => l && l.remainingFraction > 0);
|
||||
if (hasQuota) active++; else limited++;
|
||||
} else {
|
||||
limited++;
|
||||
}
|
||||
});
|
||||
this.stats = { total: accounts.length, active, limited };
|
||||
},
|
||||
|
||||
updateCharts() {
|
||||
const ctx = document.getElementById('quotaChart');
|
||||
if (!ctx || typeof Chart === 'undefined') return;
|
||||
|
||||
if (this.charts.quotaDistribution) {
|
||||
this.charts.quotaDistribution.destroy();
|
||||
}
|
||||
|
||||
const rows = Alpine.store('data').quotaRows;
|
||||
const familyStats = { claude: { sum: 0, count: 0 }, gemini: { sum: 0, count: 0 }, other: { sum: 0, count: 0 } };
|
||||
|
||||
// Calculate overall system health
|
||||
let totalHealthSum = 0;
|
||||
let totalModelCount = 0;
|
||||
|
||||
rows.forEach(row => {
|
||||
const f = familyStats[row.family] ? row.family : 'other';
|
||||
// Use avgQuota if available (new logic), fallback to minQuota (old logic compatibility)
|
||||
const quota = row.avgQuota !== undefined ? row.avgQuota : row.minQuota;
|
||||
|
||||
familyStats[f].sum += quota;
|
||||
familyStats[f].count++;
|
||||
|
||||
totalHealthSum += quota;
|
||||
totalModelCount++;
|
||||
});
|
||||
|
||||
this.stats.overallHealth = totalModelCount > 0 ? Math.round(totalHealthSum / totalModelCount) : 0;
|
||||
|
||||
const labels = ['Claude', 'Gemini', 'Other'];
|
||||
const data = [
|
||||
familyStats.claude.count ? Math.round(familyStats.claude.sum / familyStats.claude.count) : 0,
|
||||
familyStats.gemini.count ? Math.round(familyStats.gemini.sum / familyStats.gemini.count) : 0,
|
||||
familyStats.other.count ? Math.round(familyStats.other.sum / familyStats.other.count) : 0,
|
||||
];
|
||||
|
||||
this.charts.quotaDistribution = new Chart(ctx, {
|
||||
type: 'doughnut',
|
||||
data: {
|
||||
labels: labels,
|
||||
datasets: [{
|
||||
data: data,
|
||||
backgroundColor: ['#a855f7', '#22c55e', '#52525b'],
|
||||
borderColor: '#09090b', // Matches bg-space-900 roughly
|
||||
borderWidth: 2,
|
||||
hoverOffset: 0,
|
||||
borderRadius: 2
|
||||
}]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
cutout: '85%', // Thinner ring
|
||||
plugins: {
|
||||
legend: {
|
||||
display: false // Hide default legend
|
||||
},
|
||||
tooltip: {
|
||||
enabled: false // Disable tooltip for cleaner look, or style it? Let's keep it simple.
|
||||
},
|
||||
title: { display: false }
|
||||
},
|
||||
animation: {
|
||||
animateScale: true,
|
||||
animateRotate: true
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
87
public/js/components/logs-viewer.js
Normal file
87
public/js/components/logs-viewer.js
Normal file
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* Logs Viewer Component
|
||||
* Registers itself to window.Components for Alpine.js to consume
|
||||
*/
|
||||
window.Components = window.Components || {};
|
||||
|
||||
window.Components.logsViewer = () => ({
|
||||
logs: [],
|
||||
isAutoScroll: true,
|
||||
eventSource: null,
|
||||
searchQuery: '',
|
||||
filters: {
|
||||
INFO: true,
|
||||
WARN: true,
|
||||
ERROR: true,
|
||||
SUCCESS: true,
|
||||
DEBUG: false
|
||||
},
|
||||
|
||||
get filteredLogs() {
|
||||
const query = this.searchQuery.toLowerCase();
|
||||
return this.logs.filter(log => {
|
||||
// Level Filter
|
||||
if (!this.filters[log.level]) return false;
|
||||
|
||||
// Search Filter
|
||||
if (query && !log.message.toLowerCase().includes(query)) return false;
|
||||
|
||||
return true;
|
||||
});
|
||||
},
|
||||
|
||||
init() {
|
||||
this.startLogStream();
|
||||
|
||||
this.$watch('isAutoScroll', (val) => {
|
||||
if (val) this.scrollToBottom();
|
||||
});
|
||||
|
||||
// Watch filters to maintain auto-scroll if enabled
|
||||
this.$watch('searchQuery', () => { if(this.isAutoScroll) this.$nextTick(() => this.scrollToBottom()) });
|
||||
this.$watch('filters', () => { if(this.isAutoScroll) this.$nextTick(() => this.scrollToBottom()) });
|
||||
},
|
||||
|
||||
startLogStream() {
|
||||
if (this.eventSource) this.eventSource.close();
|
||||
|
||||
const password = Alpine.store('global').webuiPassword;
|
||||
const url = password
|
||||
? `/api/logs/stream?history=true&password=${encodeURIComponent(password)}`
|
||||
: '/api/logs/stream?history=true';
|
||||
|
||||
this.eventSource = new EventSource(url);
|
||||
this.eventSource.onmessage = (event) => {
|
||||
try {
|
||||
const log = JSON.parse(event.data);
|
||||
this.logs.push(log);
|
||||
|
||||
// Limit log buffer
|
||||
const limit = Alpine.store('settings')?.logLimit || 2000;
|
||||
if (this.logs.length > limit) {
|
||||
this.logs = this.logs.slice(-limit);
|
||||
}
|
||||
|
||||
if (this.isAutoScroll) {
|
||||
this.$nextTick(() => this.scrollToBottom());
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Log parse error:', e);
|
||||
}
|
||||
};
|
||||
|
||||
this.eventSource.onerror = () => {
|
||||
console.warn('Log stream disconnected, reconnecting...');
|
||||
setTimeout(() => this.startLogStream(), 3000);
|
||||
};
|
||||
},
|
||||
|
||||
scrollToBottom() {
|
||||
const container = document.getElementById('logs-container');
|
||||
if (container) container.scrollTop = container.scrollHeight;
|
||||
},
|
||||
|
||||
clearLogs() {
|
||||
this.logs = [];
|
||||
}
|
||||
});
|
||||
169
public/js/data-store.js
Normal file
169
public/js/data-store.js
Normal file
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* Data Store
|
||||
* Holds Accounts, Models, and Computed Quota Rows
|
||||
* Shared between Dashboard and AccountManager
|
||||
*/
|
||||
|
||||
// utils is loaded globally as window.utils in utils.js
|
||||
|
||||
document.addEventListener('alpine:init', () => {
|
||||
Alpine.store('data', {
|
||||
accounts: [],
|
||||
models: [], // Source of truth
|
||||
modelConfig: {}, // Model metadata (hidden, pinned, alias)
|
||||
quotaRows: [], // Filtered view
|
||||
loading: false,
|
||||
connectionStatus: 'connecting',
|
||||
lastUpdated: '-',
|
||||
|
||||
// Filters state
|
||||
filters: {
|
||||
account: 'all',
|
||||
family: 'all',
|
||||
search: ''
|
||||
},
|
||||
|
||||
// Settings for calculation
|
||||
// We need to access global settings? Or duplicate?
|
||||
// Let's assume settings are passed or in another store.
|
||||
// For simplicity, let's keep relevant filters here.
|
||||
|
||||
init() {
|
||||
// Watch filters to recompute
|
||||
// Alpine stores don't have $watch automatically unless inside a component?
|
||||
// We can manually call compute when filters change.
|
||||
},
|
||||
|
||||
async fetchData() {
|
||||
this.loading = true;
|
||||
try {
|
||||
// Get password from global store
|
||||
const password = Alpine.store('global').webuiPassword;
|
||||
const { response, newPassword } = await window.utils.request('/account-limits', {}, password);
|
||||
|
||||
if (newPassword) Alpine.store('global').webuiPassword = newPassword;
|
||||
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
|
||||
const data = await response.json();
|
||||
this.accounts = data.accounts || [];
|
||||
if (data.models && data.models.length > 0) {
|
||||
this.models = data.models;
|
||||
}
|
||||
this.modelConfig = data.modelConfig || {};
|
||||
|
||||
this.computeQuotaRows();
|
||||
|
||||
this.connectionStatus = 'connected';
|
||||
this.lastUpdated = new Date().toLocaleTimeString();
|
||||
} catch (error) {
|
||||
console.error('Fetch error:', error);
|
||||
this.connectionStatus = 'disconnected';
|
||||
Alpine.store('global').showToast('Connection Lost', 'error');
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
computeQuotaRows() {
|
||||
const models = this.models || [];
|
||||
const rows = [];
|
||||
const showExhausted = Alpine.store('settings')?.showExhausted ?? true; // Need settings store
|
||||
// Temporary debug flag or settings flag to show hidden models
|
||||
const showHidden = Alpine.store('settings')?.showHiddenModels ?? false;
|
||||
|
||||
models.forEach(modelId => {
|
||||
// Config
|
||||
const config = this.modelConfig[modelId] || {};
|
||||
const family = this.getModelFamily(modelId);
|
||||
|
||||
// Smart Visibility Logic:
|
||||
// 1. If explicit config exists, use it.
|
||||
// 2. If no config, default 'unknown' families to HIDDEN to prevent clutter.
|
||||
// 3. Known families (Claude/Gemini) default to VISIBLE.
|
||||
let isHidden = config.hidden;
|
||||
if (isHidden === undefined) {
|
||||
isHidden = (family === 'other' || family === 'unknown');
|
||||
}
|
||||
|
||||
// Skip hidden models unless "Show Hidden" is enabled
|
||||
if (isHidden && !showHidden) return;
|
||||
|
||||
// Filters
|
||||
if (this.filters.family !== 'all' && this.filters.family !== family) return;
|
||||
if (this.filters.search) {
|
||||
const searchLower = this.filters.search.toLowerCase();
|
||||
const aliasMatch = config.alias && config.alias.toLowerCase().includes(searchLower);
|
||||
const idMatch = modelId.toLowerCase().includes(searchLower);
|
||||
if (!aliasMatch && !idMatch) return;
|
||||
}
|
||||
|
||||
// Data Collection
|
||||
const quotaInfo = [];
|
||||
let minQuota = 100;
|
||||
let totalQuotaSum = 0;
|
||||
let validAccountCount = 0;
|
||||
let minResetTime = null;
|
||||
|
||||
this.accounts.forEach(acc => {
|
||||
if (this.filters.account !== 'all' && acc.email !== this.filters.account) return;
|
||||
|
||||
const limit = acc.limits?.[modelId];
|
||||
if (!limit) return;
|
||||
|
||||
const pct = limit.remainingFraction !== null ? Math.round(limit.remainingFraction * 100) : 0;
|
||||
minQuota = Math.min(minQuota, pct);
|
||||
|
||||
// Accumulate for average
|
||||
totalQuotaSum += pct;
|
||||
validAccountCount++;
|
||||
|
||||
if (limit.resetTime && (!minResetTime || new Date(limit.resetTime) < new Date(minResetTime))) {
|
||||
minResetTime = limit.resetTime;
|
||||
}
|
||||
|
||||
quotaInfo.push({
|
||||
email: acc.email.split('@')[0],
|
||||
fullEmail: acc.email,
|
||||
pct: pct,
|
||||
resetTime: limit.resetTime
|
||||
});
|
||||
});
|
||||
|
||||
if (quotaInfo.length === 0) return;
|
||||
const avgQuota = validAccountCount > 0 ? Math.round(totalQuotaSum / validAccountCount) : 0;
|
||||
|
||||
if (!showExhausted && minQuota === 0) return;
|
||||
|
||||
rows.push({
|
||||
modelId,
|
||||
displayName: config.alias || modelId, // Use alias if available
|
||||
family,
|
||||
minQuota,
|
||||
avgQuota, // Added Average Quota
|
||||
minResetTime,
|
||||
resetIn: minResetTime ? window.utils.formatTimeUntil(minResetTime) : '-',
|
||||
quotaInfo,
|
||||
pinned: !!config.pinned,
|
||||
hidden: !!isHidden // Use computed visibility
|
||||
});
|
||||
});
|
||||
|
||||
// Sort: Pinned first, then by avgQuota (descending)
|
||||
this.quotaRows = rows.sort((a, b) => {
|
||||
if (a.pinned !== b.pinned) return a.pinned ? -1 : 1;
|
||||
return b.avgQuota - a.avgQuota;
|
||||
});
|
||||
|
||||
// Trigger Dashboard Update if active
|
||||
// Ideally dashboard watches this store.
|
||||
},
|
||||
|
||||
getModelFamily(modelId) {
|
||||
const lower = modelId.toLowerCase();
|
||||
if (lower.includes('claude')) return 'claude';
|
||||
if (lower.includes('gemini')) return 'gemini';
|
||||
return 'other';
|
||||
}
|
||||
});
|
||||
});
|
||||
57
public/js/settings-store.js
Normal file
57
public/js/settings-store.js
Normal file
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* Settings Store
|
||||
*/
|
||||
document.addEventListener('alpine:init', () => {
|
||||
Alpine.store('settings', {
|
||||
refreshInterval: 60,
|
||||
logLimit: 2000,
|
||||
showExhausted: true,
|
||||
showHiddenModels: false, // New field
|
||||
compact: false,
|
||||
port: 8080, // Display only
|
||||
|
||||
init() {
|
||||
this.loadSettings();
|
||||
},
|
||||
|
||||
// Call this method when toggling settings in the UI
|
||||
toggle(key) {
|
||||
if (this.hasOwnProperty(key) && typeof this[key] === 'boolean') {
|
||||
this[key] = !this[key];
|
||||
this.saveSettings(true);
|
||||
}
|
||||
},
|
||||
|
||||
loadSettings() {
|
||||
const saved = localStorage.getItem('antigravity_settings');
|
||||
if (saved) {
|
||||
const parsed = JSON.parse(saved);
|
||||
Object.keys(parsed).forEach(k => {
|
||||
// Only load keys that exist in our default state (safety)
|
||||
if (this.hasOwnProperty(k)) this[k] = parsed[k];
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
saveSettings(silent = false) {
|
||||
const toSave = {
|
||||
refreshInterval: this.refreshInterval,
|
||||
logLimit: this.logLimit,
|
||||
showExhausted: this.showExhausted,
|
||||
showHiddenModels: this.showHiddenModels,
|
||||
compact: this.compact
|
||||
};
|
||||
localStorage.setItem('antigravity_settings', JSON.stringify(toSave));
|
||||
|
||||
if (!silent) {
|
||||
Alpine.store('global').showToast('Configuration Saved', 'success');
|
||||
}
|
||||
|
||||
// Trigger updates
|
||||
document.dispatchEvent(new CustomEvent('refresh-interval-changed'));
|
||||
if (Alpine.store('data')) {
|
||||
Alpine.store('data').computeQuotaRows();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
222
public/js/store.js
Normal file
222
public/js/store.js
Normal file
@@ -0,0 +1,222 @@
|
||||
/**
|
||||
* Global Store for Antigravity Console
|
||||
* Handles Translations, Toasts, and Shared Config
|
||||
*/
|
||||
|
||||
document.addEventListener('alpine:init', () => {
|
||||
Alpine.store('global', {
|
||||
// App State
|
||||
version: '1.0.0',
|
||||
activeTab: 'dashboard',
|
||||
webuiPassword: localStorage.getItem('antigravity_webui_password') || '',
|
||||
|
||||
// i18n
|
||||
lang: localStorage.getItem('app_lang') || 'en',
|
||||
translations: {
|
||||
en: {
|
||||
dashboard: "Dashboard",
|
||||
accounts: "Accounts",
|
||||
logs: "Logs",
|
||||
settings: "Settings",
|
||||
online: "ONLINE",
|
||||
offline: "OFFLINE",
|
||||
totalAccounts: "TOTAL ACCOUNTS",
|
||||
active: "ACTIVE",
|
||||
operational: "Operational",
|
||||
rateLimited: "RATE LIMITED",
|
||||
cooldown: "Cooldown",
|
||||
searchPlaceholder: "Search models...",
|
||||
allAccounts: "All Accounts",
|
||||
stat: "STAT",
|
||||
modelIdentity: "MODEL IDENTITY",
|
||||
globalQuota: "GLOBAL QUOTA",
|
||||
nextReset: "NEXT RESET",
|
||||
distribution: "ACCOUNT DISTRIBUTION",
|
||||
systemConfig: "System Configuration",
|
||||
language: "Language",
|
||||
pollingInterval: "Polling Interval",
|
||||
logBufferSize: "Log Buffer Size",
|
||||
showExhausted: "Show Exhausted Models",
|
||||
showExhaustedDesc: "Display models even if they have 0% remaining quota.",
|
||||
compactMode: "Compact Mode",
|
||||
compactModeDesc: "Reduce padding in tables for higher information density.",
|
||||
saveChanges: "Save Changes",
|
||||
autoScroll: "Auto-scroll",
|
||||
clearLogs: "Clear Logs",
|
||||
accessCredentials: "Access Credentials",
|
||||
manageTokens: "Manage OAuth tokens and session states",
|
||||
addNode: "Add Node",
|
||||
status: "STATUS",
|
||||
enabled: "ENABLED",
|
||||
health: "HEALTH",
|
||||
identity: "IDENTITY (EMAIL)",
|
||||
projectId: "PROJECT ID",
|
||||
sessionState: "SESSION STATE",
|
||||
operations: "OPERATIONS",
|
||||
delete: "Delete",
|
||||
confirmDelete: "Are you sure you want to remove this account?",
|
||||
connectGoogle: "Connect Google Account",
|
||||
manualReload: "Reload from Disk",
|
||||
// Tabs
|
||||
tabInterface: "Interface",
|
||||
tabClaude: "Claude CLI",
|
||||
tabModels: "Models",
|
||||
tabServer: "Server Info",
|
||||
// Dashboard
|
||||
registeredNodes: "Registered Nodes",
|
||||
noSignal: "NO SIGNAL DETECTED",
|
||||
establishingUplink: "ESTABLISHING UPLINK...",
|
||||
// Settings - Models
|
||||
modelsDesc: "Manage visibility and ordering of models in the dashboard.",
|
||||
showHidden: "Show Hidden Models",
|
||||
modelId: "Model ID",
|
||||
alias: "Alias",
|
||||
actions: "Actions",
|
||||
pinToTop: "Pin to top",
|
||||
toggleVisibility: "Toggle Visibility",
|
||||
noModels: "NO MODELS DETECTED",
|
||||
// Settings - Claude
|
||||
proxyConnection: "Proxy Connection",
|
||||
modelSelection: "Model Selection",
|
||||
aliasOverrides: "ALIAS OVERRIDES",
|
||||
opusAlias: "Opus Alias",
|
||||
sonnetAlias: "Sonnet Alias",
|
||||
haikuAlias: "Haiku Alias",
|
||||
claudeSettingsAlert: "Settings below directly modify ~/.claude/settings.json. Restart Claude CLI to apply.",
|
||||
writeToConfig: "Write to Config",
|
||||
// Settings - Server
|
||||
port: "Port",
|
||||
uiVersion: "UI Version",
|
||||
debugMode: "Debug Mode",
|
||||
environment: "Environment",
|
||||
serverReadOnly: "Server settings are read-only. Modify config.json or .env and restart the server to change.",
|
||||
dangerZone: "Danger Zone / Advanced",
|
||||
reloadConfigTitle: "Reload Account Config",
|
||||
reloadConfigDesc: "Force reload accounts.json from disk",
|
||||
reload: "Reload",
|
||||
// Config Specific
|
||||
primaryModel: "Primary Model",
|
||||
subAgentModel: "Sub-agent Model",
|
||||
advancedOverrides: "Default Model Overrides",
|
||||
opusModel: "Opus Model",
|
||||
sonnetModel: "Sonnet Model",
|
||||
haikuModel: "Haiku Model",
|
||||
authToken: "Auth Token",
|
||||
saveConfig: "Save to ~/.claude/settings.json",
|
||||
envVar: "Env",
|
||||
},
|
||||
zh: {
|
||||
dashboard: "仪表盘",
|
||||
accounts: "账号管理",
|
||||
logs: "运行日志",
|
||||
settings: "系统设置",
|
||||
online: "在线",
|
||||
offline: "离线",
|
||||
totalAccounts: "账号总数",
|
||||
active: "活跃状态",
|
||||
operational: "运行中",
|
||||
rateLimited: "受限状态",
|
||||
cooldown: "冷却中",
|
||||
searchPlaceholder: "搜索模型...",
|
||||
allAccounts: "所有账号",
|
||||
stat: "状态",
|
||||
modelIdentity: "模型标识",
|
||||
globalQuota: "全局配额",
|
||||
nextReset: "重置时间",
|
||||
distribution: "账号分布",
|
||||
systemConfig: "系统配置",
|
||||
language: "语言设置",
|
||||
pollingInterval: "数据轮询间隔",
|
||||
logBufferSize: "日志缓冲大小",
|
||||
showExhausted: "显示耗尽模型",
|
||||
showExhaustedDesc: "即使配额为 0% 也显示模型。",
|
||||
compactMode: "紧凑模式",
|
||||
compactModeDesc: "减少表格间距以显示更多信息。",
|
||||
saveChanges: "保存更改",
|
||||
autoScroll: "自动滚动",
|
||||
clearLogs: "清除日志",
|
||||
accessCredentials: "访问凭证",
|
||||
manageTokens: "管理 OAuth 令牌和会话状态",
|
||||
addNode: "添加节点",
|
||||
status: "状态",
|
||||
enabled: "启用",
|
||||
health: "健康度",
|
||||
identity: "身份 (邮箱)",
|
||||
projectId: "项目 ID",
|
||||
sessionState: "会话状态",
|
||||
operations: "操作",
|
||||
delete: "删除",
|
||||
confirmDelete: "确定要移除此账号吗?",
|
||||
connectGoogle: "连接 Google 账号",
|
||||
manualReload: "重新加载配置",
|
||||
// Tabs
|
||||
tabInterface: "界面设置",
|
||||
tabClaude: "Claude CLI",
|
||||
tabModels: "模型管理",
|
||||
tabServer: "服务器信息",
|
||||
// Dashboard
|
||||
registeredNodes: "已注册节点",
|
||||
noSignal: "无信号连接",
|
||||
establishingUplink: "正在建立上行链路...",
|
||||
// Settings - Models
|
||||
modelsDesc: "管理仪表盘中模型的可见性和排序。",
|
||||
showHidden: "显示隐藏模型",
|
||||
modelId: "模型 ID",
|
||||
alias: "别名",
|
||||
actions: "操作",
|
||||
pinToTop: "置顶",
|
||||
toggleVisibility: "切换可见性",
|
||||
noModels: "未检测到模型",
|
||||
// Settings - Claude
|
||||
proxyConnection: "代理连接",
|
||||
modelSelection: "模型选择",
|
||||
aliasOverrides: "别名覆盖",
|
||||
opusAlias: "Opus 别名",
|
||||
sonnetAlias: "Sonnet 别名",
|
||||
haikuAlias: "Haiku 别名",
|
||||
claudeSettingsAlert: "以下设置直接修改 ~/.claude/settings.json。重启 Claude CLI 生效。",
|
||||
writeToConfig: "写入配置",
|
||||
// Settings - Server
|
||||
port: "端口",
|
||||
uiVersion: "UI 版本",
|
||||
debugMode: "调试模式",
|
||||
environment: "运行环境",
|
||||
serverReadOnly: "服务器设置只读。修改 config.json 或 .env 并重启服务器以生效。",
|
||||
dangerZone: "危险区域 / 高级",
|
||||
reloadConfigTitle: "重载账号配置",
|
||||
reloadConfigDesc: "强制从磁盘重新读取 accounts.json",
|
||||
reload: "重载",
|
||||
// Config Specific
|
||||
primaryModel: "主模型",
|
||||
subAgentModel: "子代理模型",
|
||||
advancedOverrides: "默认模型覆盖 (高级)",
|
||||
opusModel: "Opus 模型",
|
||||
sonnetModel: "Sonnet 模型",
|
||||
haikuModel: "Haiku 模型",
|
||||
authToken: "认证令牌",
|
||||
saveConfig: "保存到 ~/.claude/settings.json",
|
||||
envVar: "环境变量",
|
||||
}
|
||||
},
|
||||
|
||||
// Toast Messages
|
||||
toast: null,
|
||||
|
||||
t(key) {
|
||||
return this.translations[this.lang][key] || key;
|
||||
},
|
||||
|
||||
setLang(l) {
|
||||
this.lang = l;
|
||||
localStorage.setItem('app_lang', l);
|
||||
},
|
||||
|
||||
showToast(message, type = 'info') {
|
||||
const id = Date.now();
|
||||
this.toast = { message, type, id };
|
||||
setTimeout(() => {
|
||||
if (this.toast && this.toast.id === id) this.toast = null;
|
||||
}, 3000);
|
||||
}
|
||||
});
|
||||
});
|
||||
41
public/js/utils.js
Normal file
41
public/js/utils.js
Normal file
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Utility functions for Antigravity Console
|
||||
*/
|
||||
|
||||
window.utils = {
|
||||
// Shared Request Wrapper
|
||||
async request(url, options = {}, webuiPassword = '') {
|
||||
options.headers = options.headers || {};
|
||||
if (webuiPassword) {
|
||||
options.headers['x-webui-password'] = webuiPassword;
|
||||
}
|
||||
|
||||
let response = await fetch(url, options);
|
||||
|
||||
if (response.status === 401) {
|
||||
const password = prompt('Enter Web UI Password:');
|
||||
if (password) {
|
||||
// Return new password so caller can update state
|
||||
// This implies we need a way to propagate the new password back
|
||||
// For simplicity in this functional utility, we might need a callback or state access
|
||||
// But generally utils shouldn't probably depend on global state directly if possible
|
||||
// let's stick to the current logic but wrapped
|
||||
localStorage.setItem('antigravity_webui_password', password);
|
||||
options.headers['x-webui-password'] = password;
|
||||
response = await fetch(url, options);
|
||||
return { response, newPassword: password };
|
||||
}
|
||||
}
|
||||
|
||||
return { response, newPassword: null };
|
||||
},
|
||||
|
||||
formatTimeUntil(isoTime) {
|
||||
const diff = new Date(isoTime) - new Date();
|
||||
if (diff <= 0) return 'READY';
|
||||
const mins = Math.floor(diff / 60000);
|
||||
const hrs = Math.floor(mins / 60);
|
||||
if (hrs > 0) return `${hrs}H ${mins % 60}M`;
|
||||
return `${mins}M`;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user