Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
Add Docker support and auto-start web UI from repowise serve
RaghavChamadiyafea64886acaa
diff --git a/.dockerignore b/.dockerignorenew file mode 100644index 000000000..e09ff6a0c--- /dev/null+++ b/.dockerignore@@ -0,0 +1,41 @@+# Git+.git+.gitignore++# Python+__pycache__+*.pyc+*.pyo+*.egg-info+.venv+venv+.mypy_cache+.ruff_cache+.pytest_cache+htmlcov+dist+build++# Node+node_modules+packages/web/.next+packages/web/out++# Runtime data+.repowise+*.db+*.db-shm+*.db-wal+lancedb++# IDE+.idea+.vscode+*.swp++# Docker+docker-compose.override.yml++# Docs (not needed in image)+docs/+tests/diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.ymlindex 36e66288e..847fc3f50 100644--- a/.github/workflows/publish.yml+++ b/.github/workflows/publish.yml@@ -5,11 +5,54 @@ on:tags: ['v*']permissions:- contents: read+ contents: write # needed for creating GitHub releasesjobs:- build:- name: Build distribution+ # ---------------------------------------------------------------------------+ # Build the Next.js frontend as a standalone tarball+ # ---------------------------------------------------------------------------+ build-web:+ name: Build Web UI+ runs-on: ubuntu-latest++ steps:+ - uses: actions/checkout@v4++ - name: Set up Node.js+ uses: actions/setup-node@v4+ with:+ node-version: "20"+ cache: "npm"+ cache-dependency-path: packages/web/package-lock.json++ - name: Install dependencies+ run: cd packages/web && npm install++ - name: Build Next.js (standalone)+ run: cd packages/web && npm run build+ env:+ NEXT_PUBLIC_REPOWISE_API_URL: ""++ - name: Package standalone output+ run: |+ cd packages/web/.next/standalone+ # Copy static files into standalone (Next.js requirement)+ cp -r ../../.next/static .next/static+ [ -d ../../public ] && cp -r ../../public public || true+ # Create tarball+ tar -czf /tmp/repowise-web.tar.gz .++ - name: Upload web artifact+ uses: actions/upload-artifact@v4+ with:+ name: repowise-web+ path: /tmp/repowise-web.tar.gz++ # ---------------------------------------------------------------------------+ # Build the Python package+ # ---------------------------------------------------------------------------+ build-python:+ name: Build Python packageruns-on: ubuntu-lateststeps:@@ -32,9 +75,41 @@ jobs:name: distpath: dist/+ # ---------------------------------------------------------------------------+ # Create GitHub release with web UI tarball+ # ---------------------------------------------------------------------------+ release:+ name: Create GitHub Release+ needs: [build-web, build-python]+ runs-on: ubuntu-latest++ steps:+ - name: Download web artifact+ uses: actions/download-artifact@v4+ with:+ name: repowise-web+ path: ./artifacts/++ - name: Download Python dist+ uses: actions/download-artifact@v4+ with:+ name: dist+ path: ./dist/++ - name: Create release+ uses: softprops/action-gh-release@v2+ with:+ files: |+ artifacts/repowise-web.tar.gz+ dist/*+ generate_release_notes: true++ # ---------------------------------------------------------------------------+ # Publish to PyPI+ # ---------------------------------------------------------------------------publish:name: Publish to PyPI- needs: build+ needs: build-pythonruns-on: ubuntu-latestenvironment: pypipermissions:diff --git a/Dockerfile b/Dockerfilenew file mode 100644index 000000000..dc55b944a--- /dev/null+++ b/Dockerfile@@ -0,0 +1,70 @@+# =============================================================================+# repowise — multi-stage Docker build (backend + frontend)+# =============================================================================+# Usage:+# docker build -t repowise .+# docker run -p 7337:7337 -p 3000:3000 -v /path/to/repo/.repowise:/data -e GEMINI_API_KEY=... repowise+# =============================================================================++# ---------------------------------------------------------------------------+# Stage 1: Build the Next.js frontend+# ---------------------------------------------------------------------------+FROM node:20-alpine AS frontend-builder++WORKDIR /app++# Install dependencies first (cached layer)+COPY packages/web/package.json packages/web/package-lock.json* ./+RUN npm install --production=false++# Copy source and build+COPY packages/web/ ./+ENV NEXT_TELEMETRY_DISABLED=1+ENV NEXT_PUBLIC_REPOWISE_API_URL=http://localhost:7337+RUN npm run build++# ---------------------------------------------------------------------------+# Stage 2: Python backend + frontend runtime+# ---------------------------------------------------------------------------+FROM python:3.12-slim AS runtime++# Install git (required by gitpython) and Node.js (required for Next.js server)+RUN apt-get update && apt-get install -y --no-install-recommends \+ git \+ curl \+ && curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \+ && apt-get install -y --no-install-recommends nodejs \+ && rm -rf /var/lib/apt/lists/*++WORKDIR /app++# Install repowise Python package+COPY pyproject.toml README.md LICENSE MANIFEST.in ./+COPY packages/core/ packages/core/+COPY packages/cli/ packages/cli/+COPY packages/server/ packages/server/+RUN pip install --no-cache-dir ".[all]"++# Copy built Next.js standalone output+COPY --from=frontend-builder /app/.next/standalone /app/web+COPY --from=frontend-builder /app/.next/static /app/web/.next/static+COPY --from=frontend-builder /app/public /app/web/public 2>/dev/null || true++# Data volume for .repowise directory+VOLUME /data++# Environment defaults+ENV REPOWISE_DB_URL=sqlite+aiosqlite:///data/wiki.db+ENV REPOWISE_EMBEDDER=mock+ENV PORT_BACKEND=7337+ENV PORT_FRONTEND=3000+ENV HOSTNAME=0.0.0.0++# Expose both ports+EXPOSE 7337 3000++# Startup script+COPY docker/entrypoint.sh /app/entrypoint.sh+RUN chmod +x /app/entrypoint.sh++ENTRYPOINT ["/app/entrypoint.sh"]diff --git a/README.md b/README.mdindex fa99d5ba2..fd8ce7b8c 100644--- a/README.md+++ b/README.md@@ -115,14 +115,23 @@ repowise includes a full web dashboard (Next.js + React + D3.js) with:- **Dead code finder** — unused code with confidence scores and bulk actions- **Decision tracker** — architectural decisions with health monitoring-See the [User Guide](https://github.com/RaghavChamadiya/repowise/blob/main/docs/USER_GUIDE.md#web-ui) for setup instructions.+**Starts automatically with `repowise serve`** if Node.js 20+ is installed. No separate setup — the frontend is downloaded and cached on first run.++No Node.js? Use Docker instead:++```bash+docker build -t repowise https://github.com/RaghavChamadiya/repowise.git+docker run -p 7337:7337 -p 3000:3000 -v .repowise:/data repowise+```++See the [User Guide](https://github.com/RaghavChamadiya/repowise/blob/main/docs/USER_GUIDE.md#web-ui) for more options.## Requirements- Python 3.11+- Git (for repository analysis)- An LLM API key (for documentation generation — not needed for analysis-only mode)-- Node.js 20+ (only if running the web UI frontend)+- Node.js 20+ or Docker (optional, for the web UI)## Documentationdiff --git a/docker-compose.yml b/docker-compose.ymlnew file mode 100644index 000000000..3f5c0d403--- /dev/null+++ b/docker-compose.yml@@ -0,0 +1,17 @@+services:+ repowise:+ build: .+ ports:+ - "7337:7337" # API+ - "3000:3000" # Web UI+ volumes:+ # Mount the .repowise directory from your indexed repo+ - ${REPOWISE_DATA:-./data}:/data+ environment:+ - REPOWISE_DB_URL=sqlite+aiosqlite:///data/wiki.db+ - REPOWISE_EMBEDDER=${REPOWISE_EMBEDDER:-mock}+ # Set your LLM provider API key+ - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY:-}+ - OPENAI_API_KEY=${OPENAI_API_KEY:-}+ - GEMINI_API_KEY=${GEMINI_API_KEY:-}+ restart: unless-stoppeddiff --git a/docker/README.md b/docker/README.mdindex c067cd540..5a7e15aed 100644--- a/docker/README.md+++ b/docker/README.md@@ -1,6 +1,45 @@# Docker-> Built in Phase 9. Placeholder file.+Run the full repowise stack (API + Web UI) in a single container.-The multi-stage Dockerfile and docker-compose.yml will be implemented in Phase 9.-See `BUILD_STATUS.md` for current status.+## Prerequisites++- Docker installed+- A repository already indexed with `repowise init` (the `.repowise/` directory exists)++## Quick Start++```bash+docker build -t repowise .++# Run with a mounted .repowise directory+docker run -p 7337:7337 -p 3000:3000 \+ -v /path/to/your-repo/.repowise:/data \+ -e GEMINI_API_KEY=your-key \+ -e REPOWISE_EMBEDDER=gemini \+ repowise+```++Open http://localhost:3000 for the Web UI, http://localhost:7337 for the API.++## Docker Compose++```bash+# Set the path to your .repowise directory+export REPOWISE_DATA=/path/to/your-repo/.repowise+export GEMINI_API_KEY=your-key++docker compose up+```++## Environment Variables++| Variable | Default | Description |+|----------|---------|-------------|+| `REPOWISE_DB_URL` | `sqlite+aiosqlite:///data/wiki.db` | Database URL |+| `REPOWISE_EMBEDDER` | `mock` | Embedder: `gemini`, `openai`, `mock` |+| `ANTHROPIC_API_KEY` | — | Anthropic API key (for chat) |+| `OPENAI_API_KEY` | — | OpenAI API key (for chat) |+| `GEMINI_API_KEY` | — | Gemini API key (for chat + embeddings) |+| `PORT_BACKEND` | `7337` | API server port |+| `PORT_FRONTEND` | `3000` | Web UI port |diff --git a/docker/entrypoint.sh b/docker/entrypoint.shnew file mode 100644index 000000000..687917775--- /dev/null+++ b/docker/entrypoint.sh@@ -0,0 +1,21 @@+#!/bin/bash+set -e++# Start the FastAPI backend+echo "Starting repowise API server on port ${PORT_BACKEND}..."+uvicorn repowise.server.app:create_app \+ --factory \+ --host 0.0.0.0 \+ --port "${PORT_BACKEND}" &++# Start the Next.js frontend+echo "Starting repowise Web UI on port ${PORT_FRONTEND}..."+cd /app/web+REPOWISE_API_URL="http://localhost:${PORT_BACKEND}" \+HOSTNAME="0.0.0.0" \+PORT="${PORT_FRONTEND}" \+ node server.js &++# Wait for either process to exit+wait -n+exit $?diff --git a/docs/QUICKSTART.md b/docs/QUICKSTART.mdindex 9bd830c72..8d0d92b48 100644--- a/docs/QUICKSTART.md+++ b/docs/QUICKSTART.md@@ -1,96 +1,153 @@# Quickstart-Get the repowise backend and frontend running locally against an already-indexed repo.+Get repowise running on your codebase in under 5 minutes.-## Prerequisites+> For the full CLI reference, web UI docs, MCP integration, and troubleshooting, see the [User Guide](USER_GUIDE.md).-- **Python 3.11+** managed by [uv](https://docs.astral.sh/uv/)-- **Node.js 18+** with npm-- A **Gemini API key** (or Anthropic/OpenAI — swap the env vars accordingly)-- A repo that has already been indexed with `repowise init` (the `.repowise/` directory exists)+----## Test Repo--These instructions use the `interview-coach` repo as the test target:+## 1. Install+```bash+pip install "repowise[anthropic]"```-Repo path: C:\Users\ragha\Desktop\interview-coach-Wiki DB: C:\Users\ragha\Desktop\interview-coach\.repowise\wiki.db-Provider: gemini (gemini-3.1-flash-lite-preview)-Embedder: gemini++Or substitute `openai`, `gemini`, `litellm`, or `all` depending on your LLM provider.++**Requirements:** Python 3.11+, Git.++## 2. Set Your API Key++```bash+export ANTHROPIC_API_KEY="sk-ant-..."```-## 1. Install Dependencies+Or `OPENAI_API_KEY`, `GEMINI_API_KEY` — whichever provider you installed.-From the repowise root:+On Windows PowerShell:```powershell-cd C:\Users\ragha\Desktop\repowise+$env:ANTHROPIC_API_KEY = "sk-ant-..."+```-# Python packages (all workspace packages)-uv sync+## 3. Initialize-# Node packages (web frontend)-npm install+```bash+cd /path/to/your-repo+repowise init```-## 2. Start the Backend (port 7337)+Repowise will walk you through an interactive setup — choose a provider, review the cost estimate, and confirm. It parses every file, builds a dependency graph, indexes git history, and generates wiki pages.-Open a PowerShell terminal:+A typical run on a ~500-file codebase takes 5-15 minutes.-```powershell-cd C:\Users\ragha\Desktop\repowise+**Want to skip LLM costs?** Use `--index-only` to just parse and analyze without generating docs:++```bash+repowise init --index-only+```-$env:REPOWISE_DB_URL = "sqlite+aiosqlite:///C:/Users/ragha/Desktop/interview-coach/.repowise/wiki.db"-$env:GEMINI_API_KEY = "YOUR_GEMINI_API_KEY"-$env:REPOWISE_EMBEDDER = "gemini"+## 4. Explore-uv run uvicorn repowise.server.app:create_app --factory --host 0.0.0.0 --port 7337 --reload+Once init completes, you have several ways to use the wiki:++**Search from the terminal:**++```bash+repowise search "authentication"+repowise search "how are errors handled" --mode semantic```-Verify: `http://localhost:7337/health` should return `{"status": "ok"}`.+**Browse in a web UI:**-## 3. Start the Frontend (port 3000)+```bash+repowise serve+# API on http://localhost:7337, Web UI on http://localhost:3000+```-Open a second PowerShell terminal:+If Node.js 20+ is installed, the web UI starts automatically. Otherwise, use Docker (see below).-```powershell-cd C:\Users\ragha\Desktop\repowise+**Connect to your AI editor (Claude Code, Cursor, Cline, Windsurf):**++```bash+repowise mcp --transport stdio+```++## 5. Keep It in Sync++After pulling changes or editing code:-$env:REPOWISE_API_URL = "http://localhost:7337"+```bash+repowise update+```++Or run continuous sync while you work:++```bash+repowise watch+```++---++## Web UI++Repowise includes a full web dashboard with a wiki browser, interactive dependency graph, codebase chat, search, code ownership, hotspots, and dead code detection.++### With Node.js installed++If you have Node.js 20+, `repowise serve` auto-downloads and starts the web UI:-npm run dev --workspace packages/web+```bash+repowise serve+# API: http://localhost:7337+# Web UI: http://localhost:3000```-Open **http://localhost:3000** in your browser.+The frontend is downloaded once (~50 MB) and cached in `~/.repowise/web/`.-## 4. Test the Chat+To skip the web UI and only run the API: `repowise serve --no-ui`-1. Click your repo on the dashboard-2. You'll see the chat interface with suggestion chips-3. Try: *"Give me an overview of this codebase"*-4. Watch the streaming response with tool calls appearing in real time-5. Click **View** on any tool result to open the artifact panel+### With Docker (no Node.js needed)++```bash+docker build -t repowise https://github.com/RaghavChamadiya/repowise.git++docker run -p 7337:7337 -p 3000:3000 \+ -v /path/to/your-repo/.repowise:/data \+ -e GEMINI_API_KEY=your-key \+ -e REPOWISE_EMBEDDER=gemini \+ repowise+```++### From source (for development)++```bash+git clone https://github.com/RaghavChamadiya/repowise.git+cd repowise && npm install++# Terminal 1: API+repowise serve --no-ui++# Terminal 2: Frontend (with hot reload)+REPOWISE_API_URL=http://localhost:7337 npm run dev --workspace packages/web+```-## Environment Variables Reference+----| Variable | Required | Description |-|----------|----------|-------------|-| `REPOWISE_DB_URL` | Yes | SQLite/PostgreSQL connection string pointing to the indexed wiki DB |-| `GEMINI_API_KEY` | If using Gemini | Google Gemini API key |-| `ANTHROPIC_API_KEY` | If using Anthropic | Anthropic API key |-| `OPENAI_API_KEY` | If using OpenAI | OpenAI API key |-| `REPOWISE_EMBEDDER` | No (default: `mock`) | Embedder for RAG search: `gemini`, `openai`, or `mock` |-| `REPOWISE_API_URL` | Frontend only | Backend URL for Next.js proxy (default: `http://localhost:7337`) |-| `REPOWISE_API_KEY` | No | Optional API key to protect the backend; omit for local dev |+## Environment Variables-## Switching LLM Providers+| Variable | When needed | Description |+|----------|-------------|-------------|+| `ANTHROPIC_API_KEY` | Using Anthropic | Anthropic API key |+| `OPENAI_API_KEY` | Using OpenAI | OpenAI API key |+| `GEMINI_API_KEY` | Using Gemini | Google Gemini API key |+| `REPOWISE_EMBEDDER` | Semantic search | Embedder: `gemini`, `openai`, or `mock` (default) |+| `REPOWISE_DB_URL` | Custom database | SQLite/PostgreSQL connection string (default: `.repowise/wiki.db`) |+| `REPOWISE_API_URL` | Frontend only | Backend URL for the web UI (default: `http://localhost:7337`) |-The chat model selector in the UI lets you switch providers on the fly. To use a different provider, set its API key env var on the backend and restart. The chat will auto-detect configured providers.+----## Troubleshooting+## What's Next-- **"embedder.mock_active" warning** — Set `$env:REPOWISE_EMBEDDER = "gemini"` (or `openai`) for real vector search-- **Empty repo list** — Check `REPOWISE_DB_URL` points to a DB with indexed repos-- **Chat returns 422** — The active provider doesn't have an API key set; check env vars-- **CORS errors** — Backend CORS is open (`*`) by default; ensure both servers are running+- **[User Guide](USER_GUIDE.md)** — full CLI reference (all 13 commands with every flag), web UI features, MCP setup, common workflows, and troubleshooting+- **[Architecture](ARCHITECTURE.md)** — how repowise is built internallydiff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.mdindex d58a29a3c..eb5cc24f1 100644--- a/docs/USER_GUIDE.md+++ b/docs/USER_GUIDE.md@@ -334,21 +334,36 @@ See [MCP Integration](#mcp-integration-with-ai-editors) for setup instructions.### `repowise serve`-Start a local web server for browsing the wiki in your browser.+Start the API server and web UI.```bashrepowise serve [PATH]```+If Node.js 20+ is installed, the web frontend is automatically downloaded (once, ~50 MB) and started alongside the API. No separate setup needed.+**Options:**| Flag | Description ||------|-------------|-| `--port` | Port (default: 7337) |-| `--host` | Host (default: 127.0.0.1) |+| `--port` | API server port (default: 7337) |+| `--host` | Host to bind to (default: 127.0.0.1) || `--workers` | Uvicorn workers (default: 1) |+| `--ui-port` | Web UI port (default: 3000) |+| `--no-ui` | Start API server only, skip the web UI. |++**Examples:**++```bash+# Start everything (API + Web UI)+repowise serve-Opens a FastAPI server with a REST API. Pair with the web frontend for a full UI experience (see [Web UI](#web-ui)).+# API only+repowise serve --no-ui++# Custom ports+repowise serve --port 8080 --ui-port 8081+```---@@ -533,22 +548,57 @@ Checks:## Web UI-Repowise includes a full web dashboard built with Next.js, React, and D3.js. It requires Node.js 20+ and runs alongside the backend server.+Repowise includes a full web dashboard built with Next.js, React, and D3.js.-### Starting the Web UI+### Automatic (with Node.js)-**Terminal 1 — Backend:**+If you have Node.js 20+ installed, `repowise serve` handles everything:```bash-cd /path/to/your-repo-repowise serve --port 7337+repowise serve+# API: http://localhost:7337+# Web UI: http://localhost:3000```-**Terminal 2 — Frontend:**+On first run, the pre-built frontend is downloaded (~50 MB) and cached in `~/.repowise/web/`. Subsequent runs start instantly.++### Docker (no Node.js needed)```bash-cd /path/to/repowise # the repowise source repo-npm install # first time only+# Build the image (one-time)+docker build -t repowise https://github.com/RaghavChamadiya/repowise.git++# Run with your indexed repo's .repowise directory+docker run -p 7337:7337 -p 3000:3000 \+ -v /path/to/your-repo/.repowise:/data \+ -e GEMINI_API_KEY=your-key \+ -e REPOWISE_EMBEDDER=gemini \+ repowise+```++Or with docker compose:++```bash+git clone https://github.com/RaghavChamadiya/repowise.git+cd repowise+export REPOWISE_DATA=/path/to/your-repo/.repowise+export GEMINI_API_KEY=your-key+docker compose up+```++Open **http://localhost:3000** for the Web UI, **http://localhost:7337** for the API.++### From source (for development)++For working on the frontend code with hot reload:++```bash+# Terminal 1 — API only+repowise serve --no-ui++# Terminal 2 — Frontend with hot reload+cd /path/to/repowise+npm installREPOWISE_API_URL=http://localhost:7337 npm run dev --workspace packages/web```diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd.py b/packages/cli/src/repowise/cli/commands/serve_cmd.pyindex 15fcbc933..a6060e555 100644--- a/packages/cli/src/repowise/cli/commands/serve_cmd.py+++ b/packages/cli/src/repowise/cli/commands/serve_cmd.py@@ -1,33 +1,253 @@-"""``repowise serve`` — start the FastAPI web server."""+"""``repowise serve`` — start the API server and web UI."""from __future__ import annotations+import os+import shutil+import subprocess+import sys+import tarfile+import tempfile+from pathlib import Path+import click+from repowise.cli import __version__from repowise.cli.helpers import console+_GITHUB_REPO = "RaghavChamadiya/repowise"+_WEB_CACHE_DIR = Path.home() / ".repowise" / "web"+_MARKER_FILE = _WEB_CACHE_DIR / ".version"+++def _node_available() -> str | None:+ """Return the path to node binary, or None."""+ return shutil.which("node")+++def _npm_available() -> str | None:+ """Return the path to npm binary, or None."""+ return shutil.which("npm")+++def _web_is_cached(version: str) -> bool:+ """Check if the web frontend is cached and matches the current version."""+ server_js = _WEB_CACHE_DIR / "server.js"+ if not server_js.exists():+ return False+ if _MARKER_FILE.exists() and _MARKER_FILE.read_text().strip() == version:+ return True+ return False+++def _find_local_web() -> Path | None:+ """Check if running from the repo with packages/web available."""+ # Walk up from this file to find the repo root+ candidate = Path(__file__).resolve()+ for _ in range(10):+ candidate = candidate.parent+ pkg_web = candidate / "packages" / "web"+ if (pkg_web / "package.json").exists():+ # Check if it's been built+ standalone = pkg_web / ".next" / "standalone" / "server.js"+ if standalone.exists():+ return pkg_web+ return pkg_web # exists but may need build+ return None+++def _download_web(version: str) -> bool:+ """Download pre-built web frontend from GitHub releases."""+ import urllib.request+ import urllib.error++ tag = f"v{version}"+ url = f"https://github.com/{_GITHUB_REPO}/releases/download/{tag}/repowise-web.tar.gz"++ console.print(f"[dim]Downloading web UI from {url}...[/dim]")+ try:+ with tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False) as tmp:+ urllib.request.urlretrieve(url, tmp.name)+ tmp_path = tmp.name+ except (urllib.error.URLError, urllib.error.HTTPError) as exc:+ console.print(f"[yellow]Could not download web UI: {exc}[/yellow]")+ return False++ try:+ _WEB_CACHE_DIR.mkdir(parents=True, exist_ok=True)+ # Clean old cache+ for item in _WEB_CACHE_DIR.iterdir():+ if item.is_dir():+ shutil.rmtree(item)+ else:+ item.unlink()++ with tarfile.open(tmp_path, "r:gz") as tar:+ tar.extractall(_WEB_CACHE_DIR)++ _MARKER_FILE.write_text(version)+ console.print("[green]Web UI downloaded and cached.[/green]")+ return True+ except Exception as exc:+ console.print(f"[yellow]Failed to extract web UI: {exc}[/yellow]")+ return False+ finally:+ os.unlink(tmp_path)+++def _build_local_web(web_dir: Path, npm: str) -> bool:+ """Build the Next.js frontend from source."""+ console.print("[dim]Building web UI (first time only)...[/dim]")+ try:+ # Install deps if needed+ if not (web_dir / "node_modules").exists():+ subprocess.run(+ [npm, "install"],+ cwd=str(web_dir),+ check=True,+ capture_output=True,+ )+ # Build+ subprocess.run(+ [npm, "run", "build"],+ cwd=str(web_dir),+ check=True,+ capture_output=True,+ )+ return True+ except subprocess.CalledProcessError as exc:+ console.print(f"[yellow]Web UI build failed: {exc}[/yellow]")+ return False+++def _start_frontend(node: str, backend_port: int, frontend_port: int) -> subprocess.Popen | None:+ """Start the Next.js frontend server. Returns the process or None."""+ env = {+ **os.environ,+ "REPOWISE_API_URL": f"http://localhost:{backend_port}",+ "HOSTNAME": "0.0.0.0",+ "PORT": str(frontend_port),+ }++ # Option 1: Cached download+ cached_server = _WEB_CACHE_DIR / "server.js"+ if cached_server.exists():+ return subprocess.Popen(+ [node, str(cached_server)],+ cwd=str(_WEB_CACHE_DIR),+ env=env,+ )++ # Option 2: Local repo build+ local_web = _find_local_web()+ if local_web:+ standalone_dir = local_web / ".next" / "standalone"+ server_js = standalone_dir / "server.js"+ if server_js.exists():+ # Copy static files into standalone (Next.js requirement)+ static_src = local_web / ".next" / "static"+ static_dst = standalone_dir / ".next" / "static"+ if static_src.exists() and not static_dst.exists():+ shutil.copytree(str(static_src), str(static_dst))+ public_src = local_web / "public"+ public_dst = standalone_dir / "public"+ if public_src.exists() and not public_dst.exists():+ shutil.copytree(str(public_src), str(public_dst))++ return subprocess.Popen(+ [node, str(server_js)],+ cwd=str(standalone_dir),+ env=env,+ )++ return None+@click.command("serve")[email protected]("--port", default=7337, type=int, help="Port to listen on.")[email protected]("--port", default=7337, type=int, help="API server port.")@click.option("--host", default="127.0.0.1", help="Host to bind to.")@click.option("--workers", default=1, type=int, help="Number of uvicorn workers.")-def serve_command(port: int, host: str, workers: int) -> None:- """Start a local web server for browsing wiki pages."""[email protected]("--ui-port", default=3000, type=int, help="Web UI port.")[email protected]("--no-ui", is_flag=True, help="Start API server only, skip the web UI.")+def serve_command(port: int, host: str, workers: int, ui_port: int, no_ui: bool) -> None:+ """Start the repowise server with the web UI.++ Starts the API backend and automatically launches the web frontend.+ The web UI is downloaded and cached on first run (~50 MB, one-time).++ Use --no-ui to start only the API server.+ """try:import uvicornexcept ImportError:console.print(- "[red]uvicorn is not installed. "- "Install repowise-server: pip install repowise-server[/red]"+ "[red]uvicorn is not installed. Install it with: pip install repowise[/red]")raise SystemExit(1)- console.print(f"[green]Starting repowise server on {host}:{port}[/green]")- uvicorn.run(- "repowise.server.app:create_app",- factory=True,- host=host,- port=port,- workers=workers,- log_level="info",- )+ frontend_proc: subprocess.Popen | None = None++ if not no_ui:+ node = _node_available()+ npm = _npm_available()++ if not node:+ console.print(+ "[yellow]Node.js not found — starting API server only.[/yellow]\n"+ "[dim]To get the web UI, install Node.js 20+ or use Docker:\n"+ " docker run -p 7337:7337 -p 3000:3000 -v .repowise:/data repowise[/dim]"+ )+ else:+ # Try to get the frontend running+ ready = False++ # Check cached download+ if _web_is_cached(__version__):+ ready = True++ # Check local repo build+ if not ready:+ local_web = _find_local_web()+ if local_web:+ standalone = local_web / ".next" / "standalone" / "server.js"+ if standalone.exists():+ ready = True+ elif npm:+ ready = _build_local_web(local_web, npm)++ # Try downloading from GitHub releases+ if not ready:+ ready = _download_web(__version__)++ if ready:+ frontend_proc = _start_frontend(node, port, ui_port)+ if frontend_proc:+ console.print(+ f"[green]Web UI starting on http://localhost:{ui_port}[/green]"+ )+ else:+ console.print("[yellow]Could not start web UI — running API only.[/yellow]")+ else:+ console.print(+ "[yellow]Web UI not available — starting API server only.[/yellow]\n"+ "[dim]The web UI will be available in a future release.\n"+ "For now, use Docker for the full experience:[/dim]\n"+ f"[dim] docker build -t repowise https://github.com/{_GITHUB_REPO}.git\n"+ " docker run -p 7337:7337 -p 3000:3000 -v .repowise:/data repowise[/dim]"+ )++ console.print(f"[green]API server starting on http://{host}:{port}[/green]")++ try:+ uvicorn.run(+ "repowise.server.app:create_app",+ factory=True,+ host=host,+ port=port,+ workers=workers,+ log_level="info",+ )+ finally:+ if frontend_proc:+ frontend_proc.terminate()+ frontend_proc.wait(timeout=5)