Coverage for /Users/les/Projects/crackerjack/crackerjack/mcp/dashboard.py: 0%

354 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-09-03 15:39 -0700

1import time 

2from collections import deque 

3from datetime import datetime 

4from pathlib import Path 

5from typing import TYPE_CHECKING, Any 

6 

7import aiohttp 

8from rich.text import Text 

9from textual import work 

10from textual.app import App, ComposeResult 

11from textual.containers import ( 

12 Container, 

13 Horizontal, 

14) 

15from textual.reactive import reactive 

16from textual.widgets import ( 

17 Button, 

18 DataTable, 

19 Footer, 

20 Header, 

21 Log, 

22 Static, 

23 TabbedContent, 

24 TabPane, 

25) 

26 

27from crackerjack.services import server_manager 

28 

29from .progress_components import JobDataCollector, TerminalRestorer 

30 

31if TYPE_CHECKING: 

32 from textual.timer import Timer 

33 

34 

35class MetricCard(Static): 

36 DEFAULT_CSS = """ 

37 MetricCard { 

38 width: 1fr; 

39 height: 4; 

40 border: solid $primary; 

41 padding: 0 1; 

42 margin: 0 1; 

43 } 

44 

45 MetricCard.critical { 

46 border: solid $error; 

47 color: $error; 

48 } 

49 

50 MetricCard.warning { 

51 border: solid $warning; 

52 color: $warning; 

53 } 

54 

55 MetricCard.success { 

56 border: solid $success; 

57 color: $success; 

58 } 

59 

60 MetricCard.info { 

61 border: solid $info; 

62 color: $info; 

63 } 

64 """ 

65 

66 value = reactive(" --") 

67 label = reactive("Metric") 

68 trend = reactive("") 

69 status = reactive("") 

70 

71 def __init__( 

72 self, 

73 label: str, 

74 value: str = " --", 

75 trend: str = "", 

76 status: str = "", 

77 **kwargs, 

78 ) -> None: 

79 super().__init__(**kwargs) 

80 self.label = label 

81 self.value = value 

82 self.trend = trend 

83 self.status = status 

84 

85 def render(self) -> Text: 

86 text = Text() 

87 text.append(f"{self.label}\n", style="dim") 

88 text.append(str(self.value), style="bold") 

89 if self.trend: 

90 text.append(f" {self.trend}", style="green" if "↑" in self.trend else "red") 

91 return text 

92 

93 def update_metric(self, value: str, trend: str = "", status: str = "") -> None: 

94 self.value = value 

95 self.trend = trend 

96 self.status = status 

97 

98 self.remove_class("critical", "warning", "success", "info") 

99 if status: 

100 self.add_class(status) 

101 

102 

103class SystemOverviewWidget(Static): 

104 DEFAULT_CSS = """ 

105 SystemOverviewWidget { 

106 height: 8; 

107 border: solid $primary; 

108 margin: 1; 

109 } 

110 """ 

111 

112 def compose(self) -> ComposeResult: 

113 with Container(id="system_overview"): 

114 with Horizontal(classes="metrics_row"): 

115 yield MetricCard("CPU", "0 % ", id="cpu_metric") 

116 yield MetricCard("Memory", "0MB", id="memory_metric") 

117 yield MetricCard("Active Jobs", "0", id="jobs_metric") 

118 yield MetricCard("Queue Depth", "0", id="queue_metric") 

119 

120 with Horizontal(classes="status_row"): 

121 yield MetricCard("MCP Server", "Stopped", id="mcp_status") 

122 yield MetricCard("WebSocket", "Stopped", id="websocket_status") 

123 yield MetricCard("AI Agent", "Idle", id="agent_status") 

124 yield MetricCard("Last Run", "Never", id="last_run") 

125 

126 

127class JobsTableWidget(Static): 

128 DEFAULT_CSS = """ 

129 JobsTableWidget { 

130 height: 1fr; 

131 border: solid $primary; 

132 margin: 1; 

133 } 

134 """ 

135 

136 def compose(self) -> ComposeResult: 

137 with Container(): 

138 yield DataTable(id="jobs_table") 

139 

140 def on_mount(self) -> None: 

141 table = self.query_one("#jobs_table", DataTable) 

