feat(ui): add log stats bar with success rate and command breakdown

Wire up the new GET /api/log/stats endpoint in the frontend:
- api.getLogStats() + CommandStats/LogStatsResponse types in client.ts
- logStats query key in queryKeys.ts
- LogStatsBar component on Log page showing success rate, top 4
  commands with ok/error/partial counts, and last operation badge
- Stats bar respects tab (ops/audit) and active filters
- Refresh and clear actions invalidate both log and log-stats queries
This commit is contained in:
Willie
2026-02-26 22:27:23 +08:00
parent 5186d86a3f
commit fbab56f86b
3 changed files with 97 additions and 1 deletions
+23
View File
@@ -173,6 +173,14 @@ export const api = {
},
clearLog: (type?: string) =>
apiFetch<{ success: boolean }>(`/log?type=${type ?? 'ops'}`, { method: 'DELETE' }),
getLogStats: (type?: string, filters?: { cmd?: string; status?: string; since?: string }) => {
const params = new URLSearchParams();
params.set('type', type ?? 'ops');
if (filters?.cmd) params.set('cmd', filters.cmd);
if (filters?.status) params.set('status', filters.status);
if (filters?.since) params.set('since', filters.since);
return apiFetch<LogStatsResponse>(`/log/stats?${params.toString()}`);
},
// Audit
auditAll: () => apiFetch<AuditAllResponse>('/audit'),
@@ -466,6 +474,21 @@ export interface LogListResponse {
commands: string[];
}
export interface CommandStats {
total: number;
ok: number;
error: number;
partial: number;
blocked: number;
}
export interface LogStatsResponse {
total: number;
success_rate: number;
by_command: Record<string, CommandStats>;
last_operation?: LogEntry;
}
// Audit types
export interface AuditFinding {
severity: 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO';
+2
View File
@@ -26,6 +26,8 @@ export const queryKeys = {
log: (type: string, limit: number, filters?: Record<string, string>) =>
['log', type, limit, filters ?? {}] as const,
logStats: (type: string, filters?: Record<string, string>) =>
['log-stats', type, filters ?? {}] as const,
config: ['config'] as const,
};
+72 -1
View File
@@ -2,7 +2,7 @@ import { useState, useEffect, useMemo } from 'react';
import { ScrollText, Trash2, RefreshCw, ChevronLeft, ChevronRight } from 'lucide-react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { api } from '../api/client';
import type { LogEntry } from '../api/client';
import type { LogEntry, LogStatsResponse } from '../api/client';
import { queryKeys, staleTimes } from '../lib/queryKeys';
import Card from '../components/Card';
import HandButton from '../components/HandButton';
@@ -279,6 +279,64 @@ function renderDetail(entry: LogEntry) {
);
}
function LogStatsBar({ stats }: { stats: LogStatsResponse }) {
const commands = Object.entries(stats.by_command).sort((a, b) => b[1].total - a[1].total);
const rate = stats.total > 0 ? Math.round(stats.success_rate * 100) : 0;
const rateColor = rate >= 90 ? 'text-success' : rate >= 70 ? 'text-warning' : 'text-danger';
return (
<div
className="grid gap-3"
style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))' }}
>
{/* Success rate */}
<Card className="!py-3 !px-4 text-center">
<div className="text-pencil-light text-sm" style={{ fontFamily: 'var(--font-hand)' }}>
Success Rate
</div>
<div className={`text-2xl font-bold ${rateColor}`} style={{ fontFamily: 'var(--font-heading)' }}>
{rate}%
</div>
<div className="text-pencil-light text-xs" style={{ fontFamily: 'var(--font-hand)' }}>
{stats.total} total
</div>
</Card>
{/* Top commands */}
{commands.slice(0, 4).map(([cmd, cs]) => (
<Card key={cmd} className="!py-3 !px-4 text-center">
<div className="text-pencil-light text-sm uppercase" style={{ fontFamily: 'var(--font-hand)' }}>
{cmd}
</div>
<div className="text-2xl font-bold text-pencil" style={{ fontFamily: 'var(--font-heading)' }}>
{cs.total}
</div>
<div className="flex items-center justify-center gap-1.5 text-xs" style={{ fontFamily: 'var(--font-hand)' }}>
{cs.ok > 0 && <span className="text-success">{cs.ok} ok</span>}
{cs.error > 0 && <span className="text-danger">{cs.error} err</span>}
{cs.partial > 0 && <span className="text-warning">{cs.partial} partial</span>}
</div>
</Card>
))}
{/* Last operation */}
{stats.last_operation && (
<Card className="!py-3 !px-4 text-center">
<div className="text-pencil-light text-sm" style={{ fontFamily: 'var(--font-hand)' }}>
Last Op
</div>
<div className="text-base font-bold text-pencil uppercase" style={{ fontFamily: 'var(--font-heading)' }}>
{stats.last_operation.cmd}
</div>
<div className="text-xs" style={{ fontFamily: 'var(--font-hand)' }}>
{statusBadge(stats.last_operation.status)}
</div>
</Card>
)}
</div>
);
}
const PAGE_SIZES = [10, 25, 50] as const;
function LogTable({ entries }: { entries: LogEntry[] }) {
@@ -453,6 +511,13 @@ export default function LogPage() {
staleTime: staleTimes.log,
});
const statsType = tab === 'audit' ? 'audit' : 'ops';
const statsQuery = useQuery({
queryKey: queryKeys.logStats(statsType, filters),
queryFn: () => api.getLogStats(statsType, filters),
staleTime: staleTimes.log,
});
const opsEntries = opsQuery.data?.entries ?? [];
const opsTotal = opsQuery.data?.total ?? 0;
const opsTotalAll = opsQuery.data?.totalAll ?? 0;
@@ -483,6 +548,7 @@ export default function LogPage() {
const handleRefresh = () => {
queryClient.invalidateQueries({ queryKey: ['log'] });
queryClient.invalidateQueries({ queryKey: ['log-stats'] });
};
const handleClear = async () => {
@@ -494,6 +560,7 @@ export default function LogPage() {
await api.clearLog(tab);
}
queryClient.invalidateQueries({ queryKey: ['log'] });
queryClient.invalidateQueries({ queryKey: ['log-stats'] });
toast('Log cleared', 'success');
} catch (e: any) {
toast(e.message, 'error');
@@ -626,6 +693,10 @@ export default function LogPage() {
</div>
</div>
{statsQuery.data && statsQuery.data.total > 0 && (
<LogStatsBar stats={statsQuery.data} />
)}
{tab === 'all' ? (
<div className="space-y-6">
<Section title="Operations" entries={opsEntries} emptyLabel="operation" filtered={hasFilter} />