Spaces:
Paused
Paused
Download frontend/apps/internal/src/components/WorkerLab.tsx from 3SCError404/miracle: direct link, hf CLI and curl.
- Browser
- Download file 14.6 kB
-
https://huggingface.co/spaces/3SCError404/miracle/resolve/main/frontend/apps/internal/src/components/WorkerLab.tsx
- Command line
-
hf download hf://spaces/3SCError404/miracle/frontend/apps/internal/src/components/WorkerLab.tsx
-
curl -L -o WorkerLab.tsx https://huggingface.co/spaces/3SCError404/miracle/resolve/main/frontend/apps/internal/src/components/WorkerLab.tsx
14.6 kB
| import React, { useState, useEffect } from 'react'; | |
| import { api, NexusLogo } from '@nexus/shared'; | |
| import styles from './WorkerLab.module.css'; | |
| interface Job { | |
| id: string; | |
| task_name: string; | |
| status: string; | |
| duration_ms: number; | |
| queued_at: string; | |
| started_at: string; | |
| finished_at: string; | |
| args: any[]; | |
| kwargs: Record<string, any>; | |
| result: any; | |
| error?: string; | |
| metadata?: Record<string, any>; | |
| } | |
| interface Stats { | |
| status_counts: Record<string, number>; | |
| avg_duration_ms: number; | |
| total_jobs: number; | |
| } | |
| interface WorkerLabProps { | |
| workspaceId?: string; | |
| } | |
| export const WorkerLab: React.FC<WorkerLabProps> = ({ workspaceId }) => { | |
| const [jobs, setJobs] = useState<Job[]>([]); | |
| const [activeJobs, setActiveJobs] = useState<any[]>([]); | |
| const [stats, setStats] = useState<Stats | null>(null); | |
| const [selectedJob, setSelectedJob] = useState<Job | null>(null); | |
| const [loading, setLoading] = useState(true); | |
| const [refreshing, setRefreshing] = useState(false); | |
| // Pagination & Filtering State | |
| const [page, setPage] = useState(1); | |
| const [totalPages, setTotalPages] = useState(1); | |
| const [totalCount, setTotalCount] = useState(0); | |
| const [statusFilter, setStatusFilter] = useState(''); | |
| const [searchTerm, setSearchTerm] = useState(''); | |
| const [liveMode, setLiveMode] = useState(false); | |
| const fetchData = async (targetPage = page) => { | |
| try { | |
| setRefreshing(true); | |
| const params: any = { | |
| limit: 10, | |
| page: targetPage, | |
| status: statusFilter || undefined, | |
| search: searchTerm || undefined | |
| }; | |
| if (workspaceId) params.workspace_id = workspaceId; | |
| const [histRes, statsRes, activeRes] = await Promise.all([ | |
| api.get('worker/history/', { params }), | |
| api.get('worker/stats/', { params: { workspace_id: workspaceId } }), | |
| api.get('worker/active/', { params: { workspace_id: workspaceId } }) | |
| ]); | |
| const history = histRes.data; | |
| setJobs(history.items); | |
| setTotalCount(history.total); | |
| setTotalPages(history.pages); | |
| setPage(history.page); | |
| setStats(statsRes.data); | |
| setActiveJobs(activeRes.data); | |
| if (!selectedJob && history.items.length > 0) { | |
| setSelectedJob(history.items[0]); | |
| } | |
| } catch (err) { | |
| console.error('Failed to fetch worker data:', err); | |
| } finally { | |
| setLoading(false); | |
| setRefreshing(false); | |
| } | |
| }; | |
| useEffect(() => { | |
| fetchData(1); | |
| }, [statusFilter, searchTerm, workspaceId]); | |
| useEffect(() => { | |
| if (!liveMode) return; | |
| const interval = setInterval(() => fetchData(page), 15000); // 15s refresh in live mode | |
| return () => clearInterval(interval); | |
| }, [liveMode, page, statusFilter, searchTerm]); | |
| if (loading) return ( | |
| <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', gap: '16px' }}> | |
| <NexusLogo subtitle="CALIBRATING WORKER TELEMETRY..." /> | |
| <div className="nexus-loading-bar" style={{ width: '200px' }}><div className="nexus-loading-progress" /></div> | |
| </div> | |
| ); | |
| const formatTime = (ts: string) => { | |
| if (!ts) return '-'; | |
| return new Date(ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }); | |
| }; | |
| const handlePageChange = (newPage: number) => { | |
| if (newPage < 1 || newPage > totalPages) return; | |
| fetchData(newPage); | |
| }; | |
| const copyToClipboard = (text: string) => { | |
| navigator.clipboard.writeText(text); | |
| // Simple alert for feedback, could be a toast | |
| alert('Copied to clipboard!'); | |
| }; | |
| const calculateWaitTime = (queued: string, started: string) => { | |
| if (!queued || !started) return 0; | |
| const q = new Date(queued).getTime(); | |
| const s = new Date(started).getTime(); | |
| return Math.max(0, s - q); | |
| }; | |
| return ( | |
| <div className={styles.container}> | |
| {/* Telemetry Stats */} | |
| <div className={styles.statsGrid}> | |
| <div className={styles.statCard}> | |
| <span className={styles.statLabel}>Throughput</span> | |
| <span className={styles.statValue}>{stats?.total_jobs || 0}</span> | |
| <span className={styles.statTrend}>{workspaceId ? 'Workspace executions' : 'Platform-wide executions'}</span> | |
| </div> | |
| <div className={styles.statCard} style={{ '--accent': '#10b981' } as any}> | |
| <span className={styles.statLabel}>Success Rate</span> | |
| <span className={styles.statValue}> | |
| {stats?.total_jobs ? Math.round(((stats.status_counts.success || 0) / stats.total_jobs) * 100) : 0}% | |
| </span> | |
| <span className={styles.statTrend}>Operational Stability</span> | |
| </div> | |
| <div className={styles.statCard} style={{ '--accent': '#3b82f6' } as any}> | |
| <span className={styles.statLabel}>Active Queues</span> | |
| <span className={styles.statValue}>{activeJobs.length}</span> | |
| <span className={styles.statTrend}>Live background tasks</span> | |
| </div> | |
| <div className={styles.statCard} style={{ '--accent': '#a855f7' } as any}> | |
| <span className={styles.statLabel}>Avg Latency</span> | |
| <span className={styles.statValue}>{Math.round(stats?.avg_duration_ms || 0)}ms</span> | |
| <span className={styles.statTrend}>{workspaceId ? 'Workspace responsiveness' : 'System responsiveness'}</span> | |
| </div> | |
| </div> | |
| <div className={styles.mainPanel}> | |
| {/* History Table */} | |
| <div className={styles.jobTableContainer}> | |
| <div className={styles.tableHeader}> | |
| <h3 className={styles.tableTitle}>Execution History</h3> | |
| <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}> | |
| <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '11px', color: 'var(--text3)' }}> | |
| <input | |
| type="checkbox" | |
| checked={liveMode} | |
| onChange={(e) => setLiveMode(e.target.checked)} | |
| style={{ cursor: 'pointer' }} | |
| /> | |
| {liveMode ? 'LIVE' : 'MANUAL SYNC'} | |
| </div> | |
| <div className={liveMode ? styles.liveIndicator : ''} style={{ background: liveMode ? '#10b981' : '#6b7280' }} /> | |
| <button | |
| onClick={() => fetchData()} | |
| className="nexus-btn-text" | |
| style={{ fontSize: '11px', display: 'flex', alignItems: 'center', gap: '4px' }} | |
| disabled={refreshing} | |
| > | |
| <span className={refreshing ? styles.spin : ''}>🔄</span> | |
| {refreshing ? 'REFRESHING...' : 'FORCE REFRESH'} | |
| </button> | |
| </div> | |
| </div> | |
| <div className={styles.filterBar}> | |
| <input | |
| className={styles.searchInput} | |
| placeholder="Search by Task Name or ID..." | |
| value={searchTerm} | |
| onChange={(e) => setSearchTerm(e.target.value)} | |
| /> | |
| <select | |
| className={styles.selectInput} | |
| value={statusFilter} | |
| onChange={(e) => setStatusFilter(e.target.value)} | |
| > | |
| <option value="">All Statuses</option> | |
| <option value="success">Success</option> | |
| <option value="failed">Failed</option> | |
| <option value="running">Running</option> | |
| <option value="queued">Queued</option> | |
| </select> | |
| </div> | |
| <table className={`${styles.jobTable} ${refreshing ? styles.refreshingTable : ''}`}> | |
| <thead> | |
| <tr> | |
| <th>Task</th> | |
| <th>Status</th> | |
| <th>Queued</th> | |
| <th>Latency</th> | |
| <th>ID</th> | |
| </tr> | |
| </thead> | |
| <tbody> | |
| {jobs.map((job) => ( | |
| <tr | |
| key={job.id} | |
| className={`${styles.jobRow} ${selectedJob?.id === job.id ? styles.selected : ''}`} | |
| onClick={() => setSelectedJob(job)} | |
| > | |
| <td> | |
| <span className={styles.taskName}>{job.task_name}</span> | |
| </td> | |
| <td> | |
| <span className={`${styles.statusBadge} ${styles[`status_${job.status}`]}`}> | |
| {job.status} | |
| </span> | |
| </td> | |
| <td>{formatTime(job.queued_at)}</td> | |
| <td>{job.duration_ms ? `${Math.round(job.duration_ms)}ms` : '-'}</td> | |
| <td style={{ opacity: 0.5, fontSize: '10px' }}>{job.id.slice(0, 8)}</td> | |
| </tr> | |
| ))} | |
| {jobs.length === 0 && ( | |
| <tr> | |
| <td colSpan={5} className={styles.emptyState}>No job history matches your filters.</td> | |
| </tr> | |
| )} | |
| </tbody> | |
| </table> | |
| {/* Pagination Footer */} | |
| <div className={styles.pagination}> | |
| <div className={styles.pageInfo}> | |
| Showing {(page - 1) * 10 + 1} - {Math.min(page * 10, totalCount)} of {totalCount} jobs | |
| </div> | |
| <div className={styles.pageControls}> | |
| <button | |
| className={styles.pageBtn} | |
| onClick={() => handlePageChange(1)} | |
| disabled={page === 1} | |
| >«</button> | |
| <button | |
| className={styles.pageBtn} | |
| onClick={() => handlePageChange(page - 1)} | |
| disabled={page === 1} | |
| >PREV</button> | |
| <button className={`${styles.pageBtn} ${styles.pageBtnActive}`}> | |
| {page} | |
| </button> | |
| <button | |
| className={styles.pageBtn} | |
| onClick={() => handlePageChange(page + 1)} | |
| disabled={page === totalPages} | |
| >NEXT</button> | |
| <button | |
| className={styles.pageBtn} | |
| onClick={() => handlePageChange(totalPages)} | |
| disabled={page === totalPages} | |
| >»</button> | |
| </div> | |
| </div> | |
| </div> | |
| {/* Sidebar Diagnostics */} | |
| <div className={styles.sideDetail}> | |
| {selectedJob ? ( | |
| <> | |
| <div className={styles.detailCard}> | |
| <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}> | |
| <h4 className={styles.detailTitle} style={{ margin: 0 }}>🆔 Identity</h4> | |
| <button | |
| onClick={() => copyToClipboard(selectedJob.id)} | |
| className="nexus-btn-text" | |
| style={{ fontSize: '10px', color: 'var(--accent)' }} | |
| > | |
| COPY FULL ID | |
| </button> | |
| </div> | |
| <div className={styles.idBox}>{selectedJob.id}</div> | |
| </div> | |
| <div className={styles.detailCard}> | |
| <h4 className={styles.detailTitle}>⏱️ Timeline</h4> | |
| <div className={styles.timeline}> | |
| <div className={styles.timelineItem}> | |
| <div className={styles.timelinePoint} /> | |
| <div className={styles.timelineLabel}>Queued</div> | |
| <div className={styles.timelineTime}>{new Date(selectedJob.queued_at).toLocaleTimeString()}</div> | |
| </div> | |
| <div className={styles.timelineConnector}> | |
| <span>Wait: {calculateWaitTime(selectedJob.queued_at, selectedJob.started_at)}ms</span> | |
| </div> | |
| <div className={styles.timelineItem}> | |
| <div className={styles.timelinePoint} /> | |
| <div className={styles.timelineLabel}>Started</div> | |
| <div className={styles.timelineTime}>{selectedJob.started_at ? formatTime(selectedJob.started_at) : 'Pending...'}</div> | |
| </div> | |
| <div className={styles.timelineConnector}> | |
| <span>Exec: {selectedJob.duration_ms ? `${Math.round(selectedJob.duration_ms)}ms` : '...'}</span> | |
| </div> | |
| <div className={styles.timelineItem}> | |
| <div className={styles.timelinePoint} /> | |
| <div className={styles.timelineLabel}>Finished</div> | |
| <div className={styles.timelineTime}>{selectedJob.finished_at ? formatTime(selectedJob.finished_at) : '...'}</div> | |
| </div> | |
| </div> | |
| </div> | |
| <div className={styles.detailCard}> | |
| <h4 className={styles.detailTitle}>📥 Payload</h4> | |
| <div className={styles.jsonBox}> | |
| <pre>{JSON.stringify({ args: selectedJob.args, kwargs: selectedJob.kwargs }, null, 2)}</pre> | |
| </div> | |
| </div> | |
| {selectedJob.metadata && Object.keys(selectedJob.metadata).length > 0 && ( | |
| <div className={styles.detailCard} style={{ borderLeft: '4px solid var(--accent)' }}> | |
| <h4 className={styles.detailTitle}>🧩 Context Metadata</h4> | |
| <div className={styles.metadataGrid}> | |
| {Object.entries(selectedJob.metadata).map(([key, val]) => ( | |
| <div key={key} className={styles.metadataRow}> | |
| <span className={styles.metadataLabel}>{key}</span> | |
| <span className={styles.metadataValue}>{String(val)}</span> | |
| </div> | |
| ))} | |
| </div> | |
| </div> | |
| )} | |
| <div className={styles.detailCard}> | |
| <h4 className={styles.detailTitle}>📤 Result</h4> | |
| {selectedJob.status === 'failed' ? ( | |
| <div className={styles.errorBox}> | |
| {selectedJob.error || 'Unknown execution error occurred.'} | |
| </div> | |
| ) : ( | |
| <div className={styles.jsonBox}> | |
| <pre>{selectedJob.result ? JSON.stringify(selectedJob.result, null, 2) : (selectedJob.status === 'failed' ? 'ERROR DETECTED' : 'WAITING FOR COMPLETION...')}</pre> | |
| </div> | |
| )} | |
| </div> | |
| </> | |
| ) : ( | |
| <div className={styles.emptyState}>Select a job to view diagnostics.</div> | |
| )} | |
| </div> | |
| </div> | |
| </div> | |
| ); | |
| }; | |