Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 | 'use client' /** * Admin Tasks Monitor * * Real-time view of background tasks as they progress through stages. * Auto-updates via Socket.IO subscriptions. */ import { useEffect, useState, useRef, useCallback } from 'react' import type { Socket } from 'socket.io-client' import { createSocket } from '@/lib/socket' import { css } from '../../../../styled-system/css' import { AppNavBar } from '@/components/AppNavBar' import { AdminNav } from '@/components/AdminNav' interface TaskEvent { id: number taskId: string eventType: string payload: unknown createdAt: string replayed?: boolean } interface Task { id: string type: string status: string progress: number progressMessage: string | null error: string | null createdAt: string startedAt: string | null completedAt: string | null events: TaskEvent[] } export default function AdminTasksPage() { const [tasks, setTasks] = useState<Task[]>([]) const [loading, setLoading] = useState(true) const [error, setError] = useState<string | null>(null) const [selectedTaskId, setSelectedTaskId] = useState<string | null>(null) const [statusFilter, setStatusFilter] = useState<string | null>(null) const [typeFilter, setTypeFilter] = useState<string | null>(null) const socketRef = useRef<Socket | null>(null) const subscribedTasksRef = useRef<Set<string>>(new Set()) // Fetch tasks from API const fetchTasks = useCallback(async () => { try { const response = await fetch('/api/admin/tasks') if (!response.ok) { throw new Error('Failed to fetch tasks') } const data = await response.json() setTasks(data.tasks) setError(null) } catch (err) { setError(err instanceof Error ? err.message : 'Unknown error') } finally { setLoading(false) } }, []) // Subscribe to a task's updates const subscribeToTask = useCallback((taskId: string) => { if (!socketRef.current || subscribedTasksRef.current.has(taskId)) return console.log('[AdminTasks] Subscribing to task:', taskId) socketRef.current.emit('task:subscribe', taskId) subscribedTasksRef.current.add(taskId) }, []) // Initialize socket and fetch tasks useEffect(() => { fetchTasks() // Set up polling for new tasks const pollInterval = setInterval(fetchTasks, 5000) // Set up Socket.IO const socket = createSocket({ reconnection: true, reconnectionDelay: 1000, }) socketRef.current = socket socket.on('connect', () => { console.log('[AdminTasks] Socket connected') // Re-subscribe to all active tasks subscribedTasksRef.current.forEach((taskId) => { socket.emit('task:subscribe', taskId) }) }) // Handle task state updates socket.on('task:state', (taskState: Partial<Task> & { id: string }) => { console.log('[AdminTasks] Received task:state:', taskState.id, taskState.status) setTasks((prev) => prev.map((t) => (t.id === taskState.id ? { ...t, ...taskState, events: t.events } : t)) ) }) // Handle task events socket.on( 'task:event', (event: { taskId: string eventType: string payload: unknown createdAt: string replayed?: boolean }) => { console.log('[AdminTasks] Received task:event:', event.taskId, event.eventType) setTasks((prev) => prev.map((t) => { if (t.id !== event.taskId) return t const newEvent: TaskEvent = { id: Date.now(), taskId: event.taskId, eventType: event.eventType, payload: event.payload, createdAt: event.createdAt, replayed: event.replayed, } // Update task based on event type const updates: Partial<Task> = {} const payload = event.payload as Record<string, unknown> switch (event.eventType) { case 'started': updates.status = 'running' break case 'progress': updates.progress = (payload.progress as number) ?? t.progress updates.progressMessage = (payload.message as string) ?? t.progressMessage break case 'completed': updates.status = 'completed' updates.progress = 100 break case 'failed': updates.status = 'failed' updates.error = (payload.error as string) ?? 'Unknown error' break case 'cancelled': updates.status = 'cancelled' break } return { ...t, ...updates, events: [...t.events, newEvent], } }) ) } ) return () => { clearInterval(pollInterval) socket.disconnect() socketRef.current = null } }, [fetchTasks]) // Subscribe to active tasks when task list changes useEffect(() => { const activeTasks = tasks.filter((t) => t.status === 'pending' || t.status === 'running') activeTasks.forEach((task) => subscribeToTask(task.id)) }, [tasks, subscribeToTask]) // Fetch events on-demand when a task is selected useEffect(() => { if (!selectedTaskId) return const task = tasks.find((t) => t.id === selectedTaskId) // Only fetch if we don't already have events (e.g., from Socket.IO) if (task && task.events.length === 0) { fetch(`/api/admin/tasks?taskId=${selectedTaskId}`) .then((res) => res.json()) .then((data) => { if (data.task?.events) { setTasks((prev) => prev.map((t) => (t.id === selectedTaskId ? { ...t, events: data.task.events } : t)) ) } }) .catch(() => { // Silently fail — events are supplementary }) } }, [selectedTaskId, tasks]) // Derive unique task types for filter dropdown const taskTypes = Array.from(new Set(tasks.map((t) => t.type))).sort() // Filter tasks const filteredTasks = tasks.filter((t) => { if (statusFilter && t.status !== statusFilter) return false if (typeFilter && t.type !== typeFilter) return false return true }) // Failure stats (last 24h) const now24h = Date.now() - 24 * 60 * 60 * 1000 const recentTasks = tasks.filter((t) => new Date(t.createdAt).getTime() > now24h) const failureStats = taskTypes.map((type) => { const ofType = recentTasks.filter((t) => t.type === type) const failed = ofType.filter((t) => t.status === 'failed').length return { type, total: ofType.length, failed, rate: ofType.length > 0 ? failed / ofType.length : 0, } }) const selectedTask = selectedTaskId ? tasks.find((t) => t.id === selectedTaskId) : null const getStatusColor = (status: string) => { switch (status) { case 'pending': return '#888' case 'running': return '#2196F3' case 'completed': return '#4CAF50' case 'failed': return '#f44336' case 'cancelled': return '#FF9800' default: return '#888' } } const formatTime = (dateStr: string | null) => { if (!dateStr) return '-' const date = new Date(dateStr) return date.toLocaleTimeString() } const formatDuration = (start: string | null, end: string | null) => { if (!start) return '-' const startDate = new Date(start) const endDate = end ? new Date(end) : new Date() const ms = endDate.getTime() - startDate.getTime() const seconds = Math.floor(ms / 1000) if (seconds < 60) return `${seconds}s` const minutes = Math.floor(seconds / 60) return `${minutes}m ${seconds % 60}s` } if (loading) { return ( <div className={css({ minHeight: '100vh', backgroundColor: '#1a1a2e', color: '#eee' })}> <AppNavBar /> <div className={css({ paddingTop: '56px' })}> <AdminNav /> </div> <div className={css({ padding: '24px', fontFamily: 'monospace' })}>Loading tasks...</div> </div> ) } if (error) { return ( <div className={css({ minHeight: '100vh', backgroundColor: '#1a1a2e', color: '#eee' })}> <AppNavBar /> <div className={css({ paddingTop: '56px' })}> <AdminNav /> </div> <div className={css({ padding: '24px', fontFamily: 'monospace', color: '#f44336' })}> Error: {error} </div> </div> ) } // AdminNav height is ~54px, AppNavBar is 56px const headerHeight = 56 + 54 return ( <div className={css({ minHeight: '100vh', backgroundColor: '#1a1a2e', color: '#eee', })} > <AppNavBar /> <div className={css({ paddingTop: '56px' })}> <AdminNav /> </div> <div className={css({ display: 'flex', height: `calc(100vh - ${headerHeight}px)`, fontFamily: 'monospace', fontSize: '13px', })} > {/* Task List */} <div className={css({ width: '400px', borderRight: '1px solid #333', overflow: 'auto', })} > <div className={css({ padding: '12px 16px', borderBottom: '1px solid #333', backgroundColor: '#16213e', })} > <div className={css({ fontWeight: 'bold', fontSize: '14px' })}> Background Tasks ({filteredTasks.length} {filteredTasks.length !== tasks.length ? ` / ${tasks.length}` : ''}) </div> <div className={css({ fontSize: '11px', color: '#8b949e', marginTop: '4px' })}> Worksheet parsing, vision training, and other async jobs </div> {/* Filters */} <div className={css({ display: 'flex', gap: '8px', marginTop: '8px', })} > <select data-element="status-filter" value={statusFilter ?? ''} onChange={(e) => setStatusFilter(e.target.value || null)} className={css({ backgroundColor: '#0d1117', color: '#eee', border: '1px solid #333', borderRadius: '4px', padding: '4px 8px', fontSize: '11px', flex: 1, })} > <option value="">All statuses</option> <option value="pending">Pending</option> <option value="running">Running</option> <option value="completed">Completed</option> <option value="failed">Failed</option> <option value="cancelled">Cancelled</option> </select> <select data-element="type-filter" value={typeFilter ?? ''} onChange={(e) => setTypeFilter(e.target.value || null)} className={css({ backgroundColor: '#0d1117', color: '#eee', border: '1px solid #333', borderRadius: '4px', padding: '4px 8px', fontSize: '11px', flex: 1, })} > <option value="">All types</option> {taskTypes.map((type) => ( <option key={type} value={type}> {type} </option> ))} </select> </div> {/* Failure stats (24h) */} {failureStats.some((s) => s.total > 0) && ( <div className={css({ marginTop: '8px', padding: '6px 8px', backgroundColor: '#0d1117', borderRadius: '4px', fontSize: '10px', })} > <div className={css({ color: '#8b949e', marginBottom: '4px' })}> Last 24h failure rates: </div> {failureStats .filter((s) => s.total > 0) .map((s) => ( <div key={s.type} className={css({ display: 'flex', justifyContent: 'space-between', padding: '2px 0', })} > <span>{s.type}</span> <span className={css({ color: s.rate > 0.2 ? '#f44336' : s.rate > 0 ? '#FF9800' : '#4CAF50', })} > {s.failed}/{s.total} ({(s.rate * 100).toFixed(0)}%) </span> </div> ))} </div> )} </div> {filteredTasks.length === 0 ? ( <div className={css({ padding: '16px', color: '#888' })}> {tasks.length === 0 ? 'No tasks found' : 'No tasks match filters'} </div> ) : ( filteredTasks.map((task) => ( <div key={task.id} onClick={() => setSelectedTaskId(task.id)} className={css({ padding: '12px 16px', borderBottom: '1px solid #2a2a4a', cursor: 'pointer', backgroundColor: selectedTaskId === task.id ? '#2a2a5a' : 'transparent', '&:hover': { backgroundColor: '#2a2a4a', }, })} > <div className={css({ display: 'flex', justifyContent: 'space-between', marginBottom: '4px', })} > <span className={css({ fontWeight: 'bold' })}>{task.type}</span> <span className={css({ padding: '2px 8px', borderRadius: '4px', fontSize: '11px', backgroundColor: getStatusColor(task.status), color: 'white', })} > {task.status} </span> </div> <div className={css({ fontSize: '11px', color: '#888', marginBottom: '4px' })}> {task.id} </div> {(task.status === 'running' || task.status === 'pending') && ( <div className={css({ marginTop: '8px' })}> <div className={css({ height: '4px', backgroundColor: '#333', borderRadius: '2px', overflow: 'hidden', })} > <div className={css({ height: '100%', backgroundColor: '#2196F3', transition: 'width 0.3s', })} style={{ width: `${task.progress}%` }} /> </div> <div className={css({ fontSize: '10px', color: '#888', marginTop: '4px' })}> {task.progress}% - {task.progressMessage || 'Working...'} </div> </div> )} {task.error && ( <div className={css({ fontSize: '11px', color: '#f44336', marginTop: '4px' })}> {task.error} </div> )} <div className={css({ fontSize: '10px', color: '#666', marginTop: '4px' })}> {formatTime(task.createdAt)} | Duration:{' '} {formatDuration(task.startedAt, task.completedAt)} </div> </div> )) )} </div> {/* Task Details */} <div className={css({ flex: 1, overflow: 'auto' })}> {selectedTask ? ( <div className={css({ padding: '16px' })}> <h2 className={css({ marginBottom: '16px', fontSize: '18px' })}> Task: {selectedTask.type} </h2> <div className={css({ marginBottom: '24px' })}> <table className={css({ width: '100%', borderCollapse: 'collapse' })}> <tbody> <tr> <td className={css({ padding: '4px 8px', color: '#888', width: '120px' })}> ID </td> <td className={css({ padding: '4px 8px' })}>{selectedTask.id}</td> </tr> <tr> <td className={css({ padding: '4px 8px', color: '#888' })}>Status</td> <td className={css({ padding: '4px 8px' })}> <span className={css({ padding: '2px 8px', borderRadius: '4px', fontSize: '11px', backgroundColor: getStatusColor(selectedTask.status), color: 'white', })} > {selectedTask.status} </span> </td> </tr> <tr> <td className={css({ padding: '4px 8px', color: '#888' })}>Progress</td> <td className={css({ padding: '4px 8px' })}>{selectedTask.progress}%</td> </tr> <tr> <td className={css({ padding: '4px 8px', color: '#888' })}>Message</td> <td className={css({ padding: '4px 8px' })}> {selectedTask.progressMessage || '-'} </td> </tr> <tr> <td className={css({ padding: '4px 8px', color: '#888' })}>Created</td> <td className={css({ padding: '4px 8px' })}> {formatTime(selectedTask.createdAt)} </td> </tr> <tr> <td className={css({ padding: '4px 8px', color: '#888' })}>Started</td> <td className={css({ padding: '4px 8px' })}> {formatTime(selectedTask.startedAt)} </td> </tr> <tr> <td className={css({ padding: '4px 8px', color: '#888' })}>Completed</td> <td className={css({ padding: '4px 8px' })}> {formatTime(selectedTask.completedAt)} </td> </tr> <tr> <td className={css({ padding: '4px 8px', color: '#888' })}>Duration</td> <td className={css({ padding: '4px 8px' })}> {formatDuration(selectedTask.startedAt, selectedTask.completedAt)} </td> </tr> {selectedTask.error && ( <tr> <td className={css({ padding: '4px 8px', color: '#888' })}>Error</td> <td className={css({ padding: '4px 8px', color: '#f44336' })}> {selectedTask.error} </td> </tr> )} </tbody> </table> </div> <h3 className={css({ marginBottom: '12px', fontSize: '14px' })}> Events ({selectedTask.events.length}) </h3> <div className={css({ maxHeight: '60vh', overflow: 'auto', backgroundColor: '#0d1117', borderRadius: '8px', padding: '8px', })} > {selectedTask.events.length === 0 ? ( <div className={css({ padding: '16px', color: '#888' })}>No events yet</div> ) : ( selectedTask.events.map((event, index) => ( <div key={event.id || index} className={css({ padding: '8px 12px', borderBottom: '1px solid #21262d', '&:last-child': { borderBottom: 'none' }, })} > <div className={css({ display: 'flex', justifyContent: 'space-between', marginBottom: '4px', })} > <span className={css({ fontWeight: 'bold', color: getEventColor(event.eventType), })} > {event.eventType} {event.replayed && ( <span className={css({ color: '#888', fontWeight: 'normal', marginLeft: '8px', })} > (replayed) </span> )} </span> <span className={css({ fontSize: '10px', color: '#666' })}> {formatTime(event.createdAt)} </span> </div> <pre className={css({ fontSize: '11px', color: '#8b949e', margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-all', maxHeight: '200px', overflow: 'auto', })} > {formatPayload(event.payload)} </pre> </div> )) )} </div> </div> ) : ( <div className={css({ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%', color: '#888', })} > Select a task to view details </div> )} </div> </div> </div> ) } function getEventColor(eventType: string): string { switch (eventType) { case 'started': case 'parse_started': case 'parse_llm_started': case 'reparse_started': return '#2196F3' case 'progress': case 'parse_progress': case 'llm_progress': return '#888' case 'reasoning': return '#9c27b0' case 'output_delta': return '#ff9800' case 'problem_start': return '#00bcd4' case 'problem_complete': return '#8bc34a' case 'parse_complete': case 'reparse_complete': case 'completed': return '#4CAF50' case 'parse_error': case 'failed': case 'problem_error': return '#f44336' case 'cancelled': return '#FF9800' default: return '#888' } } function formatPayload(payload: unknown): string { if (payload === null || payload === undefined) return '-' try { const str = JSON.stringify(payload, null, 2) // Truncate very long strings (like base64 images) if (str.length > 2000) { return str.substring(0, 2000) + '\n... (truncated)' } return str } catch { return String(payload) } } |