Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)
Python
patch: give integrations and messaging dedicated runtime owners (#1930)
Ali Khokhar5dc3a6771646
diff --git a/e2e/test_admin_vscode_chat.py b/e2e/test_admin_vscode_chat.pyindex 6275886b..e0d5f1d5 100644--- a/e2e/test_admin_vscode_chat.py+++ b/e2e/test_admin_vscode_chat.py@@ -73,6 +73,11 @@ def test_failed_update_has_actionable_retry(page, admin_base_url, status_read_fapage.route("**/admin/api/integrations/vscode-chat", status)page.route("**/admin/api/integrations/vscode-chat/refresh", retry)page.goto(f"{admin_base_url}/admin/integrations")+ # Startup reconciliation can temporarily disable Retry during the click.+ # Exercise the action after initial polling has settled.+ page.wait_for_function(+ "state.startup && !state.startupRequest && state.startupTimer === null"+ )main = page.locator("#openVSCodeChatIntegration")secondary = page.locator("#retryVSCodeChatIntegration")if status_read_failed:diff --git a/src/free_claude_code/runtime/application.py b/src/free_claude_code/runtime/application.pyindex c887cf56..d1491eab 100644--- a/src/free_claude_code/runtime/application.py+++ b/src/free_claude_code/runtime/application.py@@ -1,17 +1,11 @@"""Single owner for application startup, shutdown, and runtime operations."""import asyncio-import importlibimport inspectimport logging-import os-import tracebackimport uuidfrom collections.abc import Awaitable, Callable, Mapping-from dataclasses import dataclass, replace-from functools import partial-from pathlib import Path-from typing import TYPE_CHECKING, Literal+from dataclasses import replacefrom loguru import logger@@ -22,11 +16,8 @@ from free_claude_code.application.connected_accounts import (ConnectedAccountStatus,)from free_claude_code.application.errors import (- ApplicationError,ApplicationUnavailableError,- InvalidRequestError,)-from free_claude_code.application.model_catalog import ModelCatalog, read_model_catalogfrom free_claude_code.application.model_metadata import ProviderModelRefreshResultfrom free_claude_code.application.ports import StopResultfrom free_claude_code.config.admin.custom_providers import CustomProviderMutation@@ -37,66 +28,26 @@ from free_claude_code.config.admin.state import ConfigInputValue, ValueStatefrom free_claude_code.config.admin.status import provider_config_statusfrom free_claude_code.config.loader import clear_settings_cachefrom free_claude_code.config.model_refs import parse_provider_type-from free_claude_code.config.paths import (- claude_desktop_disconnect_path,- codex_model_catalog_path,- messaging_state_dir_path,-)-from free_claude_code.config.server_urls import local_admin_url, local_proxy_root_url+from free_claude_code.config.server_urls import local_admin_urlfrom free_claude_code.config.settings import Settings+from free_claude_code.core.async_tasks import run_sync_ownedfrom free_claude_code.core.json_types import JsonObject-from free_claude_code.harnesses import (- claude_desktop_integration,- claude_integration,- codex_integration,- jetbrains_acp_integration,- vscode_chat_integration,-)-from free_claude_code.messaging.platforms import factory as messaging_platform_factory-from free_claude_code.messaging.platforms.factory import MessagingPlatformOptions-from free_claude_code.messaging.platforms.ports import (- MessagingPlatformComponents,- MessagingRuntime,-)from free_claude_code.messaging.voice import Transcriberfrom free_claude_code.providers.credential_validation import (CredentialStatus,check_credentials,)-if TYPE_CHECKING:- import free_claude_code.cli.managed as cli_managed- import free_claude_code.messaging.workflow as messaging_workflow_module-- from .messaging_sqlite import SQLiteMessagingStore--from free_claude_code.application.readiness import InitializationWait-from free_claude_code.core.async_tasks import run_sync_owned-from .configuration import ConfigurationServicefrom .folder_picker import NativeFolderPicker+from .integration_service import IntegrationService+from .lifecycle import best_effort+from .messaging_service import MessagingServicefrom .provider_manager import ProviderRuntimeManagerfrom .retired_chat import remove_retired_chat_historyfrom .sqlite_database import SQLiteDatabaseRestartCallback = Callable[[], None]-IntegrationAction = Literal["status", "connect", "disconnect", "refresh"]---@dataclass-class _IntegrationUpdate:- state: Literal["starting", "ready", "failed"] = "ready"- changed: bool = False- message: str | None = None- task: asyncio.Task[None] | None = None-- def snapshot(self) -> JsonObject:- return {"state": self.state, "changed": self.changed, "message": self.message}-- def complete(self, changed: bool = False) -> None:- self.state = "ready"- self.changed = changed- self.message = None_PROVIDER_CHECK_FAILURE_MESSAGE = (@@ -104,39 +55,6 @@ _PROVIDER_CHECK_FAILURE_MESSAGE = ()-async def best_effort(- name: str,- awaitable: Awaitable[object],- *,- log_verbose_errors: bool = False,-) -> bool:- """Run one cleanup step and report whether it completed.-- The lifecycle owner intentionally applies no generic timeout here. Cancelling- an arbitrary cleanup at a deadline can abandon a half-closed SDK, thread, or- provider resource; resource-specific cleanup or the process supervisor owns- any force-termination deadline.- """- try:- await awaitable- except Exception as exc:- if log_verbose_errors:- logger.warning(- "Shutdown step failed: {}: {}: {}",- name,- type(exc).__name__,- exc,- )- else:- logger.warning(- "Shutdown step failed: {}: exc_type={}",- name,- type(exc).__name__,- )- return False- return True--def startup_failure_message(settings: Settings, exc: Exception) -> str:"""Return the existing concise ASGI startup failure message."""if isinstance(exc, ApplicationUnavailableError):@@ -198,13 +116,7 @@ class ApplicationRuntime:self._configuration = configurationself._code_service = code_serviceself._database = database- self._messaging_store: SQLiteMessagingStore | None = None- self._messaging_import_task: asyncio.Task[None] | None = None- self._messaging_warning: str | None = None- self._messaging_storage_error: Exception | None = Noneself._folder_picker = NativeFolderPicker()- self._transcriber = transcriber- self._transcriber_factory = transcriber_factoryself._restart_callback = restart_callbackself._connected_accounts = dict(connected_accounts or {})self._connected_account_revisions = {@@ -213,11 +125,6 @@ class ApplicationRuntime:}self._config_lock = asyncio.Lock()self._pending_fields: list[str] = []- self._messaging_runtime: MessagingRuntime | None = None- self._messaging_workflow: messaging_workflow_module.MessagingWorkflow | None = (- None- )- self._cli_manager: cli_managed.ManagedClaudeSessionManager | None = Noneself._started = Falseself._instance_id = uuid.uuid4().hexself._draining = False@@ -226,17 +133,21 @@ class ApplicationRuntime:self._connected_accounts_closed = Falseself._lifecycle_lock = asyncio.Lock()self._startup_tasks: list[asyncio.Task[None]] = []- self._claude_update = _IntegrationUpdate()- self._desktop_update = _IntegrationUpdate()- self._codex_update = _IntegrationUpdate()- self._jetbrains_update = _IntegrationUpdate()- self._vscode_update = _IntegrationUpdate()- self._vscode_dirty = Falseself._http_ready = asyncio.Event()- self._messaging_state = (- "disabled" if self.settings.messaging_platform == "none" else "starting"+ self._integrations = IntegrationService(+ provider_manager,+ config_lock=self._config_lock,+ is_draining=lambda: self._draining,+ has_pending_restart=lambda: bool(self._pending_fields),+ )+ self._messaging = MessagingService(+ settings=provider_manager.current_settings,+ database=database,+ http_ready=self._http_ready,+ is_draining=lambda: self._draining,+ transcriber=transcriber,+ transcriber_factory=transcriber_factory,)- self._messaging_error: str | None = None@propertydef settings(self) -> Settings:@@ -266,38 +177,22 @@ class ApplicationRuntime:)self.provider_manager.start_model_list_refresh()self.provider_manager.set_catalog_changed_callback(- self._queue_vscode_refresh+ self._integrations.catalog_changed)- self._queue_vscode_refresh()- await self.refresh_claude_vscode()- await self.refresh_codex_integration()- await self.refresh_claude_desktop()- await self.refresh_jetbrains_acp()+ await self._integrations.start()self._startup_tasks.append(asyncio.create_task(run_sync_owned(remove_retired_chat_history),name="fcc-retired-chat-cleanup",))- if self._database is not None:- self._messaging_state = "starting"- self._messaging_import_task = asyncio.create_task(- self._initialize_messaging_storage(),- name="fcc-messaging-import",- )- self._startup_tasks.append(self._messaging_import_task)+ self._messaging.start()if self._code_service is not None:self._startup_tasks.append(asyncio.create_task(self._code_service.start(), name="fcc-code-startup"))- self._startup_tasks.append(- asyncio.create_task(- self._start_messaging_if_configured(),- name="fcc-messaging-startup",- )- )self._started = Trueexcept asyncio.CancelledError:await self.close()@@ -333,9 +228,13 @@ class ApplicationRuntime:if self._closed:return Truelogger.info("Shutdown requested, cleaning up...")+ self._integrations.cancel_background_tasks()+ self._messaging.cancel_background_tasks()for task in self._startup_tasks:if not task.done():task.cancel()+ await self._integrations.wait_background_tasks()+ await self._messaging.wait_background_tasks()results = await asyncio.gather(*self._startup_tasks, return_exceptions=True)for result in results:if isinstance(result, Exception):@@ -457,415 +356,64 @@ class ApplicationRuntime:return await self._configuration.admin_values()async def vscode_chat_status(self) -> JsonObject:- return await self._vscode_chat("status")+ return await self._integrations.vscode_chat_status()async def connect_vscode_chat(self) -> JsonObject:- return await self._vscode_chat("connect")+ return await self._integrations.connect_vscode_chat()async def disconnect_vscode_chat(self) -> JsonObject:- return await self._vscode_chat("disconnect")+ return await self._integrations.disconnect_vscode_chat()async def refresh_vscode_chat(self) -> JsonObject:- self._check_integration_available()- self._queue_vscode_refresh()- return {"update": self._vscode_update.snapshot()}-- def _queue_vscode_refresh(self) -> None:- if self._draining:- return- self._vscode_dirty = True- update = self._vscode_update- if update.task is not None and not update.task.done():- return- update.state, update.changed, update.message = "starting", False, None-- async def drain() -> None:- while self._vscode_dirty:- self._vscode_dirty = False- try:- result = await self._vscode_chat("refresh")- update.complete(update.changed or result.get("changed") is True)- except ApplicationError as exc:- update.state, update.message = "failed", exc.message- except Exception as exc:- update.state = "failed"- update.message = "Could not update VS Code models. Retry shortly."- logger.warning(- "VS Code integration update failed: exc_type={}",- type(exc).__name__,- )- if self._vscode_dirty:- update.state = "starting"-- update.task = asyncio.create_task(drain(), name="fcc-vscode-models")- self._startup_tasks.append(update.task)- update.task.add_done_callback(self._startup_tasks.remove)-- async def _vscode_chat(self, action: IntegrationAction) -> JsonObject:- try:- if action == "refresh":- async with self._config_lock:- self._check_integration_available()- status = await run_sync_owned(- lambda: vscode_chat_integration.status(- vscode_chat_integration.config_path()- )- )- if not status["connected"]:- return {"changed": False}- while True:- snapshot = (- await self.provider_manager.wait_for_catalog()- if action in {"connect", "refresh"}- else None- )- revision = self.provider_manager.catalog_status()["catalog_revision"]- async with self._config_lock:- self._check_integration_available()- if snapshot is not None and (- snapshot.current_settings() is not self.settings- or revision- != self.provider_manager.catalog_status()["catalog_revision"]- or self.provider_manager.catalog_status()["catalog"] != "ready"- ):- continue- catalog = (- read_model_catalog(snapshot) if snapshot is not None else None- )- settings = self.settings-- def operate(- catalog: ModelCatalog | None = catalog,- settings: Settings = settings,- ) -> JsonObject:- path = vscode_chat_integration.config_path()- changed = False- if action == "disconnect":- vscode_chat_integration.disconnect(path)- elif catalog is not None:- changed = vscode_chat_integration.configure(- path,- local_proxy_root_url(settings),- settings.proxy_auth_token,- catalog.models,- only_existing=action == "refresh",- )- if action == "refresh":- return {"changed": changed}- return vscode_chat_integration.status(path)-- result = await run_sync_owned(operate)- if action in {"connect", "disconnect"}:- self._vscode_update.complete()- if action == "status":- result["update"] = self._vscode_update.snapshot()- return result- except ValueError, UnicodeError:- raise InvalidRequestError(- "Could not configure VS Code Chat. Check chatLanguageModels.json for invalid JSON or conflicting FCC groups."- ) from None- except OSError:- raise ApplicationUnavailableError(- "Could not access chatLanguageModels.json. Finish configuration edits, check file permissions, and retry."- ) from None+ return await self._integrations.refresh_vscode_chat()async def claude_vscode_status(self) -> JsonObject:- return await self._claude_vscode("status")+ return await self._integrations.claude_vscode_status()async def connect_claude_vscode(self) -> JsonObject:- return await self._claude_vscode("connect")+ return await self._integrations.connect_claude_vscode()async def disconnect_claude_vscode(self) -> JsonObject:- return await self._claude_vscode("disconnect")-- def _check_integration_available(self) -> None:- if self._draining or self._pending_fields:- raise ApplicationUnavailableError(- "Wait for FCC to restart before changing the integration."- )-- def _start_integration_update(- self,- update: _IntegrationUpdate,- operation: Callable[[], Awaitable[JsonObject]],- ) -> JsonObject:- self._check_integration_available()- if update.task is None or update.task.done():- update.state, update.changed, update.message = "starting", False, None-- async def run() -> None:- try:- result = await operation()- update.complete(result.get("changed") is True)- except ApplicationError as exc:- update.state, update.message = "failed", exc.message- except Exception as exc:- update.state = "failed"- update.message = (- "Could not update integration settings. Retry shortly."- )- logger.warning(- "Integration update failed: exc_type={}", type(exc).__name__- )-- update.task = asyncio.create_task(run(), name="fcc-integration-update")- self._startup_tasks.append(update.task)- update.task.add_done_callback(self._startup_tasks.remove)- return {"update": update.snapshot()}+ return await self._integrations.disconnect_claude_vscode()async def refresh_claude_vscode(self) -> JsonObject:- return self._start_integration_update(- self._claude_update, partial(self._claude_vscode, "refresh")- )+ return await self._integrations.refresh_claude_vscode()async def refresh_codex_integration(self) -> JsonObject:- return self._start_integration_update(- self._codex_update, partial(self._codex_integration, "refresh")- )+ return await self._integrations.refresh_codex_integration()async def jetbrains_acp_status(self) -> JsonObject:- return await self._jetbrains_acp("status")+ return await self._integrations.jetbrains_acp_status()async def connect_jetbrains_acp(self) -> JsonObject:- return await self._jetbrains_acp("connect")+ return await self._integrations.connect_jetbrains_acp()async def disconnect_jetbrains_acp(self) -> JsonObject:- return await self._jetbrains_acp("disconnect")+ return await self._integrations.disconnect_jetbrains_acp()async def refresh_jetbrains_acp(self) -> JsonObject:- return self._start_integration_update(- self._jetbrains_update, partial(self._jetbrains_acp, "refresh")- )-- async def _jetbrains_acp(self, action: IntegrationAction) -> JsonObject:- async with self._config_lock:- self._check_integration_available()- settings = self.settings-- def operate() -> JsonObject:- path = jetbrains_acp_integration.config_path()- url = local_proxy_root_url(settings)- if action == "refresh":- return {- "changed": jetbrains_acp_integration.refresh_connected(- path, url, settings.proxy_auth_token- )- }- return jetbrains_acp_integration.configure(- path,- url,- settings.proxy_auth_token,- None if action == "status" else action == "connect",- )-- try:- result = await run_sync_owned(operate)- except jetbrains_acp_integration.SetupError as exc:- raise InvalidRequestError(str(exc)) from None- except ValueError, UnicodeError:- raise InvalidRequestError(- "Could not read JetBrains ACP configuration. Check the JSON in acp.json and the installed Claude Agent metadata."- ) from None- except OSError:- raise ApplicationUnavailableError(- "Could not access JetBrains ACP files. Finish any configuration edits, check file permissions, and retry."- ) from None- if action in {"connect", "disconnect"}:- self._jetbrains_update.complete()- if action == "status":- result["update"] = self._jetbrains_update.snapshot()- return result+ return await self._integrations.refresh_jetbrains_acp()async def claude_desktop_status(self) -> JsonObject:- return await self._claude_desktop("status")+ return await self._integrations.claude_desktop_status()async def connect_claude_desktop(self) -> JsonObject:- return await self._claude_desktop("connect")+ return await self._integrations.connect_claude_desktop()async def disconnect_claude_desktop(self) -> JsonObject:- return await self._claude_desktop("disconnect")+ return await self._integrations.disconnect_claude_desktop()async def refresh_claude_desktop(self) -> JsonObject:- return self._start_integration_update(- self._desktop_update, partial(self._claude_desktop, "refresh")- )-- async def _claude_desktop(self, action: IntegrationAction) -> JsonObject:- async with self._config_lock:- self._check_integration_available()- settings = self.settings-- def operate() -> JsonObject:- root = claude_desktop_integration.config_root()- url = local_proxy_root_url(settings)- if action == "refresh":- return {- "changed": claude_desktop_integration.refresh_connected(- root,- url,- settings.proxy_auth_token,- disconnect_path=claude_desktop_disconnect_path(),- )- }- return claude_desktop_integration.configure(- root,- url,- settings.proxy_auth_token,- None if action == "status" else action == "connect",- disconnect_path=claude_desktop_disconnect_path(),- )-- try:- result = await run_sync_owned(operate)- except claude_desktop_integration.ManagedDesktopError:- raise InvalidRequestError(- "Claude Desktop is managed by an organization, or its policy could not be read. FCC can configure only unmanaged Desktop installations."- ) from None- except claude_desktop_integration.PendingDisconnectError:- raise InvalidRequestError(- "Finish disconnecting Claude Desktop before connecting again."- ) from None- except claude_desktop_integration.PendingMigrationError:- raise InvalidRequestError(- "Claude Desktop has data in its previous Windows location. Launch Claude Desktop once so it can migrate that data, fully quit it, then retry Connect."- ) from None- except ValueError, UnicodeError:- raise InvalidRequestError(- "Could not configure Claude Desktop. Check its configuration JSON and FCC disconnect record, and ensure FCC uses a localhost address and a nonempty managed token."- ) from None- except OSError:- raise ApplicationUnavailableError(- "Could not access Claude Desktop settings or the FCC disconnect record. Fully quit Claude Desktop, check file permissions, and retry."- ) from None- if action in {"connect", "disconnect"}:- self._desktop_update.complete()- if action == "status":- if self._desktop_update.state != "ready":- result["connected"] = None- result["update"] = self._desktop_update.snapshot()- return result-- async def _claude_vscode(self, action: IntegrationAction) -> JsonObject:- async with self._config_lock:- self._check_integration_available()- settings = self.settings-- def operate() -> JsonObject:- path = claude_integration.settings_path()- state_path = claude_integration.claude_state_path()- if action == "status" and self._claude_update.state != "ready":- return {- "connected": None,- "paths": {- "vscode_settings": str(path.resolve()),- "claude_state": str(state_path.resolve()),- },- }- if action == "refresh":- return {- "changed": claude_integration.refresh_connected(- path,- state_path,- local_proxy_root_url(settings),- settings.proxy_auth_token,- )- }- return claude_integration.configure(- path,- state_path,- local_proxy_root_url(settings),- settings.proxy_auth_token,- None if action == "status" else action == "connect",- )-- try:- result = await run_sync_owned(operate)- except ValueError, UnicodeError:- raise InvalidRequestError(- "Could not read Claude integration settings. Check the JSON in VS Code settings.json and .claude.json."- ) from None- except OSError:- raise ApplicationUnavailableError(- "Could not access VS Code settings.json or .claude.json. Check file permissions and try again."- ) from None- if action in {"connect", "disconnect"}:- self._claude_update.complete()- if action == "status":- result["update"] = self._claude_update.snapshot()- return result+ return await self._integrations.refresh_claude_desktop()async def codex_integration_status(self) -> JsonObject:- return await self._codex_integration("status")+ return await self._integrations.codex_integration_status()async def connect_codex(self) -> JsonObject:- return await self._codex_integration("connect")+ return await self._integrations.connect_codex()async def disconnect_codex(self) -> JsonObject:- return await self._codex_integration("disconnect")-- async def _codex_integration(self, action: IntegrationAction) -> JsonObject:- wait = InitializationWait(None) if action == "refresh" else InitializationWait()- needs_catalog = action in {"connect", "refresh"}- try:- if action == "refresh":- async with self._config_lock:- self._check_integration_available()- url = local_proxy_root_url(self.settings)- if not await run_sync_owned(- lambda: codex_integration.recognizes_connection(- codex_integration.config_path(), url- )- ):- return {"changed": False}- while True:- generation_id = (- await self.provider_manager.wait_for_catalog_file(wait)- if needs_catalog- else None- )- async with self._config_lock:- self._check_integration_available()- if needs_catalog and (- generation_id != self.provider_manager.current_generation_id- or self.provider_manager.catalog_status()["catalog"] != "ready"- ):- continue- url = local_proxy_root_url(self.settings)-- def operate(url: str = url) -> JsonObject:- path = codex_integration.config_path()- if action == "status" and self._codex_update.state != "ready":- return {- "connected": None,- "paths": {"codex_config": str(path.resolve())},- }- if action == "refresh":- return {- "changed": codex_integration.refresh_connected(- path, codex_model_catalog_path(), url- )- }- return codex_integration.configure(- path,- codex_model_catalog_path(),- url,- None if action == "status" else action == "connect",- )-- result = await run_sync_owned(operate)- if action in {"connect", "disconnect"}:- self._codex_update.complete()- if action == "status":- result["update"] = self._codex_update.snapshot()- return result- except ValueError, UnicodeError:- raise InvalidRequestError(- "Could not read Codex settings. Check the TOML in config.toml."- ) from None- except OSError:- raise ApplicationUnavailableError(- "Could not access Codex config.toml. Check file permissions and try again."- ) from None+ return await self._integrations.disconnect_codex()async def admin_status(self) -> JsonObject:values = await self.admin_values()@@ -878,18 +426,8 @@ class ApplicationRuntime:"code": self._code_service.storage_status()if self._code_serviceelse {"state": "disabled"},- "messaging": {- "state": self._messaging_state,- "message": self._messaging_error,- "warning": self._messaging_warning,- },- "integrations": {- "vscode-chat": self._vscode_update.snapshot(),- "claude-vscode": self._claude_update.snapshot(),- "claude-desktop": self._desktop_update.snapshot(),- "codex": self._codex_update.snapshot(),- "jetbrains-acp": self._jetbrains_update.snapshot(),- },+ "messaging": self._messaging.snapshot(),+ "integrations": self._integrations.snapshot(),},"host": settings.host,"port": settings.port,@@ -990,13 +528,7 @@ class ApplicationRuntime:return Trueasync def stop_all(self) -> StopResult | None:- if self._messaging_workflow is not None:- outcome = await self._messaging_workflow.stop_all_tasks()- return StopResult(cancelled_count=outcome.cancelled_count)- if self._cli_manager is not None:- await self._cli_manager.stop_all()- return StopResult(source="cli_manager")- return None+ return await self._messaging.stop_all()async def _commit_admin_update(self,@@ -1023,167 +555,10 @@ class ApplicationRuntime:result["instance_id"] = self._instance_idreturn result- async def _start_messaging_if_configured(self) -> None:- if self._messaging_import_task is not None:- await asyncio.shield(self._messaging_import_task)- if self.settings.messaging_platform == "none":- self._messaging_state = "disabled"- return- try:-- def load_modules() -> None:- for name in ("cli.managed", "messaging.workflow"):- importlib.import_module(f"free_claude_code.{name}")- importlib.import_module(- f"free_claude_code.messaging.platforms.{self.settings.messaging_platform}"- )-- await run_sync_owned(load_modules)- if self._transcriber_factory is not None:- self._transcriber = await self._transcriber_factory(self.settings)- components = messaging_platform_factory.create_messaging_components(- self.settings.messaging_platform,- self._messaging_options(),- )- if components is not None:- await self._start_messaging_workflow(components)- self._messaging_state = "ready"- else:- self._messaging_state = "disabled"- except ImportError as exc:- self._messaging_state = "failed"- self._messaging_error = (- "Messaging could not start. Check its configuration and restart FCC."- )- cleaned = await self._cleanup_messaging()- if self.settings.log_api_error_tracebacks:- logger.warning("Messaging module import error: {}", exc)- else:- logger.warning(- "Messaging module import error: exc_type={}",- type(exc).__name__,- )- if not cleaned:- raise RuntimeError("Messaging startup cleanup incomplete") from exc- except Exception as exc:- self._messaging_state = "failed"- self._messaging_error = (- "Messaging could not start. Check its configuration and restart FCC."- )- cleaned = await self._cleanup_messaging()- if self.settings.log_api_error_tracebacks:- logger.error("Failed to start messaging platform: {}", exc)- logger.error(traceback.format_exc())- else:- logger.error(- "Failed to start messaging platform: exc_type={}",- type(exc).__name__,- )- if not cleaned:- raise RuntimeError("Messaging startup cleanup incomplete") from exc-- def _messaging_options(self) -> MessagingPlatformOptions:- settings = self.settings- return MessagingPlatformOptions(- telegram_bot_token=settings.telegram_bot_token,- allowed_telegram_user_id=settings.allowed_telegram_user_id,- telegram_proxy_url=settings.telegram_proxy_url,- discord_bot_token=settings.discord_bot_token,- allowed_discord_channels=settings.allowed_discord_channels,- transcriber=self._transcriber,- messaging_rate_limit=settings.messaging_rate_limit,- messaging_rate_window=settings.messaging_rate_window,- log_raw_messaging_content=settings.log_raw_messaging_content,- log_messaging_error_details=settings.log_messaging_error_details,- log_api_error_tracebacks=settings.log_api_error_tracebacks,- )-- async def _initialize_messaging_storage(self) -> None:- if self._database is None:- return- try:- await self._database.start()- from .messaging_import import import_legacy- from .messaging_sqlite import SQLiteMessagingStore-- self._messaging_store = SQLiteMessagingStore(- self._database,- managed_message_cap=self.settings.max_message_log_entries_per_chat,- )- self._messaging_warning = await import_legacy(- self._database, Path(messaging_state_dir_path()) / "sessions.json"- )- await self._messaging_store.trim()- except Exception as exc:- self._messaging_storage_error = exc- logger.error(- "Messaging storage initialization failed: {}", type(exc).__name__- )- return- if self._messaging_warning:- logger.warning("{}", self._messaging_warning)-- async def _start_messaging_workflow(- self,- components: MessagingPlatformComponents,- ) -> None:- import free_claude_code.cli.managed as cli_managed- import free_claude_code.messaging.workflow as messaging_workflow_module-- settings = self.settings- self._messaging_runtime = components.runtime- workspace = (- os.path.abspath(settings.allowed_dir)- if settings.allowed_dir- else os.getcwd()- )- await run_sync_owned(partial(os.makedirs, workspace, exist_ok=True))- allowed_dirs = [workspace] if settings.allowed_dir else []-- self._cli_manager = cli_managed.ManagedClaudeSessionManager(- workspace_path=workspace,- proxy_root_url=local_proxy_root_url(settings),- allowed_dirs=allowed_dirs,- auth_token=settings.proxy_auth_token,- log_raw_cli_diagnostics=settings.log_raw_cli_diagnostics,- log_messaging_error_details=settings.log_messaging_error_details,- )- if self._messaging_import_task is not None:- await asyncio.shield(self._messaging_import_task)- if self._messaging_storage_error is not None:- raise ApplicationUnavailableError(- "Messaging storage is unavailable."- ) from self._messaging_storage_error- if self._messaging_store is None:- raise ApplicationUnavailableError("Messaging storage is unavailable.")- session_store = self._messaging_store- workflow = messaging_workflow_module.MessagingWorkflow(- platform_name=components.name,- outbound=components.outbound,- voice_cancellation=components.voice_cancellation,- cli_manager=self._cli_manager,- session_store=session_store,- debug_platform_edits=settings.debug_platform_edits,- debug_subagent_stack=settings.debug_subagent_stack,- log_raw_cli_diagnostics=settings.log_raw_cli_diagnostics,- log_messaging_error_details=settings.log_messaging_error_details,- )- self._messaging_workflow = workflow- await workflow.restore()- components.runtime.on_message(workflow.handle_message)- await self._http_ready.wait()- if self._draining:- return- await components.runtime.start()- await workflow.repair_restored_statuses()- if components.startup_notice is not None:- await workflow.publish_startup_notice(components.startup_notice)- logger.info("{} platform started with messaging workflow", components.name)-async def _close_owned_resources(self) -> bool:if not await best_effort("folder_picker.close", self._folder_picker.close()):return False- if not await self._cleanup_messaging():+ if not await self._messaging.close_delivery():return Falseverbose = self.settings.log_api_error_tracebacksif self._code_service is not None and not await best_effort(@@ -1196,7 +571,7 @@ class ApplicationRuntime:"database.close", self._database.close()):return False- if not await self._cleanup_transcriber():+ if not await self._messaging.close_transcriber():return Falseif not self._provider_manager_closed:self._provider_manager_closed = await best_effort(@@ -1228,70 +603,3 @@ class ApplicationRuntime:f"Provider {provider_id!r} does not support connected-account login.")return manager-- async def _cleanup_messaging(self) -> bool:- verbose = self.settings.log_api_error_tracebacks- workflow = self._messaging_workflow- runtime = self._messaging_runtime- cli_manager = self._cli_manager-- if runtime is not None:- quiesced = await best_effort(- "messaging_runtime.quiesce",- runtime.quiesce(),- log_verbose_errors=verbose,- )- if not quiesced:- # Delivery must remain available until ingress is known stopped.- # Retaining the graph lets the next close retry this exact gate.- return False-- if workflow is not None:- closed = await best_effort(- "messaging_workflow.close",- workflow.close(),- log_verbose_errors=verbose,- )- if not closed:- # Active workflow tasks may still need delivery, transcription,- # CLI sessions, and providers while a later close retries drain.- return False- if self._messaging_workflow is workflow:- self._messaging_workflow = None- if self._cli_manager is cli_manager:- self._cli_manager = None- elif cli_manager is not None:- drained = await best_effort(- "cli_manager.stop_all",- cli_manager.stop_all(),- log_verbose_errors=verbose,- )- if not drained:- return False- if self._cli_manager is cli_manager:- self._cli_manager = None-- if runtime is not None:- closed = await best_effort(- "messaging_runtime.close",- runtime.close(),- log_verbose_errors=verbose,- )- if not closed:- return False- if self._messaging_runtime is runtime:- self._messaging_runtime = None- return True-- async def _cleanup_transcriber(self) -> bool:- transcriber = self._transcriber- if transcriber is None:- return True- closed = await best_effort(- "transcriber.close",- transcriber.close(),- log_verbose_errors=self.settings.log_api_error_tracebacks,- )- if closed and self._transcriber is transcriber:- self._transcriber = None- return closeddiff --git a/src/free_claude_code/runtime/integration_service.py b/src/free_claude_code/runtime/integration_service.pynew file mode 100644index 00000000..d6e3ffea--- /dev/null+++ b/src/free_claude_code/runtime/integration_service.py@@ -0,0 +1,524 @@+"""Own integration workflows while sharing configuration publication ordering."""++import asyncio+from collections.abc import Awaitable, Callable+from dataclasses import dataclass+from functools import partial+from typing import Literal++from loguru import logger++from free_claude_code.application.errors import (+ ApplicationError,+ ApplicationUnavailableError,+ InvalidRequestError,+)+from free_claude_code.application.model_catalog import ModelCatalog, read_model_catalog+from free_claude_code.application.readiness import InitializationWait+from free_claude_code.config.paths import (+ claude_desktop_disconnect_path,+ codex_model_catalog_path,+)+from free_claude_code.config.server_urls import local_proxy_root_url+from free_claude_code.config.settings import Settings+from free_claude_code.core.async_tasks import run_sync_owned+from free_claude_code.core.json_types import JsonObject+from free_claude_code.harnesses import (+ claude_desktop_integration,+ claude_integration,+ codex_integration,+ jetbrains_acp_integration,+ vscode_chat_integration,+)++from .provider_manager import ProviderRuntimeManager++IntegrationAction = Literal["status", "connect", "disconnect", "refresh"]+++@dataclass+class _IntegrationUpdate:+ state: Literal["starting", "ready", "failed"] = "ready"+ changed: bool = False+ message: str | None = None+ task: asyncio.Task[None] | None = None++ def snapshot(self) -> JsonObject:+ return {"state": self.state, "changed": self.changed, "message": self.message}++ def complete(self, changed: bool = False) -> None:+ self.state = "ready"+ self.changed = changed+ self.message = None+++class IntegrationService:+ """Own integration state and background refreshes, borrowing runtime resources."""++ def __init__(+ self,+ provider_manager: ProviderRuntimeManager,+ *,+ config_lock: asyncio.Lock,+ is_draining: Callable[[], bool],+ has_pending_restart: Callable[[], bool],+ ) -> None:+ self.provider_manager = provider_manager+ self._config_lock = config_lock+ self._is_draining = is_draining+ self._has_pending_restart = has_pending_restart+ self._claude_update = _IntegrationUpdate()+ self._desktop_update = _IntegrationUpdate()+ self._codex_update = _IntegrationUpdate()+ self._jetbrains_update = _IntegrationUpdate()+ self._vscode_update = _IntegrationUpdate()+ self._vscode_dirty = False++ @property+ def settings(self) -> Settings:+ return self.provider_manager.current_settings()++ def _updates(self) -> dict[str, _IntegrationUpdate]:+ return {+ "vscode-chat": self._vscode_update,+ "claude-vscode": self._claude_update,+ "claude-desktop": self._desktop_update,+ "codex": self._codex_update,+ "jetbrains-acp": self._jetbrains_update,+ }++ def snapshot(self) -> JsonObject:+ return {name: update.snapshot() for name, update in self._updates().items()}++ async def start(self) -> None:+ self.catalog_changed()+ await self.refresh_claude_vscode()+ await self.refresh_codex_integration()+ await self.refresh_claude_desktop()+ await self.refresh_jetbrains_acp()++ def cancel_background_tasks(self) -> None:+ for update in self._updates().values():+ if update.task is not None and not update.task.done():+ update.task.cancel()++ async def wait_background_tasks(self) -> None:+ tasks = tuple(+ update.task+ for update in self._updates().values()+ if update.task is not None+ )+ results = await asyncio.gather(*tasks, return_exceptions=True)+ for result in results:+ if isinstance(result, Exception):+ logger.warning(+ "Background initialization ended with exc_type={}",+ type(result).__name__,+ )++ async def vscode_chat_status(self) -> JsonObject:+ return await self._vscode_chat("status")++ async def connect_vscode_chat(self) -> JsonObject:+ return await self._vscode_chat("connect")++ async def disconnect_vscode_chat(self) -> JsonObject:+ return await self._vscode_chat("disconnect")++ async def refresh_vscode_chat(self) -> JsonObject:+ self._check_integration_available()+ self.catalog_changed()+ return {"update": self._vscode_update.snapshot()}++ def catalog_changed(self) -> None:+ if self._is_draining():+ return+ self._vscode_dirty = True+ update = self._vscode_update+ if update.task is not None and not update.task.done():+ return+ update.state, update.changed, update.message = "starting", False, None++ async def drain() -> None:+ while self._vscode_dirty:+ self._vscode_dirty = False+ try:+ result = await self._vscode_chat("refresh")+ update.complete(update.changed or result.get("changed") is True)+ except ApplicationError as exc:+ update.state, update.message = "failed", exc.message+ except Exception as exc:+ update.state = "failed"+ update.message = "Could not update VS Code models. Retry shortly."+ logger.warning(+ "VS Code integration update failed: exc_type={}",+ type(exc).__name__,+ )+ if self._vscode_dirty:+ update.state = "starting"++ update.task = asyncio.create_task(drain(), name="fcc-vscode-models")++ async def _vscode_chat(self, action: IntegrationAction) -> JsonObject:+ try:+ if action == "refresh":+ async with self._config_lock:+ self._check_integration_available()+ status = await run_sync_owned(+ lambda: vscode_chat_integration.status(+ vscode_chat_integration.config_path()+ )+ )+ if not status["connected"]:+ return {"changed": False}+ while True:+ snapshot = (+ await self.provider_manager.wait_for_catalog()+ if action in {"connect", "refresh"}+ else None+ )+ revision = self.provider_manager.catalog_status()["catalog_revision"]+ async with self._config_lock:+ self._check_integration_available()+ if snapshot is not None and (+ snapshot.current_settings() is not self.settings+ or revision+ != self.provider_manager.catalog_status()["catalog_revision"]+ or self.provider_manager.catalog_status()["catalog"] != "ready"+ ):+ continue+ catalog = (+ read_model_catalog(snapshot) if snapshot is not None else None+ )+ settings = self.settings++ def operate(+ catalog: ModelCatalog | None = catalog,+ settings: Settings = settings,+ ) -> JsonObject:+ path = vscode_chat_integration.config_path()+ changed = False+ if action == "disconnect":+ vscode_chat_integration.disconnect(path)+ elif catalog is not None:+ changed = vscode_chat_integration.configure(+ path,+ local_proxy_root_url(settings),+ settings.proxy_auth_token,+ catalog.models,+ only_existing=action == "refresh",+ )+ if action == "refresh":+ return {"changed": changed}+ return vscode_chat_integration.status(path)++ result = await run_sync_owned(operate)+ if action in {"connect", "disconnect"}:+ self._vscode_update.complete()+ if action == "status":+ result["update"] = self._vscode_update.snapshot()+ return result+ except ValueError, UnicodeError:+ raise InvalidRequestError(+ "Could not configure VS Code Chat. Check chatLanguageModels.json for invalid JSON or conflicting FCC groups."+ ) from None+ except OSError:+ raise ApplicationUnavailableError(+ "Could not access chatLanguageModels.json. Finish configuration edits, check file permissions, and retry."+ ) from None++ async def claude_vscode_status(self) -> JsonObject:+ return await self._claude_vscode("status")++ async def connect_claude_vscode(self) -> JsonObject:+ return await self._claude_vscode("connect")++ async def disconnect_claude_vscode(self) -> JsonObject:+ return await self._claude_vscode("disconnect")++ def _check_integration_available(self) -> None:+ if self._is_draining() or self._has_pending_restart():+ raise ApplicationUnavailableError(+ "Wait for FCC to restart before changing the integration."+ )++ def _start_integration_update(+ self,+ update: _IntegrationUpdate,+ operation: Callable[[], Awaitable[JsonObject]],+ ) -> JsonObject:+ self._check_integration_available()+ if update.task is None or update.task.done():+ update.state, update.changed, update.message = "starting", False, None++ async def run() -> None:+ try:+ result = await operation()+ update.complete(result.get("changed") is True)+ except ApplicationError as exc:+ update.state, update.message = "failed", exc.message+ except Exception as exc:+ update.state = "failed"+ update.message = (+ "Could not update integration settings. Retry shortly."+ )+ logger.warning(+ "Integration update failed: exc_type={}", type(exc).__name__+ )++ update.task = asyncio.create_task(run(), name="fcc-integration-update")+ return {"update": update.snapshot()}++ async def refresh_claude_vscode(self) -> JsonObject:+ return self._start_integration_update(+ self._claude_update, partial(self._claude_vscode, "refresh")+ )++ async def refresh_codex_integration(self) -> JsonObject:+ return self._start_integration_update(+ self._codex_update, partial(self._codex_integration, "refresh")+ )++ async def jetbrains_acp_status(self) -> JsonObject:+ return await self._jetbrains_acp("status")++ async def connect_jetbrains_acp(self) -> JsonObject:+ return await self._jetbrains_acp("connect")++ async def disconnect_jetbrains_acp(self) -> JsonObject:+ return await self._jetbrains_acp("disconnect")++ async def refresh_jetbrains_acp(self) -> JsonObject:+ return self._start_integration_update(+ self._jetbrains_update, partial(self._jetbrains_acp, "refresh")+ )++ async def _jetbrains_acp(self, action: IntegrationAction) -> JsonObject:+ async with self._config_lock:+ self._check_integration_available()+ settings = self.settings++ def operate() -> JsonObject:+ path = jetbrains_acp_integration.config_path()+ url = local_proxy_root_url(settings)+ if action == "refresh":+ return {+ "changed": jetbrains_acp_integration.refresh_connected(+ path, url, settings.proxy_auth_token+ )+ }+ return jetbrains_acp_integration.configure(+ path,+ url,+ settings.proxy_auth_token,+ None if action == "status" else action == "connect",+ )++ try:+ result = await run_sync_owned(operate)+ except jetbrains_acp_integration.SetupError as exc:+ raise InvalidRequestError(str(exc)) from None+ except ValueError, UnicodeError:+ raise InvalidRequestError(+ "Could not read JetBrains ACP configuration. Check the JSON in acp.json and the installed Claude Agent metadata."+ ) from None+ except OSError:+ raise ApplicationUnavailableError(+ "Could not access JetBrains ACP files. Finish any configuration edits, check file permissions, and retry."+ ) from None+ if action in {"connect", "disconnect"}:+ self._jetbrains_update.complete()+ if action == "status":+ result["update"] = self._jetbrains_update.snapshot()+ return result++ async def claude_desktop_status(self) -> JsonObject:+ return await self._claude_desktop("status")++ async def connect_claude_desktop(self) -> JsonObject:+ return await self._claude_desktop("connect")++ async def disconnect_claude_desktop(self) -> JsonObject:+ return await self._claude_desktop("disconnect")++ async def refresh_claude_desktop(self) -> JsonObject:+ return self._start_integration_update(+ self._desktop_update, partial(self._claude_desktop, "refresh")+ )++ async def _claude_desktop(self, action: IntegrationAction) -> JsonObject:+ async with self._config_lock:+ self._check_integration_available()+ settings = self.settings++ def operate() -> JsonObject:+ root = claude_desktop_integration.config_root()+ url = local_proxy_root_url(settings)+ if action == "refresh":+ return {+ "changed": claude_desktop_integration.refresh_connected(+ root,+ url,+ settings.proxy_auth_token,+ disconnect_path=claude_desktop_disconnect_path(),+ )+ }+ return claude_desktop_integration.configure(+ root,+ url,+ settings.proxy_auth_token,+ None if action == "status" else action == "connect",+ disconnect_path=claude_desktop_disconnect_path(),+ )++ try:+ result = await run_sync_owned(operate)+ except claude_desktop_integration.ManagedDesktopError:+ raise InvalidRequestError(+ "Claude Desktop is managed by an organization, or its policy could not be read. FCC can configure only unmanaged Desktop installations."+ ) from None+ except claude_desktop_integration.PendingDisconnectError:+ raise InvalidRequestError(+ "Finish disconnecting Claude Desktop before connecting again."+ ) from None+ except claude_desktop_integration.PendingMigrationError:+ raise InvalidRequestError(+ "Claude Desktop has data in its previous Windows location. Launch Claude Desktop once so it can migrate that data, fully quit it, then retry Connect."+ ) from None+ except ValueError, UnicodeError:+ raise InvalidRequestError(+ "Could not configure Claude Desktop. Check its configuration JSON and FCC disconnect record, and ensure FCC uses a localhost address and a nonempty managed token."+ ) from None+ except OSError:+ raise ApplicationUnavailableError(+ "Could not access Claude Desktop settings or the FCC disconnect record. Fully quit Claude Desktop, check file permissions, and retry."+ ) from None+ if action in {"connect", "disconnect"}:+ self._desktop_update.complete()+ if action == "status":+ if self._desktop_update.state != "ready":+ result["connected"] = None+ result["update"] = self._desktop_update.snapshot()+ return result++ async def _claude_vscode(self, action: IntegrationAction) -> JsonObject:+ async with self._config_lock:+ self._check_integration_available()+ settings = self.settings++ def operate() -> JsonObject:+ path = claude_integration.settings_path()+ state_path = claude_integration.claude_state_path()+ if action == "status" and self._claude_update.state != "ready":+ return {+ "connected": None,+ "paths": {+ "vscode_settings": str(path.resolve()),+ "claude_state": str(state_path.resolve()),+ },+ }+ if action == "refresh":+ return {+ "changed": claude_integration.refresh_connected(+ path,+ state_path,+ local_proxy_root_url(settings),+ settings.proxy_auth_token,+ )+ }+ return claude_integration.configure(+ path,+ state_path,+ local_proxy_root_url(settings),+ settings.proxy_auth_token,+ None if action == "status" else action == "connect",+ )++ try:+ result = await run_sync_owned(operate)+ except ValueError, UnicodeError:+ raise InvalidRequestError(+ "Could not read Claude integration settings. Check the JSON in VS Code settings.json and .claude.json."+ ) from None+ except OSError:+ raise ApplicationUnavailableError(+ "Could not access VS Code settings.json or .claude.json. Check file permissions and try again."+ ) from None+ if action in {"connect", "disconnect"}:+ self._claude_update.complete()+ if action == "status":+ result["update"] = self._claude_update.snapshot()+ return result++ async def codex_integration_status(self) -> JsonObject:+ return await self._codex_integration("status")++ async def connect_codex(self) -> JsonObject:+ return await self._codex_integration("connect")++ async def disconnect_codex(self) -> JsonObject:+ return await self._codex_integration("disconnect")++ async def _codex_integration(self, action: IntegrationAction) -> JsonObject:+ wait = InitializationWait(None) if action == "refresh" else InitializationWait()+ needs_catalog = action in {"connect", "refresh"}+ try:+ if action == "refresh":+ async with self._config_lock:+ self._check_integration_available()+ url = local_proxy_root_url(self.settings)+ if not await run_sync_owned(+ lambda: codex_integration.recognizes_connection(+ codex_integration.config_path(), url+ )+ ):+ return {"changed": False}+ while True:+ generation_id = (+ await self.provider_manager.wait_for_catalog_file(wait)+ if needs_catalog+ else None+ )+ async with self._config_lock:+ self._check_integration_available()+ if needs_catalog and (+ generation_id != self.provider_manager.current_generation_id+ or self.provider_manager.catalog_status()["catalog"] != "ready"+ ):+ continue+ url = local_proxy_root_url(self.settings)++ def operate(url: str = url) -> JsonObject:+ path = codex_integration.config_path()+ if action == "status" and self._codex_update.state != "ready":+ return {+ "connected": None,+ "paths": {"codex_config": str(path.resolve())},+ }+ if action == "refresh":+ return {+ "changed": codex_integration.refresh_connected(+ path, codex_model_catalog_path(), url+ )+ }+ return codex_integration.configure(+ path,+ codex_model_catalog_path(),+ url,+ None if action == "status" else action == "connect",+ )++ result = await run_sync_owned(operate)+ if action in {"connect", "disconnect"}:+ self._codex_update.complete()+ if action == "status":+ result["update"] = self._codex_update.snapshot()+ return result+ except ValueError, UnicodeError:+ raise InvalidRequestError(+ "Could not read Codex settings. Check the TOML in config.toml."+ ) from None+ except OSError:+ raise ApplicationUnavailableError(+ "Could not access Codex config.toml. Check file permissions and try again."+ ) from Nonediff --git a/src/free_claude_code/runtime/lifecycle.py b/src/free_claude_code/runtime/lifecycle.pynew file mode 100644index 00000000..d75552d0--- /dev/null+++ b/src/free_claude_code/runtime/lifecycle.py@@ -0,0 +1,38 @@+"""Shared cleanup reporting for runtime resource owners."""++from collections.abc import Awaitable++from loguru import logger+++async def best_effort(+ name: str,+ awaitable: Awaitable[object],+ *,+ log_verbose_errors: bool = False,+) -> bool:+ """Run one cleanup step and report whether it completed.++ The lifecycle owner intentionally applies no generic timeout here. Cancelling+ an arbitrary cleanup at a deadline can abandon a half-closed SDK, thread, or+ provider resource; resource-specific cleanup or the process supervisor owns+ any force-termination deadline.+ """+ try:+ await awaitable+ except Exception as exc:+ if log_verbose_errors:+ logger.warning(+ "Shutdown step failed: {}: {}: {}",+ name,+ type(exc).__name__,+ exc,+ )+ else:+ logger.warning(+ "Shutdown step failed: {}: exc_type={}",+ name,+ type(exc).__name__,+ )+ return False+ return Truediff --git a/src/free_claude_code/runtime/messaging_service.py b/src/free_claude_code/runtime/messaging_service.pynew file mode 100644index 00000000..77e5f319--- /dev/null+++ b/src/free_claude_code/runtime/messaging_service.py@@ -0,0 +1,347 @@+"""Own messaging startup, delivery resources, and their ordered cleanup gates."""++import asyncio+import importlib+import os+import traceback+from collections.abc import Awaitable, Callable+from functools import partial+from pathlib import Path+from typing import TYPE_CHECKING++from loguru import logger++from free_claude_code.application.errors import ApplicationUnavailableError+from free_claude_code.application.ports import StopResult+from free_claude_code.config.paths import messaging_state_dir_path+from free_claude_code.config.server_urls import local_proxy_root_url+from free_claude_code.config.settings import Settings+from free_claude_code.core.async_tasks import run_sync_owned+from free_claude_code.core.json_types import JsonObject+from free_claude_code.messaging.platforms import factory as messaging_platform_factory+from free_claude_code.messaging.platforms.factory import MessagingPlatformOptions+from free_claude_code.messaging.platforms.ports import (+ MessagingPlatformComponents,+ MessagingRuntime,+)+from free_claude_code.messaging.voice import Transcriber++from .lifecycle import best_effort+from .sqlite_database import SQLiteDatabase++if TYPE_CHECKING:+ import free_claude_code.cli.managed as cli_managed+ import free_claude_code.messaging.workflow as messaging_workflow_module++ from .messaging_sqlite import SQLiteMessagingStore+++class MessagingService:+ """Own one messaging graph, borrowing the database and HTTP readiness signal."""++ def __init__(+ self,+ *,+ settings: Callable[[], Settings],+ database: SQLiteDatabase | None,+ http_ready: asyncio.Event,+ is_draining: Callable[[], bool],+ transcriber: Transcriber | None,+ transcriber_factory: Callable[[Settings], Awaitable[Transcriber | None]] | None,+ ) -> None:+ self._settings = settings+ self._database = database+ self._http_ready = http_ready+ self._is_draining = is_draining+ self._transcriber = transcriber+ self._transcriber_factory = transcriber_factory+ self._messaging_store: SQLiteMessagingStore | None = None+ self._messaging_import_task: asyncio.Task[None] | None = None+ self._messaging_warning: str | None = None+ self._messaging_storage_error: Exception | None = None+ self._messaging_runtime: MessagingRuntime | None = None+ self._messaging_workflow: messaging_workflow_module.MessagingWorkflow | None = (+ None+ )+ self._cli_manager: cli_managed.ManagedClaudeSessionManager | None = None+ self._messaging_state = (+ "disabled" if self.settings.messaging_platform == "none" else "starting"+ )+ self._messaging_error: str | None = None+ self._startup_tasks: list[asyncio.Task[None]] = []++ @property+ def settings(self) -> Settings:+ return self._settings()++ def snapshot(self) -> JsonObject:+ return {+ "state": self._messaging_state,+ "message": self._messaging_error,+ "warning": self._messaging_warning,+ }++ def start(self) -> None:+ if self._is_draining():+ raise ApplicationUnavailableError("Application runtime is shutting down.")+ if self._database is not None:+ self._messaging_state = "starting"+ self._messaging_import_task = asyncio.create_task(+ self._initialize_messaging_storage(), name="fcc-messaging-import"+ )+ self._startup_tasks.append(self._messaging_import_task)+ self._startup_tasks.append(+ asyncio.create_task(+ self._start_messaging_if_configured(), name="fcc-messaging-startup"+ )+ )++ def cancel_background_tasks(self) -> None:+ for task in self._startup_tasks:+ if not task.done():+ task.cancel()++ async def wait_background_tasks(self) -> None:+ results = await asyncio.gather(+ *tuple(self._startup_tasks), return_exceptions=True+ )+ for result in results:+ if isinstance(result, Exception):+ logger.warning(+ "Background initialization ended with exc_type={}",+ type(result).__name__,+ )+ self._startup_tasks.clear()++ async def stop_all(self) -> StopResult | None:+ if self._messaging_workflow is not None:+ outcome = await self._messaging_workflow.stop_all_tasks()+ return StopResult(cancelled_count=outcome.cancelled_count)+ if self._cli_manager is not None:+ await self._cli_manager.stop_all()+ return StopResult(source="cli_manager")+ return None++ async def _start_messaging_if_configured(self) -> None:+ if self._messaging_import_task is not None:+ await asyncio.shield(self._messaging_import_task)+ if self.settings.messaging_platform == "none":+ self._messaging_state = "disabled"+ return+ try:++ def load_modules() -> None:+ for name in ("cli.managed", "messaging.workflow"):+ importlib.import_module(f"free_claude_code.{name}")+ importlib.import_module(+ f"free_claude_code.messaging.platforms.{self.settings.messaging_platform}"+ )++ await run_sync_owned(load_modules)+ if self._transcriber_factory is not None:+ self._transcriber = await self._transcriber_factory(self.settings)+ components = messaging_platform_factory.create_messaging_components(+ self.settings.messaging_platform,+ self._messaging_options(),+ )+ if components is not None:+ await self._start_messaging_workflow(components)+ self._messaging_state = "ready"+ else:+ self._messaging_state = "disabled"+ except ImportError as exc:+ self._messaging_state = "failed"+ self._messaging_error = (+ "Messaging could not start. Check its configuration and restart FCC."+ )+ cleaned = await self.close_delivery()+ if self.settings.log_api_error_tracebacks:+ logger.warning("Messaging module import error: {}", exc)+ else:+ logger.warning(+ "Messaging module import error: exc_type={}",+ type(exc).__name__,+ )+ if not cleaned:+ raise RuntimeError("Messaging startup cleanup incomplete") from exc+ except Exception as exc:+ self._messaging_state = "failed"+ self._messaging_error = (+ "Messaging could not start. Check its configuration and restart FCC."+ )+ cleaned = await self.close_delivery()+ if self.settings.log_api_error_tracebacks:+ logger.error("Failed to start messaging platform: {}", exc)+ logger.error(traceback.format_exc())+ else:+ logger.error(+ "Failed to start messaging platform: exc_type={}",+ type(exc).__name__,+ )+ if not cleaned:+ raise RuntimeError("Messaging startup cleanup incomplete") from exc++ def _messaging_options(self) -> MessagingPlatformOptions:+ settings = self.settings+ return MessagingPlatformOptions(+ telegram_bot_token=settings.telegram_bot_token,+ allowed_telegram_user_id=settings.allowed_telegram_user_id,+ telegram_proxy_url=settings.telegram_proxy_url,+ discord_bot_token=settings.discord_bot_token,+ allowed_discord_channels=settings.allowed_discord_channels,+ transcriber=self._transcriber,+ messaging_rate_limit=settings.messaging_rate_limit,+ messaging_rate_window=settings.messaging_rate_window,+ log_raw_messaging_content=settings.log_raw_messaging_content,+ log_messaging_error_details=settings.log_messaging_error_details,+ log_api_error_tracebacks=settings.log_api_error_tracebacks,+ )++ async def _initialize_messaging_storage(self) -> None:+ if self._database is None:+ return+ try:+ await self._database.start()+ from .messaging_import import import_legacy+ from .messaging_sqlite import SQLiteMessagingStore++ self._messaging_store = SQLiteMessagingStore(+ self._database,+ managed_message_cap=self.settings.max_message_log_entries_per_chat,+ )+ self._messaging_warning = await import_legacy(+ self._database, Path(messaging_state_dir_path()) / "sessions.json"+ )+ await self._messaging_store.trim()+ except Exception as exc:+ self._messaging_storage_error = exc+ logger.error(+ "Messaging storage initialization failed: {}", type(exc).__name__+ )+ return+ if self._messaging_warning:+ logger.warning("{}", self._messaging_warning)++ async def _start_messaging_workflow(+ self,+ components: MessagingPlatformComponents,+ ) -> None:+ import free_claude_code.cli.managed as cli_managed+ import free_claude_code.messaging.workflow as messaging_workflow_module++ settings = self.settings+ self._messaging_runtime = components.runtime+ workspace = (+ os.path.abspath(settings.allowed_dir)+ if settings.allowed_dir+ else os.getcwd()+ )+ await run_sync_owned(partial(os.makedirs, workspace, exist_ok=True))+ allowed_dirs = [workspace] if settings.allowed_dir else []++ self._cli_manager = cli_managed.ManagedClaudeSessionManager(+ workspace_path=workspace,+ proxy_root_url=local_proxy_root_url(settings),+ allowed_dirs=allowed_dirs,+ auth_token=settings.proxy_auth_token,+ log_raw_cli_diagnostics=settings.log_raw_cli_diagnostics,+ log_messaging_error_details=settings.log_messaging_error_details,+ )+ if self._messaging_import_task is not None:+ await asyncio.shield(self._messaging_import_task)+ if self._messaging_storage_error is not None:+ raise ApplicationUnavailableError(+ "Messaging storage is unavailable."+ ) from self._messaging_storage_error+ if self._messaging_store is None:+ raise ApplicationUnavailableError("Messaging storage is unavailable.")+ session_store = self._messaging_store+ workflow = messaging_workflow_module.MessagingWorkflow(+ platform_name=components.name,+ outbound=components.outbound,+ voice_cancellation=components.voice_cancellation,+ cli_manager=self._cli_manager,+ session_store=session_store,+ debug_platform_edits=settings.debug_platform_edits,+ debug_subagent_stack=settings.debug_subagent_stack,+ log_raw_cli_diagnostics=settings.log_raw_cli_diagnostics,+ log_messaging_error_details=settings.log_messaging_error_details,+ )+ self._messaging_workflow = workflow+ await workflow.restore()+ components.runtime.on_message(workflow.handle_message)+ await self._http_ready.wait()+ if self._is_draining():+ return+ await components.runtime.start()+ await workflow.repair_restored_statuses()+ if components.startup_notice is not None:+ await workflow.publish_startup_notice(components.startup_notice)+ logger.info("{} platform started with messaging workflow", components.name)++ async def close_delivery(self) -> bool:+ verbose = self.settings.log_api_error_tracebacks+ workflow = self._messaging_workflow+ runtime = self._messaging_runtime+ cli_manager = self._cli_manager++ if runtime is not None:+ quiesced = await best_effort(+ "messaging_runtime.quiesce",+ runtime.quiesce(),+ log_verbose_errors=verbose,+ )+ if not quiesced:+ # Delivery must remain available until ingress is known stopped.+ # Retaining the graph lets the next close retry this exact gate.+ return False++ if workflow is not None:+ closed = await best_effort(+ "messaging_workflow.close",+ workflow.close(),+ log_verbose_errors=verbose,+ )+ if not closed:+ # Active workflow tasks may still need delivery, transcription,+ # CLI sessions, and providers while a later close retries drain.+ return False+ if self._messaging_workflow is workflow:+ self._messaging_workflow = None+ if self._cli_manager is cli_manager:+ self._cli_manager = None+ elif cli_manager is not None:+ drained = await best_effort(+ "cli_manager.stop_all",+ cli_manager.stop_all(),+ log_verbose_errors=verbose,+ )+ if not drained:+ return False+ if self._cli_manager is cli_manager:+ self._cli_manager = None++ if runtime is not None:+ closed = await best_effort(+ "messaging_runtime.close",+ runtime.close(),+ log_verbose_errors=verbose,+ )+ if not closed:+ return False+ if self._messaging_runtime is runtime:+ self._messaging_runtime = None+ return True++ async def close_transcriber(self) -> bool:+ transcriber = self._transcriber+ if transcriber is None:+ return True+ closed = await best_effort(+ "transcriber.close",+ transcriber.close(),+ log_verbose_errors=self.settings.log_api_error_tracebacks,+ )+ if closed and self._transcriber is transcriber:+ self._transcriber = None+ return closeddiff --git a/tests/api/test_app_lifespan_and_errors.py b/tests/api/test_app_lifespan_and_errors.pyindex f19b7dcb..aa70da20 100644--- a/tests/api/test_app_lifespan_and_errors.py+++ b/tests/api/test_app_lifespan_and_errors.py@@ -56,7 +56,7 @@ async def test_runtime_startup_logs_admin_url_without_printed_server_banner():patch.object(manager, "start_model_list_refresh") as start_refresh,patch.object(manager, "close", new=AsyncMock()),patch(- "free_claude_code.runtime.application.messaging_platform_factory.create_messaging_components",+ "free_claude_code.runtime.messaging_service.messaging_platform_factory.create_messaging_components",return_value=None,),patch.object(uvicorn_logger, "info") as log_info,@@ -165,7 +165,7 @@ async def test_runtime_startup_schedules_catalog_without_a_network_barrier():) as refresh,patch.object(manager, "close", new=AsyncMock()),patch(- "free_claude_code.runtime.application.messaging_platform_factory.create_messaging_components",+ "free_claude_code.runtime.messaging_service.messaging_platform_factory.create_messaging_components",return_value=None,),):@@ -386,11 +386,15 @@ async def test_bootstrap_constructs_isolated_runtime_resource_graphs(assert isinstance(first_provider, NvidiaNimProvider)assert isinstance(second_provider, NvidiaNimProvider)assert first_provider._admission is not second_provider._admission- assert first.runtime._transcriber is second.runtime._transcriber is None- assert first.runtime._transcriber_factory is not None- assert second.runtime._transcriber_factory is not None- first_voice = await first.runtime._transcriber_factory(settings)- second_voice = await second.runtime._transcriber_factory(settings)+ assert (+ first.runtime._messaging._transcriber+ is second.runtime._messaging._transcriber+ is None+ )+ assert first.runtime._messaging._transcriber_factory is not None+ assert second.runtime._messaging._transcriber_factory is not None+ first_voice = await first.runtime._messaging._transcriber_factory(settings)+ second_voice = await second.runtime._messaging._transcriber_factory(settings)assert first_voice is not None and second_voice is not Noneassert first_voice is not second_voiceawait first_voice.close()diff --git a/tests/api/test_runtime_safe_logging.py b/tests/api/test_runtime_safe_logging.pyindex d606b7bb..0f5ba1b6 100644--- a/tests/api/test_runtime_safe_logging.py+++ b/tests/api/test_runtime_safe_logging.py@@ -6,8 +6,9 @@ from unittest.mock import AsyncMock, patchimport pytestfrom free_claude_code.config.settings import Settings-from free_claude_code.runtime.application import ApplicationRuntime, best_effort+from free_claude_code.runtime.application import ApplicationRuntimefrom free_claude_code.runtime.configuration import ConfigurationService+from free_claude_code.runtime.lifecycle import best_effortfrom free_claude_code.runtime.provider_manager import ProviderRuntimeManager@@ -29,12 +30,12 @@ async def test_messaging_start_failure_default_logs_exclude_traceback(caplog):with (patch(- "free_claude_code.runtime.application.messaging_platform_factory.create_messaging_components",+ "free_claude_code.runtime.messaging_service.messaging_platform_factory.create_messaging_components",side_effect=RuntimeError("SECRET_RUNTIME_DETAIL"),),caplog.at_level(logging.ERROR),):- await runtime._start_messaging_if_configured()+ await runtime._messaging._start_messaging_if_configured()blob = " | ".join(record.getMessage() for record in caplog.records)assert "SECRET_RUNTIME_DETAIL" not in blobdiff --git a/tests/runtime/test_application_runtime.py b/tests/runtime/test_application_runtime.pyindex 7ee11375..7106564b 100644--- a/tests/runtime/test_application_runtime.py+++ b/tests/runtime/test_application_runtime.py@@ -335,7 +335,7 @@ async def test_stop_all_maps_messaging_outcome_to_application_count() -> None:fallback_required=False,))- runtime._messaging_workflow = workflow+ runtime._messaging._messaging_workflow = workflowresult = await runtime.stop_all()@@ -596,11 +596,11 @@ async def test_close_drains_messaging_before_transcriber_and_is_idempotent() ->configuration=AsyncMock(spec=ConfigurationService),transcriber=transcriber,)- runtime._messaging_runtime = TrackingMessagingRuntime(events)+ runtime._messaging._messaging_runtime = TrackingMessagingRuntime(events)workflow = MagicMock()workflow.close = AsyncMock(side_effect=lambda: events.append("workflow.close"))- runtime._messaging_workflow = workflow- runtime._cli_manager = MagicMock()+ runtime._messaging._messaging_workflow = workflow+ runtime._messaging._cli_manager = MagicMock()assert runtime.is_closed is Falseassert await runtime.close() is True@@ -613,9 +613,9 @@ async def test_close_drains_messaging_before_transcriber_and_is_idempotent() ->"transcriber.close",]assert transcriber.close_calls == 1- assert runtime._transcriber is None- assert runtime._messaging_runtime is None- assert runtime._messaging_workflow is None+ assert runtime._messaging._transcriber is None+ assert runtime._messaging._messaging_runtime is None+ assert runtime._messaging._messaging_workflow is Noneassert runtime.is_closed is True@@ -629,7 +629,7 @@ async def test_close_retains_transcriber_ownership_when_close_fails() -> None:configuration=AsyncMock(spec=ConfigurationService),transcriber=transcriber,)- runtime._messaging_runtime = TrackingMessagingRuntime(events)+ runtime._messaging._messaging_runtime = TrackingMessagingRuntime(events)assert await runtime.close() is False@@ -639,7 +639,7 @@ async def test_close_retains_transcriber_ownership_when_close_fails() -> None:"transcriber.close",]assert transcriber.close_calls == 1- assert runtime._transcriber is transcriber+ assert runtime._messaging._transcriber is transcriberassert runtime._closed is Falseawait manager.close()@@ -655,13 +655,13 @@ async def test_close_retries_runtime_before_closing_later_resources() -> None:transcriber=transcriber,)messaging = TrackingMessagingRuntime(events, fail_close_once=True)- runtime._messaging_runtime = messaging+ runtime._messaging._messaging_runtime = messagingassert await runtime.close() is Falseassert events == ["messaging.quiesce", "messaging.close"]- assert runtime._messaging_runtime is messaging- assert runtime._transcriber is transcriber+ assert runtime._messaging._messaging_runtime is messaging+ assert runtime._messaging._transcriber is transcriberassert runtime._closed is Falseassert await runtime.close() is True@@ -673,8 +673,8 @@ async def test_close_retries_runtime_before_closing_later_resources() -> None:"messaging.close","transcriber.close",]- assert runtime._messaging_runtime is None- assert runtime._transcriber is None+ assert runtime._messaging._messaging_runtime is None+ assert runtime._messaging._transcriber is Noneassert runtime._closed is True@@ -762,14 +762,14 @@ async def test_close_retries_workflow_close_before_closing_delivery() -> None:events.append("workflow.close")workflow.close = AsyncMock(side_effect=close_workflow)- runtime._messaging_runtime = messaging- runtime._messaging_workflow = workflow+ runtime._messaging._messaging_runtime = messaging+ runtime._messaging._messaging_workflow = workflowassert await runtime.close() is Falseassert events == ["messaging.quiesce"]- assert runtime._messaging_runtime is messaging- assert runtime._messaging_workflow is workflow+ assert runtime._messaging._messaging_runtime is messaging+ assert runtime._messaging._messaging_workflow is workflowassert runtime._closed is Falseassert await runtime.close() is True@@ -793,14 +793,14 @@ async def test_close_does_not_drain_workflow_until_ingress_is_quiescent() -> Nonmessaging = TrackingMessagingRuntime(events, fail_quiesce_once=True)workflow = MagicMock()workflow.close = AsyncMock(side_effect=lambda: events.append("workflow.close"))- runtime._messaging_runtime = messaging- runtime._messaging_workflow = workflow+ runtime._messaging._messaging_runtime = messaging+ runtime._messaging._messaging_workflow = workflowassert await runtime.close() is Falseworkflow.close.assert_not_awaited()- assert runtime._messaging_runtime is messaging- assert runtime._messaging_workflow is workflow+ assert runtime._messaging._messaging_runtime is messaging+ assert runtime._messaging._messaging_workflow is workflowassert await runtime.close() is True@@ -832,13 +832,13 @@ async def test_close_retries_failed_persistence_before_closing_delivery() -> Nonevents.append("workflow.close")workflow.close = AsyncMock(side_effect=close_workflow)- runtime._messaging_runtime = messaging- runtime._messaging_workflow = workflow+ runtime._messaging._messaging_runtime = messaging+ runtime._messaging._messaging_workflow = workflowawait runtime.close()- assert runtime._messaging_workflow is workflow- assert runtime._messaging_runtime is messaging+ assert runtime._messaging._messaging_workflow is workflow+ assert runtime._messaging._messaging_runtime is messagingassert "messaging.close" not in eventsawait runtime.close()@@ -864,10 +864,10 @@ async def test_cancelled_transcriber_close_retains_ownership() -> None:)with pytest.raises(asyncio.CancelledError):- await runtime._cleanup_transcriber()+ await runtime._messaging.close_transcriber()assert transcriber.close_calls == 1- assert runtime._transcriber is transcriber+ assert runtime._messaging._transcriber is transcriberawait manager.close()@@ -886,12 +886,12 @@ async def test_cancelled_application_close_remains_retryable() -> None:await runtime.close()assert runtime._closed is False- assert runtime._transcriber is transcriber+ assert runtime._messaging._transcriber is transcriberawait runtime.close()assert transcriber.close_calls == 2- assert runtime._transcriber is None+ assert runtime._messaging._transcriber is Noneassert runtime._closed is True@@ -933,12 +933,12 @@ async def test_startup_cancellation_cleans_partial_messaging_and_reraises() -> Nentered = asyncio.Event()async def start_messaging() -> None:- runtime._messaging_runtime = messaging+ runtime._messaging._messaging_runtime = messagingentered.set()await asyncio.Event().wait()with patch.object(- runtime,+ runtime._messaging,"_start_messaging_if_configured",side_effect=start_messaging,):@@ -952,8 +952,8 @@ async def test_startup_cancellation_cleans_partial_messaging_and_reraises() -> N"transcriber.close",]assert runtime._closed is True- assert runtime._messaging_runtime is None- assert runtime._transcriber is None+ assert runtime._messaging._messaging_runtime is None+ assert runtime._messaging._transcriber is None@pytest.mark.asyncio@@ -982,27 +982,27 @@ async def test_public_start_retries_transient_partial_messaging_cleanup() -> Nonpublished: MessagingPlatformComponents,) -> None:assert published is components- runtime._messaging_runtime = messaging- runtime._messaging_workflow = workflow- runtime._cli_manager = cli_manager+ runtime._messaging._messaging_runtime = messaging+ runtime._messaging._messaging_workflow = workflow+ runtime._messaging._cli_manager = cli_managerraise startup_failurewith (patch.object(manager, "start_model_list_refresh"),patch(- "free_claude_code.runtime.application.messaging_platform_factory.create_messaging_components",+ "free_claude_code.runtime.messaging_service.messaging_platform_factory.create_messaging_components",return_value=components,),patch.object(- runtime,+ runtime._messaging,"_start_messaging_workflow",side_effect=fail_after_publication,),):await runtime.start()with pytest.raises(RuntimeError, match="cleanup incomplete") as raised:- await asyncio.gather(*runtime._startup_tasks)- assert runtime._messaging_state == "failed"+ await asyncio.gather(*runtime._messaging._startup_tasks)+ assert runtime._messaging._messaging_state == "failed"assert await runtime.close() is Trueassert raised.value.__cause__ is startup_failure@@ -1013,9 +1013,9 @@ async def test_public_start_retries_transient_partial_messaging_cleanup() -> Non"messaging.close",]workflow.close.assert_awaited_once()- assert runtime._messaging_runtime is None- assert runtime._messaging_workflow is None- assert runtime._cli_manager is None+ assert runtime._messaging._messaging_runtime is None+ assert runtime._messaging._messaging_workflow is None+ assert runtime._messaging._cli_manager is Noneassert runtime.is_closed is True@@ -1050,37 +1050,37 @@ async def test_public_start_retains_persistently_unclean_partial_messaging_graphpublished: MessagingPlatformComponents,) -> None:assert published is components- runtime._messaging_runtime = messaging- runtime._messaging_workflow = workflow- runtime._cli_manager = cli_manager+ runtime._messaging._messaging_runtime = messaging+ runtime._messaging._messaging_workflow = workflow+ runtime._messaging._cli_manager = cli_managerraise startup_failurewith (patch.object(manager, "start_model_list_refresh"),patch(- "free_claude_code.runtime.application.messaging_platform_factory.create_messaging_components",+ "free_claude_code.runtime.messaging_service.messaging_platform_factory.create_messaging_components",return_value=components,),patch.object(- runtime,+ runtime._messaging,"_start_messaging_workflow",side_effect=fail_after_publication,),):await runtime.start()with pytest.raises(RuntimeError, match="cleanup incomplete") as raised:- await asyncio.gather(*runtime._startup_tasks)- assert runtime._messaging_state == "failed"+ await asyncio.gather(*runtime._messaging._startup_tasks)+ assert runtime._messaging._messaging_state == "failed"assert await runtime.close() is Falseassert raised.value.__cause__ is startup_failureassert events == ["messaging.quiesce", "messaging.quiesce"]workflow.close.assert_not_awaited()assert transcriber.close_calls == 0- assert runtime._messaging_runtime is messaging- assert runtime._messaging_workflow is workflow- assert runtime._cli_manager is cli_manager- assert runtime._transcriber is transcriber+ assert runtime._messaging._messaging_runtime is messaging+ assert runtime._messaging._messaging_workflow is workflow+ assert runtime._messaging._cli_manager is cli_manager+ assert runtime._messaging._transcriber is transcriberassert runtime._provider_manager_closed is Falseassert runtime.is_closed is False@@ -1107,12 +1107,14 @@ async def test_messaging_start_failure_is_nonfatal_after_complete_cleanup() -> Nwith (patch(- "free_claude_code.runtime.application.messaging_platform_factory.create_messaging_components",+ "free_claude_code.runtime.messaging_service.messaging_platform_factory.create_messaging_components",side_effect=RuntimeError("messaging unavailable"),),- patch.object(runtime, "_cleanup_messaging", AsyncMock(return_value=True)),+ patch.object(+ runtime._messaging, "close_delivery", AsyncMock(return_value=True)+ ),):- await runtime._start_messaging_if_configured()+ await runtime._messaging._start_messaging_if_configured()await manager.close()@@ -1128,13 +1130,15 @@ async def test_messaging_start_failure_fails_closed_when_cleanup_is_incomplete()with (patch(- "free_claude_code.runtime.application.messaging_platform_factory.create_messaging_components",+ "free_claude_code.runtime.messaging_service.messaging_platform_factory.create_messaging_components",side_effect=RuntimeError("messaging unavailable"),),- patch.object(runtime, "_cleanup_messaging", AsyncMock(return_value=False)),+ patch.object(+ runtime._messaging, "close_delivery", AsyncMock(return_value=False)+ ),pytest.raises(RuntimeError, match="cleanup incomplete") as exc_info,):- await runtime._start_messaging_if_configured()+ await runtime._messaging._start_messaging_if_configured()assert isinstance(exc_info.value.__cause__, RuntimeError)await manager.close()@@ -1156,14 +1160,14 @@ async def test_composition_records_runtime_before_workspace_setup() -> None:with (patch(- "free_claude_code.runtime.application.os.makedirs",+ "free_claude_code.runtime.messaging_service.os.makedirs",side_effect=OSError("workspace failed"),),pytest.raises(OSError, match="workspace failed"),):- await runtime._start_messaging_workflow(components)+ await runtime._messaging._start_messaging_workflow(components)- assert runtime._messaging_runtime is messaging+ assert runtime._messaging._messaging_runtime is messagingawait runtime.close()@@ -1206,14 +1210,14 @@ async def test_composition_publishes_startup_notice_after_runtime_and_repair() -"free_claude_code.cli.managed.ManagedClaudeSessionManager",return_value=cli_manager,) as manager_constructor,- patch.object(runtime, "_messaging_store", AsyncMock()),+ patch.object(runtime._messaging, "_messaging_store", AsyncMock()),patch("free_claude_code.messaging.workflow.MessagingWorkflow",return_value=workflow,),):runtime.http_started()- await runtime._start_messaging_workflow(components)+ await runtime._messaging._start_messaging_workflow(components)assert events == ["workflow.restore",diff --git a/tests/runtime/test_config_transactions.py b/tests/runtime/test_config_transactions.pyindex c7bc0cbc..46a3d3a0 100644--- a/tests/runtime/test_config_transactions.py+++ b/tests/runtime/test_config_transactions.py@@ -6,12 +6,73 @@ import pytestfrom free_claude_code.application.errors import ApplicationUnavailableErrorfrom free_claude_code.config.loader import ManagedConfigStore+from free_claude_code.harnesses import claude_integrationfrom free_claude_code.runtime.application import ApplicationRuntimefrom free_claude_code.runtime.configuration import ConfigurationServicefrom free_claude_code.runtime.provider_manager import ProviderRuntimeManagerfrom tests.runtime.test_application_runtime import TrackingFactory, _prepared, _settings[email protected]("cancel_writer", [False, True])+async def test_integration_write_finishes_before_configuration_publication(+ tmp_path, monkeypatch, cancel_writer+):+ factory = TrackingFactory()+ manager = ProviderRuntimeManager(+ _settings("nvidia_nim/old"), runtime_factory=factory+ )+ configuration = AsyncMock(spec=ConfigurationService)+ prepared = _prepared(_settings("nvidia_nim/new"), tmp_path)+ configuration.prepare.return_value = prepared+ configuration.commit.return_value = prepared.applied_response()+ runtime = ApplicationRuntime(manager, configuration=configuration, transcriber=None)+ entered, release = threading.Event(), threading.Event()+ apply_started = asyncio.Event()+ configure = claude_integration.configure++ def held(*args, **kwargs):+ entered.set()+ assert release.wait(5)+ return configure(*args, **kwargs)++ async def apply_config():+ apply_started.set()+ return await runtime.apply_admin_config({})++ monkeypatch.setattr(claude_integration, "configure", held)+ monkeypatch.setattr(+ "free_claude_code.runtime.application.check_credentials",+ AsyncMock(return_value=()),+ )+ writer = asyncio.create_task(runtime.connect_claude_vscode())+ apply = None+ try:+ assert await asyncio.to_thread(entered.wait, 5)+ if cancel_writer:+ writer.cancel()+ apply = asyncio.create_task(apply_config())+ await asyncio.wait_for(apply_started.wait(), 5)+ configuration.prepare.assert_not_awaited()+ configuration.commit.assert_not_awaited()+ assert manager.current_generation_id == 1+ assert not writer.done()+ release.set()+ if cancel_writer:+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(writer, 5)+ else:+ assert (await asyncio.wait_for(writer, 5))["connected"] is True+ assert (await asyncio.wait_for(apply, 5))["applied"] is True+ assert manager.current_generation_id == 2+ finally:+ release.set()+ await asyncio.gather(+ writer, *([apply] if apply else []), return_exceptions=True+ )+ await runtime.close()++@pytest.mark.asyncioasync def test_awaitable_restart_callback_is_not_executed_under_apply_lock(tmp_path):manager = ProviderRuntimeManager(_settings("nvidia_nim/old"))diff --git a/tests/runtime/test_feature_lifecycle.py b/tests/runtime/test_feature_lifecycle.pynew file mode 100644index 00000000..eb375e43--- /dev/null+++ b/tests/runtime/test_feature_lifecycle.py@@ -0,0 +1,122 @@+import asyncio+from unittest.mock import AsyncMock++import pytest++from free_claude_code.application.code_sessions import CodeService+from free_claude_code.application.errors import ApplicationUnavailableError+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 free_claude_code.runtime.sqlite_database import SQLiteDatabase+from tests.runtime.test_application_runtime import (+ TrackingFactory,+ TrackingMessagingRuntime,+ TrackingTranscriber,+ _settings,+)+++async def test_close_cancels_both_feature_owners_before_acquiring_config_lock():+ manager = ProviderRuntimeManager(_settings("nvidia_nim/model"))+ database = AsyncMock(spec=SQLiteDatabase)+ import_started = asyncio.Event()++ async def start_database():+ import_started.set()+ await asyncio.Event().wait()++ database.start.side_effect = start_database+ runtime = ApplicationRuntime(+ manager,+ configuration=AsyncMock(spec=ConfigurationService),+ transcriber=None,+ database=database,+ )+ close = None+ try:+ async with runtime._config_lock:+ await runtime.start()+ await asyncio.wait_for(import_started.wait(), 5)+ refresh = runtime._integrations._claude_update.task+ assert refresh is not None and not refresh.done()+ messaging_tasks = tuple(runtime._messaging._startup_tasks)+ assert len(messaging_tasks) == 2+ assert all(not task.done() for task in messaging_tasks)+ close = asyncio.create_task(runtime.close())+ results = await asyncio.wait_for(+ asyncio.gather(refresh, *messaging_tasks, return_exceptions=True), 5+ )+ assert all(isinstance(result, asyncio.CancelledError) for result in results)+ assert not close.done()+ database.close.assert_not_awaited()+ assert await asyncio.wait_for(close, 5)+ database.close.assert_awaited_once()+ finally:+ if close is not None:+ await close+ await runtime.close()+++async def test_draining_runtime_rejects_new_feature_work():+ runtime = ApplicationRuntime(+ ProviderRuntimeManager(_settings("nvidia_nim/model")),+ configuration=AsyncMock(spec=ConfigurationService),+ transcriber=None,+ )+ try:+ runtime.begin_shutdown()+ runtime._integrations.catalog_changed()+ assert runtime._integrations._vscode_update.task is None+ with pytest.raises(ApplicationUnavailableError):+ await runtime.refresh_claude_vscode()+ with pytest.raises(ApplicationUnavailableError):+ runtime._messaging.start()+ assert runtime._messaging._startup_tasks == []+ finally:+ assert await runtime.close()+++async def test_failed_messaging_drain_retains_shared_dependencies_until_retry():+ events = []+ factory = TrackingFactory()+ manager = ProviderRuntimeManager(+ _settings("nvidia_nim/model"), runtime_factory=factory+ )+ code = AsyncMock(spec=CodeService)+ database = AsyncMock(spec=SQLiteDatabase)+ code.close.side_effect = lambda: events.append("code.close")+ database.close.side_effect = lambda: events.append("database.close")+ transcriber = TrackingTranscriber(events)+ runtime = ApplicationRuntime(+ manager,+ configuration=AsyncMock(spec=ConfigurationService),+ transcriber=transcriber,+ database=database,+ code_service=code,+ )+ runtime._messaging._messaging_runtime = TrackingMessagingRuntime(+ events, fail_quiesce_once=True+ )+ try:+ assert not await runtime.close()+ assert not runtime.is_closed+ code.close.assert_not_awaited()+ database.close.assert_not_awaited()+ assert transcriber.close_calls == 0+ assert factory.runtimes[0].cleanup_calls == 0+ assert await runtime.close()+ assert events == [+ "messaging.quiesce",+ "messaging.quiesce",+ "messaging.close",+ "code.close",+ "database.close",+ "transcriber.close",+ ]+ assert factory.runtimes[0].cleanup_calls == 1+ finally:+ await runtime.close()diff --git a/tests/runtime/test_integration_startup.py b/tests/runtime/test_integration_startup.pyindex 9efe7cbe..c182f94f 100644--- a/tests/runtime/test_integration_startup.py+++ b/tests/runtime/test_integration_startup.py@@ -98,7 +98,7 @@ async def test_jetbrains_startup_refresh_and_failed_discovery_allow_disconnect()try:await runtime.start()- await asyncio.wait_for(runtime._jetbrains_update.task, 5)+ await asyncio.wait_for(runtime._integrations._jetbrains_update.task, 5)status = await runtime.jetbrains_acp_status()assert status["connected"] is Trueassert status["update"]["changed"] is True@@ -109,7 +109,7 @@ async def test_jetbrains_startup_refresh_and_failed_discovery_allow_disconnect(assert entry["env"]["ANTHROPIC_BASE_URL"] == "http://127.0.0.1:8000"jb.registry_path().unlink()await runtime.refresh_jetbrains_acp()- await asyncio.wait_for(runtime._jetbrains_update.task, 5)+ await asyncio.wait_for(runtime._integrations._jetbrains_update.task, 5)status = await runtime.jetbrains_acp_status()assert status["update"]["state"] == "failed"assert status["connected"] is True@@ -120,7 +120,11 @@ async def test_jetbrains_startup_refresh_and_failed_discovery_allow_disconnect(async def finish(runtime):await asyncio.wait_for(- asyncio.gather(runtime._claude_update.task, runtime._codex_update.task), 5+ asyncio.gather(+ runtime._integrations._claude_update.task,+ runtime._integrations._codex_update.task,+ ),+ 5,)@@ -147,7 +151,7 @@ async def test_startup_refreshes_old_connections_and_status_is_read_only(runtimeawait runtime.disconnect_claude_vscode()assert (await runtime.claude_vscode_status())["update"]["changed"] is Falseawait runtime.refresh_claude_vscode()- await runtime._claude_update.task+ await runtime._integrations._claude_update.taskassert (await runtime.claude_vscode_status())["connected"] is Falsefinally:await runtime.close()@@ -174,7 +178,7 @@ async def test_codex_wait_does_not_delay_http_or_claude(runtime, monkeypatch):try:await asyncio.wait_for(runtime.start(), 1)await asyncio.wait_for(entered.wait(), 5)- await asyncio.wait_for(runtime._claude_update.task, 5)+ await asyncio.wait_for(runtime._integrations._claude_update.task, 5)async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://127.0.0.1") as client:@@ -224,9 +228,9 @@ async def test_update_failure_is_isolated_and_retry_finishes(runtime):assert (await runtime.claude_vscode_status())["update"]["state"] == "failed"assert "CLAUDE_CODE_DISABLE_ADVISOR_TOOL" not in claude.read_text()await runtime.refresh_claude_vscode()- task = runtime._claude_update.task+ task = runtime._integrations._claude_update.taskawait runtime.refresh_claude_vscode()- assert runtime._claude_update.task is task+ assert runtime._integrations._claude_update.task is taskawait asyncio.wait_for(task, 5)assert (await runtime.claude_vscode_status())["connected"] is Truefinally:@@ -357,7 +361,7 @@ async def test_desktop_startup_rotates_selected_profile_and_disconnect_stays_off)try:await runtime.start()- await runtime._desktop_update.task+ await runtime._integrations._desktop_update.taskresult = await runtime.claude_desktop_status()assert result["connected"] is Trueassert result["update"]["changed"] is True@@ -366,7 +370,7 @@ async def test_desktop_startup_rotates_selected_profile_and_disconnect_stays_offassert before == {p: p.stat().st_mtime_ns for p in root.rglob("*.json")}await runtime.disconnect_claude_desktop()await runtime.refresh_claude_desktop()- await runtime._desktop_update.task+ await runtime._integrations._desktop_update.taskassert (await runtime.claude_desktop_status())["connected"] is Falsefinally:await runtime.close()@@ -380,11 +384,13 @@ async def test_desktop_failure_does_not_block_other_startup(runtime, monkeypatchmonkeypatch.setattr(desktop, "refresh_connected", fail)try:await runtime.start()- await runtime._desktop_update.task+ await runtime._integrations._desktop_update.taskawait finish(runtime)- assert runtime._desktop_update.state == "failed"- assert "private-invalid-file" not in runtime._desktop_update.message- assert runtime._claude_update.state == "ready"- assert runtime._codex_update.state == "ready"+ assert runtime._integrations._desktop_update.state == "failed"+ assert (+ "private-invalid-file" not in runtime._integrations._desktop_update.message+ )+ assert runtime._integrations._claude_update.state == "ready"+ assert runtime._integrations._codex_update.state == "ready"finally:await runtime.close()diff --git a/tests/runtime/test_messaging_sqlite.py b/tests/runtime/test_messaging_sqlite.pyindex e331726d..6fc79180 100644--- a/tests/runtime/test_messaging_sqlite.py+++ b/tests/runtime/test_messaging_sqlite.py@@ -562,12 +562,12 @@ async def test_startup_partial_import_preserves_links_scopes_and_code()try:with patch(- "free_claude_code.runtime.application.messaging_state_dir_path",+ "free_claude_code.runtime.messaging_service.messaging_state_dir_path",return_value=str(tmp_path),):- await runtime._initialize_messaging_storage()- assert runtime._messaging_storage_error is None- assert runtime._messaging_warning+ await runtime._messaging._initialize_messaging_storage()+ assert runtime._messaging._messaging_storage_error is None+ assert runtime._messaging._messaging_warningassert (await storage.load_conversation_snapshot()).trees == {valid.identity: valid,inactive.identity: inactive,diff --git a/tests/runtime/test_vscode_chat_sync.py b/tests/runtime/test_vscode_chat_sync.pyindex a6847f4b..68f71803 100644--- a/tests/runtime/test_vscode_chat_sync.py+++ b/tests/runtime/test_vscode_chat_sync.py@@ -57,7 +57,7 @@ async def runtime(request):async def settle(runtime):await runtime.provider_manager.wait_for_catalog()- task = runtime._vscode_update.task+ task = runtime._integrations._vscode_update.taskif task:await asyncio.wait_for(asyncio.shield(task), 5)@@ -76,7 +76,7 @@ async def test_catalog_updates_connected_file_and_disconnect_stays_removed(runtiassert {m["id"] for m in models} == {"nvidia_nim/one", "nvidia_nim/two"}assert (await runtime.vscode_chat_status())["connected"]await runtime.disconnect_vscode_chat()- runtime._queue_vscode_refresh()+ runtime._integrations.catalog_changed()await settle(runtime)assert json.loads(path.read_text()) == []assert not (await runtime.vscode_chat_status())["connected"]@@ -101,7 +101,7 @@ async def test_update_arriving_during_write_is_not_lost(runtime, monkeypatch):monkeypatch.setattr(vscode, "configure", held)try:- runtime._queue_vscode_refresh()+ runtime._integrations.catalog_changed()await asyncio.wait_for(entered.wait(), 5)runtime.provider_manager.cache_model_infos("nvidia_nim", (ProviderModelInfo("late"),)@@ -126,7 +126,7 @@ async def test_bad_file_does_not_fail_catalog_and_disconnect_needs_no_catalog(path.write_text("{broken")await runtime.refresh_vscode_chat()await settle(runtime)- assert runtime._vscode_update.state == "failed"+ assert runtime._integrations._vscode_update.state == "failed"assert runtime.provider_manager.catalog_status()["catalog_file"] == "ready"path.unlink()await runtime.connect_vscode_chat()@@ -158,7 +158,7 @@ async def test_startup_refreshes_owned_group_and_only_writes_once(runtime):await runtime.refresh_vscode_chat()await settle(runtime)assert path.stat().st_mtime_ns == before- assert not runtime._vscode_update.changed+ assert not runtime._integrations._vscode_update.changed@pytest.mark.asyncio@@ -239,7 +239,7 @@ async def test_codex_publication_failure_does_not_block_vscode(runtime):await asyncio.gather(*runtime.provider_manager._publications)await settle(runtime)assert runtime.provider_manager.catalog_status()["catalog_file"] == "failed"- assert runtime._vscode_update.state == "ready"+ assert runtime._integrations._vscode_update.state == "ready"assert "nvidia_nim/new" in [m["id"] for m in json.loads(vscode.config_path().read_text())[0]["models"]]