142 table.add_columns( 

143 "Job ID", 

144 "Status", 

145 "Stage", 

146 "Progress", 

147 "Started", 

148 "Duration", 

149 "Issues", 

150 ) 

151 table.zebra_stripes = True 

152 table.show_header = True 

153 

154 

155class LogViewWidget(Static): 

156 DEFAULT_CSS = """ 

157 LogViewWidget { 

158 height: 1fr; 

159 border: solid $primary; 

160 margin: 1; 

161 } 

162 """ 

163 

164 def compose(self) -> ComposeResult: 

165 with Container(): 

166 with Horizontal(id="log_controls"): 

167 yield Button("Clear", id="clear_logs") 

168 yield Button("Pause", id="pause_logs") 

169 yield Button("Export", id="export_logs") 

170 yield Log(id="log_display") 

171 

172 

173class AIAgentWidget(Static): 

174 DEFAULT_CSS = """ 

175 AIAgentWidget { 

176 height: 12; 

177 border: solid $primary; 

178 margin: 1; 

179 } 

180 """ 

181 

182 def compose(self) -> ComposeResult: 

183 with Container(): 

184 with Horizontal(classes="agent_metrics"): 

185 yield MetricCard("Active Agents", "0", id="active_agents") 

186 yield MetricCard("Issues Fixed", "0", "↑", id="issues_fixed") 

187 yield MetricCard("Avg Confidence", "0 % ", id="avg_confidence") 

188 yield MetricCard("Cache Hits", "0", id="cache_hits") 

189 

190 yield DataTable(id="agents_table") 

191 

192 def on_mount(self) -> None: 

193 table = self.query_one("#agents_table", DataTable) 

194 table.add_columns("Agent", "Type", "Status", "Confidence", "Fixed", "Runtime") 

195 table.zebra_stripes = True 

196 table.show_header = True 

197 

198 

199class PerformanceWidget(Static): 

200 DEFAULT_CSS = """ 

201 PerformanceWidget { 

202 height: 10; 

203 border: solid $primary; 

204 margin: 1; 

205 } 

206 """ 

207 

208 def __init__(self, **kwargs) -> None: 

209 super().__init__(**kwargs) 

210 self.cpu_history: deque[float] = deque(maxlen=50) 

211 self.memory_history: deque[float] = deque(maxlen=50) 

212 self.job_history: deque[int] = deque(maxlen=50) 

213 

214 def compose(self) -> ComposeResult: 

215 with Container(): 

216 with Horizontal(): 

217 yield MetricCard("Avg Job Time", "0s", id="avg_job_time") 

218 yield MetricCard("Success Rate", "100 % ", id="success_rate") 

219 yield MetricCard("Error Rate", "0 % ", id="error_rate") 

220 yield MetricCard("Throughput", "0 j / h", id="throughput") 

221 

222 yield Static(id="performance_chart") 

223 

224 def update_performance_data(self, cpu: float, memory: float, jobs: int) -> None: 

225 self.cpu_history.append(cpu) 

226 self.memory_history.append(memory) 

227 self.job_history.append(jobs) 

228 

229 self._render_performance_chart() 

230 

231 def _render_performance_chart(self) -> None: 

232 if not self.cpu_history: 

233 return 

234 

235 max_cpu = max(self.cpu_history) if self.cpu_history else 1 

236 max_mem = max(self.memory_history) if self.memory_history else 1 

237 

238 cpu_line = "".join(self._get_bar_char(val, max_cpu) for val in self.cpu_history) 

239 mem_line = "".join( 

240 self._get_bar_char(val, max_mem) for val in self.memory_history 

241 ) 

242 

243 chart_text = f"CPU: {cpu_line}\nMEM: {mem_line}" 

244 

245 chart = self.query_one("#performance_chart", Static) 

246 chart.update(chart_text) 

247 

248 def _get_bar_char(self, value: float, max_value: float) -> str: 

249 if max_value == 0: 

250 return "▁" 

251 ratio = value / max_value 

252 if ratio >= 0.875: 

253 return "█" 

254 if ratio >= 0.75: 

255 return "▇" 

256 if ratio >= 0.625: 

257 return "▆" 

258 if ratio >= 0.5: 

259 return "▅" 

260 if ratio >= 0.375: 

261 return "▄" 

262 if ratio >= 0.25: 

263 return "▃" 

