feat(ui): add SSE-based audit streaming and real-time progress

Add server-sent events endpoint for audit scans so the web UI can
display per-skill progress instead of waiting for the full batch.

Backend:
- Extract discoverAuditSkills and processAuditResults from handler
- Add handler_audit_stream.go with SSE streaming endpoint
- Register GET /api/audit/stream route with read-lock middleware
- Add CORS headers for SSE connections in middleware

Frontend:
- Add AuditStreamPanel and AuditResultCard components
- Wire streaming audit into AuditPage with start/stop controls
- Add useAuditStream hook and streamAudit API client method
- Add per-skill audit action on SkillDetailPage
- Add check-based update detection on UpdatePage
- Configure Vite proxy for SSE endpoint
This commit is contained in:
Willie
2026-03-05 02:13:21 +08:00
parent 0daafd20ee
commit 76c1904afb
14 changed files with 640 additions and 159 deletions
+47 -21
View File
@@ -67,20 +67,13 @@ type skillEntry struct {
path string
}
func (s *Server) handleAuditAll(w http.ResponseWriter, r *http.Request) {
start := time.Now()
source := s.cfg.Source
policy := s.auditPolicy()
threshold := policy.Threshold
// Discover all skills
// discoverAuditSkills discovers and deduplicates skills for audit scanning.
func discoverAuditSkills(source string) ([]skillEntry, error) {
discovered, err := sync.DiscoverSourceSkills(source)
if err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
return nil, err
}
// Deduplicate and also pick up top-level dirs without SKILL.md
seen := make(map[string]bool)
var skills []skillEntry
@@ -104,6 +97,21 @@ func (s *Server) handleAuditAll(w http.ResponseWriter, r *http.Request) {
}
}
return skills, nil
}
// auditAggregation holds the aggregated audit results and summary.
type auditAggregation struct {
Results []auditResultResponse
Summary auditSummary
LogArgs map[string]any
Status string
Message string
}
// processAuditResults aggregates scan outputs into results, summary, and log args.
func processAuditResults(skills []skillEntry, scanned []audit.ScanOutput, policy audit.Policy) auditAggregation {
threshold := policy.Threshold
var results []auditResultResponse
var rawResults []*audit.Result
summary := auditSummary{
@@ -125,14 +133,6 @@ func (s *Server) handleAuditAll(w http.ResponseWriter, r *http.Request) {
sumAnalyzability := 0.0
catCounts := make(map[string]int)
// Phase 1: parallel scan with bounded workers.
projectRoot := s.projectRoot
if !s.IsProjectMode() {
projectRoot = ""
}
scanned := audit.ParallelScan(skillsToAuditInputs(skills), projectRoot, nil, nil)
// Phase 2: sequential result collection.
for i := range skills {
se := scanned[i]
if se.Err != nil {
@@ -240,11 +240,37 @@ func (s *Server) handleAuditAll(w http.ResponseWriter, r *http.Request) {
results = append(results, toAuditResponse(xr))
}
s.writeAuditLog(status, start, args, msg)
return auditAggregation{
Results: results,
Summary: summary,
LogArgs: args,
Status: status,
Message: msg,
}
}
func (s *Server) handleAuditAll(w http.ResponseWriter, r *http.Request) {
start := time.Now()
policy := s.auditPolicy()
skills, err := discoverAuditSkills(s.cfg.Source)
if err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
projectRoot := s.projectRoot
if !s.IsProjectMode() {
projectRoot = ""
}
scanned := audit.ParallelScan(skillsToAuditInputs(skills), projectRoot, nil, nil)
agg := processAuditResults(skills, scanned, policy)
s.writeAuditLog(agg.Status, start, agg.LogArgs, agg.Message)
writeJSON(w, map[string]any{
"results": results,
"summary": summary,
"results": agg.Results,
"summary": agg.Summary,
})
}
+97
View File
@@ -0,0 +1,97 @@
package server
import (
"net/http"
"sync"
"sync/atomic"
"time"
"skillshare/internal/audit"
)
// handleAuditStream serves an SSE endpoint that streams audit progress in real time.
// Events:
// - "start" → {"total": N} after skill discovery
// - "progress" → {"scanned": N} every 200ms during scan
// - "done" → {"results":…,"summary":…} final payload (same shape as GET /api/audit)
func (s *Server) handleAuditStream(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
writeError(w, http.StatusInternalServerError, "streaming not supported")
return
}
// Disable WriteTimeout for this long-lived SSE connection.
if rc := http.NewResponseController(w); rc != nil {
_ = rc.SetWriteDeadline(time.Time{}) // zero = no deadline
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
// Mutex protects all writes to the ResponseWriter (not goroutine-safe).
var mu sync.Mutex
safeSend := func(event string, data any) {
mu.Lock()
defer mu.Unlock()
sendSSE(w, flusher, event, data)
}
start := time.Now()
policy := s.auditPolicy()
// 1. Discover skills
skills, err := discoverAuditSkills(s.cfg.Source)
if err != nil {
safeSend("error", map[string]string{"error": err.Error()})
return
}
safeSend("start", map[string]int{"total": len(skills)})
// 2. Atomic counter + ticker for progress events
var scanned atomic.Int64
ctx := r.Context()
done := make(chan struct{})
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
ticker := time.NewTicker(200 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ticker.C:
safeSend("progress", map[string]int64{"scanned": scanned.Load()})
case <-done:
return
case <-ctx.Done():
return
}
}
}()
onDone := func() { scanned.Add(1) }
projectRoot := s.projectRoot
if !s.IsProjectMode() {
projectRoot = ""
}
// 3. Parallel scan (blocks until all skills are scanned)
outputs := audit.ParallelScan(skillsToAuditInputs(skills), projectRoot, onDone, nil)
close(done) // signal ticker goroutine to stop
wg.Wait() // wait for it to fully exit before writing to w
// 4. Process results
agg := processAuditResults(skills, outputs, policy)
s.writeAuditLog(agg.Status, start, agg.LogArgs, agg.Message)
// 5. Send final result (no concurrent writers at this point)
safeSend("done", map[string]any{
"results": agg.Results,
"summary": agg.Summary,
})
}
+11
View File
@@ -2,6 +2,7 @@ package server
import (
"encoding/json"
"fmt"
"net/http"
)
@@ -17,3 +18,13 @@ func writeError(w http.ResponseWriter, code int, msg string) {
w.WriteHeader(code)
json.NewEncoder(w).Encode(map[string]string{"error": msg})
}
// sendSSE writes a single Server-Sent Event frame and flushes.
func sendSSE(w http.ResponseWriter, f http.Flusher, event string, data any) {
b, err := json.Marshal(data)
if err != nil {
return
}
fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event, b)
f.Flush()
}
+1
View File
@@ -293,6 +293,7 @@ func (s *Server) registerRoutes() {
s.mux.HandleFunc("POST /api/pull", s.handlePull)
// Audit
s.mux.HandleFunc("GET /api/audit/stream", s.handleAuditStream)
s.mux.HandleFunc("GET /api/audit/rules/compiled", s.handleGetCompiledRules)
s.mux.HandleFunc("POST /api/audit/rules/toggle", s.handleToggleRule)
s.mux.HandleFunc("POST /api/audit/rules/reset", s.handleResetRules)
+37 -1
View File
@@ -13,7 +13,16 @@ export async function apiFetch<T>(path: string, init?: RequestInit): Promise<T>
headers: { 'Content-Type': 'application/json' },
...init,
});
const data = await res.json();
const text = await res.text();
if (!text) {
throw new ApiError(res.status || 502, 'Empty response from server (request may have timed out)');
}
let data: any;
try {
data = JSON.parse(text);
} catch {
throw new ApiError(res.status || 502, `Invalid JSON response: ${text.slice(0, 200)}`);
}
if (!res.ok) {
throw new ApiError(res.status, data.error ?? res.statusText);
}
@@ -185,6 +194,33 @@ export const api = {
// Audit
auditAll: () => apiFetch<AuditAllResponse>('/audit'),
auditSkill: (name: string) => apiFetch<AuditSkillResponse>(`/audit/${encodeURIComponent(name)}`),
auditAllStream: (
onStart: (total: number) => void,
onProgress: (scanned: number) => void,
onDone: (data: AuditAllResponse) => void,
onError: (err: Error) => void,
): EventSource => {
const es = new EventSource(BASE + '/audit/stream');
let completed = false;
es.addEventListener('start', (e) => {
onStart(JSON.parse((e as MessageEvent).data).total);
});
es.addEventListener('progress', (e) => {
onProgress(JSON.parse((e as MessageEvent).data).scanned);
});
es.addEventListener('done', (e) => {
completed = true;
es.close();
onDone(JSON.parse((e as MessageEvent).data));
});
es.addEventListener('error', () => {
// After 'done' closes the stream, the browser may still fire 'error'.
if (completed) return;
es.close();
onError(new Error('Audit stream failed'));
});
return es;
},
// Audit Rules
getAuditRules: () => apiFetch<AuditRulesResponse>('/audit/rules'),
+42
View File
@@ -0,0 +1,42 @@
import { ShieldOff, CircleCheck } from 'lucide-react';
import { wobbly } from '../../design';
export default function BlockStamp({ isBlocked }: { isBlocked: boolean }) {
if (isBlocked) {
return (
<div
className="flex items-center gap-1.5 px-3 py-1.5 border-[3px] border-danger bg-danger-light"
style={{
borderRadius: wobbly.sm,
boxShadow: '3px 3px 0px 0px rgba(192, 57, 43, 0.3)',
transform: 'rotate(-2deg)',
}}
>
<ShieldOff size={16} strokeWidth={3} className="text-danger" />
<span
className="text-danger font-bold text-sm uppercase tracking-wider"
style={{ fontFamily: 'var(--font-heading)' }}
>
Blocked
</span>
</div>
);
}
return (
<div
className="flex items-center gap-1.5 px-3 py-1.5 border-2 border-success bg-success-light"
style={{
borderRadius: wobbly.sm,
}}
>
<CircleCheck size={14} strokeWidth={2.5} className="text-success" />
<span
className="text-success font-medium text-sm"
style={{ fontFamily: 'var(--font-hand)' }}
>
Pass
</span>
</div>
);
}
+46
View File
@@ -0,0 +1,46 @@
import { wobbly } from '../../design';
import { riskColor, riskBgColor } from './helpers';
export default function RiskMeter({ riskLabel, riskScore }: { riskLabel: string; riskScore: number }) {
const color = riskColor(riskLabel);
return (
<div
className="flex items-center gap-2 px-3 py-1.5 border-2 border-dashed"
style={{
borderRadius: wobbly.sm,
borderColor: color,
backgroundColor: riskBgColor(riskLabel),
}}
>
<div className="flex flex-col items-start gap-0.5">
<span className="text-[10px] text-pencil-light uppercase tracking-wide leading-none" style={{ fontFamily: 'var(--font-hand)' }}>
Risk
</span>
<span
className="text-sm font-bold leading-none"
style={{ fontFamily: 'var(--font-heading)', color }}
>
{riskLabel.toUpperCase()}
</span>
</div>
{/* Mini bar */}
<div className="flex flex-col items-end gap-0.5">
<div
className="w-12 h-1.5 bg-muted/50 overflow-hidden"
style={{ borderRadius: '999px' }}
>
<div
className="h-full"
style={{
width: `${riskScore}%`,
backgroundColor: color,
borderRadius: '999px',
}}
/>
</div>
<span className="text-[10px] text-pencil-light leading-none font-mono">{riskScore}/100</span>
</div>
</div>
);
}
+21
View File
@@ -0,0 +1,21 @@
import { colors } from '../../design';
export function riskColor(risk: string): string {
switch (risk) {
case 'critical': return colors.danger;
case 'high': return colors.warning;
case 'medium': return colors.blue;
case 'low': return colors.success;
default: return colors.success;
}
}
export function riskBgColor(risk: string): string {
switch (risk) {
case 'critical': return 'rgba(192, 57, 43, 0.06)';
case 'high': return 'rgba(212, 135, 14, 0.06)';
case 'medium': return 'rgba(45, 93, 161, 0.06)';
case 'low': return 'rgba(46, 139, 87, 0.06)';
default: return 'rgba(46, 139, 87, 0.06)';
}
}
+3
View File
@@ -0,0 +1,3 @@
export { default as BlockStamp } from './BlockStamp';
export { default as RiskMeter } from './RiskMeter';
export { riskColor, riskBgColor } from './helpers';
+2
View File
@@ -21,6 +21,7 @@ export const queryKeys = {
audit: {
all: ['audit'] as const,
skill: (name: string) => ['audit', 'skill', name] as const,
rules: ['audit', 'rules'] as const,
compiled: ['audit', 'rules', 'compiled'] as const,
},
@@ -47,5 +48,6 @@ export const staleTimes = {
auditRules: 5 * 60 * 1000, // 5min
backups: 2 * 60 * 1000, // 2min
trash: 2 * 60 * 1000, // 2min
auditSkill: 5 * 60 * 1000, // 5min — per-skill audit, rarely changes
check: 60 * 1000, // 1min
};
+108 -134
View File
@@ -1,10 +1,9 @@
import { useMemo, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import {
ShieldCheck,
ShieldAlert,
ShieldX,
ShieldOff,
AlertTriangle,
Info,
FileText,
@@ -25,6 +24,7 @@ import { PageSkeleton } from '../components/Skeleton';
import { useToast } from '../components/Toast';
import { wobbly, shadows, colors } from '../design';
import { severityBadgeVariant } from '../lib/severity';
import { BlockStamp, RiskMeter, riskColor, riskBgColor } from '../components/audit';
type SeverityFilter = 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO';
@@ -42,6 +42,16 @@ export default function AuditPage() {
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [minSeverity, setMinSeverity] = useState<SeverityFilter>('MEDIUM');
const [progress, setProgress] = useState<{ scanned: number; total: number } | null>(null);
const esRef = useRef<EventSource | null>(null);
const startTimeRef = useRef<number>(0);
// Clean up EventSource on unmount
useEffect(() => {
return () => {
esRef.current?.close();
};
}, []);
const totalFindings = useMemo(() => {
if (!data) return 0;
@@ -69,28 +79,41 @@ export default function AuditPage() {
[filteredResults],
);
const runAudit = async () => {
const showAuditToast = useCallback((res: AuditAllResponse) => {
const { summary } = res;
if (summary.failed > 0) {
toast(`Audit complete: ${summary.failed} skill(s) blocked at ${summary.threshold}+`, 'warning');
} else if (summary.warning > 0) {
toast(`Audit complete: ${summary.warning} skill(s) with warnings`, 'warning');
} else if (summary.low > 0 || summary.info > 0) {
toast(`Audit complete: ${summary.low + summary.info} informational findings`, 'warning');
} else {
toast('Audit complete: all skills passed', 'success');
}
}, [toast]);
const runAudit = () => {
setLoading(true);
setError(null);
try {
const res = await api.auditAll();
setData(res);
const { summary } = res;
if (summary.failed > 0) {
toast(`Audit complete: ${summary.failed} skill(s) blocked at ${summary.threshold}+`, 'warning');
} else if (summary.warning > 0) {
toast(`Audit complete: ${summary.warning} skill(s) with warnings`, 'warning');
} else if (summary.low > 0 || summary.info > 0) {
toast(`Audit complete: ${summary.low + summary.info} informational findings`, 'warning');
} else {
toast('Audit complete: all skills passed', 'success');
}
} catch (e: any) {
setError(e.message);
toast(e.message, 'error');
} finally {
setLoading(false);
}
setProgress(null);
startTimeRef.current = Date.now();
esRef.current = api.auditAllStream(
(total) => setProgress({ scanned: 0, total }),
(scanned) => setProgress((p) => p ? { ...p, scanned } : null),
(res) => {
setData(res);
setLoading(false);
setProgress(null);
showAuditToast(res);
},
(err) => {
setError(err.message);
setLoading(false);
setProgress(null);
toast(err.message, 'error');
},
);
};
return (
@@ -131,8 +154,14 @@ export default function AuditPage() {
</div>
</div>
{/* Loading */}
{loading && <PageSkeleton />}
{/* Loading / Progress */}
{loading && (
progress ? (
<AuditProgressBar scanned={progress.scanned} total={progress.total} startTime={startTimeRef.current} />
) : (
<PageSkeleton />
)
)}
{/* Error */}
{error && (
@@ -576,97 +605,7 @@ function SkillAuditCard({ result, index }: { result: AuditResult; index: number
);
}
/* ──────────────────────────────────────────────────────────────────────
* BlockStamp — alarming red stamp or reassuring green check
* ────────────────────────────────────────────────────────────────────── */
function BlockStamp({ isBlocked }: { isBlocked: boolean }) {
if (isBlocked) {
return (
<div
className="flex items-center gap-1.5 px-3 py-1.5 border-[3px] border-danger bg-danger-light"
style={{
borderRadius: wobbly.sm,
boxShadow: '3px 3px 0px 0px rgba(192, 57, 43, 0.3)',
transform: 'rotate(-2deg)',
}}
>
<ShieldOff size={16} strokeWidth={3} className="text-danger" />
<span
className="text-danger font-bold text-sm uppercase tracking-wider"
style={{ fontFamily: 'var(--font-heading)' }}
>
Blocked
</span>
</div>
);
}
return (
<div
className="flex items-center gap-1.5 px-3 py-1.5 border-2 border-success bg-success-light"
style={{
borderRadius: wobbly.sm,
}}
>
<CircleCheck size={14} strokeWidth={2.5} className="text-success" />
<span
className="text-success font-medium text-sm"
style={{ fontFamily: 'var(--font-hand)' }}
>
Pass
</span>
</div>
);
}
/* ──────────────────────────────────────────────────────────────────────
* RiskMeter — compact visual indicator for aggregate risk
* ────────────────────────────────────────────────────────────────────── */
function RiskMeter({ riskLabel, riskScore }: { riskLabel: string; riskScore: number }) {
const color = riskColor(riskLabel);
return (
<div
className="flex items-center gap-2 px-3 py-1.5 border-2 border-dashed"
style={{
borderRadius: wobbly.sm,
borderColor: color,
backgroundColor: riskBgColor(riskLabel),
}}
>
<div className="flex flex-col items-start gap-0.5">
<span className="text-[10px] text-pencil-light uppercase tracking-wide leading-none" style={{ fontFamily: 'var(--font-hand)' }}>
Risk
</span>
<span
className="text-sm font-bold leading-none"
style={{ fontFamily: 'var(--font-heading)', color }}
>
{riskLabel.toUpperCase()}
</span>
</div>
{/* Mini bar */}
<div className="flex flex-col items-end gap-0.5">
<div
className="w-12 h-1.5 bg-muted/50 overflow-hidden"
style={{ borderRadius: '999px' }}
>
<div
className="h-full"
style={{
width: `${riskScore}%`,
backgroundColor: color,
borderRadius: '999px',
}}
/>
</div>
<span className="text-[10px] text-pencil-light leading-none font-mono">{riskScore}/100</span>
</div>
</div>
);
}
/* BlockStamp and RiskMeter imported from ../components/audit */
/* ──────────────────────────────────────────────────────────────────────
* FindingRow — severity color stripe + better visual hierarchy
@@ -721,29 +660,64 @@ function FindingRow({ finding }: { finding: AuditFinding }) {
);
}
/* ──────────────────────────────────────────────────────────────────────
* AuditProgressBar — hand-drawn style scan progress
* ────────────────────────────────────────────────────────────────────── */
function AuditProgressBar({ scanned, total, startTime }: { scanned: number; total: number; startTime: number }) {
const pct = total > 0 ? Math.min((scanned / total) * 100, 100) : 0;
const elapsed = (Date.now() - startTime) / 1000;
const eta = scanned > 0 && pct < 100
? Math.round((elapsed / scanned) * (total - scanned))
: null;
return (
<Card variant="outlined">
<div className="space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<ShieldCheck size={18} strokeWidth={2.5} className="text-pencil-light animate-pulse-gentle" />
<span className="font-medium text-pencil" style={{ fontFamily: 'var(--font-hand)' }}>
Scanning skills...
</span>
</div>
<span className="text-sm text-pencil-light font-mono">
{Math.round(pct)}%
</span>
</div>
{/* Progress bar */}
<div
className="h-4 border-2 border-dashed border-pencil-light/50 bg-paper-warm overflow-hidden"
style={{ borderRadius: wobbly.sm }}
>
<div
className="h-full transition-all duration-200 ease-out"
style={{
width: `${pct}%`,
backgroundColor: colors.blue,
borderRadius: wobbly.sm,
}}
/>
</div>
{/* Stats line */}
<div className="flex items-center justify-between text-sm text-pencil-light" style={{ fontFamily: 'var(--font-hand)' }}>
<span>
{scanned.toLocaleString()} / {total.toLocaleString()} skills
</span>
{eta !== null && (
<span>~{eta}s remaining</span>
)}
</div>
</div>
</Card>
);
}
/* ──────────────────────────────────────────────────────────────────────
* Helper functions
* ────────────────────────────────────────────────────────────────────── */
function riskColor(risk: string): string {
switch (risk) {
case 'critical': return colors.danger;
case 'high': return colors.warning;
case 'medium': return colors.blue;
case 'low': return colors.success;
default: return colors.success;
}
}
function riskBgColor(risk: string): string {
switch (risk) {
case 'critical': return 'rgba(192, 57, 43, 0.06)';
case 'high': return 'rgba(212, 135, 14, 0.06)';
case 'medium': return 'rgba(45, 93, 161, 0.06)';
case 'low': return 'rgba(46, 139, 87, 0.06)';
default: return 'rgba(46, 139, 87, 0.06)';
}
}
/* riskColor and riskBgColor imported from ../components/audit */
function severityStripeColor(sev: string): string {
switch (sev) {
+219 -2
View File
@@ -1,5 +1,10 @@
import { useParams, useNavigate, Link } from 'react-router-dom';
import { ArrowLeft, Trash2, ExternalLink, FileText, ArrowUpRight, RefreshCw, Target } from 'lucide-react';
import {
ArrowLeft, Trash2, ExternalLink, FileText, ArrowUpRight, RefreshCw, Target,
Type, AlignLeft, Files, Scale,
FileCode2, Braces, Settings, BookOpen, File, FolderOpen,
ShieldCheck, Link2,
} from 'lucide-react';
import Markdown, { type Components } from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { useQuery, useQueryClient } from '@tanstack/react-query';
@@ -13,6 +18,8 @@ import ConfirmDialog from '../components/ConfirmDialog';
import { api, type Skill } from '../api/client';
import { lazy, Suspense, useState, useMemo } from 'react';
import { wobbly, shadows } from '../design';
import { BlockStamp, RiskMeter } from '../components/audit';
import { severityBadgeVariant } from '../lib/severity';
const FileViewerModal = lazy(() => import('../components/FileViewerModal'));
@@ -89,6 +96,46 @@ function skillTypeLabel(type?: string): string | undefined {
return type;
}
/** Returns a lucide icon component + color class for a filename */
function getFileIcon(filename: string): { icon: typeof File; className: string } {
if (filename === 'SKILL.md') return { icon: FileText, className: 'text-blue' };
if (/\.(ts|tsx|js|jsx|go|py|rs|rb|sh|bash)$/i.test(filename)) return { icon: FileCode2, className: 'text-pencil-light' };
if (/\.json$/i.test(filename)) return { icon: Braces, className: 'text-pencil-light' };
if (/\.(yaml|yml|toml)$/i.test(filename)) return { icon: Settings, className: 'text-pencil-light' };
if (/\.md$/i.test(filename)) return { icon: BookOpen, className: 'text-pencil-light' };
if (filename.endsWith('/')) return { icon: FolderOpen, className: 'text-warning' };
return { icon: File, className: 'text-pencil-light' };
}
/** Content stats bar showing word count, line count, file count, license */
function ContentStatsBar({ content, fileCount, license }: { content: string; fileCount: number; license?: string }) {
const wordCount = content.trim() ? content.trim().split(/\s+/).length : 0;
const lineCount = content.trim() ? content.trim().split(/\r?\n/).length : 0;
return (
<div className="flex items-center gap-4 flex-wrap text-sm text-pencil-light py-3 mb-4 border-b-2 border-dashed border-pencil-light/30">
<span className="inline-flex items-center gap-1.5">
<Type size={14} strokeWidth={2.5} />
{wordCount.toLocaleString()} words
</span>
<span className="inline-flex items-center gap-1.5">
<AlignLeft size={14} strokeWidth={2.5} />
{lineCount.toLocaleString()} lines
</span>
<span className="inline-flex items-center gap-1.5">
<Files size={14} strokeWidth={2.5} />
{fileCount} file{fileCount !== 1 ? 's' : ''}
</span>
{license && (
<span className="inline-flex items-center gap-1.5">
<Scale size={14} strokeWidth={2.5} />
{license}
</span>
)}
</div>
);
}
export default function SkillDetailPage() {
const { name } = useParams<{ name: string }>();
const navigate = useNavigate();
@@ -104,6 +151,17 @@ export default function SkillDetailPage() {
queryFn: () => api.listSkills(),
staleTime: staleTimes.skills,
});
const auditQuery = useQuery({
queryKey: queryKeys.audit.skill(name!),
queryFn: () => api.auditSkill(name!),
staleTime: staleTimes.auditSkill,
enabled: !!name,
});
const diffQuery = useQuery({
queryKey: queryKeys.diff(),
queryFn: () => api.diff(),
staleTime: staleTimes.diff,
});
const [deleting, setDeleting] = useState(false);
const [confirmDelete, setConfirmDelete] = useState(false);
const [updating, setUpdating] = useState(false);
@@ -332,6 +390,12 @@ export default function SkillDetailPage() {
</dl>
</div>
)}
{/* Stage 1: Content Stats Bar */}
<ContentStatsBar
content={skillMdContent ?? ''}
fileCount={files.length}
license={parsedDoc.manifest.license}
/>
<div className="prose-hand">
{renderedMarkdown ? (
<Markdown remarkPlugins={[remarkGfm]} components={mdComponents}>
@@ -425,6 +489,9 @@ export default function SkillDetailPage() {
</div>
</Card>
{/* Stage 2: Security Audit Card */}
<SecurityAuditCard auditQuery={auditQuery} />
<Card>
<h3
className="font-bold text-pencil mb-3 flex items-center gap-2"
@@ -438,12 +505,13 @@ export default function SkillDetailPage() {
{files.map((f) => {
const linkedSkill = resolveFileSkill(f);
const isSkillMd = f === 'SKILL.md';
const { icon: FileIcon, className: iconClass } = getFileIcon(f);
return (
<li
key={f}
className="text-sm text-pencil-light truncate flex items-center gap-2"
>
<span className="w-1.5 h-1.5 rounded-full bg-muted-dark shrink-0" />
<FileIcon size={14} strokeWidth={2} className={`shrink-0 ${iconClass}`} />
{linkedSkill ? (
<Link
to={`/skills/${encodeURIComponent(linkedSkill.flatName)}`}
@@ -479,6 +547,9 @@ export default function SkillDetailPage() {
<p className="text-sm text-muted-dark italic">No files.</p>
)}
</Card>
{/* Stage 4: Target Sync Status */}
<SyncStatusCard diffQuery={diffQuery} skillFlatName={skill.flatName} />
</div>
</div>
@@ -553,3 +624,149 @@ function MetaItem({
</div>
);
}
/** Security Audit sidebar card */
function SecurityAuditCard({
auditQuery,
}: {
auditQuery: ReturnType<typeof useQuery<Awaited<ReturnType<typeof api.auditSkill>>>>;
}) {
if (auditQuery.isPending) {
return (
<Card variant="outlined">
<div className="flex items-center gap-2 animate-pulse">
<ShieldCheck size={16} strokeWidth={2.5} className="text-pencil-light" />
<span className="text-sm text-pencil-light" style={{ fontFamily: 'var(--font-hand)' }}>
Scanning security...
</span>
</div>
</Card>
);
}
if (auditQuery.error || !auditQuery.data) return null;
const { result } = auditQuery.data;
const findingCounts = result.findings.reduce(
(acc, f) => {
acc[f.severity] = (acc[f.severity] || 0) + 1;
return acc;
},
{} as Record<string, number>,
);
return (
<Card variant="outlined">
<h3
className="font-bold text-pencil mb-3 flex items-center gap-2"
style={{ fontFamily: 'var(--font-heading)' }}
>
<ShieldCheck size={16} strokeWidth={2.5} />
Security
</h3>
<div className="space-y-3">
<div className="flex items-center gap-2 flex-wrap">
<BlockStamp isBlocked={result.isBlocked} />
<RiskMeter riskLabel={result.riskLabel} riskScore={result.riskScore} />
</div>
{result.findings.length > 0 && (
<div className="flex flex-wrap gap-1.5 pt-2 border-t border-dashed border-pencil-light/30">
{Object.entries(findingCounts)
.sort(([a], [b]) => sevOrder(a) - sevOrder(b))
.map(([sev, count]) => (
<Badge key={sev} variant={severityBadgeVariant(sev)}>
{count} {sev}
</Badge>
))}
</div>
)}
{result.findings.length === 0 && (
<p className="text-sm text-success" style={{ fontFamily: 'var(--font-hand)' }}>
No security issues detected
</p>
)}
</div>
</Card>
);
}
function sevOrder(sev: string): number {
switch (sev) {
case 'CRITICAL': return 0;
case 'HIGH': return 1;
case 'MEDIUM': return 2;
case 'LOW': return 3;
case 'INFO': return 4;
default: return 5;
}
}
/** Sync Status sidebar card */
function SyncStatusCard({
diffQuery,
skillFlatName,
}: {
diffQuery: ReturnType<typeof useQuery<Awaited<ReturnType<typeof api.diff>>>>;
skillFlatName: string;
}) {
if (diffQuery.isPending || !diffQuery.data) return null;
// Find which targets have this skill and their status
const targetStatuses: { name: string; status: 'linked' | 'missing' | 'excluded' | 'conflict' }[] = [];
for (const dt of diffQuery.data.diffs) {
const item = dt.items.find((i) => i.skill === skillFlatName);
if (item) {
const status = item.action === 'ok' || item.action === 'linked'
? 'linked'
: item.action === 'excluded'
? 'excluded'
: item.action === 'conflict' || item.action === 'broken'
? 'conflict'
: 'missing';
targetStatuses.push({ name: dt.target, status });
} else {
// Skill not in diff for this target — check if it's because it's already synced (no diff entry = linked)
targetStatuses.push({ name: dt.target, status: 'linked' });
}
}
if (targetStatuses.length === 0) return null;
const statusDot: Record<string, string> = {
linked: 'bg-success',
missing: 'bg-warning',
conflict: 'bg-danger',
excluded: 'bg-muted-dark',
};
const statusLabel: Record<string, string> = {
linked: 'linked',
missing: 'not synced',
conflict: 'conflict',
excluded: 'excluded',
};
return (
<Card variant="outlined">
<h3
className="font-bold text-pencil mb-3 flex items-center gap-2"
style={{ fontFamily: 'var(--font-heading)' }}
>
<Link2 size={16} strokeWidth={2.5} />
Target Sync
</h3>
<ul className="space-y-1.5">
{targetStatuses.map((t) => (
<li key={t.name} className="flex items-center gap-2 text-sm">
<span className={`w-2 h-2 rounded-full shrink-0 ${statusDot[t.status]}`} />
<span className="text-pencil font-medium" style={{ fontFamily: "'Courier New', monospace", fontSize: '0.8125rem' }}>
{t.name}
</span>
<span className="text-pencil-light text-xs">{statusLabel[t.status]}</span>
</li>
))}
</ul>
</Card>
);
}
+1 -1
View File
@@ -195,7 +195,7 @@ export default function UpdatePage() {
Check Now
</HandButton>
)}
{phase === 'idle' && totalSelected > 0 && (
{phase === 'idle' && hasUpdates && totalSelected > 0 && (
<HandButton onClick={handleUpdate}>
<ArrowUpCircle size={16} />
Update Selected ({totalSelected})
+5
View File
@@ -11,6 +11,11 @@ export default defineConfig({
host: true,
port: 5173,
proxy: {
'/api/audit/stream': {
target: 'http://localhost:19420',
// SSE requires no response buffering; set Accept header to bypass compression.
headers: { Accept: 'text/event-stream' },
},
'/api': 'http://localhost:19420',
},
},