Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)
Python
Keep connected integrations up to date on startup (#1839)
Ali Khokhar002d850d96c6
diff --git a/README.md b/README.mdindex 3231cc65..2b72c8a9 100644--- a/README.md+++ b/README.md@@ -346,152 +346,20 @@ For terminal use, start `fcc-server`, then run `fcc-claude`, `fcc-codex`,`fcc-pi`, `fcc-opencode`, `fcc-cline`, `fcc-hermes`, `fcc-dsh`, `fcc-grok`,`fcc-muse`, or `fcc-aider`.-Use the guides below for editor integrations.+For editor and app integrations, install the client, start FCC, then open+**Admin UI → Integrations** and click **Connect** on its card.-<details>-<summary><strong>Claude Code in VS Code</strong></summary>--Install the [Claude Code extension](https://marketplace.visualstudio.com/items?itemName=anthropic.claude-code). Open VS Code's user settings as JSON and add:--```json-"claudeCode.disableLoginPrompt": true,-"claudeCode.environmentVariables": [- { "name": "ANTHROPIC_BASE_URL", "value": "http://localhost:8082" },- { "name": "ANTHROPIC_AUTH_TOKEN", "value": "freecc" },- { "name": "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY", "value": "1" },- { "name": "CLAUDE_CODE_DISABLE_ADVISOR_TOOL", "value": "1" },- { "name": "CLAUDE_CODE_AUTO_COMPACT_WINDOW", "value": "190000" },- { "name": "DISABLE_AUTOUPDATER", "value": "1" },- { "name": "DISABLE_FEEDBACK_COMMAND", "value": "1" },- { "name": "DISABLE_ERROR_REPORTING", "value": "1" }-]-```--Match the port and authentication token to the Admin UI, then reload the extension.--</details>--<details>-<summary><strong>Codex App</strong></summary>--Start FCC, then edit your Codex configuration:--- Windows: `%USERPROFILE%\.codex\config.toml`-- macOS: `~/.codex/config.toml`--Add the matching model-catalog path and replace `YOUR_USERNAME`.--Windows:--```toml-model_catalog_json = "C:/Users/YOUR_USERNAME/.fcc/codex-model-catalog.json"-```--macOS:--```toml-model_catalog_json = "/Users/YOUR_USERNAME/.fcc/codex-model-catalog.json"-```--Then add the shared FCC settings:--```toml-model_provider = "fcc"-model = "nvidia_nim/nvidia/nemotron-3-super-120b-a12b"--[model_providers.fcc]-name = "Free Claude Code"-base_url = "http://127.0.0.1:8082/v1"-wire_api = "responses"--[model_providers.fcc.auth]-command = "fcc-codex"-args = ["--print-proxy-auth-token"]-```--Match the model and port to the Admin UI. The auth command reads FCC's current-proxy token automatically. Restart the Codex App after setup or model changes,-then select an FCC model from its model picker.--</details>--<details>-<summary><strong>Codex in VS Code</strong></summary>+- **Claude Code in VS Code** — install the [Claude Code extension](https://marketplace.visualstudio.com/items?itemName=anthropic.claude-code).+- **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.-Install the [Codex extension](https://marketplace.visualstudio.com/items?itemName=openai.chatgpt). Create or edit `~/.codex/config.toml` (`%USERPROFILE%\.codex\config.toml` on Windows):+Reload VS Code or restart the app/IDE after connecting. In Codex, select an FCC+model from the model picker. FCC keeps connected integrations up to date when it+starts; reload or restart the client when FCC reports updated settings. Use+**Disconnect** on the same card to remove the integration.-```toml-model_provider = "fcc"-model = "nvidia_nim/nvidia/nemotron-3-super-120b-a12b"--[model_providers.fcc]-name = "Free Claude Code"-base_url = "http://127.0.0.1:8082/v1"-wire_api = "responses"--[model_providers.fcc.auth]-command = "fcc-codex"-args = ["--print-proxy-auth-token"]-```--Match `model` and the port to the Admin UI. The auth command reads FCC's current-proxy token automatically. Restart VS Code after setup or model changes. For-WSL-backed Codex, edit the file inside WSL.--</details>--<details>-<summary><strong>Claude Code in JetBrains ACP</strong></summary>--Edit the installed Claude ACP configuration:--- Windows: `C:\Users\%USERNAME%\AppData\Roaming\JetBrains\acp-agents\installed.json`-- Linux/macOS: `~/.jetbrains/acp.json`--Set the environment for `acp.registry.claude-acp`:--```json-"env": {- "ANTHROPIC_BASE_URL": "http://localhost:8082",- "ANTHROPIC_AUTH_TOKEN": "freecc",- "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY": "1",- "CLAUDE_CODE_DISABLE_ADVISOR_TOOL": "1",- "CLAUDE_CODE_AUTO_COMPACT_WINDOW": "190000",- "DISABLE_AUTOUPDATER": "1",- "DISABLE_FEEDBACK_COMMAND": "1",- "DISABLE_ERROR_REPORTING": "1"-}-```--Match the port and token to the Admin UI, then restart the IDE.--</details>--<details>-<summary><strong>Claude Code still asks you to log in</strong></summary>--If Claude Code asks you to log in after you configure the FCC URL and token, open its state file:--- Windows: `%USERPROFILE%\.claude.json`-- macOS/Linux/WSL: `~/.claude.json`--Merge this property into the existing JSON without removing its other fields:--```json-"hasCompletedOnboarding": true-```--If the file does not exist, create it with a complete JSON object:--```json-{- "hasCompletedOnboarding": true-}-```--Restart Claude Code or the IDE after saving the file.--</details>+Run FCC on the same computer and in the same user environment as the client you+are configuring.<a id="optional-integrations"></a>diff --git a/e2e/conftest.py b/e2e/conftest.pyindex f2e32db1..cd060f07 100644--- a/e2e/conftest.py+++ b/e2e/conftest.py@@ -120,12 +120,18 @@ def code_control(tmp_path):return CodeControl(tmp_path / "code")+def admin_client_files():+ """Allow integration tests to seed client files before server startup."""++@pytest.fixturedef admin_base_url(request: pytest.FixtureRequest,monkeypatch: pytest.MonkeyPatch,tmp_path: Path,code_control: CodeControl,+ admin_client_files,) -> Iterator[str]:"""Serve one fully isolated Admin application on an OS-assigned port."""diff --git a/e2e/test_admin_integrations.py b/e2e/test_admin_integrations.pyindex 85da402a..3247d7f3 100644--- a/e2e/test_admin_integrations.py+++ b/e2e/test_admin_integrations.py@@ -397,3 +397,116 @@ def test_codex_save_pending_and_failure_stay_in_modal(page, admin_base_url, tmp_"Could not save settings.")assert not (tmp_path / ".codex" / "config.toml").exists()+++ "integration,prefix", [("claude-vscode", "Claude"), ("codex", "Codex")]+)+def test_background_update_spinner_failure_retry_and_completion(+ page, admin_base_url, integration, prefix+):+ progress = {"state": "starting", "changed": False, "message": None}+ retries = []++ def startup(route):+ response = route.fetch()+ payload = response.json()+ payload["startup"]["integrations"][integration] = dict(progress)+ route.fulfill(response=response, json=payload)++ def status(route):+ route.fulfill(+ json={+ "connected": True if progress["state"] == "ready" else None,+ "paths": None,+ "update": dict(progress),+ }+ )++ def retry(route):+ retries.append(route.request.method)+ progress.update(state="starting", changed=False, message=None)+ route.fulfill(json={"update": dict(progress)})++ page.route("**/admin/api/status", startup)+ page.route(f"**/admin/api/integrations/{integration}", status)+ page.route(f"**/admin/api/integrations/{integration}/refresh", retry)+ page.goto(f"{admin_base_url}/admin/integrations")+ button = page.locator(f"#open{prefix}Integration")+ confirm = page.locator(f"#confirm{prefix}Integration")+ message = page.locator(f"#{prefix.lower()}IntegrationMessage")+ expect(button).to_be_disabled()+ expect(confirm).to_be_disabled()+ expect(button).to_have_attribute("aria-busy", "true")+ progress.update(+ state="failed", message="Could not update settings. Check permissions."+ )+ expect(button).to_have_text("Retry")+ expect(button).to_be_enabled()+ expect(message).to_have_text(progress["message"])+ button.click()+ expect(button).to_be_disabled()+ assert retries == ["POST"]+ progress.update(state="ready", changed=True)+ expect(button).to_have_text("Disconnect")+ expect(button).to_be_enabled()+ expect(button).to_have_css("color", "rgb(239, 68, 68)")+ expect(message).to_have_text(+ "Settings updated. Reload VS Code."+ if prefix == "Claude"+ else "Settings updated. Restart Codex."+ )+++def admin_client_files(request, tmp_path):+ if not getattr(request, "param", False):+ return None+ path = tmp_path / "vscode/settings.json"+ path.parent.mkdir()+ path.write_text(+ json.dumps(+ {+ "editor.fontSize": 15,+ "claudeCode.disableLoginPrompt": True,+ "claudeCode.environmentVariables": [+ {"name": "ANTHROPIC_BASE_URL", "value": "http://localhost:8082"},+ {"name": "ANTHROPIC_AUTH_TOKEN", "value": "e2e-proxy-token"},+ {+ "name": "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY",+ "value": "1",+ },+ ],+ }+ )+ )+ return path++[email protected]("admin_client_files", [True], indirect=True)+def test_startup_updates_before_opening_integrations(+ admin_client_files, admin_base_url, page, tmp_path+):+ page.goto(f"{admin_base_url}/admin/integrations")+ button = page.locator("#openClaudeIntegration")+ expect(button).to_have_text("Disconnect")+ expect(page.locator("#claudeIntegrationMessage")).to_have_text(+ "Settings updated. Reload VS Code."+ )+ saved = json.loads(admin_client_files.read_text())+ assert saved["editor.fontSize"] == 15+ assert any(+ entry == {"name": "CLAUDE_CODE_DISABLE_ADVISOR_TOOL", "value": "1"}+ for entry in saved["claudeCode.environmentVariables"]+ )+ assert (+ json.loads((tmp_path / ".claude.json").read_text())["hasCompletedOnboarding"]+ is True+ )+ page.screenshot(path=str(tmp_path / "integration-updated.png"), full_page=True)+ button.click()+ page.locator("#confirmClaudeIntegration").click()+ expect(button).to_have_text("Connect")+ page.reload()+ expect(button).to_have_text("Connect")+ expect(page.locator("#claudeIntegrationMessage")).to_be_hidden()diff --git a/pyproject.toml b/pyproject.tomlindex c1fc1296..4c97e8d2 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "free-claude-code"-version = "6.2.43"+version = "6.2.44"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 f312f020..683c1e89 100644--- a/src/free_claude_code/api/admin_routes.py+++ b/src/free_claude_code/api/admin_routes.py@@ -269,6 +269,15 @@ async def connect_claude_vscode(return await _integration_response(services.admin.connect_claude_vscode)[email protected]("/admin/api/integrations/claude-vscode/refresh")+async def refresh_claude_vscode(+ request: Request,+ services: ApiServices = Depends(get_services),+):+ require_loopback_admin(request)+ return await _integration_response(services.admin.refresh_claude_vscode)++@router.post("/admin/api/integrations/claude-vscode/disconnect")async def disconnect_claude_vscode(request: Request,@@ -296,6 +305,15 @@ async def connect_codex(return await _integration_response(services.admin.connect_codex)[email protected]("/admin/api/integrations/codex/refresh")+async def refresh_codex_integration(+ request: Request,+ services: ApiServices = Depends(get_services),+):+ require_loopback_admin(request)+ return await _integration_response(services.admin.refresh_codex_integration)++@router.post("/admin/api/integrations/codex/disconnect")async def disconnect_codex(request: Request,diff --git a/src/free_claude_code/api/admin_static/admin.js b/src/free_claude_code/api/admin_static/admin.jsindex 3be4ed8f..8aac97b9 100644--- a/src/free_claude_code/api/admin_static/admin.js+++ b/src/free_claude_code/api/admin_static/admin.js@@ -138,6 +138,7 @@ function renderStartup() {state.config.provider_status.forEach((provider) => {renderProviderCheckResult(provider.provider_id);});+ renderClaudeIntegration();renderCodexIntegration();}@@ -162,12 +163,14 @@ async function refreshStartup() {)) return;state.startup = result;renderStartup();+ refreshIntegrationUpdates(previous?.startup?.integrations, current.integrations);const changed = !previous || previous.instance_id !== result.instance_id ||JSON.stringify(previous.startup) !== JSON.stringify(current);if (changed) void hydrateModelOptions();if (changed || state.codeCatalogRetry) state.codeCatalogRetry = await window.CodeSessions?.refresh(result) === false;pending = state.codeCatalogRetry || current.catalog === "starting" || current.catalog_file === "starting" ||current.code?.state === "starting" || current.messaging?.state === "starting" ||+ Object.values(current.integrations || {}).some((update) => update.state === "starting") ||Object.values(current.providers || {}).includes("starting");} catch (error) {if (error.name !== "AbortError") pending = true;@@ -1474,7 +1477,7 @@ try {}const claudeIntegrationDialog = byId("claudeIntegrationDialog");-const claudeIntegration = { connected: null, busy: false, paths: null };+const claudeIntegration = { connected: null, busy: false, paths: null, update: null };const claudeIntegrationPath = "/admin/api/integrations/claude-vscode";function integrationMessage(id, message, error = false) {@@ -1484,8 +1487,27 @@ function integrationMessage(id, message, error = false) {element.classList.toggle("error", error);}+function integrationUpdating(integration, id) {+ return integration.update?.state === "starting" ||+ state.startup?.startup?.integrations?.[id]?.state === "starting";+}++function refreshIntegrationUpdates(previous, current) {+ if (state.activeView !== "integrations") return;+ for (const [id, integration, refresh] of [+ ["claude-vscode", claudeIntegration, refreshClaudeIntegration],+ ["codex", codexIntegration, refreshCodexIntegration],+ ]) {+ const phase = current?.[id]?.state;+ if (phase && phase !== "starting" && (+ previous?.[id]?.state === "starting" || integration.update?.state === "starting"+ )) void refresh();+ }+}+function renderClaudeIntegration() {- const { connected, busy, paths } = claudeIntegration;+ const { connected, paths } = claudeIntegration;+ const busy = claudeIntegration.busy || integrationUpdating(claudeIntegration, "claude-vscode");const action = connected ? "Disconnect" : "Connect";byId("openClaudeIntegration").textContent = busy ? "Loading…" : connected === null ? "Retry" : action;byId("openClaudeIntegration").disabled = busy;@@ -1511,34 +1533,40 @@ function renderClaudeIntegration() {}}-async function refreshClaudeIntegration() {+async function refreshClaudeIntegration(retry = false) {if (claudeIntegration.busy) return;claudeIntegration.busy = true;renderClaudeIntegration();integrationMessage("claudeIntegrationMessage", "");try {+ if (retry) await api(`${claudeIntegrationPath}/refresh`, { method: "POST" });const result = await api(claudeIntegrationPath);claudeIntegration.connected = result.connected;claudeIntegration.paths = result.paths;+ claudeIntegration.update = result.update;+ if (result.update?.state === "failed") integrationMessage("claudeIntegrationMessage", result.update.message, true);+ else if (result.update?.changed) integrationMessage("claudeIntegrationMessage", "Settings updated. Reload VS Code.");} catch (error) {claudeIntegration.connected = null;+ claudeIntegration.update = null;integrationMessage("claudeIntegrationMessage", error.message, true);} finally {claudeIntegration.busy = false;renderClaudeIntegration();+ if (claudeIntegration.update?.state === "starting") void refreshStartup();}}byId("openClaudeIntegration").addEventListener("click", () => {if (claudeIntegration.connected === null) {- refreshClaudeIntegration();+ refreshClaudeIntegration(claudeIntegration.update?.state === "failed");return;}integrationMessage("claudeIntegrationDialogMessage", "");claudeIntegrationDialog.showModal();});byId("confirmClaudeIntegration").addEventListener("click", async () => {- if (claudeIntegration.busy || claudeIntegration.connected === null) return;+ if (byId("confirmClaudeIntegration").disabled) return;const disconnect = claudeIntegration.connected;claudeIntegration.busy = true;renderClaudeIntegration();@@ -1547,6 +1575,7 @@ byId("confirmClaudeIntegration").addEventListener("click", async () => {try {const result = await api(`${claudeIntegrationPath}/${disconnect ? "disconnect" : "connect"}`, { method: "POST" });claudeIntegration.connected = result.connected;+ claudeIntegration.update = null;claudeIntegrationDialog.close();integrationMessage("claudeIntegrationMessage", disconnect? "Settings removed. Reload VS Code to disconnect."@@ -1569,14 +1598,14 @@ claudeIntegrationDialog.addEventListener("click", (event) => {});const codexIntegrationDialog = byId("codexIntegrationDialog");-const codexIntegration = { connected: null, busy: false, paths: null };+const codexIntegration = { connected: null, busy: false, paths: null, update: null };const codexIntegrationPath = "/admin/api/integrations/codex";function renderCodexIntegration() {const { connected, paths } = codexIntegration;const initializing = connected === false && state.startup?.startup?.catalog_file === "starting";const unavailable = connected === false && state.startup?.startup?.catalog_file === "failed";- const busy = codexIntegration.busy || initializing;+ const busy = codexIntegration.busy || initializing || integrationUpdating(codexIntegration, "codex");const catalogError = "Could not prepare the Codex model catalog. Refresh models to retry.";if (unavailable) integrationMessage("codexIntegrationMessage", catalogError, true);else if (byId("codexIntegrationMessage").textContent === catalogError) integrationMessage("codexIntegrationMessage", "");@@ -1605,34 +1634,40 @@ function renderCodexIntegration() {}}-async function refreshCodexIntegration() {+async function refreshCodexIntegration(retry = false) {if (codexIntegration.busy) return;codexIntegration.busy = true;renderCodexIntegration();integrationMessage("codexIntegrationMessage", "");try {+ if (retry) await api(`${codexIntegrationPath}/refresh`, { method: "POST" });const result = await api(codexIntegrationPath);codexIntegration.connected = result.connected;codexIntegration.paths = result.paths;+ codexIntegration.update = result.update;+ if (result.update?.state === "failed") integrationMessage("codexIntegrationMessage", result.update.message, true);+ else if (result.update?.changed) integrationMessage("codexIntegrationMessage", "Settings updated. Restart Codex.");} catch (error) {codexIntegration.connected = null;+ codexIntegration.update = null;integrationMessage("codexIntegrationMessage", error.message, true);} finally {codexIntegration.busy = false;renderCodexIntegration();+ if (codexIntegration.update?.state === "starting") void refreshStartup();}}byId("openCodexIntegration").addEventListener("click", () => {if (codexIntegration.connected === null) {- refreshCodexIntegration();+ refreshCodexIntegration(codexIntegration.update?.state === "failed");return;}integrationMessage("codexIntegrationDialogMessage", "");codexIntegrationDialog.showModal();});byId("confirmCodexIntegration").addEventListener("click", async () => {- if (codexIntegration.busy || codexIntegration.connected === null) return;+ if (byId("confirmCodexIntegration").disabled) return;const disconnect = codexIntegration.connected;codexIntegration.busy = true;renderCodexIntegration();@@ -1642,6 +1677,7 @@ byId("confirmCodexIntegration").addEventListener("click", async () => {const result = await api(`${codexIntegrationPath}/${disconnect ? "disconnect" : "connect"}`, { method: "POST" });codexIntegration.connected = result.connected;codexIntegration.paths = result.paths;+ codexIntegration.update = null;codexIntegrationDialog.close();integrationMessage("codexIntegrationMessage", disconnect? "Settings removed. Restart Codex to disconnect."diff --git a/src/free_claude_code/api/ports.py b/src/free_claude_code/api/ports.pyindex 5c2fbfe6..2b942194 100644--- a/src/free_claude_code/api/ports.py+++ b/src/free_claude_code/api/ports.py@@ -35,12 +35,16 @@ class AdminRuntimePort(Protocol):async def disconnect_claude_vscode(self) -> JsonObject: ...+ async def refresh_claude_vscode(self) -> JsonObject: ...+async def codex_integration_status(self) -> JsonObject: ...async def connect_codex(self) -> JsonObject: ...async def disconnect_codex(self) -> JsonObject: ...+ async def refresh_codex_integration(self) -> JsonObject: ...+async def pick_folder(self, initial_path: str | None) -> str | None: ...async def test_provider(self, provider_id: str) -> JsonObject: ...diff --git a/src/free_claude_code/application/readiness.py b/src/free_claude_code/application/readiness.pyindex 719b090a..edb3badf 100644--- a/src/free_claude_code/application/readiness.py+++ b/src/free_claude_code/application/readiness.py@@ -1,4 +1,4 @@-"""Bounded request waits on initialization owned by a longer-lived service."""+"""Wait budgets for initialization owned by a longer-lived service."""import asyncio@@ -8,9 +8,9 @@ STARTUP_WAIT_SECONDS = 30.0class InitializationWait:- """One request's remaining time spent waiting, excluding normal execution."""+ """Remaining wait time; lifecycle-owned work may use None for no deadline."""- def __init__(self, seconds: float = STARTUP_WAIT_SECONDS) -> None:+ def __init__(self, seconds: float | None = STARTUP_WAIT_SECONDS) -> None:self.remaining = secondsasync def wait[T](self, task: asyncio.Task[T]) -> T:@@ -37,6 +37,7 @@ class InitializationWait:) from Noneraisefinally:- self.remaining = max(- 0.0, self.remaining - (asyncio.get_running_loop().time() - started)- )+ if self.remaining is not None:+ self.remaining = max(+ 0.0, self.remaining - (asyncio.get_running_loop().time() - started)+ )diff --git a/src/free_claude_code/harnesses/claude_integration.py b/src/free_claude_code/harnesses/claude_integration.pyindex ae886075..64c4c4af 100644--- a/src/free_claude_code/harnesses/claude_integration.py+++ b/src/free_claude_code/harnesses/claude_integration.py@@ -83,6 +83,47 @@ def _connected()+def _connect(+ path: Path,+ state_path: Path,+ document: JsonObject,+ entries: list[JsonObject],+ values: dict[str, str],+) -> bool:+ onboarding = _read_object(state_path)+ before = json.dumps(document, allow_nan=False)+ document[_LOGIN] = True+ remaining = dict(values)+ for entry in entries:+ name = cast(str, entry["name"])+ if name in remaining:+ entry["value"] = remaining.pop(name)+ entries.extend({"name": name, "value": value} for name, value in remaining.items())+ document[_ENV] = entries+ settings_changed = json.dumps(document, allow_nan=False) != before+ onboarding_changed = onboarding.get(_ONBOARDING) is not True+ if onboarding_changed:+ onboarding[_ONBOARDING] = True+ atomic_write_text(+ state_path, json.dumps(onboarding, indent=2, allow_nan=False) + "\n"+ )+ if settings_changed:+ atomic_write_text(path, json.dumps(document, indent=2, allow_nan=False) + "\n")+ return settings_changed or onboarding_changed+++def refresh_connected(+ path: Path, state_path: Path, proxy_root_url: str, auth_token: str+) -> bool:+ """Apply current settings only to an existing connection, even from release one."""+ path = path.resolve()+ values = claude_proxy_values(proxy_root_url, auth_token)+ document, entries = _read(path, set(values))+ if not _connected(document, entries, values):+ return False+ return _connect(path, state_path.resolve(), document, entries, values)++def configure(path: Path,state_path: Path,@@ -94,43 +135,26 @@ def configure(path = path.resolve()values = claude_proxy_values(proxy_root_url, auth_token)document, entries = _read(path, set(values))- onboarding: JsonObject = {}if connected is not False:state_path = state_path.resolve()- onboarding = _read_object(state_path)- if connected is not None:+ if connected is True:+ _connect(path, state_path, document, entries, values)+ elif connected is False:before = json.dumps(document, allow_nan=False)- if connected:- document[_LOGIN] = True- remaining = dict(values)- for entry in entries:- name = cast(str, entry["name"])- if name in remaining:- entry["value"] = remaining.pop(name)- entries.extend(- {"name": name, "value": value} for name, value in remaining.items()- )- document[_ENV] = entries- else:- document.pop(_LOGIN, None)- retained = [entry for entry in entries if entry["name"] not in values]- if len(retained) != len(entries):- if retained:- document[_ENV] = retained- else:- document.pop(_ENV, None)- settings_changed = json.dumps(document, allow_nan=False) != before- settings_content = json.dumps(document, indent=2, allow_nan=False) + "\n"- if connected and onboarding.get(_ONBOARDING) is not True:- onboarding[_ONBOARDING] = True+ document.pop(_LOGIN, None)+ retained = [entry for entry in entries if entry["name"] not in values]+ if len(retained) != len(entries):+ if retained:+ document[_ENV] = retained+ else:+ document.pop(_ENV, None)+ if json.dumps(document, allow_nan=False) != before:atomic_write_text(- state_path, json.dumps(onboarding, indent=2, allow_nan=False) + "\n"+ path, json.dumps(document, indent=2, allow_nan=False) + "\n")- if settings_changed:- atomic_write_text(path, settings_content)+ if connected is not None:document, entries = _read(path, set(values))- if connected:- onboarding = _read_object(state_path)+ onboarding = _read_object(state_path) if connected is not False else {}result: JsonObject = {"connected": _connected(document, entries, values)and onboarding.get(_ONBOARDING) is True,diff --git a/src/free_claude_code/harnesses/codex_integration.py b/src/free_claude_code/harnesses/codex_integration.pyindex 631ba2b3..f8192b3c 100644--- a/src/free_claude_code/harnesses/codex_integration.py+++ b/src/free_claude_code/harnesses/codex_integration.py@@ -67,19 +67,59 @@ def _same_catalog(value: object, catalog_path: Path) -> bool:)+def _recognizes_connection(document: TOMLDocument, proxy_root_url: str) -> bool:+ provider = _child_table(_child_table(document, "model_providers"), "fcc")+ return document.get("model_provider") == "fcc" and same_proxy_url(+ provider.get("base_url"), proxy_v1_url(proxy_root_url)+ )+++def recognizes_connection(path: Path, proxy_root_url: str) -> bool:+ """Identify FCC independently of newly introduced managed settings."""+ return _recognizes_connection(_read(path.resolve()), proxy_root_url)++def _connected(document: TOMLDocument, catalog_path: Path, proxy_root_url: str) -> bool:provider = _child_table(_child_table(document, "model_providers"), "fcc")auth = _child_table(provider, "auth")return (- document.get("model_provider") == "fcc"+ _recognizes_connection(document, proxy_root_url)and _same_catalog(document.get("model_catalog_json"), catalog_path)- and same_proxy_url(provider.get("base_url"), proxy_v1_url(proxy_root_url))and provider.get("wire_api") == "responses"and auth.get("command") == "fcc-codex"and auth.get("args") == [PRINT_PROXY_AUTH_TOKEN_FLAG])+def _connect(+ path: Path, document: TOMLDocument, catalog_path: Path, proxy_root_url: str+) -> bool:+ before = tomlkit.dumps(document)+ values = codex_config_values(api_url=proxy_root_url)+ values["model_catalog_json"] = str(catalog_path)+ for dotted_key, value in values.items():+ *parents, key = dotted_key.split(".")+ parent: TOMLDocument | Table | InlineTable | OutOfOrderTableProxy = document+ for name in parents:+ parent = _child_table(parent, name, create=True)+ if parent.get(key) != value:+ parent[key] = value+ content = tomlkit.dumps(document)+ if content == before:+ return False+ atomic_write_text(path, content)+ return True+++def refresh_connected(path: Path, catalog_path: Path, proxy_root_url: str) -> bool:+ """Refresh an existing FCC connection without selecting a provider or model."""+ path = path.resolve()+ document = _read(path)+ if not _recognizes_connection(document, proxy_root_url):+ return False+ return _connect(path, document, catalog_path.resolve(), proxy_root_url)++def configure(path: Path, catalog_path: Path, proxy_root_url: str, connected: bool | None = None) -> JsonObject:@@ -87,29 +127,19 @@ def configure(path = path.resolve()catalog_path = catalog_path.resolve()document = _read(path)- if connected is not None:+ if connected is True:+ _connect(path, document, catalog_path, proxy_root_url)+ elif connected is False:before = tomlkit.dumps(document)- if connected:- values = codex_config_values(api_url=proxy_root_url)- values["model_catalog_json"] = str(catalog_path)- for dotted_key, value in values.items():- *parents, key = dotted_key.split(".")- parent: TOMLDocument | Table | InlineTable | OutOfOrderTableProxy = (- document- )- for name in parents:- parent = _child_table(parent, name, create=True)- if parent.get(key) != value:- parent[key] = value- else:- _child_table(document, "model_providers").pop("fcc", None)- if document.get("model_provider") == "fcc":- document.pop("model_provider")- if _same_catalog(document.get("model_catalog_json"), catalog_path):- document.pop("model_catalog_json")+ _child_table(document, "model_providers").pop("fcc", None)+ if document.get("model_provider") == "fcc":+ document.pop("model_provider")+ if _same_catalog(document.get("model_catalog_json"), catalog_path):+ document.pop("model_catalog_json")content = tomlkit.dumps(document)if content != before:atomic_write_text(path, content)+ if connected is not None:document = _read(path)return {"connected": _connected(document, catalog_path, proxy_root_url),diff --git a/src/free_claude_code/runtime/application.py b/src/free_claude_code/runtime/application.pyindex e23013d0..d1869cf7 100644--- a/src/free_claude_code/runtime/application.py+++ b/src/free_claude_code/runtime/application.py@@ -8,11 +8,10 @@ import osimport tracebackimport uuidfrom collections.abc import Awaitable, Callable, Mapping-from dataclasses import replace+from dataclasses import dataclass, replacefrom functools import partial-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Literal-from anyio import to_threadfrom loguru import loggerfrom free_claude_code.application.code_sessions import CodeService@@ -22,6 +21,7 @@ from free_claude_code.application.connected_accounts import (ConnectedAccountStatus,)from free_claude_code.application.errors import (+ ApplicationError,ApplicationUnavailableError,InvalidRequestError,)@@ -67,6 +67,24 @@ from .provider_manager import ProviderRuntimeManagerfrom .retired_chat import remove_retired_chat_historyRestartCallback = 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 = ("Could not refresh this provider's models. Verify its configuration and access."@@ -189,6 +207,8 @@ class ApplicationRuntime:self._connected_accounts_closed = Falseself._lifecycle_lock = asyncio.Lock()self._startup_tasks: list[asyncio.Task[None]] = []+ self._claude_update = _IntegrationUpdate()+ self._codex_update = _IntegrationUpdate()self._http_ready = asyncio.Event()self._messaging_state = ("disabled" if self.settings.messaging_platform == "none" else "starting"@@ -222,6 +242,8 @@ class ApplicationRuntime:"Application runtime is shutting down.")self.provider_manager.start_model_list_refresh()+ await self.refresh_claude_vscode()+ await self.refresh_codex_integration()self._startup_tasks.append(asyncio.create_task(run_sync_owned(remove_retired_chat_history),@@ -395,34 +417,94 @@ class ApplicationRuntime:return await self._configuration.admin_values()async def claude_vscode_status(self) -> JsonObject:- return await self._claude_vscode(None)+ return await self._claude_vscode("status")async def connect_claude_vscode(self) -> JsonObject:- return await self._claude_vscode(True)+ return await self._claude_vscode("connect")async def disconnect_claude_vscode(self) -> JsonObject:- return await self._claude_vscode(False)+ 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 _claude_vscode(self, connected: bool | None) -> JsonObject:+ 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()}++ 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 _claude_vscode(self, action: IntegrationAction) -> JsonObject:async with self._config_lock:- if self._draining or self._pending_fields:- raise ApplicationUnavailableError(- "Wait for FCC to restart before changing the integration."- )+ self._check_integration_available()settings = self.settings- try:- return await _await_owned_task(- asyncio.create_task(- to_thread.run_sync(- claude_integration.configure,- claude_integration.settings_path(),- claude_integration.claude_state_path(),++ 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,- connected,)- )+ }+ 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."@@ -431,55 +513,84 @@ class ApplicationRuntime: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 resultasync def codex_integration_status(self) -> JsonObject:- return await self._codex_integration(None)+ return await self._codex_integration("status")async def connect_codex(self) -> JsonObject:- return await self._codex_integration(True)+ return await self._codex_integration("connect")async def disconnect_codex(self) -> JsonObject:- return await self._codex_integration(False)-- async def _codex_integration(self, connected: bool | None) -> JsonObject:- wait = InitializationWait()- while True:- generation_id = (- await self.provider_manager.wait_for_catalog_file(wait)- if connected is True- else None- )- async with self._config_lock:- if connected is True and (- generation_id != self.provider_manager.current_generation_id- or self.provider_manager.catalog_status()["catalog"] != "ready"- ):- continue- if self._draining or self._pending_fields:- raise ApplicationUnavailableError(- "Wait for FCC to restart before changing the integration."- )- settings = self.settings- try:- return await _await_owned_task(- asyncio.create_task(- to_thread.run_sync(- codex_integration.configure,- codex_integration.config_path(),- codex_model_catalog_path(),- local_proxy_root_url(settings),- connected,- )+ 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",)- )- 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++ 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 Noneasync def admin_status(self) -> JsonObject:values = await self.admin_values()@@ -496,6 +607,10 @@ class ApplicationRuntime:"state": self._messaging_state,"message": self._messaging_error,},+ "integrations": {+ "claude-vscode": self._claude_update.snapshot(),+ "codex": self._codex_update.snapshot(),+ },},"host": settings.host,"port": settings.port,diff --git a/tests/api/test_codex_integration_routes.py b/tests/api/test_codex_integration_routes.pyindex 531a20a7..5dddf865 100644--- a/tests/api/test_codex_integration_routes.py+++ b/tests/api/test_codex_integration_routes.py@@ -30,6 +30,7 @@ def test_routes_inspect_connect_and_disconnect(integration):assert response.json() == {"connected": False,"paths": {"codex_config": str(path.resolve())},+ "update": {"state": "ready", "changed": False, "message": None},}assert response.headers["cache-control"] == "no-store"assert not path.exists()@@ -63,7 +64,7 @@ def test_invalid_file_returns_safe_uncached_error(integration, action):assert path.read_text() == source[email protected]("action", ["", "/connect", "/disconnect"])[email protected]("action", ["", "/connect", "/disconnect", "/refresh"])@pytest.mark.parametrize("headers", [{"Host": "evil.test"}, {"Origin": "https://evil.test"}])@@ -102,7 +103,9 @@ def test_pending_restart_and_shutdown_do_not_write(integration):client, path, runtime = integrationruntime._pending_fields = ["PORT"]assert client.post(f"{ROOT}/connect").status_code == 503+ assert client.post(f"{ROOT}/refresh").status_code == 503runtime._pending_fields = []runtime.begin_shutdown()assert client.post(f"{ROOT}/connect").status_code == 503+ assert client.post(f"{ROOT}/refresh").status_code == 503assert not path.exists()diff --git a/tests/api/test_vscode_integration.py b/tests/api/test_vscode_integration.pyindex 5d50f613..e48dbc3c 100644--- a/tests/api/test_vscode_integration.py+++ b/tests/api/test_vscode_integration.py@@ -95,7 +95,7 @@ def test_invalid_file_returns_safe_uncached_error(integration, action, target):assert path.read_text() == source[email protected]("action", ["", "/connect", "/disconnect"])[email protected]("action", ["", "/connect", "/disconnect", "/refresh"])@pytest.mark.parametrize("headers", [{"Host": "evil.test"}, {"Origin": "https://evil.test"}])@@ -133,7 +133,9 @@ def test_pending_restart_and_shutdown_do_not_write(integration):client, path, runtime = integrationruntime._pending_fields = ["PORT"]assert client.post(f"{ROOT}/connect").status_code == 503+ assert client.post(f"{ROOT}/refresh").status_code == 503runtime._pending_fields = []runtime.begin_shutdown()assert client.post(f"{ROOT}/connect").status_code == 503+ assert client.post(f"{ROOT}/refresh").status_code == 503assert not path.exists()diff --git a/tests/conftest.py b/tests/conftest.pyindex 5f14b40b..5a5d5d72 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -9,6 +9,7 @@ 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_integrationfrom tests.providers.support import (immediate_admission,make_provider_config,@@ -30,6 +31,15 @@ def _isolate_managed_config(monkeypatch, tmp_path):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)+ monkeypatch.setattr(+ claude_integration, "settings_path", lambda: tmp_path / "vscode/settings.json"+ )+ monkeypatch.setattr(+ claude_integration, "claude_state_path", lambda: tmp_path / ".claude.json"+ )+ monkeypatch.setattr(+ codex_integration, "config_path", lambda: tmp_path / ".codex/config.toml"+ )clear_settings_cache()yieldclear_settings_cache()diff --git a/tests/harnesses/test_claude_integration.py b/tests/harnesses/test_claude_integration.pyindex bfb9439e..a7fd0015 100644--- a/tests/harnesses/test_claude_integration.py+++ b/tests/harnesses/test_claude_integration.py@@ -4,6 +4,7 @@ from pathlib import Pathimport pytestfrom free_claude_code.harnesses import claude_integration+from free_claude_code.harnesses.claude_integration import settings_pathURL = "http://127.0.0.1:8000"TOKEN = "test-integration-token"@@ -344,7 +345,7 @@ def test_standard_global_path(tmp_path, monkeypatch, platform, suffix):monkeypatch.setattr(Path, "home", lambda: tmp_path)monkeypatch.delenv("APPDATA", raising=False)monkeypatch.delenv("XDG_CONFIG_HOME", raising=False)- assert claude_integration.settings_path() == tmp_path / suffix+ assert settings_path() == tmp_path / suffix@pytest.mark.parametrize(@@ -353,4 +354,4 @@ def test_standard_global_path(tmp_path, monkeypatch, platform, suffix):def test_config_root_override(tmp_path, monkeypatch, platform, variable):monkeypatch.setattr(claude_integration.sys, "platform", platform)monkeypatch.setenv(variable, str(tmp_path))- assert claude_integration.settings_path() == tmp_path / "Code/User/settings.json"+ assert settings_path() == tmp_path / "Code/User/settings.json"diff --git a/tests/harnesses/test_codex_integration.py b/tests/harnesses/test_codex_integration.pyindex 3c25210b..41aacaab 100644--- a/tests/harnesses/test_codex_integration.py+++ b/tests/harnesses/test_codex_integration.py@@ -4,6 +4,7 @@ from pathlib import Pathimport pytestfrom free_claude_code.harnesses import codex_integration+from free_claude_code.harnesses.codex_integration import config_pathURL = "http://127.0.0.1:8082"@@ -204,6 +205,6 @@ def test_symlink_unicode_and_path_display(tmp_path):def test_native_config_path_honors_codex_home(tmp_path, monkeypatch):monkeypatch.setattr(Path, "home", lambda: tmp_path)monkeypatch.delenv("CODEX_HOME", raising=False)- assert codex_integration.config_path() == tmp_path / ".codex/config.toml"+ assert config_path() == tmp_path / ".codex/config.toml"monkeypatch.setenv("CODEX_HOME", str(tmp_path / "custom"))- assert codex_integration.config_path() == tmp_path / "custom/config.toml"+ assert config_path() == tmp_path / "custom/config.toml"diff --git a/tests/harnesses/test_integration_refresh.py b/tests/harnesses/test_integration_refresh.pynew file mode 100644index 00000000..7fed88a9--- /dev/null+++ b/tests/harnesses/test_integration_refresh.py@@ -0,0 +1,156 @@+import json+import tomllib++import pytest++from free_claude_code.harnesses import claude_integration, codex_integration++URL = "http://127.0.0.1:8000"+TOKEN = "test-integration-token"+# Original connection markers, deliberately independent of today's desired settings.+OLD_CLAUDE = {+ "editor.fontSize": 15,+ "claudeCode.disableLoginPrompt": True,+ "claudeCode.environmentVariables": [+ {"name": "ANTHROPIC_BASE_URL", "value": "http://localhost:8000"},+ {"name": "ANTHROPIC_AUTH_TOKEN", "value": TOKEN},+ {"name": "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY", "value": "1"},+ {"name": "KEEP_ME", "value": "user-value"},+ ],+}+OLD_CODEX = """model = "my-model" # Preserve my choice+model_provider = "fcc"+model_catalog_json = "/old/catalog.json"+[model_providers.fcc]+base_url = "http://localhost:8000/v1"+[model_providers.other]+base_url = "https://example.com/v1"+"""+++def test_refresh_upgrades_original_claude_directly_and_only_once(tmp_path):+ settings, state = tmp_path / "settings.json", tmp_path / ".claude.json"+ settings.write_text(json.dumps(OLD_CLAUDE))+ state.write_text('{"theme":"dark"}')+ assert (+ claude_integration.configure(settings, state, URL, TOKEN)["connected"] is False+ )+ assert claude_integration.refresh_connected(settings, state, URL, TOKEN) is True+ saved = json.loads(settings.read_text())+ env = {+ entry["name"]: entry["value"]+ for entry in saved["claudeCode.environmentVariables"]+ }+ assert env["CLAUDE_CODE_DISABLE_ADVISOR_TOOL"] == "1"+ assert env["KEEP_ME"] == "user-value"+ assert saved["editor.fontSize"] == 15+ assert json.loads(state.read_text()) == {+ "theme": "dark",+ "hasCompletedOnboarding": True,+ }+ assert (+ claude_integration.configure(settings, state, URL, TOKEN)["connected"] is True+ )+ before = [path.stat().st_mtime_ns for path in (settings, state)]+ assert claude_integration.refresh_connected(settings, state, URL, TOKEN) is False+ assert [path.stat().st_mtime_ns for path in (settings, state)] == before++[email protected]("change", ["missing", "disconnected", "url", "token"])+def test_refresh_does_not_claim_unrecognized_claude(tmp_path, change):+ settings, state = tmp_path / "settings.json", tmp_path / ".claude.json"+ document = json.loads(json.dumps(OLD_CLAUDE))+ if change == "disconnected":+ document.pop("claudeCode.disableLoginPrompt")+ elif change in {"url", "token"}:+ document["claudeCode.environmentVariables"][0 if change == "url" else 1][+ "value"+ ] = "other"+ if change != "missing":+ settings.write_text(json.dumps(document))+ before = settings.read_bytes() if settings.exists() else None+ # Unrelated Claude state is not even parsed when the integration is not ours.+ state.write_text("{invalid")+ assert claude_integration.refresh_connected(settings, state, URL, TOKEN) is False+ assert (settings.read_bytes() if settings.exists() else None) == before+ assert state.read_text() == "{invalid"+++def test_refresh_claude_retry_finishes_partial_write(tmp_path, monkeypatch):+ settings, state = tmp_path / "settings.json", tmp_path / ".claude.json"+ settings.write_text(json.dumps(OLD_CLAUDE))+ before = settings.read_bytes()+ write = claude_integration.atomic_write_text++ def fail_settings(path, content):+ if path == settings:+ raise PermissionError("denied")+ write(path, content)++ with monkeypatch.context() as patch:+ patch.setattr(claude_integration, "atomic_write_text", fail_settings)+ with pytest.raises(PermissionError):+ claude_integration.refresh_connected(settings, state, URL, TOKEN)+ assert settings.read_bytes() == before+ assert json.loads(state.read_text())["hasCompletedOnboarding"] is True+ assert claude_integration.refresh_connected(settings, state, URL, TOKEN) is True+ assert (+ claude_integration.configure(settings, state, URL, TOKEN)["connected"] is True+ )+++def test_refresh_codex_merges_latest_settings_without_changing_model(tmp_path):+ path, catalog = tmp_path / "config.toml", tmp_path / "catalog.json"+ path.write_text(OLD_CODEX)+ assert codex_integration.recognizes_connection(path, URL) is True+ assert codex_integration.refresh_connected(path, catalog, URL) is True+ saved = tomllib.loads(path.read_text())+ assert saved["model"] == "my-model"+ assert "# Preserve my choice" in path.read_text()+ assert saved["model_catalog_json"] == str(catalog.resolve())+ assert saved["model_providers"]["fcc"]["auth"] == {+ "command": "fcc-codex",+ "args": ["--print-proxy-auth-token"],+ }+ assert saved["model_providers"]["other"] == {"base_url": "https://example.com/v1"}+ assert codex_integration.configure(path, catalog, URL)["connected"] is True+ before = path.stat().st_mtime_ns+ assert codex_integration.refresh_connected(path, catalog, URL) is False+ assert path.stat().st_mtime_ns == before+++ "source",+ [+ None,+ "",+ OLD_CODEX.replace('model_provider = "fcc"', 'model_provider = "other"'),+ OLD_CODEX.replace("localhost:8000", "localhost:9999"),+ ],+)+def test_refresh_codex_leaves_unrecognized_settings_alone(tmp_path, source):+ path = tmp_path / "config.toml"+ if source is not None:+ path.write_text(source)+ before = path.read_bytes() if path.exists() else None+ assert codex_integration.recognizes_connection(path, URL) is False+ assert (+ codex_integration.refresh_connected(path, tmp_path / "catalog.json", URL)+ is False+ )+ assert (path.read_bytes() if path.exists() else None) == before++[email protected]("integration", ["claude", "codex"])+def test_refresh_rejects_malformed_input_without_writing(tmp_path, integration):+ path = tmp_path / "settings"+ path.write_text("{invalid")+ with pytest.raises(ValueError):+ if integration == "claude":+ claude_integration.refresh_connected(+ path, tmp_path / ".claude.json", URL, TOKEN+ )+ else:+ codex_integration.refresh_connected(path, tmp_path / "catalog.json", URL)+ assert path.read_text() == "{invalid"+ assert list(tmp_path.iterdir()) == [path]diff --git a/tests/runtime/test_integration_startup.py b/tests/runtime/test_integration_startup.pynew file mode 100644index 00000000..01d167ca--- /dev/null+++ b/tests/runtime/test_integration_startup.py@@ -0,0 +1,288 @@+import asyncio+import json+import threading+from unittest.mock import AsyncMock, MagicMock++import httpx+import pytest++from free_claude_code.api.app import create_app+from free_claude_code.api.ports import ApiServices+from free_claude_code.application.model_metadata import ProviderModelInfo+from free_claude_code.application.readiness import InitializationWait+from free_claude_code.config.loader import ManagedConfigStore+from free_claude_code.config.settings import Settings+from free_claude_code.harnesses import claude_integration, codex_integration+from free_claude_code.providers.base import BaseProvider+from free_claude_code.providers.runtime.runtime import ProviderRuntime+from free_claude_code.runtime.application import ApplicationRuntime+from free_claude_code.runtime.configuration import ConfigurationService+from free_claude_code.runtime.provider_manager import ProviderRuntimeManager+from tests.harnesses.test_integration_refresh import OLD_CLAUDE, OLD_CODEX, TOKEN+from tests.web_tools_support import StubWebToolsClient+++def runtime():+ settings = Settings().model_copy(+ update={+ "port": 8000,+ "proxy_auth_token": TOKEN,+ "messaging_platform": "none",+ "model": "nvidia_nim/one",+ "nvidia_nim_api_key": "test",+ }+ )+ provider = MagicMock(spec=BaseProvider)+ provider.list_model_infos = AsyncMock(+ return_value=frozenset({ProviderModelInfo("one")})+ )++ async def construct(_id, _settings):+ return provider++ manager = ProviderRuntimeManager(+ settings,+ runtime_factory=lambda snapshot: ProviderRuntime(+ snapshot, provider_constructor=construct+ ),+ )+ return ApplicationRuntime(+ manager,+ configuration=ConfigurationService(ManagedConfigStore()),+ transcriber=None,+ )+++def old_connections():+ claude, codex = claude_integration.settings_path(), codex_integration.config_path()+ claude.parent.mkdir(parents=True)+ codex.parent.mkdir(parents=True)+ claude.write_text(json.dumps(OLD_CLAUDE))+ codex.write_text(OLD_CODEX)+ return claude, codex+++async def finish(runtime):+ await asyncio.wait_for(+ asyncio.gather(runtime._claude_update.task, runtime._codex_update.task), 5+ )+++async def test_startup_refreshes_old_connections_and_status_is_read_only(runtime):+ claude, codex = old_connections()+ try:+ await runtime.start()+ await finish(runtime)+ for status in (+ await runtime.claude_vscode_status(),+ await runtime.codex_integration_status(),+ ):+ assert status["connected"] is True+ assert status["update"] == {+ "state": "ready",+ "changed": True,+ "message": None,+ }+ before = [p.stat().st_mtime_ns for p in (claude, codex)]+ await runtime.claude_vscode_status()+ await runtime.codex_integration_status()+ assert [p.stat().st_mtime_ns for p in (claude, codex)] == before+ await runtime.disconnect_claude_vscode()+ assert (await runtime.claude_vscode_status())["update"]["changed"] is False+ await runtime.refresh_claude_vscode()+ await runtime._claude_update.task+ assert (await runtime.claude_vscode_status())["connected"] is False+ finally:+ await runtime.close()+++async def test_codex_wait_does_not_delay_http_or_claude(runtime, monkeypatch):+ old_connections()+ entered, release = asyncio.Event(), asyncio.Event()+ wait_for_catalog = runtime.provider_manager.wait_for_catalog_file++ async def held(wait):+ assert wait.remaining is None+ entered.set()+ await release.wait()+ return await wait_for_catalog(wait)++ monkeypatch.setattr(runtime.provider_manager, "wait_for_catalog_file", held)+ app = create_app(+ ApiServices(+ runtime.provider_manager, runtime, runtime, web_tools=StubWebToolsClient()+ )+ )+ try:+ await asyncio.wait_for(runtime.start(), 1)+ await asyncio.wait_for(entered.wait(), 5)+ await asyncio.wait_for(runtime._claude_update.task, 5)+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url="http://127.0.0.1"+ ) as client:+ assert (await client.get("/health")).status_code == 200+ status = (await client.get("/admin/api/integrations/codex")).json()+ assert status["connected"] is None+ assert status["update"]["state"] == "starting"+ assert (await runtime.claude_vscode_status())["connected"] is True+ assert (await client.get("/admin/api/status")).json()["startup"][+ "integrations"+ ]["codex"]["state"] == "starting"+ release.set()+ await finish(runtime)+ assert (await runtime.codex_integration_status())["connected"] is True+ finally:+ release.set()+ await runtime.close()+++async def test_unrecognized_codex_never_waits_for_catalog(runtime, monkeypatch):+ wait = AsyncMock(side_effect=AssertionError("No connection to refresh"))+ monkeypatch.setattr(runtime.provider_manager, "wait_for_catalog_file", wait)+ try:+ await runtime.start()+ await finish(runtime)+ wait.assert_not_awaited()+ assert (await runtime.codex_integration_status())["connected"] is False+ assert not codex_integration.config_path().exists()+ assert not claude_integration.claude_state_path().exists()+ finally:+ await runtime.close()+++async def test_update_failure_is_isolated_and_retry_finishes(runtime):+ claude, _ = old_connections()+ claude.write_text("{secret-invalid-json")+ try:+ await runtime.start()+ await finish(runtime)+ status = await runtime.claude_vscode_status()+ assert status["update"]["state"] == "failed"+ assert "secret" not in status["update"]["message"]+ assert (await runtime.codex_integration_status())["connected"] is True+ claude.write_text(json.dumps(OLD_CLAUDE))+ 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+ await runtime.refresh_claude_vscode()+ assert runtime._claude_update.task is task+ await asyncio.wait_for(task, 5)+ assert (await runtime.claude_vscode_status())["connected"] is True+ finally:+ await runtime.close()+++async def test_shutdown_drains_integration_writer(runtime, monkeypatch):+ entered, release = threading.Event(), threading.Event()+ write = claude_integration.refresh_connected++ def held(*args):+ entered.set()+ assert release.wait(5)+ return write(*args)++ monkeypatch.setattr(claude_integration, "refresh_connected", held)+ close = None+ try:+ await runtime.start()+ assert await asyncio.to_thread(entered.wait, 5)+ close = asyncio.create_task(runtime.close())+ await asyncio.sleep(0)+ assert not close.done()+ assert runtime._config_lock.locked()+ release.set()+ assert await asyncio.wait_for(close, 5)+ finally:+ release.set()+ if close is not None:+ await close+ else:+ await runtime.close()+++async def test_unbounded_initialization_wait_remains_owned_on_cancel():+ release = asyncio.Event()+ work = asyncio.create_task(release.wait())+ wait = InitializationWait(None)+ observer = asyncio.create_task(wait.wait(work))+ try:+ await asyncio.sleep(0)+ observer.cancel()+ with pytest.raises(asyncio.CancelledError):+ await observer+ assert not work.done()+ release.set()+ assert await wait.wait(work)+ assert wait.remaining is None+ finally:+ release.set()+ await work+++async def test_codex_refresh_rechecks_catalog_generation_before_writing(+ runtime, monkeypatch+):+ old_connections()+ original = runtime.provider_manager.wait_for_catalog_file+ calls = 0++ async def replace_after_wait(wait):+ nonlocal calls+ generation = await original(wait)+ calls += 1+ if calls == 1:+ settings = runtime.settings.model_copy(update={"model": "nvidia_nim/new"})+ await runtime.provider_manager.replace(settings, commit=AsyncMock())+ return generation++ monkeypatch.setattr(+ runtime.provider_manager, "wait_for_catalog_file", replace_after_wait+ )+ try:+ await runtime.start()+ await finish(runtime)+ assert calls == 2+ assert (await runtime.codex_integration_status())["connected"] is True+ finally:+ await runtime.close()++[email protected]("integration", ["claude-vscode", "codex"])+async def test_refresh_endpoint_is_local_only_and_does_not_connect(+ runtime, integration+):+ app = create_app(+ ApiServices(+ runtime.provider_manager, runtime, runtime, web_tools=StubWebToolsClient()+ )+ )+ try:+ await runtime.start()+ await finish(runtime)+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url="http://127.0.0.1"+ ) as client:+ path = f"/admin/api/integrations/{integration}"+ blocked = await client.post(+ path + "/refresh", headers={"Origin": "https://other.test"}+ )+ assert blocked.status_code == 403+ response = await client.post(path + "/refresh")+ assert response.status_code == 200+ assert response.json()["update"]["state"] == "starting"+ await finish(runtime)+ assert (await client.get(path)).json()["connected"] is False+ assert not claude_integration.settings_path().exists()+ assert not codex_integration.config_path().exists()+ finally:+ await runtime.close()diff --git a/uv.lock b/uv.lockindex ac56ee3a..8a215021 100644--- a/uv.lock+++ b/uv.lock@@ -599,7 +599,7 @@ wheels = [[[package]]name = "free-claude-code"-version = "6.2.43"+version = "6.2.44"source = { editable = "." }dependencies = [{ name = "aiohttp" },