Coverage for /Users/les/Projects/crackerjack/crackerjack/mcp/websocket/endpoints.py: 0%
60 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 json
2from pathlib import Path
4from fastapi import FastAPI
5from fastapi.responses import HTMLResponse
7from ...services.secure_status_formatter import (
8 StatusVerbosity,
9 format_secure_status,
10 get_secure_status_formatter,
11)
12from .jobs import JobManager
15def _build_job_list(job_manager: JobManager, progress_dir: Path) -> list[dict]:
16 jobs = []
17 if not progress_dir.exists():
18 return jobs
19 for progress_file in progress_dir.glob("job-*.json"):
20 job_id = job_manager.extract_job_id_from_file(progress_file)
21 if job_id and job_manager.validate_job_id(job_id):
22 try:
23 progress_data = json.loads(progress_file.read_text())
24 jobs.append(
25 {
26 "job_id": job_id,
27 "status": progress_data.get("status", "unknown"),
28 "message": progress_data.get("message", ""),
29 "progress": progress_data.get("overall_progress", 0),
30 },
31 )
32 except (json.JSONDecodeError, OSError):
33 continue
34 jobs.sort(key=lambda j: j.get("job_id", ""), reverse=True)
35 return jobs
38def _build_status_response(job_manager: JobManager, jobs: list[dict]) -> dict:
39 return {
40 "status": "running",
41 "message": "Crackerjack WebSocket Server",
42 "active_connections": len(job_manager.active_connections),
43 "jobs": jobs[:10],
44 "websocket_url": "ws://[INTERNAL_URL]/ws/progress/{job_id}",
45 "endpoints": {
46 "status": "/",
47 "latest_job": "/latest",
48 "job_monitor": "/monitor/{job_id}",
49 "test": "/test",
50 "websocket": "/ws/progress/{job_id}",
51 },
52 }
55def _get_monitor_html(job_id: str) -> str:
56 """Generate secure HTML for job monitoring page."""
57 return f"""
58 <!DOCTYPE html>
59 <html>
60 <head>
61 <title>Job Monitor - {job_id}</title>
62 <meta charset="UTF-8">
63 <meta name="viewport" content="width=device-width, initial-scale=1.0">
64 <style>
65 body {{
66 font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
67 margin: 0;
68 padding: 20px;
69 background-color: #f5f5f5;
70 }}
71 .container {{
72 max-width: 800px;
73 margin: 0 auto;
74 background: white;
75 padding: 30px;
76 border-radius: 10px;
77 box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
78 }}
79 .header {{
80 text-align: center;
81 margin-bottom: 30px;
82 padding-bottom: 20px;
83 border-bottom: 2px solid #eee;
84 }}
85 .job-id {{
86 font-family: 'Courier New', monospace;
87 background: #f0f0f0;
88 padding: 5px 10px;
89 border-radius: 5px;
90 color: #666;
91 }}
92 .status {{
93 margin: 20px 0;
94 padding: 15px;
95 border-radius: 5px;
96 font-weight: bold;
97 }}
98 .status.running {{ background-color: #e3f2fd; color: #1976d2; }}
99 .status.completed {{ background-color: #e8f5e8; color: #388e3c; }}
100 .status.failed {{ background-color: #ffebee; color: #d32f2f; }}
101 .status.connecting {{ background-color: #fff3e0; color: #f57c00; }}
102 .log {{
103 margin: 20px 0;
104 padding: 15px;
105 background: #1e1e1e;
106 color: #fff;
107 font-family: 'Courier New', monospace;
108 border-radius: 5px;
109 max-height: 300px;
110 overflow-y: auto;
111 font-size: 12px;
112 line-height: 1.4;
113 }}
114 .connection-status {{
115 position: fixed;
116 top: 10px;
117 right: 10px;
118 padding: 5px 10px;
119 border-radius: 15px;
120 font-size: 12px;
121 font-weight: bold;
122 }}
123 .connected {{ background: #4caf50; color: white; }}
124 .disconnected {{ background: #f44336; color: white; }}
125 </style>
126 </head>
127 <body>
128 <div class="connection-status" id="connectionStatus">Connecting...</div>
129 <div class="container">
130 <div class="header">
131 <h1>🚀 Crackerjack Job Monitor</h1>
132 <p>Job ID: <span class="job-id">{job_id}</span></p>
133 </div>
134 <div class="status connecting" id="status">
135 Status: Connecting to job...
136 </div>
137 <div class="log" id="log">
138 <div>Connecting to WebSocket...</div>
139 </div>
140 </div>
142 <script>
143 const jobId = '{job_id}';
144 const wsUrl = `ws://[INTERNAL_URL]/ws/progress/${{jobId}}`;
145 let ws = null;
147 function updateConnectionStatus(status) {{
148 const elem = document.getElementById('connectionStatus');
149 elem.className = 'connection-status ' + status;
150 elem.textContent = status === 'connected' ? '🟢 Connected' : '🔴 Disconnected';
151 }}
153 function addLogEntry(message) {{
154 const log = document.getElementById('log');
155 const timestamp = new Date().toLocaleTimeString();
156 const entry = document.createElement('div');
157 entry.textContent = `[${{timestamp}}] ${{message}}`;
158 log.appendChild(entry);
159 log.scrollTop = log.scrollHeight;
160 }}
162 function connect() {{
163 ws = new WebSocket(wsUrl);
165 ws.onopen = function() {{
166 updateConnectionStatus('connected');
167 addLogEntry('Connected to WebSocket');
168 }};
170 ws.onmessage = function(event) {{
171 try {{
172 const data = JSON.parse(event.data);
173 addLogEntry(data.message || 'Progress update');
174 }} catch (e) {{
175 addLogEntry('Received: ' + event.data);
176 }}
177 }};
179 ws.onclose = function() {{
180 updateConnectionStatus('disconnected');
181 addLogEntry('WebSocket connection closed');
182 }};
184 ws.onerror = function() {{
185 updateConnectionStatus('disconnected');
186 addLogEntry('WebSocket error occurred');
187 }};
188 }}
190 // Start connection
191 connect();
192 </script>
193 </body>
194 </html>
195 """
198def _get_test_html() -> str:
199 return """
200 < ! DOCTYPE html >
201 < html >
202 < head >
203 < title > WebSocket Test Page < / title >
204 < meta charset ="UTF-8">
205 < style >
206 body {
207 font - family: Arial, sans - serif;
208 max - width: 800px;
209 margin: 50px auto;
210 padding: 20px;
211 background - color:
212 }
213 .container {
214 background: white;
215 padding: 30px;
216 border - radius: 10px;
217 box - shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
218 }
219 .test - section {
220 margin: 20px 0;
221 padding: 15px;
222 border: 1px solid
223 border - radius: 5px;
224 }
225 button {
226 background:
227 color: white;
228 border: none;
229 padding: 10px 20px;
230 border - radius: 5px;
231 cursor: pointer;
232 margin: 5px;
233 }
234 button: hover { background:
235 input[type ="text"] {
236 padding: 8px;
237 border: 1px solid
238 border - radius: 3px;
239 margin: 5px;
240 width: 200px;
241 }
242 .status {
243 margin: 10px 0;
244 padding: 10px;
245 border - radius: 5px;
246 font - weight: bold;
247 }
248 .success { background:
249 .error { background:
250 .info { background:
252 background:
253 color:
254 padding: 15px;
255 border - radius: 5px;
256 font - family: 'Courier New', monospace;
257 max - height: 300px;
258 overflow - y: auto;
259 margin-top: 20px;
260 }
261 < / style >
262 < / head >
263 < body >
264 < div class ="container">
265 < h1 >🧪 WebSocket Test Page < / h1 >
266 < p > Test WebSocket connectivity and server functionality < / p >
268 < div class ="test-section">
269 < h3 > 1. Server Status < / h3 >
270 < button onclick ="checkServerStatus()"> Check Status < / button >
271 < div id ="serverStatus"> </ div >
272 < / div >
274 < div class ="test-section">
275 < h3 > 2. Latest Job < / h3 >
276 < button onclick ="checkLatestJob()"> Get Latest Job < / button >
277 < div id ="latestJob"> </ div >
278 < / div >
280 < div class ="test-section">
281 < h3 > 3. WebSocket Test < / h3 >
282 < input type ="text" id ="testJobId" placeholder ="Enter job ID (e.g., test-123)" value ="test-123">
283 < button onclick ="testWebSocket()"> Test WebSocket < / button >
284 < button onclick ="disconnectWebSocket()"> Disconnect < / button >
285 < div id ="wsStatus"> </ div >
286 < / div >
288 < div id ="log">
289 < div > Ready to test...< / div >
290 < / div >
291 < / div >
293 < script >
294 let testWs=null;
295 const log=document.getElementById('log');
297 function addLog(message, type='info') {
298 const timestamp=new Date().toLocaleTimeString();
299 const div=document.createElement('div');
300 div.textContent=`[${timestamp}] ${message}`;
301 if (type = == 'error') div.style.color='#ff6b6b';
302 if (type = == 'success') div.style.color='#51cf66';
303 log.appendChild(div);
304 log.scrollTop=log.scrollHeight;
305 }
307 function showStatus(elementId, message, type='info') {
308 const element=document.getElementById(elementId);
309 element.innerHTML=`< div class ="status ${type}">${message}< / div >`;
310 }
312 async function checkServerStatus() {
313 try {
314 addLog('Checking server status...');
315 const response=await fetch('/');
316 const data=await response.json();
318 showStatus('serverStatus',
319 `Status: ${data.status}< br >` +
320 `Active connections: ${data.active_connections}< br >` +
321 `Jobs: ${data.jobs?.length | | 0}`, 'success');
322 addLog('Server status retrieved successfully', 'success');
323 } catch (error) {
324 showStatus('serverStatus', `Error: ${error.message}`, 'error');
325 addLog(`Server status error: ${error.message}`, 'error');
326 }
327 }
329 async function checkLatestJob() {
330 try {
331 addLog('Getting latest job...');
332 const response=await fetch('/ latest');
333 const data=await response.json();
335 if (data.job_id) {
336 showStatus('latestJob',
337 `Job ID: ${data.job_id}< br >` +
338 `Status: ${data.progress?.status | | 'unknown'}< br >` +
339 `Progress: ${data.progress?.overall_progress | | 0}%`, 'success');
340 addLog(`Latest job: ${data.job_id}`, 'success');
341 } else {
342 showStatus('latestJob', data.message, 'info');
343 addLog(data.message);
344 }
345 } catch (error) {
346 showStatus('latestJob', `Error: ${error.message}`, 'error');
347 addLog(`Latest job error: ${error.message}`, 'error');
348 }
349 }
351 function testWebSocket() {
352 const jobId=document.getElementById('testJobId').value;
353 if (! jobId) {
354 showStatus('wsStatus', 'Please enter a job ID', 'error');
355 return;
356 }
358 disconnectWebSocket();
360 addLog(`Connecting to WebSocket for job: ${jobId}`);
361 const wsUrl=`ws: / / localhost: 8675 / ws / progress /${jobId}`;
362 testWs=new WebSocket(wsUrl);
364 testWs.onopen=function() {
365 showStatus('wsStatus', `Connected to ${jobId}`, 'success');
366 addLog('WebSocket connected successfully', 'success');
367 };
369 testWs.onmessage=function(event) {
370 try {
371 const data=JSON.parse(event.data);
372 addLog(`Received: ${data.message | | 'Progress update'}`);
373 } catch (e) {
374 addLog(`Raw message: ${event.data}`);
375 }
376 };
378 testWs.onclose=function() {
379 showStatus('wsStatus', 'WebSocket closed', 'info');
380 addLog('WebSocket connection closed');
381 };
383 testWs.onerror=function(error) {
384 showStatus('wsStatus', `WebSocket error: ${error.message}`, 'error');
385 addLog(`WebSocket error: ${error.message}`, 'error');
386 };
387 }
389 function disconnectWebSocket() {
390 if (testWs) {
391 testWs.close();
392 testWs=null;
393 showStatus('wsStatus', 'Disconnected', 'info');
394 addLog('WebSocket disconnected');
395 }
396 }
398 / / Auto - check server status on load
399 window.onload=function() {
400 checkServerStatus();
401 };
402 < / script >
403 < / body >
404 < / html >
406 < ! DOCTYPE html >
407 < html >
408 < head >
409 < title > Job Monitor-{job_id}< / title >
410 < meta charset ="UTF - 8">
411 < meta name ="viewport" content ="width=device - width, initial-scale=1.0">
412 < style >
413 body {{
414 font - family: 'Segoe UI', Tahoma, Geneva, Verdana, sans - serif;
415 margin: 0;
416 padding: 20px;
417 background - color:
418 }}
419 .container {{
420 max - width: 800px;
421 margin: 0 auto;
422 background: white;
423 padding: 30px;
424 border - radius: 10px;
425 box - shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
426 }}
427 .header {{
428 text - align: center;
429 margin - bottom: 30px;
430 padding - bottom: 20px;
431 border - bottom: 2px solid
432 }}
433 .job - id {{
434 font - family: 'Courier New', monospace;
435 background:
436 padding: 5px 10px;
437 border - radius: 5px;
438 color:
439 }}
440 .status {{
441 margin: 20px 0;
442 padding: 15px;
443 border - radius: 5px;
444 font - weight: bold;
445 }}
446 .status.running {{ background - color:
447 .status.completed {{ background - color:
448 .status.failed {{ background - color:
449 .status.connecting {{ background - color:
450 .progress - bar {{
451 width: 100 %;
452 height: 20px;
453 background - color:
454 border - radius: 10px;
455 overflow: hidden;
456 margin: 10px 0;
457 }}
458 .progress - fill {{
459 height: 100 %;
460 background - color:
461 width: 0 %;
462 transition: width 0.3s ease;
463 }}
464 .details {{
465 margin: 20px 0;
466 padding: 15px;
467 background:
468 border - radius: 5px;
469 border - left: 4px solid
470 }}
471 .log {{
472 margin: 20px 0;
473 padding: 15px;
474 background:
475 color:
476 font - family: 'Courier New', monospace;
477 border - radius: 5px;
478 max - height: 300px;
479 overflow - y: auto;
480 font - size: 12px;
481 line - height: 1.4;
482 }}
483 .connection - status {{
484 position: fixed;
485 top: 10px;
486 right: 10px;
487 padding: 5px 10px;
488 border - radius: 15px;
489 font - size: 12px;
490 font - weight: bold;
491 }}
492 .connected {{ background:
493 .disconnected {{ background:
494 .reconnecting {{ background:
495 < / style >
496 < / head >
497 < body >
498 < div class ="connection-status" id ="connectionStatus"> Connecting...< / div >
500 < div class ="container">
501 < div class ="header">
502 < h1 >🚀 Crackerjack Job Monitor < / h1 >
503 < p > Job ID: < span class ="job-id">{job_id}< / span > </ p >
504 < / div >
506 < div class ="status connecting" id ="status">
507 Status: Connecting to job...
508 < / div >
510 < div class ="progress-bar">
511 < div class ="progress-fill" id ="progressFill"> </ div >
512 < / div >
513 < div id ="progressText"> Progress: 0 % </ div >
515 < div class ="details" id ="details">
516 < strong > Current Stage: < / strong > < span id ="currentStage"> Initializing < / span > < br >
517 < strong > Iteration: < / strong > < span id ="iteration"> 0 < / span > / < span id ="maxIterations"> 10 < / span > < br >
518 < strong > Message: < / strong > < span id ="message"> Connecting...< / span >
519 < / div >
521 < div class ="log" id ="log">
522 < div > Connecting to WebSocket...< / div >
523 < / div >
524 < / div >
526 < script >
527 const jobId='{job_id}';
528 const wsUrl=`ws: / / localhost: 8675 / ws / progress /${{jobId}}`;
529 let ws=null;
530 let reconnectAttempts=0;
531 const maxReconnectAttempts=10;
533 const elements={{
534 status: document.getElementById('status'),
535 progressFill: document.getElementById('progressFill'),
536 progressText: document.getElementById('progressText'),
537 currentStage: document.getElementById('currentStage'),
538 iteration: document.getElementById('iteration'),
539 maxIterations: document.getElementById('maxIterations'),
540 message: document.getElementById('message'),
541 log: document.getElementById('log'),
542 connectionStatus: document.getElementById('connectionStatus')
543 }};
545 function updateConnectionStatus(status) {{
546 elements.connectionStatus.className='connection-status ' + status;
547 elements.connectionStatus.textContent={{
548 'connected': '🟢 Connected',
549 'disconnected': '🔴 Disconnected',
550 'reconnecting': '🟡 Reconnecting...'
551 }}[status] | | '⚪ Unknown';
552 }}
554 function addLogEntry(message, type='info') {{
555 const timestamp=new Date().toLocaleTimeString();
556 const logEntry=document.createElement('div');
557 logEntry.textContent=`[${{timestamp}}] ${{message}}`;
558 if (type = == 'error') logEntry.style.color='#ff6b6b';
559 if (type = == 'success') logEntry.style.color='#51cf66';
560 elements.log.appendChild(logEntry);
561 elements.log.scrollTop=elements.log.scrollHeight;
562 }}
564 function updateProgress(data) {{
565 const progress=data.overall_progress | | 0;
566 const status=data.status | | 'unknown';
568 elements.progressFill.style.width=progress + '%';
569 elements.progressText.textContent=`Progress: ${{progress}}%`;
571 elements.status.textContent=`Status: ${{status}}`;
572 elements.status.className='status ' + status.toLowerCase();
574 elements.currentStage.textContent=data.current_stage | | 'Unknown';
575 elements.iteration.textContent=data.iteration | | 0;
576 elements.maxIterations.textContent=data.max_iterations | | 10;
577 elements.message.textContent=data.message | | 'No message';
579 addLogEntry(`${{data.current_stage | | 'Unknown stage'}}: ${{data.message | | 'No message'}}`,
580 status = == 'failed' ? 'error' : status = == 'completed' ? 'success' : 'info');
581 }}
583 function connect() {{
584 if (ws & & ws.readyState = == WebSocket.OPEN) return;
586 updateConnectionStatus('reconnecting');
587 addLogEntry('Connecting to WebSocket...');
589 ws=new WebSocket(wsUrl);
591 ws.onopen=function() {{
592 updateConnectionStatus('connected');
593 addLogEntry('Connected to WebSocket', 'success');
594 reconnectAttempts=0;
595 }};
597 ws.onmessage=function(event) {{
598 try {{
599 const data=JSON.parse(event.data);
600 updateProgress(data);
601 }} catch (e) {{
602 addLogEntry('Error parsing message: ' + e.message, 'error');
603 }}
604 }};
606 ws.onclose=function() {{
607 updateConnectionStatus('disconnected');
608 addLogEntry('WebSocket connection closed');
609 if (reconnectAttempts < maxReconnectAttempts) {{
610 setTimeout(() = > {{
611 reconnectAttempts + +;
612 addLogEntry(`Attempting to reconnect (${{reconnectAttempts}}/${{maxReconnectAttempts}})...`);
613 connect();
614 }}, 2000);
615 }} else {{
616 addLogEntry('Maximum reconnection attempts reached', 'error');
617 }}
618 }};
620 ws.onerror=function(error) {{
621 addLogEntry('WebSocket error occurred', 'error');
622 updateConnectionStatus('disconnected');
623 }};
624 }}
626 / / Start connection
627 connect();
629 / / Periodically check connection health
630 setInterval(() = > {{
631 if (! ws | | ws.readyState ! == WebSocket.OPEN) {{
632 if (reconnectAttempts < maxReconnectAttempts) {{
633 connect();
634 }}
635 }}
636 }}, 5000);
637 < / script >
638 < / body >
639 < / html >
640 """
643def register_endpoints(
644 app: FastAPI,
645 job_manager: JobManager,
646 progress_dir: Path,
647) -> None:
648 @app.get("/")
649 async def get_status():
650 try:
651 # Build raw status response
652 jobs = _build_job_list(job_manager, progress_dir)
653 raw_status = _build_status_response(job_manager, jobs)
655 # Apply secure formatting
656 secure_status = format_secure_status(
657 raw_status,
658 verbosity=StatusVerbosity.STANDARD,
659 project_root=progress_dir.parent,
660 user_context="websocket_client",
661 )
663 return secure_status
664 except Exception as e:
665 # Use secure error formatting
666 formatter = get_secure_status_formatter()
667 error_response = formatter.format_error_response(
668 str(e),
669 verbosity=StatusVerbosity.STANDARD,
670 )
671 return error_response
673 @app.get("/latest")
674 async def get_latest_job():
675 try:
676 latest_job_id = job_manager.get_latest_job_id()
678 if not latest_job_id:
679 raw_response = {
680 "status": "no_jobs",
681 "message": "No jobs found",
682 "job_id": None,
683 "progress": None,
684 }
685 else:
686 progress_data = job_manager.get_job_progress(latest_job_id)
687 raw_response = {
688 "status": "success",
689 "message": f"Latest job: {latest_job_id}",
690 "job_id": latest_job_id,
691 "progress": progress_data,
692 "websocket_url": f"ws://[INTERNAL_URL]/ws/progress/{latest_job_id}",
693 "monitor_url": f"http://[INTERNAL_URL]/monitor/{latest_job_id}",
694 }
696 # Apply secure formatting
697 secure_response = format_secure_status(
698 raw_response,
699 verbosity=StatusVerbosity.STANDARD,
700 project_root=progress_dir.parent,
701 user_context="websocket_client",
702 )
704 return secure_response
706 except Exception as e:
707 # Use secure error formatting
708 formatter = get_secure_status_formatter()
709 error_response = formatter.format_error_response(
710 f"Failed to get latest job: {e}",
711 verbosity=StatusVerbosity.STANDARD,
712 )
713 return error_response
715 @app.get("/monitor/{job_id}")
716 async def get_job_monitor_page(job_id: str):
717 if not job_manager.validate_job_id(job_id):
718 return HTMLResponse(
719 content="<h1>Error</h1><p>Invalid job ID</p>",
720 status_code=400,
721 )
722 return HTMLResponse(content=_get_monitor_html(job_id))
724 @app.get("/test")
725 async def get_test_page():
726 return HTMLResponse(content=_get_test_html())