264 if ratio >= 0.125: 

265 return "▂" 

266 return "▁" 

267 

268 

269class CrackerjackDashboard(App): 

270 TITLE = "Crackerjack Dashboard" 

271 SUB_TITLE = "Comprehensive Project Monitoring" 

272 

273 CSS_PATH = None 

274 

275 BINDINGS = [ 

276 ("q", "quit", "Quit"), 

277 ("r", "refresh", "Refresh"), 

278 ("c", "clear_logs", "Clear Logs"), 

279 ("p", "pause_logs", "Pause / Resume Logs"), 

280 ("s", "toggle_servers", "Start / Stop Servers"), 

281 ("d", "toggle_debug", "Debug Mode"), 

282 ] 

283 

284 DEFAULT_CSS = """ 

285 Screen { 

286 layout: vertical; 

287 } 

288 

289 Header { 

290 dock: top; 

291 height: 3; 

292 } 

293 

294 Footer { 

295 dock: bottom; 

296 height: 1; 

297 } 

298 

299 .metrics_row { 

300 height: 4; 

301 margin: 0 1; 

302 } 

303 

304 .status_row { 

305 height: 4; 

306 margin: 0 1; 

307 } 

308 """ 

309 

310 def __init__(self, **kwargs) -> None: 

311 super().__init__(**kwargs) 

312 

313 self.job_collector = JobDataCollector() 

314 self.terminal_restorer = TerminalRestorer() 

315 

316 self.is_paused = False 

317 self.debug_mode = False 

318 self.last_refresh = time.time() 

319 

320 self.jobs_data: dict[str, Any] = {} 

321 self.logs_buffer: list[str] = [] 

322 self.performance_data = { 

323 "cpu": 0.0, 

324 "memory": 0.0, 

325 "jobs": 0, 

326 "success_rate": 100.0, 

327 } 

328 

329 self.update_timer: Timer | None = None 

330 

331 def compose(self) -> ComposeResult: 

332 yield Header() 

333 

334 with TabbedContent(id="main_tabs"): 

335 with TabPane("Overview", id="overview_tab"): 

336 yield SystemOverviewWidget(id="system_overview") 

337 yield JobsTableWidget(id="jobs_widget") 

338 

339 with TabPane("AI Agents", id="agents_tab"): 

340 yield AIAgentWidget(id="ai_agent_widget") 

341 

342 with TabPane("Performance", id="performance_tab"): 

343 yield PerformanceWidget(id="performance_widget") 

344 

345 with TabPane("Logs", id="logs_tab"): 

346 yield LogViewWidget(id="log_widget") 

347 

348 yield Footer() 

349 

350 def on_mount(self) -> None: 

351 self.log("Crackerjack Dashboard starting...") 

352 

353 self.update_timer = self.set_interval(2.0, self.update_dashboard) 

354 

355 self.call_later(self.initial_setup) 

356 

357 async def initial_setup(self) -> None: 

358 try: 

359 await self._check_server_status() 

360 

361 await self._load_jobs_data() 

362 

363 self.call_later(self.update_dashboard) 

364 

365 self.log("Dashboard initialized successfully") 

366 

367 except Exception as e: 

368 self.log(f"Error during initial setup: {e}") 

369 

370 @work(exclusive=True) 

371 async def update_dashboard(self) -> None: 

372 if self.is_paused: 

373 return 

374 

375 try: 

376 current_time = time.time() 

377 

378 await self._update_system_metrics() 

379 

380 await self._update_jobs_data() 

381 

382 await self._update_agent_status() 

383 

384 await self._update_performance_metrics() 

385 

386 await self._update_logs() 

387 

388 self.last_refresh = current_time 

389 

390 except Exception as e: 

391 self.log(f"Error updating dashboard: {e}") 

392 

393 async def _check_server_status(self) -> None: 

394 try: 

395 mcp_processes = server_manager.find_mcp_server_processes() 

396 mcp_running = len(mcp_processes) > 0 

397 mcp_metric = self.query_one("#mcp_status", MetricCard) 

398 mcp_metric.update_metric( 

399 "Running" if mcp_running else "Stopped", 

400 status="success" if mcp_running else "critical", 

401 ) 

402 

403 ws_running = await self._check_websocket_server() 

404 ws_metric = self.query_one("#websocket_status", MetricCard) 

