Skip to content

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: Include Uvicorn logs in the FCC log file (#1942)

Ali Khokhar9e239055819e
diff --git a/e2e/test_admin_apply.py b/e2e/test_admin_apply.py
index cd8fb0c3..2550d029 100644
--- a/e2e/test_admin_apply.py
+++ b/e2e/test_admin_apply.py
@@ -190,7 +190,8 @@ def test_apply_network_error_unlocks_form_and_keeps_edits(
def test_restart_waits_for_a_new_running_server(page: Page, admin_base_url: str):
- pending: list[Route] = []
+ status = {"status": "running", "instance_id": "old-server"}
+ status_url = f"{admin_base_url}/admin/api/status"
page.route(
"**/admin/api/config/apply",
lambda route: route.fulfill(
@@ -210,21 +211,25 @@ def test_restart_waits_for_a_new_running_server(page: Page, admin_base_url: str)
page.goto(f"{admin_base_url}/admin")
expect(page.locator("#messageArea")).to_have_text("")
page.wait_for_function("!state.startupRequest && !state.startupTimer")
- page.route("**/admin/api/status", lambda route: pending.append(route))
+ page.route(status_url, lambda route: route.fulfill(json=status))
open_provider(page, "nvidia_nim")
page.locator("#field-NVIDIA_NIM_API_KEY").fill("new-key")
with page.expect_request("**/admin/api/status"):
page.get_by_role("button", name="Save", exact=True).click()
expect(page.locator("#applyButton")).to_have_text("Reconnecting…")
- for status in (
+ for next_status in (
{"status": "running", "instance_id": "old-server"},
{"status": "stopping", "instance_id": "new-server"},
):
- with page.expect_request("**/admin/api/status"):
- pending.pop(0).fulfill(json=status)
+ with page.expect_response(
+ lambda response, expected=next_status: (
+ response.url == status_url and response.json() == expected
+ )
+ ):
+ status = next_status
expect(page.locator("#view-providers")).to_have_attribute("inert", "")
expect(page.locator("#dirtyState")).to_have_text("Changes saved")
- pending.pop(0).fulfill(json={"status": "running", "instance_id": "new-server"})
+ status = {"status": "running", "instance_id": "new-server"}
expect(page.locator('[data-provider="nvidia_nim"]')).to_be_enabled()
expect(page.locator("#dirtyState")).to_have_text("No changes")
expect(page.locator("#messageArea")).to_have_text("Applied")
diff --git a/src/free_claude_code/cli/commands.py b/src/free_claude_code/cli/commands.py
index fbc0aa70..5421a461 100644
--- a/src/free_claude_code/cli/commands.py
+++ b/src/free_claude_code/cli/commands.py
@@ -259,7 +259,7 @@ class ServerSupervisor:
from free_claude_code.runtime.bootstrap import build_asgi_app
- from .uvicorn_server import RuntimeServer
+ from .uvicorn_server import RuntimeServer, uvicorn_log_config
asgi_app = build_asgi_app(
settings,
@@ -270,9 +270,7 @@ class ServerSupervisor:
host=settings.host,
port=settings.port,
log_level="debug",
- log_config=(
- uvicorn.config.LOGGING_CONFIG if self._console_logging else None
- ),
+ log_config=uvicorn_log_config(console=self._console_logging),
timeout_graceful_shutdown=SERVER_GRACEFUL_SHUTDOWN_SECONDS,
)
diff --git a/src/free_claude_code/cli/uvicorn_server.py b/src/free_claude_code/cli/uvicorn_server.py
index a0fec010..d4366ccc 100644
--- a/src/free_claude_code/cli/uvicorn_server.py
+++ b/src/free_claude_code/cli/uvicorn_server.py
@@ -2,9 +2,25 @@
import socket
from collections.abc import Awaitable, Callable
+from copy import deepcopy
import uvicorn
+from free_claude_code.config.logging_config import InterceptHandler
+
+
+def uvicorn_log_config(*, console: bool) -> dict[str, object]:
+ """Send Uvicorn records to FCC's file and optional standard console handlers."""
+ config = deepcopy(uvicorn.config.LOGGING_CONFIG)
+ if not console:
+ config["formatters"] = {}
+ config["handlers"] = {}
+ config["handlers"]["fcc"] = {"()": InterceptHandler}
+ for name in ("uvicorn", "uvicorn.access"):
+ handlers = config["loggers"][name]["handlers"]
+ config["loggers"][name]["handlers"] = [*handlers, "fcc"] if console else ["fcc"]
+ return config
+
class RuntimeServer(uvicorn.Server):
"""Notify the runtime before Uvicorn waits for long-lived HTTP responses."""
diff --git a/tests/cli/test_server_logging.py b/tests/cli/test_server_logging.py
new file mode 100644
index 00000000..91295f31
--- /dev/null
+++ b/tests/cli/test_server_logging.py
@@ -0,0 +1,127 @@
+"""Server logging contracts run outside pytest's process-wide logging state."""
+
+import asyncio
+import json
+import logging
+import logging.config
+import subprocess
+import sys
+from contextlib import nullcontext
+from copy import deepcopy
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+import uvicorn
+from loguru import logger
+
+from free_claude_code.cli.commands import ServerSupervisor
+from free_claude_code.cli.uvicorn_server import RuntimeServer
+from free_claude_code.config.logging_config import configure_logging
+from free_claude_code.config.settings import Settings
+from free_claude_code.runtime.application import ApplicationRuntime
+
+
+def _exercise_server_logging(
+ path: Path, console: bool, level: str, without_streams: bool
+) -> None:
+ baseline = deepcopy(uvicorn.config.LOGGING_CONFIG)
+ # 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)
+
+ def build_app(settings, restart_callback):
+ configure_logging(path, level=settings.log_level)
+ runtime = MagicMock(
+ spec=ApplicationRuntime,
+ settings=settings,
+ _draining=False,
+ _http_ready=asyncio.Event(),
+ is_closed=True,
+ begin_shutdown=lambda: None,
+ close=AsyncMock(return_value=True),
+ )
+ runtime.http_started.side_effect = lambda: ApplicationRuntime.http_started(
+ runtime
+ )
+ return SimpleNamespace(runtime=runtime)
+
+ def run(server, sockets):
+ server._on_started()
+ logging.getLogger("uvicorn.access").info(
+ '%s - "%s %s HTTP/%s" %d',
+ "127.0.0.1:1234",
+ "POST",
+ "/test-request",
+ "1.1",
+ 200,
+ )
+ try:
+ raise ValueError("controlled server failure")
+ except ValueError:
+ logging.getLogger("uvicorn.error").exception("ASGI request failed")
+ logging.getLogger("test.dependency").warning("dependency warning")
+
+ with (
+ patch("free_claude_code.runtime.bootstrap.build_asgi_app", build_app),
+ patch.object(RuntimeServer, "run", run),
+ patch.multiple(sys, stdout=None, stderr=None)
+ if without_streams
+ else nullcontext(),
+ ):
+ supervisor = ServerSupervisor(console_logging=console)
+ for _ in range(2):
+ supervisor._run_bound(
+ settings, [], open_admin_browser=False, restart_generation=0
+ )
+ logger.complete()
+ assert baseline == uvicorn.config.LOGGING_CONFIG
+
+
+ ("console", "without_streams"),
+ [(True, False), (False, False), (False, True)],
+ ids=["cli", "desktop", "desktop-no-console"],
+)
[email protected]("level", ["INFO", "WARNING"])
+def test_server_logs_reach_file_once_per_start(
+ tmp_path, console, level, without_streams
+):
+ path = tmp_path / "server.log"
+ result = subprocess.run(
+ [
+ sys.executable,
+ "-c",
+ "import sys; from pathlib import Path; "
+ "from tests.cli.test_server_logging import _exercise_server_logging; "
+ "_exercise_server_logging(Path(sys.argv[1]), sys.argv[2] == 'True', "
+ "sys.argv[3], sys.argv[4] == 'True')",
+ str(path),
+ str(console),
+ level,
+ str(without_streams),
+ ],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ timeout=30,
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+ rows = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()]
+ messages = [row["record"]["message"] for row in rows]
+ info_count = 2 if level == "INFO" else 0
+ assert sum(message.startswith("Admin UI:") for message in messages) == info_count
+ assert sum("/test-request" in message for message in messages) == info_count
+ assert messages.count("ASGI request failed") == 2
+ assert messages.count("dependency warning") == 2
+ failures = [
+ row for row in rows if row["record"]["message"] == "ASGI request failed"
+ ]
+ for row in failures:
+ assert row["record"]["exception"]["type"] == "ValueError"
+ assert "controlled server failure" in row["text"]
+ assert "Traceback" in row["text"]
+ 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)