Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(serve): open the web UI in your browser once it is up (#4679)

Raghav Chamadiya3918ee4f8c60
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 030adf60b..64dc3f044 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -402,6 +402,7 @@ repowise serve --port 8080 --ui-port 8081
| `--workers` | Uvicorn workers. | `1` |
| `--ui-port` | Web UI port. | `3000` |
| `--no-ui` | API only. | off |
+| `--no-open` | Don't open the UI in a browser. It opens only in an interactive terminal outside CI, once the UI answers. Env `REPOWISE_NO_OPEN`. | off |
| `--refresh-ui` | Re-download the UI tarball (skips sources 1 and 2). | off |
The UI needs Node >= 20, else API-only. UI sources, in precedence:
diff --git a/docs/start/QUICKSTART.md b/docs/start/QUICKSTART.md
index f4f7aa719..11cbd7939 100644
--- a/docs/start/QUICKSTART.md
+++ b/docs/start/QUICKSTART.md
@@ -62,7 +62,8 @@ repowise serve
This is the first thing to run after `init`. The API starts on port 7337 and
the dashboard on port 3000, or the next free port. The dashboard needs
Node.js 20+, and its first run downloads the UI (about 50 MB, cached in
-`~/.repowise/web/`). `--no-ui` starts the API alone, and the
+`~/.repowise/web/`). The dashboard opens in your browser once it is up;
+`--no-open` skips that. `--no-ui` starts the API alone, and the
[Docker image](../../docker/README.md) avoids installing Node. View by view:
[Dashboard](DASHBOARD.md).
diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd/_browser.py b/packages/cli/src/repowise/cli/commands/serve_cmd/_browser.py
new file mode 100644
index 000000000..8101f9dc7
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/serve_cmd/_browser.py
@@ -0,0 +1,107 @@
+"""Opening the web UI in the default browser once it answers."""
+
+from __future__ import annotations
+
+import logging
+import os
+import subprocess
+import sys
+import threading
+import time
+import urllib.error
+import urllib.request
+import webbrowser
+from collections.abc import Callable
+
+from repowise.cli.helpers import console
+
+logger = logging.getLogger(__name__)
+
+#: How long to wait for the UI before giving up quietly. A first start of the
+#: Next.js server takes a few seconds; a slow disk can take longer.
+_READY_TIMEOUT_S = 60.0
+_POLL_INTERVAL_S = 0.5
+
+# localhost never goes through a proxy, even when HTTP_PROXY is set.
+_NO_PROXY_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
+
+
+def has_display_for_browser() -> bool:
+ """False on a Linux box with no graphical session.
+
+ There ``webbrowser`` falls back to a text browser that would take over the
+ terminal the server logs to.
+ """
+ if not sys.platform.startswith("linux"):
+ return True
+ return bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"))
+
+
+def should_open_browser(
+ *, ui_started: bool, no_open: bool, interactive: bool, ci: bool, has_display: bool
+) -> bool:
+ """Open only for a person at a terminal whose UI actually started.
+
+ ``ui_started`` is False both for ``--no-ui`` and for a UI that could not
+ start (no Node, failed download).
+ """
+ return ui_started and not no_open and interactive and not ci and has_display
+
+
+def _ui_answers(url: str) -> bool:
+ """True when anything answers HTTP at *url*, an error status included."""
+ try:
+ with _NO_PROXY_OPENER.open(url, timeout=1):
+ return True
+ except urllib.error.HTTPError:
+ return True
+ except (urllib.error.URLError, OSError):
+ return False
+
+
+def _wait_until_up(
+ url: str,
+ proc: subprocess.Popen | None,
+ probe: Callable[[str], bool],
+ timeout_s: float,
+ interval_s: float,
+) -> bool:
+ """Poll *url*; False once the UI process exits or the timeout passes."""
+ deadline = time.monotonic() + timeout_s
+ while not probe(url):
+ if (proc is not None and proc.poll() is not None) or time.monotonic() > deadline:
+ return False
+ time.sleep(interval_s)
+ return True
+
+
+def _wait_and_open(
+ url: str,
+ proc: subprocess.Popen | None,
+ *,
+ probe: Callable[[str], bool] | None = None,
+ opener: Callable[[str], bool] | None = None,
+ timeout_s: float = _READY_TIMEOUT_S,
+ interval_s: float = _POLL_INTERVAL_S,
+) -> bool:
+ """Open *url* once it answers. Never raises: the server must not notice."""
+ try:
+ if not _wait_until_up(url, proc, probe or _ui_answers, timeout_s, interval_s):
+ logger.debug("web UI at %s never answered, not opening a browser", url)
+ return False
+ if not (opener or webbrowser.open)(url):
+ logger.debug("no browser available to open %s", url)
+ return False
+ console.print(f"[dim]Opening {url} in your browser[/dim]")
+ return True
+ except Exception: # a browser failure must never reach the server
+ logger.debug("could not open %s in a browser", url, exc_info=True)
+ return False
+
+
+def open_when_ready(ui_port: int, proc: subprocess.Popen | None) -> None:
+ """Open the UI root on localhost from a daemon thread, so the server never waits."""
+ url = f"http://localhost:{ui_port}"
+ threading.Thread(
+ target=_wait_and_open, args=(url, proc), name="repowise-open-browser", daemon=True
+ ).start()
diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd/command.py b/packages/cli/src/repowise/cli/commands/serve_cmd/command.py
index f41b5666e..f5f60db95 100644
--- a/packages/cli/src/repowise/cli/commands/serve_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/serve_cmd/command.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import os
import subprocess
+import sys
from pathlib import Path
from types import ModuleType
@@ -11,7 +12,7 @@ import click
from repowise.cli.helpers import console
-from . import _advisory, _embedder, _frontend, _lock, _ports
+from . import _advisory, _browser, _embedder, _frontend, _lock, _ports
_LOOPBACK_HOSTS = ("127.0.0.1", "localhost", "::1")
@@ -92,6 +93,21 @@ def _run_api(
frontend_proc.wait(timeout=5)
+def _maybe_open_browser(
+ frontend_proc: subprocess.Popen | None, ui_port: int, *, no_open: bool
+) -> None:
+ from repowise.cli.platform.telemetry.environment import is_ci
+
+ if _browser.should_open_browser(
+ ui_started=frontend_proc is not None,
+ no_open=no_open,
+ interactive=sys.stdin.isatty() and sys.stdout.isatty(),
+ ci=is_ci(),
+ has_display=_browser.has_display_for_browser(),
+ ):
+ _browser.open_when_ready(ui_port, frontend_proc)
+
+
@click.command("serve")
@click.option("--port", default=7337, type=int, help="API server port.", envvar="REPOWISE_PORT")
@click.option("--host", default="127.0.0.1", help="Host to bind to.")
@@ -103,20 +119,33 @@ def _run_api(
help="Web UI port (the next free one if taken).",
)
@click.option("--no-ui", is_flag=True, help="Start API server only, skip the web UI.")
+ "--no-open",
+ is_flag=True,
+ envvar="REPOWISE_NO_OPEN",
+ help="Don't open the web UI in a browser. Env: REPOWISE_NO_OPEN.",
+)
@click.option(
"--refresh-ui",
is_flag=True,
help="Force re-download of the web UI tarball, ignoring any cache.",
)
def serve_command(
- port: int, host: str, workers: int, ui_port: int, no_ui: bool, refresh_ui: bool
+ port: int,
+ host: str,
+ workers: int,
+ ui_port: int,
+ no_ui: bool,
+ no_open: bool,
+ refresh_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.
+ In an interactive terminal the web UI opens in your browser once it
+ answers. Use --no-open to skip that, --no-ui to start only the API server.
"""
uvicorn = _import_uvicorn()
_advisory._start_update_advisory()
@@ -138,6 +167,7 @@ def serve_command(
# The UI takes the same bind as the API, so probe there.
ui_port = _ports._find_free_port(host, ui_port, "web UI")
frontend_proc = _frontend._launch_web_ui(host, port, ui_port, refresh_ui=refresh_ui)
+ _maybe_open_browser(frontend_proc, ui_port, no_open=no_open)
console.print(f"[green]API server starting on http://{host}:{port}[/green]")
_run_api(
diff --git a/tests/unit/cli/test_serve_open_browser.py b/tests/unit/cli/test_serve_open_browser.py
new file mode 100644
index 000000000..44ffa9610
--- /dev/null
+++ b/tests/unit/cli/test_serve_open_browser.py
@@ -0,0 +1,164 @@
+"""`repowise serve` opens the web UI in a browser only when a person can see it."""
+
+from __future__ import annotations
+
+import threading
+
+import pytest
+
+from repowise.cli.commands.serve_cmd import _browser
+
+_OPEN = {"ui_started": True, "no_open": False, "interactive": True, "ci": False, "has_display": True}
+
+
+def test_opens_for_an_interactive_run_whose_ui_started() -> None:
+ assert _browser.should_open_browser(**_OPEN)
+
+
+ ("field", "value"),
+ [
+ ("ui_started", False), # --no-ui, or no Node / failed download
+ ("no_open", True),
+ ("interactive", False),
+ ("ci", True),
+ ("has_display", False),
+ ],
+)
+def test_any_blocker_keeps_the_browser_closed(field: str, value: bool) -> None:
+ assert not _browser.should_open_browser(**{**_OPEN, field: value})
+
+
+def test_opens_the_ui_root_once_after_it_answers() -> None:
+ answers = iter([False, False, True])
+ probed: list[str] = []
+ opened: list[str] = []
+
+ def probe(url: str) -> bool:
+ probed.append(url)
+ return next(answers)
+
+ def opener(url: str) -> bool:
+ opened.append(url)
+ return True
+
+ assert _browser._wait_and_open(
+ "http://localhost:3000", None, probe=probe, opener=opener, interval_s=0
+ )
+ assert len(probed) == 3
+ assert opened == ["http://localhost:3000"]
+
+
+def test_never_opens_a_url_that_is_not_up() -> None:
+ opened: list[str] = []
+ result = _browser._wait_and_open(
+ "http://localhost:3000",
+ None,
+ probe=lambda _url: False,
+ opener=opened.append,
+ timeout_s=0,
+ interval_s=0,
+ )
+ assert result is False
+ assert opened == []
+
+
+def test_stops_waiting_when_the_ui_process_exits() -> None:
+ class _Exited:
+ def poll(self) -> int:
+ return 1
+
+ opened: list[str] = []
+ result = _browser._wait_and_open(
+ "http://localhost:3000",
+ _Exited(), # type: ignore[arg-type]
+ probe=lambda _url: False,
+ opener=opened.append,
+ timeout_s=60,
+ interval_s=0,
+ )
+ assert result is False
+ assert opened == []
+
+
+def test_an_opener_failure_is_swallowed() -> None:
+ def boom(_url: str) -> bool:
+ raise RuntimeError("no browser")
+
+ assert not _browser._wait_and_open(
+ "http://localhost:3000", None, probe=lambda _url: True, opener=boom
+ )
+
+
+def test_open_when_ready_targets_localhost_on_the_ui_port(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ done = threading.Event()
+ opened: list[str] = []
+
+ def fake_open(url: str) -> bool:
+ opened.append(url)
+ done.set()
+ return True
+
+ monkeypatch.setattr(_browser, "_ui_answers", lambda _url: True)
+ monkeypatch.setattr(_browser.webbrowser, "open", fake_open)
+ _browser.open_when_ready(3001, None)
+ assert done.wait(5)
+ assert opened == ["http://localhost:3001"]
+
+
+def test_ui_answers_counts_an_error_status_as_up(monkeypatch: pytest.MonkeyPatch) -> None:
+ import urllib.error
+
+ def raise_http_error(url: str, timeout: float) -> None:
+ raise urllib.error.HTTPError(url, 500, "boom", None, None) # type: ignore[arg-type]
+
+ monkeypatch.setattr(_browser._NO_PROXY_OPENER, "open", raise_http_error)
+ assert _browser._ui_answers("http://localhost:3000")
+
+
+def test_ui_answers_is_false_when_nothing_listens(monkeypatch: pytest.MonkeyPatch) -> None:
+ def refuse(url: str, timeout: float) -> None:
+ raise ConnectionRefusedError
+
+ monkeypatch.setattr(_browser._NO_PROXY_OPENER, "open", refuse)
+ assert not _browser._ui_answers("http://localhost:3000")
+
+
[email protected](("no_open", "expected"), [(False, [(3000, "proc")]), (True, [])])
+def test_serve_wires_the_flag_and_terminal_into_the_decision(
+ monkeypatch: pytest.MonkeyPatch, no_open: bool, expected: list[tuple[int, str]]
+) -> None:
+ import io
+ import sys
+
+ from repowise.cli.commands.serve_cmd import command
+ from repowise.cli.platform.telemetry import environment
+
+ class _Tty(io.StringIO):
+ def isatty(self) -> bool:
+ return True
+
+ calls: list[tuple[int, str]] = []
+ monkeypatch.setattr(sys, "stdin", _Tty())
+ monkeypatch.setattr(sys, "stdout", _Tty())
+ monkeypatch.setattr(environment, "is_ci", lambda: False)
+ monkeypatch.setattr(_browser, "has_display_for_browser", lambda: True)
+ monkeypatch.setattr(_browser, "open_when_ready", lambda port, proc: calls.append((port, proc)))
+ command._maybe_open_browser("proc", 3000, no_open=no_open) # type: ignore[arg-type]
+ assert calls == expected
+
+
[email protected](("env", "args", "expected"), [(None, [], False), ("1", [], True), (None, ["--no-open"], True)])
+def test_no_open_reads_the_flag_and_env(
+ monkeypatch: pytest.MonkeyPatch, env: str | None, args: list[str], expected: bool
+) -> None:
+ from repowise.cli.commands.serve_cmd import serve_command
+
+ if env is None:
+ monkeypatch.delenv("REPOWISE_NO_OPEN", raising=False)
+ else:
+ monkeypatch.setenv("REPOWISE_NO_OPEN", env)
+ ctx = serve_command.make_context("serve", list(args))
+ assert ctx.params["no_open"] is expected