405 ws_metric.update_metric( 

406 "Running" if ws_running else "Stopped", 

407 status="success" if ws_running else "critical", 

408 ) 

409 

410 except Exception as e: 

411 self.log(f"Error checking server status: {e}") 

412 

413 async def _check_websocket_server(self) -> bool: 

414 try: 

415 timeout = aiohttp.ClientTimeout(total=5.0) 

416 async with aiohttp.ClientSession(timeout=timeout) as session: 

417 async with session.get("http: / / localhost: 8675 /") as response: 

418 return response.status == 200 

419 except Exception: 

420 return False 

421 

422 async def _update_system_metrics(self) -> None: 

423 try: 

424 import psutil 

425 

426 cpu_percent = psutil.cpu_percent(interval=None) 

427 memory = psutil.virtual_memory() 

428 memory_mb = memory.used / (1024 * 1024) 

429 

430 cpu_metric = self.query_one("#cpu_metric", MetricCard) 

431 memory_metric = self.query_one("#memory_metric", MetricCard) 

432 

433 cpu_metric.update_metric(f"{cpu_percent: .1f} % ") 

434 memory_metric.update_metric(f"{memory_mb}MB") 

435 

436 self.performance_data["cpu"] = cpu_percent 

437 self.performance_data["memory"] = memory_mb 

438 

439 except ImportError: 

440 pass 

441 except Exception as e: 

442 self.log(f"Error updating system metrics: {e}") 

443 

444 async def _load_jobs_data(self) -> None: 

445 try: 

446 if await self._check_websocket_server(): 

447 jobs_data = await self._fetch_jobs_from_websocket() 

448 if jobs_data: 

449 self.jobs_data.update(jobs_data) 

450 

451 file_jobs = await self._collect_jobs_from_filesystem() 

452 if file_jobs: 

453 self.jobs_data.update(file_jobs) 

454 

455 except Exception as e: 

456 self.log(f"Error loading jobs data: {e}") 

457 

458 async def _fetch_jobs_from_websocket(self) -> dict[str, Any]: 

459 try: 

460 timeout = aiohttp.ClientTimeout(total=10.0) 

461 async with aiohttp.ClientSession(timeout=timeout) as session: 

462 async with session.get( 

463 "http: / / localhost: 8675 / api / jobs" 

464 ) as response: 

465 if response.status == 200: 

466 return await response.json() 

467 return {} 

468 except Exception as e: 

469 self.log(f"Error fetching WebSocket jobs: {e}") 

470 return {} 

471 

472 async def _collect_jobs_from_filesystem(self) -> dict[str, Any]: 

473 try: 

474 jobs = {} 

475 

476 import tempfile 

477 

478 temp_dir = Path(tempfile.gettempdir()) 

479 debug_files = temp_dir.glob("crackerjack - debug-*.log") 

480 for debug_file in debug_files: 

481 try: 

482 if debug_file.stat().st_mtime > (time.time() - 3600): 

483 debug_file.read_text() 

484 job_id = debug_file.stem.replace("crackerjack-debug -", "") 

485 jobs[job_id] = { 

486 "id": job_id, 

487 "status": "completed", 

488 "log_file": str(debug_file), 

489 "timestamp": debug_file.stat().st_mtime, 

490 } 

491 except Exception: 

492 continue 

493 

494 return jobs 

495 

496 except Exception as e: 

497 self.log(f"Error collecting filesystem jobs: {e}") 

498 return {} 

499 

500 async def _update_jobs_data(self) -> None: 

501 try: 

502 table = self.query_one("#jobs_table", DataTable) 

503 table.clear() 

504 

505 active_count = len( 

506 [j for j in self.jobs_data.values() if j.get("status") != "completed"], 

507 ) 

508 jobs_metric = self.query_one("#jobs_metric", MetricCard) 

509 jobs_metric.update_metric(str(active_count)) 

510 

511 for job_id, job_data in sorted( 

512 self.jobs_data.items(), 

513 key=lambda x: x[1].get("timestamp", 0), 

514 reverse=True, 

515 ): 

516 status = job_data.get("status", "unknown") 

517 stage = job_data.get("current_stage", "N / A") 

518 progress = job_data.get("progress", 0) 

