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:
Wha1eChai
2026-01-04 08:32:36 +08:00
parent d03c79cc39
commit 85f7d3bae7
34 changed files with 4330 additions and 23 deletions

View File

@@ -0,0 +1,217 @@
/**
* Frontend Test Suite - Accounts Page
* Tests the account manager component functionality
*
* Run: node tests/test-frontend-accounts.cjs
*/
const http = require('http');
const BASE_URL = 'http://localhost:8090';
function request(path, options = {}) {
return new Promise((resolve, reject) => {
const url = new URL(path, BASE_URL);
const req = http.request(url, {
method: options.method || 'GET',
headers: {
'Content-Type': 'application/json',
...options.headers
}
}, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
resolve({ status: res.statusCode, data, headers: res.headers });
});
});
req.on('error', reject);
if (options.body) req.write(JSON.stringify(options.body));
req.end();
});
}
const tests = [
{
name: 'Accounts view loads successfully',
async run() {
const res = await request('/views/accounts.html');
if (res.status !== 200) {
throw new Error(`Expected 200, got ${res.status}`);
}
if (!res.data.includes('x-data="accountManager"')) {
throw new Error('AccountManager component not found');
}
return 'Accounts HTML loads with component';
}
},
{
name: 'Accounts API endpoint exists',
async run() {
const res = await request('/api/accounts');
if (res.status !== 200) {
throw new Error(`Expected 200, got ${res.status}`);
}
const data = JSON.parse(res.data);
if (!data.accounts || !Array.isArray(data.accounts)) {
throw new Error('accounts array not found in response');
}
if (!data.summary) {
throw new Error('summary object not found in response');
}
return `API returns ${data.accounts.length} accounts`;
}
},
{
name: 'Accounts view has table with required columns',
async run() {
const res = await request('/views/accounts.html');
const columns = ['enabled', 'identity', 'projectId', 'health', 'operations'];
const missing = columns.filter(col => !res.data.includes(col));
if (missing.length > 0) {
throw new Error(`Missing columns: ${missing.join(', ')}`);
}
return 'All table columns present';
}
},
{
name: 'Accounts view has toggle switch',
async run() {
const res = await request('/views/accounts.html');
if (!res.data.includes('toggleAccount')) {
throw new Error('Toggle account function not found');
}
if (!res.data.includes('acc.enabled')) {
throw new Error('Enabled state binding not found');
}
return 'Account toggle switch present';
}
},
{
name: 'Accounts view has refresh button',
async run() {
const res = await request('/views/accounts.html');
if (!res.data.includes('refreshAccount')) {
throw new Error('Refresh account function not found');
}
return 'Refresh button present';
}
},
{
name: 'Accounts view has delete button',
async run() {
const res = await request('/views/accounts.html');
if (!res.data.includes('deleteAccount')) {
throw new Error('Delete account function not found');
}
return 'Delete button present';
}
},
{
name: 'Accounts view has fix/re-auth button',
async run() {
const res = await request('/views/accounts.html');
if (!res.data.includes('fixAccount')) {
throw new Error('Fix account function not found');
}
return 'Fix/re-auth button present';
}
},
{
name: 'Accounts view has Add Node button',
async run() {
const res = await request('/views/accounts.html');
if (!res.data.includes('addNode') && !res.data.includes('add_account_modal')) {
throw new Error('Add account button not found');
}
return 'Add Node button present';
}
},
{
name: 'Account toggle API works',
async run() {
// First get an account
const accountsRes = await request('/api/accounts');
const accounts = JSON.parse(accountsRes.data).accounts;
if (accounts.length === 0) {
return 'Skipped: No accounts to test';
}
const email = accounts[0].email;
const currentEnabled = accounts[0].isInvalid !== true;
// Toggle the account (this is a real API call, be careful)
const toggleRes = await request(`/api/accounts/${encodeURIComponent(email)}/toggle`, {
method: 'POST',
body: { enabled: !currentEnabled }
});
if (toggleRes.status !== 200) {
throw new Error(`Toggle failed with status ${toggleRes.status}`);
}
// Toggle back to original state
await request(`/api/accounts/${encodeURIComponent(email)}/toggle`, {
method: 'POST',
body: { enabled: currentEnabled }
});
return `Toggle API works for ${email.split('@')[0]}`;
}
},
{
name: 'Account refresh API works',
async run() {
const accountsRes = await request('/api/accounts');
const accounts = JSON.parse(accountsRes.data).accounts;
if (accounts.length === 0) {
return 'Skipped: No accounts to test';
}
const email = accounts[0].email;
const refreshRes = await request(`/api/accounts/${encodeURIComponent(email)}/refresh`, {
method: 'POST'
});
if (refreshRes.status !== 200) {
throw new Error(`Refresh failed with status ${refreshRes.status}`);
}
return `Refresh API works for ${email.split('@')[0]}`;
}
}
];
async function runTests() {
console.log('🧪 Accounts Frontend Tests\n');
console.log('='.repeat(50));
let passed = 0;
let failed = 0;
for (const test of tests) {
try {
const result = await test.run();
console.log(`${test.name}`);
console.log(` ${result}\n`);
passed++;
} catch (error) {
console.log(`${test.name}`);
console.log(` Error: ${error.message}\n`);
failed++;
}
}
console.log('='.repeat(50));
console.log(`Results: ${passed} passed, ${failed} failed`);
process.exit(failed > 0 ? 1 : 0);
}
runTests().catch(err => {
console.error('Test runner failed:', err);
process.exit(1);
});