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
« 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
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)
27from crackerjack.services import server_manager
29from .progress_components import JobDataCollector, TerminalRestorer
31if TYPE_CHECKING:
32 from textual.timer import Timer
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 }
45 MetricCard.critical {
46 border: solid $error;
47 color: $error;
48 }
50 MetricCard.warning {
51 border: solid $warning;
52 color: $warning;
53 }
55 MetricCard.success {
56 border: solid $success;
57 color: $success;
58 }
60 MetricCard.info {
61 border: solid $info;
62 color: $info;
63 }
64 """
66 value = reactive(" --")
67 label = reactive("Metric")
68 trend = reactive("")
69 status = reactive("")
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
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
93 def update_metric(self, value: str, trend: str = "", status: str = "") -> None:
94 self.value = value
95 self.trend = trend
96 self.status = status
98 self.remove_class("critical", "warning", "success", "info")
99 if status:
100 self.add_class(status)
103class SystemOverviewWidget(Static):
104 DEFAULT_CSS = """
105 SystemOverviewWidget {
106 height: 8;
107 border: solid $primary;
108 margin: 1;
109 }
110 """
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")
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")
127class JobsTableWidget(Static):
128 DEFAULT_CSS = """
129 JobsTableWidget {
130 height: 1fr;
131 border: solid $primary;
132 margin: 1;
133 }
134 """
136 def compose(self) -> ComposeResult:
137 with Container():
138 yield DataTable(id="jobs_table")
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
155class LogViewWidget(Static):
156 DEFAULT_CSS = """
157 LogViewWidget {
158 height: 1fr;
159 border: solid $primary;
160 margin: 1;
161 }
162 """
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")
173class AIAgentWidget(Static):
174 DEFAULT_CSS = """
175 AIAgentWidget {
176 height: 12;
177 border: solid $primary;
178 margin: 1;
179 }
180 """
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")
190 yield DataTable(id="agents_table")
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
199class PerformanceWidget(Static):
200 DEFAULT_CSS = """
201 PerformanceWidget {
202 height: 10;
203 border: solid $primary;
204 margin: 1;
205 }
206 """
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)
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")
222 yield Static(id="performance_chart")
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)
229 self._render_performance_chart()
231 def _render_performance_chart(self) -> None:
232 if not self.cpu_history:
233 return
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
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 )
243 chart_text = f"CPU: {cpu_line}\nMEM: {mem_line}"
245 chart = self.query_one("#performance_chart", Static)
246 chart.update(chart_text)
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 "▁"
269class CrackerjackDashboard(App):
270 TITLE = "Crackerjack Dashboard"
271 SUB_TITLE = "Comprehensive Project Monitoring"
273 CSS_PATH = None
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 ]
284 DEFAULT_CSS = """
285 Screen {
286 layout: vertical;
287 }
289 Header {
290 dock: top;
291 height: 3;
292 }
294 Footer {
295 dock: bottom;
296 height: 1;
297 }
299 .metrics_row {
300 height: 4;
301 margin: 0 1;
302 }
304 .status_row {
305 height: 4;
306 margin: 0 1;
307 }
308 """
310 def __init__(self, **kwargs) -> None:
311 super().__init__(**kwargs)
313 self.job_collector = JobDataCollector()
314 self.terminal_restorer = TerminalRestorer()
316 self.is_paused = False
317 self.debug_mode = False
318 self.last_refresh = time.time()
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 }
329 self.update_timer: Timer | None = None
331 def compose(self) -> ComposeResult:
332 yield Header()
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")
339 with TabPane("AI Agents", id="agents_tab"):
340 yield AIAgentWidget(id="ai_agent_widget")
342 with TabPane("Performance", id="performance_tab"):
343 yield PerformanceWidget(id="performance_widget")
345 with TabPane("Logs", id="logs_tab"):
346 yield LogViewWidget(id="log_widget")
348 yield Footer()
350 def on_mount(self) -> None:
351 self.log("Crackerjack Dashboard starting...")
353 self.update_timer = self.set_interval(2.0, self.update_dashboard)
355 self.call_later(self.initial_setup)
357 async def initial_setup(self) -> None:
358 try:
359 await self._check_server_status()
361 await self._load_jobs_data()
363 self.call_later(self.update_dashboard)
365 self.log("Dashboard initialized successfully")
367 except Exception as e:
368 self.log(f"Error during initial setup: {e}")
370 @work(exclusive=True)
371 async def update_dashboard(self) -> None:
372 if self.is_paused:
373 return
375 try:
376 current_time = time.time()
378 await self._update_system_metrics()
380 await self._update_jobs_data()
382 await self._update_agent_status()
384 await self._update_performance_metrics()
386 await self._update_logs()
388 self.last_refresh = current_time
390 except Exception as e:
391 self.log(f"Error updating dashboard: {e}")
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 )
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 )
410 except Exception as e:
411 self.log(f"Error checking server status: {e}")
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
422 async def _update_system_metrics(self) -> None:
423 try:
424 import psutil
426 cpu_percent = psutil.cpu_percent(interval=None)
427 memory = psutil.virtual_memory()
428 memory_mb = memory.used / (1024 * 1024)
430 cpu_metric = self.query_one("#cpu_metric", MetricCard)
431 memory_metric = self.query_one("#memory_metric", MetricCard)
433 cpu_metric.update_metric(f"{cpu_percent: .1f} % ")
434 memory_metric.update_metric(f"{memory_mb}MB")
436 self.performance_data["cpu"] = cpu_percent
437 self.performance_data["memory"] = memory_mb
439 except ImportError:
440 pass
441 except Exception as e:
442 self.log(f"Error updating system metrics: {e}")
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)
451 file_jobs = await self._collect_jobs_from_filesystem()
452 if file_jobs:
453 self.jobs_data.update(file_jobs)
455 except Exception as e:
456 self.log(f"Error loading jobs data: {e}")
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 {}
472 async def _collect_jobs_from_filesystem(self) -> dict[str, Any]:
473 try:
474 jobs = {}
476 import tempfile
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
494 return jobs
496 except Exception as e:
497 self.log(f"Error collecting filesystem jobs: {e}")
498 return {}
500 async def _update_jobs_data(self) -> None:
501 try:
502 table = self.query_one("#jobs_table", DataTable)
503 table.clear()
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))
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)
525 table.add_row(
526 job_id[:8],
527 status.title(),
528 stage,
529 f"{progress} % ",
530 started,
531 duration,
532 str(issues),
533 )
535 except Exception as e:
536 self.log(f"Error updating jobs data: {e}")
538 async def _update_agent_status(self) -> None:
539 try:
540 agents_table = self.query_one("#agents_table", DataTable)
541 agents_table.clear()
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)
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")
553 except Exception as e:
554 self.log(f"Error updating agent status: {e}")
556 async def _update_performance_metrics(self) -> None:
557 try:
558 performance_widget = self.query_one(
559 "#performance_widget",
560 PerformanceWidget,
561 )
563 cpu = self.performance_data.get("cpu", 0)
564 memory = self.performance_data.get("memory", 0)
565 jobs = len(self.jobs_data)
567 performance_widget.update_performance_data(cpu, memory, jobs)
569 avg_job_time = self.query_one("#avg_job_time", MetricCard)
570 success_rate = self.query_one("#success_rate", MetricCard)
572 avg_job_time.update_metric("0s")
573 success_rate.update_metric("100 % ")
575 except Exception as e:
576 self.log(f"Error updating performance metrics: {e}")
578 async def _update_logs(self) -> None:
579 try:
580 log_display = self.query_one("#log_display", Log)
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")
586 except Exception as e:
587 self.log(f"Error updating logs: {e}")
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"
598 def action_refresh(self) -> None:
599 self.call_later(self.update_dashboard)
600 self.log("Manual refresh triggered")
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}")
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}")
616 def action_toggle_servers(self) -> None:
617 self.log("Server toggle not implemented yet")
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'}")
623 async def on_exit(self) -> None:
624 if self.update_timer:
625 self.update_timer.stop()
627 self.terminal_restorer.restore_terminal()
629 self.log("Dashboard shutting down...")
632def run_dashboard() -> None:
633 app = CrackerjackDashboard()
634 app.run()
637if __name__ == "__main__":
638 run_dashboard()