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: Identify server instances and versions in logs (#1950)
Ali Khokhare40eb4062b4b
diff --git a/src/free_claude_code/cli/commands.py b/src/free_claude_code/cli/commands.pyindex 5421a461..25b8aa57 100644--- a/src/free_claude_code/cli/commands.py+++ b/src/free_claude_code/cli/commands.py@@ -35,20 +35,23 @@ _BROWSER_HANDOFF_SECONDS = 5.0def _start_admin_browser(- settings: Settings, eligible: Callable[[], bool]+ settings: Settings, eligible: Callable[[], bool], *, instance_id: str) -> threading.Event:"""Hand off an optional browser action without keeping FCC alive."""completed = threading.Event()url = local_admin_url(settings)+ browser_logger = logger.bind(instance_id=instance_id)def open_browser() -> None:try:if eligible() and not webbrowser.open(url):- logger.warning(+ browser_logger.warning("Could not open Admin in a browser. Open {} manually.", url)except Exception as exc:- logger.warning("Could not open Admin: {}. Open {} manually.", exc, url)+ browser_logger.warning(+ "Could not open Admin: {}. Open {} manually.", exc, url+ )finally:completed.set()@@ -57,7 +60,7 @@ def _start_admin_browser(target=open_browser, name="fcc-open-admin-browser", daemon=True).start()except Exception as exc:- logger.warning(+ browser_logger.warning("Could not start the Admin browser: {}. Open {} manually.", exc, url)completed.set()@@ -93,6 +96,7 @@ class ServerSupervisor:self._running = Falseself.stop_event = threading.Event()self._ready_settings: Settings | None = None+ self._ready_instance_id: str | None = Noneself._pending_admin = Falseself._auto_browser_opened = Falseself._owned_server = False@@ -211,11 +215,14 @@ class ServerSupervisor:returnself._pending_admin = Truesettings = self._ready_settings+ instance_id = self._ready_instance_idgeneration = self._restart_generation- if settings is not None:- self._open_admin(settings, generation)+ if settings is not None and instance_id is not None:+ self._open_admin(settings, generation, instance_id)- def _open_admin(self, settings: Settings, generation: int) -> None:+ def _open_admin(+ self, settings: Settings, generation: int, instance_id: str+ ) -> None:def eligible() -> bool:with self._lock:if (@@ -227,7 +234,7 @@ class ServerSupervisor:self._pending_admin = Falsereturn True- _start_admin_browser(settings, eligible)+ _start_admin_browser(settings, eligible, instance_id=instance_id)def _run_once(self,@@ -283,12 +290,15 @@ class ServerSupervisor:):returnself._ready_settings = settings+ self._ready_instance_id = asgi_app.runtime.instance_idshould_open = open_admin_browser or self._pending_adminif open_admin_browser:self._auto_browser_opened = Trueasgi_app.runtime.http_started()if should_open:- self._open_admin(settings, restart_generation)+ self._open_admin(+ settings, restart_generation, asgi_app.runtime.instance_id+ )server = RuntimeServer(config,@@ -305,12 +315,14 @@ class ServerSupervisor:server.should_exit = Truetry:- server.run(sockets=sockets)+ with logger.contextualize(instance_id=asgi_app.runtime.instance_id):+ server.run(sockets=sockets)finally:with self._lock:if self._server is server:self._server = Noneself._ready_settings = None+ self._ready_instance_id = Nonewith self._lock:restart_requested = self._restart_generation != restart_generation@@ -361,7 +373,11 @@ def open_admin_when_ready():return Falseif payload["status"] == "running" and not stop.is_set():- completed = _start_admin_browser(settings, lambda: not stop.is_set())+ completed = _start_admin_browser(+ settings,+ lambda: not stop.is_set(),+ instance_id=payload["instance_id"],+ )# This extra launcher is about to exit: allow a brief URL handoff.handoff_deadline = time.monotonic() + _BROWSER_HANDOFF_SECONDSwhile not stop.is_set():diff --git a/src/free_claude_code/runtime/application.py b/src/free_claude_code/runtime/application.pyindex d1491eab..7f0d8a12 100644--- a/src/free_claude_code/runtime/application.py+++ b/src/free_claude_code/runtime/application.py@@ -32,6 +32,7 @@ from free_claude_code.config.server_urls import local_admin_urlfrom free_claude_code.config.settings import Settingsfrom free_claude_code.core.async_tasks import run_sync_ownedfrom free_claude_code.core.json_types import JsonObject+from free_claude_code.core.version import package_versionfrom free_claude_code.messaging.voice import Transcriberfrom free_claude_code.providers.credential_validation import (CredentialStatus,@@ -149,6 +150,11 @@ class ApplicationRuntime:transcriber_factory=transcriber_factory,)+ @property+ def instance_id(self) -> str:+ """Identity shared by this runtime's status responses and logs."""+ return self._instance_id+@propertydef settings(self) -> Settings:return self.provider_manager.current_settings()@@ -167,7 +173,11 @@ class ApplicationRuntime:)if self._started:return- logger.info("Starting Claude Code Proxy...")+ logger.bind(+ event="server.starting",+ instance_id=self.instance_id,+ fcc_version=package_version(),+ ).info("Starting Claude Code Proxy...")await _await_owned_task(asyncio.create_task(self._configuration.initialize()))diff --git a/src/free_claude_code/runtime/asgi.py b/src/free_claude_code/runtime/asgi.pyindex 0b32da6a..69562add 100644--- a/src/free_claude_code/runtime/asgi.py+++ b/src/free_claude_code/runtime/asgi.py@@ -18,10 +18,11 @@ class RuntimeASGIApp:return getattr(self.app, name)async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:- if scope["type"] != "lifespan":- await self.app(scope, receive, send)- return- await self._lifespan(receive, send)+ with logger.contextualize(instance_id=self.runtime.instance_id):+ if scope["type"] != "lifespan":+ await self.app(scope, receive, send)+ return+ await self._lifespan(receive, send)async def _lifespan(self, receive: Receive, send: Send) -> None:started = Falsediff --git a/tests/api/test_app_lifespan_and_errors.py b/tests/api/test_app_lifespan_and_errors.pyindex aa70da20..2604732f 100644--- a/tests/api/test_app_lifespan_and_errors.py+++ b/tests/api/test_app_lifespan_and_errors.py@@ -1,3 +1,4 @@+import asyncioimport loggingfrom pathlib import Pathfrom typing import cast@@ -6,13 +7,17 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient+from loguru import logger+from free_claude_code.api.request_ids import RequestCorrelationMiddlewarefrom free_claude_code.application.errors import (ApplicationUnavailableError,InvalidRequestError,)from free_claude_code.application.model_metadata import ProviderModelInfofrom free_claude_code.config.settings import Settings+from free_claude_code.core.async_tasks import run_sync_owned+from free_claude_code.core.version import package_versionfrom free_claude_code.messaging.transcription import TranscriptionServicefrom free_claude_code.providers.nvidia_nim.client import NvidiaNimProviderfrom free_claude_code.providers.nvidia_nim.voice import NvidiaNimTranscriber@@ -39,7 +44,7 @@ def _redirect_fcc_home(monkeypatch, tmp_path):@pytest.mark.asyncio-async def test_runtime_startup_logs_admin_url_without_printed_server_banner():+async def test_runtime_startup_logs_admin_url_without_printed_server_banner(caplog):settings = _settings(messaging_platform="none",host="127.0.0.1",@@ -61,6 +66,7 @@ async def test_runtime_startup_logs_admin_url_without_printed_server_banner():),patch.object(uvicorn_logger, "info") as log_info,):+ await runtime.start()await runtime.start()log_info.assert_not_called()runtime.http_started()@@ -72,6 +78,14 @@ async def test_runtime_startup_logs_admin_url_without_printed_server_banner():"Admin UI: %s (local-only)","http://127.0.0.1:9099/admin",)+ startup = [+ record+ for record in caplog.records+ if record.extra.get("event") == "server.starting"+ ]+ assert len(startup) == 1+ assert startup[0].extra["instance_id"] == runtime.instance_id+ assert startup[0].extra["fcc_version"] == package_version()def test_create_app_application_error_handler_returns_anthropic_format():@@ -196,11 +210,16 @@ def test_startup_failure_message_preserves_existing_concise_contract():@pytest.mark.asyncio-async def test_runtime_asgi_app_starts_and_closes_owner_once():- runtime = MagicMock(spec=ApplicationRuntime)+async def test_runtime_asgi_app_starts_and_closes_owner_once(caplog):+ runtime = MagicMock(spec=ApplicationRuntime, instance_id="lifespan-instance")runtime.settings = _settings()- runtime.start = AsyncMock()- runtime.close = AsyncMock(return_value=True)+ runtime.start = AsyncMock(side_effect=lambda: logger.info("lifespan starting"))++ async def close():+ logger.info("lifespan closing")+ return True++ runtime.close = AsyncMock(side_effect=close)app = RuntimeASGIApp(AsyncMock(), runtime)received = iter([@@ -224,6 +243,66 @@ async def test_runtime_asgi_app_starts_and_closes_owner_once():{"type": "lifespan.startup.complete"},{"type": "lifespan.shutdown.complete"},]+ assert len(caplog.records) == 2+ assert all(+ record.extra["instance_id"] == "lifespan-instance" for record in caplog.records+ )++[email protected]("failure", [None, RuntimeError, asyncio.CancelledError])+async def test_asgi_log_context_isolated_across_runtimes_tasks_and_workers(+ caplog, failure+):+ release = asyncio.Event()+ jobs = []++ async def background(path):+ await release.wait()+ logger.info("background {}", path)++ async def app(scope, receive, send):+ path = scope["path"]+ logger.info("request {}", path)+ jobs.append(asyncio.create_task(background(path)))+ await run_sync_owned(lambda: logger.info("worker {}", path))+ if failure is not None:+ raise failure()++ async def request(name):+ runtime = MagicMock(spec=ApplicationRuntime, instance_id=name)+ wrapped = RuntimeASGIApp(RequestCorrelationMiddleware(app), runtime)+ try:+ await wrapped(+ {"type": "http", "method": "GET", "path": "/" + name, "headers": []},+ AsyncMock(),+ AsyncMock(),+ )+ finally:+ logger.info("after {}", name)++ try:+ results = await asyncio.gather(+ request("first"), request("second"), return_exceptions=True+ )+ finally:+ release.set()+ await asyncio.gather(*jobs)+ for name in ("first", "second"):+ records = [+ record for record in caplog.records if record.message.endswith("/" + name)+ ]+ assert len(records) == 3+ assert all(record.extra["instance_id"] == name for record in records)+ assert len({record.extra["request_id"] for record in records}) == 1+ after = next(+ record for record in caplog.records if record.message == "after " + name+ )+ assert "instance_id" not in after.extra+ assert "request_id" not in after.extra+ assert all(+ isinstance(result, failure) if failure else result is None for result in results+ )@pytest.mark.asynciodiff --git a/tests/cli/test_entrypoints.py b/tests/cli/test_entrypoints.pyindex 856dbe6d..a922ff30 100644--- a/tests/cli/test_entrypoints.py+++ b/tests/cli/test_entrypoints.py@@ -116,8 +116,9 @@ def test_explicit_open_admin_waits_for_owned_http_ready():open_admin.assert_not_called()settings = _launcher_settings()supervisor._ready_settings = settings+ supervisor._ready_instance_id = "ready-instance"supervisor.request_open_admin()- open_admin.assert_called_once_with(settings, 0)+ open_admin.assert_called_once_with(settings, 0, "ready-instance")@pytest.mark.parametrize("open_admin_browser", (False, True))@@ -296,6 +297,7 @@ def test_serve_supervisor_restarts_when_app_requests_restart() -> None:restart_callbacks.append(restart_callback)app = SimpleNamespace(runtime=SimpleNamespace(+ instance_id=f"instance-{len(apps)}",is_closed=False,begin_shutdown=lambda: None,http_started=lambda: None,@@ -340,7 +342,7 @@ def test_serve_supervisor_restarts_when_app_requests_restart() -> None:commands.serve()assert len(servers) == 2- open_admin.assert_called_once_with(settings, 0)+ open_admin.assert_called_once_with(settings, 0, "instance-0")clear_settings_cache.assert_called_once()kill_all.assert_called_once()@@ -357,6 +359,7 @@ def test_serve_supervisor_refuses_restart_after_incomplete_shutdown() -> None:restart_callbacks.append(restart_callback)return SimpleNamespace(runtime=SimpleNamespace(+ instance_id="incomplete-instance",is_closed=False,begin_shutdown=lambda: None,http_started=lambda: None,diff --git a/tests/cli/test_progressive_launch.py b/tests/cli/test_progressive_launch.pyindex 35410b65..08b23b60 100644--- a/tests/cli/test_progressive_launch.py+++ b/tests/cli/test_progressive_launch.py@@ -113,7 +113,7 @@ async def test_uvicorn_readiness_and_early_exit_close_runtime(failure):@pytest.mark.parametrize("valid", [False, True])@pytest.mark.parametrize("browser_result", [True, False, RuntimeError("opener failed")])def test_existing_server_must_identify_itself_as_fcc(- monkeypatch, browser_workers, valid, browser_result+ monkeypatch, browser_workers, valid, browser_result, caplog):settings = Settings()payload = {"unrelated": "server"}@@ -138,6 +138,70 @@ def test_existing_server_must_identify_itself_as_fcc(monkeypatch.setattr(commands.webbrowser, "open", browser)assert commands.open_admin_when_ready(settings) is validassert browser.call_count == int(valid)+ if valid and browser_result is not True:+ assert len(caplog.records) == 1+ assert caplog.records[0].extra["instance_id"] == payload["instance_id"]++[email protected]("automatic", [False, True], ids=["tray", "automatic"])[email protected]("raises", [False, True])+def test_browser_warning_retains_owning_instance_after_server_exit(+ monkeypatch, browser_workers, caplog, automatic, raises+):+ supervisor = commands.ServerSupervisor(console_logging=False)+ settings = Settings()+ entered, release = threading.Event(), threading.Event()+ instances = []++ def build(*args, **kwargs):+ instance_id = f"instance-{len(instances)}"+ instances.append(instance_id)+ return SimpleNamespace(+ runtime=SimpleNamespace(+ instance_id=instance_id,+ is_closed=True,+ http_started=lambda: None,+ begin_shutdown=lambda: None,+ close=AsyncMock(return_value=True),+ )+ )++ def browser(url):+ entered.set()+ assert release.wait(5)+ if raises:+ raise RuntimeError("opener failed")+ return False++ class Server:+ def __init__(self, config, *, on_started, **kwargs):+ self.on_started = on_started++ def run(self, **kwargs):+ self.on_started()+ if not automatic:+ tray = threading.Thread(target=supervisor.request_open_admin)+ tray.start()+ tray.join(2)+ assert not tray.is_alive()+ assert entered.wait(2)++ monkeypatch.setattr("free_claude_code.runtime.bootstrap.build_asgi_app", build)+ monkeypatch.setattr(uvicorn, "Config", lambda *args, **kwargs: None)+ monkeypatch.setattr("free_claude_code.cli.uvicorn_server.RuntimeServer", Server)+ monkeypatch.setattr(commands.webbrowser, "open", browser)+ try:+ for _ in range(2):+ entered.clear()+ supervisor._run_bound(+ settings, [], open_admin_browser=automatic, restart_generation=0+ )+ finally:+ release.set()+ for worker in browser_workers:+ worker.join(2)+ assert len(caplog.records) == 2+ assert {record.extra["instance_id"] for record in caplog.records} == set(instances)@pytest.mark.parametrize("change", ["none", "stop", "restart", "settings"])@@ -146,6 +210,7 @@ def test_queued_browser_rechecks_owner_before_handoff(monkeypatch, change):settings = Settings()supervisor.schedule_run()supervisor._ready_settings = settings+ supervisor._ready_instance_id = "queued-instance"queued = []monkeypatch.setattr(threading.Thread, "start", lambda thread: queued.append(thread))browser = MagicMock(return_value=True)@@ -163,7 +228,7 @@ def test_queued_browser_rechecks_owner_before_handoff(monkeypatch, change):@pytest.mark.parametrize("reuse", [False, True])-def test_browser_thread_start_failure_does_not_fail_fcc(monkeypatch, reuse):+def test_browser_thread_start_failure_does_not_fail_fcc(monkeypatch, reuse, caplog):settings = Settings()browser = MagicMock()monkeypatch.setattr(commands.webbrowser, "open", browser)@@ -187,9 +252,11 @@ def test_browser_thread_start_failure_does_not_fail_fcc(monkeypatch, reuse):else:supervisor = commands.ServerSupervisor()supervisor._ready_settings = settings+ supervisor._ready_instance_id = "a" * 32supervisor.request_open_admin()supervisor.request_stop()browser.assert_not_called()+ assert caplog.records[-1].extra["instance_id"] == "a" * 32def _run_browser_shutdown_probe(mode, outcome, directory, setup_delay="0"):@@ -224,6 +291,7 @@ def _run_browser_shutdown_probe(mode, outcome, directory, setup_delay="0"):if mode in {"server", "desktop"}:supervisor = commands.ServerSupervisor(console_logging=False)runtime = SimpleNamespace(+ instance_id="browser-probe-instance",is_closed=True,begin_shutdown=lambda: None,http_started=lambda: None,diff --git a/tests/cli/test_server_logging.py b/tests/cli/test_server_logging.pyindex 91295f31..da720ac9 100644--- a/tests/cli/test_server_logging.py+++ b/tests/cli/test_server_logging.py@@ -30,11 +30,14 @@ def _exercise_server_logging(# An earlier server may already have installed Uvicorn's console handlers.logging.config.dictConfig(baseline)settings = Settings(host="127.0.0.1", port=8082, log_level=level)+ instances = []def build_app(settings, restart_callback):+ instances.append(f"instance-{len(instances) + 1}")configure_logging(path, level=settings.log_level)runtime = MagicMock(spec=ApplicationRuntime,+ instance_id=instances[-1],settings=settings,_draining=False,_http_ready=asyncio.Event(),@@ -75,6 +78,7 @@ def _exercise_server_logging(supervisor._run_bound(settings, [], open_admin_browser=False, restart_generation=0)+ logger.warning("outside server run")logger.complete()assert baseline == uvicorn.config.LOGGING_CONFIG@@ -122,6 +126,17 @@ def test_server_logs_reach_file_once_per_start(assert row["record"]["exception"]["type"] == "ValueError"assert "controlled server failure" in row["text"]assert "Traceback" in row["text"]+ server_records = [+ row["record"]+ for row in rows+ if row["record"]["message"] != "outside server run"+ ]+ assert {record["extra"]["instance_id"] for record in server_records} == {+ "instance-1",+ "instance-2",+ }+ assert len({record["process"]["id"] for record in server_records}) == 1+ assert "instance_id" not in rows[-1]["record"]["extra"]assert result.stdout.count("/test-request") == (2 if console else 0)assert result.stderr.count("Admin UI:") == (2 if console else 0)assert result.stderr.count("ASGI request failed") == (2 if console else 0)diff --git a/tests/cli/test_server_shutdown.py b/tests/cli/test_server_shutdown.pyindex 7f3fe4c8..3dac664d 100644--- a/tests/cli/test_server_shutdown.py+++ b/tests/cli/test_server_shutdown.py@@ -108,3 +108,14 @@ async def test_supervisor_drains_admin_event_feed_without_forced_cancellation(assert "timeout graceful shutdown exceeded" not in caplog.textassert all(app.runtime.is_closed for app in apps)assert len(apps) == (2 if restart else 1)+ starts = [+ extra+ for record in caplog.records+ if (extra := getattr(record, "extra", {})).get("event") == "server.starting"+ ]+ assert [extra["instance_id"] for extra in starts] == [+ app.runtime.instance_id for app in apps+ ]+ assert starts[0]["instance_id"] == old_instance+ if restart:+ assert starts[1]["instance_id"] == new_status["instance_id"]diff --git a/tests/cli/test_update_wrapper.py b/tests/cli/test_update_wrapper.pyindex dcb7ac7a..43d41e6e 100644--- a/tests/cli/test_update_wrapper.py+++ b/tests/cli/test_update_wrapper.py@@ -45,7 +45,9 @@ def installer_server(body, status, outcome):passserver = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)- thread = threading.Thread(target=server.serve_forever)+ thread = threading.Thread(+ target=server.serve_forever, kwargs={"poll_interval": 0.01}+ )thread.start()try:yield f"http://127.0.0.1:{server.server_port}/install", requests@@ -116,7 +118,6 @@ def test_installed_update_delegates_and_survives_replacement(tmp_path, outcome):env.update(UV_TOOL_DIR=str(area / "tools"),UV_TOOL_BIN_DIR=str(area / "bin"),- UV_CACHE_DIR=str(area / "cache"),UV_NO_CONFIG="1",UV_PYTHON_DOWNLOADS="never",FCC_TEST_LAUNCHER=str(diff --git a/tests/runtime/test_sqlite_database.py b/tests/runtime/test_sqlite_database.pyindex a31aa427..12577fbf 100644--- a/tests/runtime/test_sqlite_database.py+++ b/tests/runtime/test_sqlite_database.py@@ -1,5 +1,6 @@import asyncioimport os+import shutilimport sqlite3import subprocessimport sys@@ -252,8 +253,9 @@ async def test_checkout_timeout_uses_sqlite_error_contract(@pytest.mark.asyncio@pytest.mark.parametrize("cancel", [False, True])async def test_startup_failure_disposes_connections_before_releasing_owner(- tmp_path, cancel+ tmp_path, cancel, initialized_database):+ shutil.copyfile(initialized_database, tmp_path / "fcc.db")entered, release = threading.Event(), threading.Event()observed = []@@ -294,6 +296,14 @@ async def test_startup_failure_disposes_connections_before_releasing_owner(await database.close()[email protected](scope="module")+def initialized_database(tmp_path_factory):+ """Build the schema once, outside the ownership test's synchronization window."""+ path = tmp_path_factory.mktemp("initialized-database") / "fcc.db"+ initialize_database(path)+ return path++def test_connection_setup_failure_closes_raw_connection(tmp_path, monkeypatch):connect = sqlite3.connectobserved = []