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:
217
tests/frontend/test-frontend-accounts.cjs
Normal file
217
tests/frontend/test-frontend-accounts.cjs
Normal 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);
|
||||
});
|
||||
85
tests/frontend/test-frontend-all.cjs
Normal file
85
tests/frontend/test-frontend-all.cjs
Normal file
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* Frontend Test Runner
|
||||
* Runs all frontend test suites
|
||||
*
|
||||
* Run: node tests/frontend/test-frontend-all.cjs
|
||||
*/
|
||||
|
||||
const { execSync, spawn } = require('child_process');
|
||||
const path = require('path');
|
||||
|
||||
const testFiles = [
|
||||
'test-frontend-dashboard.cjs',
|
||||
'test-frontend-logs.cjs',
|
||||
'test-frontend-accounts.cjs',
|
||||
'test-frontend-settings.cjs'
|
||||
];
|
||||
|
||||
async function runTests() {
|
||||
console.log('🚀 Running All Frontend Tests\n');
|
||||
console.log('═'.repeat(60));
|
||||
|
||||
let totalPassed = 0;
|
||||
let totalFailed = 0;
|
||||
const results = [];
|
||||
|
||||
for (const testFile of testFiles) {
|
||||
const testPath = path.join(__dirname, testFile);
|
||||
console.log(`\n📋 Running: ${testFile}`);
|
||||
console.log('─'.repeat(60));
|
||||
|
||||
try {
|
||||
const output = execSync(`node "${testPath}"`, {
|
||||
encoding: 'utf8',
|
||||
stdio: ['pipe', 'pipe', 'pipe']
|
||||
});
|
||||
console.log(output);
|
||||
|
||||
// Parse results from output
|
||||
const match = output.match(/Results: (\d+) passed, (\d+) failed/);
|
||||
if (match) {
|
||||
const passed = parseInt(match[1]);
|
||||
const failed = parseInt(match[2]);
|
||||
totalPassed += passed;
|
||||
totalFailed += failed;
|
||||
results.push({ file: testFile, passed, failed, status: 'completed' });
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(error.stdout || '');
|
||||
console.log(error.stderr || '');
|
||||
|
||||
// Try to parse results even on failure
|
||||
const output = error.stdout || '';
|
||||
const match = output.match(/Results: (\d+) passed, (\d+) failed/);
|
||||
if (match) {
|
||||
const passed = parseInt(match[1]);
|
||||
const failed = parseInt(match[2]);
|
||||
totalPassed += passed;
|
||||
totalFailed += failed;
|
||||
results.push({ file: testFile, passed, failed, status: 'completed with errors' });
|
||||
} else {
|
||||
results.push({ file: testFile, passed: 0, failed: 1, status: 'crashed' });
|
||||
totalFailed++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log('\n' + '═'.repeat(60));
|
||||
console.log('📊 SUMMARY\n');
|
||||
|
||||
for (const result of results) {
|
||||
const icon = result.failed === 0 ? '✅' : '❌';
|
||||
console.log(`${icon} ${result.file}: ${result.passed} passed, ${result.failed} failed (${result.status})`);
|
||||
}
|
||||
|
||||
console.log('\n' + '─'.repeat(60));
|
||||
console.log(`Total: ${totalPassed} passed, ${totalFailed} failed`);
|
||||
console.log('═'.repeat(60));
|
||||
|
||||
process.exit(totalFailed > 0 ? 1 : 0);
|
||||
}
|
||||
|
||||
runTests().catch(err => {
|
||||
console.error('Test runner crashed:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
160
tests/frontend/test-frontend-dashboard.cjs
Normal file
160
tests/frontend/test-frontend-dashboard.cjs
Normal file
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* Frontend Test Suite - Dashboard Page
|
||||
* Tests the dashboard component functionality
|
||||
*
|
||||
* Run: node tests/test-frontend-dashboard.cjs
|
||||
*/
|
||||
|
||||
const http = require('http');
|
||||
|
||||
const BASE_URL = 'http://localhost:8090';
|
||||
|
||||
// Helper to make HTTP requests
|
||||
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: 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();
|
||||
});
|
||||
}
|
||||
|
||||
// Test cases
|
||||
const tests = [
|
||||
{
|
||||
name: 'Dashboard view loads successfully',
|
||||
async run() {
|
||||
const res = await request('/views/dashboard.html');
|
||||
if (res.status !== 200) {
|
||||
throw new Error(`Expected 200, got ${res.status}`);
|
||||
}
|
||||
if (!res.data.includes('x-data="dashboard"')) {
|
||||
throw new Error('Dashboard component not found in HTML');
|
||||
}
|
||||
if (!res.data.includes('quotaChart')) {
|
||||
throw new Error('Quota chart canvas not found');
|
||||
}
|
||||
return 'Dashboard HTML loads with component and chart';
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'Account limits API returns data',
|
||||
async run() {
|
||||
const res = await request('/account-limits');
|
||||
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.models || !Array.isArray(data.models)) {
|
||||
throw new Error('models array not found in response');
|
||||
}
|
||||
return `API returns ${data.accounts.length} accounts and ${data.models.length} models`;
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'Dashboard has stats grid elements',
|
||||
async run() {
|
||||
const res = await request('/views/dashboard.html');
|
||||
const html = res.data;
|
||||
|
||||
const requiredElements = [
|
||||
'totalAccounts', // Total accounts stat
|
||||
'stats.total', // Total stat binding
|
||||
'stats.active', // Active stat binding
|
||||
'stats.limited', // Limited stat binding
|
||||
'quotaChart' // Chart canvas
|
||||
];
|
||||
|
||||
const missing = requiredElements.filter(el => !html.includes(el));
|
||||
if (missing.length > 0) {
|
||||
throw new Error(`Missing elements: ${missing.join(', ')}`);
|
||||
}
|
||||
return 'All required dashboard elements present';
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'Dashboard has filter controls',
|
||||
async run() {
|
||||
const res = await request('/views/dashboard.html');
|
||||
const html = res.data;
|
||||
|
||||
const filterElements = [
|
||||
'filters.account', // Account filter
|
||||
'filters.family', // Model family filter
|
||||
'filters.search', // Search input
|
||||
'computeQuotaRows' // Filter action
|
||||
];
|
||||
|
||||
const missing = filterElements.filter(el => !html.includes(el));
|
||||
if (missing.length > 0) {
|
||||
throw new Error(`Missing filter elements: ${missing.join(', ')}`);
|
||||
}
|
||||
return 'All filter controls present';
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'Dashboard table has required columns',
|
||||
async run() {
|
||||
const res = await request('/views/dashboard.html');
|
||||
const html = res.data;
|
||||
|
||||
const columns = [
|
||||
'modelIdentity', // Model name column
|
||||
'globalQuota', // Quota column
|
||||
'nextReset', // Reset time column
|
||||
'distribution' // Account distribution column
|
||||
];
|
||||
|
||||
const missing = columns.filter(col => !html.includes(col));
|
||||
if (missing.length > 0) {
|
||||
throw new Error(`Missing table columns: ${missing.join(', ')}`);
|
||||
}
|
||||
return 'All table columns present';
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
// Run tests
|
||||
async function runTests() {
|
||||
console.log('🧪 Dashboard 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);
|
||||
});
|
||||
163
tests/frontend/test-frontend-logs.cjs
Normal file
163
tests/frontend/test-frontend-logs.cjs
Normal file
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* Frontend Test Suite - Logs Page
|
||||
* Tests the logs viewer component functionality
|
||||
*
|
||||
* Run: node tests/test-frontend-logs.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: 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: 'Logs view loads successfully',
|
||||
async run() {
|
||||
const res = await request('/views/logs.html');
|
||||
if (res.status !== 200) {
|
||||
throw new Error(`Expected 200, got ${res.status}`);
|
||||
}
|
||||
if (!res.data.includes('x-data="logsViewer"')) {
|
||||
throw new Error('LogsViewer component not found');
|
||||
}
|
||||
return 'Logs HTML loads with component';
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'Logs API endpoint exists',
|
||||
async run() {
|
||||
const res = await request('/api/logs');
|
||||
if (res.status !== 200) {
|
||||
throw new Error(`Expected 200, got ${res.status}`);
|
||||
}
|
||||
const data = JSON.parse(res.data);
|
||||
if (!data.logs || !Array.isArray(data.logs)) {
|
||||
throw new Error('logs array not found in response');
|
||||
}
|
||||
return `API returns ${data.logs.length} log entries`;
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'Logs SSE stream endpoint exists',
|
||||
async run() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const url = new URL('/api/logs/stream', BASE_URL);
|
||||
const req = http.request(url, (res) => {
|
||||
if (res.statusCode !== 200) {
|
||||
reject(new Error(`Expected 200, got ${res.statusCode}`));
|
||||
return;
|
||||
}
|
||||
if (res.headers['content-type'] !== 'text/event-stream') {
|
||||
reject(new Error(`Expected text/event-stream, got ${res.headers['content-type']}`));
|
||||
return;
|
||||
}
|
||||
req.destroy(); // Close connection
|
||||
resolve('SSE stream endpoint responds correctly');
|
||||
});
|
||||
req.on('error', reject);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'Logs view has auto-scroll toggle',
|
||||
async run() {
|
||||
const res = await request('/views/logs.html');
|
||||
if (!res.data.includes('isAutoScroll')) {
|
||||
throw new Error('Auto-scroll toggle not found');
|
||||
}
|
||||
if (!res.data.includes('autoScroll')) {
|
||||
throw new Error('Auto-scroll translation key not found');
|
||||
}
|
||||
return 'Auto-scroll toggle present';
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'Logs view has clear logs button',
|
||||
async run() {
|
||||
const res = await request('/views/logs.html');
|
||||
if (!res.data.includes('clearLogs')) {
|
||||
throw new Error('Clear logs function not found');
|
||||
}
|
||||
return 'Clear logs button present';
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'Logs view has log container',
|
||||
async run() {
|
||||
const res = await request('/views/logs.html');
|
||||
if (!res.data.includes('logs-container')) {
|
||||
throw new Error('Logs container element not found');
|
||||
}
|
||||
if (!res.data.includes('x-for="(log, idx) in filteredLogs"')) {
|
||||
throw new Error('Log iteration template not found');
|
||||
}
|
||||
return 'Log container and template present';
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'Logs view shows log levels with colors',
|
||||
async run() {
|
||||
const res = await request('/views/logs.html');
|
||||
const levels = ['INFO', 'WARN', 'ERROR', 'SUCCESS', 'DEBUG'];
|
||||
const colors = ['blue-400', 'yellow-400', 'red-500', 'neon-green', 'purple-400'];
|
||||
|
||||
for (const level of levels) {
|
||||
if (!res.data.includes(`'${level}'`)) {
|
||||
throw new Error(`Log level ${level} styling not found`);
|
||||
}
|
||||
}
|
||||
return 'All log levels have color styling';
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
async function runTests() {
|
||||
console.log('🧪 Logs 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);
|
||||
});
|
||||
348
tests/frontend/test-frontend-settings.cjs
Normal file
348
tests/frontend/test-frontend-settings.cjs
Normal file
@@ -0,0 +1,348 @@
|
||||
/**
|
||||
* Frontend Test Suite - Settings Page
|
||||
* Tests the settings and Claude configuration components
|
||||
*
|
||||
* Run: node tests/test-frontend-settings.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 = [
|
||||
// ==================== VIEW TESTS ====================
|
||||
{
|
||||
name: 'Settings view loads successfully',
|
||||
async run() {
|
||||
const res = await request('/views/settings.html');
|
||||
if (res.status !== 200) {
|
||||
throw new Error(`Expected 200, got ${res.status}`);
|
||||
}
|
||||
return 'Settings HTML loads successfully';
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'Settings view has UI preferences section',
|
||||
async run() {
|
||||
const res = await request('/views/settings.html');
|
||||
const html = res.data;
|
||||
|
||||
const uiElements = [
|
||||
'language', // Language selector
|
||||
'refreshInterval', // Polling interval
|
||||
'logLimit', // Log buffer size
|
||||
'showExhausted', // Show exhausted models toggle
|
||||
'compact' // Compact mode toggle
|
||||
];
|
||||
|
||||
const missing = uiElements.filter(el => !html.includes(el));
|
||||
if (missing.length > 0) {
|
||||
throw new Error(`Missing UI elements: ${missing.join(', ')}`);
|
||||
}
|
||||
return 'All UI preference elements present';
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'Settings view has Claude CLI config section',
|
||||
async run() {
|
||||
const res = await request('/views/settings.html');
|
||||
const html = res.data;
|
||||
|
||||
if (!html.includes('x-data="claudeConfig"')) {
|
||||
throw new Error('ClaudeConfig component not found');
|
||||
}
|
||||
|
||||
const claudeElements = [
|
||||
'ANTHROPIC_BASE_URL',
|
||||
'ANTHROPIC_MODEL',
|
||||
'ANTHROPIC_AUTH_TOKEN'
|
||||
];
|
||||
|
||||
const missing = claudeElements.filter(el => !html.includes(el));
|
||||
if (missing.length > 0) {
|
||||
throw new Error(`Missing Claude config elements: ${missing.join(', ')}`);
|
||||
}
|
||||
return 'Claude CLI config section present';
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'Settings view has save buttons',
|
||||
async run() {
|
||||
const res = await request('/views/settings.html');
|
||||
const html = res.data;
|
||||
|
||||
if (!html.includes('saveSettings')) {
|
||||
throw new Error('Settings save function not found');
|
||||
}
|
||||
if (!html.includes('saveClaudeConfig')) {
|
||||
throw new Error('Claude config save function not found');
|
||||
}
|
||||
return 'Save buttons present for both sections';
|
||||
}
|
||||
},
|
||||
|
||||
// ==================== API TESTS ====================
|
||||
{
|
||||
name: 'Server config API GET works',
|
||||
async run() {
|
||||
const res = await request('/api/config');
|
||||
if (res.status !== 200) {
|
||||
throw new Error(`Expected 200, got ${res.status}`);
|
||||
}
|
||||
const data = JSON.parse(res.data);
|
||||
if (!data.config) {
|
||||
throw new Error('config object not found in response');
|
||||
}
|
||||
return `Config API returns: debug=${data.config.debug}, logLevel=${data.config.logLevel}`;
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'Claude config API GET works',
|
||||
async run() {
|
||||
const res = await request('/api/claude/config');
|
||||
if (res.status !== 200) {
|
||||
throw new Error(`Expected 200, got ${res.status}`);
|
||||
}
|
||||
const data = JSON.parse(res.data);
|
||||
if (!data.config) {
|
||||
throw new Error('config object not found in response');
|
||||
}
|
||||
if (!data.path) {
|
||||
throw new Error('config path not found in response');
|
||||
}
|
||||
return `Claude config loaded from: ${data.path}`;
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'Claude config has env section',
|
||||
async run() {
|
||||
const res = await request('/api/claude/config');
|
||||
const data = JSON.parse(res.data);
|
||||
|
||||
if (!data.config.env) {
|
||||
throw new Error('env section not found in config');
|
||||
}
|
||||
|
||||
const envKeys = Object.keys(data.config.env);
|
||||
return `Config has ${envKeys.length} env vars: ${envKeys.slice(0, 3).join(', ')}${envKeys.length > 3 ? '...' : ''}`;
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'Claude config API POST works (read-back test)',
|
||||
async run() {
|
||||
// First, read current config
|
||||
const getRes = await request('/api/claude/config');
|
||||
const originalConfig = JSON.parse(getRes.data).config;
|
||||
|
||||
// POST the same config back (safe operation)
|
||||
const postRes = await request('/api/claude/config', {
|
||||
method: 'POST',
|
||||
body: originalConfig
|
||||
});
|
||||
|
||||
if (postRes.status !== 200) {
|
||||
throw new Error(`POST failed with status ${postRes.status}`);
|
||||
}
|
||||
|
||||
const postData = JSON.parse(postRes.data);
|
||||
if (postData.status !== 'ok') {
|
||||
throw new Error(`POST returned error: ${postData.error}`);
|
||||
}
|
||||
|
||||
return 'Claude config POST API works (config preserved)';
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'Server config API POST validates input',
|
||||
async run() {
|
||||
// Test with invalid logLevel
|
||||
const res = await request('/api/config', {
|
||||
method: 'POST',
|
||||
body: { logLevel: 'invalid_level' }
|
||||
});
|
||||
|
||||
if (res.status === 200) {
|
||||
const data = JSON.parse(res.data);
|
||||
// Check if the invalid value was rejected
|
||||
if (data.updates && data.updates.logLevel === 'invalid_level') {
|
||||
throw new Error('Invalid logLevel was accepted');
|
||||
}
|
||||
}
|
||||
|
||||
return 'Config API properly validates logLevel input';
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'Server config accepts valid debug value',
|
||||
async run() {
|
||||
// Get current config
|
||||
const getRes = await request('/api/config');
|
||||
const currentDebug = JSON.parse(getRes.data).config.debug;
|
||||
|
||||
// Toggle debug
|
||||
const postRes = await request('/api/config', {
|
||||
method: 'POST',
|
||||
body: { debug: !currentDebug }
|
||||
});
|
||||
|
||||
if (postRes.status !== 200) {
|
||||
throw new Error(`POST failed with status ${postRes.status}`);
|
||||
}
|
||||
|
||||
// Restore original value
|
||||
await request('/api/config', {
|
||||
method: 'POST',
|
||||
body: { debug: currentDebug }
|
||||
});
|
||||
|
||||
return 'Config API accepts valid debug boolean';
|
||||
}
|
||||
},
|
||||
|
||||
// ==================== SETTINGS STORE TESTS ====================
|
||||
{
|
||||
name: 'Settings API returns server port',
|
||||
async run() {
|
||||
const res = await request('/api/settings');
|
||||
if (res.status !== 200) {
|
||||
throw new Error(`Expected 200, got ${res.status}`);
|
||||
}
|
||||
const data = JSON.parse(res.data);
|
||||
if (!data.settings || !data.settings.port) {
|
||||
throw new Error('port not found in settings');
|
||||
}
|
||||
return `Server port: ${data.settings.port}`;
|
||||
}
|
||||
},
|
||||
|
||||
// ==================== INTEGRATION TESTS ====================
|
||||
{
|
||||
name: 'All views are accessible',
|
||||
async run() {
|
||||
const views = ['dashboard', 'logs', 'accounts', 'settings'];
|
||||
const results = [];
|
||||
|
||||
for (const view of views) {
|
||||
const res = await request(`/views/${view}.html`);
|
||||
if (res.status !== 200) {
|
||||
throw new Error(`${view} view returned ${res.status}`);
|
||||
}
|
||||
results.push(`${view}: OK`);
|
||||
}
|
||||
|
||||
return results.join(', ');
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'All component JS files load',
|
||||
async run() {
|
||||
const components = [
|
||||
'js/components/dashboard.js',
|
||||
'js/components/account-manager.js',
|
||||
'js/components/claude-config.js',
|
||||
'js/components/logs-viewer.js'
|
||||
];
|
||||
|
||||
for (const comp of components) {
|
||||
const res = await request(`/${comp}`);
|
||||
if (res.status !== 200) {
|
||||
throw new Error(`${comp} returned ${res.status}`);
|
||||
}
|
||||
if (!res.data.includes('window.Components')) {
|
||||
throw new Error(`${comp} doesn't register to window.Components`);
|
||||
}
|
||||
}
|
||||
|
||||
return 'All component files load and register correctly';
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'All store JS files load',
|
||||
async run() {
|
||||
const stores = [
|
||||
'js/store.js',
|
||||
'js/data-store.js',
|
||||
'js/settings-store.js',
|
||||
'js/utils.js'
|
||||
];
|
||||
|
||||
for (const store of stores) {
|
||||
const res = await request(`/${store}`);
|
||||
if (res.status !== 200) {
|
||||
throw new Error(`${store} returned ${res.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
return 'All store files load correctly';
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'Main app.js loads',
|
||||
async run() {
|
||||
const res = await request('/app.js');
|
||||
if (res.status !== 200) {
|
||||
throw new Error(`app.js returned ${res.status}`);
|
||||
}
|
||||
if (!res.data.includes('alpine:init')) {
|
||||
throw new Error('app.js missing alpine:init listener');
|
||||
}
|
||||
if (!res.data.includes('load-view')) {
|
||||
throw new Error('app.js missing load-view directive');
|
||||
}
|
||||
return 'app.js loads with all required components';
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
async function runTests() {
|
||||
console.log('🧪 Settings 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);
|
||||
});
|
||||
Reference in New Issue
Block a user