519 started = datetime.fromtimestamp(job_data.get("timestamp", 0)).strftime( 

520 "% H: % M: % S", 

521 ) 

522 duration = self._format_duration(job_data.get("duration", 0)) 

523 issues = job_data.get("issues_found", 0) 

524 

525 table.add_row( 

526 job_id[:8], 

527 status.title(), 

528 stage, 

529 f"{progress} % ", 

530 started, 

531 duration, 

532 str(issues), 

533 ) 

534 

535 except Exception as e: 

536 self.log(f"Error updating jobs data: {e}") 

537 

538 async def _update_agent_status(self) -> None: 

539 try: 

540 agents_table = self.query_one("#agents_table", DataTable) 

541 agents_table.clear() 

542 

543 active_agents_metric = self.query_one("#active_agents", MetricCard) 

544 issues_fixed_metric = self.query_one("#issues_fixed", MetricCard) 

545 avg_confidence_metric = self.query_one("#avg_confidence", MetricCard) 

546 cache_hits_metric = self.query_one("#cache_hits", MetricCard) 

547 

548 active_agents_metric.update_metric("0") 

549 issues_fixed_metric.update_metric("0") 

550 avg_confidence_metric.update_metric("0 % ") 

551 cache_hits_metric.update_metric("0") 

552 

553 except Exception as e: 

554 self.log(f"Error updating agent status: {e}") 

555 

556 async def _update_performance_metrics(self) -> None: 

557 try: 

558 performance_widget = self.query_one( 

559 "#performance_widget", 

560 PerformanceWidget, 

561 ) 

562 

563 cpu = self.performance_data.get("cpu", 0) 

564 memory = self.performance_data.get("memory", 0) 

565 jobs = len(self.jobs_data) 

566 

567 performance_widget.update_performance_data(cpu, memory, jobs) 

568 

569 avg_job_time = self.query_one("#avg_job_time", MetricCard) 

570 success_rate = self.query_one("#success_rate", MetricCard) 

571 

572 avg_job_time.update_metric("0s") 

573 success_rate.update_metric("100 % ") 

574 

575 except Exception as e: 

576 self.log(f"Error updating performance metrics: {e}") 

577 

578 async def _update_logs(self) -> None: 

579 try: 

580 log_display = self.query_one("#log_display", Log) 

581 

582 current_time = datetime.now().strftime("% H: % M: % S") 

583 if len(self.logs_buffer) % 10 == 0: 

584 log_display.write_line(f"[{current_time}] Dashboard refresh completed") 

585 

586 except Exception as e: 

587 self.log(f"Error updating logs: {e}") 

588 

589 def _format_duration(self, seconds: float) -> str: 

590 if seconds < 60: 

591 return f"{seconds: .1f}s" 

592 if seconds < 3600: 

593 minutes = seconds / 60 

594 return f"{minutes: .1f}m" 

595 hours = seconds / 3600 

596 return f"{hours: .1f}h" 

597 

598 def action_refresh(self) -> None: 

599 self.call_later(self.update_dashboard) 

600 self.log("Manual refresh triggered") 

601 

602 def action_clear_logs(self) -> None: 

603 try: 

604 log_display = self.query_one("#log_display", Log) 

605 log_display.clear() 

606 self.logs_buffer.clear() 

607 self.log("Logs cleared") 

608 except Exception as e: 

609 self.log(f"Error clearing logs: {e}") 

610 

611 def action_pause_logs(self) -> None: 

612 self.is_paused = not self.is_paused 

613 status = "paused" if self.is_paused else "resumed" 

614 self.log(f"Dashboard updates {status}") 

615 

616 def action_toggle_servers(self) -> None: 

617 self.log("Server toggle not implemented yet") 

618 

619 def action_toggle_debug(self) -> None: 

620 self.debug_mode = not self.debug_mode 

621 self.log(f"Debug mode {'enabled' if self.debug_mode else 'disabled'}") 

622 

623 async def on_exit(self) -> None: 

624 if self.update_timer: 

625 self.update_timer.stop() 

626 

627 self.terminal_restorer.restore_terminal() 

628 

629 self.log("Dashboard shutting down...") 

630 

631 

632def run_dashboard() -> None: 

633 app = CrackerjackDashboard() 

634 app.run() 

635 

636 

637if __name__ == "__main__": 

638 run_dashboard()