|
| 1 | +# cli/ui.py |
| 2 | + |
| 3 | +import os |
| 4 | +import subprocess |
| 5 | +import typer |
| 6 | +from pathlib import Path |
| 7 | +from typing import Optional |
| 8 | + |
| 9 | +from cli.utils import print_result |
| 10 | + |
| 11 | +ui_app = typer.Typer(help="Manage Needle UI (Web Interface).") |
| 12 | + |
| 13 | + |
| 14 | +class UIManager: |
| 15 | + """Manages the Needle web UI.""" |
| 16 | + |
| 17 | + def __init__(self, needle_home: str): |
| 18 | + self.needle_home = Path(needle_home) |
| 19 | + self.ui_dir = self.needle_home / "ui" |
| 20 | + self.build_dir = self.ui_dir / "build" |
| 21 | + self.ui_pid_file = self.needle_home / "logs" / "ui.pid" |
| 22 | + |
| 23 | + def _is_ui_running(self) -> bool: |
| 24 | + """Check if the UI server is running.""" |
| 25 | + if not self.ui_pid_file.exists(): |
| 26 | + return False |
| 27 | + |
| 28 | + try: |
| 29 | + with open(self.ui_pid_file, 'r') as f: |
| 30 | + pid = int(f.read().strip()) |
| 31 | + |
| 32 | + # Check if process is still running |
| 33 | + os.kill(pid, 0) |
| 34 | + return True |
| 35 | + except (OSError, ValueError, FileNotFoundError): |
| 36 | + return False |
| 37 | + |
| 38 | + def _get_ui_pid(self) -> Optional[int]: |
| 39 | + """Get the PID of the UI server if it's running.""" |
| 40 | + if not self._is_ui_running(): |
| 41 | + return None |
| 42 | + |
| 43 | + try: |
| 44 | + with open(self.ui_pid_file, 'r') as f: |
| 45 | + return int(f.read().strip()) |
| 46 | + except (OSError, ValueError, FileNotFoundError): |
| 47 | + return None |
| 48 | + |
| 49 | + def start_ui(self, port: int = 3000): |
| 50 | + """Start the UI server.""" |
| 51 | + if self._is_ui_running(): |
| 52 | + pid = self._get_ui_pid() |
| 53 | + typer.echo(f"UI is already running (PID: {pid})") |
| 54 | + typer.echo(f"🌐 Access the UI at: http://localhost:{port}") |
| 55 | + return True |
| 56 | + |
| 57 | + # Check if build directory exists |
| 58 | + if not self.build_dir.exists(): |
| 59 | + typer.echo("❌ UI build directory not found. Please build the UI first:") |
| 60 | + typer.echo(" cd ui && npm install && npm run build") |
| 61 | + return False |
| 62 | + |
| 63 | + # Ensure logs directory exists |
| 64 | + self.ui_pid_file.parent.mkdir(parents=True, exist_ok=True) |
| 65 | + |
| 66 | + # Start UI server using Python's built-in HTTP server |
| 67 | + log_file = self.needle_home / "logs" / "ui.log" |
| 68 | + |
| 69 | + # Use Python's built-in HTTP server to serve the static files |
| 70 | + command = [ |
| 71 | + "python3", "-m", "http.server", str(port), "--directory", str(self.build_dir) |
| 72 | + ] |
| 73 | + |
| 74 | + # Start server in background |
| 75 | + with open(log_file, 'w') as log_f: |
| 76 | + process = subprocess.Popen( |
| 77 | + command, |
| 78 | + stdout=log_f, |
| 79 | + stderr=subprocess.STDOUT, |
| 80 | + cwd=self.build_dir |
| 81 | + ) |
| 82 | + |
| 83 | + # Save PID |
| 84 | + with open(self.ui_pid_file, 'w') as f: |
| 85 | + f.write(str(process.pid)) |
| 86 | + |
| 87 | + typer.echo(f"✅ UI started (PID: {process.pid})") |
| 88 | + typer.echo(f"🌐 Access the UI at: http://localhost:{port}") |
| 89 | + typer.echo(f"📝 Logs: {log_file}") |
| 90 | + return True |
| 91 | + |
| 92 | + def stop_ui(self): |
| 93 | + """Stop the UI server.""" |
| 94 | + if not self._is_ui_running(): |
| 95 | + typer.echo("UI is not running") |
| 96 | + return True |
| 97 | + |
| 98 | + pid = self._get_ui_pid() |
| 99 | + if pid: |
| 100 | + try: |
| 101 | + os.kill(pid, 15) # SIGTERM |
| 102 | + import time |
| 103 | + time.sleep(2) |
| 104 | + |
| 105 | + # Check if still running |
| 106 | + if self._is_ui_running(): |
| 107 | + os.kill(pid, 9) # SIGKILL |
| 108 | + time.sleep(1) |
| 109 | + |
| 110 | + typer.echo("✅ UI stopped") |
| 111 | + except OSError: |
| 112 | + typer.echo("❌ Error stopping UI") |
| 113 | + return False |
| 114 | + finally: |
| 115 | + # Remove PID file |
| 116 | + if self.ui_pid_file.exists(): |
| 117 | + self.ui_pid_file.unlink() |
| 118 | + |
| 119 | + return True |
| 120 | + |
| 121 | + def get_status(self): |
| 122 | + """Get UI status.""" |
| 123 | + is_running = self._is_ui_running() |
| 124 | + pid = self._get_ui_pid() if is_running else None |
| 125 | + |
| 126 | + return { |
| 127 | + "running": is_running, |
| 128 | + "pid": pid, |
| 129 | + "build_exists": self.build_dir.exists(), |
| 130 | + "ui_directory": str(self.ui_dir), |
| 131 | + "build_directory": str(self.build_dir) |
| 132 | + } |
| 133 | + |
| 134 | + |
| 135 | +@ui_app.command("start") |
| 136 | +def ui_start(ctx: typer.Context, port: int = typer.Option(3000, "--port", "-p", help="Port to run the UI on")): |
| 137 | + """Start the Needle web UI.""" |
| 138 | + needle_home = ctx.obj.get("needle_home", ".") |
| 139 | + manager = UIManager(needle_home) |
| 140 | + manager.start_ui(port) |
| 141 | + |
| 142 | + |
| 143 | +@ui_app.command("stop") |
| 144 | +def ui_stop(ctx: typer.Context): |
| 145 | + """Stop the Needle web UI.""" |
| 146 | + needle_home = ctx.obj.get("needle_home", ".") |
| 147 | + manager = UIManager(needle_home) |
| 148 | + manager.stop_ui() |
| 149 | + |
| 150 | + |
| 151 | +@ui_app.command("status") |
| 152 | +def ui_status_cmd(ctx: typer.Context): |
| 153 | + """Show UI status.""" |
| 154 | + needle_home = ctx.obj.get("needle_home", ".") |
| 155 | + manager = UIManager(needle_home) |
| 156 | + status = manager.get_status() |
| 157 | + print_result(status, ctx.obj["output"]) |
| 158 | + |
| 159 | + |
| 160 | +@ui_app.command("build") |
| 161 | +def ui_build(ctx: typer.Context): |
| 162 | + """Build the UI for production.""" |
| 163 | + needle_home = ctx.obj.get("needle_home", ".") |
| 164 | + ui_dir = Path(needle_home) / "ui" |
| 165 | + |
| 166 | + if not ui_dir.exists(): |
| 167 | + typer.echo("❌ UI directory not found. Please run this from the Needle project root.") |
| 168 | + return |
| 169 | + |
| 170 | + typer.echo("🔨 Building UI for production...") |
| 171 | + |
| 172 | + # Check if node_modules exists |
| 173 | + node_modules = ui_dir / "node_modules" |
| 174 | + if not node_modules.exists(): |
| 175 | + typer.echo("📦 Installing dependencies...") |
| 176 | + result = subprocess.run(["npm", "install"], cwd=ui_dir, capture_output=True, text=True) |
| 177 | + if result.returncode != 0: |
| 178 | + typer.echo(f"❌ Failed to install dependencies: {result.stderr}") |
| 179 | + return |
| 180 | + |
| 181 | + # Build the UI |
| 182 | + typer.echo("🏗️ Building React app...") |
| 183 | + result = subprocess.run(["npm", "run", "build"], cwd=ui_dir, capture_output=True, text=True) |
| 184 | + if result.returncode != 0: |
| 185 | + typer.echo(f"❌ Build failed: {result.stderr}") |
| 186 | + return |
| 187 | + |
| 188 | + typer.echo("✅ UI built successfully!") |
| 189 | + typer.echo(f"📁 Build directory: {ui_dir / 'build'}") |
| 190 | + typer.echo("🚀 You can now start the UI with: needlectl ui start") |
| 191 | + |
| 192 | + |
| 193 | +@ui_app.command("log") |
| 194 | +def ui_log_cmd(ctx: typer.Context): |
| 195 | + """Show UI logs.""" |
| 196 | + needle_home = ctx.obj.get("needle_home", ".") |
| 197 | + log_file = Path(needle_home) / "logs" / "ui.log" |
| 198 | + |
| 199 | + if log_file.exists(): |
| 200 | + typer.echo("📝 UI Logs:") |
| 201 | + with open(log_file, 'r') as f: |
| 202 | + typer.echo(f.read()) |
| 203 | + else: |
| 204 | + typer.echo("📝 No UI logs found") |
0 commit comments