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
Keep managed configuration I/O off the server event loop (#1677)
Ali Khokharb19c3ee50b6d
diff --git a/e2e/conftest.py b/e2e/conftest.pyindex 2b278a24..aa3b45ce 100644--- a/e2e/conftest.py+++ b/e2e/conftest.py@@ -25,7 +25,11 @@ from free_claude_code.application.chat import (from free_claude_code.application.model_metadata import ProviderModelInfofrom free_claude_code.config import env_migrations, pathsfrom free_claude_code.config.env_migrations import recognized_env_keys-from free_claude_code.config.loader import clear_settings_cache, get_settings+from free_claude_code.config.loader import (+ ManagedConfigStore,+ clear_settings_cache,+ get_settings,+)from free_claude_code.core.anthropic.models import MessagesRequestfrom free_claude_code.core.anthropic.streaming import format_sse_eventfrom free_claude_code.core.openai_responses import OpenAIResponsesRequest@@ -35,6 +39,7 @@ from free_claude_code.providers.runtime import ProviderRuntimefrom free_claude_code.runtime.application import ApplicationRuntimefrom free_claude_code.runtime.asgi import RuntimeASGIAppfrom free_claude_code.runtime.chat_sqlite import SQLiteChatStore+from free_claude_code.runtime.configuration import ConfigurationServicefrom free_claude_code.runtime.provider_manager import ProviderRuntimeManager@@ -385,7 +390,12 @@ def admin_base_url(return resultmonkeypatch.setattr(chat_store, "begin_send", begin_send_with_delayed_ack)- runtime = ApplicationRuntime(manager, transcriber=None, chat_service=chat)+ runtime = ApplicationRuntime(+ manager,+ configuration=ConfigurationService(ManagedConfigStore()),+ transcriber=None,+ chat_service=chat,+ )app = RuntimeASGIApp(create_app(ApiServices(diff --git a/pyproject.toml b/pyproject.tomlindex cdf9ff1f..950ec823 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "free-claude-code"-version = "5.22.4"+version = "5.22.5"description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"readme = "README.md"requires-python = ">=3.14.0"diff --git a/src/free_claude_code/api/admin_routes.py b/src/free_claude_code/api/admin_routes.pyindex d0efb3c1..07ad3924 100644--- a/src/free_claude_code/api/admin_routes.py+++ b/src/free_claude_code/api/admin_routes.py@@ -7,7 +7,6 @@ from pathlib import Pathimport httpxfrom fastapi import (APIRouter,- BackgroundTasks,Depends,HTTPException,Request,@@ -22,7 +21,6 @@ from free_claude_code.application.connected_accounts import ()from free_claude_code.application.model_metadata import ProviderModelRefreshResultfrom free_claude_code.config.admin.manifest import FIELD_BY_KEY-from free_claude_code.config.admin.values import load_config_response, load_value_statefrom free_claude_code.config.model_refs import configured_chat_model_refsfrom free_claude_code.config.provider_catalog import (PROVIDER_CATALOG,@@ -106,23 +104,21 @@ async def admin_asset(version: str, filename: str, request: Request):@router.get("/admin/api/config")-async def get_admin_config(request: Request):+async def get_admin_config(+ request: Request, services: ApiServices = Depends(get_services)+):require_loopback_admin(request)- return load_config_response()+ return await services.admin.admin_config()@router.post("/admin/api/config/apply")async def apply_admin_config(payload: AdminConfigPayload,request: Request,- background_tasks: BackgroundTasks,services: ApiServices = Depends(get_services),):require_loopback_admin(request)result = await services.admin.apply_admin_config(_filtered_values(payload.values))- restart = result.get("restart")- if isinstance(restart, dict) and restart.get("automatic"):- background_tasks.add_task(services.admin.request_restart)return result@@ -138,13 +134,18 @@ async def admin_status(if origin := request.headers.get("origin"):response.headers["Access-Control-Allow-Origin"] = originresponse.headers["Vary"] = "Origin"- return services.admin.admin_status()+ return await services.admin.admin_status()@router.get("/admin/api/providers/local-status")-async def local_provider_status(request: Request):+async def local_provider_status(+ request: Request, services: ApiServices = Depends(get_services)+):require_loopback_admin(request)- values = {key: entry.value or "" for key, entry in load_value_state().items()}+ values = {+ key: entry.value or ""+ for key, entry in (await services.admin.admin_values()).items()+ }checks = await asyncio.gather(*(_check_local_provider(diff --git a/src/free_claude_code/api/ports.py b/src/free_claude_code/api/ports.pyindex ba48164d..7c45a37e 100644--- a/src/free_claude_code/api/ports.py+++ b/src/free_claude_code/api/ports.py@@ -11,7 +11,7 @@ from free_claude_code.application.connected_accounts import ()from free_claude_code.application.model_metadata import ProviderModelRefreshResultfrom free_claude_code.application.ports import RequestRuntimePort, TaskController-from free_claude_code.config.admin.state import ConfigInputValue+from free_claude_code.config.admin.state import ConfigInputValue, ValueStatefrom free_claude_code.core.json_types import JsonObject@@ -22,14 +22,16 @@ class AdminRuntimePort(Protocol):self, updates: Mapping[str, ConfigInputValue]) -> JsonObject: ...- def admin_status(self) -> JsonObject: ...+ async def admin_config(self) -> JsonObject: ...++ async def admin_values(self) -> ValueState: ...++ async def admin_status(self) -> JsonObject: ...async def test_provider(self, provider_id: str) -> JsonObject: ...async def refresh_models(self) -> ProviderModelRefreshResult: ...- async def request_restart(self) -> None: ...-async def connected_account_status(self, provider_id: str) -> ConnectedAccountStatus: ...diff --git a/src/free_claude_code/cli/commands.py b/src/free_claude_code/cli/commands.pyindex 587e8d87..d2b4fe08 100644--- a/src/free_claude_code/cli/commands.py+++ b/src/free_claude_code/cli/commands.py@@ -13,9 +13,9 @@ from loguru import loggerfrom free_claude_code.cli.launchers.common import preflight_proxyfrom free_claude_code.cli.process_registry import kill_all_best_effortfrom free_claude_code.config.loader import (+ ManagedConfigStore,clear_settings_cache,get_settings,- repair_invalid_managed_provider_proxies,)from free_claude_code.config.paths import managed_env_pathfrom free_claude_code.config.server_urls import local_admin_url, local_proxy_root_url@@ -203,7 +203,7 @@ def load_server_settings() -> Settings:"""Return canonical settings after repairing invalid managed proxies."""settings = get_settings()- removed = repair_invalid_managed_provider_proxies()+ removed = ManagedConfigStore().repair_invalid_provider_proxies()if not removed:return settingsdiff --git a/src/free_claude_code/config/__init__.py b/src/free_claude_code/config/__init__.pyindex b670d90c..f2c4f291 100644--- a/src/free_claude_code/config/__init__.py+++ b/src/free_claude_code/config/__init__.py@@ -1,11 +1,10 @@"""Configuration management."""-from .loader import clear_settings_cache, get_settings, resolve_settings_snapshot+from .loader import clear_settings_cache, get_settingsfrom .settings import Settings__all__ = ["Settings","clear_settings_cache","get_settings",- "resolve_settings_snapshot",]diff --git a/src/free_claude_code/config/admin/persistence.py b/src/free_claude_code/config/admin/persistence.pyindex 8d4d1aee..7d5bb486 100644--- a/src/free_claude_code/config/admin/persistence.py+++ b/src/free_claude_code/config/admin/persistence.py@@ -6,21 +6,19 @@ from pathlib import Pathfrom free_claude_code.config.env_files import (FCC_CONFIG_SCHEMA_ENV,- dotenv_values_from_file,)from free_claude_code.config.env_migrations import (CONFIG_SCHEMA_VERSION,- atomic_write_managed_config,recognized_env_keys,render_managed_config,)+from free_claude_code.config.loader import ManagedConfigSnapshotfrom free_claude_code.config.model_refs import normalize_retired_model_settings-from free_claude_code.config.paths import managed_env_pathfrom free_claude_code.config.provider_proxies import invalid_provider_proxy_keysfrom free_claude_code.config.settings import Settingsfrom free_claude_code.core.json_types import JsonObject-from .manifest import FIELD_BY_KEY+from .manifest import FIELD_BY_KEY, FIELDSfrom .state import ConfigInputValuefrom .validation import settings_from_valuesfrom .values import MASKED_SECRET, is_locked_source, load_value_state, normalize_for_env@@ -77,12 +75,12 @@ class PreparedAdminUpdate:def target_values_with_updates(updates: Mapping[str, ConfigInputValue],+ snapshot: ManagedConfigSnapshot,) -> dict[str, str]:"""Return sparse managed state after applying valid partial-update semantics."""- state = load_value_state()- path = managed_env_path()- values = dotenv_values_from_file(path) if path.is_file() else {}+ state = load_value_state(snapshot)+ values = dict(snapshot.managed)known = recognized_env_keys()for key in tuple(values):if key in known and key != FCC_CONFIG_SCHEMA_ENV and not values[key].strip():@@ -107,54 +105,47 @@ def target_values_with_updates(return normalize_retired_model_settings(values, preserve_empty_overrides=False)-def changed_pending_fields(- updates: Mapping[str, ConfigInputValue],- *,- settings: Settings,-) -> list[str]:- """Return changed fields that require manual runtime action."""-- state = load_value_state()- pending: list[str] = []- for key, submitted in updates.items():- field = FIELD_BY_KEY.get(key)- if field is None or is_locked_source(state[key].source):- continue- if field.secret and (- submitted == MASKED_SECRET- or (isinstance(submitted, str) and not submitted.strip())- ):- continue- requires_restart = field.restart_required or field.session_sensitive- if not requires_restart:- requires_restart = _active_voice_credential(settings) == key- if not requires_restart:- continue- if normalize_for_env(submitted) == state[key].value:- continue- pending.append(key)- return pending+def pending_restart_fields(active: Settings, prospective: Settings) -> tuple[str, ...]:+ """Compare saved intent with the settings actually used by running resources."""+ voice_credentials = {+ _active_voice_credential(active),+ _active_voice_credential(prospective),+ }+ return tuple(+ field.key+ for field in FIELDS+ if field.settings_attr is not None+ and (+ field.restart_required+ or field.session_sensitive+ or field.key in voice_credentials+ )+ and getattr(active, field.settings_attr)+ != getattr(prospective, field.settings_attr)+ )def prepare_admin_update(updates: Mapping[str, ConfigInputValue],+ snapshot: ManagedConfigSnapshot,+ active_settings: Settings,) -> PreparedAdminUpdate:"""Validate an update and construct its prospective Settings snapshot."""update_errors = _update_protocol_errors(updates)- target_values = target_values_with_updates(updates)- settings, settings_errors = settings_from_values(target_values)+ target_values = target_values_with_updates(updates, snapshot)+ settings, settings_errors = settings_from_values(target_values, snapshot.process)errors = (*update_errors,*settings_errors,*_provider_proxy_errors(target_values),)pending_fields = (- tuple(changed_pending_fields(updates, settings=settings))+ pending_restart_fields(active_settings, settings)if settings is not None and not errorselse ())- state = load_value_state()+ state = load_value_state(snapshot)changed_keys = tuple(keyfor key, submitted in updates.items()@@ -171,20 +162,11 @@ def prepare_admin_update(settings=settings,errors=errors,pending_fields=pending_fields,- path=managed_env_path(),+ path=snapshot.path,changed_keys=changed_keys,)-def commit_prepared_admin_update(prepared: PreparedAdminUpdate) -> JsonObject:- """Atomically persist a previously validated Admin update."""-- if not prepared.valid:- raise ValueError("Cannot commit an invalid Admin update")- atomic_write_managed_config(prepared.target_values, path=prepared.path)- return prepared.applied_response()--def _update_protocol_errors(updates: Mapping[str, ConfigInputValue],) -> tuple[str, ...]:diff --git a/src/free_claude_code/config/admin/validation.py b/src/free_claude_code/config/admin/validation.pyindex 45716d71..db73d923 100644--- a/src/free_claude_code/config/admin/validation.py+++ b/src/free_claude_code/config/admin/validation.py@@ -8,20 +8,23 @@ from free_claude_code.config.loader import compose_settings_snapshotfrom free_claude_code.config.settings import Settings-def validate_values(values: Mapping[str, str]) -> tuple[bool, list[str]]:+def validate_values(+ values: Mapping[str, str], process: Mapping[str, str]+) -> tuple[bool, list[str]]:"""Validate proposed env values against the Settings model."""- settings, errors = settings_from_values(values)+ settings, errors = settings_from_values(values, process)return settings is not None, errorsdef settings_from_values(values: Mapping[str, str],+ process: Mapping[str, str],) -> tuple[Settings | None, list[str]]:"""Build the prospective Settings snapshot without reading dotenv files."""try:- return compose_settings_snapshot(values).settings, []+ return compose_settings_snapshot(values, process).settings, []except ValidationError as exc:return None, format_validation_errors(exc)diff --git a/src/free_claude_code/config/admin/values.py b/src/free_claude_code/config/admin/values.pyindex d60d7306..3069d448 100644--- a/src/free_claude_code/config/admin/values.py+++ b/src/free_claude_code/config/admin/values.py@@ -1,11 +1,8 @@"""Admin config value state and API response assembly."""-import osfrom enum import Enum-from free_claude_code.config.env_files import dotenv_values_from_file-from free_claude_code.config.loader import ConfigSource, resolve_settings_snapshot-from free_claude_code.config.paths import managed_env_path+from free_claude_code.config.loader import ConfigSource, ManagedConfigSnapshotfrom free_claude_code.core.json_types import JsonObjectfrom .manifest import FIELDS, SECTIONS@@ -44,19 +41,17 @@ def is_locked_source(source: str | ConfigSource) -> bool:return str(source) == ConfigSource.PROCESS.value-def load_value_state() -> ValueState:+def load_value_state(snapshot: ManagedConfigSnapshot) -> ValueState:"""Load effective Admin values from the canonical Settings resolver."""- snapshot = resolve_settings_snapshot()- managed_path = managed_env_path()- managed = dotenv_values_from_file(managed_path) if managed_path.is_file() else {}+ managed = snapshot.managedstate: ValueState = {}for field in FIELDS:if field.settings_attr is not None:value = normalize_for_env(getattr(snapshot.settings, field.settings_attr))source = snapshot.sources[field.settings_attr].value- elif field.key in os.environ:- value = os.environ[field.key].strip() or None+ elif field.key in snapshot.process:+ value = snapshot.process[field.key].strip() or Nonesource = ConfigSource.PROCESS.valueelif field.key in managed:value = managed[field.key].strip() or None@@ -68,10 +63,10 @@ def load_value_state() -> ValueState:return state-def load_config_response() -> JsonObject:+def load_config_response(snapshot: ManagedConfigSnapshot) -> JsonObject:"""Return manifest and current config values for the Admin UI."""- state = load_value_state()+ state = load_value_state(snapshot)fields: list[JsonObject] = []for field in FIELDS:entry = state[field.key]@@ -115,6 +110,6 @@ def load_config_response() -> JsonObject:for section in SECTIONS],"fields": fields,- "paths": {"managed": str(managed_env_path())},+ "paths": {"managed": str(snapshot.path)},"provider_status": provider_config_status(state),}diff --git a/src/free_claude_code/config/env_migrations.py b/src/free_claude_code/config/env_migrations.pyindex 896094cd..01fb0e6a 100644--- a/src/free_claude_code/config/env_migrations.py+++ b/src/free_claude_code/config/env_migrations.py@@ -2,6 +2,7 @@import osimport re+import uuidfrom collections.abc import Mappingfrom dataclasses import dataclassfrom pathlib import Path@@ -265,9 +266,9 @@ def atomic_write_managed_config(return renderedtarget.parent.mkdir(parents=True, exist_ok=True)- temp_path = target.with_name(f".{target.name}.{os.getpid()}.tmp")+ temp_path = target.with_name(f".{target.name}.{uuid.uuid4().hex}.tmp")try:- with temp_path.open("w", encoding="utf-8", newline="\n") as handle:+ with temp_path.open("x", encoding="utf-8", newline="\n") as handle:handle.write(rendered)handle.flush()os.fsync(handle.fileno())diff --git a/src/free_claude_code/config/loader.py b/src/free_claude_code/config/loader.pyindex 569bee6f..1833258d 100644--- a/src/free_claude_code/config/loader.py+++ b/src/free_claude_code/config/loader.py@@ -1,16 +1,23 @@"""Canonical managed-config loading, precedence, provenance, and caching."""import os-from collections.abc import Mapping+from collections.abc import Iterator, Mapping+from contextlib import contextmanagerfrom dataclasses import dataclassfrom enum import StrEnumfrom functools import lru_cache+from pathlib import Pathfrom types import MappingProxyTypefrom free_claude_code.core.interprocess_lock import InterprocessFileLock-from .env_files import ANTHROPIC_AUTH_TOKEN_ENV, dotenv_values_from_file+from .env_files import (+ ANTHROPIC_AUTH_TOKEN_ENV,+ FCC_CONFIG_SCHEMA_ENV,+ dotenv_values_from_file,+)from .env_migrations import (+ CONFIG_SCHEMA_VERSION,atomic_write_managed_config,consolidate_managed_config,settings_env_keys,@@ -37,70 +44,103 @@ class SettingsSnapshot:sources: Mapping[str, ConfigSource]-def resolve_settings_snapshot(- env: Mapping[str, str] | None = None,-) -> SettingsSnapshot:- """Resolve one uncached Settings snapshot from managed and process state."""+@dataclass(frozen=True, slots=True)+class ManagedConfigSnapshot:+ """One disk/environment capture and its validated effective settings."""- process = env if env is not None else os.environ- lock = InterprocessFileLock(config_lock_path())- if not lock.acquire(wait=True, timeout=10.0):- raise TimeoutError(- f"Could not acquire managed-config lock: {config_lock_path()}"- )- try:- consolidate_managed_config(process)- finally:- lock.release()-- managed_path = managed_env_path()- managed = dotenv_values_from_file(managed_path) if managed_path.is_file() else {}- return compose_settings_snapshot(managed, process)---def repair_invalid_managed_provider_proxies(- env: Mapping[str, str] | None = None,-) -> tuple[str, ...]:- """Atomically remove invalid managed proxies not owned by the process."""-- process = env if env is not None else os.environ- managed_path = managed_env_path()- if not managed_path.is_file():- return ()-- lock = InterprocessFileLock(config_lock_path())- if not lock.acquire(wait=True, timeout=10.0):- raise TimeoutError(- f"Could not acquire managed-config lock: {config_lock_path()}"- )- try:- if not managed_path.is_file():- return ()- managed = dotenv_values_from_file(managed_path)- removed = tuple(- key for key in invalid_provider_proxy_keys(managed) if key not in process+ settings: Settings+ sources: Mapping[str, ConfigSource]+ managed: Mapping[str, str]+ process: Mapping[str, str]+ path: Path+++class ManagedConfigStore:+ """Own initialization and coordinate fresh reads with atomic writes."""++ def __init__(self) -> None:+ self.path = managed_env_path()+ self._lock_path = config_lock_path()++ @contextmanager+ def _storage_lock(self) -> Iterator[None]:+ lock = InterprocessFileLock(self._lock_path)+ if not lock.acquire(wait=True, timeout=10.0):+ raise TimeoutError(+ f"Could not acquire managed-config lock: {self._lock_path}"+ )+ try:+ yield+ finally:+ lock.release()++ def initialize(self, env: Mapping[str, str] | None = None) -> None:+ with self._storage_lock():+ consolidate_managed_config(dict(os.environ if env is None else env))++ def _read_managed(self) -> dict[str, str]:+ if not self.path.is_file():+ raise ValueError(+ "Managed configuration is missing; initialize it before reading."+ )+ managed = dotenv_values_from_file(self.path)+ schema = managed.get(FCC_CONFIG_SCHEMA_ENV)+ if schema != CONFIG_SCHEMA_VERSION:+ raise ValueError(+ f"Managed config {self.path} uses unsupported schema {schema!r}; "+ f"initialize with a compatible FCC version (supports {CONFIG_SCHEMA_VERSION})."+ )+ return managed++ def read(self, env: Mapping[str, str] | None = None) -> ManagedConfigSnapshot:+ process = dict(os.environ if env is None else env)+ # Windows readers deny replacement while their file handles remain open.+ with self._storage_lock():+ managed = self._read_managed()+ snapshot = compose_settings_snapshot(managed, process)+ return ManagedConfigSnapshot(+ snapshot.settings,+ snapshot.sources,+ MappingProxyType(managed),+ MappingProxyType(process),+ self.path,)- if not removed:- return ()- repaired = dict(managed)- for key in removed:- repaired.pop(key)- atomic_write_managed_config(repaired, path=managed_path)- return removed- finally:- lock.release()+ def commit(self, values: Mapping[str, str]) -> None:+ with self._storage_lock():+ self._read_managed() # Never overwrite a newer schema or missing storage.+ atomic_write_managed_config(values, path=self.path)++ def repair_invalid_provider_proxies(+ self,+ env: Mapping[str, str] | None = None,+ ) -> tuple[str, ...]:+ process = dict(os.environ if env is None else env)+ if not self.path.is_file():+ return ()+ with self._storage_lock():+ if not self.path.is_file():+ return ()+ managed = self._read_managed()+ removed = tuple(+ key+ for key in invalid_provider_proxy_keys(managed)+ if key not in process+ )+ if removed:+ for key in removed:+ managed.pop(key)+ atomic_write_managed_config(managed, path=self.path)+ return removeddef compose_settings_snapshot(managed: Mapping[str, str],- env: Mapping[str, str] | None = None,+ env: Mapping[str, str],) -> SettingsSnapshot:"""Validate prospective managed values with live process precedence."""- process = normalize_retired_model_settings(- env if env is not None else os.environ, preserve_empty_overrides=True- )+ process = normalize_retired_model_settings(env, preserve_empty_overrides=True)managed = normalize_retired_model_settings(managed, preserve_empty_overrides=False)aliases = _settings_aliases()recognized = settings_env_keys()@@ -138,7 +178,9 @@ def compose_settings_snapshot(def get_settings() -> Settings:"""Return the process-wide cached settings model."""- return resolve_settings_snapshot().settings+ store = ManagedConfigStore()+ store.initialize()+ return store.read().settingsdef clear_settings_cache() -> None:diff --git a/src/free_claude_code/runtime/application.py b/src/free_claude_code/runtime/application.pyindex 64d5a827..b4ff500d 100644--- a/src/free_claude_code/runtime/application.py+++ b/src/free_claude_code/runtime/application.py@@ -25,12 +25,9 @@ from free_claude_code.application.model_metadata import ProviderModelRefreshResufrom free_claude_code.application.ports import StopResultfrom free_claude_code.config.admin.persistence import (PreparedAdminUpdate,- commit_prepared_admin_update,- prepare_admin_update,)-from free_claude_code.config.admin.state import ConfigInputValue+from free_claude_code.config.admin.state import ConfigInputValue, ValueStatefrom free_claude_code.config.admin.status import provider_config_status-from free_claude_code.config.admin.values import load_value_statefrom free_claude_code.config.loader import clear_settings_cachefrom free_claude_code.config.model_refs import parse_provider_typefrom free_claude_code.config.paths import messaging_state_dir_path@@ -49,9 +46,10 @@ from free_claude_code.providers.credential_validation import (check_credentials,)+from .configuration import ConfigurationServicefrom .provider_manager import ProviderRuntimeManager-RestartCallback = Callable[[], Awaitable[None] | None]+RestartCallback = Callable[[], None]_PROVIDER_CHECK_FAILURE_MESSAGE = ("Could not refresh this provider's models. Verify its configuration and access."@@ -100,6 +98,38 @@ def startup_failure_message(settings: Settings, exc: Exception) -> str:return f"Server startup failed: exc_type={type(exc).__name__}"+async def _await_owned_task[T](+ task: asyncio.Task[T],+ *,+ cancel_on_interrupt: Callable[[], bool] | None = None,+) -> T:+ """Keep ownership until a task settles, then propagate caller cancellation."""+ cancellation: asyncio.CancelledError | None = None+ while not task.done():+ try:+ # wait never cancels the owned task or logs its exception on interruption.+ await asyncio.wait({task})+ except asyncio.CancelledError as exc:+ if cancellation is None:+ cancellation = exc+ if cancel_on_interrupt is not None and cancel_on_interrupt():+ task.cancel()+ try:+ result = task.result()+ except BaseException as exc:+ if cancellation is not None:+ if not isinstance(exc, asyncio.CancelledError):+ logger.warning(+ "Cancelled runtime operation failed: exc_type={}",+ type(exc).__name__,+ )+ raise cancellation from exc+ raise+ if cancellation is not None:+ raise cancellation+ return result++class ApplicationRuntime:"""Own every process-lifetime resource used by one server instance."""@@ -107,12 +137,14 @@ class ApplicationRuntime:self,provider_manager: ProviderRuntimeManager,*,+ configuration: ConfigurationService,transcriber: Transcriber | None,chat_service: ChatService | None = None,restart_callback: RestartCallback | None = None,connected_accounts: Mapping[str, ConnectedAccountPort] | None = None,) -> None:self.provider_manager = provider_manager+ self._configuration = configurationself._chat_service = chat_serviceself._transcriber = transcriberself._restart_callback = restart_callback@@ -134,7 +166,7 @@ class ApplicationRuntime:self._closed = Falseself._provider_manager_closed = Falseself._connected_accounts_closed = False- self._close_lock = asyncio.Lock()+ self._lifecycle_lock = asyncio.Lock()@propertydef settings(self) -> Settings:@@ -146,27 +178,42 @@ class ApplicationRuntime:return self._closedasync def start(self) -> None:- if self._started:- return- logger.info("Starting Claude Code Proxy...")try:- await self.provider_manager.warm_referenced_model_cache()- self.provider_manager.start_model_list_refresh()- if self._chat_service is not None:- await self._chat_service.start()- await self._start_messaging_if_configured()- logging.getLogger("uvicorn.error").info(- "Admin UI: %s (local-only)",- local_admin_url(self.settings),- )- self._started = True+ async with self._lifecycle_lock:+ if self._draining:+ raise ApplicationUnavailableError(+ "Application runtime is shutting down."+ )+ if self._started:+ return+ logger.info("Starting Claude Code Proxy...")+ await _await_owned_task(+ asyncio.create_task(self._configuration.initialize())+ )+ if self._draining:+ raise ApplicationUnavailableError(+ "Application runtime is shutting down."+ )+ await self.provider_manager.warm_referenced_model_cache()+ self.provider_manager.start_model_list_refresh()+ if self._chat_service is not None:+ await self._chat_service.start()+ await self._start_messaging_if_configured()+ if self._draining:+ raise ApplicationUnavailableError(+ "Application runtime is shutting down."+ )+ logging.getLogger("uvicorn.error").info(+ "Admin UI: %s (local-only)",+ local_admin_url(self.settings),+ )+ self._started = Trueexcept asyncio.CancelledError:await self.close()raiseexcept Exception as exc:logger.error(- "Startup failed:\n{}",- startup_failure_message(self.settings, exc),+ "Startup failed:\n{}", startup_failure_message(self.settings, exc))await self.close()raise@@ -178,11 +225,13 @@ class ApplicationRuntime:self._chat_service.begin_shutdown()async def close(self) -> bool:- async with self._close_lock:+ self.begin_shutdown()+ async with self._lifecycle_lock:if self._closed:return Truelogger.info("Shutdown requested, cleaning up...")- self._closed = await self._close_owned_resources()+ async with self._config_lock:+ self._closed = await self._close_owned_resources()if self._closed:self._started = Falselogger.info("Server shut down cleanly")@@ -197,8 +246,15 @@ class ApplicationRuntime:updates: Mapping[str, ConfigInputValue],) -> JsonObject:"""Apply one validated config update without splitting runtime ownership."""+ caller = asyncio.current_task()+ assert caller is not None+ initial_cancellations = caller.cancelling()async with self._config_lock:- prepared = prepare_admin_update(updates)+ if self._draining:+ raise ApplicationUnavailableError(+ "Configuration runtime is shutting down."+ )+ prepared = await self._configuration.prepare(updates, self.settings)if not prepared.valid:return prepared.applied_response() | {"credential_checks": []}assert prepared.settings is not None@@ -224,35 +280,64 @@ class ApplicationRuntime:"credential_checks": check_response,}- if prepared.pending_fields:- result = self._commit_admin_update(prepared)- result["credential_checks"] = check_response- restart = self._restart_metadata(- prepared.pending_fields,- prepared.settings,- )- result["restart"] = restart- self._pending_fields = (- [] if restart["automatic"] else list(prepared.pending_fields)- )- return result+ persistence_started = False++ async def commit() -> JsonObject:+ nonlocal persistence_started+ # The caller's cancellation wakeup may run after finalization starts.+ if caller.cancelling() > initial_cancellations:+ raise asyncio.CancelledError+ persistence_started = True+ return await self._commit_admin_update(prepared)+ finalization = asyncio.create_task(+ self._finalize_admin_update(prepared, check_response, commit)+ )+ return await _await_owned_task(+ finalization,+ cancel_on_interrupt=lambda: not persistence_started,+ )++ async def _finalize_admin_update(+ self,+ prepared: PreparedAdminUpdate,+ check_response: list[JsonObject],+ commit: Callable[[], Awaitable[JsonObject]],+ ) -> JsonObject:+ assert prepared.settings is not None+ if prepared.pending_fields:+ result = await commit()+ else:result: JsonObject = {}- def commit() -> None:- result.update(self._commit_admin_update(prepared))+ async def publish_commit() -> None:+ result.update(await commit())await self.provider_manager.replace(prepared.settings,- commit=commit,+ commit=publish_commit,reason="admin_apply",)+ self._pending_fields = list(prepared.pending_fields)+ automatic = bool(prepared.pending_fields and self._signal_restart())+ if automatic:self._pending_fields = []- result["restart"] = self._restart_metadata((), prepared.settings)- result["credential_checks"] = check_response- return result+ result["restart"] = self._restart_metadata(+ prepared.pending_fields,+ prepared.settings,+ automatic=automatic,+ )+ result["credential_checks"] = check_response+ return result++ async def admin_config(self) -> JsonObject:+ return await self._configuration.admin_config()- def admin_status(self) -> JsonObject:+ async def admin_values(self) -> ValueState:+ return await self._configuration.admin_values()++ async def admin_status(self) -> JsonObject:+ values = await self.admin_values()settings = self.settingsreturn {"status": "stopping" if self._draining else "running",@@ -262,7 +347,7 @@ class ApplicationRuntime:"model": settings.model,"provider": parse_provider_type(settings.model),"pending_fields": list(self._pending_fields),- "provider_status": provider_config_status(load_value_state()),+ "provider_status": provider_config_status(values),"cached_models": {provider_id: sorted(model_ids)for provider_id, model_ids in self.provider_manager.cached_model_ids().items()@@ -341,13 +426,28 @@ class ApplicationRuntime:self._connected_account_revisions[provider_id] = status.revisionreturn status- async def request_restart(self) -> None:+ def _signal_restart(self) -> bool:+ """Invoke a synchronous signal; failure leaves the saved change pending."""callback = self._restart_callbackif callback is None:- return- result = callback()- if inspect.isawaitable(result):- await result+ return False+ try:+ result = callback()+ # Enforce the contract for dynamically supplied callbacks as well.+ # Never execute an async callback that could await runtime.close().+ if inspect.iscoroutine(result):+ result.close()+ if result is not None:+ raise TypeError(+ "Restart callback must signal synchronously and return None."+ )+ except Exception as exc:+ logger.warning(+ "Config saved but restart signal failed: exc_type={}",+ type(exc).__name__,+ )+ return False+ return Trueasync def stop_all(self) -> StopResult | None:if self._messaging_workflow is not None:@@ -358,11 +458,11 @@ class ApplicationRuntime:return StopResult(source="cli_manager")return None- def _commit_admin_update(+ async def _commit_admin_update(self,prepared: PreparedAdminUpdate,) -> JsonObject:- result = commit_prepared_admin_update(prepared)+ result = await self._configuration.commit(prepared)clear_settings_cache()return result@@ -370,8 +470,9 @@ class ApplicationRuntime:self,fields: tuple[str, ...],settings: Settings,+ *,+ automatic: bool,) -> JsonObject:- automatic = bool(fields and self._restart_callback is not None)result: JsonObject = {"required": bool(fields),"automatic": automatic,diff --git a/src/free_claude_code/runtime/bootstrap.py b/src/free_claude_code/runtime/bootstrap.pyindex ed970b6a..53ef508f 100644--- a/src/free_claude_code/runtime/bootstrap.py+++ b/src/free_claude_code/runtime/bootstrap.py@@ -7,6 +7,7 @@ from pathlib import Pathfrom free_claude_code.api.app import create_appfrom free_claude_code.api.ports import ApiServicesfrom free_claude_code.application.chat import ChatService+from free_claude_code.config.loader import ManagedConfigStorefrom free_claude_code.config.logging_config import configure_loggingfrom free_claude_code.config.paths import (chat_database_path,@@ -32,6 +33,7 @@ from .application import ApplicationRuntime, RestartCallbackfrom .asgi import RuntimeASGIAppfrom .chat_sqlite import SQLiteChatStorefrom .codex_catalog import CodexModelCatalogPublisher+from .configuration import ConfigurationServicefrom .provider_manager import ProviderRuntimeManager@@ -76,6 +78,7 @@ def build_asgi_app()runtime = ApplicationRuntime(provider_manager,+ configuration=ConfigurationService(ManagedConfigStore()),chat_service=chat_service,transcriber=_create_transcriber(settings),restart_callback=restart_callback,diff --git a/src/free_claude_code/runtime/configuration.py b/src/free_claude_code/runtime/configuration.pynew file mode 100644index 00000000..e0198e2f--- /dev/null+++ b/src/free_claude_code/runtime/configuration.py@@ -0,0 +1,53 @@+"""Worker boundary for managed configuration; runtime state stays on the loop."""++from collections.abc import Mapping++from anyio import CapacityLimiter, to_thread++from free_claude_code.config.admin.persistence import (+ PreparedAdminUpdate,+ prepare_admin_update,+)+from free_claude_code.config.admin.state import ConfigInputValue, ValueState+from free_claude_code.config.admin.values import load_config_response, load_value_state+from free_claude_code.config.loader import ManagedConfigStore+from free_claude_code.config.settings import Settings+from free_claude_code.core.json_types import JsonObject+++class ConfigurationService:+ def __init__(self, store: ManagedConfigStore) -> None:+ self._store = store+ # Storage is serialized; its waiters must not exhaust FastAPI's worker pool.+ self._worker_limiter = CapacityLimiter(1)++ async def initialize(self) -> None:+ await to_thread.run_sync(self._store.initialize, limiter=self._worker_limiter)++ async def admin_config(self) -> JsonObject:+ snapshot = await to_thread.run_sync(+ self._store.read, limiter=self._worker_limiter+ )+ return load_config_response(snapshot)++ async def admin_values(self) -> ValueState:+ snapshot = await to_thread.run_sync(+ self._store.read, limiter=self._worker_limiter+ )+ return load_value_state(snapshot)++ async def prepare(+ self, updates: Mapping[str, ConfigInputValue], active_settings: Settings+ ) -> PreparedAdminUpdate:+ snapshot = await to_thread.run_sync(+ self._store.read, limiter=self._worker_limiter+ )+ return prepare_admin_update(updates, snapshot, active_settings)++ async def commit(self, prepared: PreparedAdminUpdate) -> JsonObject:+ if not prepared.valid:+ raise ValueError("Cannot commit an invalid Admin update")+ await to_thread.run_sync(+ self._store.commit, prepared.target_values, limiter=self._worker_limiter+ )+ return prepared.applied_response()diff --git a/src/free_claude_code/runtime/provider_manager.py b/src/free_claude_code/runtime/provider_manager.pyindex 81248a56..4fb40f88 100644--- a/src/free_claude_code/runtime/provider_manager.py+++ b/src/free_claude_code/runtime/provider_manager.py@@ -1,7 +1,7 @@"""Single-owner provider generations and application model catalog."""import asyncio-from collections.abc import Callable, Iterable+from collections.abc import Awaitable, Callable, Iterablefrom dataclasses import dataclass, fieldfrom typing import Protocol@@ -25,7 +25,7 @@ from free_claude_code.providers.runtime.model_cache import ProviderModelCacheProviderRuntimeFactory = Callable[[Settings], ProviderRuntime]ConnectedProviderIds = Callable[[], tuple[str, ...]]-CommitConfig = Callable[[], None]+CommitConfig = Callable[[], Awaitable[None]]class ModelCatalogPublisher(Protocol):@@ -255,8 +255,8 @@ class ProviderRuntimeManager:candidate_runtime: ProviderRuntime | None = Nonetry:candidate_runtime = self._runtime_factory(settings)- commit()- except Exception as exc:+ await commit()+ except BaseException as exc:trace_event(stage="runtime",event="provider_generation.replace_failed",diff --git a/tests/api/support.py b/tests/api/support.pyindex 3b343ed5..60df99d3 100644--- a/tests/api/support.py+++ b/tests/api/support.py@@ -8,10 +8,12 @@ from free_claude_code.api.app import create_appfrom free_claude_code.api.ports import ApiServicesfrom free_claude_code.application.chat import ChatApplicationPortfrom free_claude_code.application.connected_accounts import ConnectedAccountPort+from free_claude_code.config.loader import ManagedConfigStorefrom free_claude_code.config.settings import Settingsfrom free_claude_code.providers.base import BaseProviderfrom free_claude_code.providers.runtime import ProviderRuntimefrom free_claude_code.runtime.application import ApplicationRuntime, RestartCallback+from free_claude_code.runtime.configuration import ConfigurationServicefrom free_claude_code.runtime.provider_manager import ProviderRuntimeManager@@ -24,7 +26,9 @@ def create_test_app(chat: ChatApplicationPort | None = None,) -> FastAPI:"""Build an API app with explicit in-memory runtime services."""- settings = settings or Settings()+ store = ManagedConfigStore()+ store.initialize() # API-only tests do not run the production ASGI lifespan.+ settings = settings or store.read().settingsconnected_accounts = dict(connected_accounts or {})def connected_provider_ids() -> tuple[str, ...]:@@ -50,6 +54,7 @@ def create_test_app()runtime = ApplicationRuntime(manager,+ configuration=ConfigurationService(store),transcriber=None,restart_callback=restart_callback,connected_accounts=connected_accounts,diff --git a/tests/api/test_admin.py b/tests/api/test_admin.pyindex 5477de11..7210be08 100644--- a/tests/api/test_admin.py+++ b/tests/api/test_admin.py@@ -309,7 +309,7 @@ def test_admin_unexpected_errors_are_never_cached(monkeypatch, tmp_path):)with patch(- "free_claude_code.api.admin_routes.load_config_response",+ "free_claude_code.runtime.configuration.ConfigurationService.admin_config",side_effect=RuntimeError("test error"),):response = client.get("/admin/api/config")@@ -1197,7 +1197,7 @@ def test_admin_apply_rejects_invalid_provider_proxy_without_side_effects(env_file.write_text("MODEL=open_router/test-model\n", encoding="utf-8")callbacks: list[str] = []- async def restart_callback() -> None:+ def restart_callback() -> None:callbacks.append("restart")app = create_test_app(restart_callback=restart_callback)@@ -1771,7 +1771,7 @@ def test_admin_apply_restart_required_reports_automatic_restart(monkeypatch, tmp_clear_process_config(monkeypatch)callbacks: list[str] = []- async def restart_callback() -> None:+ def restart_callback() -> None:callbacks.append("restart")app = create_test_app(restart_callback=restart_callback)@@ -1842,6 +1842,107 @@ def test_admin_apply_restart_required_reports_manual_fallback(monkeypatch, tmp_p}+def test_restart_signal_failure_reports_saved_config_and_manual_restart(+ monkeypatch, tmp_path, caplog+):+ _set_home(monkeypatch, tmp_path)+ _clear_process_config(monkeypatch)++ def restart_callback() -> None:+ raise RuntimeError("private restart failure detail")++ app = create_test_app(restart_callback=restart_callback)+ client = _local_client(app)+ original_port = client.get("/admin/api/status").json()["port"]+ response = client.post("/admin/api/config/apply", json={"values": {"PORT": "9090"}})++ assert response.status_code == 200+ body = response.json()+ assert body["applied"] is True+ assert body["restart"] == {+ "required": True,+ "automatic": False,+ "admin_url": None,+ "fields": ["PORT"],+ }+ assert "PORT=9090" in (tmp_path / ".fcc" / ".env").read_text()+ status = client.get("/admin/api/status").json()+ assert status["port"] == original_port+ assert status["pending_fields"] == ["PORT"]+ assert "private restart failure detail" not in response.text + caplog.text+++ "followup",+ [{"PORT": "9090"}, {"MODEL": "nvidia_nim/new"}, {"LOG_LEVEL": "WARNING"}],+)[email protected]("signal_recovers", [False, True])+def test_pending_restart_survives_later_apply(+ monkeypatch, tmp_path, followup, signal_recovers+):+ from unittest.mock import MagicMock++ from free_claude_code.config.loader import ManagedConfigStore++ _set_home(monkeypatch, tmp_path)+ _clear_process_config(monkeypatch)+ store = ManagedConfigStore()+ store.initialize()+ settings = store.read().settings+ callback = MagicMock(+ side_effect=[+ RuntimeError("first signal failed"),+ None if signal_recovers else RuntimeError("still unavailable"),+ ]+ )+ app = create_test_app(settings, restart_callback=callback)+ client = _local_client(app)+ assert client.post(+ "/admin/api/config/apply", json={"values": {"PORT": "9090"}}+ ).json()["restart"]["required"]+ result = client.post("/admin/api/config/apply", json={"values": followup}).json()+ fields = ["PORT", "LOG_LEVEL"] if "LOG_LEVEL" in followup else ["PORT"]+ assert result["applied"] is True+ assert result["restart"]["required"] is True+ assert result["restart"]["automatic"] is signal_recovers+ assert result["restart"]["fields"] == fields+ assert callback.call_count == 2+ status = client.get("/admin/api/status").json()+ assert status["port"] == settings.port+ assert status["pending_fields"] == ([] if signal_recovers else fields)+ assert provider_manager_for_app(app).current_generation_id == 1+++def test_reverting_pending_restart_restores_hot_apply(monkeypatch, tmp_path):+ from unittest.mock import MagicMock++ from free_claude_code.config.loader import ManagedConfigStore++ _set_home(monkeypatch, tmp_path)+ _clear_process_config(monkeypatch)+ store = ManagedConfigStore()+ store.initialize()+ settings = store.read().settings+ callback = MagicMock(side_effect=RuntimeError("restart failed"))+ app = create_test_app(settings, restart_callback=callback)+ client = _local_client(app)+ client.post("/admin/api/config/apply", json={"values": {"PORT": "9090"}})+ with patch.object(+ provider_manager_for_app(app), "_refresh_generation_in_background", AsyncMock()+ ):+ result = client.post(+ "/admin/api/config/apply",+ json={"values": {"PORT": str(settings.port), "MODEL": "nvidia_nim/new"}},+ ).json()+ assert result["applied"] is True+ assert result["restart"]["required"] is False+ assert callback.call_count == 1+ status = client.get("/admin/api/status").json()+ assert status["pending_fields"] == []+ assert status["port"] == settings.port+ assert status["model"] == "nvidia_nim/new"++def test_admin_process_env_values_are_locked_and_not_written(monkeypatch, tmp_path):_set_home(monkeypatch, tmp_path)_clear_process_config(monkeypatch)diff --git a/tests/api/test_admin_configuration_io.py b/tests/api/test_admin_configuration_io.pynew file mode 100644index 00000000..52016cc7--- /dev/null+++ b/tests/api/test_admin_configuration_io.py@@ -0,0 +1,66 @@+import asyncio+import threading+from unittest.mock import AsyncMock, patch++import httpx+import pytest+from anyio import to_thread++from free_claude_code.config.loader import ManagedConfigStore+from tests.api.support import create_test_app+++ "path", ["config", "status", "providers/local-status", "config/apply"]+)+async def test_admin_storage_wait_allows_health_and_authenticated_requests(path):+ app = create_test_app()+ entered, release = threading.Event(), threading.Event()+ read = ManagedConfigStore.read+ worker_limiter = to_thread.current_default_thread_limiter()+ original_tokens = worker_limiter.total_tokens++ def blocked_read(store, *args):+ entered.set()+ assert release.wait(5), "Admin blocked the event loop"+ return read(store, *args)++ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app, client=("127.0.0.1", 50000)),+ base_url="http://127.0.0.1",+ ) as client:++ async def health_during_read():+ while not entered.is_set():+ await asyncio.sleep(0)+ try:+ assert (await client.get("/health")).status_code == 200+ response = await asyncio.wait_for(client.get("/"), timeout=1)+ assert response.status_code == 200+ finally:+ release.set()++ observer = asyncio.create_task(health_during_read())+ try:+ # Model the last shared worker being occupied by configuration I/O.+ worker_limiter.total_tokens = 1+ with (+ patch.object(ManagedConfigStore, "read", blocked_read),+ patch(+ "free_claude_code.api.admin_routes._check_local_provider",+ AsyncMock(return_value={}),+ ),+ ):+ if path == "config/apply":+ response = await client.post(+ f"/admin/api/{path}", json={"values": {"PORT": None}}+ )+ else:+ response = await client.get(f"/admin/api/{path}")+ assert response.status_code == 200+ await asyncio.wait_for(observer, 5)+ finally:+ release.set()+ observer.cancel()+ worker_limiter.total_tokens = original_tokensdiff --git a/tests/api/test_api.py b/tests/api/test_api.pyindex 8dce6fa6..b4be0ebc 100644--- a/tests/api/test_api.py+++ b/tests/api/test_api.py@@ -4,6 +4,7 @@ import pytestfrom fastapi.testclient import TestClientfrom free_claude_code.config.constants import DEFAULT_MODEL+from free_claude_code.config.settings import Settingsfrom free_claude_code.core.anthropic import ReasoningReplayModefrom free_claude_code.core.failures import ExecutionFailure, FailureKindfrom free_claude_code.core.reasoning import ReasoningPolicy@@ -41,7 +42,10 @@ def test_retired_model_ingress_calls_default_provider(client, stream, prefix):assert kwargs["reasoning"] == ReasoningPolicy.off()-app = create_test_app()+def app():+ return create_test_app(Settings())+# Mock providermock_provider = MagicMock(spec=NvidiaNimProvider)@@ -89,8 +93,8 @@ def _terminal_json_error(response, *, status_code: int):mock_provider.stream_messages = _mock_stream_messages[email protected](scope="module")-def client():+def client(app):"""HTTP client with provider resolution stubbed; patch only for this file."""with (patch(@@ -536,7 +540,7 @@ def test_count_tokens_endpoint(client: TestClient):assert response.headers["request-id"].startswith("req_")-def test_stop_endpoint_no_workflow_no_cli_503(client: TestClient):+def test_stop_endpoint_no_workflow_no_cli_503(app, client: TestClient):"""POST /stop without messaging workflow or cli_manager returns 503."""# Ensure no messaging workflow or cli_manager on app stateif hasattr(app.state, "messaging_workflow"):diff --git a/tests/api/test_app_lifespan_and_errors.py b/tests/api/test_app_lifespan_and_errors.pyindex 888f36ab..8aac3b75 100644--- a/tests/api/test_app_lifespan_and_errors.py+++ b/tests/api/test_app_lifespan_and_errors.py@@ -22,6 +22,7 @@ from free_claude_code.runtime.application import ()from free_claude_code.runtime.asgi import RuntimeASGIAppfrom free_claude_code.runtime.bootstrap import _create_transcriber, build_asgi_app+from free_claude_code.runtime.configuration import ConfigurationServicefrom free_claude_code.runtime.provider_manager import ProviderRuntimeManagerfrom tests.api.support import create_test_app@@ -45,7 +46,9 @@ async def test_runtime_startup_logs_admin_url_without_printed_server_banner():port=9099,)manager = ProviderRuntimeManager(settings)- runtime = ApplicationRuntime(manager, transcriber=None)+ runtime = ApplicationRuntime(+ manager, configuration=AsyncMock(spec=ConfigurationService), transcriber=None+ )uvicorn_logger = MagicMock()with (@@ -151,7 +154,9 @@ def test_general_exception_default_log_excludes_exception_message():async def test_runtime_startup_warms_catalog_before_background_refresh():settings = _settings(messaging_platform="none")manager = ProviderRuntimeManager(settings)- runtime = ApplicationRuntime(manager, transcriber=None)+ runtime = ApplicationRuntime(+ manager, configuration=AsyncMock(spec=ConfigurationService), transcriber=None+ )events: list[str] = []async def warm_cache() -> None:diff --git a/tests/api/test_auth.py b/tests/api/test_auth.pyindex 39c427d8..8e81cad4 100644--- a/tests/api/test_auth.py+++ b/tests/api/test_auth.py@@ -1,15 +1,19 @@from unittest.mock import AsyncMock, patch+import pytestfrom fastapi.testclient import TestClientfrom free_claude_code.api.dependencies import get_settingsfrom free_claude_code.config.settings import Settingsfrom tests.api.support import create_test_app-app = create_test_app()+def app():+ return create_test_app(Settings())-def test_anthropic_post_routes_accept_x_api_key():++def test_anthropic_post_routes_accept_x_api_key(app):client = TestClient(app)settings = Settings(proxy_auth_enabled=True, proxy_auth_token="s3cr3t")app.dependency_overrides[get_settings] = lambda: settings@@ -46,7 +50,7 @@ def test_anthropic_post_routes_accept_x_api_key():app.dependency_overrides.clear()-def test_anthropic_probe_routes_accept_x_api_key():+def test_anthropic_probe_routes_accept_x_api_key(app):client = TestClient(app)settings = Settings(proxy_auth_enabled=True, proxy_auth_token="probe-token")app.dependency_overrides[get_settings] = lambda: settings@@ -60,7 +64,7 @@ def test_anthropic_probe_routes_accept_x_api_key():app.dependency_overrides.clear()-def test_anthropic_routes_still_reject_anthropic_auth_token_only():+def test_anthropic_routes_still_reject_anthropic_auth_token_only(app):client = TestClient(app)settings = Settings(proxy_auth_enabled=True, proxy_auth_token="s3cr3t")app.dependency_overrides[get_settings] = lambda: settings@@ -73,7 +77,7 @@ def test_anthropic_routes_still_reject_anthropic_auth_token_only():app.dependency_overrides.clear()-def test_messages_auth_gives_authorization_precedence_over_x_api_key():+def test_messages_auth_gives_authorization_precedence_over_x_api_key(app):client = TestClient(app)settings = Settings(proxy_auth_enabled=True, proxy_auth_token="b3artoken")app.dependency_overrides[get_settings] = lambda: settings@@ -114,7 +118,7 @@ def test_messages_auth_gives_authorization_precedence_over_x_api_key():app.dependency_overrides.clear()-def test_x_api_key_remains_rejected_on_non_messages_routes():+def test_x_api_key_remains_rejected_on_non_messages_routes(app):client = TestClient(app)settings = Settings(proxy_auth_enabled=True, proxy_auth_token="route-token")app.dependency_overrides[get_settings] = lambda: settings@@ -130,7 +134,7 @@ def test_x_api_key_remains_rejected_on_non_messages_routes():app.dependency_overrides.clear()-def test_proxy_auth_token_normalizes_configured_whitespace():+def test_proxy_auth_token_normalizes_configured_whitespace(app):client = TestClient(app)settings = Settings(proxy_auth_enabled=True,@@ -155,7 +159,7 @@ def test_proxy_auth_token_normalizes_configured_whitespace():app.dependency_overrides.clear()-def test_proxy_auth_token_applies_to_model_catalog_endpoints():+def test_proxy_auth_token_applies_to_model_catalog_endpoints(app):client = TestClient(app)settings = Settings(proxy_auth_enabled=True, proxy_auth_token="models-token")app.dependency_overrides[get_settings] = lambda: settings@@ -173,7 +177,7 @@ def test_proxy_auth_token_applies_to_model_catalog_endpoints():app.dependency_overrides.clear()-def test_root_get_requires_auth_but_root_probes_are_public():+def test_root_get_requires_auth_but_root_probes_are_public(app):client = TestClient(app)settings = Settings(proxy_auth_enabled=True, proxy_auth_token="root-token")app.dependency_overrides[get_settings] = lambda: settingsdiff --git a/tests/api/test_openai_responses.py b/tests/api/test_openai_responses.pyindex e1811824..51e16c7d 100644--- a/tests/api/test_openai_responses.py+++ b/tests/api/test_openai_responses.py@@ -7,6 +7,7 @@ from fastapi.testclient import TestClientfrom free_claude_code.application.errors import InvalidRequestErrorfrom free_claude_code.config.constants import DEFAULT_MODEL+from free_claude_code.config.settings import Settingsfrom free_claude_code.core.anthropic import ReasoningReplayModefrom free_claude_code.core.anthropic.stream_contracts import parse_sse_textfrom free_claude_code.core.failures import ExecutionFailure, FailureKind@@ -72,7 +73,7 @@ class PreStartFailingProvider(FakeProvider):@pytest.fixturedef responses_client():provider = FakeProvider(_responses_text_stream("Hello from provider"))- app = create_test_app()+ app = create_test_app(Settings())with (patch("free_claude_code.api.routes.resolve_provider", return_value=provider),TestClient(app) as client,diff --git a/tests/api/test_routes_optimizations.py b/tests/api/test_routes_optimizations.pyindex b77127fb..38fe351a 100644--- a/tests/api/test_routes_optimizations.py+++ b/tests/api/test_routes_optimizations.py@@ -9,11 +9,14 @@ from free_claude_code.application.ports import StopResultfrom free_claude_code.config.settings import Settingsfrom tests.api.support import create_test_app-app = create_test_app()++def app():+ return create_test_app(Settings())@pytest.fixture-def client():+def client(app):return TestClient(app)@@ -26,7 +29,7 @@ def mock_settings():return settings-def test_create_message_fast_prefix_detection(client, mock_settings):+def test_create_message_fast_prefix_detection(app, client, mock_settings):app.dependency_overrides[get_settings] = lambda: mock_settingspayload = {@@ -54,7 +57,7 @@ def test_create_message_fast_prefix_detection(client, mock_settings):app.dependency_overrides.clear()-def test_create_message_quota_check_mock(client, mock_settings):+def test_create_message_quota_check_mock(app, client, mock_settings):app.dependency_overrides[get_settings] = lambda: mock_settingspayload = {@@ -75,7 +78,7 @@ def test_create_message_quota_check_mock(client, mock_settings):app.dependency_overrides.clear()-def test_create_message_title_generation_skip(client, mock_settings):+def test_create_message_title_generation_skip(app, client, mock_settings):app.dependency_overrides[get_settings] = lambda: mock_settingspayload = {@@ -179,7 +182,7 @@ def test_count_tokens_error_returns_500(client):assert "token error" in response.json()["detail"]-def test_stop_cli_with_messaging_workflow(client):+def test_stop_cli_with_messaging_workflow(app, client):session_control = MagicMock()session_control.stop_all = AsyncMock(return_value=StopResult(cancelled_count=3))services = app.state.services@@ -196,7 +199,7 @@ def test_stop_cli_with_messaging_workflow(client):session_control.stop_all.assert_awaited_once()-def test_stop_cli_fallback_to_manager(client):+def test_stop_cli_fallback_to_manager(app, client):session_control = MagicMock()session_control.stop_all = AsyncMock(return_value=StopResult(source="cli_manager"))services = app.state.servicesdiff --git a/tests/api/test_runtime_safe_logging.py b/tests/api/test_runtime_safe_logging.pyindex faa6ec89..d606b7bb 100644--- a/tests/api/test_runtime_safe_logging.py+++ b/tests/api/test_runtime_safe_logging.py@@ -1,12 +1,13 @@"""Safe default logging tests for the application runtime owner."""import logging-from unittest.mock import patch+from unittest.mock import AsyncMock, patchimport pytestfrom free_claude_code.config.settings import Settingsfrom free_claude_code.runtime.application import ApplicationRuntime, best_effort+from free_claude_code.runtime.configuration import ConfigurationServicefrom free_claude_code.runtime.provider_manager import ProviderRuntimeManager@@ -22,6 +23,7 @@ async def test_messaging_start_failure_default_logs_exclude_traceback(caplog):)runtime = ApplicationRuntime(ProviderRuntimeManager(settings),+ configuration=AsyncMock(spec=ConfigurationService),transcriber=None,)diff --git a/tests/cli/test_config_restart_lifecycle.py b/tests/cli/test_config_restart_lifecycle.pynew file mode 100644index 00000000..0b1f5857--- /dev/null+++ b/tests/cli/test_config_restart_lifecycle.py@@ -0,0 +1,131 @@+"""Real HTTP and supervisor coverage for runtime-owned Apply restarts."""++import socket+import threading+import time+from concurrent.futures import ThreadPoolExecutor+from unittest.mock import AsyncMock++import httpx+import pytest++from free_claude_code.api.app import create_app+from free_claude_code.api.ports import ApiServices+from free_claude_code.cli import commands+from free_claude_code.config.loader import ManagedConfigStore+from free_claude_code.providers.runtime import ProviderRuntime+from free_claude_code.runtime.application import ApplicationRuntime+from free_claude_code.runtime.asgi import RuntimeASGIApp+from free_claude_code.runtime.configuration import ConfigurationService+from free_claude_code.runtime.provider_manager import ProviderRuntimeManager++[email protected]("stop_during_commit", [False, True])+def test_supervised_http_apply_finishes_and_reconnects(monkeypatch, stop_during_commit):+ monkeypatch.setenv("HOST", "127.0.0.1")+ monkeypatch.delenv("PORT", raising=False)+ monkeypatch.delenv("LOG_LEVEL", raising=False)+ with socket.socket() as listener:+ listener.bind(("127.0.0.1", 0))+ port = listener.getsockname()[1]+ 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: ProviderRuntime(snapshot, {})+ )+ monkeypatch.setattr(manager, "warm_referenced_model_cache", AsyncMock())+ monkeypatch.setattr(manager, "start_model_list_refresh", lambda: None)+ monkeypatch.setattr(manager, "_refresh_generation_in_background", AsyncMock())+ runtime = ApplicationRuntime(+ manager,+ configuration=ConfigurationService(ManagedConfigStore()),+ transcriber=None,+ restart_callback=restart_callback,+ )+ runtimes.append(runtime)+ return RuntimeASGIApp(+ create_app(ApiServices(requests=manager, admin=runtime, tasks=runtime)),+ runtime,+ )++ monkeypatch.setattr(commands, "build_asgi_app", build)+ monkeypatch.setattr(commands, "kill_all_best_effort", lambda: None)+ supervisor = commands.ServerSupervisor(console_logging=False)+ errors = []++ def serve():+ try:+ supervisor.run(open_admin_browser=False)+ except BaseException as exc:+ errors.append(exc)++ thread = threading.Thread(target=serve, daemon=True)+ thread.start()+ entered, release = threading.Event(), threading.Event()+ commit = ManagedConfigStore.commit++ def blocked_commit(self, values):+ entered.set()+ assert release.wait(10)+ commit(self, values)++ def wait_status(client, old_id=None):+ deadline = time.monotonic() + 10+ while time.monotonic() < deadline:+ assert not errors+ try:+ response = client.get("/admin/api/status")+ if response.status_code == 200:+ status = response.json()+ if (+ status["status"] == "running"+ and status["instance_id"] != old_id+ ):+ return status+ except httpx.TransportError:+ pass+ time.sleep(0.02)+ pytest.fail("supervisor did not become ready")++ try:+ with httpx.Client(+ base_url=f"http://127.0.0.1:{port}", trust_env=False, timeout=5+ ) as client:+ before = wait_status(client)+ monkeypatch.setattr(ManagedConfigStore, "commit", blocked_commit)+ with ThreadPoolExecutor(max_workers=1) as executor:+ apply = executor.submit(+ client.post,+ "/admin/api/config/apply",+ json={"values": {"LOG_LEVEL": "WARNING"}},+ )+ try:+ assert entered.wait(5)+ if stop_during_commit:+ supervisor.request_stop()+ finally:+ release.set()+ response = apply.result(timeout=10)+ assert response.status_code == 200+ result = response.json()+ assert result["applied"]+ assert result["restart"]["automatic"]+ assert result["restart"]["instance_id"] == before["instance_id"]+ assert result["restart"]["admin_url"] == f"http://127.0.0.1:{port}/admin"+ if not stop_during_commit:+ after = wait_status(client, before["instance_id"])+ assert after["pending_fields"] == []+ assert len(runtimes) == 2+ assert runtimes[0].is_closed+ finally:+ release.set()+ supervisor.request_stop()+ thread.join(timeout=10)+ assert not thread.is_alive()+ assert not errors+ assert all(runtime.is_closed for runtime in runtimes)+ assert len(runtimes) == (1 if stop_during_commit else 2)diff --git a/tests/cli/test_entrypoints.py b/tests/cli/test_entrypoints.pyindex e3e9ae68..e889749e 100644--- a/tests/cli/test_entrypoints.py+++ b/tests/cli/test_entrypoints.py@@ -244,8 +244,8 @@ def test_load_server_settings_skips_reload_when_no_repair_occurs(caplog.at_level("WARNING"),patch.object(commands, "get_settings", return_value=settings) as get_settings,patch.object(- commands,- "repair_invalid_managed_provider_proxies",+ commands.ManagedConfigStore,+ "repair_invalid_provider_proxies",return_value=(),) as repair,patch.object(commands, "clear_settings_cache") as clear_cache,@@ -274,8 +274,8 @@ def test_load_server_settings_reloads_once_and_warns_after_repair(caplog.at_level("WARNING"),patch.object(commands, "get_settings", get_settings),patch.object(- commands,- "repair_invalid_managed_provider_proxies",+ commands.ManagedConfigStore,+ "repair_invalid_provider_proxies",return_value=("OPENAI_PROXY", "GROQ_PROXY"),),patch.object(commands, "clear_settings_cache") as clear_cache,diff --git a/tests/config/test_admin_credential_changes.py b/tests/config/test_admin_credential_changes.pyindex 3cbbe97d..136fc4f0 100644--- a/tests/config/test_admin_credential_changes.py+++ b/tests/config/test_admin_credential_changes.py@@ -1,25 +1,30 @@"""Only effective edits, against saved settings, request credential validation."""from free_claude_code.config.admin.persistence import (- commit_prepared_admin_update,prepare_admin_update,)from free_claude_code.config.admin.values import MASKED_SECRET+from free_claude_code.config.loader import ManagedConfigStoredef test_changed_keys_exclude_masks_noops_and_removals(monkeypatch):monkeypatch.delenv("GROQ_API_KEY", raising=False)- first = prepare_admin_update({"GROQ_API_KEY": " saved-key "})+ store = ManagedConfigStore()+ store.initialize()+ active = store.read().settings+ first = prepare_admin_update({"GROQ_API_KEY": " saved-key "}, store.read(), active)assert first.validassert first.changed_keys == ("GROQ_API_KEY",)- commit_prepared_admin_update(first)+ store.commit(first.target_values)# Compare to the saved value even if a running generation has not restarted.for value in ("saved-key", " saved-key ", MASKED_SECRET, "", " ", None):- prepared = prepare_admin_update({"GROQ_API_KEY": value})+ prepared = prepare_admin_update({"GROQ_API_KEY": value}, store.read(), active)assert prepared.validassert prepared.changed_keys == ()changed = prepare_admin_update(- {"GROQ_API_KEY": "new-key", "GROQ_PROXY": "http://localhost:8080"}+ {"GROQ_API_KEY": "new-key", "GROQ_PROXY": "http://localhost:8080"},+ store.read(),+ active,)assert "GROQ_API_KEY" in changed.changed_keysassert changed.settings is not None@@ -29,7 +34,12 @@ def test_changed_keys_exclude_masks_noops_and_removals(monkeypatch):def test_process_locked_key_is_not_a_change(monkeypatch):monkeypatch.setenv("GROQ_API_KEY", "process-key")- prepared = prepare_admin_update({"GROQ_API_KEY": "submitted-key"})+ store = ManagedConfigStore()+ store.initialize()+ active = store.read().settings+ prepared = prepare_admin_update(+ {"GROQ_API_KEY": "submitted-key"}, store.read(), active+ )assert prepared.validassert prepared.changed_keys == ()assert prepared.settings is not Nonediff --git a/tests/config/test_config.py b/tests/config/test_config.pyindex 196e630d..b13cd1c7 100644--- a/tests/config/test_config.py+++ b/tests/config/test_config.py@@ -17,10 +17,10 @@ from free_claude_code.config.constants import (from free_claude_code.config.env_files import dotenv_values_from_filefrom free_claude_code.config.loader import (ConfigSource,+ ManagedConfigStore,clear_settings_cache,compose_settings_snapshot,get_settings,- repair_invalid_managed_provider_proxies,)from free_claude_code.config.model_refs import (configured_chat_model_refs,@@ -81,7 +81,8 @@ def test_retirement_preserves_effective_default_order_and_process_environment("MODEL": "groq/default","MODEL_OPUS": "groq/managed-tier","MODEL_FALLBACKS": "groq/first, github_models/old, deepseek/last",- }+ },+ dict(loader.os.environ),)assert snapshot.settings.model == "groq/default"assert snapshot.settings.model_opus is None@@ -300,7 +301,7 @@ def test_repair_invalid_managed_provider_proxies_removes_all_eligible_values() -))- removed = repair_invalid_managed_provider_proxies({})+ removed = ManagedConfigStore().repair_invalid_provider_proxies({})values = dotenv_values_from_file(managed)assert removed == ("OPENROUTER_PROXY", "OPENAI_PROXY")@@ -320,14 +321,14 @@ def test_repair_valid_managed_provider_proxy_leaves_file_unchanged() -> None:)baseline = managed.read_bytes()- assert repair_invalid_managed_provider_proxies({}) == ()+ assert ManagedConfigStore().repair_invalid_provider_proxies({}) == ()assert managed.read_bytes() == baselinedef test_repair_without_managed_file_is_a_noop() -> None:managed = managed_env_path()- assert repair_invalid_managed_provider_proxies({}) == ()+ assert ManagedConfigStore().repair_invalid_provider_proxies({}) == ()assert not managed.exists()@@ -344,7 +345,9 @@ def test_repair_preserves_process_owned_managed_proxy(process = {"OPENAI_PROXY": process_value, "KEEP_PROCESS": "unchanged"}baseline_process = dict(process)- assert repair_invalid_managed_provider_proxies(process) == ("OPENROUTER_PROXY",)+ assert ManagedConfigStore().repair_invalid_provider_proxies(process) == (+ "OPENROUTER_PROXY",+ )values = dotenv_values_from_file(managed)assert values["OPENAI_PROXY"] == invalid_openai@@ -366,7 +369,7 @@ def test_repair_propagates_atomic_write_failure_without_changing_source() -> Non),pytest.raises(OSError, match="disk full"),):- repair_invalid_managed_provider_proxies({})+ ManagedConfigStore().repair_invalid_provider_proxies({})assert managed.read_bytes() == baseline@@ -381,9 +384,11 @@ def test_repair_is_idempotent_and_writes_only_once() -> None:"atomic_write_managed_config",wraps=loader.atomic_write_managed_config,) as writer:- assert repair_invalid_managed_provider_proxies({}) == ("OPENAI_PROXY",)+ assert ManagedConfigStore().repair_invalid_provider_proxies({}) == (+ "OPENAI_PROXY",+ )repaired = managed.read_bytes()- assert repair_invalid_managed_provider_proxies({}) == ()+ assert ManagedConfigStore().repair_invalid_provider_proxies({}) == ()assert writer.call_count == 1assert managed.read_bytes() == repaired@@ -394,7 +399,7 @@ def test_repair_propagates_malformed_managed_config() -> None:baseline = managed.read_bytes()with pytest.raises(ValueError, match="Could not parse configuration file"):- repair_invalid_managed_provider_proxies({})+ ManagedConfigStore().repair_invalid_provider_proxies({})assert managed.read_bytes() == baseline@@ -419,7 +424,7 @@ def test_repair_propagates_config_lock_timeout(monkeypatch.setattr(loader, "InterprocessFileLock", UnavailableLock)with pytest.raises(TimeoutError, match="Could not acquire managed-config lock"):- repair_invalid_managed_provider_proxies({})+ ManagedConfigStore().repair_invalid_provider_proxies({})assert managed.read_bytes() == baselinediff --git a/tests/config/test_env_migrations.py b/tests/config/test_env_migrations.pyindex 98c5bfc0..8330af21 100644--- a/tests/config/test_env_migrations.py+++ b/tests/config/test_env_migrations.py@@ -15,7 +15,7 @@ from free_claude_code.config.env_migrations import (consolidate_managed_config,migrate_env_setting_in_text,)-from free_claude_code.config.loader import resolve_settings_snapshot+from free_claude_code.config.loader import ManagedConfigStore@pytest.mark.parametrize("schema", ["", "FCC_CONFIG_SCHEMA=1\n"])@@ -376,10 +376,13 @@ def test_concurrent_loaders_produce_one_valid_managed_file(legacy.parent.mkdir(parents=True)legacy.write_text("MODEL=deepseek/concurrent\n", encoding="utf-8")+ def initialize_and_read(_index):+ store = ManagedConfigStore()+ store.initialize({})+ return store.read({})+with ThreadPoolExecutor(max_workers=8) as executor:- snapshots = list(- executor.map(lambda _index: resolve_settings_snapshot({}), range(8))- )+ snapshots = list(executor.map(initialize_and_read, range(8)))assert {snapshot.settings.model for snapshot in snapshots} == {"deepseek/concurrent"diff --git a/tests/contracts/test_admin_provider_manifest.py b/tests/contracts/test_admin_provider_manifest.pyindex c61df192..fc25a35e 100644--- a/tests/contracts/test_admin_provider_manifest.py+++ b/tests/contracts/test_admin_provider_manifest.py@@ -115,10 +115,13 @@ def test_openai_proxy_override_applies_to_catalog_proxy_field() -> None:def test_provider_catalog_display_names_are_admin_status_source() -> None:from free_claude_code.config.admin.status import provider_config_statusfrom free_claude_code.config.admin.values import load_value_state+ from free_claude_code.config.loader import ManagedConfigStore+ store = ManagedConfigStore()+ store.initialize()status_by_provider = {entry["provider_id"]: entry- for entry in provider_config_status(load_value_state())+ for entry in provider_config_status(load_value_state(store.read()))}assert set(status_by_provider) == set(PROVIDER_CATALOG)diff --git a/tests/contracts/test_import_boundaries.py b/tests/contracts/test_import_boundaries.pyindex 9b4bf9ff..ca0aea7b 100644--- a/tests/contracts/test_import_boundaries.py+++ b/tests/contracts/test_import_boundaries.py@@ -122,6 +122,23 @@ class _ImportVisitor(ast.NodeVisitor):)+def test_api_configuration_access_goes_through_runtime() -> None:+ storage_modules = {+ "free_claude_code.config.loader",+ "free_claude_code.config.env_files",+ "free_claude_code.config.env_migrations",+ }+ offenders = [+ record.describe()+ for record in _scan_imports(_PACKAGE_ROOT)+ if record.importer.startswith("free_claude_code.api.")+ and record.imported in storage_modules+ ]+ assert not offenders, (+ "API config I/O belongs behind the async runtime port:\n" + "\n".join(offenders)+ )++def test_package_dependencies_follow_declarative_policy() -> None:modules = _module_paths(_PACKAGE_ROOT)records = _scan_imports(_PACKAGE_ROOT)diff --git a/tests/runtime/test_application_runtime.py b/tests/runtime/test_application_runtime.pyindex ab3c09ba..51dea90f 100644--- a/tests/runtime/test_application_runtime.py+++ b/tests/runtime/test_application_runtime.py@@ -34,6 +34,7 @@ from free_claude_code.providers.credential_validation import ()from free_claude_code.providers.runtime import ProviderRuntimefrom free_claude_code.runtime.application import ApplicationRuntime+from free_claude_code.runtime.configuration import ConfigurationServicefrom free_claude_code.runtime.provider_manager import ProviderRuntimeManagerfrom tests.providers.support import make_provider_config@@ -252,7 +253,9 @@ def _runtime_with_admin_provider({"nvidia_nim": provider},),)- return ApplicationRuntime(manager, transcriber=None), manager+ return ApplicationRuntime(+ manager, configuration=AsyncMock(spec=ConfigurationService), transcriber=None+ ), manager@pytest.mark.asyncio@@ -335,7 +338,9 @@ async def test_provider_check_never_returns_unrecognized_credentials(@pytest.mark.asyncioasync def test_stop_all_maps_messaging_outcome_to_application_count() -> None:manager = ProviderRuntimeManager(_settings("nvidia_nim/model"))- runtime = ApplicationRuntime(manager, transcriber=None)+ runtime = ApplicationRuntime(+ manager, configuration=AsyncMock(spec=ConfigurationService), transcriber=None+ )workflow = MagicMock()workflow.stop_all_tasks = AsyncMock(return_value=StopOutcome(@@ -361,7 +366,9 @@ async def test_provider_apply_constructs_before_commit_then_publishes(tmp_path)_settings("nvidia_nim/old"),runtime_factory=factory,)- runtime = ApplicationRuntime(manager, transcriber=None)+ runtime = ApplicationRuntime(+ manager, configuration=AsyncMock(spec=ConfigurationService), transcriber=None+ )prepared = _prepared(_settings("nvidia_nim/new"), tmp_path)factory.events.clear()@@ -371,12 +378,14 @@ async def test_provider_apply_constructs_before_commit_then_publishes(tmp_path)return _applied_response()with (- patch(- "free_claude_code.runtime.application.prepare_admin_update",+ patch.object(+ runtime._configuration,+ "prepare",return_value=prepared,),- patch(- "free_claude_code.runtime.application.commit_prepared_admin_update",+ patch.object(+ runtime._configuration,+ "commit",side_effect=commit,),):@@ -401,18 +410,19 @@ async def test_candidate_failure_never_commits_and_preserves_current(tmp_path) -_settings("nvidia_nim/old"),runtime_factory=factory,)- runtime = ApplicationRuntime(manager, transcriber=None)+ runtime = ApplicationRuntime(+ manager, configuration=AsyncMock(spec=ConfigurationService), transcriber=None+ )prepared = _prepared(_settings("nvidia_nim/new"), tmp_path)factory.fail = Truewith (- patch(- "free_claude_code.runtime.application.prepare_admin_update",+ patch.object(+ runtime._configuration,+ "prepare",return_value=prepared,),- patch(- "free_claude_code.runtime.application.commit_prepared_admin_update"- ) as commit,+ patch.object(runtime._configuration, "commit") as commit,pytest.raises(RuntimeError, match="candidate failed"),):await runtime.apply_admin_config({"MODEL": "nvidia_nim/new"})@@ -432,16 +442,20 @@ async def test_persistence_failure_closes_candidate_and_preserves_current(_settings("nvidia_nim/old"),runtime_factory=factory,)- runtime = ApplicationRuntime(manager, transcriber=None)+ runtime = ApplicationRuntime(+ manager, configuration=AsyncMock(spec=ConfigurationService), transcriber=None+ )prepared = _prepared(_settings("nvidia_nim/new"), tmp_path)with (- patch(- "free_claude_code.runtime.application.prepare_admin_update",+ patch.object(+ runtime._configuration,+ "prepare",return_value=prepared,),- patch(- "free_claude_code.runtime.application.commit_prepared_admin_update",+ patch.object(+ runtime._configuration,+ "commit",side_effect=OSError("disk full"),),pytest.raises(OSError, match="disk full"),@@ -461,9 +475,10 @@ async def test_restart_required_apply_commits_without_hot_publication(tmp_path)_settings("nvidia_nim/old"),runtime_factory=factory,)- restart = AsyncMock()+ restart = MagicMock(return_value=None)runtime = ApplicationRuntime(manager,+ configuration=AsyncMock(spec=ConfigurationService),transcriber=None,restart_callback=restart,)@@ -472,15 +487,20 @@ async def test_restart_required_apply_commits_without_hot_publication(tmp_path)tmp_path,pending_fields=("PORT",),)- instance_id = runtime.admin_status()["instance_id"]+ with patch.object(+ runtime._configuration, "admin_values", AsyncMock(return_value={})+ ):+ instance_id = (await runtime.admin_status())["instance_id"]with (- patch(- "free_claude_code.runtime.application.prepare_admin_update",+ patch.object(+ runtime._configuration,+ "prepare",return_value=prepared,),- patch(- "free_claude_code.runtime.application.commit_prepared_admin_update",+ patch.object(+ runtime._configuration,+ "commit",return_value=_applied_response(("PORT",)),) as commit,):@@ -496,9 +516,7 @@ async def test_restart_required_apply_commits_without_hot_publication(tmp_path)"fields": ["PORT"],"instance_id": instance_id,}- restart.assert_not_awaited()- await runtime.request_restart()- restart.assert_awaited_once()+ restart.assert_called_once_with()await manager.close()@@ -510,7 +528,9 @@ async def test_credential_checks_gate_both_apply_paths(tmp_path, pending, statusmanager = ProviderRuntimeManager(_settings("nvidia_nim/old"), runtime_factory=factory)- runtime = ApplicationRuntime(manager, transcriber=None)+ runtime = ApplicationRuntime(+ manager, configuration=AsyncMock(spec=ConfigurationService), transcriber=None+ )prepared = replace(_prepared(_settings("nvidia_nim/new"), tmp_path, pending_fields=pending),changed_keys=("GROQ_API_KEY",),@@ -520,16 +540,18 @@ async def test_credential_checks_gate_both_apply_paths(tmp_path, pending, statusCredentialCheck("OPENROUTER_API_KEY", CredentialStatus.VERIFIED, "Accepted"),)with (- patch(- "free_claude_code.runtime.application.prepare_admin_update",+ patch.object(+ runtime._configuration,+ "prepare",return_value=prepared,),patch("free_claude_code.runtime.application.check_credentials",AsyncMock(return_value=checks),) as check,- patch(- "free_claude_code.runtime.application.commit_prepared_admin_update",+ patch.object(+ runtime._configuration,+ "commit",return_value=_applied_response(pending),) as commit,):@@ -553,22 +575,23 @@ async def test_credential_checks_gate_both_apply_paths(tmp_path, pending, status@pytest.mark.asyncioasync def test_cancelled_credential_check_never_commits(tmp_path):manager = ProviderRuntimeManager(_settings("nvidia_nim/old"))- runtime = ApplicationRuntime(manager, transcriber=None)+ runtime = ApplicationRuntime(+ manager, configuration=AsyncMock(spec=ConfigurationService), transcriber=None+ )prepared = replace(_prepared(_settings("nvidia_nim/new"), tmp_path), changed_keys=("GROQ_API_KEY",))with (- patch(- "free_claude_code.runtime.application.prepare_admin_update",+ patch.object(+ runtime._configuration,+ "prepare",return_value=prepared,),patch("free_claude_code.runtime.application.check_credentials",AsyncMock(side_effect=asyncio.CancelledError),),- patch(- "free_claude_code.runtime.application.commit_prepared_admin_update"- ) as commit,+ patch.object(runtime._configuration, "commit") as commit,pytest.raises(asyncio.CancelledError),):await runtime.apply_admin_config({"GROQ_API_KEY": "new"})@@ -582,7 +605,11 @@ async def test_close_drains_messaging_before_transcriber_and_is_idempotent() ->events: list[str] = []manager = ProviderRuntimeManager(_settings("nvidia_nim/model"))transcriber = TrackingTranscriber(events)- runtime = ApplicationRuntime(manager, transcriber=transcriber)+ runtime = ApplicationRuntime(+ manager,+ configuration=AsyncMock(spec=ConfigurationService),+ transcriber=transcriber,+ )runtime._messaging_runtime = TrackingMessagingRuntime(events)workflow = MagicMock()workflow.close = AsyncMock(side_effect=lambda: events.append("workflow.close"))@@ -611,7 +638,11 @@ async def test_close_retains_transcriber_ownership_when_close_fails() -> None:events: list[str] = []manager = ProviderRuntimeManager(_settings("nvidia_nim/model"))transcriber = FailingTranscriber(events)- runtime = ApplicationRuntime(manager, transcriber=transcriber)+ runtime = ApplicationRuntime(+ manager,+ configuration=AsyncMock(spec=ConfigurationService),+ transcriber=transcriber,+ )runtime._messaging_runtime = TrackingMessagingRuntime(events)assert await runtime.close() is False@@ -632,7 +663,11 @@ async def test_close_retries_runtime_before_closing_later_resources() -> None:events: list[str] = []manager = ProviderRuntimeManager(_settings("nvidia_nim/model"))transcriber = TrackingTranscriber(events)- runtime = ApplicationRuntime(manager, transcriber=transcriber)+ runtime = ApplicationRuntime(+ manager,+ configuration=AsyncMock(spec=ConfigurationService),+ transcriber=transcriber,+ )messaging = TrackingMessagingRuntime(events, fail_close_once=True)runtime._messaging_runtime = messaging@@ -669,6 +704,7 @@ async def test_close_retries_connected_account_without_reclosing_providers() ->account.close = AsyncMock(side_effect=[RuntimeError("auth cleanup failed"), None])runtime = ApplicationRuntime(manager,+ configuration=AsyncMock(spec=ConfigurationService),transcriber=None,connected_accounts={"openai": account},)@@ -708,6 +744,7 @@ async def test_connected_account_status_reports_cached_model_count() -> None:)runtime = ApplicationRuntime(manager,+ configuration=AsyncMock(spec=ConfigurationService),transcriber=None,connected_accounts={"openai": account},)@@ -724,7 +761,9 @@ async def test_connected_account_status_reports_cached_model_count() -> None:async def test_close_retries_workflow_close_before_closing_delivery() -> None:events: list[str] = []manager = ProviderRuntimeManager(_settings("nvidia_nim/model"))- runtime = ApplicationRuntime(manager, transcriber=None)+ runtime = ApplicationRuntime(+ manager, configuration=AsyncMock(spec=ConfigurationService), transcriber=None+ )messaging = TrackingMessagingRuntime(events)workflow = MagicMock()close_calls = 0@@ -762,7 +801,9 @@ async def test_close_retries_workflow_close_before_closing_delivery() -> None:async def test_close_does_not_drain_workflow_until_ingress_is_quiescent() -> None:events: list[str] = []manager = ProviderRuntimeManager(_settings("nvidia_nim/model"))- runtime = ApplicationRuntime(manager, transcriber=None)+ runtime = ApplicationRuntime(+ manager, configuration=AsyncMock(spec=ConfigurationService), transcriber=None+ )messaging = TrackingMessagingRuntime(events, fail_quiesce_once=True)workflow = MagicMock()workflow.close = AsyncMock(side_effect=lambda: events.append("workflow.close"))@@ -790,7 +831,9 @@ async def test_close_does_not_drain_workflow_until_ingress_is_quiescent() -> Nonasync def test_close_retries_failed_persistence_before_closing_delivery() -> None:events: list[str] = []manager = ProviderRuntimeManager(_settings("nvidia_nim/model"))- runtime = ApplicationRuntime(manager, transcriber=None)+ runtime = ApplicationRuntime(+ manager, configuration=AsyncMock(spec=ConfigurationService), transcriber=None+ )messaging = TrackingMessagingRuntime(events)workflow = MagicMock()close_calls = 0@@ -829,7 +872,9 @@ async def test_close_retries_real_workflow_persistence_without_losing_latest_sta) -> None:events: list[str] = []manager = ProviderRuntimeManager(_settings("nvidia_nim/model"))- runtime = ApplicationRuntime(manager, transcriber=None)+ runtime = ApplicationRuntime(+ manager, configuration=AsyncMock(spec=ConfigurationService), transcriber=None+ )messaging = TrackingMessagingRuntime(events)cli_manager = MagicMock()cli_manager.stop_all = AsyncMock()@@ -912,7 +957,11 @@ async def test_cancelled_transcriber_close_retains_ownership() -> None:events: list[str] = []manager = ProviderRuntimeManager(_settings("nvidia_nim/model"))transcriber = CancelledTranscriber(events)- runtime = ApplicationRuntime(manager, transcriber=transcriber)+ runtime = ApplicationRuntime(+ manager,+ configuration=AsyncMock(spec=ConfigurationService),+ transcriber=transcriber,+ )with pytest.raises(asyncio.CancelledError):await runtime._cleanup_transcriber()@@ -927,7 +976,11 @@ async def test_cancelled_application_close_remains_retryable() -> None:events: list[str] = []manager = ProviderRuntimeManager(_settings("nvidia_nim/model"))transcriber = CancellingOnceTranscriber(events)- runtime = ApplicationRuntime(manager, transcriber=transcriber)+ runtime = ApplicationRuntime(+ manager,+ configuration=AsyncMock(spec=ConfigurationService),+ transcriber=transcriber,+ )with pytest.raises(asyncio.CancelledError):await runtime.close()@@ -947,7 +1000,11 @@ async def test_startup_failure_closes_owned_transcriber() -> None:events: list[str] = []manager = ProviderRuntimeManager(_settings("nvidia_nim/model"))transcriber = TrackingTranscriber(events)- runtime = ApplicationRuntime(manager, transcriber=transcriber)+ runtime = ApplicationRuntime(+ manager,+ configuration=AsyncMock(spec=ConfigurationService),+ transcriber=transcriber,+ )with (patch.object(@@ -967,7 +1024,11 @@ async def test_startup_cancellation_cleans_partial_messaging_and_reraises() -> Nevents: list[str] = []manager = ProviderRuntimeManager(_settings("nvidia_nim/model"))transcriber = TrackingTranscriber(events)- runtime = ApplicationRuntime(manager, transcriber=transcriber)+ runtime = ApplicationRuntime(+ manager,+ configuration=AsyncMock(spec=ConfigurationService),+ transcriber=transcriber,+ )messaging = TrackingMessagingRuntime(events)entered = asyncio.Event()@@ -1001,7 +1062,9 @@ async def test_startup_cancellation_cleans_partial_messaging_and_reraises() -> Nasync def test_public_start_retries_transient_partial_messaging_cleanup() -> None:events: list[str] = []manager = ProviderRuntimeManager(_settings("nvidia_nim/model"))- runtime = ApplicationRuntime(manager, transcriber=None)+ runtime = ApplicationRuntime(+ manager, configuration=AsyncMock(spec=ConfigurationService), transcriber=None+ )messaging = TrackingMessagingRuntime(events, fail_quiesce_once=True)workflow = MagicMock()workflow.close = AsyncMock(side_effect=lambda: events.append("workflow.close"))@@ -1063,7 +1126,11 @@ async def test_public_start_retains_persistently_unclean_partial_messaging_graphevents: list[str] = []manager = ProviderRuntimeManager(_settings("nvidia_nim/model"))transcriber = TrackingTranscriber(events)- runtime = ApplicationRuntime(manager, transcriber=transcriber)+ runtime = ApplicationRuntime(+ manager,+ configuration=AsyncMock(spec=ConfigurationService),+ transcriber=transcriber,+ )messaging = PersistentlyFailingMessagingRuntime(events)workflow = MagicMock()workflow.close = AsyncMock(side_effect=lambda: events.append("workflow.close"))@@ -1132,7 +1199,9 @@ async def test_public_start_retains_persistently_unclean_partial_messaging_graph@pytest.mark.asyncioasync def test_messaging_start_failure_is_nonfatal_after_complete_cleanup() -> None:manager = ProviderRuntimeManager(_settings("nvidia_nim/model"))- runtime = ApplicationRuntime(manager, transcriber=None)+ runtime = ApplicationRuntime(+ manager, configuration=AsyncMock(spec=ConfigurationService), transcriber=None+ )with (patch(@@ -1151,7 +1220,9 @@ async def test_messaging_start_failure_fails_closed_when_cleanup_is_incomplete()None):manager = ProviderRuntimeManager(_settings("nvidia_nim/model"))- runtime = ApplicationRuntime(manager, transcriber=None)+ runtime = ApplicationRuntime(+ manager, configuration=AsyncMock(spec=ConfigurationService), transcriber=None+ )with (patch(@@ -1171,7 +1242,9 @@ async def test_messaging_start_failure_fails_closed_when_cleanup_is_incomplete()async def test_composition_records_runtime_before_workspace_setup() -> None:events: list[str] = []manager = ProviderRuntimeManager(_settings("nvidia_nim/model"))- runtime = ApplicationRuntime(manager, transcriber=None)+ runtime = ApplicationRuntime(+ manager, configuration=AsyncMock(spec=ConfigurationService), transcriber=None+ )messaging = TrackingMessagingRuntime(events)components = MessagingPlatformComponents(name="tracking",@@ -1200,7 +1273,9 @@ async def test_composition_records_runtime_before_workspace_setup() -> None:async def test_composition_publishes_startup_notice_after_runtime_and_repair() -> None:events: list[str] = []manager = ProviderRuntimeManager(_settings("nvidia_nim/model"))- runtime = ApplicationRuntime(manager, transcriber=None)+ runtime = ApplicationRuntime(+ manager, configuration=AsyncMock(spec=ConfigurationService), transcriber=None+ )messaging = TrackingMessagingRuntime(events)notice = MessagingStartupNotice(chat_id="chat",diff --git a/tests/runtime/test_config_startup.py b/tests/runtime/test_config_startup.pynew file mode 100644index 00000000..20227988--- /dev/null+++ b/tests/runtime/test_config_startup.py@@ -0,0 +1,108 @@+import asyncio+import threading+from unittest.mock import AsyncMock, patch++import pytest++from free_claude_code.application.errors import ApplicationUnavailableError+from free_claude_code.config import loader+from free_claude_code.config.loader import ManagedConfigStore+from free_claude_code.config.paths import config_lock_path+from free_claude_code.core.interprocess_lock import InterprocessFileLock+from free_claude_code.runtime.application import ApplicationRuntime+from free_claude_code.runtime.configuration import ConfigurationService+from free_claude_code.runtime.provider_manager import ProviderRuntimeManager+from tests.runtime.test_application_runtime import _settings++[email protected]("cancel", [False, True])[email protected]("fail", [False, True])+async def test_shutdown_drains_initialization_worker(cancel, fail):+ loop = asyncio.get_running_loop()+ previous_handler = loop.get_exception_handler()+ unhandled_errors = []+ loop.set_exception_handler(lambda _loop, context: unhandled_errors.append(context))+ entered, release, finished = threading.Event(), threading.Event(), threading.Event()+ store = ManagedConfigStore()+ manager = ProviderRuntimeManager(_settings("nvidia_nim/old"))+ runtime = ApplicationRuntime(+ manager, configuration=ConfigurationService(store), transcriber=None+ )+ consolidate = loader.consolidate_managed_config++ def blocked_consolidation(env):+ entered.set()+ try:+ assert release.wait(5)+ if fail:+ raise OSError("private-initialization-detail")+ return consolidate(env)+ finally:+ finished.set()++ async def wait_for_worker():+ while not entered.is_set():+ await asyncio.sleep(0)++ with (+ patch.object(loader, "consolidate_managed_config", blocked_consolidation),+ patch.object(manager, "warm_referenced_model_cache", AsyncMock()) as warm,+ ):+ start = asyncio.create_task(runtime.start())+ close = None+ try:+ await asyncio.wait_for(wait_for_worker(), 5)+ if cancel:+ start.cancel()+ await asyncio.sleep(0)+ start.cancel()+ close = asyncio.create_task(runtime.close())+ await asyncio.sleep(0)+ await asyncio.sleep(0)+ assert not start.done()+ assert not close.done()+ assert not runtime.is_closed+ assert not finished.is_set()+ assert not store.path.exists()+ release.set()+ error = (+ asyncio.CancelledError+ if cancel+ else OSError+ if fail+ else ApplicationUnavailableError+ )+ with pytest.raises(error):+ await asyncio.wait_for(start, 5)+ assert await asyncio.wait_for(close, 5)+ assert finished.is_set()+ assert unhandled_errors == []+ assert store.path.exists() is not fail+ warm.assert_not_awaited()+ lock = InterprocessFileLock(config_lock_path())+ try:+ assert lock.acquire()+ finally:+ lock.release()+ finally:+ release.set()+ await asyncio.gather(+ start, *([close] if close else []), return_exceptions=True+ )+ await runtime.close()+ loop.set_exception_handler(previous_handler)+++async def test_closed_runtime_cannot_start_another_configuration_writer():+ store = ManagedConfigStore()+ runtime = ApplicationRuntime(+ ProviderRuntimeManager(_settings("nvidia_nim/old")),+ configuration=ConfigurationService(store),+ transcriber=None,+ )+ await runtime.close()+ with pytest.raises(ApplicationUnavailableError):+ await runtime.start()+ assert not store.path.exists()diff --git a/tests/runtime/test_config_transactions.py b/tests/runtime/test_config_transactions.pynew file mode 100644index 00000000..b016d06b--- /dev/null+++ b/tests/runtime/test_config_transactions.py@@ -0,0 +1,270 @@+import asyncio+import threading+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from free_claude_code.application.errors import ApplicationUnavailableError+from free_claude_code.config.loader import ManagedConfigStore+from free_claude_code.runtime.application import ApplicationRuntime+from free_claude_code.runtime.configuration import ConfigurationService+from free_claude_code.runtime.provider_manager import ProviderRuntimeManager+from tests.runtime.test_application_runtime import TrackingFactory, _prepared, _settings+++async def test_awaitable_restart_callback_is_not_executed_under_apply_lock(tmp_path):+ manager = ProviderRuntimeManager(_settings("nvidia_nim/old"))+ configuration = AsyncMock(spec=ConfigurationService)+ prepared = _prepared(+ _settings("nvidia_nim/old", port=9090), tmp_path, pending_fields=("PORT",)+ )+ configuration.prepare.return_value = prepared+ configuration.commit.return_value = prepared.applied_response()+ callback_tasks = []++ async def close_on_restart():+ callback_tasks.append(asyncio.current_task())+ await runtime.close()++ # A dynamically supplied callback can evade static checking by returning a coroutine.+ callback = MagicMock(side_effect=close_on_restart)+ runtime = ApplicationRuntime(+ manager,+ configuration=configuration,+ transcriber=None,+ restart_callback=callback,+ )+ with patch(+ "free_claude_code.runtime.application.check_credentials",+ AsyncMock(return_value=()),+ ):+ apply = asyncio.create_task(runtime.apply_admin_config({"PORT": "9090"}))+ try:+ done, _ = await asyncio.wait({apply}, timeout=2)+ assert apply in done, "restart callback deadlocked with runtime.close"+ result = apply.result()+ assert result["applied"] is True+ restart = result["restart"]+ assert isinstance(restart, dict)+ assert restart["automatic"] is False+ assert runtime._pending_fields == ["PORT"]+ assert callback_tasks == []+ callback.assert_called_once_with()+ finally:+ for task in callback_tasks:+ task.cancel()+ apply.cancel()+ await asyncio.gather(apply, return_exceptions=True)+ await runtime.close()++[email protected]("pending", [(), ("PORT",)])[email protected]("fail", [False, True])+async def test_cancelled_commit_settles_before_shutdown(tmp_path, pending, fail):+ factory = TrackingFactory()+ manager = ProviderRuntimeManager(+ _settings("nvidia_nim/old"), runtime_factory=factory+ )+ configuration = AsyncMock(spec=ConfigurationService)+ prepared = _prepared(_settings("nvidia_nim/new"), tmp_path, pending_fields=pending)+ configuration.prepare.return_value = prepared+ entered, release = asyncio.Event(), asyncio.Event()++ async def commit(_prepared):+ entered.set()+ await release.wait()+ if fail:+ raise OSError("disk full")+ return prepared.applied_response()++ configuration.commit.side_effect = commit+ restart = MagicMock(return_value=None)+ runtime = ApplicationRuntime(+ manager, configuration=configuration, transcriber=None, restart_callback=restart+ )+ with patch(+ "free_claude_code.runtime.application.check_credentials",+ AsyncMock(return_value=()),+ ):+ apply = asyncio.create_task(runtime.apply_admin_config({}))+ await asyncio.wait_for(entered.wait(), 5)+ apply.cancel()+ await asyncio.sleep(0)+ apply.cancel()+ close = asyncio.create_task(runtime.close())+ await asyncio.sleep(0)+ assert not apply.done()+ assert not close.done()+ assert factory.runtimes[0].cleanup_calls == 0+ release.set()+ with pytest.raises(asyncio.CancelledError) as error:+ await asyncio.wait_for(apply, 5)+ if fail:+ assert isinstance(error.value.__cause__, OSError)+ assert manager.current_generation_id == (2 if not pending and not fail else 1)+ assert restart.call_count == (1 if pending and not fail else 0)+ assert await asyncio.wait_for(close, 5)+ with pytest.raises(ApplicationUnavailableError):+ await runtime.apply_admin_config({})+ configuration.commit.assert_awaited_once()++[email protected]("restart_required", [False, True])[email protected]("cancel_during_apply", [False, True])[email protected]("previous_cancellation", [False, True])+async def test_cancellation_at_finalization_handoff_prevents_persistence(+ monkeypatch, restart_required, cancel_during_apply, previous_cancellation+):+ monkeypatch.delenv("MODEL", raising=False)+ monkeypatch.delenv("PORT", raising=False)+ store = ManagedConfigStore()+ store.initialize()+ initial = store.read()+ original_bytes = initial.path.read_bytes()+ factory = TrackingFactory()+ manager = ProviderRuntimeManager(initial.settings, runtime_factory=factory)+ restart = MagicMock(return_value=None)+ runtime = ApplicationRuntime(+ manager,+ configuration=ConfigurationService(store),+ transcriber=None,+ restart_callback=restart,+ )+ updates = {"PORT": "8123"} if restart_required else {"MODEL": "nvidia_nim/new"}++ async def run_apply():+ if previous_cancellation:+ caller = asyncio.current_task()+ assert caller is not None+ caller.cancel()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.sleep(0)+ return await runtime.apply_admin_config(updates)++ async def check_credentials(*_args):+ if cancel_during_apply:+ # Queue cancellation before finalization, with the caller's wakeup after it.+ asyncio.get_running_loop().call_soon(apply.cancel)+ return ()++ with (+ patch(+ "free_claude_code.runtime.application.check_credentials", check_credentials+ ),+ patch.object(manager, "_refresh_generation_in_background", AsyncMock()),+ patch.object(store, "commit", wraps=store.commit) as commit,+ ):+ apply = asyncio.create_task(run_apply())+ try:+ if cancel_during_apply:+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(apply, 5)+ commit.assert_not_called()+ assert initial.path.read_bytes() == original_bytes+ assert manager.current_generation_id == 1+ assert runtime._pending_fields == []+ restart.assert_not_called()+ assert all(item.cleanup_calls == 1 for item in factory.runtimes[1:])+ else:+ assert (await asyncio.wait_for(apply, 5))["applied"] is True+ commit.assert_called_once()+ assert manager.current_generation_id == (1 if restart_required else 2)+ assert restart.call_count == int(restart_required)+ finally:+ apply.cancel()+ await asyncio.gather(apply, return_exceptions=True)+ await runtime.close()+++async def test_cancellation_waiting_for_replacement_does_not_persist(tmp_path):+ manager = ProviderRuntimeManager(_settings("nvidia_nim/old"))+ configuration = AsyncMock(spec=ConfigurationService)+ configuration.prepare.return_value = _prepared(+ _settings("nvidia_nim/new"), tmp_path+ )+ runtime = ApplicationRuntime(manager, configuration=configuration, transcriber=None)+ with patch(+ "free_claude_code.runtime.application.check_credentials",+ AsyncMock(return_value=()),+ ):+ async with manager._replace_lock:+ apply = asyncio.create_task(runtime.apply_admin_config({}))+ while not manager._replace_lock._waiters:+ await asyncio.sleep(0)+ apply.cancel()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(apply, 5)+ configuration.commit.assert_not_awaited()+ assert manager.current_generation_id == 1+ await runtime.close()++[email protected]("shutdown", [False, True])+async def test_worker_commit_retains_ownership_against_queued_apply(+ monkeypatch, shutdown+):+ monkeypatch.delenv("LOG_LEVEL", raising=False)+ store = ManagedConfigStore()+ store.initialize()+ manager = ProviderRuntimeManager(_settings("nvidia_nim/old"))+ restart = MagicMock(return_value=None)+ runtime = ApplicationRuntime(+ manager,+ configuration=ConfigurationService(store),+ transcriber=None,+ restart_callback=restart,+ )+ entered, release = threading.Event(), threading.Event()+ original = store.commit+ writes = []++ def blocked_commit(values):+ entered.set()+ assert release.wait(5)+ writes.append(values["LOG_LEVEL"])+ original(values)++ async def wait_for_commit():+ while not entered.is_set():+ await asyncio.sleep(0)++ with patch.object(store, "commit", blocked_commit):+ first = asyncio.create_task(+ runtime.apply_admin_config({"LOG_LEVEL": "WARNING"})+ )+ second = None+ try:+ await asyncio.wait_for(wait_for_commit(), 5)+ first.cancel()+ second = asyncio.create_task(+ runtime.apply_admin_config({"LOG_LEVEL": "ERROR"})+ )+ await asyncio.sleep(0)+ assert runtime._config_lock.locked()+ assert not second.done()+ assert writes == []+ if shutdown:+ runtime.begin_shutdown()+ first.cancel()+ release.set()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(first, 5)+ if shutdown:+ with pytest.raises(ApplicationUnavailableError):+ await asyncio.wait_for(second, 5)+ else:+ assert (await asyncio.wait_for(second, 5))["applied"]+ assert writes == (["WARNING"] if shutdown else ["WARNING", "ERROR"])+ assert store.read().settings.log_level == writes[-1]+ assert restart.call_count == len(writes)+ finally:+ release.set()+ await asyncio.gather(+ first, *([second] if second is not None else []), return_exceptions=True+ )+ await runtime.close()diff --git a/tests/runtime/test_configuration.py b/tests/runtime/test_configuration.pynew file mode 100644index 00000000..ef6fcc7d--- /dev/null+++ b/tests/runtime/test_configuration.py@@ -0,0 +1,199 @@+import asyncio+import io+import threading+from concurrent.futures import ThreadPoolExecutor+from unittest.mock import patch++import pytest++from free_claude_code.config import loader+from free_claude_code.config.admin.persistence import prepare_admin_update+from free_claude_code.config.env_files import FCC_CONFIG_SCHEMA_ENV+from free_claude_code.config.env_migrations import CONFIG_SCHEMA_VERSION+from free_claude_code.config.loader import ManagedConfigStore+from free_claude_code.config.paths import config_lock_path+from free_claude_code.core.interprocess_lock import InterprocessFileLock+from free_claude_code.runtime.configuration import ConfigurationService+++def test_reads_are_fresh_read_only_snapshots():+ store = ManagedConfigStore()+ store.initialize()+ for port in (8123, 8124):+ store.path.write_text(+ f"{FCC_CONFIG_SCHEMA_ENV}={CONFIG_SCHEMA_VERSION}\nPORT={port}\n"+ )+ with patch(+ "free_claude_code.config.loader.consolidate_managed_config",+ side_effect=AssertionError("read migrated"),+ ):+ snapshot = store.read()+ assert snapshot.settings.port == port+ assert snapshot.managed["PORT"] == str(port)+++def test_read_does_not_recreate_missing_storage():+ store = ManagedConfigStore()+ with pytest.raises(ValueError, match="initializ"):+ store.read()+ assert not store.path.exists()+++def test_preparation_uses_captured_disk_and_process_state(monkeypatch):+ store = ManagedConfigStore()+ store.initialize()+ snapshot = store.read({"PORT": "8123"})+ monkeypatch.setenv("PORT", "9999")+ store.path.unlink()+ prepared = prepare_admin_update({"PORT": "8124"}, snapshot, snapshot.settings)+ assert prepared.settings is not None+ assert prepared.settings.port == 8123+ assert "PORT" not in prepared.target_values+++async def test_read_waits_for_storage_lock_without_blocking_event_loop():+ store = ManagedConfigStore()+ store.initialize()+ service = ConfigurationService(store)+ with InterprocessFileLock(config_lock_path()):+ reader = asyncio.create_task(service.admin_values())+ done, _ = await asyncio.wait({reader}, timeout=0.1)+ try:+ assert not done+ finally:+ await asyncio.wait_for(reader, 5)++[email protected]("schema", ["", "999"])+def test_reads_and_commits_fail_closed_on_uninitialized_or_newer_schema(schema):+ store = ManagedConfigStore()+ store.initialize()+ text = f"FCC_CONFIG_SCHEMA={schema}\nANTHROPIC_AUTH_TOKEN=preserve\n"+ store.path.write_text(text)+ with pytest.raises(ValueError, match="schema"):+ store.read()+ with pytest.raises(ValueError, match="schema"):+ store.commit({"FCC_CONFIG_SCHEMA": "1"})+ assert store.path.read_text() == text+++def test_cooperative_commits_are_serialized_and_leave_complete_files():+ store = ManagedConfigStore()+ store.initialize()+ original = loader.atomic_write_managed_config+ writing = threading.Lock()+ seen = []++ def checked_write(values, **kwargs):+ probe = InterprocessFileLock(config_lock_path())+ try:+ assert not probe.acquire(), "commit does not hold the shared write lock"+ finally:+ probe.release()+ assert writing.acquire(blocking=False), "cooperative writes overlap"+ try:+ seen.append(values["PORT"])+ return original(values, **kwargs)+ finally:+ writing.release()++ def write(port):+ ManagedConfigStore().commit({"FCC_CONFIG_SCHEMA": "1", "PORT": str(port)})++ with (+ patch(+ "free_claude_code.config.loader.atomic_write_managed_config", checked_write+ ),+ ThreadPoolExecutor(max_workers=8) as executor,+ ):+ list(executor.map(write, range(8120, 8128)))+ assert len(seen) == 8+ assert store.read().managed["PORT"] == seen[-1]+ assert not list(store.path.parent.glob("*.tmp"))+++def test_atomic_commit_waits_for_an_open_snapshot_reader(monkeypatch):+ store = ManagedConfigStore()+ store.initialize()+ store.commit({"FCC_CONFIG_SCHEMA": "1", "PORT": "8123"})+ opened, release = threading.Event(), threading.Event()+ original_open = io.open+ reader_thread = None++ def hold_reader(path, *args, **kwargs):+ handle = original_open(path, *args, **kwargs)+ if path == store.path and threading.current_thread() is reader_thread:+ opened.set()+ if not release.wait(5):+ handle.close()+ raise TimeoutError("snapshot reader was not released")+ return handle++ def read_snapshot():+ nonlocal reader_thread+ reader_thread = threading.current_thread()+ return store.read({})++ monkeypatch.setattr(io, "open", hold_reader)+ with ThreadPoolExecutor(max_workers=2) as executor:+ reader = executor.submit(read_snapshot)+ writer = None+ try:+ assert opened.wait(5)+ writer = executor.submit(+ store.commit, {"FCC_CONFIG_SCHEMA": "1", "PORT": "8124"}+ )+ with pytest.raises(TimeoutError):+ writer.result(timeout=0.1)+ finally:+ release.set()+ assert reader.result(timeout=5).settings.port == 8123+ assert writer.result(timeout=5) is None+ assert store.read({}).settings.port == 8124+ assert not list(store.path.parent.glob("*.tmp"))+++ "operation", ["initialize", "admin_config", "admin_values", "prepare", "commit"]+)+async def test_storage_work_does_not_block_event_loop(operation):+ store = ManagedConfigStore()+ store.initialize()+ service = ConfigurationService(store)+ active = store.read().settings+ prepared = await service.prepare({"PORT": "8123"}, active)+ entered = threading.Event()+ release = threading.Event()+ heartbeat = asyncio.Event()+ method = {"admin_config": "read", "admin_values": "read", "prepare": "read"}.get(+ operation, operation+ )+ original = getattr(store, method)++ def blocked(*args, **kwargs):+ entered.set()+ assert release.wait(5), "event loop failed to release storage"+ assert heartbeat.is_set()+ return original(*args, **kwargs)++ async def observe():+ while not entered.is_set():+ await asyncio.sleep(0)+ heartbeat.set()+ release.set()++ observer = asyncio.create_task(observe())+ try:+ with patch.object(store, method, side_effect=blocked):+ if operation == "prepare":+ await service.prepare({"PORT": "8124"}, active)+ elif operation == "commit":+ await service.commit(prepared)+ else:+ await getattr(service, operation)()+ await asyncio.wait_for(observer, 5)+ finally:+ release.set()+ observer.cancel()diff --git a/tests/runtime/test_provider_manager.py b/tests/runtime/test_provider_manager.pyindex 5a67f88c..b6e40a1c 100644--- a/tests/runtime/test_provider_manager.py+++ b/tests/runtime/test_provider_manager.py@@ -228,7 +228,7 @@ async def test_catalog_publication_tracks_replacement_and_its_refresh() -> None:await manager.replace(_settings("nvidia_nim/two"),- commit=lambda: None,+ commit=AsyncMock(),)refresh_task = manager._refresh_taskassert refresh_task is not None@@ -284,7 +284,7 @@ async def test_replacement_keeps_leased_generation_open_until_final_release() ->generation_id = await manager.replace(second_settings,- commit=lambda: committed.append("persisted"),+ commit=AsyncMock(side_effect=lambda: committed.append("persisted")),)new_lease = await manager.acquire()@@ -322,7 +322,7 @@ async def test_hot_replacement_owns_admission_per_provider_generation() -> None:refresh = AsyncMock()with patch.object(manager, "_refresh_generation", refresh):- await manager.replace(second_settings, commit=lambda: None)+ await manager.replace(second_settings, commit=AsyncMock())new_lease = await manager.acquire()new_provider = new_lease.resolve_provider("nvidia_nim")await asyncio.sleep(0)@@ -355,7 +355,7 @@ async def test_replacement_closes_unleased_generation_immediately() -> None:await manager.replace(_settings("nvidia_nim/two"),- commit=lambda: None,+ commit=AsyncMock(),)assert factory.runtimes[0].cleanup_calls == 1@@ -383,7 +383,7 @@ async def test_cancelled_replacement_does_not_cancel_owned_generation_cleanup()replace_task = asyncio.create_task(manager.replace(_settings("nvidia_nim/two"),- commit=lambda: None,+ commit=AsyncMock(),))await cleanup_started.wait()@@ -420,7 +420,7 @@ async def test_cancelled_final_lease_release_keeps_owned_cleanup_running() -> Nolease = await manager.acquire()await manager.replace(_settings("nvidia_nim/two"),- commit=lambda: None,+ commit=AsyncMock(),)cleanup_started = asyncio.Event()cleanup_release = asyncio.Event()@@ -461,7 +461,7 @@ async def test_hot_cleanup_failure_keeps_published_replacement() -> None:generation_id = await manager.replace(_settings("nvidia_nim/two"),- commit=lambda: None,+ commit=AsyncMock(),)assert generation_id == 2@@ -488,7 +488,7 @@ async def test_candidate_construction_failure_preserves_current_generation() ->with pytest.raises(RuntimeError, match="cannot construct"):await manager.replace(_settings("nvidia_nim/two"),- commit=lambda: None,+ commit=AsyncMock(),)assert manager.current_generation_id == 1@@ -505,7 +505,7 @@ async def test_failed_candidate_cleanup_is_retried_at_shutdown() -> None:runtime_factory=factory,)- def fail_commit() -> None:+ async def fail_commit() -> None:factory.runtimes[1].cleanup_error = RuntimeError("private cleanup detail")raise OSError("disk full")@@ -550,7 +550,7 @@ async def test_later_replacement_retries_failed_unpublished_candidate() -> None:runtime_factory=factory,)- def fail_commit() -> None:+ async def fail_commit() -> None:factory.runtimes[1].cleanup_error = RuntimeError("cleanup failed")raise OSError("disk full")@@ -563,7 +563,7 @@ async def test_later_replacement_retries_failed_unpublished_candidate() -> None:factory.runtimes[1].cleanup_error = Nonegeneration_id = await manager.replace(_settings("nvidia_nim/three"),- commit=lambda: None,+ commit=AsyncMock(),)assert generation_id == 2@@ -582,7 +582,7 @@ async def test_cancelled_candidate_cleanup_remains_owned_until_shutdown() -> Noncleanup_started = asyncio.Event()cleanup_release = asyncio.Event()- def fail_commit() -> None:+ async def fail_commit() -> None:candidate = factory.runtimes[1]candidate.cleanup_started = cleanup_startedcandidate.cleanup_release = cleanup_release@@ -634,14 +634,14 @@ async def test_concurrent_replacements_are_serialized_in_call_order() -> None:first = asyncio.create_task(manager.replace(_settings("nvidia_nim/two"),- commit=lambda: None,+ commit=AsyncMock(),))await first_entered.wait()second = asyncio.create_task(manager.replace(_settings("nvidia_nim/three"),- commit=lambda: None,+ commit=AsyncMock(),))await asyncio.sleep(0)@@ -693,7 +693,7 @@ async def test_cancelled_shutdown_retains_generation_for_retry() -> None:with pytest.raises(ApplicationUnavailableError, match="shutting down"):await manager.acquire()with pytest.raises(ApplicationUnavailableError, match="shutting down"):- await manager.replace(_settings("nvidia_nim/two"), commit=lambda: None)+ await manager.replace(_settings("nvidia_nim/two"), commit=AsyncMock())assert factory.runtimes[0].cleanup_calls == 0await lease.release()@@ -787,7 +787,7 @@ async def test_application_catalog_survives_generation_replacement() -> None:await manager.replace(_settings("nvidia_nim/two"),- commit=lambda: None,+ commit=AsyncMock(),)assert manager.cached_model_ids() == {"lmstudio": frozenset({"persisted"})}@@ -819,7 +819,7 @@ async def test_generation_lease_keeps_its_model_metadata_after_replacement() ->await manager.replace(_settings("nvidia_nim/two"),- commit=lambda: None,+ commit=AsyncMock(),)assert lease.model_infos == (@@ -844,7 +844,7 @@ async def test_replacement_prunes_and_rejects_removed_remote_provider_cache() ->await manager.replace(_settings("nvidia_nim/two"),- commit=lambda: None,+ commit=AsyncMock(),)manager.cache_model_infos("open_router", {ProviderModelInfo("late-old-model")})@@ -864,7 +864,7 @@ async def test_generation_lifecycle_traces_contain_minimal_correlation_fields()lease = await manager.acquire()await manager.replace(_settings("nvidia_nim/two"),- commit=lambda: None,+ commit=AsyncMock(),reason="test_replace",)await lease.release()diff --git a/uv.lock b/uv.lockindex 55da772f..35ef331b 100644--- a/uv.lock+++ b/uv.lock@@ -598,7 +598,7 @@ wheels = [[[package]]name = "free-claude-code"-version = "5.22.4"+version = "5.22.5"source = { editable = "." }dependencies = [{ name = "aiohttp" },