Skip to content

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 and disconnect Codex from Integrations (#1760)

Ali Khokhar896dd68c8b60
diff --git a/e2e/conftest.py b/e2e/conftest.py
index 0cb03ebf..711f8d63 100644
--- a/e2e/conftest.py
+++ b/e2e/conftest.py
@@ -16,7 +16,7 @@ from e2e.code_support import CodeControl
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.cli import vscode
+from free_claude_code.cli import codex_integration, vscode
from free_claude_code.config import env_migrations, paths
from free_claude_code.config.env_migrations import recognized_env_keys
from free_claude_code.config.loader import (
@@ -129,6 +129,9 @@ def admin_base_url(
"""Serve one fully isolated Admin application on an OS-assigned port."""
config_dir = tmp_path / ".fcc"
+ monkeypatch.setattr(
+ codex_integration, "config_path", lambda: tmp_path / ".codex" / "config.toml"
+ )
monkeypatch.setattr(vscode, "claude_state_path", lambda: tmp_path / ".claude.json")
monkeypatch.setattr(
vscode, "settings_path", lambda: tmp_path / "vscode" / "settings.json"
diff --git a/e2e/test_admin_integrations.py b/e2e/test_admin_integrations.py
index 9a910bb9..fb5321af 100644
--- a/e2e/test_admin_integrations.py
+++ b/e2e/test_admin_integrations.py
@@ -1,4 +1,5 @@
import json
+import tomllib
import pytest
from playwright.sync_api import expect
@@ -7,7 +8,7 @@ from free_claude_code.cli import vscode
@pytest.mark.parametrize("width", [1280, 390])
-def test_codex_preview_modal_is_noop_and_dismissible(
+def test_codex_connect_disconnect_and_modal_paths(
page, admin_base_url, tmp_path, width
):
page.set_viewport_size({"width": width, "height": 900})
@@ -19,8 +20,6 @@ def test_codex_preview_modal_is_noop_and_dismissible(
expect(cards.nth(1)).to_contain_text(
"Use FCC's models in the Codex CLI, VS Code extension, and desktop app."
)
- requests = []
- page.on("request", lambda request: requests.append(request.url))
opener = page.locator("#openCodexIntegration")
dialog = page.get_by_role("dialog", name="Codex", exact=True)
opener.click()
@@ -28,14 +27,13 @@ def test_codex_preview_modal_is_noop_and_dismissible(
expect(page.locator("#claudeIntegrationDialog")).not_to_be_visible()
expect(dialog.get_by_role("button", name="Close", exact=True)).to_be_focused()
expect(dialog).to_contain_text(
- "Will configure Codex to use FCC's models through its shared config.toml."
+ "Configure Codex to use FCC. Your selected model stays unchanged."
)
assert dialog.evaluate("element => element.scrollWidth <= element.clientWidth")
- action = dialog.get_by_role("button", name="Connect", exact=True)
- for _ in range(3):
- action.click()
- expect(action).to_be_enabled()
- expect(dialog).to_be_visible()
+ path = tmp_path / ".codex" / "config.toml"
+ expect(dialog.locator("#codexIntegrationFiles li")).to_have_text(
+ [str(path.resolve())]
+ )
page.locator("#codexIntegrationDescription").click()
expect(dialog).to_be_visible()
dialog.get_by_role("button", name="Close", exact=True).click()
@@ -47,7 +45,29 @@ def test_codex_preview_modal_is_noop_and_dismissible(
opener.click()
page.mouse.click(1, 1)
expect(dialog).not_to_be_visible()
- assert requests == []
+ assert not path.exists()
+ path.parent.mkdir()
+ path.write_text('model = "my-choice" # Keep this\n')
+ opener.click()
+ page.locator("#confirmCodexIntegration").click()
+ expect(dialog).not_to_be_visible()
+ expect(opener).to_have_text("Disconnect")
+ expect(page.locator("#codexIntegrationStatus")).to_have_text("Connected")
+ expect(page.locator("#codexIntegrationMessage")).to_have_text(
+ "Settings saved. Restart Codex and select an FCC model."
+ )
+ assert tomllib.loads(path.read_text())["model"] == "my-choice"
+ assert "# Keep this" in path.read_text()
+ page.reload()
+ expect(opener).to_have_text("Disconnect")
+ opener.click()
+ expect(page.locator("#confirmCodexIntegration")).to_have_text("Disconnect")
+ expect(dialog.locator("#codexIntegrationFiles li")).to_have_text(
+ [str(path.resolve())]
+ )
+ page.locator("#confirmCodexIntegration").click()
+ expect(opener).to_have_text("Connect")
+ assert tomllib.loads(path.read_text()) == {"model": "my-choice"}
assert not (tmp_path / "vscode" / "settings.json").exists()
assert not (tmp_path / ".claude.json").exists()
@@ -180,3 +200,44 @@ def test_save_pending_and_failure_stay_in_modal(page, admin_base_url):
expect(page.locator("#claudeIntegrationDialogMessage")).to_have_text(
"Could not save settings."
)
+
+
+def test_codex_existing_setup_revisit_and_invalid_config_retry(
+ page, admin_base_url, tmp_path
+):
+ path = tmp_path / ".codex" / "config.toml"
+ assert page.request.post(
+ f"{admin_base_url}/admin/api/integrations/codex/connect"
+ ).ok
+ page.goto(f"{admin_base_url}/admin/integrations")
+ opener = page.locator("#openCodexIntegration")
+ expect(opener).to_have_text("Disconnect")
+ page.get_by_role("button", name="Providers", exact=True).click()
+ path.write_text("[invalid")
+ page.get_by_role("button", name="Integrations", exact=True).click()
+ expect(page.locator("#codexIntegrationMessage")).to_contain_text("Check the TOML")
+ expect(opener).to_have_text("Retry")
+ path.write_text("")
+ opener.click()
+ expect(opener).to_have_text("Connect")
+
+
+def test_codex_save_pending_and_failure_stay_in_modal(page, admin_base_url, tmp_path):
+ page.goto(f"{admin_base_url}/admin/integrations")
+ page.locator("#openCodexIntegration").click()
+ requests = []
+ page.route(
+ "**/admin/api/integrations/codex/connect", lambda route: requests.append(route)
+ )
+ action = page.locator("#confirmCodexIntegration")
+ action.click()
+ expect(action).to_be_disabled()
+ expect(action).to_have_text("Saving…")
+ expect(page.locator("#openCodexIntegration")).to_be_disabled()
+ requests[0].fulfill(status=503, json={"detail": "Could not save settings."})
+ expect(action).to_be_enabled()
+ expect(page.locator("#codexIntegrationDialog")).to_be_visible()
+ expect(page.locator("#codexIntegrationDialogMessage")).to_have_text(
+ "Could not save settings."
+ )
+ assert not (tmp_path / ".codex" / "config.toml").exists()
diff --git a/pyproject.toml b/pyproject.toml
index 1dc5828d..44b5295c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "free-claude-code"
-version = "6.2.8"
+version = "6.2.9"
description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"
readme = "README.md"
requires-python = ">=3.14.0"
@@ -25,6 +25,7 @@ dependencies = [
"aiohttp>=3.14.3",
"jsonschema>=4.25.0",
"json5>=0.15.0",
+ "tomlkit>=0.13.3",
"google-auth[requests]>=2.56.3",
"requests[socks]>=2.34.2",
"pystray>=0.19.5; sys_platform == 'win32' or sys_platform == 'darwin'",
diff --git a/src/free_claude_code/api/admin_routes.py b/src/free_claude_code/api/admin_routes.py
index aedc192d..9e44dda1 100644
--- a/src/free_claude_code/api/admin_routes.py
+++ b/src/free_claude_code/api/admin_routes.py
@@ -273,6 +273,33 @@ async def disconnect_claude_vscode(
return await _integration_response(services.admin.disconnect_claude_vscode)
[email protected]("/admin/api/integrations/codex")
+async def codex_integration_status(
+ request: Request,
+ services: ApiServices = Depends(get_services),
+):
+ require_loopback_admin(request)
+ return await _integration_response(services.admin.codex_integration_status)
+
+
[email protected]("/admin/api/integrations/codex/connect")
+async def connect_codex(
+ request: Request,
+ services: ApiServices = Depends(get_services),
+):
+ require_loopback_admin(request)
+ return await _integration_response(services.admin.connect_codex)
+
+
[email protected]("/admin/api/integrations/codex/disconnect")
+async def disconnect_codex(
+ request: Request,
+ services: ApiServices = Depends(get_services),
+):
+ require_loopback_admin(request)
+ return await _integration_response(services.admin.disconnect_codex)
+
+
async def _integration_response(
operation: Callable[[], Awaitable[JsonObject]],
) -> JSONResponse:
diff --git a/src/free_claude_code/api/admin_static/admin.js b/src/free_claude_code/api/admin_static/admin.js
index 4589e805..ff6a9f0e 100644
--- a/src/free_claude_code/api/admin_static/admin.js
+++ b/src/free_claude_code/api/admin_static/admin.js
@@ -175,7 +175,10 @@ function setActiveView(viewId, { scroll = false } = {}) {
}
if (activeView.id === "code") window.CodeSessions.activate(window.location.pathname);
else window.CodeSessions.deactivate();
- if (activeView.id === "integrations") refreshClaudeIntegration();
+ if (activeView.id === "integrations") {
+ refreshClaudeIntegration();
+ refreshCodexIntegration();
+ }
}
function navigateToView(viewId) {
@@ -1342,7 +1345,87 @@ claudeIntegrationDialog.addEventListener("click", (event) => {
});
const codexIntegrationDialog = byId("codexIntegrationDialog");
-byId("openCodexIntegration").addEventListener("click", () => codexIntegrationDialog.showModal());
+const codexIntegration = { connected: null, busy: false, paths: null };
+const codexIntegrationPath = "/admin/api/integrations/codex";
+
+function renderCodexIntegration() {
+ const { connected, busy, paths } = codexIntegration;
+ const action = connected ? "Disconnect" : "Connect";
+ byId("openCodexIntegration").textContent = connected === null && !busy ? "Retry" : action;
+ byId("openCodexIntegration").disabled = busy;
+ byId("confirmCodexIntegration").textContent = busy ? "Saving…" : action;
+ byId("confirmCodexIntegration").disabled = busy || connected === null;
+ const status = byId("codexIntegrationStatus");
+ status.textContent = connected === null
+ ? (busy ? "Checking settings…" : "Could not check settings")
+ : (connected ? "Connected" : "Not connected");
+ status.className = `status-pill ${connected ? "ok" : "neutral"}`;
+ byId("codexIntegrationDescription").textContent = connected
+ ? "Remove FCC's Codex configuration. Other settings stay unchanged."
+ : "Configure Codex to use FCC. Your selected model stays unchanged.";
+ const files = byId("codexIntegrationFiles");
+ files.replaceChildren();
+ if (paths) {
+ const targets = [paths.codex_config];
+ targets.forEach((path) => {
+ const item = document.createElement("li");
+ const code = document.createElement("code");
+ code.textContent = path;
+ item.appendChild(code);
+ files.appendChild(item);
+ });
+ }
+}
+
+async function refreshCodexIntegration() {
+ if (codexIntegration.busy) return;
+ codexIntegration.busy = true;
+ renderCodexIntegration();
+ integrationMessage("codexIntegrationMessage", "");
+ try {
+ const result = await api(codexIntegrationPath);
+ codexIntegration.connected = result.connected;
+ codexIntegration.paths = result.paths;
+ } catch (error) {
+ codexIntegration.connected = null;
+ integrationMessage("codexIntegrationMessage", error.message, true);
+ } finally {
+ codexIntegration.busy = false;
+ renderCodexIntegration();
+ }
+}
+
+byId("openCodexIntegration").addEventListener("click", () => {
+ if (codexIntegration.connected === null) {
+ refreshCodexIntegration();
+ return;
+ }
+ integrationMessage("codexIntegrationDialogMessage", "");
+ codexIntegrationDialog.showModal();
+});
+byId("confirmCodexIntegration").addEventListener("click", async () => {
+ if (codexIntegration.busy || codexIntegration.connected === null) return;
+ const disconnect = codexIntegration.connected;
+ codexIntegration.busy = true;
+ renderCodexIntegration();
+ integrationMessage("codexIntegrationDialogMessage", "");
+ integrationMessage("codexIntegrationMessage", "");
+ try {
+ const result = await api(`${codexIntegrationPath}/${disconnect ? "disconnect" : "connect"}`, { method: "POST" });
+ codexIntegration.connected = result.connected;
+ codexIntegration.paths = result.paths;
+ codexIntegrationDialog.close();
+ integrationMessage("codexIntegrationMessage", disconnect
+ ? "Settings removed. Restart Codex to disconnect."
+ : "Settings saved. Restart Codex and select an FCC model.");
+ } catch (error) {
+ integrationMessage("codexIntegrationDialogMessage", error.message, true);
+ integrationMessage("codexIntegrationMessage", error.message, true);
+ } finally {
+ codexIntegration.busy = false;
+ renderCodexIntegration();
+ }
+});
byId("closeCodexIntegration").addEventListener("click", () => codexIntegrationDialog.close());
codexIntegrationDialog.addEventListener("click", (event) => {
if (event.target !== codexIntegrationDialog) return;
diff --git a/src/free_claude_code/api/admin_static/index.html b/src/free_claude_code/api/admin_static/index.html
index 37f77bcd..717963fd 100644
--- a/src/free_claude_code/api/admin_static/index.html
+++ b/src/free_claude_code/api/admin_static/index.html
@@ -112,17 +112,24 @@
<div>
<h3>Codex</h3>
<p>Use FCC's models in the Codex CLI, VS Code extension, and desktop app.</p>
+ <span id="codexIntegrationStatus" class="status-pill neutral" role="status">Checking settings…</span>
</div>
</div>
- <button id="openCodexIntegration" class="primary-button" type="button">Connect</button>
+ <button id="openCodexIntegration" class="primary-button" type="button" disabled>Connect</button>
+ <p id="codexIntegrationMessage" class="message-area" role="status" hidden></p>
</article>
<dialog id="codexIntegrationDialog" class="integration-dialog" aria-labelledby="codexIntegrationTitle" aria-describedby="codexIntegrationDescription">
<div class="section-heading">
<h3 id="codexIntegrationTitle">Codex</h3>
<button id="closeCodexIntegration" class="ghost-button" type="button" aria-label="Close" autofocus>×</button>
</div>
- <p id="codexIntegrationDescription">Will configure Codex to use FCC's models through its shared config.toml.</p>
- <button class="primary-button" type="button">Connect</button>
+ <p id="codexIntegrationDescription">Configure Codex to use FCC. Your selected model stays unchanged.</p>
+ <div class="integration-files">
+ <strong>Files to modify</strong>
+ <ul id="codexIntegrationFiles"></ul>
+ </div>
+ <button id="confirmCodexIntegration" class="primary-button" type="button">Connect</button>
+ <p id="codexIntegrationDialogMessage" class="message-area error" role="alert" hidden></p>
</dialog>
</section>
diff --git a/src/free_claude_code/api/ports.py b/src/free_claude_code/api/ports.py
index b2d76b54..a09f696f 100644
--- a/src/free_claude_code/api/ports.py
+++ b/src/free_claude_code/api/ports.py
@@ -34,6 +34,12 @@ class AdminRuntimePort(Protocol):
async def disconnect_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 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/cli/codex_integration.py b/src/free_claude_code/cli/codex_integration.py
new file mode 100644
index 00000000..cf75d974
--- /dev/null
+++ b/src/free_claude_code/cli/codex_integration.py
@@ -0,0 +1,115 @@
+"""Connect native Codex clients through their shared TOML configuration."""
+
+import os
+from pathlib import Path
+
+import tomlkit
+from tomlkit.container import OutOfOrderTableProxy
+from tomlkit.exceptions import ParseError
+from tomlkit.items import InlineTable, Table
+from tomlkit.toml_document import TOMLDocument
+
+from free_claude_code.cli.config_file import atomic_write_text
+from free_claude_code.cli.launchers.codex import codex_config_values
+from free_claude_code.cli.launchers.common import proxy_v1_url
+from free_claude_code.config.server_urls import same_proxy_url
+from free_claude_code.core.json_types import JsonObject
+
+
+def config_path() -> Path:
+ root = Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex")
+ return root / "config.toml"
+
+
+def _child_table(
+ parent: TOMLDocument | Table | InlineTable | OutOfOrderTableProxy,
+ key: str,
+ *,
+ create: bool = False,
+) -> Table | InlineTable | OutOfOrderTableProxy:
+ if key not in parent:
+ child = (
+ tomlkit.inline_table()
+ if isinstance(parent, InlineTable)
+ else tomlkit.table()
+ )
+ if create:
+ parent[key] = child
+ return child
+ child = parent[key]
+ if not isinstance(child, Table | InlineTable | OutOfOrderTableProxy):
+ raise ValueError("Codex provider configuration must use TOML tables")
+ return child
+
+
+def _read(path: Path) -> TOMLDocument:
+ try:
+ content = path.read_text(encoding="utf-8-sig")
+ except FileNotFoundError:
+ return tomlkit.document()
+ try:
+ document = tomlkit.parse(content)
+ except ParseError:
+ raise ValueError("Invalid Codex TOML") from None
+ providers = _child_table(document, "model_providers")
+ provider = _child_table(providers, "fcc")
+ _child_table(provider, "auth")
+ return document
+
+
+def _same_catalog(value: object, catalog_path: Path) -> bool:
+ return (
+ isinstance(value, str)
+ and Path(value).is_absolute()
+ and Path(value).resolve() == catalog_path
+ )
+
+
+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"
+ 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"]
+ )
+
+
+def configure(
+ path: Path, catalog_path: Path, proxy_root_url: str, connected: bool | None = None
+) -> JsonObject:
+ """Inspect or edit FCC's entries without changing the user's selected model."""
+ path = path.resolve()
+ catalog_path = catalog_path.resolve()
+ document = _read(path)
+ if connected is not None:
+ 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")
+ content = tomlkit.dumps(document)
+ if content != before:
+ atomic_write_text(path, content)
+ document = _read(path)
+ return {
+ "connected": _connected(document, catalog_path, proxy_root_url),
+ "paths": {"codex_config": str(path)},
+ }
diff --git a/src/free_claude_code/cli/config_file.py b/src/free_claude_code/cli/config_file.py
new file mode 100644
index 00000000..3bd674d6
--- /dev/null
+++ b/src/free_claude_code/cli/config_file.py
@@ -0,0 +1,33 @@
+"""Atomic text-file replacement for local client configuration."""
+
+import os
+import stat
+import tempfile
+from pathlib import Path
+
+
+def atomic_write_text(path: Path, content: str) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temporary: Path | None = None
+ try:
+ with tempfile.NamedTemporaryFile(
+ mode="w",
+ encoding="utf-8",
+ newline="\n",
+ dir=path.parent,
+ prefix=f".{path.name}.",
+ suffix=".tmp",
+ delete=False,
+ ) as output:
+ temporary = Path(output.name)
+ output.write(content)
+ output.flush()
+ os.fsync(output.fileno())
+ if path.exists():
+ temporary.chmod(stat.S_IMODE(path.stat().st_mode))
+ temporary.replace(path)
+ finally:
+ if temporary is not None and temporary.exists():
+ # Windows cannot delete a temporary file after copying a read-only mode.
+ temporary.chmod(stat.S_IRUSR | stat.S_IWUSR)
+ temporary.unlink()
diff --git a/src/free_claude_code/cli/launchers/codex.py b/src/free_claude_code/cli/launchers/codex.py
index 05f87052..819293ff 100644
--- a/src/free_claude_code/cli/launchers/codex.py
+++ b/src/free_claude_code/cli/launchers/codex.py
@@ -30,8 +30,10 @@ _STRIPPED_CODEX_ENV_KEYS = frozenset(
)
-def codex_config_args(*, api_url: str, model: str | None = None) -> list[str]:
- """Build native TOML overrides for the FCC Responses provider."""
+def codex_config_values(
+ *, api_url: str, model: str | None = None
+) -> dict[str, str | list[str]]:
+ """Shared configuration for the FCC Responses provider."""
values: dict[str, str | list[str]] = {
"model_provider": "fcc",
@@ -43,6 +45,12 @@ def codex_config_args(*, api_url: str, model: str | None = None) -> list[str]:
}
if model:
values["model"] = model
+ return values
+
+
+def codex_config_args(*, api_url: str, model: str | None = None) -> list[str]:
+ """Build native TOML overrides for the FCC Responses provider."""
+ values = codex_config_values(api_url=api_url, model=model)
return [
arg
for key, value in values.items()
diff --git a/src/free_claude_code/cli/vscode.py b/src/free_claude_code/cli/vscode.py
index 50a75b68..3f2fe20b 100644
--- a/src/free_claude_code/cli/vscode.py
+++ b/src/free_claude_code/cli/vscode.py
@@ -2,16 +2,15 @@
import json
import os
-import stat
import sys
-import tempfile
from pathlib import Path
from typing import cast
-from urllib.parse import urlsplit
import json5
from free_claude_code.cli.claude_env import claude_proxy_values
+from free_claude_code.cli.config_file import atomic_write_text
+from free_claude_code.config.server_urls import same_proxy_url
from free_claude_code.core.json_types import JsonObject
_ENV = "claudeCode.environmentVariables"
@@ -70,32 +69,13 @@ def _read(path: Path, names: set[str]) -> tuple[JsonObject, list[JsonObject]]:
return document, cast(list[JsonObject], entries)
-def _same_url(value: object, expected: str) -> bool:
- if not isinstance(value, str):
- return False
-
- def normalized(url: str) -> tuple[str, str | None, int | None, str]:
- parsed = urlsplit(url)
- if parsed.username or parsed.password or parsed.query or parsed.fragment:
- raise ValueError("Unexpected URL components")
- host = parsed.hostname
- if host in {"localhost", "127.0.0.1", "::1"}:
- host = "localhost"
- return parsed.scheme, host, parsed.port, parsed.path.rstrip("/")
-
- try:
- return normalized(value) == normalized(expected)
- except ValueError:
- return False
-
-
def _connected(
document: JsonObject, entries: list[JsonObject], values: dict[str, str]
) -> bool:
environment = {entry["name"]: entry["value"] for entry in entries}
return (
document.get(_LOGIN) is True
- and _same_url(
+ and same_proxy_url(
environment.get("ANTHROPIC_BASE_URL"), values["ANTHROPIC_BASE_URL"]
)
and environment.get("ANTHROPIC_AUTH_TOKEN") == values["ANTHROPIC_AUTH_TOKEN"]
@@ -103,33 +83,6 @@ def _connected(
)
-def _write(path: Path, content: str) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- temporary: Path | None = None
- try:
- with tempfile.NamedTemporaryFile(
- mode="w",
- encoding="utf-8",
- newline="\n",
- dir=path.parent,
- prefix=f".{path.name}.",
- suffix=".tmp",
- delete=False,
- ) as output:
- temporary = Path(output.name)
- output.write(content)
- output.flush()
- os.fsync(output.fileno())
- if path.exists():
- temporary.chmod(stat.S_IMODE(path.stat().st_mode))
- temporary.replace(path)
- finally:
- if temporary is not None and temporary.exists():
- # Windows cannot delete a temporary file after copying a read-only mode.
- temporary.chmod(stat.S_IRUSR | stat.S_IWUSR)
- temporary.unlink()
-
-
def configure(
path: Path,
state_path: Path,
@@ -170,9 +123,11 @@ def configure(
settings_content = json.dumps(document, indent=2, allow_nan=False) + "\n"
if connected and onboarding.get(_ONBOARDING) is not True:
onboarding[_ONBOARDING] = True
- _write(state_path, json.dumps(onboarding, indent=2, allow_nan=False) + "\n")
+ atomic_write_text(
+ state_path, json.dumps(onboarding, indent=2, allow_nan=False) + "\n"
+ )
if settings_changed:
- _write(path, settings_content)
+ atomic_write_text(path, settings_content)
document, entries = _read(path, set(values))
if connected:
onboarding = _read_object(state_path)
diff --git a/src/free_claude_code/config/server_urls.py b/src/free_claude_code/config/server_urls.py
index c5414384..d58e0234 100644
--- a/src/free_claude_code/config/server_urls.py
+++ b/src/free_claude_code/config/server_urls.py
@@ -1,5 +1,7 @@
"""Browser-friendly local server URLs shared by runtime and launchers."""
+from urllib.parse import urlsplit
+
from free_claude_code.config.settings import Settings
@@ -24,3 +26,23 @@ def local_admin_url(settings: Settings) -> str:
"""Return a browser-friendly URL for the localhost-only admin UI."""
return f"{local_proxy_root_url(settings)}/admin"
+
+
+def same_proxy_url(value: object, expected: str) -> bool:
+ """Compare client endpoints, allowing equivalent loopback names and trailing slashes."""
+ if not isinstance(value, str):
+ return False
+
+ def normalized(url: str) -> tuple[str, str | None, int | None, str]:
+ parsed = urlsplit(url)
+ if parsed.username or parsed.password or parsed.query or parsed.fragment:
+ raise ValueError("Unexpected URL components")
+ host = parsed.hostname
+ if host in {"localhost", "127.0.0.1", "::1"}:
+ host = "localhost"
+ return parsed.scheme, host, parsed.port, parsed.path.rstrip("/")
+
+ try:
+ return normalized(value) == normalized(expected)
+ except ValueError:
+ return False
diff --git a/src/free_claude_code/runtime/application.py b/src/free_claude_code/runtime/application.py
index 88a781e3..b6933900 100644
--- a/src/free_claude_code/runtime/application.py
+++ b/src/free_claude_code/runtime/application.py
@@ -27,7 +27,7 @@ from free_claude_code.application.errors import (
)
from free_claude_code.application.model_metadata import ProviderModelRefreshResult
from free_claude_code.application.ports import StopResult
-from free_claude_code.cli import vscode
+from free_claude_code.cli import codex_integration, vscode
from free_claude_code.config.admin.persistence import (
PreparedAdminUpdate,
)
@@ -35,7 +35,10 @@ from free_claude_code.config.admin.state import ConfigInputValue, ValueState
from free_claude_code.config.admin.status import provider_config_status
from free_claude_code.config.loader import clear_settings_cache
from free_claude_code.config.model_refs import parse_provider_type
-from free_claude_code.config.paths import messaging_state_dir_path
+from free_claude_code.config.paths import (
+ codex_model_catalog_path,
+ messaging_state_dir_path,
+)
from free_claude_code.config.server_urls import local_admin_url, local_proxy_root_url
from free_claude_code.config.settings import Settings
from free_claude_code.core.json_types import JsonObject
@@ -389,6 +392,43 @@ class ApplicationRuntime:
"Could not access VS Code settings.json or .claude.json. Check file permissions and try again."
) from None
+ async def codex_integration_status(self) -> JsonObject:
+ return await self._codex_integration(None)
+
+ async def connect_codex(self) -> JsonObject:
+ return await self._codex_integration(True)
+
+ async def disconnect_codex(self) -> JsonObject:
+ return await self._codex_integration(False)
+
+ async def _codex_integration(self, connected: bool | None) -> JsonObject:
+ async with self._config_lock:
+ 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,
+ )
+ )
+ )
+ 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
+
async def admin_status(self) -> JsonObject:
values = await self.admin_values()
settings = self.settings
diff --git a/tests/api/test_codex_integration_routes.py b/tests/api/test_codex_integration_routes.py
new file mode 100644
index 00000000..be9ba62f
--- /dev/null
+++ b/tests/api/test_codex_integration_routes.py
@@ -0,0 +1,108 @@
+import tomllib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from free_claude_code.cli import codex_integration
+from free_claude_code.config.paths import codex_model_catalog_path
+from free_claude_code.config.settings import Settings
+from tests.api.support import create_test_app, runtime_for_app
+
+ROOT = "/admin/api/integrations/codex"
+
+
+def integration(tmp_path, monkeypatch):
+ path = tmp_path / "config.toml"
+ monkeypatch.setattr(codex_integration, "config_path", lambda: path)
+ app = create_test_app(
+ Settings(host="0.0.0.0", port=4321, proxy_auth_token="integration-secret")
+ )
+ with TestClient(
+ app, base_url="http://127.0.0.1", client=("127.0.0.1", 50000)
+ ) as client:
+ yield client, path, runtime_for_app(app)
+
+
+def test_routes_inspect_connect_and_disconnect(integration):
+ client, path, _ = integration
+ response = client.get(ROOT)
+ assert response.json() == {
+ "connected": False,
+ "paths": {"codex_config": str(path.resolve())},
+ }
+ assert response.headers["cache-control"] == "no-store"
+ assert not path.exists()
+ path.write_text('model = "user-choice" # Keep\n')
+ response = client.post(f"{ROOT}/connect")
+ assert response.status_code == 200
+ assert response.json()["connected"] is True
+ assert response.headers["cache-control"] == "no-store"
+ assert "integration-secret" not in response.text + path.read_text()
+ data = tomllib.loads(path.read_text())
+ assert data["model"] == "user-choice"
+ assert data["model_catalog_json"] == str(codex_model_catalog_path().resolve())
+ assert data["model_providers"]["fcc"]["base_url"] == "http://127.0.0.1:4321/v1"
+ path.write_text(path.read_text().replace('"user-choice"', '"picker-choice"'))
+ assert client.get(ROOT).json()["connected"] is True
+ assert client.post(f"{ROOT}/disconnect").json()["connected"] is False
+ assert tomllib.loads(path.read_text()) == {"model": "picker-choice"}
+ assert "# Keep" in path.read_text()
+
+
[email protected]("action", ["", "/connect", "/disconnect"])
+def test_invalid_file_returns_safe_uncached_error(integration, action):
+ client, path, _ = integration
+ source = "[integration-secret"
+ path.write_text(source)
+ response = client.request("GET" if not action else "POST", ROOT + action)
+ assert response.status_code == 400
+ assert response.headers["cache-control"] == "no-store"
+ assert "integration-secret" not in response.text
+ assert response.json()["detail"]
+ assert path.read_text() == source
+
+
[email protected]("action", ["", "/connect", "/disconnect"])
+ "headers", [{"Host": "evil.test"}, {"Origin": "https://evil.test"}]
+)
+def test_local_admin_security_applies(integration, action, headers):
+ client, path, _ = integration
+ response = client.request(
+ "GET" if not action else "POST", ROOT + action, headers=headers
+ )
+ assert response.status_code == 403
+ assert not path.exists()
+
+
+def test_remote_client_is_rejected(integration):
+ client, path, _ = integration
+ with TestClient(
+ client.app, base_url="http://127.0.0.1", client=("192.0.2.1", 50000)
+ ) as remote:
+ assert remote.post(f"{ROOT}/connect").status_code == 403
+ assert not path.exists()
+
+
+def test_io_failure_returns_safe_error(integration, monkeypatch):
+ client, _, _ = integration
+
+ def fail(*args):
+ raise PermissionError("integration-secret")
+
+ monkeypatch.setattr(codex_integration, "configure", fail)
+ response = client.post(f"{ROOT}/connect")
+ assert response.status_code == 503
+ assert response.headers["cache-control"] == "no-store"
+ assert "integration-secret" not in response.text
+
+
+def test_pending_restart_and_shutdown_do_not_write(integration):
+ client, path, runtime = integration
+ runtime._pending_fields = ["PORT"]
+ assert client.post(f"{ROOT}/connect").status_code == 503
+ runtime._pending_fields = []
+ runtime.begin_shutdown()
+ assert client.post(f"{ROOT}/connect").status_code == 503
+ assert not path.exists()
diff --git a/tests/cli/test_codex_integration.py b/tests/cli/test_codex_integration.py
new file mode 100644
index 00000000..4da93998
--- /dev/null
+++ b/tests/cli/test_codex_integration.py
@@ -0,0 +1,209 @@
+import tomllib
+from pathlib import Path
+
+import pytest
+
+from free_claude_code.cli import codex_integration
+
+URL = "http://127.0.0.1:8082"
+
+
+def operate(path, connected=None):
+ return codex_integration.configure(
+ path, path.parent / "catalog.json", URL, connected
+ )
+
+
+def test_connect_disconnect_preserve_model_comments_and_other_providers(tmp_path):
+ path = tmp_path / "config.toml"
+ original = '# My preferences\nmodel = "my-choice" # Keep this\n\n[model_providers.other]\nname = "Other"\n'
+ path.write_text(original)
+ assert operate(path, True)["connected"] is True
+ saved = path.read_text()
+ assert '# My preferences\nmodel = "my-choice" # Keep this' in saved
+ data = tomllib.loads(saved)
+ assert data["model"] == "my-choice"
+ assert data["model_provider"] == "fcc"
+ assert Path(data["model_catalog_json"]) == tmp_path / "catalog.json"
+ assert data["model_providers"]["fcc"] == {
+ "name": "Free Claude Code",
+ "base_url": URL + "/v1",
+ "wire_api": "responses",
+ "auth": {"command": "fcc-codex", "args": ["--print-proxy-auth-token"]},
+ }
+ assert not (tmp_path / "catalog.json").exists()
+ assert operate(path, False)["connected"] is False
+ assert tomllib.loads(path.read_text()) == {
+ "model": "my-choice",
+ "model_providers": {"other": {"name": "Other"}},
+ }
+ assert '# My preferences\nmodel = "my-choice" # Keep this' in path.read_text()
+
+
+def test_missing_file_noops_and_unset_model(tmp_path):
+ path = tmp_path / "codex" / "config.toml"
+ assert operate(path)["connected"] is False
+ assert operate(path, False)["connected"] is False
+ assert not path.parent.exists()
+ result = operate(path, True)
+ assert result == {"connected": True, "paths": {"codex_config": str(path.resolve())}}
+ assert "model" not in tomllib.loads(path.read_text())
+ before = path.stat().st_mtime_ns
+ operate(path, True)
+ assert path.stat().st_mtime_ns == before
+ operate(path, False)
+ before = path.stat().st_mtime_ns
+ operate(path, False)
+ assert path.stat().st_mtime_ns == before
+
+
+def test_inline_tables_merge_without_losing_extra_values(tmp_path):
+ path = tmp_path / "config.toml"
+ path.write_text(
+ 'model_providers = {fcc = {name = "Old", extra = 7, auth = {command = "old", keep = true}}, other = {name = "Other"}} # Keep comment\n'
+ )
+ operate(path, True)
+ data = tomllib.loads(path.read_text())
+ assert data["model_providers"]["fcc"]["extra"] == 7
+ assert data["model_providers"]["fcc"]["auth"]["keep"] is True
+ assert "# Keep comment" in path.read_text()
+ assert operate(path)["connected"] is True
+ operate(path, False)
+ assert tomllib.loads(path.read_text())["model_providers"] == {
+ "other": {"name": "Other"}
+ }
+
+
+def test_manual_connection_ignores_model_and_display_name(tmp_path):
+ path = tmp_path / "config.toml"
+ path.write_text(
+ 'model = "another-model"\nmodel_provider = "fcc"\n'
+ f'model_catalog_json = "{(tmp_path / "catalog.json").as_posix()}"\n'
+ '[model_providers.fcc]\nname = "My FCC"\nbase_url = "http://localhost:8082/v1/"\nwire_api = "responses"\n'
+ '[model_providers.fcc.auth]\ncommand = "fcc-codex"\nargs = ["--print-proxy-auth-token"]\n'
+ )
+ before = path.read_bytes()
+ assert operate(path)["connected"] is True
+ assert path.read_bytes() == before
+
+
+ "content",
+ [
+ "model_providers = {}\n",
+ 'model_providers = {fcc = {name = "Old"}}\n',
+ '[model_providers.fcc]\nname = "Old"\n[other]\nkeep = true\n[model_providers.other]\nname = "Other"\n[model_providers.fcc.auth]\ncommand = "old"\n',
+ ],
+)
+def test_valid_table_layouts_can_be_updated(tmp_path, content):
+ path = tmp_path / "config.toml"
+ path.write_text(content)
+ original = tomllib.loads(content)
+ assert operate(path, True)["connected"] is True
+ assert tomllib.loads(path.read_text())["model_providers"]["fcc"]["auth"][
+ "args"
+ ] == ["--print-proxy-auth-token"]
+ assert operate(path, False)["connected"] is False
+ if "other" in original:
+ result = tomllib.loads(path.read_text())
+ assert result["other"] == original["other"]
+ assert (
+ result["model_providers"]["other"] == original["model_providers"]["other"]
+ )
+
+
+ "old,new",
+ [
+ ('model_provider = "fcc"', 'model_provider = "other"'),
+ ('wire_api = "responses"', 'wire_api = "chat"'),
+ (
+ 'base_url = "http://127.0.0.1:8082/v1"',
+ 'base_url = "http://127.0.0.1:8083/v1"',
+ ),
+ ('command = "fcc-codex"', 'command = "other"'),
+ ("--print-proxy-auth-token", "--other"),
+ ("catalog.json", "another-catalog.json"),
+ ],
+)
+def test_changed_connection_fields_are_detected(tmp_path, old, new):
+ path = tmp_path / "config.toml"
+ operate(path, True)
+ content = path.read_text()
+ assert old in content
+ path.write_text(content.replace(old, new))
+ assert operate(path)["connected"] is False
+
+
+def test_disconnect_keeps_global_selections_for_another_provider(tmp_path):
+ path = tmp_path / "config.toml"
+ operate(path, True)
+ path.write_text(
+ path.read_text()
+ .replace('model_provider = "fcc"', 'model_provider = "other"')
+ .replace("catalog.json", "other.json")
+ )
+ operate(path, False)
+ data = tomllib.loads(path.read_text())
+ assert data["model_provider"] == "other"
+ assert Path(data["model_catalog_json"]) == tmp_path / "other.json"
+ assert "fcc" not in data.get("model_providers", {})
+
+
+ "content",
+ [
+ "[invalid",
+ 'model_provider="fcc"\nmodel_provider="other"',
+ 'model_providers = "bad"',
+ "[model_providers]\nfcc = []",
+ '[model_providers.fcc]\nauth = "bad"',
+ ],
+)
+def test_invalid_documents_are_not_rewritten(tmp_path, content):
+ path = tmp_path / "config.toml"
+ path.write_text(content)
+ for action in (None, True, False):
+ with pytest.raises(ValueError):
+ operate(path, action)
+ assert path.read_text() == content
+
+
+def test_atomic_failure_preserves_file_and_cleans_temp(tmp_path, monkeypatch):
+ path = tmp_path / "config.toml"
+ path.write_text('model = "keep"')
+
+ def fail(self, target):
+ raise PermissionError("failure")
+
+ monkeypatch.setattr(Path, "replace", fail)
+ with pytest.raises(OSError):
+ operate(path, True)
+ assert path.read_text() == 'model = "keep"'
+ assert list(tmp_path.iterdir()) == [path]
+
+
+def test_symlink_unicode_and_path_display(tmp_path):
+ target = tmp_path / "actual.toml"
+ target.write_text('model = "模型" # Keep 😀\n', encoding="utf-8")
+ path = tmp_path / "config.toml"
+ try:
+ path.symlink_to(target.name)
+ except OSError as exc:
+ if getattr(exc, "winerror", None) == 1314:
+ pytest.skip("Windows symlink creation requires Developer Mode or privilege")
+ raise
+ assert operate(path, True)["paths"]["codex_config"] == str(target.resolve())
+ assert path.is_symlink()
+ assert tomllib.loads(target.read_text(encoding="utf-8"))["model"] == "模型"
+ operate(path, False)
+ assert path.is_symlink()
+ assert "# Keep 😀" in target.read_text(encoding="utf-8")
+
+
+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"
+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / "custom"))
+ assert codex_integration.config_path() == tmp_path / "custom/config.toml"
diff --git a/uv.lock b/uv.lock
index b1ede5b2..3ed623ea 100644
--- a/uv.lock
+++ b/uv.lock
@@ -598,7 +598,7 @@ wheels = [
[[package]]
name = "free-claude-code"
-version = "6.2.8"
+version = "6.2.9"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },
@@ -621,6 +621,7 @@ dependencies = [
{ name = "python-telegram-bot" },
{ name = "requests", extra = ["socks"] },
{ name = "tiktoken" },
+ { name = "tomlkit" },
{ name = "uvicorn" },
]
@@ -675,6 +676,7 @@ requires-dist = [
{ name = "python-telegram-bot", specifier = ">=22.8" },
{ name = "requests", extras = ["socks"], specifier = ">=2.34.2" },
{ name = "tiktoken", specifier = ">=0.13.0" },
+ { name = "tomlkit", specifier = ">=0.13.3" },
{ name = "torch", marker = "extra == 'voice-local'", specifier = ">=2.13.0", index = "https://download.pytorch.org/whl/cu130" },
{ name = "transformers", marker = "extra == 'voice-local'", specifier = ">=5.15.0" },
{ name = "uvicorn", specifier = ">=0.52.1" },
@@ -2608,6 +2610,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/72/f4/0de46cfa12cdcbcd464cc59fde36912af405696f687e53a091fb432f694c/tokenizers-0.22.2-cp39-abi3-win_arm64.whl", hash = "sha256:9ce725d22864a1e965217204946f830c37876eee3b2ba6fc6255e8e903d5fcbc", size = 2612133, upload-time = "2026-01-05T10:45:17.232Z" },
]
+[[package]]
+name = "tomlkit"
+version = "0.15.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/94/96/e07752635b98536177fa1f37671c8f3cdde2e724c6bcf6034b2cfb571565/tomlkit-0.15.1.tar.gz", hash = "sha256:e25bbf38843005246210a12982776f27f99cb9be67160e14434d0c0d21ee1e97", size = 180129, upload-time = "2026-07-17T01:48:04.562Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/13/bc/8c13eb66537dce1d2bd3a57132902f38d0e7f5bb46fa9f4daed9fe9d76ee/tomlkit-0.15.1-py3-none-any.whl", hash = "sha256:177a05aece5a8ca5266fd3c448abb47b8d352f09d477d3ca8332db4d89b24304", size = 49449, upload-time = "2026-07-17T01:48:05.728Z" },
+]
+
[[package]]
name = "torch"
version = "2.13.0+cu130"