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
fix(serve): auto-fallback to next free port when 3000/7337 is taken (#287)
Raghav Chamadiya3cec03c37e1a
diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd.py b/packages/cli/src/repowise/cli/commands/serve_cmd.pyindex 99d55e82f..8029291c8 100644--- a/packages/cli/src/repowise/cli/commands/serve_cmd.py+++ b/packages/cli/src/repowise/cli/commands/serve_cmd.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport osimport shutil+import socketimport subprocessimport tarfileimport tempfile@@ -189,6 +190,45 @@ def _load_local_provider_config() -> None:os.environ["REPOWISE_EMBEDDER"] = str(embedder)+def _is_port_free(host: str, port: int) -> bool:+ """Return True if *port* can be bound on *host* right now."""+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:+ try:+ sock.bind((host, port))+ except OSError:+ return False+ return True+++def _find_free_port(host: str, preferred: int, label: str, max_attempts: int = 20) -> int:+ """Return *preferred* if free, otherwise the next free port within range.++ Falls back to an OS-assigned port if a contiguous slot can't be found.+ Prints a notice when the preferred port is unavailable so the user knows+ the bind moved.+ """+ if _is_port_free(host, preferred):+ return preferred++ for offset in range(1, max_attempts + 1):+ candidate = preferred + offset+ if candidate > 65535:+ break+ if _is_port_free(host, candidate):+ console.print(+ f"[yellow]Port {preferred} for {label} is in use — using {candidate} instead.[/yellow]"+ )+ return candidate++ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:+ sock.bind((host, 0))+ candidate = sock.getsockname()[1]+ console.print(+ f"[yellow]Port {preferred} for {label} and nearby ports busy — using {candidate}.[/yellow]"+ )+ return candidate++_GITHUB_REPO = "repowise-dev/repowise"_WEB_CACHE_DIR = Path.home() / ".repowise" / "web"_MARKER_FILE = _WEB_CACHE_DIR / ".version"@@ -449,9 +489,18 @@ def serve_command(os.environ["REPOWISE_DB_URL"] = f"sqlite+aiosqlite:///{local_db.as_posix()}"console.print(f"[dim]Using local database: {local_db}[/dim]")+ # Resolve a usable API port up front — uvicorn would otherwise crash later+ # with a bare OSError, and the chosen port needs to flow into the frontend+ # via REPOWISE_API_URL.+ port = _find_free_port(host, port, "API server")+frontend_proc: subprocess.Popen | None = Noneif not no_ui:+ # The Next.js server binds to 0.0.0.0 (see HOSTNAME below), so probe+ # there — a port can be free on 127.0.0.1 but taken on the wildcard.+ ui_port = _find_free_port("0.0.0.0", ui_port, "web UI")+node = _node_available()npm = _npm_available()diff --git a/tests/unit/cli/test_serve_port_fallback.py b/tests/unit/cli/test_serve_port_fallback.pynew file mode 100644index 000000000..a5ecbec95--- /dev/null+++ b/tests/unit/cli/test_serve_port_fallback.py@@ -0,0 +1,70 @@+"""Regression tests for `repowise serve` port auto-fallback (issue #232).++When the user's project already occupies the default UI port (3000) or the+default API port (7337), `repowise serve` should pick the next available+port instead of crashing with EADDRINUSE.+"""++from __future__ import annotations++import socket++import pytest++from repowise.cli.commands import serve_cmd+++def _bind_listener(host: str = "127.0.0.1") -> tuple[socket.socket, int]:+ """Bind a listening socket on an OS-assigned port and return (sock, port)."""+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ sock.bind((host, 0))+ sock.listen(1)+ return sock, sock.getsockname()[1]+++def test_is_port_free_detects_free_port() -> None:+ sock, port = _bind_listener()+ sock.close()+ assert serve_cmd._is_port_free("127.0.0.1", port) is True+++def test_is_port_free_detects_busy_port() -> None:+ sock, port = _bind_listener()+ try:+ assert serve_cmd._is_port_free("127.0.0.1", port) is False+ finally:+ sock.close()+++def test_find_free_port_returns_preferred_when_free() -> None:+ sock, port = _bind_listener()+ sock.close()+ assert serve_cmd._find_free_port("127.0.0.1", port, "test") == port+++def test_find_free_port_falls_back_to_next_available() -> None:+ """The exact scenario from issue #232: preferred port already taken."""+ sock, busy_port = _bind_listener()+ try:+ chosen = serve_cmd._find_free_port("127.0.0.1", busy_port, "web UI")+ assert chosen != busy_port+ assert chosen > busy_port+ # Chosen port must actually be bindable.+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:+ probe.bind(("127.0.0.1", chosen))+ finally:+ sock.close()+++def test_find_free_port_handles_contiguous_busy_block(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """When the preferred port and the scan window are all busy, fall back+ to an OS-assigned ephemeral port instead of raising."""+ # Pretend every port in the scan range is busy; the function should still+ # produce a usable port via the wildcard bind path.+ monkeypatch.setattr(serve_cmd, "_is_port_free", lambda host, port: False)++ chosen = serve_cmd._find_free_port("127.0.0.1", 3000, "web UI", max_attempts=5)+ assert isinstance(chosen, int)+ assert 1024 <= chosen <= 65535