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
Connect Claude Desktop to FCC (#1844)
Ali Khokhar0abd870e1099
diff --git a/README.md b/README.mdindex 10a6532c..cf4a2fcb 100644--- a/README.md+++ b/README.md@@ -363,10 +363,11 @@ For editor and app integrations, install the client, start FCC, then open**Admin UI → Integrations** and click **Connect** on its card.- **Claude Code in VS Code** — install the [Claude Code extension](https://marketplace.visualstudio.com/items?itemName=anthropic.claude-code).+- **Claude Desktop** — install [Claude Desktop](https://claude.ai/download). Fully quit it before connecting or disconnecting, then reopen it. Disconnect returns to normal Claude sign-in.- **Codex in VS Code and App** — install the [Codex extension](https://marketplace.visualstudio.com/items?itemName=openai.chatgpt) or Codex App.- **Claude Code in JetBrains ACP** — install the Claude Code agent in your JetBrains IDE.-Reload VS Code or restart the app/IDE after connecting. In Codex, select an FCC+Reload VS Code or restart the app/IDE after connecting. In Codex and Claude Desktop, select an FCCmodel from the model picker. FCC keeps connected integrations up to date when itstarts; reload or restart the client when FCC reports updated settings. Use**Disconnect** on the same card to remove the integration.diff --git a/e2e/conftest.py b/e2e/conftest.pyindex cd060f07..902191f6 100644--- a/e2e/conftest.py+++ b/e2e/conftest.py@@ -26,7 +26,11 @@ from free_claude_code.config.loader import (from free_claude_code.core.anthropic.models import MessagesRequestfrom free_claude_code.core.openai_responses import OpenAIResponsesRequestfrom free_claude_code.core.reasoning import DEFAULT_REASONING_POLICY, ReasoningPolicy-from free_claude_code.harnesses import claude_integration, codex_integration+from free_claude_code.harnesses import (+ claude_desktop_integration,+ claude_integration,+ codex_integration,+)from free_claude_code.providers.base import BaseProvider, ProviderConfigfrom free_claude_code.providers.runtime import ProviderRuntimefrom free_claude_code.runtime.application import ApplicationRuntime@@ -136,6 +140,15 @@ def admin_base_url("""Serve one fully isolated Admin application on an OS-assigned port."""config_dir = tmp_path / ".fcc"+ monkeypatch.setattr(+ claude_desktop_integration, "config_root", lambda: tmp_path / "Claude-3p"+ )+ monkeypatch.setattr(claude_desktop_integration, "check_unmanaged", lambda: None)+ monkeypatch.setattr(+ claude_desktop_integration,+ "legacy_windows_root",+ lambda: tmp_path / "LegacyClaude-3p",+ )monkeypatch.setattr(codex_integration, "config_path", lambda: tmp_path / ".codex" / "config.toml")diff --git a/e2e/test_admin_integrations.py b/e2e/test_admin_integrations.pyindex 88687f37..00beb5c5 100644--- a/e2e/test_admin_integrations.py+++ b/e2e/test_admin_integrations.py@@ -13,6 +13,7 @@ from free_claude_code.harnesses import claude_integration[("claude-vscode", "openClaudeIntegration"),("codex", "openCodexIntegration"),+ ("claude-desktop", "openClaudeDesktopIntegration"),],)@pytest.mark.parametrize("connected", [False, True])@@ -165,15 +166,8 @@ def test_codex_connect_disconnect_and_modal_paths("Route Claude Code in JetBrains through your FCC server.",2,),- (- "ClaudeDesktop",- "Claude Desktop",- "Use FCC's models in the Claude desktop app.",- "Route Claude Desktop through your FCC server. Setup is coming soon.",- 3,- ),],- ids=["jetbrains", "claude-desktop"],+ ids=["jetbrains"],)@pytest.mark.parametrize("width", [1200, 1440, 390])def test_preview_connect_is_noop_and_modal_dismisses(diff --git a/e2e/test_claude_desktop_integration.py b/e2e/test_claude_desktop_integration.pynew file mode 100644index 00000000..8b078ed1--- /dev/null+++ b/e2e/test_claude_desktop_integration.py@@ -0,0 +1,137 @@+import json+from pathlib import Path++import pytest+from playwright.sync_api import expect++from free_claude_code.harnesses import claude_desktop_integration as desktop++[email protected]("status_failure", ["none", "read", "startup"])+def test_real_disconnect_failure_keeps_retry_after_reload(+ page, admin_base_url, tmp_path, monkeypatch, status_failure+):+ profile = tmp_path / "Claude-3p/configLibrary" / f"{desktop.FCC_ID}.json"+ page.goto(admin_base_url + "/admin/integrations")+ opener = page.locator("#openClaudeDesktopIntegration")+ expect(opener).to_have_text("Connect")+ opener.click()+ dialog = page.get_by_role("dialog", name="Claude Desktop", exact=True)+ dialog.get_by_role("button", name="Connect", exact=True).click()+ expect(opener).to_have_text("Disconnect")+ unlink = Path.unlink++ def fail(path, *args, **kwargs):+ if path == profile:+ raise PermissionError("test")+ return unlink(path, *args, **kwargs)++ with monkeypatch.context() as patch:+ patch.setattr(Path, "unlink", fail)+ opener.click()+ endpoint = "**/admin/api/integrations/claude-desktop"+ if status_failure == "read":+ page.route(+ endpoint,+ lambda route: route.fulfill(+ status=503, json={"detail": "Status unavailable"}+ ),+ )+ elif status_failure == "startup":++ def failed_update(route):+ result = route.fetch()+ body = result.json()+ if body["disconnect_pending"]:+ body["connected"] = None+ body["update"] = {+ "state": "failed",+ "message": "Startup check failed",+ }+ route.fulfill(response=result, json=body)++ page.route(endpoint, failed_update)+ dialog.get_by_role("button", name="Disconnect", exact=True).click()+ expect(+ dialog.get_by_role(+ "button",+ name="Disconnect" if status_failure == "read" else "Retry disconnect",+ exact=True,+ )+ ).to_be_enabled()+ expect(dialog.get_by_role("alert")).to_be_visible()+ assert profile.exists()+ if status_failure == "read":+ page.unroute(endpoint)+ page.reload()+ expect(opener).to_have_text("Retry disconnect")+ expect(opener).to_be_enabled()+ opener.click()+ dialog.get_by_role("button", name="Retry disconnect", exact=True).click()+ expect(dialog).not_to_be_visible()+ expect(opener).to_have_text("Connect")+ assert not profile.exists()+ assert not (tmp_path / ".fcc/claude-desktop-disconnect.json").exists()+++def test_desktop_connect_disconnect_and_retry(page, admin_base_url, tmp_path):+ page.set_viewport_size({"width": 1440, "height": 1000})+ page.goto(admin_base_url + "/admin/integrations")+ opener = page.locator("#openClaudeDesktopIntegration")+ expect(opener).to_have_text("Connect")+ expect(opener).to_be_enabled()+ dialog = page.get_by_role("dialog", name="Claude Desktop", exact=True)+ profile = tmp_path / "Claude-3p/configLibrary" / f"{desktop.FCC_ID}.json"+ for dismissal in ("close", "escape", "outside"):+ opener.click()+ expect(dialog).to_be_visible()+ expect(dialog.locator("#claudeDesktopIntegrationFiles")).to_contain_text(+ str(profile.resolve())+ )+ dialog.locator("p").first.click()+ expect(dialog).to_be_visible()+ if dismissal == "close":+ dialog.get_by_role("button", name="Close", exact=True).click()+ elif dismissal == "escape":+ page.keyboard.press("Escape")+ else:+ page.mouse.click(1, 1)+ expect(dialog).not_to_be_visible()+ expect(opener).to_be_focused()+ assert not profile.exists()+ opener.click()+ page.screenshot(path=str(tmp_path / "claude-desktop-connect.png"))+ action = dialog.get_by_role("button", name="Connect", exact=True)+ action.click()+ expect(dialog).not_to_be_visible()+ expect(opener).to_have_text("Disconnect")+ expect(opener).to_have_css("color", "rgb(239, 68, 68)")+ assert json.loads(profile.read_text())["inferenceProvider"] == "gateway"+ page.reload()+ expect(opener).to_have_text("Disconnect")+ page.screenshot(path=str(tmp_path / "claude-desktop-connected.png"))+ opener.click()+ endpoint = "**/admin/api/integrations/claude-desktop/disconnect"+ page.route(+ endpoint,+ lambda route: route.fulfill(+ status=503, json={"detail": "File is busy; retry."}+ ),+ )+ dialog.get_by_role("button", name="Disconnect", exact=True).click()+ expect(dialog).to_be_visible()+ expect(dialog.get_by_role("alert")).to_contain_text("retry")+ expect(dialog.get_by_role("button", name="Disconnect", exact=True)).to_be_enabled()+ page.unroute(endpoint)+ dialog.get_by_role("button", name="Disconnect", exact=True).click()+ expect(dialog).not_to_be_visible()+ expect(opener).to_have_text("Connect")+ assert not profile.exists()+ assert (+ json.loads((tmp_path / "Claude-3p/claude_desktop_config.json").read_text())[+ "deploymentMode"+ ]+ == "1p"+ )+ assert not (tmp_path / "vscode/settings.json").exists()+ expect(page.locator("#dirtyState")).to_have_text("No changes")diff --git a/pyproject.toml b/pyproject.tomlindex 859912fe..689d309f 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "free-claude-code"-version = "6.2.48"+version = "6.2.49"description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"readme = "README.md"requires-python = ">=3.14.0"diff --git a/src/free_claude_code/api/admin_routes.py b/src/free_claude_code/api/admin_routes.pyindex 683c1e89..a579468b 100644--- a/src/free_claude_code/api/admin_routes.py+++ b/src/free_claude_code/api/admin_routes.py@@ -287,6 +287,38 @@ async def disconnect_claude_vscode(return await _integration_response(services.admin.disconnect_claude_vscode)[email protected]("/admin/api/integrations/claude-desktop")+async def claude_desktop_status(+ request: Request, services: ApiServices = Depends(get_services)+):+ require_loopback_admin(request)+ return await _integration_response(services.admin.claude_desktop_status)++[email protected]("/admin/api/integrations/claude-desktop/connect")+async def connect_claude_desktop(+ request: Request, services: ApiServices = Depends(get_services)+):+ require_loopback_admin(request)+ return await _integration_response(services.admin.connect_claude_desktop)++[email protected]("/admin/api/integrations/claude-desktop/disconnect")+async def disconnect_claude_desktop(+ request: Request, services: ApiServices = Depends(get_services)+):+ require_loopback_admin(request)+ return await _integration_response(services.admin.disconnect_claude_desktop)++[email protected]("/admin/api/integrations/claude-desktop/refresh")+async def refresh_claude_desktop(+ request: Request, services: ApiServices = Depends(get_services)+):+ require_loopback_admin(request)+ return await _integration_response(services.admin.refresh_claude_desktop)++@router.get("/admin/api/integrations/codex")async def codex_integration_status(request: Request,diff --git a/src/free_claude_code/api/admin_static/admin.js b/src/free_claude_code/api/admin_static/admin.jsindex 315b3bfd..d0b4a535 100644--- a/src/free_claude_code/api/admin_static/admin.js+++ b/src/free_claude_code/api/admin_static/admin.js@@ -140,6 +140,7 @@ function renderStartup() {});renderClaudeIntegration();renderCodexIntegration();+ renderClaudeDesktopIntegration();}async function refreshStartup() {@@ -282,6 +283,7 @@ function setActiveView(viewId, { scroll = false } = {}) {if (activeView.id === "integrations") {refreshClaudeIntegration();refreshCodexIntegration();+ refreshClaudeDesktopIntegration();}}@@ -1497,6 +1499,7 @@ function refreshIntegrationUpdates(previous, current) {for (const [id, integration, refresh] of [["claude-vscode", claudeIntegration, refreshClaudeIntegration],["codex", codexIntegration, refreshCodexIntegration],+ ["claude-desktop", claudeDesktopIntegration, refreshClaudeDesktopIntegration],]) {const phase = current?.[id]?.state;if (phase && phase !== "starting" && (@@ -1711,7 +1714,110 @@ jetBrainsIntegrationDialog.addEventListener("click", (event) => {});const claudeDesktopIntegrationDialog = byId("claudeDesktopIntegrationDialog");-byId("openClaudeDesktopIntegration").addEventListener("click", () => claudeDesktopIntegrationDialog.showModal());+const claudeDesktopIntegration = { connected: null, disconnectPending: false, busy: false, paths: null, update: null };+const claudeDesktopIntegrationPath = "/admin/api/integrations/claude-desktop";++function renderClaudeDesktopIntegration() {+ const { connected, paths, disconnectPending } = claudeDesktopIntegration;+ const busy = claudeDesktopIntegration.busy || integrationUpdating(claudeDesktopIntegration, "claude-desktop");+ const disconnect = disconnectPending || connected;+ const action = disconnectPending ? "Retry disconnect" : connected ? "Disconnect" : "Connect";+ byId("openClaudeDesktopIntegration").textContent = busy ? "Loading…" : connected === null && !disconnectPending ? "Retry" : action;+ byId("openClaudeDesktopIntegration").disabled = busy;+ byId("openClaudeDesktopIntegration").setAttribute("aria-busy", String(busy));+ byId("confirmClaudeDesktopIntegration").textContent = busy ? "Saving…" : action;+ byId("confirmClaudeDesktopIntegration").disabled = busy || (connected === null && !disconnectPending);+ byId("openClaudeDesktopIntegration").className = disconnect && !busy ? "danger-button" : "primary-button";+ byId("confirmClaudeDesktopIntegration").className = disconnect ? "danger-button" : "primary-button";+ byId("claudeDesktopIntegrationDescription").textContent = disconnectPending+ ? "Finish removing FCC's configuration. Fully quit Claude Desktop before retrying, then reopen it."+ : connected+ ? "Remove FCC's configuration and return to normal Claude sign-in. Fully quit Claude Desktop first, then reopen it."+ : "Set FCC as Claude Desktop's gateway. Fully quit Claude Desktop before connecting, then reopen it.";+ const files = byId("claudeDesktopIntegrationFiles");+ files.replaceChildren();+ if (paths) {+ const targets = Object.values(paths);+ targets.forEach((path) => {+ const item = document.createElement("li");+ const code = document.createElement("code");+ code.textContent = path;+ item.appendChild(code);+ files.appendChild(item);+ });+ }+}++async function refreshClaudeDesktopIntegration(retry = false) {+ if (claudeDesktopIntegration.busy) return;+ claudeDesktopIntegration.busy = true;+ renderClaudeDesktopIntegration();+ integrationMessage("claudeDesktopIntegrationMessage", "");+ try {+ if (retry) await api(`${claudeDesktopIntegrationPath}/refresh`, { method: "POST" });+ const result = await api(claudeDesktopIntegrationPath);+ claudeDesktopIntegration.connected = result.connected;+ claudeDesktopIntegration.disconnectPending = result.disconnect_pending;+ claudeDesktopIntegration.paths = result.paths;+ claudeDesktopIntegration.update = result.update;+ if (result.update?.state === "failed") integrationMessage("claudeDesktopIntegrationMessage", result.update.message, true);+ else if (result.update?.changed) integrationMessage("claudeDesktopIntegrationMessage", "Settings updated. Reopen Claude Desktop.");+ } catch (error) {+ claudeDesktopIntegration.connected = null;+ claudeDesktopIntegration.disconnectPending = false;+ claudeDesktopIntegration.update = null;+ integrationMessage("claudeDesktopIntegrationMessage", error.message, true);+ } finally {+ claudeDesktopIntegration.busy = false;+ renderClaudeDesktopIntegration();+ if (claudeDesktopIntegration.update?.state === "starting") void refreshStartup();+ }+}++byId("openClaudeDesktopIntegration").addEventListener("click", () => {+ if (claudeDesktopIntegration.connected === null && !claudeDesktopIntegration.disconnectPending) {+ refreshClaudeDesktopIntegration(claudeDesktopIntegration.update?.state === "failed");+ return;+ }+ integrationMessage("claudeDesktopIntegrationDialogMessage", "");+ claudeDesktopIntegrationDialog.showModal();+});+byId("confirmClaudeDesktopIntegration").addEventListener("click", async () => {+ if (byId("confirmClaudeDesktopIntegration").disabled) return;+ const disconnect = claudeDesktopIntegration.disconnectPending || claudeDesktopIntegration.connected;+ claudeDesktopIntegration.busy = true;+ renderClaudeDesktopIntegration();+ integrationMessage("claudeDesktopIntegrationDialogMessage", "");+ integrationMessage("claudeDesktopIntegrationMessage", "");+ try {+ const result = await api(`${claudeDesktopIntegrationPath}/${disconnect ? "disconnect" : "connect"}`, { method: "POST" });+ claudeDesktopIntegration.connected = result.connected;+ claudeDesktopIntegration.disconnectPending = result.disconnect_pending;+ claudeDesktopIntegration.paths = result.paths;+ claudeDesktopIntegration.update = null;+ claudeDesktopIntegrationDialog.close();+ integrationMessage("claudeDesktopIntegrationMessage", disconnect+ ? "Settings removed. Reopen Claude Desktop to disconnect."+ : "Settings saved. Reopen Claude Desktop to connect.");+ } catch (error) {+ if (disconnect) {+ try {+ const result = await api(claudeDesktopIntegrationPath);+ claudeDesktopIntegration.connected = result.connected;+ claudeDesktopIntegration.disconnectPending = result.disconnect_pending;+ claudeDesktopIntegration.paths = result.paths;+ claudeDesktopIntegration.update = result.update;+ } catch {+ // Keep the user's disconnect action available if status is unreadable too.+ }+ }+ integrationMessage("claudeDesktopIntegrationDialogMessage", error.message, true);+ integrationMessage("claudeDesktopIntegrationMessage", error.message, true);+ } finally {+ claudeDesktopIntegration.busy = false;+ renderClaudeDesktopIntegration();+ }+});byId("closeClaudeDesktopIntegration").addEventListener("click", () => claudeDesktopIntegrationDialog.close());claudeDesktopIntegrationDialog.addEventListener("click", (event) => {if (event.target !== claudeDesktopIntegrationDialog) return;diff --git a/src/free_claude_code/api/admin_static/index.html b/src/free_claude_code/api/admin_static/index.htmlindex 0c3ca3cc..eac522bb 100644--- a/src/free_claude_code/api/admin_static/index.html+++ b/src/free_claude_code/api/admin_static/index.html@@ -135,15 +135,21 @@<p>Use FCC's models in the Claude desktop app.</p></div></div>- <button id="openClaudeDesktopIntegration" class="primary-button" type="button">Connect</button>+ <p id="claudeDesktopIntegrationMessage" class="message-area" role="status" hidden></p>+ <button id="openClaudeDesktopIntegration" class="primary-button" type="button" aria-busy="true" disabled>Loading…</button></article><dialog id="claudeDesktopIntegrationDialog" class="integration-dialog" aria-labelledby="claudeDesktopIntegrationTitle" aria-describedby="claudeDesktopIntegrationDescription"><div class="section-heading"><h3 id="claudeDesktopIntegrationTitle">Claude Desktop</h3><button id="closeClaudeDesktopIntegration" class="ghost-button" type="button" aria-label="Close" autofocus>×</button></div>- <p id="claudeDesktopIntegrationDescription">Route Claude Desktop through your FCC server. Setup is coming soon.</p>+ <p id="claudeDesktopIntegrationDescription">Set FCC as Claude Desktop's gateway. Fully quit Claude Desktop before connecting, then reopen it.</p>+ <div class="integration-files">+ <strong>Files to modify</strong>+ <ul id="claudeDesktopIntegrationFiles"></ul>+ </div><button id="confirmClaudeDesktopIntegration" class="primary-button" type="button">Connect</button>+ <p id="claudeDesktopIntegrationDialogMessage" class="message-area error" role="alert" hidden></p></dialog></section>diff --git a/src/free_claude_code/api/model_catalog.py b/src/free_claude_code/api/model_catalog.pyindex c9dce48f..b873a19e 100644--- a/src/free_claude_code/api/model_catalog.py+++ b/src/free_claude_code/api/model_catalog.py@@ -10,6 +10,7 @@ from free_claude_code.application.model_catalog import ModelCatalog, read_model_from free_claude_code.application.ports import ModelCatalogPortfrom free_claude_code.config.settings import Settingsfrom free_claude_code.core.gateway_model_ids import (+ desktop_model_id,gateway_model_id,no_thinking_gateway_model_id,)@@ -24,6 +25,7 @@ class ModelCatalogView(StrEnum):"""Client-specific projections of the application model inventory."""CLAUDE = "claude"+ CLAUDE_DESKTOP = "claude-desktop"MESSAGES = "messages"RESPONSES = "responses"@@ -146,8 +148,10 @@ def build_models_list_response() -> ModelsListResponse:"""Return the application model inventory in the requested client view."""catalog = read_model_catalog(runtime, settings)- if view is ModelCatalogView.CLAUDE:- return _build_claude_models_response(catalog)+ if view in {ModelCatalogView.CLAUDE, ModelCatalogView.CLAUDE_DESKTOP}:+ return _build_claude_models_response(+ catalog, desktop=view is ModelCatalogView.CLAUDE_DESKTOP+ )return _build_direct_models_response(settings, catalog, view=view)@@ -178,18 +182,25 @@ def build_muse_models_list_response(return catalog-def _build_claude_models_response(catalog: ModelCatalog) -> ModelsListResponse:+def _build_claude_models_response(+ catalog: ModelCatalog, *, desktop: bool = False+) -> ModelsListResponse:"""Keep shortcuts first and provider variants together in catalog order."""models = list(SUPPORTED_CLAUDE_MODELS)for model in catalog.models:ref = model.provider_model_refif model.supports_reasoning is not False:models.append(- _discovered_model_response(gateway_model_id(ref), display_name=ref)+ _discovered_model_response(+ desktop_model_id(ref) if desktop else gateway_model_id(ref),+ display_name=ref,+ ))models.append(_discovered_model_response(- no_thinking_gateway_model_id(ref),+ desktop_model_id(ref, no_thinking=True)+ if desktop+ else no_thinking_gateway_model_id(ref),display_name=f"{ref} (no thinking)",))diff --git a/src/free_claude_code/api/ports.py b/src/free_claude_code/api/ports.pyindex 2b942194..c19855e7 100644--- a/src/free_claude_code/api/ports.py+++ b/src/free_claude_code/api/ports.py@@ -37,6 +37,14 @@ class AdminRuntimePort(Protocol):async def refresh_claude_vscode(self) -> JsonObject: ...+ async def claude_desktop_status(self) -> JsonObject: ...++ async def connect_claude_desktop(self) -> JsonObject: ...++ async def disconnect_claude_desktop(self) -> JsonObject: ...++ async def refresh_claude_desktop(self) -> JsonObject: ...+async def codex_integration_status(self) -> JsonObject: ...async def connect_codex(self) -> JsonObject: ...diff --git a/src/free_claude_code/api/routes.py b/src/free_claude_code/api/routes.pyindex 47f6640b..2e1d2c2d 100644--- a/src/free_claude_code/api/routes.py+++ b/src/free_claude_code/api/routes.py@@ -2,7 +2,7 @@from collections.abc import Mapping-from fastapi import APIRouter, Depends, HTTPException, Request, Response+from fastapi import APIRouter, Depends, Header, HTTPException, Request, Responsefrom loguru import loggerfrom free_claude_code.application.errors import ApplicationError@@ -215,14 +215,19 @@ async def probe_health():response_model_exclude_none=True,)async def list_models(- view: ModelCatalogView = ModelCatalogView.CLAUDE,+ view: ModelCatalogView | None = None,+ x_fcc_model_view: ModelCatalogView | None = Header(default=None),services: ApiServices = Depends(get_services),_auth=Depends(require_proxy_auth),):"""List the model ids this proxy advertises to compatible clients."""trace_event(stage="ingress", event="free_claude_code.api.models.list", source="api")snapshot = await services.requests.wait_for_catalog()- return build_models_list_response(snapshot.settings, snapshot, view=view)+ return build_models_list_response(+ snapshot.settings,+ snapshot,+ view=view or x_fcc_model_view or ModelCatalogView.CLAUDE,+ )@router.get(diff --git a/src/free_claude_code/application/routing.py b/src/free_claude_code/application/routing.pyindex 7ca3ed46..cc2afd8b 100644--- a/src/free_claude_code/application/routing.py+++ b/src/free_claude_code/application/routing.py@@ -4,7 +4,10 @@ from dataclasses import dataclassfrom loguru import logger-from free_claude_code.application.errors import UnknownProviderError+from free_claude_code.application.errors import (+ InvalidRequestError,+ UnknownProviderError,+)from free_claude_code.config.model_refs import (is_retired_model_ref,parse_model_name,@@ -17,7 +20,11 @@ from free_claude_code.config.provider_catalog import (from free_claude_code.config.reasoning import ReasoningPreferencefrom free_claude_code.config.settings import Settingsfrom free_claude_code.core.anthropic import MessagesRequest, TokenCountRequest-from free_claude_code.core.gateway_model_ids import decode_gateway_model_id+from free_claude_code.core.gateway_model_ids import (+ DESKTOP_MODEL_PREFIX,+ DESKTOP_NO_THINKING_PREFIX,+ decode_gateway_model_id,+)from free_claude_code.core.openai_responses import OpenAIResponsesRequestfrom free_claude_code.core.reasoning import ReasoningPolicy@@ -150,7 +157,10 @@ class ModelRouter:def _direct_provider_model(self, model_name: str) -> tuple[str | None, str | None, bool]:- decoded = decode_gateway_model_id(model_name)+ try:+ decoded = decode_gateway_model_id(model_name)+ except ValueError:+ raise InvalidRequestError("Invalid Claude Desktop model ID") from Nonecandidate = (f"{decoded.provider_id}/{decoded.provider_model}"if decoded is not None@@ -164,6 +174,13 @@ class ModelRouter:)if decoded is not None:if decoded.provider_id not in SUPPORTED_PROVIDER_IDS:+ if model_name.partition("/")[0] in {+ DESKTOP_MODEL_PREFIX,+ DESKTOP_NO_THINKING_PREFIX,+ }:+ raise UnknownProviderError.for_provider(+ decoded.provider_id, PROVIDER_CATALOG+ )return None, None, Falsereturn (decoded.provider_id,diff --git a/src/free_claude_code/config/paths.py b/src/free_claude_code/config/paths.pyindex 979a1b9c..cefcf75f 100644--- a/src/free_claude_code/config/paths.py+++ b/src/free_claude_code/config/paths.py@@ -83,6 +83,10 @@ def codex_model_catalog_path() -> Path:return config_dir_path() / CODEX_MODEL_CATALOG_FILENAME+def claude_desktop_disconnect_path() -> Path:+ return config_dir_path() / "claude-desktop-disconnect.json"++def openai_auth_path() -> Path:"""Return FCC's private ChatGPT credential file path."""diff --git a/src/free_claude_code/core/gateway_model_ids.py b/src/free_claude_code/core/gateway_model_ids.pyindex 184c85a9..1f87e517 100644--- a/src/free_claude_code/core/gateway_model_ids.py+++ b/src/free_claude_code/core/gateway_model_ids.py@@ -8,6 +8,13 @@ GATEWAY_MODEL_ID_PREFIX = "anthropic"# supporting thinking. This intentionally uses that client-side capability# heuristic while keeping the real provider/model ref reversible for routing.NO_THINKING_GATEWAY_MODEL_ID_PREFIX = "claude-3-freecc-no-thinking"+DESKTOP_MODEL_PREFIX = "claude-fcc"+DESKTOP_NO_THINKING_PREFIX = "claude-3-fcc"+++def desktop_model_id(provider_model_ref: str, *, no_thinking: bool = False) -> str:+ prefix = DESKTOP_NO_THINKING_PREFIX if no_thinking else DESKTOP_MODEL_PREFIX+ return f"{prefix}/{provider_model_ref.encode('utf-8').hex()}"@dataclass(frozen=True, slots=True)@@ -31,8 +38,23 @@ def decode_gateway_model_id(model_name: str) -> DecodedGatewayModelId | None:"""Decode a model id advertised by this gateway, if it is one."""prefix, separator, remainder = model_name.partition("/")if not separator:+ if prefix in {DESKTOP_MODEL_PREFIX, DESKTOP_NO_THINKING_PREFIX}:+ raise ValueError("Invalid Desktop model ID")return None+ if prefix in {DESKTOP_MODEL_PREFIX, DESKTOP_NO_THINKING_PREFIX}:+ try:+ decoded = bytes.fromhex(remainder).decode("utf-8")+ except ValueError, UnicodeError:+ raise ValueError("Invalid Desktop model ID") from None+ if not remainder or decoded.encode("utf-8").hex() != remainder:+ raise ValueError("Invalid Desktop model ID")+ provider_id, separator, provider_model = decoded.partition("/")+ if not provider_id or not separator or not provider_model:+ raise ValueError("Invalid Desktop model ID")+ return DecodedGatewayModelId(+ provider_id, provider_model, prefix == DESKTOP_NO_THINKING_PREFIX+ )if prefix == GATEWAY_MODEL_ID_PREFIX:force_reasoning_off = Falseelif prefix == NO_THINKING_GATEWAY_MODEL_ID_PREFIX:diff --git a/src/free_claude_code/harnesses/claude_desktop_integration.py b/src/free_claude_code/harnesses/claude_desktop_integration.pynew file mode 100644index 00000000..f29f5772--- /dev/null+++ b/src/free_claude_code/harnesses/claude_desktop_integration.py@@ -0,0 +1,418 @@+"""Manage FCC's own saved Claude Desktop gateway configuration."""++import getpass+import json+import os+import re+import sys+from dataclasses import dataclass+from pathlib import Path+from typing import cast+from urllib.parse import urlsplit+from uuid import NAMESPACE_URL, uuid5++import json5++from free_claude_code.config.server_urls import same_proxy_url+from free_claude_code.core.json_types import JsonObject+from free_claude_code.harnesses.config_file import atomic_write_text++_IDENTITY = (+ "https://github.com/Alishahryar1/free-claude-code/integrations/claude-desktop"+)+FCC_ID = str(uuid5(NAMESPACE_URL, _IDENTITY))+DEFAULT_ID = str(uuid5(NAMESPACE_URL, _IDENTITY + "/default"))+_VIEW_HEADER = "X-FCC-Model-View"+++class ManagedDesktopError(ValueError):+ """Local configuration cannot override an organization policy."""+++class PendingDisconnectError(ValueError):+ """A new connection must wait for the requested removal to finish."""+++class PendingMigrationError(ValueError):+ """Desktop must move its legacy Windows data before FCC creates the new root."""+++def config_root() -> Path:+ home = Path.home()+ if sys.platform == "win32":+ parent = Path(os.environ.get("LOCALAPPDATA") or home / "AppData/Local")+ elif sys.platform == "darwin":+ parent = home / "Library/Application Support"+ else:+ parent = Path(os.environ.get("XDG_CONFIG_HOME") or home / ".config")+ if not parent.is_absolute():+ parent = home / ".config"+ return parent / "Claude-3p"+++def legacy_windows_root() -> Path | None:+ appdata = os.environ.get("APPDATA")+ return Path(appdata) / "Claude-3p" if appdata else None+++def _check_pending_migration(root: Path) -> None:+ if sys.platform != "win32":+ return+ try:+ root.stat()+ except FileNotFoundError:+ pass+ else:+ return+ legacy = legacy_windows_root()+ if legacy is not None:+ try:+ legacy.stat()+ except FileNotFoundError:+ return+ raise PendingMigrationError+++def check_unmanaged() -> None:+ """Conservatively leave managed installations to their administrator."""+ try:+ if sys.platform == "win32":+ import winreg++ for hive in (winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER):+ try:+ with winreg.OpenKey(hive, r"SOFTWARE\Policies\Claude") as key:+ if winreg.QueryInfoKey(key)[1]:+ raise ManagedDesktopError+ except FileNotFoundError:+ pass+ else:+ candidates = (+ [+ Path(+ "/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"+ ),+ Path("/Library/Managed Preferences")+ / getpass.getuser()+ / "com.anthropic.claudefordesktop.plist",+ ]+ if sys.platform == "darwin"+ else [Path("/etc/claude-desktop/managed-settings.json")]+ )+ for path in candidates:+ try:+ path.stat()+ except FileNotFoundError:+ continue+ raise ManagedDesktopError+ except OSError:+ raise ManagedDesktopError from None+++def _read(path: Path) -> JsonObject | None:+ try:+ value = json5.loads(+ path.read_text(encoding="utf-8-sig"), allow_duplicate_keys=False+ )+ except FileNotFoundError:+ return None+ if not isinstance(value, dict):+ raise ValueError("Desktop settings must be objects")+ json.dumps(value, allow_nan=False)+ return cast(JsonObject, value)+++def _write(path: Path, value: JsonObject) -> bool:+ if _read(path) == value:+ return False+ atomic_write_text(path, json.dumps(value, indent=2, allow_nan=False) + "\n")+ return True+++def _headers(profile: JsonObject) -> dict[str, str]:+ value = profile.get("inferenceCustomHeaders", {})+ if not isinstance(value, dict) or any(+ not isinstance(k, str) or not isinstance(v, str) for k, v in value.items()+ ):+ raise ValueError("Invalid Desktop custom headers")+ return cast(dict[str, str], value)+++def _owned(profile: JsonObject) -> bool:+ return profile.get("inferenceProvider") == "gateway" and any(+ key.lower() == _VIEW_HEADER.lower() and value == "claude-desktop"+ for key, value in _headers(profile).items()+ )+++@dataclass+class _Library:+ root: Path+ metadata: JsonObject | None+ entries: list[JsonObject]+ profile: JsonObject | None+ mode: JsonObject++ def file(self, name: str) -> Path:+ return (self.root / name).resolve()++ @property+ def profile_path(self) -> Path:+ return self.file(f"configLibrary/{FCC_ID}.json")++ @property+ def metadata_path(self) -> Path:+ return self.file("configLibrary/_meta.json")++ @property+ def mode_path(self) -> Path:+ return self.file("claude_desktop_config.json")++ @property+ def default_path(self) -> Path:+ return self.file(f"configLibrary/{DEFAULT_ID}.json")++ @property+ def selected(self) -> bool:+ return self.metadata is not None and self.metadata.get("appliedId") == FCC_ID++ @property+ def active(self) -> bool:+ return (+ self.selected+ and self.mode.get("deploymentMode") == "3p"+ and self.metadata is not None+ and not self.metadata.get("hybridPointer")+ )++ def paths(self) -> JsonObject:+ result: JsonObject = {+ "desktop_profile": str(self.profile_path),+ "desktop_library": str(self.metadata_path),+ "desktop_settings": str(self.mode_path),+ }+ if not self.entries or self.selected:+ result["default_profile"] = str(self.default_path)+ return result++ def validate_default(self) -> None:+ if _read(self.default_path) not in (None, {}):+ raise ValueError("Reserved Default configuration is already used")++ def ensure_default(self) -> JsonObject:+ self.validate_default()+ _write(self.default_path, {})+ return {"id": DEFAULT_ID, "name": "Default"}+++def _load(root: Path) -> _Library:+ check_unmanaged()+ library = _Library(root.resolve(), None, [], None, {})+ library.metadata = _read(library.metadata_path)+ library.profile = _read(library.profile_path)+ library.mode = _read(library.mode_path) or {}+ if library.metadata is not None:+ entries = library.metadata.get("entries")+ if not isinstance(entries, list) or not entries:+ raise ValueError("Invalid Desktop configuration library")+ ids: set[str] = set()+ for entry in entries:+ if (+ not isinstance(entry, dict)+ or not isinstance(entry.get("id"), str)+ or not isinstance(entry.get("name"), str)+ ):+ raise ValueError("Invalid Desktop entry")+ entry_id = cast(str, entry["id"])+ if not re.fullmatch(r"[a-f0-9-]{36}", entry_id) or entry_id in ids:+ raise ValueError("Invalid or duplicate Desktop entry ID")+ if entry_id == FCC_ID and entry["name"] != "FCC":+ raise ValueError("FCC profile ID is already used")+ ids.add(entry_id)+ applied_id = library.metadata.get("appliedId")+ if not isinstance(applied_id, str) or applied_id not in ids:+ raise ValueError("Invalid Desktop active entry")+ library.entries = cast(list[JsonObject], entries)+ if library.profile is not None:+ _headers(library.profile)+ registered = any(entry["id"] == FCC_ID for entry in library.entries)+ if library.profile.get("inferenceProvider") != "gateway" or (+ not registered and not _owned(library.profile)+ ):+ raise ValueError("FCC profile ID is already used")+ return library+++def _values(url: str, token: str) -> JsonObject:+ parsed = urlsplit(url)+ if (+ not token+ or not parsed.hostname+ or parsed.username+ or parsed.password+ or parsed.query+ or parsed.fragment+ or parsed.path not in ("", "/")+ ):+ raise ValueError("Invalid Desktop gateway")+ if parsed.scheme != "https" and not (+ parsed.scheme == "http" and parsed.hostname in {"localhost", "127.0.0.1", "::1"}+ ):+ raise ValueError("Desktop requires a loopback HTTP or HTTPS gateway")+ return {+ "inferenceProvider": "gateway",+ "inferenceGatewayBaseUrl": url.rstrip("/"),+ "inferenceCredentialKind": "static",+ "inferenceGatewayApiKey": token,+ "inferenceGatewayAuthScheme": "bearer",+ "modelDiscoveryEnabled": True,+ }+++def _current(library: _Library, values: JsonObject) -> bool:+ profile = library.profile+ return bool(+ library.active+ and profile is not None+ and _owned(profile)+ and all(+ profile.get(key) == value+ for key, value in values.items()+ if key != "inferenceGatewayBaseUrl"+ )+ and same_proxy_url(+ profile.get("inferenceGatewayBaseUrl"),+ str(values["inferenceGatewayBaseUrl"]),+ )+ and "inferenceModels" not in profile+ )+++def _update_profile(library: _Library, values: JsonObject) -> bool:+ profile = dict(library.profile or {})+ headers = {+ k: v for k, v in _headers(profile).items() if k.lower() != _VIEW_HEADER.lower()+ }+ headers[_VIEW_HEADER] = "claude-desktop"+ profile.update(values)+ profile["inferenceCustomHeaders"] = headers+ profile.pop("inferenceModels", None)+ return _write(library.profile_path, profile)+++def _disconnect_intent(path: Path, root: Path) -> bool | None:+ record = _read(path)+ if record is None:+ return None+ if (+ set(record) != {"root", "return_to_sign_in"}+ or record["root"] != str(root.resolve())+ or not isinstance(record["return_to_sign_in"], bool)+ ):+ raise ValueError("Invalid Desktop disconnect record")+ return record["return_to_sign_in"]+++def _empty_profile(path: Path) -> bool:+ try:+ return _read(path) == {}+ except ValueError, UnicodeError:+ # A user may change the neutral profile between a failure and retry.+ return False+++def _disconnect(library: _Library, path: Path, intent: bool | None) -> None:+ has_entry = any(entry["id"] == FCC_ID for entry in library.entries)+ if not has_entry and library.profile is None and intent is None:+ return+ if library.selected:+ library.validate_default()+ return_to_sign_in = intent is True or library.selected+ _write(path, {"root": str(library.root), "return_to_sign_in": return_to_sign_in})+ if library.selected:+ default = library.ensure_default()+ entries = list(library.entries)+ if not any(entry["id"] == DEFAULT_ID for entry in entries):+ entries.append(default)+ metadata = dict(library.metadata or {})+ metadata.update({"entries": entries, "appliedId": DEFAULT_ID})+ metadata.pop("hybridPointer", None)+ _write(library.metadata_path, metadata)+ library = _load(library.root)+ if (+ return_to_sign_in+ and library.metadata is not None+ and library.metadata.get("appliedId") == DEFAULT_ID+ and not library.metadata.get("hybridPointer")+ and _empty_profile(library.default_path)+ ):+ _write(library.mode_path, library.mode | {"deploymentMode": "1p"})+ # Keep the registered ownership until unlink succeeds, even if its header+ # was changed. A retry after unlink safely accepts the missing profile.+ library.profile_path.unlink(missing_ok=True)+ library = _load(library.root)+ entries = [entry for entry in library.entries if entry["id"] != FCC_ID]+ if len(entries) != len(library.entries):+ metadata = dict(library.metadata or {})+ metadata["entries"] = entries+ _write(library.metadata_path, metadata)+ remaining = _load(library.root)+ if remaining.profile is not None or any(+ entry["id"] == FCC_ID for entry in remaining.entries+ ):+ raise ValueError("Desktop disconnect cleanup is incomplete")+ path.unlink(missing_ok=True)+++def refresh_connected(+ root: Path, proxy_root_url: str, auth_token: str, *, disconnect_path: Path+) -> bool:+ library = _load(root)+ if _disconnect_intent(disconnect_path, root) is not None:+ return False+ if not library.active or library.profile is None:+ return False+ return _update_profile(library, _values(proxy_root_url, auth_token))+++def configure(+ root: Path,+ proxy_root_url: str,+ auth_token: str,+ connected: bool | None = None,+ *,+ disconnect_path: Path,+) -> JsonObject:+ library = _load(root)+ disconnect_path = disconnect_path.resolve()+ intent = _disconnect_intent(disconnect_path, root)+ if connected is True:+ if intent is not None:+ raise PendingDisconnectError+ _check_pending_migration(library.root)+ values = _values(proxy_root_url, auth_token)+ if not library.entries:+ library.validate_default()+ library.entries = [library.ensure_default()]+ _update_profile(library, values)+ entries = [entry for entry in library.entries if entry["id"] != FCC_ID]+ entries.append({"id": FCC_ID, "name": "FCC"})+ metadata = dict(library.metadata or {})+ metadata.update({"entries": entries, "appliedId": FCC_ID})+ metadata.pop("hybridPointer", None)+ _write(library.metadata_path, metadata)+ _write(library.mode_path, library.mode | {"deploymentMode": "3p"})+ elif connected is False:+ _disconnect(library, disconnect_path, intent)+ if connected is not None:+ library = _load(root)+ is_connected = (+ library.active and library.profile is not None and connected is not False+ )+ if is_connected:+ is_connected = _current(library, _values(proxy_root_url, auth_token))+ return {+ "connected": is_connected,+ "disconnect_pending": _disconnect_intent(disconnect_path, root) is not None,+ "paths": library.paths() | {"disconnect_record": str(disconnect_path)},+ }diff --git a/src/free_claude_code/runtime/application.py b/src/free_claude_code/runtime/application.pyindex d1869cf7..252d1a33 100644--- a/src/free_claude_code/runtime/application.py+++ b/src/free_claude_code/runtime/application.py@@ -35,13 +35,18 @@ from 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_typefrom 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_urlfrom free_claude_code.config.settings import Settingsfrom free_claude_code.core.json_types import JsonObject-from free_claude_code.harnesses import claude_integration, codex_integration+from free_claude_code.harnesses import (+ claude_desktop_integration,+ claude_integration,+ codex_integration,+)from free_claude_code.messaging.platforms import factory as messaging_platform_factoryfrom free_claude_code.messaging.platforms.factory import MessagingPlatformOptionsfrom free_claude_code.messaging.platforms.ports import (@@ -208,6 +213,7 @@ class ApplicationRuntime:self._lifecycle_lock = asyncio.Lock()self._startup_tasks: list[asyncio.Task[None]] = []self._claude_update = _IntegrationUpdate()+ self._desktop_update = _IntegrationUpdate()self._codex_update = _IntegrationUpdate()self._http_ready = asyncio.Event()self._messaging_state = (@@ -244,6 +250,7 @@ class ApplicationRuntime:self.provider_manager.start_model_list_refresh()await self.refresh_claude_vscode()await self.refresh_codex_integration()+ await self.refresh_claude_desktop()self._startup_tasks.append(asyncio.create_task(run_sync_owned(remove_retired_chat_history),@@ -470,6 +477,75 @@ class ApplicationRuntime:self._codex_update, partial(self._codex_integration, "refresh"))+ 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()@@ -609,6 +685,7 @@ class ApplicationRuntime:},"integrations": {"claude-vscode": self._claude_update.snapshot(),+ "claude-desktop": self._desktop_update.snapshot(),"codex": self._codex_update.snapshot(),},},diff --git a/tests/api/test_claude_desktop_integration.py b/tests/api/test_claude_desktop_integration.pynew file mode 100644index 00000000..4436da1b--- /dev/null+++ b/tests/api/test_claude_desktop_integration.py@@ -0,0 +1,197 @@+import json+from pathlib import Path+from unittest.mock import patch++import pytest+from fastapi.testclient import TestClient++from free_claude_code.application.errors import InvalidRequestError+from free_claude_code.application.routing import ModelRouter+from free_claude_code.config.settings import Settings+from free_claude_code.core.gateway_model_ids import desktop_model_id+from free_claude_code.harnesses import claude_desktop_integration as desktop+from tests.api.support import create_test_app++ROOT = "/admin/api/integrations/claude-desktop"+++def test_pending_disconnect_survives_runtime_restart(monkeypatch):+ settings = Settings(host="127.0.0.1", port=4321, proxy_auth_token="original")+ root = desktop.config_root()+ profile = root / "configLibrary" / f"{desktop.FCC_ID}.json"+ unlink = Path.unlink++ def fail(path, *args, **kwargs):+ if path == profile:+ raise PermissionError("test")+ return unlink(path, *args, **kwargs)++ with TestClient(+ create_test_app(settings),+ base_url="http://127.0.0.1",+ client=("127.0.0.1", 50000),+ ) as client:+ assert client.post(ROOT + "/connect").status_code == 200+ with monkeypatch.context() as patch:+ patch.setattr(Path, "unlink", fail)+ assert client.post(ROOT + "/disconnect").status_code == 503+ assert client.get(ROOT).json()["disconnect_pending"] is True+ before = profile.read_bytes()+ with TestClient(+ create_test_app(settings.model_copy(update={"proxy_auth_token": "rotated"})),+ base_url="http://127.0.0.1",+ client=("127.0.0.1", 50000),+ ) as client:+ status = client.get(ROOT).json()+ assert status["disconnect_pending"] is True+ assert profile.read_bytes() == before+ refused = client.post(ROOT + "/connect")+ assert refused.status_code == 400+ assert "Finish disconnecting" in refused.json()["detail"]+ result = client.post(ROOT + "/disconnect").json()+ assert result["connected"] is False+ assert result["disconnect_pending"] is False+ assert not profile.exists()+++def client():+ app = create_test_app(+ Settings(host="0.0.0.0", port=4321, proxy_auth_token="desktop-secret")+ )+ with TestClient(+ app, base_url="http://127.0.0.1", client=("127.0.0.1", 50000)+ ) as client:+ yield client+++def test_desktop_routes_connect_disconnect_and_hide_credentials(client):+ root = desktop.config_root()+ response = client.get(ROOT)+ assert response.json()["connected"] is False+ assert response.headers["cache-control"] == "no-store"+ assert not root.exists()+ response = client.post(ROOT + "/connect")+ assert response.status_code == 200+ assert response.json()["connected"] is True+ assert "desktop-secret" not in response.text+ profile = root / "configLibrary" / f"{desktop.FCC_ID}.json"+ assert (+ json.loads(profile.read_text())["inferenceGatewayBaseUrl"]+ == "http://127.0.0.1:4321"+ )+ before = {path: path.stat().st_mtime_ns for path in root.rglob("*.json")}+ assert client.get(ROOT).json()["connected"] is True+ assert before == {path: path.stat().st_mtime_ns for path in root.rglob("*.json")}+ assert client.post(ROOT + "/disconnect").json()["connected"] is False+ assert not profile.exists()++[email protected]("action", ["", "/connect", "/disconnect", "/refresh"])+def test_desktop_admin_routes_reject_other_origins(client, action):+ response = client.request(+ "POST" if action else "GET",+ ROOT + action,+ headers={"Origin": "https://evil.test"},+ )+ assert response.status_code == 403+ assert not desktop.config_root().exists()+++def test_managed_desktop_error_is_safe(client, monkeypatch):+ def managed():+ raise desktop.ManagedDesktopError("private-policy-secret")++ monkeypatch.setattr(desktop, "check_unmanaged", managed)+ response = client.post(ROOT + "/connect")+ assert response.status_code == 400+ assert "private-policy-secret" not in response.text+ assert "organization" in response.json()["detail"]+++def test_desktop_model_view_preserves_labels_and_query_precedence():+ ref = "nvidia_nim/nemotron-3.5"+ settings = Settings().model_copy(+ update={+ "model": ref,+ "model_opus": None,+ "model_haiku": None,+ "model_fallbacks": (),+ "proxy_auth_enabled": False,+ }+ )+ with TestClient(create_test_app(settings)) as client:+ headers = {"X-FCC-Model-View": "claude-desktop"}+ payload = client.get("/v1/models", headers=headers).json()+ models = [row for row in payload["data"] if "/" in row["id"]]+ assert [row["id"] for row in models] == [+ desktop_model_id(ref),+ desktop_model_id(ref, no_thinking=True),+ ]+ assert [row["display_name"] for row in models] == [ref, ref + " (no thinking)"]+ regular = client.get("/v1/models").json()+ assert client.get("/v1/models?view=claude", headers=headers).json() == regular+ assert (+ client.get(+ "/v1/models", headers={"X-FCC-Model-View": "invalid"}+ ).status_code+ == 422+ )+ route = ModelRouter(settings).resolve(models[0]["id"])+ assert route.primary.provider_model_ref == ref+ assert (+ ModelRouter(settings).resolve(models[1]["id"]).reasoning_preference.value+ == "off"+ )+++ "model",+ ["claude-fcc/", "claude-fcc/zz", "claude-fcc", desktop_model_id("unknown/model")],+)+def test_invalid_desktop_model_never_routes_to_default(model):+ with pytest.raises(InvalidRequestError):+ ModelRouter(Settings()).resolve(model)++[email protected]("no_thinking", [False, True])+def test_desktop_token_count_routes_to_original_provider(no_thinking):+ ref = "groq/desktop-model"+ app = create_test_app(Settings(proxy_auth_enabled=False))+ with (+ TestClient(app) as client,+ patch("free_claude_code.api.routes.get_token_count", return_value=7),+ patch("free_claude_code.api.handlers.token_count.trace_event") as trace,+ ):+ response = client.post(+ "/v1/messages/count_tokens",+ json={+ "model": desktop_model_id(ref, no_thinking=no_thinking),+ "messages": [{"role": "user", "content": "hello"}],+ },+ )+ assert response.status_code == 200+ assert response.json()["input_tokens"] == 7+ routed = next(+ call.kwargs+ for call in trace.call_args_list+ if call.kwargs["stage"] == "routing"+ )+ assert routed["provider_model_ref"] == ref+++def test_pending_windows_migration_reports_recovery_without_writes(client, monkeypatch):+ monkeypatch.setattr(desktop.sys, "platform", "win32")+ legacy = desktop.legacy_windows_root()+ assert legacy is not None+ legacy.mkdir()+ history = legacy / "history.json"+ history.write_text('{"chat":"keep"}')+ response = client.post(ROOT + "/connect")+ assert response.status_code == 400+ detail = response.json()["detail"]+ assert "Launch Claude Desktop" in detail+ assert "quit" in detail+ assert "retry Connect" in detail+ assert not desktop.config_root().exists()+ assert history.read_text() == '{"chat":"keep"}'diff --git a/tests/conftest.py b/tests/conftest.pyindex 5a5d5d72..4488d960 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -9,7 +9,11 @@ import pytestfrom free_claude_code.config import env_migrations, pathsfrom free_claude_code.config.loader import clear_settings_cache-from free_claude_code.harnesses import claude_integration, codex_integration+from free_claude_code.harnesses import (+ claude_desktop_integration,+ claude_integration,+ codex_integration,+)from tests.providers.support import (immediate_admission,make_provider_config,@@ -28,6 +32,15 @@ def _isolate_managed_config(monkeypatch, tmp_path):"""Keep every test away from real home, checkout, and running-server config."""config_dir = tmp_path / ".fcc"+ monkeypatch.setattr(+ claude_desktop_integration, "config_root", lambda: tmp_path / "Claude-3p"+ )+ monkeypatch.setattr(claude_desktop_integration, "check_unmanaged", lambda: None)+ monkeypatch.setattr(+ claude_desktop_integration,+ "legacy_windows_root",+ lambda: tmp_path / "LegacyClaude-3p",+ )monkeypatch.setattr(paths, "config_dir_path", lambda: config_dir)monkeypatch.setattr(env_migrations, "legacy_env_paths", lambda: ())monkeypatch.setattr(env_migrations, "verified_checkout_env_path", lambda: None)diff --git a/tests/core/test_desktop_model_ids.py b/tests/core/test_desktop_model_ids.pynew file mode 100644index 00000000..511bcdda--- /dev/null+++ b/tests/core/test_desktop_model_ids.py@@ -0,0 +1,36 @@+import pytest++from free_claude_code.core.gateway_model_ids import (+ decode_gateway_model_id,+ desktop_model_id,+)+++ "ref",+ [+ "nvidia_nim/nemotron-3.5",+ "open_router/qwen/qwen3",+ "openai/gpt-5",+ "open_router/模型/one",+ ],+)[email protected]("no_thinking", [False, True])+def test_desktop_ids_roundtrip_without_vendor_fragments(ref, no_thinking):+ wire = desktop_model_id(ref, no_thinking=no_thinking)+ assert wire.startswith("claude-")+ assert not any(part in wire for part in ("gpt", "qwen", "nemotron", "openai"))+ decoded = decode_gateway_model_id(wire)+ assert decoded is not None+ assert f"{decoded.provider_id}/{decoded.provider_model}" == ref+ assert decoded.force_reasoning_off is no_thinking+ assert desktop_model_id(ref, no_thinking=no_thinking) == wire+++ "suffix", ["", "ff", "not-hex", "123", "6E", "6162", "2f78", "782f", "61 2f62"]+)[email protected]("prefix", ["claude-fcc/", "claude-3-fcc/"])+def test_malformed_reserved_ids_do_not_fall_through(prefix, suffix):+ with pytest.raises(ValueError):+ decode_gateway_model_id(prefix + suffix)diff --git a/tests/harnesses/test_claude_desktop_integration.py b/tests/harnesses/test_claude_desktop_integration.pynew file mode 100644index 00000000..ad508a9b--- /dev/null+++ b/tests/harnesses/test_claude_desktop_integration.py@@ -0,0 +1,653 @@+import json+from contextlib import nullcontext+from pathlib import Path+from types import SimpleNamespace++import pytest++from free_claude_code.config.paths import claude_desktop_disconnect_path+from free_claude_code.harnesses import claude_desktop_integration as desktop+from free_claude_code.harnesses.claude_desktop_integration import (+ check_unmanaged,+ config_root,+)++URL = "http://127.0.0.1:8000"+TOKEN = "desktop-test-token"+++def test_connect_preserves_pending_windows_migration(tmp_path, monkeypatch):+ root = tmp_path / "Local/Claude-3p"+ legacy = tmp_path / "Roaming/Claude-3p"+ record = claude_desktop_disconnect_path()+ monkeypatch.setattr(desktop.sys, "platform", "win32")+ monkeypatch.setattr(desktop, "legacy_windows_root", lambda: legacy)+ other = "11111111-1111-4111-8111-111111111111"+ write(legacy / "configLibrary" / f"{other}.json", {"user": "settings"})+ write(+ meta(legacy), {"appliedId": other, "entries": [{"id": other, "name": "Other"}]}+ )+ write(legacy / "claude-code-sessions/history.json", {"chat": "keep"})+ before = {p.relative_to(legacy): p.read_bytes() for p in legacy.rglob("*.json")}+ assert not desktop.configure(root, URL, TOKEN, disconnect_path=record)["connected"]+ assert not desktop.refresh_connected(root, URL, TOKEN, disconnect_path=record)+ with pytest.raises(desktop.PendingMigrationError):+ desktop.configure(root, URL, TOKEN, True, disconnect_path=record)+ assert not root.exists()+ assert not record.exists()+ assert {+ p.relative_to(legacy): p.read_bytes() for p in legacy.rglob("*.json")+ } == before+ # Simulate Desktop completing its own native migration, then retry Connect.+ root.parent.mkdir(parents=True)+ legacy.rename(root)+ assert desktop.configure(root, URL, TOKEN, True, disconnect_path=record)[+ "connected"+ ]+ assert (root / "configLibrary" / f"{other}.json").read_bytes() == before[+ Path("configLibrary") / f"{other}.json"+ ]+ assert (root / "claude-code-sessions/history.json").read_bytes() == before[+ Path("claude-code-sessions/history.json")+ ]+++ "platform,existing_root,existing_legacy",+ [("win32", False, False), ("win32", True, True), ("darwin", False, True)],+)+def test_connect_allowed_without_pending_migration(+ tmp_path, monkeypatch, platform, existing_root, existing_legacy+):+ root = tmp_path / "current"+ legacy = tmp_path / "legacy"+ monkeypatch.setattr(desktop.sys, "platform", platform)+ monkeypatch.setattr(desktop, "legacy_windows_root", lambda: legacy)+ if existing_root:+ root.mkdir()+ if existing_legacy:+ write(legacy / "history.json", {"chat": "keep"})+ assert desktop.configure(+ root, URL, TOKEN, True, disconnect_path=claude_desktop_disconnect_path()+ )["connected"]+ if existing_legacy:+ assert read(legacy / "history.json") == {"chat": "keep"}+++ "platform,variable,suffix",+ [+ ("win32", "LOCALAPPDATA", "local/Claude-3p"),+ ("darwin", None, "Library/Application Support/Claude-3p"),+ ("linux", "XDG_CONFIG_HOME", "local/Claude-3p"),+ ],+)+def test_platform_config_root(monkeypatch, tmp_path, platform, variable, suffix):+ monkeypatch.setattr(desktop.sys, "platform", platform)+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ if variable:+ monkeypatch.setenv(variable, str(tmp_path / "local"))+ assert config_root() == tmp_path / suffix++[email protected]("state", ["absent", "empty", "policy", "unreadable"])+def test_windows_policy_boundary(monkeypatch, state):+ opened = []++ def open_key(hive, path):+ opened.append((hive, path))+ if state == "absent":+ raise FileNotFoundError+ if state == "unreadable":+ raise PermissionError+ return nullcontext("test-key")++ monkeypatch.setattr(desktop.sys, "platform", "win32")+ monkeypatch.setitem(+ desktop.sys.modules,+ "winreg",+ SimpleNamespace(+ HKEY_LOCAL_MACHINE=1,+ HKEY_CURRENT_USER=2,+ OpenKey=open_key,+ QueryInfoKey=lambda key: (0, int(state == "policy"), 0),+ ),+ )+ if state in {"policy", "unreadable"}:+ with pytest.raises(desktop.ManagedDesktopError):+ check_unmanaged()+ else:+ check_unmanaged()+ assert opened == [+ (1, r"SOFTWARE\Policies\Claude"),+ (2, r"SOFTWARE\Policies\Claude"),+ ]+++def read(path):+ return json.loads(path.read_text())+++def write(path, value):+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(value))+++def profile(root):+ return root / "configLibrary" / f"{desktop.FCC_ID}.json"+++def meta(root):+ return root / "configLibrary" / "_meta.json"+++def mode(root):+ return root / "claude_desktop_config.json"+++def test_fresh_connection_and_disconnect_preserve_native_library(tmp_path):+ root = tmp_path / "desktop"+ assert (+ desktop.configure(+ root, URL, TOKEN, disconnect_path=claude_desktop_disconnect_path()+ )["connected"]+ is False+ )+ assert not root.exists()+ assert (+ desktop.refresh_connected(+ root, URL, TOKEN, disconnect_path=claude_desktop_disconnect_path()+ )+ is False+ )+ assert not root.exists()+ assert (+ desktop.configure(+ root, URL, TOKEN, True, disconnect_path=claude_desktop_disconnect_path()+ )["connected"]+ is True+ )+ assert read(meta(root))["appliedId"] == desktop.FCC_ID+ assert read(mode(root))["deploymentMode"] == "3p"+ assert read(profile(root))["inferenceGatewayApiKey"] == TOKEN+ before = {p: p.read_bytes() for p in root.rglob("*.json")}+ assert (+ desktop.refresh_connected(+ root, URL, TOKEN, disconnect_path=claude_desktop_disconnect_path()+ )+ is False+ )+ desktop.configure(+ root, URL, TOKEN, True, disconnect_path=claude_desktop_disconnect_path()+ )+ assert {p: p.read_bytes() for p in root.rglob("*.json")} == before+ assert (+ desktop.configure(+ root, URL, TOKEN, False, disconnect_path=claude_desktop_disconnect_path()+ )["connected"]+ is False+ )+ assert not profile(root).exists()+ assert read(mode(root))["deploymentMode"] == "1p"+ assert read(meta(root))["entries"] == [+ {"id": desktop.DEFAULT_ID, "name": "Default"}+ ]+ assert read(root / "configLibrary" / f"{desktop.DEFAULT_ID}.json") == {}+ after = {p: p.read_bytes() for p in root.rglob("*.json")}+ desktop.configure(+ root, URL, TOKEN, False, disconnect_path=claude_desktop_disconnect_path()+ )+ assert {p: p.read_bytes() for p in root.rglob("*.json")} == after+++def test_refresh_rotates_credentials_without_reactivating(tmp_path):+ desktop.configure(+ tmp_path, URL, TOKEN, True, disconnect_path=claude_desktop_disconnect_path()+ )+ assert desktop.refresh_connected(+ tmp_path,+ "http://localhost:9000",+ "new-token",+ disconnect_path=claude_desktop_disconnect_path(),+ )+ assert desktop.configure(+ tmp_path,+ "http://localhost:9000",+ "new-token",+ disconnect_path=claude_desktop_disconnect_path(),+ )["connected"]+ write(mode(tmp_path), {"deploymentMode": "1p", "unrelated": True})+ before = profile(tmp_path).read_bytes()+ assert not desktop.refresh_connected(+ tmp_path, URL, TOKEN, disconnect_path=claude_desktop_disconnect_path()+ )+ assert profile(tmp_path).read_bytes() == before+ assert read(mode(tmp_path))["unrelated"] is True+++def test_refresh_repairs_registered_profile_header_without_changing_selection(tmp_path):+ desktop.configure(+ tmp_path, URL, TOKEN, True, disconnect_path=claude_desktop_disconnect_path()+ )+ config = read(profile(tmp_path))+ config["inferenceCustomHeaders"] = {"X-Other": "preserved"}+ write(profile(tmp_path), config)+ metadata = meta(tmp_path).read_bytes()+ assert not desktop.configure(+ tmp_path, URL, TOKEN, disconnect_path=claude_desktop_disconnect_path()+ )["connected"]+ assert desktop.refresh_connected(+ tmp_path, URL, TOKEN, disconnect_path=claude_desktop_disconnect_path()+ )+ assert desktop.configure(+ tmp_path, URL, TOKEN, disconnect_path=claude_desktop_disconnect_path()+ )["connected"]+ assert meta(tmp_path).read_bytes() == metadata+ assert read(profile(tmp_path))["inferenceCustomHeaders"] == {+ "X-Other": "preserved",+ "X-FCC-Model-View": "claude-desktop",+ }+++ "failure",+ ["intent", "default", "selection", "mode", "profile", "metadata", "record"],+)+def test_disconnect_recovers_every_failure_boundary(tmp_path, monkeypatch, failure):+ record = claude_desktop_disconnect_path()+ desktop.configure(tmp_path, URL, TOKEN, True, disconnect_path=record)+ write(+ meta(tmp_path),+ {+ "appliedId": desktop.FCC_ID,+ "entries": [{"id": desktop.FCC_ID, "name": "FCC"}],+ },+ )+ default = tmp_path / "configLibrary" / f"{desktop.DEFAULT_ID}.json"+ default.unlink()+ atomic, unlink = desktop.atomic_write_text, Path.unlink++ def fail_write(path, content):+ value = json.loads(content)+ step = (+ "intent"+ if path == record+ else "default"+ if path == default+ else "mode"+ if path == mode(tmp_path)+ else "selection"+ if any(e["id"] == desktop.FCC_ID for e in value.get("entries", []))+ else "metadata"+ )+ if step == failure:+ raise PermissionError("test")+ atomic(path, content)++ def fail_unlink(path, *args, **kwargs):+ if (failure == "profile" and path == profile(tmp_path)) or (+ failure == "record" and path == record+ ):+ raise PermissionError("test")+ return unlink(path, *args, **kwargs)++ with monkeypatch.context() as patch:+ patch.setattr(desktop, "atomic_write_text", fail_write)+ patch.setattr(Path, "unlink", fail_unlink)+ with pytest.raises(PermissionError):+ desktop.configure(tmp_path, URL, TOKEN, False, disconnect_path=record)+ selected = read(meta(tmp_path))["appliedId"]+ assert (tmp_path / "configLibrary" / f"{selected}.json").exists()+ status = desktop.configure(tmp_path, URL, TOKEN, disconnect_path=record)+ assert status["disconnect_pending"] is (failure != "intent")+ assert TOKEN not in json.dumps(status)+ before = {p: p.read_bytes() for p in tmp_path.rglob("*.json")}+ if record.exists():+ assert not desktop.refresh_connected(+ tmp_path, URL, "rotated-token", disconnect_path=record+ )+ assert {p: p.read_bytes() for p in tmp_path.rglob("*.json")} == before+ if record.exists():+ with pytest.raises(desktop.PendingDisconnectError):+ desktop.configure(tmp_path, URL, TOKEN, True, disconnect_path=record)+ result = desktop.configure(tmp_path, URL, TOKEN, False, disconnect_path=record)+ assert result["connected"] is False+ assert result["disconnect_pending"] is False+ assert not profile(tmp_path).exists()+ assert not record.exists()+ assert read(meta(tmp_path))["appliedId"] == desktop.DEFAULT_ID+ assert read(mode(tmp_path))["deploymentMode"] == "1p"+ before = {p: p.read_bytes() for p in tmp_path.rglob("*.json")}+ desktop.configure(tmp_path, URL, TOKEN, False, disconnect_path=record)+ assert {p: p.read_bytes() for p in tmp_path.rglob("*.json")} == before+++def test_other_profiles_and_unknown_settings_are_preserved(tmp_path):+ other = "11111111-1111-4111-8111-111111111111"+ other_path = tmp_path / "configLibrary" / f"{other}.json"+ write(other_path, {"inferenceProvider": "gateway", "secret": "other-secret"})+ write(+ meta(tmp_path),+ {"entries": [{"id": other, "name": "Other"}], "appliedId": other, "extra": 1},+ )+ write(mode(tmp_path), {"deploymentMode": "3p", "keep": "yes"})+ before = other_path.read_bytes()+ desktop.configure(+ tmp_path, URL, TOKEN, True, disconnect_path=claude_desktop_disconnect_path()+ )+ config = read(profile(tmp_path))+ config["keep"] = True+ config["inferenceCustomHeaders"]["X-Other"] = "value"+ config["inferenceModels"] = ["old-model"]+ write(profile(tmp_path), config)+ desktop.refresh_connected(+ tmp_path, URL, TOKEN, disconnect_path=claude_desktop_disconnect_path()+ )+ assert read(profile(tmp_path))["keep"] is True+ assert read(profile(tmp_path))["inferenceCustomHeaders"]["X-Other"] == "value"+ assert "inferenceModels" not in read(profile(tmp_path))+ metadata = read(meta(tmp_path))+ metadata["appliedId"] = other+ metadata["hybridPointer"] = {"bootstrapUrl": "https://example.test"}+ write(meta(tmp_path), metadata)+ assert not desktop.refresh_connected(+ tmp_path, URL, TOKEN, disconnect_path=claude_desktop_disconnect_path()+ )+ desktop.configure(+ tmp_path, URL, TOKEN, False, disconnect_path=claude_desktop_disconnect_path()+ )+ assert read(meta(tmp_path))["appliedId"] == other+ assert "hybridPointer" in read(meta(tmp_path))+ assert read(meta(tmp_path))["extra"] == 1+ assert read(mode(tmp_path)) == {"deploymentMode": "3p", "keep": "yes"}+ assert other_path.read_bytes() == before++[email protected]("failed_write", [1, 2, 3, 4])+def test_connect_partial_write_is_retryable(tmp_path, monkeypatch, failed_write):+ atomic = desktop.atomic_write_text+ calls = 0++ def fail(path, content):+ nonlocal calls+ calls += 1+ if calls == failed_write:+ raise PermissionError("test")+ atomic(path, content)++ monkeypatch.setattr(desktop, "atomic_write_text", fail)+ with pytest.raises(PermissionError):+ desktop.configure(+ tmp_path, URL, TOKEN, True, disconnect_path=claude_desktop_disconnect_path()+ )+ assert not mode(tmp_path).exists()+ monkeypatch.setattr(desktop, "atomic_write_text", atomic)+ assert desktop.configure(+ tmp_path, URL, TOKEN, True, disconnect_path=claude_desktop_disconnect_path()+ )["connected"]++[email protected]("missing_header", [False, True])+def test_disconnect_recovers_orphan_after_delete_failure(+ tmp_path, monkeypatch, missing_header+):+ desktop.configure(+ tmp_path, URL, TOKEN, True, disconnect_path=claude_desktop_disconnect_path()+ )+ if missing_header:+ config = read(profile(tmp_path))+ config.pop("inferenceCustomHeaders")+ write(profile(tmp_path), config)+ unlink = Path.unlink++ def fail(path, *args, **kwargs):+ if path == profile(tmp_path):+ raise PermissionError("test")+ return unlink(path, *args, **kwargs)++ monkeypatch.setattr(Path, "unlink", fail)+ with pytest.raises(PermissionError):+ desktop.configure(+ tmp_path,+ URL,+ TOKEN,+ False,+ disconnect_path=claude_desktop_disconnect_path(),+ )+ assert read(mode(tmp_path))["deploymentMode"] == "1p"+ assert read(meta(tmp_path))["appliedId"] != desktop.FCC_ID+ monkeypatch.setattr(Path, "unlink", unlink)+ desktop.configure(+ tmp_path, URL, TOKEN, False, disconnect_path=claude_desktop_disconnect_path()+ )+ assert not profile(tmp_path).exists()+++def test_disconnect_last_entry_creates_default(tmp_path):+ desktop.configure(+ tmp_path, URL, TOKEN, True, disconnect_path=claude_desktop_disconnect_path()+ )+ write(+ meta(tmp_path),+ {+ "appliedId": desktop.FCC_ID,+ "entries": [{"id": desktop.FCC_ID, "name": "FCC"}],+ },+ )+ (tmp_path / "configLibrary" / f"{desktop.DEFAULT_ID}.json").unlink()+ status = desktop.configure(+ tmp_path, URL, TOKEN, disconnect_path=claude_desktop_disconnect_path()+ )+ paths = status["paths"]+ assert isinstance(paths, dict)+ assert "default_profile" in paths+ desktop.configure(+ tmp_path, URL, TOKEN, False, disconnect_path=claude_desktop_disconnect_path()+ )+ assert read(meta(tmp_path))["appliedId"] == desktop.DEFAULT_ID+++ "metadata",+ [+ [],+ {},+ {"entries": []},+ {"entries": [{"id": desktop.FCC_ID, "name": "FCC"}], "appliedId": []},+ {"entries": [{"id": desktop.FCC_ID, "name": "FCC"}], "appliedId": {}},+ {+ "entries": [{"id": "../../other", "name": "Other"}],+ "appliedId": "../../other",+ },+ ],+)+def test_invalid_metadata_is_never_overwritten(tmp_path, metadata):+ write(meta(tmp_path), metadata)+ before = meta(tmp_path).read_bytes()+ with pytest.raises(ValueError):+ desktop.configure(+ tmp_path, URL, TOKEN, True, disconnect_path=claude_desktop_disconnect_path()+ )+ assert meta(tmp_path).read_bytes() == before+ assert not profile(tmp_path).exists()+++def test_reserved_profile_collision_is_not_overwritten(tmp_path):+ write(profile(tmp_path), {"inferenceProvider": "bedrock"})+ with pytest.raises(ValueError):+ desktop.configure(+ tmp_path, URL, TOKEN, True, disconnect_path=claude_desktop_disconnect_path()+ )+ assert read(profile(tmp_path)) == {"inferenceProvider": "bedrock"}++[email protected]("url,token", [("http://192.0.2.1:8000", TOKEN), (URL, "")])+def test_invalid_gateway_does_not_write(tmp_path, url, token):+ with pytest.raises(ValueError):+ desktop.configure(+ tmp_path, url, token, True, disconnect_path=claude_desktop_disconnect_path()+ )+ assert not list(tmp_path.rglob("*.json"))+++def test_disconnect_selects_empty_profile_not_other_forced_gateway(tmp_path):+ other = "11111111-1111-4111-8111-111111111111"+ other_path = tmp_path / "configLibrary" / f"{other}.json"+ write(+ other_path,+ {"inferenceProvider": "gateway", "disableDeploymentModeChooser": True},+ )+ write(+ meta(tmp_path),+ {"entries": [{"id": other, "name": "Other"}], "appliedId": other},+ )+ before = other_path.read_bytes()+ desktop.configure(+ tmp_path, URL, TOKEN, True, disconnect_path=claude_desktop_disconnect_path()+ )+ desktop.configure(+ tmp_path, URL, TOKEN, False, disconnect_path=claude_desktop_disconnect_path()+ )+ selected = read(meta(tmp_path))["appliedId"]+ # Native Desktop gives a selected provider's disabled chooser priority over 1p.+ assert read(tmp_path / "configLibrary" / f"{selected}.json") == {}+ assert other_path.read_bytes() == before+++def test_unlink_failure_remains_retryable_after_status_reload(tmp_path, monkeypatch):+ desktop.configure(+ tmp_path, URL, TOKEN, True, disconnect_path=claude_desktop_disconnect_path()+ )+ unlink = Path.unlink++ def fail(path, *args, **kwargs):+ if path == profile(tmp_path):+ raise PermissionError("busy")+ return unlink(path, *args, **kwargs)++ monkeypatch.setattr(Path, "unlink", fail)+ with pytest.raises(PermissionError):+ desktop.configure(+ tmp_path,+ URL,+ TOKEN,+ False,+ disconnect_path=claude_desktop_disconnect_path(),+ )+ status = desktop.configure(+ tmp_path, URL, TOKEN, disconnect_path=claude_desktop_disconnect_path()+ )+ assert status["connected"] is False+ assert status["disconnect_pending"] is True+ assert not desktop.refresh_connected(+ tmp_path, URL, TOKEN, disconnect_path=claude_desktop_disconnect_path()+ )++[email protected]("change", ["selection", "hybrid", "default"])+def test_retry_preserves_a_later_external_choice(tmp_path, monkeypatch, change):+ record = claude_desktop_disconnect_path()+ desktop.configure(tmp_path, URL, TOKEN, True, disconnect_path=record)+ atomic = desktop.atomic_write_text++ def fail_mode(path, content):+ if path == mode(tmp_path):+ raise PermissionError("test")+ atomic(path, content)++ with monkeypatch.context() as patch:+ patch.setattr(desktop, "atomic_write_text", fail_mode)+ with pytest.raises(PermissionError):+ desktop.configure(tmp_path, URL, TOKEN, False, disconnect_path=record)+ metadata = read(meta(tmp_path))+ if change == "selection":+ other = "11111111-1111-4111-8111-111111111111"+ write(+ tmp_path / "configLibrary" / f"{other}.json",+ {"inferenceProvider": "gateway"},+ )+ metadata["entries"].append({"id": other, "name": "Other"})+ metadata["appliedId"] = other+ elif change == "hybrid":+ metadata["hybridPointer"] = {"bootstrapUrl": "https://example.test"}+ else:+ write(+ tmp_path / "configLibrary" / f"{desktop.DEFAULT_ID}.json",+ {"inferenceProvider": "gateway", "disableDeploymentModeChooser": True},+ )+ write(meta(tmp_path), metadata)+ before = {+ p: p.read_bytes()+ for p in tmp_path.rglob("*.json")+ if p not in {meta(tmp_path), profile(tmp_path), record}+ }+ desktop.configure(tmp_path, URL, TOKEN, False, disconnect_path=record)+ expected = metadata | {+ "entries": [e for e in metadata["entries"] if e["id"] != desktop.FCC_ID]+ }+ assert read(meta(tmp_path)) == expected+ assert all(p.read_bytes() == content for p, content in before.items())+ assert not record.exists()+ assert not profile(tmp_path).exists()+++ "record_value",+ [+ {},+ [],+ {"root": "elsewhere", "return_to_sign_in": True},+ {"return_to_sign_in": True},+ {"root": "ROOT", "return_to_sign_in": 1},+ ],+)+def test_invalid_disconnect_record_never_mutates_native_files(tmp_path, record_value):+ record = claude_desktop_disconnect_path()+ desktop.configure(tmp_path, URL, TOKEN, True, disconnect_path=record)+ if isinstance(record_value, dict) and record_value.get("root") == "ROOT":+ record_value = record_value | {"root": str(tmp_path.resolve())}+ write(record, record_value)+ before = {p: p.read_bytes() for p in tmp_path.rglob("*.json")}+ for operation in (None, False, True):+ with pytest.raises(ValueError):+ desktop.configure(tmp_path, URL, TOKEN, operation, disconnect_path=record)+ with pytest.raises(ValueError):+ desktop.refresh_connected(tmp_path, URL, TOKEN, disconnect_path=record)+ assert {p: p.read_bytes() for p in tmp_path.rglob("*.json")} == before+++def test_default_collision_fails_before_record_or_native_mutation(tmp_path):+ record = claude_desktop_disconnect_path()+ desktop.configure(tmp_path, URL, TOKEN, True, disconnect_path=record)+ write(+ tmp_path / "configLibrary" / f"{desktop.DEFAULT_ID}.json", {"user": "settings"}+ )+ before = {p: p.read_bytes() for p in tmp_path.rglob("*.json")}+ with pytest.raises(ValueError):+ desktop.configure(tmp_path, URL, TOKEN, False, disconnect_path=record)+ assert not record.exists()+ assert {p: p.read_bytes() for p in tmp_path.rglob("*.json")} == before+++def test_unrelated_invalid_profile_is_not_read_on_disconnect(tmp_path):+ record = claude_desktop_disconnect_path()+ desktop.configure(tmp_path, URL, TOKEN, True, disconnect_path=record)+ other = "11111111-1111-4111-8111-111111111111"+ other_path = tmp_path / "configLibrary" / f"{other}.json"+ other_path.write_text("not json", encoding="utf-8")+ metadata = read(meta(tmp_path))+ metadata["entries"].insert(0, {"id": other, "name": "Other"})+ write(meta(tmp_path), metadata)+ desktop.configure(tmp_path, URL, TOKEN, False, disconnect_path=record)+ assert other_path.read_text(encoding="utf-8") == "not json"+++def test_pending_removal_handles_missing_profile_and_later_fcc_selection(tmp_path):+ record = claude_desktop_disconnect_path()+ desktop.configure(tmp_path, URL, TOKEN, True, disconnect_path=record)+ profile(tmp_path).unlink()+ write(record, {"root": str(tmp_path.resolve()), "return_to_sign_in": False})+ result = desktop.configure(tmp_path, URL, TOKEN, False, disconnect_path=record)+ assert result["disconnect_pending"] is False+ assert read(meta(tmp_path))["appliedId"] == desktop.DEFAULT_ID+ assert read(mode(tmp_path))["deploymentMode"] == "1p"diff --git a/tests/runtime/test_integration_startup.py b/tests/runtime/test_integration_startup.pyindex 01d167ca..0d56f05e 100644--- a/tests/runtime/test_integration_startup.py+++ b/tests/runtime/test_integration_startup.py@@ -11,8 +11,15 @@ from free_claude_code.api.ports import ApiServicesfrom free_claude_code.application.model_metadata import ProviderModelInfofrom free_claude_code.application.readiness import InitializationWaitfrom free_claude_code.config.loader import ManagedConfigStore+from free_claude_code.config.paths import claude_desktop_disconnect_pathfrom free_claude_code.config.settings import Settings-from free_claude_code.harnesses import claude_integration, codex_integration+from free_claude_code.harnesses import (+ claude_desktop_integration as desktop,+)+from free_claude_code.harnesses import (+ claude_integration,+ codex_integration,+)from free_claude_code.providers.base import BaseProviderfrom free_claude_code.providers.runtime.runtime import ProviderRuntimefrom free_claude_code.runtime.application import ApplicationRuntime@@ -286,3 +293,50 @@ async def test_refresh_endpoint_is_local_only_and_does_not_connect(assert not codex_integration.config_path().exists()finally:await runtime.close()+++async def test_desktop_startup_rotates_selected_profile_and_disconnect_stays_off(+ runtime,+):+ root = desktop.config_root()+ desktop.configure(+ root,+ "http://localhost:9999",+ "old-token",+ True,+ disconnect_path=claude_desktop_disconnect_path(),+ )+ try:+ await runtime.start()+ await runtime._desktop_update.task+ result = await runtime.claude_desktop_status()+ assert result["connected"] is True+ assert result["update"]["changed"] is True+ before = {p: p.stat().st_mtime_ns for p in root.rglob("*.json")}+ await runtime.claude_desktop_status()+ assert 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+ assert (await runtime.claude_desktop_status())["connected"] is False+ finally:+ await runtime.close()+++async def test_desktop_failure_does_not_block_other_startup(runtime, monkeypatch):+ def fail(*args, **kwargs):+ raise ValueError("private-invalid-file")++ monkeypatch.setattr(desktop, "refresh_connected", fail)+ try:+ await runtime.start()+ await runtime._desktop_update.task+ await 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"+ finally:+ await runtime.close()diff --git a/uv.lock b/uv.lockindex 96e09453..afd058ff 100644--- a/uv.lock+++ b/uv.lock@@ -599,7 +599,7 @@ wheels = [[[package]]name = "free-claude-code"-version = "6.2.48"+version = "6.2.49"source = { editable = "." }dependencies = [{ name = "aiohttp" },