Merge pull request #336 from kaitranntt/kai/feat/dashboard-ux-parity

feat(dashboard): implement full UX parity with edge case fixes
This commit is contained in:
Kai (Tam Nhu) Tran
2026-01-14 17:36:55 -05:00
committed by GitHub
10 changed files with 761 additions and 31 deletions
+4
View File
@@ -22,6 +22,7 @@ import copilotRoutes from './copilot-routes';
import miscRoutes from './misc-routes';
import cliproxyServerRoutes from './proxy-routes';
import authRoutes from './auth-routes';
import persistRoutes from './persist-routes';
// Create the main API router
export const apiRoutes = Router();
@@ -42,6 +43,9 @@ apiRoutes.use('/health', healthRoutes);
// ==================== Dashboard Auth ====================
apiRoutes.use('/auth', authRoutes);
// ==================== Persist (Backup Management) ====================
apiRoutes.use('/persist', persistRoutes);
// ==================== CLIProxy ====================
// Variants, auth, accounts, stats, status, models, error logs
apiRoutes.use('/cliproxy', variantRoutes);
+254
View File
@@ -0,0 +1,254 @@
/**
* Persist Routes - Backup management for ~/.claude/settings.json
*/
import { Router, Request, Response } from 'express';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
const router = Router();
interface BackupFile {
path: string;
timestamp: string;
date: Date;
}
/**
* Async mutex for restore operations - prevents race conditions
* Uses a Promise queue pattern for atomic lock acquisition
*/
class RestoreMutex {
private locked = false;
private queue: Array<() => void> = [];
async acquire(): Promise<boolean> {
if (this.locked) {
// Already locked - add to queue and wait
return new Promise((resolve) => {
this.queue.push(() => resolve(false)); // Return false = was queued, reject
});
}
this.locked = true;
return true;
}
release(): void {
const next = this.queue.shift();
if (next) {
next(); // Signal queued request to fail
} else {
this.locked = false;
}
}
}
const restoreMutex = new RestoreMutex();
/** Get Claude settings.json path */
function getClaudeSettingsPath(): string {
return path.join(os.homedir(), '.claude', 'settings.json');
}
/** Check if path is a symlink (security check) */
function isSymlink(filePath: string): boolean {
try {
const stats = fs.lstatSync(filePath);
return stats.isSymbolicLink();
} catch {
return false;
}
}
/** Get all backup files sorted by date (newest first) */
function getBackupFiles(): BackupFile[] {
const settingsPath = getClaudeSettingsPath();
const dir = path.dirname(settingsPath);
if (!fs.existsSync(dir)) {
return [];
}
const backupPattern = /^settings\.json\.backup\.(\d{8}_\d{6})$/;
const files = fs
.readdirSync(dir)
.filter((f) => backupPattern.test(f))
.map((f) => {
const match = f.match(backupPattern);
if (!match) return null;
const timestamp = match[1];
const year = parseInt(timestamp.slice(0, 4));
const month = parseInt(timestamp.slice(4, 6)) - 1;
const day = parseInt(timestamp.slice(6, 8));
const hour = parseInt(timestamp.slice(9, 11));
const min = parseInt(timestamp.slice(11, 13));
const sec = parseInt(timestamp.slice(13, 15));
return {
path: path.join(dir, f),
timestamp,
date: new Date(year, month, day, hour, min, sec),
};
})
.filter((f): f is BackupFile => f !== null)
.sort((a, b) => b.date.getTime() - a.date.getTime());
return files;
}
/**
* GET /api/persist/backups - List available backups
*/
router.get('/backups', (_req: Request, res: Response): void => {
try {
const backups = getBackupFiles();
res.json({
backups: backups.map((b, i) => ({
timestamp: b.timestamp,
date: b.date.toISOString(),
isLatest: i === 0,
})),
});
} catch (error) {
res.status(500).json({ error: (error as Error).message });
}
});
/**
* POST /api/persist/restore - Restore from a backup
* Body: { timestamp?: string } - If not provided, restores latest
*/
router.post('/restore', async (req: Request, res: Response): Promise<void> => {
// Atomic mutex acquisition - prevents race conditions
const acquired = await restoreMutex.acquire();
if (!acquired) {
res.status(409).json({ error: 'Restore already in progress' });
return;
}
try {
const { timestamp } = req.body;
const backups = getBackupFiles();
if (backups.length === 0) {
res.status(404).json({ error: 'No backups found' });
return;
}
// Find backup
let backup: BackupFile;
if (!timestamp) {
backup = backups[0]; // Latest
} else {
const found = backups.find((b) => b.timestamp === timestamp);
if (!found) {
res.status(404).json({ error: `Backup not found: ${timestamp}` });
return;
}
backup = found;
}
// Security: reject symlinks to prevent path traversal attacks
if (isSymlink(backup.path)) {
res.status(400).json({ error: 'Backup file is a symlink - refusing for security' });
return;
}
const settingsPath = getClaudeSettingsPath();
if (isSymlink(settingsPath)) {
res.status(400).json({ error: 'settings.json is a symlink - refusing for security' });
return;
}
// Read backup content securely using file descriptor to prevent TOCTOU
// Open with O_NOFOLLOW equivalent check then read atomically
let backupContent: string;
let fd: number | undefined;
try {
// Verify not symlink immediately before open
const stats = fs.lstatSync(backup.path);
if (stats.isSymbolicLink()) {
res
.status(400)
.json({ error: 'Backup became symlink during read - refusing for security' });
return;
}
// Open file descriptor for atomic read
fd = fs.openSync(backup.path, 'r');
const buffer = Buffer.alloc(stats.size);
fs.readSync(fd, buffer, 0, stats.size, 0);
backupContent = buffer.toString('utf8');
const parsed = JSON.parse(backupContent);
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
res.status(400).json({ error: 'Backup file is corrupted' });
return;
}
} catch (err) {
const error = err as NodeJS.ErrnoException;
if (error.code === 'ENOENT') {
res.status(404).json({ error: 'Backup was deleted during restore' });
return;
}
res.status(400).json({ error: 'Backup file is corrupted or invalid JSON' });
return;
} finally {
if (fd !== undefined) {
try {
fs.closeSync(fd);
} catch {
// Ignore close errors
}
}
}
// Atomic restore with rollback capability
const settingsDir = path.dirname(settingsPath);
const tempPath = path.join(settingsDir, 'settings.json.restore-tmp');
const rollbackPath = path.join(settingsDir, 'settings.json.rollback-tmp');
try {
// Step 1: Backup current settings for rollback
if (fs.existsSync(settingsPath)) {
fs.copyFileSync(settingsPath, rollbackPath);
}
// Step 2: Write validated content to temp file
fs.writeFileSync(tempPath, backupContent, 'utf8');
// Step 3: Atomic rename (replaces existing file)
fs.renameSync(tempPath, settingsPath);
// Step 4: Cleanup rollback backup on success
if (fs.existsSync(rollbackPath)) {
fs.unlinkSync(rollbackPath);
}
res.json({
success: true,
timestamp: backup.timestamp,
date: backup.date.toISOString(),
});
} catch (error) {
// Rollback on failure
try {
if (fs.existsSync(rollbackPath)) {
fs.renameSync(rollbackPath, settingsPath);
}
if (fs.existsSync(tempPath)) {
fs.unlinkSync(tempPath);
}
} catch (rollbackErr) {
console.error('[persist-routes] Rollback failed:', rollbackErr);
res.status(500).json({
error: 'Restore failed and rollback unsuccessful - manual recovery may be needed',
});
return;
}
throw error;
}
} catch (error) {
res.status(500).json({ error: (error as Error).message });
} finally {
restoreMutex.release();
}
});
export default router;
@@ -24,6 +24,7 @@ import {
HelpCircle,
Pause,
Play,
AlertCircle,
} from 'lucide-react';
import {
cn,
@@ -40,8 +41,9 @@ import type { AccountItemProps } from './types';
* Get color class based on quota percentage
*/
function getQuotaColor(percentage: number): string {
if (percentage <= 20) return 'bg-destructive';
if (percentage <= 50) return 'bg-yellow-500';
const clamped = Math.max(0, Math.min(100, percentage));
if (clamped <= 20) return 'bg-destructive';
if (clamped <= 50) return 'bg-yellow-500';
return 'bg-green-500';
}
@@ -95,13 +97,13 @@ export function AccountItem({
showQuota,
}: AccountItemProps) {
// Fetch runtime stats to get actual lastUsedAt (more accurate than file state)
const { data: stats } = useCliproxyStats(showQuota && account.provider === 'agy');
const { data: stats } = useCliproxyStats(showQuota);
// Fetch quota for 'agy' provider accounts
// Fetch quota for all provider accounts
const { data: quota, isLoading: quotaLoading } = useAccountQuota(
account.provider,
account.id,
showQuota && account.provider === 'agy'
showQuota
);
// Get last used time from runtime stats (more accurate than file)
@@ -217,8 +219,8 @@ export function AccountItem({
</DropdownMenu>
</div>
{/* Quota bar - only for 'agy' provider */}
{showQuota && account.provider === 'agy' && (
{/* Quota bar - supports all providers with quota API */}
{showQuota && (
<div className="pl-11">
{quotaLoading ? (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
@@ -256,7 +258,7 @@ export function AccountItem({
<TooltipTrigger asChild>
<div className="flex items-center gap-2">
<Progress
value={minQuota}
value={Math.max(0, Math.min(100, minQuota))}
className="h-2 flex-1"
indicatorClassName={getQuotaColor(minQuota)}
/>
@@ -285,8 +287,25 @@ export function AccountItem({
</Tooltip>
</TooltipProvider>
</div>
) : quota?.error ? (
<div className="text-xs text-muted-foreground">{quota.error}</div>
) : quota?.error || (quota && !quota.success) ? (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="flex items-center gap-1.5">
<Badge
variant="outline"
className="text-[10px] h-5 px-2 gap-1 border-muted-foreground/50 text-muted-foreground"
>
<AlertCircle className="w-3 h-3" />
N/A
</Badge>
</div>
</TooltipTrigger>
<TooltipContent side="bottom">
<p className="text-xs">{quota?.error || 'Quota information unavailable'}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
) : null}
</div>
)}
+2 -2
View File
@@ -218,13 +218,13 @@ async function fetchAccountQuota(provider: string, accountId: string): Promise<Q
/**
* Hook to get account quota
* Only enabled for 'agy' provider (Antigravity) as it's the only one supporting quota
* Supports all providers that have quota API implemented
*/
export function useAccountQuota(provider: string, accountId: string, enabled = true) {
return useQuery({
queryKey: ['account-quota', provider, accountId],
queryFn: () => fetchAccountQuota(provider, accountId),
enabled: enabled && provider === 'agy' && !!accountId,
enabled: enabled && !!accountId,
staleTime: 30000, // Consider stale after 30s (tokens can refresh anytime)
refetchInterval: 60000, // Refresh every 1 minute
retry: 1,
@@ -4,7 +4,7 @@
*/
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Globe, Settings2, Server, KeyRound } from 'lucide-react';
import { Globe, Settings2, Server, KeyRound, Archive } from 'lucide-react';
import type { SettingsTab } from '../types';
interface TabNavigationProps {
@@ -32,6 +32,10 @@ export function TabNavigation({ activeTab, onTabChange }: TabNavigationProps) {
<KeyRound className="w-4 h-4" />
Auth
</TabsTrigger>
<TabsTrigger value="backups" className="flex-1 gap-2">
<Archive className="w-4 h-4" />
Backups
</TabsTrigger>
</TabsList>
</Tabs>
);
@@ -8,7 +8,8 @@ import type { SettingsTab } from '../types';
export function useSettingsTab() {
const [searchParams, setSearchParams] = useSearchParams();
const tabParam = searchParams.get('tab');
// Normalize to lowercase for case-insensitive matching (fixes ?tab=Backups vs ?tab=backups)
const tabParam = searchParams.get('tab')?.toLowerCase();
const activeTab: SettingsTab =
tabParam === 'globalenv'
? 'globalenv'
@@ -16,7 +17,9 @@ export function useSettingsTab() {
? 'proxy'
: tabParam === 'auth'
? 'auth'
: 'websearch';
: tabParam === 'backups'
? 'backups'
: 'websearch';
const setActiveTab = useCallback(
(tab: SettingsTab) => {
+86 -13
View File
@@ -3,10 +3,18 @@
* Main entry point with lazy-loaded sections and URL tab persistence
*/
import { lazy, Suspense, startTransition, useEffect } from 'react';
import {
lazy,
Suspense,
startTransition,
useEffect,
Component,
type ReactNode,
type ComponentType,
} from 'react';
import { Panel, PanelGroup, PanelResizeHandle } from 'react-resizable-panels';
import { Button } from '@/components/ui/button';
import { RefreshCw, FileCode, Copy, Check, GripVertical } from 'lucide-react';
import { RefreshCw, FileCode, Copy, Check, GripVertical, AlertCircle } from 'lucide-react';
import { CodeEditor } from '@/components/shared/code-editor';
import { SettingsProvider } from './context';
import { useSettingsTab, useRawConfig } from './hooks';
@@ -14,11 +22,73 @@ import { TabNavigation } from './components/tab-navigation';
import { SectionSkeleton } from './components/section-skeleton';
import type { SettingsTab } from './types';
// Lazy-loaded sections
const WebSearchSection = lazy(() => import('./sections/websearch'));
const GlobalEnvSection = lazy(() => import('./sections/globalenv-section'));
const ProxySection = lazy(() => import('./sections/proxy'));
const AuthSection = lazy(() => import('./sections/auth-section'));
/**
* Retry wrapper for dynamic imports with exponential backoff
* Handles temporary network failures gracefully
*/
function retryImport<T extends ComponentType<unknown>>(
importFn: () => Promise<{ default: T }>,
retries = 3,
delay = 1000
): Promise<{ default: T }> {
return importFn().catch((error: Error) => {
if (retries <= 0) throw error;
return new Promise((resolve) => setTimeout(resolve, delay)).then(() =>
retryImport(importFn, retries - 1, delay * 2)
);
});
}
/** Lazy load with automatic retry on failure */
function lazyWithRetry<T extends ComponentType<unknown>>(importFn: () => Promise<{ default: T }>) {
return lazy(() => retryImport(importFn));
}
// Lazy-loaded sections with retry capability
const WebSearchSection = lazyWithRetry(() => import('./sections/websearch'));
const GlobalEnvSection = lazyWithRetry(() => import('./sections/globalenv-section'));
const ProxySection = lazyWithRetry(() => import('./sections/proxy'));
const AuthSection = lazyWithRetry(() => import('./sections/auth-section'));
const BackupsSection = lazyWithRetry(() => import('./sections/backups-section'));
// Error Boundary for lazy-loaded sections
class SectionErrorBoundary extends Component<
{ children: ReactNode },
{ hasError: boolean; error: Error | null }
> {
constructor(props: { children: ReactNode }) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error: Error) {
return { hasError: true, error };
}
render() {
if (this.state.hasError) {
return (
<div className="flex-1 flex items-center justify-center text-muted-foreground">
<div className="text-center p-6 max-w-md">
<AlertCircle className="w-12 h-12 mx-auto mb-4 text-destructive" />
<p className="font-medium text-foreground mb-2">Failed to load section</p>
<p className="text-sm mb-4">{this.state.error?.message || 'Unknown error occurred'}</p>
<Button
variant="outline"
onClick={() => window.location.reload()}
className="inline-flex items-center gap-2"
>
<RefreshCw className="w-4 h-4" />
Reload page
</Button>
</div>
</div>
);
}
return this.props.children;
}
}
// Inner component that uses context
function SettingsPageInner() {
@@ -54,12 +124,15 @@ function SettingsPageInner() {
</div>
{/* Tab Content */}
<Suspense fallback={<SectionSkeleton />}>
{activeTab === 'websearch' && <WebSearchSection />}
{activeTab === 'globalenv' && <GlobalEnvSection />}
{activeTab === 'proxy' && <ProxySection />}
{activeTab === 'auth' && <AuthSection />}
</Suspense>
<SectionErrorBoundary>
<Suspense fallback={<SectionSkeleton />}>
{activeTab === 'websearch' && <WebSearchSection />}
{activeTab === 'globalenv' && <GlobalEnvSection />}
{activeTab === 'proxy' && <ProxySection />}
{activeTab === 'auth' && <AuthSection />}
{activeTab === 'backups' && <BackupsSection />}
</Suspense>
</SectionErrorBoundary>
</div>
</Panel>
@@ -0,0 +1,307 @@
/**
* Backups Section
* Settings section for managing settings.json backups (list and restore)
*/
import { useEffect, useState, useCallback, useRef } from 'react';
import { Button } from '@/components/ui/button';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Card } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { Badge } from '@/components/ui/badge';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { RefreshCw, CheckCircle2, AlertCircle, RotateCcw, Clock, Archive } from 'lucide-react';
import { useRawConfig } from '../hooks';
interface Backup {
timestamp: string;
date: string;
}
interface BackupsResponse {
backups: Backup[];
}
export default function BackupsSection() {
const { fetchRawConfig } = useRawConfig();
// AbortController refs for cleanup
const abortControllerRef = useRef<AbortController | null>(null);
const restoreAbortControllerRef = useRef<AbortController | null>(null);
// State
const [backups, setBackups] = useState<Backup[]>([]);
const [loading, setLoading] = useState(true);
const [restoring, setRestoring] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
const [confirmRestore, setConfirmRestore] = useState<string | null>(null); // Confirmation dialog state
// Fetch backups
const fetchBackups = useCallback(async () => {
// Abort previous request
abortControllerRef.current?.abort();
abortControllerRef.current = new AbortController();
try {
setLoading(true);
setError(null);
const response = await fetch('/api/persist/backups', {
signal: abortControllerRef.current.signal,
});
if (!response.ok) {
throw new Error('Failed to fetch backups');
}
const data: BackupsResponse = await response.json();
setBackups(data.backups || []);
} catch (err) {
// Ignore abort errors
if (err instanceof Error && err.name === 'AbortError') return;
setError(err instanceof Error ? err.message : 'Unknown error');
} finally {
setLoading(false);
}
}, []);
// Restore backup (wrapped in useCallback for callback stability)
const restoreBackup = useCallback(
async (timestamp: string) => {
// Abort previous restore request
restoreAbortControllerRef.current?.abort();
restoreAbortControllerRef.current = new AbortController();
try {
setRestoring(timestamp);
setError(null);
const response = await fetch('/api/persist/restore', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ timestamp }),
signal: restoreAbortControllerRef.current.signal,
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || 'Failed to restore backup');
}
setSuccess('Backup restored successfully');
await fetchBackups();
await fetchRawConfig();
} catch (err) {
// Ignore abort errors
if (err instanceof Error && err.name === 'AbortError') return;
setError(err instanceof Error ? err.message : 'Unknown error');
} finally {
setRestoring(null);
}
},
[fetchBackups, fetchRawConfig]
);
// Load on mount
useEffect(() => {
fetchBackups();
}, [fetchBackups]);
// Cleanup: abort pending requests on unmount
useEffect(() => {
return () => {
abortControllerRef.current?.abort();
restoreAbortControllerRef.current?.abort();
};
}, []);
// Clear success after timeout
useEffect(() => {
if (success) {
const timer = setTimeout(() => setSuccess(null), 3000);
return () => clearTimeout(timer);
}
}, [success]);
// Clear error after timeout
useEffect(() => {
if (error) {
const timer = setTimeout(() => setError(null), 5000);
return () => clearTimeout(timer);
}
}, [error]);
// Loading skeleton
if (loading) {
return (
<>
<ScrollArea className="flex-1">
<div className="p-5 space-y-4">
<div className="space-y-2">
<Skeleton className="h-6 w-40" />
<Skeleton className="h-4 w-full" />
</div>
{[1, 2, 3].map((i) => (
<Card key={i} className="p-4">
<div className="flex items-center justify-between">
<div className="space-y-2 flex-1">
<Skeleton className="h-4 w-32" />
<Skeleton className="h-3 w-48" />
</div>
<Skeleton className="h-8 w-20" />
</div>
</Card>
))}
</div>
</ScrollArea>
<div className="p-4 border-t bg-background">
<Skeleton className="h-9 w-full" />
</div>
</>
);
}
return (
<>
{/* Toast-style alerts */}
<div
className={`absolute left-5 right-5 top-20 z-10 transition-all duration-200 ease-out ${
error || success
? 'opacity-100 translate-y-0'
: 'opacity-0 -translate-y-2 pointer-events-none'
}`}
>
{error && (
<Alert variant="destructive" className="py-2 shadow-lg">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{success && (
<div className="flex items-center gap-2 px-3 py-2 rounded-md border border-green-200 bg-green-50 text-green-700 shadow-lg dark:border-green-900/50 dark:bg-green-900/90 dark:text-green-300">
<CheckCircle2 className="h-4 w-4 shrink-0" />
<span className="text-sm font-medium">{success}</span>
</div>
)}
</div>
{/* Scrollable Content */}
<ScrollArea className="flex-1">
<div className="p-5 space-y-4">
{/* Header */}
<div>
<div className="flex items-center gap-2 mb-2">
<Archive className="w-5 h-5 text-primary" />
<h2 className="text-lg font-semibold">Settings Backups</h2>
</div>
<p className="text-sm text-muted-foreground">
Restore previous versions of your settings.json file. Backups are created
automatically when settings are modified.
</p>
</div>
{/* Backups List */}
{backups.length === 0 ? (
<Card className="p-8">
<div className="text-center">
<Archive className="w-12 h-12 mx-auto mb-3 opacity-30 text-muted-foreground" />
<p className="text-sm text-muted-foreground">No backups available</p>
<p className="text-xs text-muted-foreground mt-1">
Backups will appear here when you modify settings
</p>
</div>
</Card>
) : (
<div className="space-y-2">
{backups.map((backup, index) => (
<Card key={backup.timestamp} className="p-4 hover:bg-muted/50 transition-colors">
<div className="flex items-center justify-between gap-4">
<div className="flex items-start gap-3 flex-1 min-w-0">
<Clock className="w-4 h-4 text-muted-foreground mt-0.5 shrink-0" />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 mb-1">
<p className="text-sm font-medium font-mono">{backup.timestamp}</p>
{index === 0 && (
<Badge variant="secondary" className="text-xs">
Latest
</Badge>
)}
</div>
<p className="text-xs text-muted-foreground">{backup.date}</p>
</div>
</div>
<Button
variant="outline"
size="sm"
onClick={() => setConfirmRestore(backup.timestamp)}
disabled={restoring !== null}
className="gap-2 shrink-0"
>
<RotateCcw
className={`w-4 h-4 ${restoring === backup.timestamp ? 'animate-spin' : ''}`}
/>
{restoring === backup.timestamp ? 'Restoring...' : 'Restore'}
</Button>
</div>
</Card>
))}
</div>
)}
</div>
</ScrollArea>
{/* Footer */}
<div className="p-4 border-t bg-background">
<Button
variant="outline"
size="sm"
onClick={() => {
fetchBackups();
fetchRawConfig();
}}
disabled={loading || restoring !== null}
className="w-full"
>
<RefreshCw className={`w-4 h-4 mr-2 ${loading ? 'animate-spin' : ''}`} />
Refresh
</Button>
</div>
{/* Restore Confirmation Dialog */}
<AlertDialog open={!!confirmRestore} onOpenChange={() => setConfirmRestore(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Restore Backup?</AlertDialogTitle>
<AlertDialogDescription>
This will replace your current settings with backup from{' '}
<code className="font-mono bg-muted px-1.5 py-0.5 rounded text-foreground">
{confirmRestore}
</code>
. This action cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
if (confirmRestore) {
restoreBackup(confirmRestore);
}
setConfirmRestore(null);
}}
>
Restore
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
}
+68 -2
View File
@@ -3,16 +3,19 @@
* Settings section for CLIProxyAPI configuration (local/remote)
*/
import { useEffect } from 'react';
import { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Switch } from '@/components/ui/switch';
import { RefreshCw, CheckCircle2, AlertCircle, Laptop, Cloud } from 'lucide-react';
import { RefreshCw, CheckCircle2, AlertCircle, Laptop, Cloud, Bug } from 'lucide-react';
import { useProxyConfig, useRawConfig } from '../../hooks';
import { LocalProxyCard } from './local-proxy-card';
import { RemoteProxyCard } from './remote-proxy-card';
/** LocalStorage key for debug mode preference */
const DEBUG_MODE_KEY = 'ccs_debug_mode';
export default function ProxySection() {
const {
config,
@@ -39,6 +42,40 @@ export default function ProxySection() {
const { fetchRawConfig } = useRawConfig();
// Debug mode state (persisted in localStorage)
const [debugMode, setDebugMode] = useState(() => {
try {
return localStorage.getItem(DEBUG_MODE_KEY) === 'true';
} catch {
return false;
}
});
const handleDebugModeChange = (enabled: boolean) => {
setDebugMode(enabled);
try {
localStorage.setItem(DEBUG_MODE_KEY, String(enabled));
} catch {
// Ignore storage errors
}
};
// Log when debug mode changes (sanitize sensitive fields)
useEffect(() => {
if (debugMode && config) {
// Sanitize config before logging to prevent credential exposure
const sanitizedConfig = {
...config,
remote: {
...config.remote,
auth_token: config.remote.auth_token ? '[REDACTED]' : undefined,
management_key: config.remote.management_key ? '[REDACTED]' : undefined,
},
};
console.log('[CCS Debug] Debug mode enabled - proxy config:', sanitizedConfig);
}
}, [debugMode, config]);
// Load data on mount
useEffect(() => {
fetchConfig();
@@ -269,6 +306,35 @@ export default function ProxySection() {
</div>
</div>
{/* Advanced Settings */}
<div className="space-y-3">
<h3 className="text-base font-medium flex items-center gap-2">
<Bug className="w-4 h-4" />
Advanced
</h3>
<div className="space-y-3 p-4 rounded-lg border bg-muted/30">
{/* Debug Mode Toggle */}
<div className="flex items-center justify-between">
<div>
<p className="font-medium text-sm">Debug Mode</p>
<p className="text-xs text-muted-foreground">
Enable developer diagnostics in browser console
</p>
</div>
<Switch
checked={debugMode}
onCheckedChange={handleDebugModeChange}
disabled={saving}
/>
</div>
{debugMode && (
<p className="text-xs text-amber-600 dark:text-amber-400 pl-0.5">
Debug mode enabled. Check browser console for detailed logs.
</p>
)}
</div>
</div>
{/* Local Proxy Settings - Only show in Local mode */}
{!isRemoteMode && (
<LocalProxyCard
+1 -1
View File
@@ -49,7 +49,7 @@ export interface GlobalEnvConfig {
// === Tab Types ===
export type SettingsTab = 'websearch' | 'globalenv' | 'proxy' | 'auth';
export type SettingsTab = 'websearch' | 'globalenv' | 'proxy' | 'auth' | 'backups';
// === Re-exports from api-client ===