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: Start FCC automatically from installed harness launchers (#1852)
gokhankelebek20bf5cfd42ca
diff --git a/README.md b/README.mdindex c4ecbc71..258f4aeb 100644--- a/README.md+++ b/README.md@@ -374,6 +374,14 @@ Providers that do not support a selected control retain their own behavior.## Connect Your Client+If FCC is not running when you start a launcher, it starts FCC Desktop on+Windows/macOS or `fcc-server` on Linux and waits for it to become ready. FCC+stays running after the client exits. If startup fails, the launcher reports the+error and startup log location. If early output cannot be saved, the launcher+warns and continues startup. If startup times out, a running Desktop stays+open so you can check its status and retry. You can also run `fcc-desktop`+(Windows/macOS) or `fcc-server` (Linux) manually to diagnose startup problems.+For editor and app integrations, install the client, start FCC, then open**Admin UI → Integrations** and click **Connect** on its card.diff --git a/smoke/lib/child_process.py b/smoke/lib/child_process.pyindex 4b81a64c..31167c32 100644--- a/smoke/lib/child_process.py+++ b/smoke/lib/child_process.py@@ -36,7 +36,7 @@ def cmd_fcc_server() -> list[str]:return [python_exe(),"-c",- "from free_claude_code.cli.entrypoints import serve; serve()",+ "from smoke.lib.server_runtime import serve; serve()",]diff --git a/smoke/lib/server.py b/smoke/lib/server.pyindex 47bd7ab5..ae757e01 100644--- a/smoke/lib/server.py+++ b/smoke/lib/server.py@@ -11,8 +11,11 @@ from pathlib import Pathimport httpx+from free_claude_code.cli.process_registry import kill_pid_tree_best_effort+from .child_process import cmd_fcc_serverfrom .config import SmokeConfig, redacted+from .server_runtime import server_environment@dataclass(slots=True)@@ -60,11 +63,15 @@ def start_server(cmd = command or cmd_fcc_server()- with log_path.open("ab") as log_file:+ caller_home = any(key in (env_overrides or {}) for key in ("HOME", "USERPROFILE"))+ with (+ server_environment(env, caller_home=caller_home) as child_env,+ log_path.open("ab") as log_file,+ ):process = subprocess.Popen(cmd,cwd=config.root,- env=env,+ env=child_env,stdout=log_file,stderr=subprocess.STDOUT,)@@ -110,7 +117,11 @@ def _wait_for_health(server: RunningServer, *, timeout_s: float) -> None:def _stop_process(process: subprocess.Popen[bytes]) -> None:if process.poll() is not None:return- process.terminate()+ if os.name == "nt":+ # The venv Python executable can wrap a second Python process.+ kill_pid_tree_best_effort(process.pid)+ else:+ process.terminate()try:process.wait(timeout=8)except subprocess.TimeoutExpired:diff --git a/smoke/lib/server_runtime.py b/smoke/lib/server_runtime.pynew file mode 100644index 00000000..286252eb--- /dev/null+++ b/smoke/lib/server_runtime.py@@ -0,0 +1,61 @@+"""Private smoke runtime state with the developer's original credential ownership."""++import os+from collections.abc import Iterator, Mapping+from contextlib import ExitStack, contextmanager+from pathlib import Path+from tempfile import TemporaryDirectory+from unittest.mock import patch++from free_claude_code.config import paths+from free_claude_code.config.env_migrations import atomic_write_managed_config+from free_claude_code.config.loader import ManagedConfigStore++_CONFIG_DIR = "FCC_SMOKE_CONFIG_DIR"+_SOURCE_DIR = "FCC_SMOKE_SOURCE_CONFIG_DIR"+++@contextmanager+def server_environment(+ env: Mapping[str, str], *, caller_home: bool+) -> Iterator[dict[str, str]]:+ child_env = dict(env)+ child_env.pop(_CONFIG_DIR, None)+ child_env.pop(_SOURCE_DIR, None)+ if caller_home:+ yield child_env+ return++ snapshot = ManagedConfigStore().read()+ with TemporaryDirectory(prefix="fcc-smoke-") as directory:+ private = Path(directory)+ atomic_write_managed_config(snapshot.managed, path=private / ".env")+ child_env[_CONFIG_DIR] = str(private)+ child_env[_SOURCE_DIR] = str(snapshot.path.parent)+ yield child_env+++def serve() -> None:+ """Set FCC paths before importing the real server entrypoint."""+ directory = os.environ.pop(_CONFIG_DIR, None)+ with ExitStack() as stack:+ if directory is not None:+ source = Path(os.environ.pop(_SOURCE_DIR))+ with patch.object(paths, "config_dir_path", lambda: source):+ auth = paths.openai_auth_path()+ auth_lock = paths.openai_auth_lock_path()+ copilot = paths.github_copilot_auth_path()+ # Keep rotating OAuth credentials and their refresh lock together.+ stack.enter_context(+ patch.multiple(+ paths,+ config_dir_path=lambda: Path(directory),+ openai_auth_path=lambda: auth,+ openai_auth_lock_path=lambda: auth_lock,+ github_copilot_auth_path=lambda: copilot,+ )+ )++ from free_claude_code.cli.entrypoints import serve as run_server++ run_server()diff --git a/src/free_claude_code/cli/commands.py b/src/free_claude_code/cli/commands.pyindex 35b63531..6f78e35d 100644--- a/src/free_claude_code/cli/commands.py+++ b/src/free_claude_code/cli/commands.py@@ -21,9 +21,10 @@ from free_claude_code.config.loader import (clear_settings_cache,get_settings,)-from free_claude_code.config.paths import managed_env_path+from free_claude_code.config.paths import managed_env_path, server_owner_lock_pathfrom free_claude_code.config.server_urls import local_admin_url, local_proxy_root_urlfrom free_claude_code.config.settings import Settings+from free_claude_code.core.interprocess_lock import InterprocessFileLockfrom .server_socket import ServerSockets@@ -67,10 +68,10 @@ def _start_admin_browser(return completed-def serve() -> None:+def serve(*, console_logging: bool = True) -> None:"""Start and supervise the FastAPI server."""try:- ServerSupervisor().run()+ ServerSupervisor(console_logging=console_logging).run()except OSError as exc:if exc.errno == errno.EADDRINUSE:_log_port_in_use(get_settings())@@ -185,10 +186,19 @@ class ServerSupervisor:if self.stop_event.is_set():returnself._running = True+ self._owned_server = Falseself._auto_browser_opened = False+ owner_lock = InterprocessFileLock(server_owner_lock_path())try:try:+ if not owner_lock.acquire():+ if existing_server and existing_server(load_server_settings()):+ return+ raise OSError(+ errno.EADDRINUSE,+ "Another FCC server already owns this configuration.",+ )while not self._is_stop_requested():with self._lock:restart_generation = self._restart_generation@@ -218,11 +228,14 @@ class ServerSupervisor:except KeyboardInterrupt:returnfinally:- with self._lock:- self._server = None- self._running = False- if self._owned_server:- kill_all_best_effort()+ try:+ with self._lock:+ self._server = None+ self._running = False+ if self._owned_server:+ kill_all_best_effort()+ finally:+ owner_lock.release()def request_restart(self) -> bool:"""Reload an active generation or coalesce into a scheduled fresh run."""diff --git a/src/free_claude_code/cli/desktop.py b/src/free_claude_code/cli/desktop.pyindex 8cbb04d3..0b431bad 100644--- a/src/free_claude_code/cli/desktop.py+++ b/src/free_claude_code/cli/desktop.py@@ -114,15 +114,20 @@ class DesktopController:self._server_run()-def launch_desktop(tray_factory: DesktopTrayFactory) -> None:+def launch_desktop(+ tray_factory: DesktopTrayFactory, *, auto_started: bool = False+) -> None:"""Show the tray before acquiring configuration, singleton and server ownership."""supervisor = ServerSupervisor(console_logging=False)def reuse_existing(settings) -> bool:- reused = open_admin_when_ready(settings, stop_event=supervisor.stop_event)- if reused:+ if auto_started:+ controller.quit()+ return True+ try:+ return open_admin_when_ready(settings, stop_event=supervisor.stop_event)+ finally:controller.quit()- return reuseddef run_server() -> None:instance_lock = InterprocessFileLock(config_dir_path() / "desktop.lock")@@ -134,9 +139,10 @@ def launch_desktop(tray_factory: DesktopTrayFactory) -> None:returnif not acquired:try:- open_admin_when_ready(- load_server_settings(), stop_event=supervisor.stop_event- )+ if not auto_started:+ open_admin_when_ready(+ load_server_settings(), stop_event=supervisor.stop_event+ )finally:controller.quit()returndiff --git a/src/free_claude_code/cli/desktop_entrypoint.py b/src/free_claude_code/cli/desktop_entrypoint.pyindex fa527aa8..9636de74 100644--- a/src/free_claude_code/cli/desktop_entrypoint.py+++ b/src/free_claude_code/cli/desktop_entrypoint.py@@ -15,7 +15,8 @@ def launch(argv: Sequence[str] | None = None) -> None:if len(args) == 2 and args[0] == "--export-icon":export_app_icon(Path(args[1]))return- if args:+ auto_started = args == ("--auto-started",)+ if args and not auto_started:print("Usage: fcc-desktop [--export-icon PATH]", file=sys.stderr)raise SystemExit(2)if sys.platform not in {"darwin", "win32"}:@@ -26,4 +27,4 @@ def launch(argv: Sequence[str] | None = None) -> None:from free_claude_code.cli.desktop_tray import launch as launch_tray- launch_tray()+ launch_tray(auto_started=auto_started)diff --git a/src/free_claude_code/cli/desktop_tray.py b/src/free_claude_code/cli/desktop_tray.pyindex 00f7c5d8..f48767de 100644--- a/src/free_claude_code/cli/desktop_tray.py+++ b/src/free_claude_code/cli/desktop_tray.py@@ -61,7 +61,7 @@ def _create_icon() -> Image.Image:return image.convert("RGBA")-def launch() -> None:+def launch(*, auto_started: bool = False) -> None:"""Launch the supported native tray adapter."""- launch_desktop(PystrayDesktopTray)+ launch_desktop(PystrayDesktopTray, auto_started=auto_started)diff --git a/src/free_claude_code/cli/entrypoints.py b/src/free_claude_code/cli/entrypoints.pyindex 17854b9d..01748a0b 100644--- a/src/free_claude_code/cli/entrypoints.py+++ b/src/free_claude_code/cli/entrypoints.py@@ -14,7 +14,8 @@ def serve(argv: Sequence[str] | None = None) -> None:# Keep the server composition root off metadata-only command paths.from free_claude_code.cli.commands import serve as run_server- run_server()+ args = sys.argv[1:] if argv is None else argv+ run_server(console_logging="--auto-started" not in args)def _print_version_if_requested(argv: Sequence[str] | None) -> bool:diff --git a/src/free_claude_code/cli/launchers/common.py b/src/free_claude_code/cli/launchers/common.pyindex 9c830aa7..fedbaaa0 100644--- a/src/free_claude_code/cli/launchers/common.py+++ b/src/free_claude_code/cli/launchers/common.py@@ -1,11 +1,19 @@"""Shared process helpers for installed client CLI launchers."""+import errno+import osimport shutil+import socketimport subprocessimport sysimport timefrom collections.abc import Mapping+from contextlib import ExitStack+from dataclasses import dataclass+from enum import StrEnum+from pathlib import Pathfrom urllib.error import HTTPError, URLError+from urllib.parse import urlsplitfrom urllib.request import Requestfrom free_claude_code.cli.local_http import open_local_request@@ -14,39 +22,337 @@ from free_claude_code.cli.process_registry import (register_pid,unregister_pid,)+from free_claude_code.config import paths+from free_claude_code.config.paths import server_startup_lock_path+from free_claude_code.core.interprocess_lock import InterprocessFileLockPROXY_PREFLIGHT_PATH = "/health"PROXY_PREFLIGHT_TIMEOUT_SECONDS = 1.5+SERVER_STARTUP_TIMEOUT_SECONDS = 30.0+SERVER_STARTUP_LOCK_TIMEOUT_SECONDS = 30.0+SERVER_STARTUP_POLL_SECONDS = 0.25-def preflight_proxy(proxy_root_url: str) -> str | None:- """Return an error message when the local proxy health check is unreachable."""+class ProxyState(StrEnum):+ """What one health probe learned about the local proxy."""++ HEALTHY = "healthy"+ # An HTTP server answered, so a proxy exists even if it is unhealthy.+ HTTP_ERROR = "http_error"+ # A listener accepted TCP but never answered: the app is still loading.+ STARTING = "starting"+ # Nothing accepted the connection, so no server is running.+ UNREACHABLE = "unreachable"+ # The listener closed a connection during a possible owner restart.+ CONNECTION_CLOSED = "connection_closed"+ NETWORK_ERROR = "network_error"+++@dataclass(frozen=True, slots=True)+class ProxyProbe:+ state: ProxyState+ error: str | None = None+++def _probe_proxy(proxy_root_url: str, *, deadline: float) -> ProxyProbe:+ """Observe the endpoint once without consuming the whole startup wait."""++ remaining = deadline - time.monotonic()+ if remaining <= 0:+ return ProxyProbe(ProxyState.STARTING, "readiness deadline expired")url = f"{proxy_root_url.rstrip('/')}{PROXY_PREFLIGHT_PATH}"request = Request(url, method="GET")- deadline = time.monotonic() + 30.0- while True:+ try:+ with open_local_request(+ request, timeout=min(PROXY_PREFLIGHT_TIMEOUT_SECONDS, remaining)+ ) as response:+ status_code = response.status+ except HTTPError as exc:+ return ProxyProbe(ProxyState.HTTP_ERROR, f"returned HTTP {exc.code}")+ except (URLError, OSError) as exc:+ reason = exc.reason if isinstance(exc, URLError) else exc+ if isinstance(reason, TimeoutError):+ # Windows can time out connecting to an absent listener. Conversely,+ # FCC reserves a listening socket before the HTTP app is ready.+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ return ProxyProbe(ProxyState.STARTING, str(reason))+ address = urlsplit(url)+ try:+ with socket.create_connection(+ (address.hostname or "127.0.0.1", address.port or 80),+ timeout=min(PROXY_PREFLIGHT_TIMEOUT_SECONDS, remaining),+ ):+ pass+ except ConnectionRefusedError, TimeoutError:+ return ProxyProbe(ProxyState.UNREACHABLE, str(reason))+ except OSError as exc:+ return ProxyProbe(ProxyState.NETWORK_ERROR, str(exc))+ return ProxyProbe(ProxyState.STARTING, str(reason))+ if isinstance(reason, ConnectionRefusedError) or getattr(+ reason, "errno", None+ ) in {errno.ECONNREFUSED, 10061}:+ return ProxyProbe(ProxyState.UNREACHABLE, str(reason))+ if isinstance(reason, ConnectionError):+ return ProxyProbe(ProxyState.CONNECTION_CLOSED, str(reason))+ return ProxyProbe(ProxyState.NETWORK_ERROR, str(reason))+ if not 200 <= status_code < 300:+ return ProxyProbe(ProxyState.HTTP_ERROR, f"returned HTTP {status_code}")+ return ProxyProbe(ProxyState.HEALTHY)+++def server_command() -> list[str]:+ """Run the installed platform owner with its normal process identity."""++ name = "fcc-desktop" if sys.platform in {"win32", "darwin"} else "fcc-server"+ suffix = ".exe" if sys.platform == "win32" else ""+ sibling = Path(sys.executable).parent / f"{name}{suffix}"+ if sibling.is_file() and os.access(sibling, os.X_OK):+ return [str(sibling), "--auto-started"]+ raise FileNotFoundError(+ f"Installed {name} command is missing or not executable: {sibling}"+ )+++def _spawn_server(+ env: Mapping[str, str],+) -> tuple[subprocess.Popen[bytes], Path | None]:+ """Detach the owner and retain errors raised before runtime logging starts."""+ command = server_command()+ log_path = paths.server_startup_log_path()+ output = subprocess.DEVNULL+ capture_path = None+ with ExitStack() as stack:try:- with open_local_request(- request,- timeout=min(- PROXY_PREFLIGHT_TIMEOUT_SECONDS,- max(0.001, deadline - time.monotonic()),+ log_path.parent.mkdir(parents=True, exist_ok=True)+ output = stack.enter_context(log_path.open("wb"))+ capture_path = log_path+ except OSError as exc:+ print(+ f"Could not capture startup output in {log_path}: {exc}\n"+ "FCC will start without early output capture.",+ file=sys.stderr,+ )+ return (+ subprocess.Popen(+ command,+ stdin=subprocess.DEVNULL,+ stdout=output,+ stderr=subprocess.STDOUT,+ env=dict(env),+ creationflags=(+ getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)+ | getattr(subprocess, "DETACHED_PROCESS", 0)+ if sys.platform == "win32"+ else 0),- ) as response:- status_code = response.status- except HTTPError as exc:- return f"returned HTTP {exc.code}"- except (URLError, OSError) as exc:- reason = exc.reason if isinstance(exc, URLError) else exc- # A reserved listener can accept TCP while the HTTP app is loading.- # Refusals and other failures still return the normal launch hint.- if isinstance(reason, TimeoutError) and time.monotonic() < deadline:- continue- return str(reason)- if not 200 <= status_code < 300:- return f"returned HTTP {status_code}"+ start_new_session=sys.platform != "win32",+ ),+ capture_path,+ )+++def _startup_diagnostics(detail: str, path: Path | None) -> str:+ if path is None:+ return f"{detail}\nStartup output was not captured for this attempt."+ try:+ with path.open("rb") as output:+ output.seek(0, os.SEEK_END)+ output.seek(max(0, output.tell() - 2048))+ tail = output.read().decode("utf-8", errors="replace").strip()+ except OSError as exc:+ return f"{detail}\nCould not read startup output: {exc}"+ return f"{detail}\nStartup log: {path}" + (f"\n{tail}" if tail else "")+++def _desktop_owner_running() -> bool:+ """A manually launched Desktop may own startup outside our launcher lock."""++ if sys.platform not in {"win32", "darwin"}:+ return False+ lock = InterprocessFileLock(paths.config_dir_path() / "desktop.lock")+ try:+ acquired = lock.acquire()+ except OSError:+ return False+ if acquired:+ lock.release()+ return not acquired+++def _server_owner_running() -> bool:+ """The server may be between listener generations, regardless of entrypoint."""++ lock = InterprocessFileLock(paths.server_owner_lock_path())+ try:+ acquired = lock.acquire()+ except OSError:+ return False+ if acquired:+ lock.release()+ return not acquired+++def _owner_running() -> bool:+ return _desktop_owner_running() or _server_owner_running()+++def _stop_owned_process(process: subprocess.Popen[bytes]) -> None:+ if process.poll() is not None:+ return+ try:+ process.terminate()+ process.wait(timeout=2)+ except subprocess.TimeoutExpired:+ try:+ process.kill()+ process.wait(timeout=2)+ except OSError, subprocess.TimeoutExpired:+ pass+ except OSError:+ pass+++def _unreachable_message(proxy_root_url: str, probe: ProxyProbe, detail: str) -> str:+ name = "fcc-desktop" if sys.platform in {"win32", "darwin"} else "fcc-server"+ return (+ f"Free Claude Code proxy is not reachable at {proxy_root_url}: {probe.error}\n"+ f"{detail}\n"+ f"Start it manually with: {name}"+ )+++def _wait_for_server(+ proxy_root_url: str,+ process: subprocess.Popen[bytes] | None,+ *,+ deadline: float,+) -> ProxyProbe | str:+ """Poll until the spawned server answers, exits, or the budget runs out."""++ while time.monotonic() < deadline:+ probe = _probe_proxy(proxy_root_url, deadline=deadline)+ if probe.state in {+ ProxyState.HEALTHY,+ ProxyState.HTTP_ERROR,+ ProxyState.NETWORK_ERROR,+ }:+ return probe+ if (+ probe.state is ProxyState.CONNECTION_CLOSED+ and process is None+ and not _owner_running()+ ):+ return probe+ exit_code = process.poll() if process is not None else None+ if exit_code is not None:+ if _owner_running():+ # A manual owner may have won the bind/singleton race. Its actual+ # endpoint, not the duplicate's exit code, determines readiness.+ process = None+ else:+ name = (+ "fcc-desktop"+ if sys.platform in {"win32", "darwin"}+ else "fcc-server"+ )+ return f"{name} exited with code {exit_code} before it was ready."+ remaining = deadline - time.monotonic()+ if remaining > 0:+ time.sleep(min(SERVER_STARTUP_POLL_SECONDS, remaining))+ return (+ "Free Claude Code did not become ready within "+ f"{SERVER_STARTUP_TIMEOUT_SECONDS:g} seconds. If FCC is already running, "+ "check its configured port or restart it."+ )+++def ensure_proxy_available(+ proxy_root_url: str, *, env: Mapping[str, str]+) -> str | None:+ """Return an error message when the proxy is down and cannot be started here.++ A missing server is started once, under an interprocess lock, so concurrent+ launchers share one platform owner instead of racing to bind the same port.+ """++ probe = _probe_proxy(+ proxy_root_url, deadline=time.monotonic() + SERVER_STARTUP_TIMEOUT_SECONDS+ )+ if probe.state is ProxyState.HEALTHY:return None+ if probe.state in {ProxyState.HTTP_ERROR, ProxyState.NETWORK_ERROR} or (+ probe.state is ProxyState.CONNECTION_CLOSED and not _owner_running()+ ):+ return _unreachable_message(+ proxy_root_url, probe, "The configured endpoint failed its health check."+ )+ lock = InterprocessFileLock(server_startup_lock_path())+ try:+ acquired = lock.acquire(wait=True, timeout=SERVER_STARTUP_LOCK_TIMEOUT_SECONDS)+ except OSError as exc:+ return _unreachable_message(+ proxy_root_url, probe, f"Could not acquire the startup lock: {exc}"+ )+ process = None+ capture_path = None+ try:+ # The startup budget starts now: time spent waiting for another+ # launcher's attempt must not shorten this launcher's own attempt.+ deadline = time.monotonic() + SERVER_STARTUP_TIMEOUT_SECONDS+ # Another launcher may have started the server while this one waited.+ probe = _probe_proxy(proxy_root_url, deadline=deadline)+ if probe.state is ProxyState.HEALTHY:+ return None+ if probe.state in {ProxyState.HTTP_ERROR, ProxyState.NETWORK_ERROR} or (+ probe.state is ProxyState.CONNECTION_CLOSED and not _owner_running()+ ):+ return _unreachable_message(+ proxy_root_url,+ probe,+ "The configured endpoint failed its health check.",+ )+ if not acquired:+ return _unreachable_message(+ proxy_root_url,+ probe,+ "Another launcher is still starting the server; retry shortly.",+ )+ if (+ probe.state is ProxyState.UNREACHABLE+ and time.monotonic() < deadline+ and not _owner_running()+ ):+ try:+ process, capture_path = _spawn_server(env)+ except OSError as exc:+ return _unreachable_message(+ proxy_root_url, probe, f"Could not start FCC: {exc}"+ )+ print(+ f"Starting Free Claude Code at {proxy_root_url} "+ "(it keeps running after this client exits).",+ file=sys.stderr,+ )+ outcome = _wait_for_server(proxy_root_url, process, deadline=deadline)+ if isinstance(outcome, str):+ if process is not None:+ if process.poll() is None:+ outcome += "\nFCC was left running for inspection."+ outcome = _startup_diagnostics(outcome, capture_path)+ return _unreachable_message(proxy_root_url, probe, outcome)+ if outcome.state is ProxyState.HEALTHY:+ return None+ return _unreachable_message(+ proxy_root_url, outcome, "Could not use the FCC endpoint."+ )+ except BaseException:+ if process is not None:+ _stop_owned_process(process)+ raise+ finally:+ lock.release()def resolve_client_binary(diff --git a/src/free_claude_code/cli/launchers/runner.py b/src/free_claude_code/cli/launchers/runner.pyindex 16006400..74b848a3 100644--- a/src/free_claude_code/cli/launchers/runner.py+++ b/src/free_claude_code/cli/launchers/runner.py@@ -18,7 +18,7 @@ from free_claude_code.harnesses.launch import NativeCheck, PreparedLaunchfrom free_claude_code.harnesses.resources import LaunchResourcesfrom .catalog_http import fetch_proxy_model_catalog-from .common import preflight_proxy, resolve_client_binary, run_client_process+from .common import ensure_proxy_available, resolve_client_binary, run_client_process@dataclass(frozen=True, slots=True)@@ -114,11 +114,8 @@ def launch_harness(spec: HarnessSpec, argv: Sequence[str] | None = None) -> Noneif not auth_token:raise LaunchError("Free Claude Code proxy authentication token is empty.")proxy_root_url = local_proxy_root_url(settings)- if error := preflight_proxy(proxy_root_url):- raise LaunchError(- f"Free Claude Code proxy is not reachable at {proxy_root_url}: {error}\n"- "Start it in another terminal with: fcc-server"- )+ if error := ensure_proxy_available(proxy_root_url, env=base_env):+ raise LaunchError(error)catalog = Noneif spec.catalog_view is not None:stage = "prepare model catalog"diff --git a/src/free_claude_code/config/paths.py b/src/free_claude_code/config/paths.pyindex 7e353bb1..aa508646 100644--- a/src/free_claude_code/config/paths.py+++ b/src/free_claude_code/config/paths.py@@ -9,11 +9,14 @@ LEGACY_XDG_CONFIG_DIRNAME = ".config"MESSAGING_STATE_DIRNAME = "agent_workspace"FCC_LOGS_DIRNAME = "logs"SERVER_LOG_FILENAME = "server.log"+SERVER_STARTUP_LOG_FILENAME = "startup.log"CODEX_MODEL_CATALOG_FILENAME = "codex-model-catalog.json"AUTH_DIRNAME = "auth"OPENAI_AUTH_FILENAME = "openai.json"OPENAI_AUTH_LOCK_FILENAME = "openai.lock"CONFIG_LOCK_FILENAME = "config.lock"+SERVER_STARTUP_LOCK_FILENAME = "server.startup.lock"+SERVER_OWNER_LOCK_FILENAME = "server.owner.lock"FCC_TEMP_DIRNAME = "tmp"LAUNCHER_TEMP_DIRNAME = "launchers"CODE_STATE_DIRNAME = "code"@@ -40,6 +43,18 @@ def config_lock_path() -> Path:return config_dir_path() / CONFIG_LOCK_FILENAME+def server_startup_lock_path() -> Path:+ """Return the lock launchers hold while starting one shared fcc-server."""++ return config_dir_path() / SERVER_STARTUP_LOCK_FILENAME+++def server_owner_lock_path() -> Path:+ """Return the lock held by one server through all configuration restarts."""++ return config_dir_path() / SERVER_OWNER_LOCK_FILENAME++def launcher_temp_dir_path() -> Path:"""Return the base directory for private native launcher configuration."""@@ -83,6 +98,12 @@ def server_log_path() -> Path:return config_dir_path() / FCC_LOGS_DIRNAME / SERVER_LOG_FILENAME+def server_startup_log_path() -> Path:+ """Return the latest automatic owner's output before runtime logging starts."""++ return config_dir_path() / FCC_LOGS_DIRNAME / SERVER_STARTUP_LOG_FILENAME++def codex_model_catalog_path() -> Path:"""Return the generated Codex model catalog path."""diff --git a/tests/cli/test_autostart_logging.py b/tests/cli/test_autostart_logging.pynew file mode 100644index 00000000..7dcc972c--- /dev/null+++ b/tests/cli/test_autostart_logging.py@@ -0,0 +1,96 @@+"""Automatic server launches retain runtime logs across config restarts."""++import subprocess+import sys+import textwrap++import pytest++from free_claude_code.core.interprocess_lock import InterprocessFileLock++[email protected]("automatic", [False, True])+def test_server_entrypoint_routes_logs_across_restarts(+ tmp_path, monkeypatch, automatic+):+ user_home = tmp_path / "user-home"+ monkeypatch.setenv("HOME", str(user_home))+ monkeypatch.setenv("USERPROFILE", str(user_home))+ log_path = tmp_path / "server.log"+ script = textwrap.dedent("""+ import logging+ import sys+ from pathlib import Path+ from types import SimpleNamespace+ from unittest.mock import patch+ from loguru import logger+ from free_claude_code.config import paths+ paths.config_dir_path = lambda: Path(sys.argv[3])+ from free_claude_code.cli import commands, entrypoints, uvicorn_server+ from free_claude_code.config.logging_config import configure_logging+ from free_claude_code.config.settings import Settings+ from free_claude_code.runtime import bootstrap++ settings = Settings.model_construct(+ host="127.0.0.1", port=0, open_admin_browser=False,+ )+ generations = []+ async def closed():+ return True++ def build(settings, restart_callback):+ configure_logging(sys.argv[1])+ generations.append(restart_callback)+ return SimpleNamespace(runtime=SimpleNamespace(+ is_closed=True, begin_shutdown=lambda: None, close=closed,+ http_started=lambda: None, instance_id="test-instance",+ ))++ def run(self, **kwargs):+ generation = len(generations)+ logging.getLogger("uvicorn.access").info(+ '%s - "%s %s HTTP/%s" %d', "client", "GET",+ f"/generation-{generation}", "1.1", 200,+ )+ logging.getLogger("uvicorn.error").error(f"error-generation-{generation}")+ logger.info(f"application-generation-{generation}")+ if generation == 1:+ generations[-1]()++ with (+ patch.object(commands, "load_server_settings", return_value=settings),+ patch.object(commands, "kill_all_best_effort"),+ patch.object(bootstrap, "build_asgi_app", side_effect=build),+ patch.object(uvicorn_server.RuntimeServer, "run", run),+ ):+ entrypoints.serve(["--auto-started"] if sys.argv[2] == "True" else [])+ logger.complete()+ assert len(generations) == 2+ """)+ with InterprocessFileLock(user_home / ".fcc" / "server.owner.lock"):+ result = subprocess.run(+ [+ sys.executable,+ "-c",+ script,+ str(log_path),+ str(automatic),+ str(tmp_path / "test-config"),+ ],+ capture_output=True,+ text=True,+ timeout=15,+ check=False,+ )+ assert result.returncode == 0, result.stderr+ saved = log_path.read_text(encoding="utf-8")+ for generation in (1, 2):+ assert f"application-generation-{generation}" in saved+ if automatic:+ assert f"/generation-{generation}" in saved+ assert f"error-generation-{generation}" in saved+ else:+ assert f"/generation-{generation}" in result.stdout+ assert f"error-generation-{generation}" in result.stderr+ if automatic:+ assert result.stdout == result.stderr == ""diff --git a/tests/cli/test_config_restart_lifecycle.py b/tests/cli/test_config_restart_lifecycle.pyindex a3868329..2f1d1bf9 100644--- a/tests/cli/test_config_restart_lifecycle.py+++ b/tests/cli/test_config_restart_lifecycle.py@@ -4,22 +4,209 @@ import socketimport threadingimport timefrom concurrent.futures import ThreadPoolExecutor+from types import SimpleNamespaceimport httpximport pytestfrom free_claude_code.api.app import create_appfrom free_claude_code.api.ports import ApiServices-from free_claude_code.cli import commands+from free_claude_code.application.code_sessions import CodeService+from free_claude_code.cli import commands, desktop+from free_claude_code.cli.launchers import common+from free_claude_code.config import pathsfrom free_claude_code.config.loader import ManagedConfigStore+from free_claude_code.core.interprocess_lock import InterprocessFileLockfrom free_claude_code.providers.runtime import ProviderRuntimefrom free_claude_code.runtime.application import ApplicationRuntimefrom free_claude_code.runtime.asgi import RuntimeASGIApp+from free_claude_code.runtime.code_sessions_sqlite import SQLiteCodeStorefrom free_claude_code.runtime.configuration import ConfigurationServicefrom free_claude_code.runtime.provider_manager import ProviderRuntimeManager+from free_claude_code.runtime.sqlite_database import SQLiteDatabase+from tests.code_sessions_support import FakeHarnessfrom tests.web_tools_support import StubWebToolsClient[email protected]("owner_kind", ["desktop", "terminal"])[email protected]("change_port", [False, True])+def test_harness_waits_through_owner_apply_restart(+ monkeypatch, change_port, owner_kind+):+ monkeypatch.setenv("HOST", "127.0.0.1")+ monkeypatch.setenv("FCC_OPEN_BROWSER", "0")+ monkeypatch.delenv("PORT", raising=False)+ monkeypatch.delenv("LOG_LEVEL", raising=False)+ with socket.socket() as first, socket.socket() as second:+ first.bind(("127.0.0.1", 0))+ second.bind(("127.0.0.1", 0))+ port = first.getsockname()[1]+ next_port = second.getsockname()[1] if change_port else port+ store = ManagedConfigStore()+ store.initialize()+ store.commit(dict(store.read().managed) | {"PORT": str(port)})+ runtimes = []++ def build(settings, restart_callback):+ manager = ProviderRuntimeManager(+ settings,+ runtime_factory=lambda snapshot, admission_registry: ProviderRuntime(+ snapshot, admission_registry, {}+ ),+ )+ monkeypatch.setattr(manager, "start_model_list_refresh", lambda: None)+ monkeypatch.setattr(manager, "_start_pass", lambda *args, **kwargs: None)+ database = SQLiteDatabase(paths.fcc_database_path(), paths.code_lock_path())+ code = CodeService(SQLiteCodeStore(database), FakeHarness())+ runtime = ApplicationRuntime(+ manager,+ configuration=ConfigurationService(ManagedConfigStore()),+ code_service=code,+ database=database,+ transcriber=None,+ restart_callback=restart_callback,+ )+ runtimes.append(runtime)+ return RuntimeASGIApp(+ create_app(+ ApiServices(+ requests=manager,+ admin=runtime,+ tasks=runtime,+ web_tools=StubWebToolsClient(),+ code=code,+ )+ ),+ runtime,+ )++ monkeypatch.setattr("free_claude_code.runtime.bootstrap.build_asgi_app", build)+ monkeypatch.setattr(commands, "kill_all_best_effort", lambda: None)+ monkeypatch.setattr(desktop, "config_dir_path", paths.config_dir_path)+ # Exercise both installed owner paths on every host without native tray code.+ monkeypatch.setattr(+ common,+ "sys",+ SimpleNamespace(platform="win32" if owner_kind == "desktop" else "linux"),+ )+ monkeypatch.setattr(common, "PROXY_PREFLIGHT_TIMEOUT_SECONDS", 0.1)+ monkeypatch.setattr(common, "SERVER_STARTUP_POLL_SECONDS", 0.01)++ def unexpected_spawn(_env):+ pytest.fail("The existing FCC process must own its restart")++ monkeypatch.setattr(common, "_spawn_server", unexpected_spawn)+ restart_entered, release_restart = threading.Event(), threading.Event()+ run_once = commands.ServerSupervisor._run_once++ def gated_run(self, settings, **kwargs):+ if runtimes:+ restart_entered.set()+ assert release_restart.wait(10)+ return run_once(self, settings, **kwargs)++ monkeypatch.setattr(commands.ServerSupervisor, "_run_once", gated_run)+ wait_for_server = common._wait_for_server++ def release_when_waiting(*args, **kwargs):+ release_restart.set()+ return wait_for_server(*args, **kwargs)++ monkeypatch.setattr(common, "_wait_for_server", release_when_waiting)+ trays = []++ class Tray:+ def __init__(self, controller):+ self.controller = controller+ self.stopped = threading.Event()+ trays.append(self)++ def run(self, setup):+ setup()+ assert self.stopped.wait(20)++ def stop(self):+ self.stopped.set()++ errors = []+ supervisor = commands.ServerSupervisor(console_logging=False)++ def serve_terminal():+ try:+ supervisor.run(open_admin_browser=False)+ except BaseException as exc:+ errors.append(exc)++ owner = (+ threading.Thread(target=desktop.launch_desktop, args=(Tray,))+ if owner_kind == "desktop"+ else threading.Thread(target=serve_terminal)+ )+ owner.start()+ try:+ with httpx.Client(trust_env=False, timeout=1) as client:++ def code_ready(on_port):+ deadline = time.monotonic() + 10+ while time.monotonic() < deadline:+ response = client.get(+ f"http://127.0.0.1:{on_port}/admin/api/code/bootstrap"+ )+ if response.json()["storage"]["state"] == "ready":+ assert response.json()["available"]+ return+ time.sleep(0.01)+ pytest.fail("Code storage did not become ready")++ deadline = time.monotonic() + 10+ while True:+ try:+ before = client.get(f"http://127.0.0.1:{port}/admin/api/status")+ if before.status_code == 200:+ break+ except httpx.TransportError:+ pass+ assert time.monotonic() < deadline+ time.sleep(0.01)+ code_ready(port)+ response = client.post(+ f"http://127.0.0.1:{port}/admin/api/config/apply",+ json={+ "values": {"PORT": str(next_port)}+ if change_port+ else {"LOG_LEVEL": "WARNING"}+ },+ )+ assert response.status_code == 200+ assert response.json()["restart"]["automatic"]+ assert restart_entered.wait(5)+ with pytest.raises(OSError, match="already owns"):+ commands.ServerSupervisor().run(open_admin_browser=False)+ assert (+ common.ensure_proxy_available(f"http://127.0.0.1:{next_port}", env={})+ is None+ )+ after = client.get(f"http://127.0.0.1:{next_port}/admin/api/status").json()+ assert after["instance_id"] != before.json()["instance_id"]+ assert after["port"] == next_port+ assert owner.is_alive()+ code_ready(next_port)+ finally:+ release_restart.set()+ if trays:+ trays[0].controller.quit()+ else:+ supervisor.request_stop()+ owner.join(10)+ assert not owner.is_alive()+ assert not errors+ released = InterprocessFileLock(paths.server_owner_lock_path())+ assert released.acquire()+ released.release()+ assert len(runtimes) == 2+ assert all(runtime.is_closed for runtime in runtimes)++@pytest.mark.parametrize("stop_during_commit", [False, True])def test_supervised_http_apply_finishes_and_reconnects(monkeypatch, stop_during_commit):monkeypatch.setenv("HOST", "127.0.0.1")diff --git a/tests/cli/test_desktop.py b/tests/cli/test_desktop.pyindex 38baee6f..d7504636 100644--- a/tests/cli/test_desktop.py+++ b/tests/cli/test_desktop.py@@ -4,6 +4,8 @@ import threadingfrom pathlib import Pathfrom unittest.mock import MagicMock, patch+import pytest+from free_claude_code.cli.commands import ServerStatus, ServerSupervisorfrom free_claude_code.cli.desktop import DesktopControllerfrom free_claude_code.config.settings import Settings@@ -234,7 +236,38 @@ def test_second_desktop_launch_opens_existing_admin_without_new_server() -> Noneinstance_lock.release.assert_not_called()-def test_desktop_attaches_to_terminal_server_instead_of_binding_twice() -> None:[email protected]("loser", ["singleton", "existing_server"])+def test_automatically_started_duplicate_does_not_open_admin(+ loser: str,+) -> None:+ from free_claude_code.cli import desktop++ settings = _settings()+ instance_lock = MagicMock()+ instance_lock.acquire.return_value = loser != "singleton"+ controller = MagicMock()+ with (+ patch.object(desktop, "load_server_settings", return_value=settings),+ patch.object(desktop, "InterprocessFileLock", return_value=instance_lock),+ patch.object(desktop, "open_admin_when_ready") as open_admin,+ patch.object(desktop, "ServerSupervisor") as supervisor,+ patch.object(desktop, "DesktopController", return_value=controller) as shell,+ ):+ controller.run.side_effect = lambda: shell.call_args.args[3]()+ if loser == "existing_server":+ supervisor.return_value.run.side_effect = lambda **kwargs: kwargs[+ "existing_server"+ ](settings)+ desktop.launch_desktop(MagicMock(), auto_started=True)++ open_admin.assert_not_called()+ controller.quit.assert_called_once_with()++[email protected]("endpoint_ready", [False, True])+def test_desktop_attaches_to_terminal_server_instead_of_binding_twice(+ endpoint_ready: bool,+) -> None:from free_claude_code.cli import desktopsettings = _settings()@@ -245,7 +278,9 @@ def test_desktop_attaches_to_terminal_server_instead_of_binding_twice() -> None:with (patch.object(desktop, "load_server_settings", return_value=settings),patch.object(desktop, "InterprocessFileLock", return_value=instance_lock),- patch.object(desktop, "open_admin_when_ready", return_value=True) as open_admin,+ patch.object(+ desktop, "open_admin_when_ready", return_value=endpoint_ready+ ) as open_admin,patch.object(desktop, "ServerSupervisor") as supervisor,patch.object(desktop, "DesktopController", return_value=controller) as shell,):@@ -261,6 +296,7 @@ def test_desktop_attaches_to_terminal_server_instead_of_binding_twice() -> None:supervisor.assert_called_once_with(console_logging=False)supervisor.return_value.run.assert_called_once()instance_lock.release.assert_called_once_with()+ controller.quit.assert_called_once_with()def test_fresh_desktop_launch_uses_console_free_supervisor() -> None:@@ -295,6 +331,7 @@ def test_desktop_lock_failure_closes_tray_without_starting_server():instance_lock.acquire.side_effect = PermissionError("locked directory")controller = MagicMock()with (+ patch.object(desktop, "load_server_settings", return_value=_settings()),patch.object(desktop, "InterprocessFileLock", return_value=instance_lock),patch.object(desktop, "ServerSupervisor") as supervisor,patch.object(desktop, "DesktopController", return_value=controller) as shell,diff --git a/tests/cli/test_desktop_assets.py b/tests/cli/test_desktop_assets.pyindex c0689661..5dbf53d7 100644--- a/tests/cli/test_desktop_assets.py+++ b/tests/cli/test_desktop_assets.py@@ -59,7 +59,8 @@ def test_desktop_entrypoint_rejects_unknown_arguments(assert "Usage: fcc-desktop" in capsys.readouterr().err-def test_desktop_sets_scaling_before_importing_native_tray(monkeypatch):[email protected]("auto_started", [False, True])+def test_desktop_sets_scaling_before_importing_native_tray(monkeypatch, auto_started):calls = []monkeypatch.setattr(desktop_entrypoint.sys, "platform", "win32")monkeypatch.setattr(@@ -72,9 +73,14 @@ def test_desktop_sets_scaling_before_importing_native_tray(monkeypatch):def import_module(name, *args, **kwargs):if name == "free_claude_code.cli.desktop_tray":assert calls == ["scaling"]- return SimpleNamespace(launch=lambda: calls.append("tray"))++ def launch(**kwargs):+ assert kwargs == {"auto_started": auto_started}+ calls.append("tray")++ return SimpleNamespace(launch=launch)return original_import(name, *args, **kwargs)monkeypatch.setattr(builtins, "__import__", import_module)- desktop_entrypoint.launch([])+ desktop_entrypoint.launch(["--auto-started"] if auto_started else [])assert calls == ["scaling", "tray"]diff --git a/tests/cli/test_entrypoints.py b/tests/cli/test_entrypoints.pyindex 1389a822..546462ce 100644--- a/tests/cli/test_entrypoints.py+++ b/tests/cli/test_entrypoints.py@@ -104,7 +104,7 @@ def test_non_version_entrypoint_delegates_to_server_command() -> None:with patch.object(commands, "serve") as command:entrypoints.serve(())- command.assert_called_once_with()+ command.assert_called_once_with(console_logging=True)def test_explicit_open_admin_waits_for_owned_http_ready():diff --git a/tests/cli/test_local_http.py b/tests/cli/test_local_http.pyindex 139f44c2..5b706287 100644--- a/tests/cli/test_local_http.py+++ b/tests/cli/test_local_http.py@@ -7,7 +7,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServerimport pytest-from free_claude_code.cli.launchers.common import preflight_proxy+from free_claude_code.cli.launchers.common import ensure_proxy_available@contextmanager@@ -44,7 +44,7 @@ def test_proxy_preflight_connects_directly_when_http_proxy_is_configured(monkeypatch.delenv("no_proxy", raising=False)with _status_server(200) as (fcc_url, fcc_hits):- assert preflight_proxy(fcc_url) is None+ assert ensure_proxy_available(fcc_url, env={}) is Noneassert fcc_hits == ["/health"]assert forward_proxy_hits == []diff --git a/tests/cli/test_progressive_launch.py b/tests/cli/test_progressive_launch.pyindex 82fa5c20..fa0d7e21 100644--- a/tests/cli/test_progressive_launch.py+++ b/tests/cli/test_progressive_launch.py@@ -17,7 +17,6 @@ import uvicornfrom fastapi import FastAPIfrom free_claude_code.cli import commands-from free_claude_code.cli.launchers import commonfrom free_claude_code.cli.server_socket import ServerSocketsfrom free_claude_code.cli.uvicorn_server import RuntimeServerfrom free_claude_code.config.settings import Settings@@ -330,6 +329,7 @@ def test_browser_thread_start_failure_does_not_fail_fcc(monkeypatch, reuse, capldef _run_browser_shutdown_probe(mode, outcome, directory, setup_delay="0"):"""Run real FCC lifecycle owners with only OS/browser/server dependencies faked."""from free_claude_code.cli import desktop, uvicorn_server+ from free_claude_code.config import pathsfrom free_claude_code.runtime import bootstrapprint("probe: setup", flush=True)@@ -341,6 +341,7 @@ def _run_browser_shutdown_probe(mode, outcome, directory, setup_delay="0"):patcher.setattr(commands, "load_server_settings", lambda: settings)patcher.setattr(desktop, "load_server_settings", lambda: settings)patcher.setattr(desktop, "config_dir_path", lambda: Path(directory))+ patcher.setattr(paths, "config_dir_path", lambda: Path(directory))def browser(url):assert url == "http://127.0.0.1:0/admin"@@ -522,24 +523,3 @@ def test_external_probe_is_cancelled_before_any_request(monkeypatch):monkeypatch.setattr(commands, "open_local_request", request)assert not commands.open_admin_when_ready(Settings(), stop_event=stop)request.assert_not_called()---def test_launcher_retries_starting_http_but_not_refused_socket(monkeypatch):- response = MagicMock()- response.__enter__.return_value.status = 200- request = MagicMock(side_effect=[TimeoutError("starting"), response])- monkeypatch.setattr(common, "open_local_request", request)- assert common.preflight_proxy("http://127.0.0.1:12345") is None- assert request.call_count == 2- request.reset_mock(side_effect=True)- request.side_effect = URLError(ConnectionRefusedError("refused"))- assert common.preflight_proxy("http://127.0.0.1:12345") == "refused"- assert request.call_count == 1---def test_launcher_http_wait_has_a_finite_budget(monkeypatch):- monkeypatch.setattr(common.time, "monotonic", MagicMock(side_effect=[0, 0, 31]))- request = MagicMock(side_effect=TimeoutError("still starting"))- monkeypatch.setattr(common, "open_local_request", request)- assert common.preflight_proxy("http://127.0.0.1:12345") == "still starting"- assert request.call_count == 1diff --git a/tests/cli/test_server_autostart.py b/tests/cli/test_server_autostart.pynew file mode 100644index 00000000..faf30c0a--- /dev/null+++ b/tests/cli/test_server_autostart.py@@ -0,0 +1,714 @@+"""Launchers start one shared platform owner when the local proxy is down."""++import os+import socket+import subprocess+import sys+import threading+from collections.abc import Mapping+from concurrent.futures import ThreadPoolExecutor+from http.client import RemoteDisconnected+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import MagicMock+from urllib.error import URLError++import pytest++from free_claude_code.cli.launchers import common+from free_claude_code.config.paths import (+ server_owner_lock_path,+ server_startup_lock_path,+)+from free_claude_code.core.interprocess_lock import InterprocessFileLock+from tests.cli.conftest import LaunchCapture+from tests.cli.test_launcher_workflow import launch++URL = "http://127.0.0.1:8182"+++def _status(code: int) -> MagicMock:+ response = MagicMock()+ response.__enter__.return_value.status = code+ return response+++def _healthy() -> MagicMock:+ return _status(200)+++def _refused() -> URLError:+ return URLError(ConnectionRefusedError("refused"))+++class FakeServer:+ def __init__(self, exit_code: int | None = None) -> None:+ self.exit_code = exit_code+ self.terminated = False++ def poll(self) -> int | None:+ return self.exit_code++ def terminate(self) -> None:+ self.terminated = True+ self.exit_code = 0++ def wait(self, timeout: float | None = None) -> int:+ assert self.exit_code is not None+ return self.exit_code++[email protected](autouse=True)+def _fast_polling(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(common, "SERVER_STARTUP_POLL_SECONDS", 0)+ monkeypatch.setattr(common, "_desktop_owner_running", lambda: False)+++def clock(monkeypatch):+ clock = SimpleNamespace(now=0.0)++ def sleep(seconds):+ clock.now += seconds++ monkeypatch.setattr(+ common, "time", SimpleNamespace(monotonic=lambda: clock.now, sleep=sleep)+ )+ monkeypatch.setattr(common, "SERVER_STARTUP_POLL_SECONDS", 0.25)+ monkeypatch.setattr(common, "SERVER_STARTUP_TIMEOUT_SECONDS", 1.0)+ return clock+++def spawned(monkeypatch: pytest.MonkeyPatch) -> list[tuple[list[str], dict]]:+ calls: list[tuple[list[str], dict]] = []++ def popen(command: list[str], **kwargs: object) -> FakeServer:+ calls.append((command, kwargs))+ return FakeServer()++ monkeypatch.setattr(common.subprocess, "Popen", popen)+ return calls+++def _responses(monkeypatch: pytest.MonkeyPatch, *responses: object) -> MagicMock:+ request = MagicMock(side_effect=list(responses))+ monkeypatch.setattr(common, "open_local_request", request)+ return request+++def test_healthy_proxy_needs_no_server(monkeypatch, spawned) -> None:+ request = _responses(monkeypatch, _healthy())+ assert common.ensure_proxy_available(URL, env={}) is None+ assert request.call_count == 1+ assert spawned == []+++def test_answering_but_unhealthy_proxy_is_not_restarted(monkeypatch, spawned) -> None:+ _responses(monkeypatch, _status(503))+ message = common.ensure_proxy_available(URL, env={})+ assert message is not None+ assert "returned HTTP 503" in message+ assert "Start it manually with:" in message+ assert spawned == []+++def test_missing_server_is_started_once_and_awaited(+ monkeypatch, spawned, capsys: pytest.CaptureFixture[str]+) -> None:+ request = _responses(monkeypatch, _refused(), _refused(), _refused(), _healthy())+ env = {"PATH": "/usr/bin", "MODEL": "nvidia_nim/test"}++ assert common.ensure_proxy_available(URL, env=env) is None++ assert request.call_count == 4+ assert len(spawned) == 1+ command, kwargs = spawned[0]+ assert command == common.server_command()+ assert kwargs["env"] == env+ assert kwargs["env"] is not env+ assert kwargs["stdin"] is subprocess.DEVNULL+ assert kwargs["stdout"] not in (None, subprocess.DEVNULL)+ assert kwargs["stderr"] is subprocess.STDOUT+ if sys.platform == "win32":+ assert kwargs["creationflags"]+ else:+ assert kwargs["start_new_session"] is True+ assert "Starting Free Claude Code" in capsys.readouterr().err+ # The startup lock is released for the next launcher.+ lock = InterprocessFileLock(server_startup_lock_path())+ assert lock.acquire()+ lock.release()+++def test_server_exit_before_ready_is_reported(monkeypatch) -> None:+ _responses(monkeypatch, _refused(), _refused(), _refused())+ monkeypatch.setattr(+ common.subprocess, "Popen", lambda *_a, **_k: FakeServer(exit_code=3)+ )+ message = common.ensure_proxy_available(URL, env={})+ assert message is not None+ assert "exited with code 3" in message+ assert "Start it manually with:" in message+++def test_startup_wait_is_bounded(monkeypatch, spawned, clock) -> None:+ monkeypatch.setattr(common, "open_local_request", MagicMock(side_effect=_refused()))+ message = common.ensure_proxy_available(URL, env={})+ assert message is not None+ assert "did not become ready" in message+ assert len(spawned) == 1+ assert clock.now == 1.0+++def test_timed_out_start_preserves_running_desktop(monkeypatch, clock) -> None:+ monkeypatch.setattr(common, "open_local_request", MagicMock(side_effect=_refused()))+ child = FakeServer()+ monkeypatch.setattr(common, "server_command", lambda: ["fcc-test"])+ monkeypatch.setattr(common.subprocess, "Popen", lambda *_a, **_k: child)++ message = common.ensure_proxy_available(URL, env={})++ assert message is not None and "did not become ready" in message+ assert not child.terminated+++def test_unhealthy_started_server_remains_available_for_inspection(monkeypatch) -> None:+ _responses(monkeypatch, _refused(), _refused(), _status(503))+ child = FakeServer()+ monkeypatch.setattr(common, "server_command", lambda: ["fcc-test"])+ monkeypatch.setattr(common.subprocess, "Popen", lambda *_a, **_k: child)++ message = common.ensure_proxy_available(URL, env={})++ assert message is not None and "returned HTTP 503" in message+ assert not child.terminated+++def test_ready_server_outlives_harness(monkeypatch) -> None:+ _responses(monkeypatch, _refused(), _refused(), _healthy())+ child = FakeServer()+ monkeypatch.setattr(common, "server_command", lambda: ["fcc-test"])+ monkeypatch.setattr(common.subprocess, "Popen", lambda *_a, **_k: child)++ assert common.ensure_proxy_available(URL, env={}) is None+ assert not child.terminated+++def test_manual_desktop_startup_is_awaited_without_another_spawn(+ monkeypatch, spawned+) -> None:+ monkeypatch.setattr(common, "_desktop_owner_running", lambda: True)+ _responses(monkeypatch, _refused(), _refused(), _healthy())++ assert common.ensure_proxy_available(URL, env={}) is None+ assert spawned == []+++def test_short_lived_duplicate_desktop_yields_to_manual_owner(monkeypatch) -> None:+ _responses(monkeypatch, _refused(), _refused(), _refused(), _healthy())+ ownership = iter((False, True))+ monkeypatch.setattr(common, "_desktop_owner_running", lambda: next(ownership))+ child = FakeServer(exit_code=0)+ monkeypatch.setattr(common, "server_command", lambda: ["fcc-test"])+ monkeypatch.setattr(common.subprocess, "Popen", lambda *_a, **_k: child)++ assert common.ensure_proxy_available(URL, env={}) is None+ assert not child.terminated+++def test_other_port_desktop_owner_waits_without_spawning(+ monkeypatch, spawned, clock+) -> None:+ monkeypatch.setattr(common, "_desktop_owner_running", lambda: True)+ monkeypatch.setattr(common, "open_local_request", MagicMock(side_effect=_refused()))++ message = common.ensure_proxy_available(URL, env={})++ assert message is not None and "did not become ready" in message+ assert URL in message+ assert clock.now == 1.0+ assert spawned == []+++def test_terminal_owner_at_other_port_waits_without_spawning(+ monkeypatch, spawned, clock+) -> None:+ owner = InterprocessFileLock(server_owner_lock_path())+ assert owner.acquire()+ try:+ monkeypatch.setattr(+ common, "open_local_request", MagicMock(side_effect=_refused())+ )+ message = common.ensure_proxy_available(URL, env={})+ finally:+ owner.release()++ assert message is not None and "did not become ready" in message+ assert "check its configured port" in message+ assert spawned == []+++ "closed_connection",+ [+ ConnectionResetError("reset during restart"),+ ConnectionAbortedError("aborted during restart"),+ RemoteDisconnected("closed during restart"),+ ],+)[email protected]("phase", ["first_probe", "readiness_wait"])+def test_harness_waits_through_owner_connection_close(+ monkeypatch, spawned, closed_connection, phase+) -> None:+ owner = InterprocessFileLock(server_owner_lock_path())+ assert owner.acquire()+ try:+ if phase == "first_probe":+ _responses(monkeypatch, closed_connection, closed_connection, _healthy())+ else:+ _responses(+ monkeypatch, _refused(), _refused(), closed_connection, _healthy()+ )+ assert common.ensure_proxy_available(URL, env={}) is None+ finally:+ owner.release()+ assert spawned == []+++def test_unowned_connection_reset_does_not_start_fcc(monkeypatch, spawned) -> None:+ _responses(monkeypatch, ConnectionResetError("foreign listener reset"))+ message = common.ensure_proxy_available(URL, env={})+ assert message is not None and "foreign listener reset" in message+ assert spawned == []+++def test_cancelled_start_stops_only_new_child(monkeypatch) -> None:+ _responses(monkeypatch, _refused(), _refused())+ child = FakeServer()+ monkeypatch.setattr(common, "_spawn_server", lambda _env: (child, None))+ monkeypatch.setattr(+ common,+ "_wait_for_server",+ lambda *_a, **_k: (_ for _ in ()).throw(KeyboardInterrupt),+ )++ with pytest.raises(KeyboardInterrupt):+ common.ensure_proxy_available(URL, env={})++ assert child.terminated+ lock = InterprocessFileLock(server_startup_lock_path())+ assert lock.acquire()+ lock.release()+++def test_cancelled_wait_preserves_existing_owner(monkeypatch, spawned) -> None:+ monkeypatch.setattr(common, "_desktop_owner_running", lambda: True)+ _responses(monkeypatch, _refused(), _refused(), KeyboardInterrupt())+ with pytest.raises(KeyboardInterrupt):+ common.ensure_proxy_available(URL, env={})+ assert spawned == []+ lock = InterprocessFileLock(server_startup_lock_path())+ assert lock.acquire()+ lock.release()+++def test_manual_listener_wins_the_bind_race(monkeypatch) -> None:+ owner = InterprocessFileLock(server_owner_lock_path())+ try:+ with socket.socket() as listener:+ listener.bind(("127.0.0.1", 0))+ listener.listen()+ url = f"http://127.0.0.1:{listener.getsockname()[1]}"+ _responses(+ monkeypatch,+ _refused(),+ _refused(),+ TimeoutError("starting"),+ _healthy(),+ )+ child = FakeServer(exit_code=1)++ def spawn(_env):+ assert owner.acquire()+ return child, None++ monkeypatch.setattr(common, "_spawn_server", spawn)+ assert common.ensure_proxy_available(url, env={}) is None+ assert not child.terminated+ finally:+ owner.release()+++def test_unowned_listener_winning_bind_race_does_not_hide_child_failure(+ monkeypatch,+) -> None:+ with socket.socket() as listener:+ listener.bind(("127.0.0.1", 0))+ listener.listen()+ url = f"http://127.0.0.1:{listener.getsockname()[1]}"+ _responses(+ monkeypatch, _refused(), _refused(), TimeoutError("starting"), _healthy()+ )+ child = FakeServer(exit_code=1)+ monkeypatch.setattr(common, "_spawn_server", lambda _env: (child, None))+ message = common.ensure_proxy_available(url, env={})+ assert message is not None and "exited with code 1" in message+ assert not child.terminated+++def test_probe_caps_both_connections_to_remaining_time(monkeypatch, clock) -> None:+ def http(_request, *, timeout):+ assert timeout == 1.0+ clock.now = 0.8+ raise TimeoutError("loading")++ def tcp(_address, *, timeout):+ assert timeout == pytest.approx(0.2)+ return MagicMock()++ monkeypatch.setattr(common, "open_local_request", http)+ monkeypatch.setattr(common.socket, "create_connection", tcp)+ assert common._probe_proxy(URL, deadline=1.0).state is common.ProxyState.STARTING+++def test_expired_probe_does_not_start_any_connection(monkeypatch, clock) -> None:+ http = MagicMock()+ tcp = MagicMock()+ monkeypatch.setattr(common, "open_local_request", http)+ monkeypatch.setattr(common.socket, "create_connection", tcp)+ common._probe_proxy(URL, deadline=0.0)+ http.assert_not_called()+ tcp.assert_not_called()+++def test_http_timeout_at_deadline_does_not_start_tcp_probe(monkeypatch, clock) -> None:+ def http(_request, *, timeout):+ clock.now = 1.0+ raise TimeoutError("loading")++ tcp = MagicMock()+ monkeypatch.setattr(common, "open_local_request", http)+ monkeypatch.setattr(common.socket, "create_connection", tcp)+ assert common._probe_proxy(URL, deadline=1.0).state is common.ProxyState.STARTING+ tcp.assert_not_called()+++def test_exhausted_recheck_budget_does_not_spawn(monkeypatch, spawned, clock) -> None:+ calls = 0++ def request(_request, *, timeout):+ nonlocal calls+ calls += 1+ if calls == 2:+ clock.now = 1.0+ raise _refused()++ monkeypatch.setattr(common, "open_local_request", request)+ message = common.ensure_proxy_available(URL, env={})+ assert message is not None and "did not become ready" in message+ assert spawned == []+++def test_detached_streams_and_browser_preference_are_independent(monkeypatch) -> None:+ monkeypatch.setattr(common, "server_command", lambda: ["fcc-test"])+ observed = {}++ def popen(_command, **kwargs):+ observed.update(kwargs)+ return FakeServer()++ monkeypatch.setattr(common.subprocess, "Popen", popen)+ common._spawn_server({"FCC_OPEN_BROWSER": "0"})++ assert observed["env"]["FCC_OPEN_BROWSER"] == "0"+ assert observed["stdin"] is subprocess.DEVNULL+ assert observed["stdout"] not in (None, subprocess.DEVNULL)+ assert observed["stderr"] is subprocess.STDOUT+++def test_early_startup_error_is_retained_and_reported(monkeypatch) -> None:+ monkeypatch.setattr(common, "open_local_request", MagicMock(side_effect=_refused()))+ monkeypatch.setattr(+ common,+ "server_command",+ lambda: [+ sys.executable,+ "-c",+ "import sys; print('FCC startup: invalid test setting', "+ "file=sys.stderr); raise SystemExit(7)",+ ],+ )++ message = common.ensure_proxy_available(URL, env=dict(os.environ))++ assert message is not None+ assert "exited with code 7" in message+ assert "FCC startup: invalid test setting" in message+ log_path = common.paths.server_log_path().with_name("startup.log")+ assert str(log_path) in message+ assert "FCC startup: invalid test setting" in log_path.read_text()++[email protected]("failure", ["directory", "file"])[email protected]("outcome", ["ready", "exited", "timeout", "spawn_failure"])+def test_startup_log_failure_does_not_block_or_reuse_stale_output(+ monkeypatch, capsys, clock, failure, outcome+) -> None:+ log_path = common.paths.server_startup_log_path()+ log_path.parent.mkdir(parents=True, exist_ok=True)+ log_path.write_text("Previous attempt: stale startup error", encoding="utf-8")+ operation = Path.mkdir if failure == "directory" else Path.open++ def denied(path, *args, **kwargs):+ if (failure == "directory" and path == log_path.parent) or (+ failure == "file" and path == log_path and args == ("wb",)+ ):+ raise PermissionError("startup log access denied")+ return operation(path, *args, **kwargs)++ monkeypatch.setattr(Path, "mkdir" if failure == "directory" else "open", denied)+ if outcome == "timeout":+ monkeypatch.setattr(+ common, "open_local_request", MagicMock(side_effect=_refused())+ )+ else:+ _responses(+ monkeypatch,+ _refused(),+ _refused(),+ _healthy() if outcome == "ready" else _refused(),+ )+ child = FakeServer(exit_code=3 if outcome == "exited" else None)+ popen = MagicMock(return_value=child)+ if outcome == "spawn_failure":+ popen.side_effect = OSError("test executable failed")+ monkeypatch.setattr(common.subprocess, "Popen", popen)++ message = common.ensure_proxy_available(URL, env={"FCC_OPEN_BROWSER": "0"})++ popen.assert_called_once()+ assert popen.call_args.kwargs["stdout"] is subprocess.DEVNULL+ assert popen.call_args.kwargs["stderr"] is subprocess.STDOUT+ assert popen.call_args.kwargs["env"]["FCC_OPEN_BROWSER"] == "0"+ warning = capsys.readouterr().err+ assert str(log_path) in warning+ assert "startup log access denied" in warning+ if outcome == "ready":+ assert message is None+ else:+ detail = {+ "exited": "exited with code 3",+ "timeout": "did not become ready",+ "spawn_failure": "test executable failed",+ }[outcome]+ assert message is not None and detail in message+ assert "stale startup error" not in message+ assert not child.terminated+ lock = InterprocessFileLock(server_startup_lock_path())+ assert lock.acquire()+ lock.release()+++def test_existing_unresponsive_listener_is_not_replaced(+ monkeypatch, spawned, clock+) -> None:+ with socket.socket() as listener:+ listener.bind(("127.0.0.1", 0))+ listener.listen()+ url = f"http://127.0.0.1:{listener.getsockname()[1]}"+ monkeypatch.setattr(+ common,+ "open_local_request",+ MagicMock(side_effect=URLError(TimeoutError("starting"))),+ )+ assert common.ensure_proxy_available(url, env={}) is not None+ assert spawned == []+++def test_timed_out_tcp_connect_is_not_mistaken_for_starting_server(+ monkeypatch, spawned+) -> None:+ with socket.socket() as unused:+ unused.bind(("127.0.0.1", 0))+ url = f"http://127.0.0.1:{unused.getsockname()[1]}"+ _responses(+ monkeypatch,+ URLError(TimeoutError("timed out")),+ URLError(TimeoutError("timed out")),+ _healthy(),+ )+ assert common.ensure_proxy_available(url, env={}) is None+ assert len(spawned) == 1+++def test_other_network_error_is_not_treated_as_absent(monkeypatch, spawned) -> None:+ _responses(monkeypatch, URLError(PermissionError("blocked")))+ assert common.ensure_proxy_available(URL, env={}) is not None+ assert spawned == []+++def test_spawn_failure_is_reported(monkeypatch) -> None:+ _responses(monkeypatch, _refused(), _refused())++ def fail(*_args: object, **_kwargs: object) -> FakeServer:+ raise OSError("no such executable")++ monkeypatch.setattr(common.subprocess, "Popen", fail)+ message = common.ensure_proxy_available(URL, env={})+ assert message is not None+ assert "Could not start" in message+ assert "no such executable" in message++[email protected]("winner_succeeds", [True, False])+def test_concurrent_launchers_wait_for_the_lock_holder(+ monkeypatch, spawned, winner_succeeds: bool+) -> None:+ monkeypatch.setattr(common, "SERVER_STARTUP_TIMEOUT_SECONDS", 0.05)+ monkeypatch.setattr(common, "SERVER_STARTUP_LOCK_TIMEOUT_SECONDS", 0.05)+ holder = InterprocessFileLock(server_startup_lock_path())+ assert holder.acquire()+ try:+ _responses(+ monkeypatch, _refused(), _healthy() if winner_succeeds else _refused()+ )+ message = common.ensure_proxy_available(URL, env={})+ finally:+ holder.release()+ if winner_succeeds:+ assert message is None+ else:+ assert message is not None+ assert "Another launcher is still starting" in message+ assert spawned == []+++def test_two_launchers_share_one_start_attempt(monkeypatch) -> None:+ spawning, other_probed, release, healthy = (threading.Event() for _ in range(4))+ starts = []+ child = FakeServer()++ def probe(_url, *, deadline):+ if healthy.is_set():+ return common.ProxyProbe(common.ProxyState.HEALTHY)+ if starts and starts[0] != threading.get_ident():+ other_probed.set()+ return common.ProxyProbe(common.ProxyState.UNREACHABLE, "refused")++ def spawn(_env):+ starts.append(threading.get_ident())+ spawning.set()+ assert release.wait(5)+ healthy.set()+ return child, None++ monkeypatch.setattr(common, "_probe_proxy", probe)+ monkeypatch.setattr(common, "_spawn_server", spawn)+ with ThreadPoolExecutor(max_workers=2) as workers:+ first = workers.submit(common.ensure_proxy_available, URL, env={})+ try:+ assert spawning.wait(5)+ second = workers.submit(common.ensure_proxy_available, URL, env={})+ assert other_probed.wait(5)+ finally:+ release.set()+ assert first.result(timeout=5) is None+ assert second.result(timeout=5) is None+ assert len(starts) == 1+ assert not child.terminated+++def test_startup_budget_starts_after_the_lock_is_acquired(monkeypatch, spawned) -> None:+ monkeypatch.setattr(common, "SERVER_STARTUP_TIMEOUT_SECONDS", 0.05)+ monkeypatch.setattr(common, "SERVER_STARTUP_LOCK_TIMEOUT_SECONDS", 5.0)+ holder = InterprocessFileLock(server_startup_lock_path())+ assert holder.acquire()+ # The previous launcher gave up without a server, well after this+ # launcher's own startup budget would have expired.+ releaser = threading.Timer(0.2, holder.release)+ releaser.start()+ try:+ _responses(monkeypatch, _refused(), _refused(), _refused(), _healthy())+ assert common.ensure_proxy_available(URL, env={}) is None+ finally:+ releaser.cancel()+ holder.release()+ assert len(spawned) == 1+++ "platform,command_name",+ [("win32", "fcc-desktop.exe"), ("darwin", "fcc-desktop"), ("linux", "fcc-server")],+)+def test_server_command_selects_platform_owner(+ monkeypatch, tmp_path, platform, command_name+) -> None:+ executable = tmp_path / "bin" / "python"+ executable.parent.mkdir()+ monkeypatch.setattr(+ common, "sys", SimpleNamespace(executable=str(executable), platform=platform)+ )+ sibling = executable.parent / command_name+ sibling.write_text("")+ if sys.platform != "win32":+ sibling.chmod(0o755)+ assert common.server_command() == [str(sibling), "--auto-started"]+++def test_missing_installed_owner_does_not_fallback_to_python(+ monkeypatch, tmp_path+) -> None:+ executable = tmp_path / "bin" / "python"+ executable.parent.mkdir()+ monkeypatch.setattr(+ common,+ "sys",+ SimpleNamespace(executable=str(executable), platform=sys.platform),+ )+ with pytest.raises(OSError, match="fcc-"):+ common.server_command()++[email protected]("name", ["claude", "aider"])+def test_launcher_starts_the_server_then_runs_the_client(+ name: str,+ launch_capture: LaunchCapture,+ monkeypatch: pytest.MonkeyPatch,+ capsys: pytest.CaptureFixture[str],+) -> None:+ launch_capture.health_error = _refused()+ client_start = subprocess.Popen+ server_command = common.server_command()++ def popen(command: list[str], **kwargs: object) -> object:+ if command == server_command:+ assert kwargs["stdout"] not in (None, subprocess.DEVNULL)+ launch_capture.health_error = None+ return FakeServer()+ env = kwargs["env"]+ assert isinstance(env, Mapping)+ return client_start(command, env=env)++ monkeypatch.setattr(subprocess, "Popen", popen)+ launch(name, ["--help"])++ assert [command[-1] for command in launch_capture.commands] == ["--help"]+ health = [r for r in launch_capture.requests if r.full_url.endswith("/health")]+ assert len(health) >= 3+ assert "Starting Free Claude Code" in capsys.readouterr().err+ assert server_startup_lock_path().exists()+++def test_launcher_keeps_the_manual_hint_when_the_server_cannot_start(+ launch_capture: LaunchCapture,+ monkeypatch: pytest.MonkeyPatch,+ capsys: pytest.CaptureFixture[str],+) -> None:+ launch_capture.health_error = _refused()+ monkeypatch.setattr(subprocess, "Popen", lambda *_a, **_k: FakeServer(exit_code=1))+ launch("claude", [], exit_code=1)+ assert not launch_capture.commands+ err = capsys.readouterr().err+ assert "exited with code 1" in err+ assert "Start it manually with:" in errdiff --git a/tests/contracts/test_smoke_child_process.py b/tests/contracts/test_smoke_child_process.pyindex b9f6a9f0..436e981b 100644--- a/tests/contracts/test_smoke_child_process.py+++ b/tests/contracts/test_smoke_child_process.py@@ -6,6 +6,7 @@ from unittest.mock import MagicMockimport httpximport pytest+from free_claude_code.config.loader import ManagedConfigStorefrom free_claude_code.config.settings import Settingsfrom smoke.lib import child_processfrom smoke.lib import e2e as smoke_e2e@@ -46,11 +47,12 @@ def test_fcc_server_command_uses_cli_entrypoint() -> None:assert cmd_fcc_server() == [child_process.python_exe(),"-c",- "from free_claude_code.cli.entrypoints import serve; serve()",+ "from smoke.lib.server_runtime import serve; serve()",]def test_start_server_disables_cli_admin_browser(monkeypatch, tmp_path: Path) -> None:+ ManagedConfigStore().initialize({})captured: dict[str, object] = {}class FakeProcess:diff --git a/tests/contracts/test_smoke_server_isolation.py b/tests/contracts/test_smoke_server_isolation.pynew file mode 100644index 00000000..5a3bfa84--- /dev/null+++ b/tests/contracts/test_smoke_server_isolation.py@@ -0,0 +1,187 @@+"""Smoke server subprocesses isolate runtime state and retain credential ownership."""++import json+import sys+import textwrap+from dataclasses import replace+from pathlib import Path++import pytest++from free_claude_code.config import paths+from free_claude_code.config.env_migrations import (+ CONFIG_SCHEMA_VERSION,+ atomic_write_managed_config,+)+from free_claude_code.config.loader import ManagedConfigStore, get_settings+from free_claude_code.core.interprocess_lock import InterprocessFileLock+from smoke.lib.child_process import cmd_fcc_server+from smoke.lib.config import SmokeConfig+from smoke.lib.server import start_server+++def smoke_config(tmp_path, monkeypatch):+ home = tmp_path / "user-home"+ monkeypatch.setenv("HOME", str(home))+ monkeypatch.setenv("USERPROFILE", str(home))+ monkeypatch.setattr(paths, "config_dir_path", lambda: home / ".fcc")+ store = ManagedConfigStore()+ store.initialize({})+ values = dict(store.read({}).managed)+ values.update(+ MODEL="nvidia_nim/managed-model",+ NVIDIA_NIM_API_KEY='["managed-one", "managed-two"]',+ ANTHROPIC_AUTH_TOKEN="managed-proxy-token",+ )+ store.commit(values)+ monkeypatch.setenv("GROQ_API_KEY", "process-only-key")+ return SmokeConfig(+ root=Path(__file__).resolve().parents[2],+ results_dir=tmp_path / "results",+ live=True,+ interactive=False,+ targets=frozenset(),+ provider_matrix=frozenset(),+ timeout_s=10,+ prompt="",+ claude_bin="claude",+ worker_id="test",+ settings=get_settings(),+ )+++def probe_command():+ # Execute the normal smoke command against a local owner/HTTP probe. This+ # exercises its actual child bootstrap without contacting model providers.+ probe = textwrap.dedent("""+ import json, os+ from http.server import BaseHTTPRequestHandler, HTTPServer+ from free_claude_code.cli import entrypoints+ from free_claude_code.config import paths+ from free_claude_code.config.api_keys import api_key_values+ from free_claude_code.config.loader import get_settings+ from free_claude_code.core.interprocess_lock import InterprocessFileLock++ def serve():+ settings = get_settings()+ print(json.dumps({+ 'config': str(paths.config_dir_path()),+ 'database': str(paths.fcc_database_path()),+ 'owner': str(paths.server_owner_lock_path()),+ 'auth': str(paths.openai_auth_path()),+ 'auth_lock': str(paths.openai_auth_lock_path()),+ 'copilot': str(paths.github_copilot_auth_path()),+ 'model': settings.model,+ 'keys': api_key_values(settings.nvidia_nim_api_keys),+ 'token': settings.proxy_auth_token,+ 'removed': os.environ.get('GROQ_API_KEY'),+ 'groq': api_key_values(settings.groq_api_keys),+ 'home': os.environ.get('USERPROFILE'),+ }), flush=True)+ class Health(BaseHTTPRequestHandler):+ def do_GET(self):+ self.send_response(200)+ self.end_headers()+ def log_message(self, *args):+ pass+ with InterprocessFileLock(paths.server_owner_lock_path()):+ with HTTPServer(('127.0.0.1', int(os.environ['PORT'])), Health) as server:+ server.serve_forever()+ entrypoints.serve = serve+ """)+ return [sys.executable, "-c", probe + "\n" + cmd_fcc_server()[-1]]+++def snapshot(server):+ return json.loads(server.log_path.read_text().splitlines()[0])+++def test_smoke_servers_isolate_runtime_and_share_original_auth(smoke_config):+ source = paths.config_dir_path()+ original = paths.managed_env_path().read_bytes()+ overrides = {"MODEL": "nvidia_nim/override"}+ unset = {"NVIDIA_NIM_API_KEY", "GROQ_API_KEY", "ANTHROPIC_AUTH_TOKEN"}+ with InterprocessFileLock(paths.server_owner_lock_path()):+ with start_server(+ smoke_config,+ command=probe_command(),+ env_overrides=overrides,+ env_unset=unset,+ ) as first:+ one = snapshot(first)+ with start_server(+ smoke_config,+ command=probe_command(),+ env_unset=unset,+ env_overrides={**overrides, "NVIDIA_NIM_API_KEY": "explicit-key"},+ ) as second:+ two = snapshot(second)+ assert one["config"] != two["config"] != str(source)+ assert one["database"] != two["database"]+ assert (+ one["owner"] != two["owner"] != str(paths.server_owner_lock_path())+ )+ assert one["keys"] == ["managed-one", "managed-two"]+ assert two["keys"] == ["explicit-key"]+ for state in (one, two):+ assert state["model"] == "nvidia_nim/override"+ assert state["token"] == "managed-proxy-token"+ assert state["removed"] is None+ assert state["groq"] == []+ assert state["auth"] == str(paths.openai_auth_path())+ assert state["auth_lock"] == str(paths.openai_auth_lock_path())+ assert state["copilot"] == str(paths.github_copilot_auth_path())+ assert state["home"] == str(source.parent)+ assert not Path(one["config"]).exists()+ assert not Path(two["config"]).exists()+ assert paths.managed_env_path().read_bytes() == original+ assert first.log_path.is_file() and second.log_path.is_file()+++def test_explicit_smoke_home_remains_authoritative(smoke_config, tmp_path):+ home = tmp_path / "caller-home"+ atomic_write_managed_config(+ {"FCC_CONFIG_SCHEMA": CONFIG_SCHEMA_VERSION, "ANTHROPIC_AUTH_TOKEN": "caller"},+ path=home / ".fcc" / ".env",+ )+ with start_server(+ smoke_config,+ command=probe_command(),+ env_overrides={"HOME": str(home), "USERPROFILE": str(home)},+ env_unset={"NVIDIA_NIM_API_KEY", "GROQ_API_KEY", "ANTHROPIC_AUTH_TOKEN"},+ ) as server:+ state = snapshot(server)+ assert state["config"] == str(home / ".fcc")+ assert state["keys"] == []+ assert state["token"] != "managed-proxy-token"+ assert state["auth"] == str(home / ".fcc" / "auth" / "openai.json")+ assert (home / ".fcc").is_dir()++[email protected]("failure", ["health", "spawn"])+def test_failed_smoke_start_cleans_private_state(smoke_config, monkeypatch, failure):+ from smoke.lib import server as smoke_server++ captured = {}+ command = ["custom-command", "--custom-arg"]++ def popen(args, **kwargs):+ assert args == command+ captured.update(kwargs["env"])+ if failure == "spawn":+ raise OSError("spawn failed")+ return object()++ def unhealthy(_server, **_kwargs):+ raise OSError("health failed")++ monkeypatch.setattr(smoke_server.subprocess, "Popen", popen)+ monkeypatch.setattr(smoke_server, "_wait_for_health", unhealthy)+ monkeypatch.setattr(smoke_server, "_stop_process", lambda _process: None)+ with (+ pytest.raises(OSError, match=f"{failure} failed"),+ start_server(replace(smoke_config, timeout_s=0.1), command=command),+ ):+ pytest.fail("startup should fail")+ assert not Path(captured["FCC_SMOKE_CONFIG_DIR"]).exists()