Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)
Python
patch: Explain busy port when fcc-server cannot start (#1958)
Basile Vincenzod93a4c3317d8
diff --git a/src/free_claude_code/cli/commands.py b/src/free_claude_code/cli/commands.pyindex 25b8aa57..35b63531 100644--- a/src/free_claude_code/cli/commands.py+++ b/src/free_claude_code/cli/commands.py@@ -8,7 +8,7 @@ import timeimport webbrowserfrom collections.abc import Callablefrom enum import StrEnum-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Anyfrom urllib.error import HTTPError, URLErrorfrom urllib.request import Request@@ -72,10 +72,54 @@ def serve() -> None:try:ServerSupervisor().run()except OSError as exc:- logger.error("Could not start FCC: {}", exc)+ if exc.errno == errno.EADDRINUSE:+ _log_port_in_use(get_settings())+ else:+ logger.error("Could not start FCC: {}", exc)raise SystemExit(1) from None+def _log_port_in_use(settings: Settings) -> None:+ """Explain a busy port, telling a running FCC apart from another program."""+ status = None+ try:+ status = _external_fcc_status(settings, timeout=1.5)+ other_program = status is None+ except HTTPError as exc:+ # Admin rejects non-loopback requests, so a 403 cannot rule out FCC.+ other_program = exc.code != 403+ except ValueError:+ other_program = True+ except OSError:+ other_program = False+ if status is not None and status["status"] == "running":+ logger.error(+ "FCC is already running on port {}. Use it at {}, or stop it before "+ "starting another instance.",+ settings.port,+ local_admin_url(settings),+ )+ elif status is not None:+ logger.error(+ "The FCC instance on port {} is still stopping. Try again in a moment.",+ settings.port,+ )+ elif other_program:+ logger.error(+ "Could not start FCC: port {} is already in use by another program. "+ "Stop that program, or set PORT to a free port in {}.",+ settings.port,+ managed_env_path(),+ )+ else:+ logger.error(+ "Could not start FCC: port {} is already in use. If FCC is not already "+ "running, stop the program using it, or set PORT to a free port in {}.",+ settings.port,+ managed_env_path(),+ )++class ServerStatus(StrEnum):"""Observable state of the server owned by a supervisor."""@@ -351,32 +395,42 @@ def load_server_settings() -> Settings:return get_settings()+def _external_fcc_status(+ settings: Settings, *, timeout: float+) -> dict[str, Any] | None:+ """Return the status payload an FCC instance reports on this port, or None for other servers."""+ url = f"{local_proxy_root_url(settings)}/admin/api/status"+ with open_local_request(Request(url), timeout=timeout) as response:+ payload = json.loads(response.read().decode("utf-8"))+ if not isinstance(payload, dict) or not (+ isinstance(payload.get("instance_id"), str)+ and len(payload["instance_id"]) == 32+ and payload.get("status") in {"running", "stopping"}+ and isinstance(payload.get("host"), str)+ and payload.get("port") == settings.port+ and isinstance(payload.get("provider_status"), list)+ and isinstance(payload.get("cached_models"), dict)+ ):+ return None+ return payload++def open_admin_when_ready(settings: Settings, *, stop_event: threading.Event | None = None) -> bool:"""Recognize an external FCC instance and attempt to open its local Admin page."""stop = stop_event or threading.Event()deadline = time.monotonic() + 30.0- url = f"{local_proxy_root_url(settings)}/admin/api/status"while not stop.is_set() and time.monotonic() < deadline:try:- with open_local_request(Request(url), timeout=1.5) as response:- payload = json.loads(response.read().decode("utf-8"))- if not isinstance(payload, dict) or not (- isinstance(payload.get("instance_id"), str)- and len(payload["instance_id"]) == 32- and payload.get("status") in {"running", "stopping"}- and isinstance(payload.get("host"), str)- and payload.get("port") == settings.port- and isinstance(payload.get("provider_status"), list)- and isinstance(payload.get("cached_models"), dict)- ):+ status = _external_fcc_status(settings, timeout=1.5)+ if status is None:return False- if payload["status"] == "running" and not stop.is_set():+ if status["status"] == "running" and not stop.is_set():completed = _start_admin_browser(settings,lambda: not stop.is_set(),- instance_id=payload["instance_id"],+ instance_id=status["instance_id"],)# This extra launcher is about to exit: allow a brief URL handoff.handoff_deadline = time.monotonic() + _BROWSER_HANDOFF_SECONDSdiff --git a/tests/cli/test_progressive_launch.py b/tests/cli/test_progressive_launch.pyindex 08b23b60..82fa5c20 100644--- a/tests/cli/test_progressive_launch.py+++ b/tests/cli/test_progressive_launch.py@@ -6,10 +6,11 @@ import subprocessimport sysimport threadingfrom contextlib import asynccontextmanager+from email.message import Messagefrom pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock-from urllib.error import URLError+from urllib.error import HTTPError, URLErrorimport pytestimport uvicorn@@ -204,6 +205,73 @@ def test_browser_warning_retains_owning_instance_after_server_exit(assert {record.extra["instance_id"] for record in caplog.records} == set(instances)+ ("occupant", "expected"),+ [+ ("running", "FCC is already running on port 8082. Use it at http://"),+ ("stopping", "The FCC instance on port 8082 is still stopping."),+ ("other", "port 8082 is already in use by another program"),+ ("not_found", "port 8082 is already in use by another program"),+ ("forbidden", "port 8082 is already in use. If FCC is not already running"),+ ("unreachable", "port 8082 is already in use. If FCC is not already running"),+ ],+)+def test_terminal_serve_explains_busy_port(monkeypatch, caplog, occupant, expected):+ settings = Settings()+ monkeypatch.setattr(commands, "get_settings", lambda: settings)+ monkeypatch.setattr(+ commands.ServerSupervisor,+ "run",+ MagicMock(side_effect=OSError(errno.EADDRINUSE, "Address already in use")),+ )+ if occupant == "unreachable":+ request = MagicMock(side_effect=URLError("refused"))+ elif occupant in {"not_found", "forbidden"}:+ code = 404 if occupant == "not_found" else 403+ error = HTTPError("url", code, "error", Message(), None)+ error.close() # Only the status code matters; release its body up front.+ request = MagicMock(side_effect=error)+ else:+ payload = {"unrelated": "server"}+ if occupant != "other":+ payload = {+ "instance_id": "a" * 32,+ "status": occupant,+ "host": settings.host,+ "port": settings.port,+ "provider_status": [],+ "cached_models": {},+ }+ response = MagicMock()+ response.__enter__.return_value.read.return_value = json.dumps(payload).encode()+ request = MagicMock(return_value=response)+ monkeypatch.setattr(commands, "open_local_request", request)++ with pytest.raises(SystemExit) as exited:+ commands.serve()++ assert exited.value.code == 1+ assert expected in caplog.text+ request.assert_called_once()+++def test_terminal_serve_reports_other_startup_errors_unchanged(monkeypatch, caplog):+ monkeypatch.setattr(+ commands.ServerSupervisor,+ "run",+ MagicMock(side_effect=OSError(errno.EACCES, "Permission denied")),+ )+ request = MagicMock()+ monkeypatch.setattr(commands, "open_local_request", request)++ with pytest.raises(SystemExit) as exited:+ commands.serve()++ assert exited.value.code == 1+ assert "Could not start FCC: [Errno" in caplog.text+ request.assert_not_called()++@pytest.mark.parametrize("change", ["none", "stop", "restart", "settings"])def test_queued_browser_rechecks_owner_before_handoff(monkeypatch, change):supervisor = commands.ServerSupervisor()