Coverage for /Users/les/Projects/crackerjack/crackerjack/mcp/progress_components.py: 0%
280 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 asyncio
2import json
3import subprocess
4import tempfile
5import time
6from contextlib import suppress
7from pathlib import Path
8from typing import Any
10import aiohttp
11from rich.console import Console
13from crackerjack.core.timeout_manager import TimeoutStrategy, get_timeout_manager
16class JobDataCollector:
17 def __init__(self, progress_dir: Path, websocket_url: str) -> None:
18 self.progress_dir = progress_dir
19 self.websocket_url = websocket_url
20 self.console = Console()
22 async def discover_jobs(self) -> dict[str, Any]:
23 jobs_data = self._init_jobs_data()
25 websocket_jobs = await self._discover_jobs_websocket()
26 if websocket_jobs and websocket_jobs["total"] > 0:
27 return {"method": "WebSocket", "data": websocket_jobs}
29 filesystem_jobs = await self._discover_jobs_filesystem(jobs_data)
30 return {"method": "File", "data": filesystem_jobs}
32 def _init_jobs_data(self) -> dict[str, Any]:
33 return {
34 "active": 0,
35 "completed": 0,
36 "failed": 0,
37 "total": 0,
38 "individual_jobs": [],
39 "total_issues": 0,
40 "errors_fixed": 0,
41 "errors_failed": 0,
42 "current_errors": 0,
43 }
45 async def _discover_jobs_filesystem(
46 self,
47 jobs_data: dict[str, Any],
48 ) -> dict[str, Any]:
49 with suppress(Exception):
50 if not self.progress_dir.exists():
51 return jobs_data
53 for progress_file in self.progress_dir.glob("job-* .json"):
54 self._process_progress_file(progress_file, jobs_data)
56 return jobs_data
58 def _process_progress_file(
59 self,
60 progress_file: Path,
61 jobs_data: dict[str, Any],
62 ) -> None:
63 with suppress(json.JSONDecodeError, OSError):
64 with progress_file.open() as f:
65 data = json.load(f)
67 job_id = progress_file.stem.replace("job-", "")
68 self._update_job_counters(data, jobs_data)
69 self._aggregate_error_metrics(data, jobs_data)
70 self._add_individual_job(job_id, data, jobs_data)
72 def _update_job_counters(
73 self,
74 data: dict[str, Any],
75 jobs_data: dict[str, Any],
76 ) -> None:
77 status = data.get("status", "unknown")
78 if status == "running":
79 jobs_data["active"] += 1
80 elif status == "completed":
81 jobs_data["completed"] += 1
82 elif status == "failed":
83 jobs_data["failed"] += 1
84 jobs_data["total"] += 1
86 def _aggregate_error_metrics(
87 self,
88 data: dict[str, Any],
89 jobs_data: dict[str, Any],
90 ) -> None:
91 jobs_data["total_issues"] += data.get("total_issues", 0)
92 jobs_data["errors_fixed"] += data.get("errors_fixed", 0)
93 jobs_data["errors_failed"] += data.get("errors_failed", 0)
95 current_errors_data = data.get("current_errors", {})
96 current_errors = (
97 current_errors_data.get("total", 0)
98 if isinstance(current_errors_data, dict)
99 else 0
100 )
101 jobs_data["current_errors"] += current_errors
103 def _add_individual_job(
104 self,
105 job_id: str,
106 data: dict[str, Any],
107 jobs_data: dict[str, Any],
108 ) -> None:
109 status = data.get("status", "unknown")
110 stage = data.get("current_stage", "Unknown")
111 iteration = data.get("iteration", 0)
112 max_iterations = data.get("max_iterations", 10)
114 status_emoji = {
115 "running": "🚀 Running",
116 "completed": "✅ Done",
117 }.get(status, "❌ Error")
119 jobs_data["individual_jobs"].append(
120 {
121 "job_id": job_id[:8],
122 "full_job_id": job_id,
123 "project": data.get("project_name", "crackerjack"),
124 "stage": stage,
125 "progress": f"{iteration} / {max_iterations}",
126 "status": status_emoji,
127 "iteration": iteration,
128 "max_iterations": max_iterations,
129 "message": data.get("message", "Processing job..."),
130 "errors": data.get("errors", []),
131 "hook_failures": data.get("hook_failures", []),
132 "test_failures": data.get("test_failures", []),
133 "total_issues": data.get("total_issues", 0),
134 "errors_fixed": data.get("errors_fixed", 0),
135 "errors_failed": data.get("errors_failed", 0),
136 "current_errors": data.get("current_errors", {}),
137 },
138 )
140 async def _discover_jobs_websocket(self) -> dict[str, Any]:
141 jobs_data = {
142 "active": 0,
143 "completed": 0,
144 "failed": 0,
145 "total": 0,
146 "individual_jobs": [],
147 "total_issues": 0,
148 "errors_fixed": 0,
149 "errors_failed": 0,
150 "current_errors": 0,
151 }
153 timeout_manager = get_timeout_manager()
155 try:
156 async with timeout_manager.timeout_context(
157 "network_operations",
158 timeout=5.0, # Short timeout for websocket discovery
159 strategy=TimeoutStrategy.FAIL_FAST,
160 ):
161 websocket_base = self.websocket_url.replace("ws://", "http://").replace(
162 "wss://",
163 "https://",
164 )
166 async with (
167 aiohttp.ClientSession(
168 timeout=aiohttp.ClientTimeout(total=3),
169 ) as session,
170 session.get(f"{websocket_base}/") as response,
171 ):
172 if response.status == 200:
173 data = await response.json()
175 active_jobs = data.get("active_jobs_detailed", [])
177 for job in active_jobs:
178 job_id = job.get("job_id", "unknown")
179 status = job.get("status", "unknown")
181 if status == "running":
182 jobs_data["active"] += 1
183 elif status == "completed":
184 jobs_data["completed"] += 1
185 elif status == "failed":
186 jobs_data["failed"] += 1
188 jobs_data["total"] += 1
190 job_entry = {
191 "job_id": job_id,
192 "status": status,
193 "iteration": job.get("iteration", 1),
194 "max_iterations": job.get("max_iterations", 10),
195 "current_stage": job.get("current_stage", "unknown"),
196 "message": job.get("message", "Processing..."),
197 "project": job.get("project", "crackerjack"),
198 "total_issues": job.get("total_issues", 0),
199 "errors_fixed": job.get("errors_fixed", 0),
200 "errors_failed": job.get("errors_failed", 0),
201 "current_errors": job.get("current_errors", 0),
202 "overall_progress": job.get("overall_progress", 0.0),
203 "stage_progress": job.get("stage_progress", 0.0),
204 }
205 jobs_data["individual_jobs"].append(job_entry)
207 jobs_data["total_issues"] += job.get("total_issues", 0)
208 jobs_data["errors_fixed"] += job.get("errors_fixed", 0)
209 jobs_data["errors_failed"] += job.get("errors_failed", 0)
211 except Exception:
212 # Return empty data on timeout or error - fail gracefully
213 pass
215 return jobs_data
218class ServiceHealthChecker:
219 def __init__(self) -> None:
220 self.console = Console()
222 async def collect_services_data(self) -> list[tuple[str, str, str]]:
223 services = []
225 services.extend(
226 (
227 await self._check_websocket_server(),
228 self._check_mcp_server(),
229 ),
230 )
232 services.extend(
233 (
234 self._check_service_watchdog(),
235 ("File Monitor", "🟢 Watching", "0"),
236 ),
237 )
239 return services
241 async def _check_websocket_server(self) -> tuple[str, str, str]:
242 timeout_manager = get_timeout_manager()
244 try:
245 async with timeout_manager.timeout_context(
246 "network_operations",
247 timeout=3.0, # Quick health check timeout
248 strategy=TimeoutStrategy.FAIL_FAST,
249 ):
250 async with (
251 aiohttp.ClientSession(
252 timeout=aiohttp.ClientTimeout(total=2),
253 ) as session,
254 session.get("http://localhost:8675/") as response,
255 ):
256 if response.status == 200:
257 data = await response.json()
258 connections = data.get("total_connections", 0)
259 len(data.get("active_jobs", []))
260 return (
261 "WebSocket Server",
262 f"🟢 Active ({connections} conn)",
263 "0",
264 )
265 return ("WebSocket Server", "🔴 HTTP Error", "1")
266 except Exception:
267 return ("WebSocket Server", "🔴 Connection Failed", "1")
269 def _check_mcp_server(self) -> tuple[str, str, str]:
270 try:
271 result = subprocess.run(
272 ["pgrep", "-f", "crackerjack.*mcp"],
273 check=False,
274 capture_output=True,
275 text=True,
276 timeout=5.0, # Add timeout protection
277 )
278 if result.returncode == 0:
279 return ("MCP Server", "🟢 Process Active", "0")
280 return ("MCP Server", "🔴 No Process", "0")
281 except subprocess.TimeoutExpired:
282 return ("MCP Server", "🔴 Process Check Timeout", "0")
283 except Exception:
284 return ("MCP Server", "🔴 Check Failed", "0")
286 def _check_service_watchdog(self) -> tuple[str, str, str]:
287 try:
288 result = subprocess.run(
289 ["pgrep", "-f", "crackerjack.*watchdog"],
290 check=False,
291 capture_output=True,
292 text=True,
293 timeout=5.0, # Add timeout protection
294 )
295 if result.returncode == 0:
296 return ("Service Watchdog", "🟢 Active", "0")
297 return ("Service Watchdog", "🔴 Inactive", "0")
298 except subprocess.TimeoutExpired:
299 return ("Service Watchdog", "🔴 Process Check Timeout", "0")
300 except Exception:
301 return ("Service Watchdog", "🔴 Check Failed", "0")
304class ErrorCollector:
305 def __init__(self) -> None:
306 self.console = Console()
308 async def collect_recent_errors(self) -> list[tuple[str, str, str, str]]:
309 errors = []
311 errors.extend(self._check_debug_logs())
313 errors.extend(self._check_crackerjack_logs())
315 if not errors:
316 errors = [
317 (
318 time.strftime(" % H: % M: % S"),
319 "system",
320 "No recent errors found",
321 "Clean",
322 ),
323 (" - - : - - : --", "monitor", "System monitoring active", "Status"),
324 ]
326 return errors[-5:]
328 def _check_debug_logs(self) -> list[tuple[str, str, str, str]]:
329 errors = []
331 with suppress(Exception):
332 debug_log = Path(tempfile.gettempdir()) / "tui_debug.log"
333 if debug_log.exists():
334 errors = self._extract_debug_log_errors(debug_log)
336 return errors
338 def _extract_debug_log_errors(
339 self,
340 debug_log: Path,
341 ) -> list[tuple[str, str, str, str]]:
342 errors = []
344 with debug_log.open() as f:
345 lines = f.readlines()[-10:]
347 for line in lines:
348 if self._is_debug_error_line(line):
349 error_entry = self._parse_debug_error_line(line)
350 if error_entry:
351 errors.append(error_entry)
353 return errors
355 def _is_debug_error_line(self, line: str) -> bool:
356 return any(indicator in line for indicator in ("ERROR", "Exception", "Failed"))
358 def _parse_debug_error_line(self, line: str) -> tuple[str, str, str, str] | None:
359 parts = line.strip().split(" ", 2)
360 if len(parts) < 3:
361 return None
363 timestamp = parts[0]
364 error_msg = self._truncate_debug_message(parts[2])
365 return (timestamp, "debug", error_msg, "System")
367 def _truncate_debug_message(self, message: str) -> str:
368 return message[:40] + "..." if len(message) > 40 else message
370 def _check_crackerjack_logs(self) -> list[tuple[str, str, str, str]]:
371 errors = []
373 with suppress(Exception):
374 for log_file in Path(tempfile.gettempdir()).glob(
375 "crackerjack - debug-*.log"
376 ):
377 if self._is_log_file_recent(log_file):
378 errors.extend(self._extract_errors_from_log_file(log_file))
380 return errors
382 def _is_log_file_recent(self, log_file: Path) -> bool:
383 return time.time() - log_file.stat().st_mtime < 3600
385 def _extract_errors_from_log_file(
386 self,
387 log_file: Path,
388 ) -> list[tuple[str, str, str, str]]:
389 errors = []
391 with log_file.open() as f:
392 lines = f.readlines()[-5:]
394 for line in lines:
395 if self._is_error_line(line):
396 error_entry = self._create_error_entry(line, log_file)
397 errors.append(error_entry)
399 return errors
401 def _is_error_line(self, line: str) -> bool:
402 return any(
403 keyword in line.lower() for keyword in ("error", "failed", "exception")
404 )
406 def _create_error_entry(
407 self,
408 line: str,
409 log_file: Path,
410 ) -> tuple[str, str, str, str]:
411 timestamp = time.strftime(
412 " % H: % M: % S",
413 time.localtime(log_file.stat().st_mtime),
414 )
415 error_msg = self._truncate_error_message(line.strip())
416 return (timestamp, "job", error_msg, "Crackerjack")
418 def _truncate_error_message(self, message: str) -> str:
419 return message[:50] + "..." if len(message) > 50 else message
422class ServiceManager:
423 def __init__(self) -> None:
424 self.started_services: list[tuple[str, subprocess.Popen]] = []
425 self.console = Console()
427 async def ensure_services_running(self) -> None:
428 with suppress(Exception):
429 websocket_running = await self._check_websocket_server()
430 mcp_running = self._check_mcp_server()
432 self._cleanup_dead_services()
434 if not websocket_running:
435 await self._start_websocket_server()
437 if not mcp_running:
438 await self._start_mcp_server()
440 await self._start_service_watchdog()
442 def _cleanup_dead_services(self) -> None:
443 self.started_services = [
444 (service_name, process)
445 for service_name, process in self.started_services
446 if process.poll() is None
447 ]
449 async def _check_websocket_server(self) -> bool:
450 timeout_manager = get_timeout_manager()
452 try:
453 async with timeout_manager.timeout_context(
454 "network_operations",
455 timeout=3.0, # Quick check timeout
456 strategy=TimeoutStrategy.FAIL_FAST,
457 ):
458 async with aiohttp.ClientSession(
459 timeout=aiohttp.ClientTimeout(total=2),
460 ) as session:
461 async with session.get("http://localhost:8675/") as response:
462 return response.status == 200
463 except Exception:
464 pass
465 return False
467 def _check_mcp_server(self) -> bool:
468 with suppress(Exception):
469 result = subprocess.run(
470 ["pgrep", "-f", "crackerjack.*mcp"],
471 check=False,
472 capture_output=True,
473 text=True,
474 timeout=5.0, # Add timeout protection
475 )
476 return result.returncode == 0
477 return False
479 async def _start_websocket_server(self) -> None:
480 with suppress(Exception):
481 process = subprocess.Popen(
482 ["python", "-m", "crackerjack", "--start-websocket-server"],
483 stdout=subprocess.PIPE,
484 stderr=subprocess.PIPE,
485 start_new_session=True,
486 )
487 self.started_services.append(("websocket", process))
488 await asyncio.sleep(2)
490 async def _start_mcp_server(self) -> None:
491 with suppress(Exception):
492 process = subprocess.Popen(
493 ["python", "-m", "crackerjack", "--start-mcp-server"],
494 stdout=subprocess.PIPE,
495 stderr=subprocess.PIPE,
496 start_new_session=True,
497 )
498 self.started_services.append(("mcp", process))
499 await asyncio.sleep(2)
501 async def _start_service_watchdog(self) -> None:
502 with suppress(Exception):
503 result = subprocess.run(
504 ["pgrep", "-f", "crackerjack.*watchdog"],
505 check=False,
506 capture_output=True,
507 text=True,
508 timeout=5.0, # Add timeout protection
509 )
510 if result.returncode == 0:
511 return
513 process = subprocess.Popen(
514 ["python", "-m", "crackerjack", "--watchdog"],
515 stdout=subprocess.PIPE,
516 stderr=subprocess.PIPE,
517 start_new_session=True,
518 )
519 self.started_services.append(("watchdog", process))
521 def cleanup_services(self) -> None:
522 for _service_name, process in self.started_services:
523 self._cleanup_single_service(process)
524 self.started_services.clear()
526 def _cleanup_single_service(self, process: subprocess.Popen) -> None:
527 with suppress(Exception):
528 if process.poll() is not None:
529 return
531 process.terminate()
532 try:
533 process.wait(timeout=5)
534 except subprocess.TimeoutExpired:
535 process.kill()
536 try:
537 process.wait(timeout=2)
538 except subprocess.TimeoutExpired:
539 import os
541 os.kill(process.pid, 9)
544class TerminalRestorer:
545 @staticmethod
546 def restore_terminal() -> None:
547 try:
548 import subprocess
549 import sys
551 restoration_sequences = [
552 "\033[?1049l",
553 "\033[?1000l",
554 "\033[?1003l",
555 "\033[?1015l",
556 "\033[?1006l",
557 "\033[?25h",
558 "\033[?1004l",
559 "\033[?2004l",
560 "\033[?7h",
561 "\033[0m",
562 "\r",
563 ]
565 for sequence in restoration_sequences:
566 sys.stdout.write(sequence)
567 sys.stdout.flush()
569 subprocess.run(
570 ["stty", "echo", "icanon", "icrnl", "ixon"],
571 check=False,
572 capture_output=True,
573 timeout=1,
574 )
576 except Exception:
577 with suppress(Exception):
578 import subprocess
579 import sys
581 critical_sequences = [
582 "\033[?1049l",
583 "\033[?25h",
584 "\033[0m",
585 "\r",
586 ]
588 for sequence in critical_sequences:
589 sys.stdout.write(sequence)
590 sys.stdout.flush()
592 subprocess.run(
593 ["stty", "sane"],
594 check=False,
595 capture_output=True,
596 timeout=1,
597 )