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

Add Claude Code VS Code connect and disconnect (#1756)

Ali Khokharf861d7dcefcc
diff --git a/e2e/conftest.py b/e2e/conftest.py
index f4de377e..551bbec1 100644
--- a/e2e/conftest.py
+++ b/e2e/conftest.py
@@ -16,6 +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.config import env_migrations, paths
from free_claude_code.config.env_migrations import recognized_env_keys
from free_claude_code.config.loader import (
@@ -128,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(
+ vscode, "settings_path", lambda: tmp_path / "vscode" / "settings.json"
+ )
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.setenv("USERPROFILE", str(tmp_path))
for key in recognized_env_keys():
diff --git a/e2e/test_admin_integrations.py b/e2e/test_admin_integrations.py
new file mode 100644
index 00000000..dcd5d71d
--- /dev/null
+++ b/e2e/test_admin_integrations.py
@@ -0,0 +1,97 @@
+import json
+
+from playwright.sync_api import expect
+
+from free_claude_code.cli import vscode
+
+
+def test_connect_disconnect_and_modal_dismissal(page, admin_base_url, tmp_path):
+ path = tmp_path / "vscode" / "settings.json"
+ page.goto(f"{admin_base_url}/admin/integrations")
+ card_button = page.locator("#openClaudeIntegration")
+ dialog = page.locator("#claudeIntegrationDialog")
+ action = page.locator("#confirmClaudeIntegration")
+ expect(card_button).to_be_enabled()
+ expect(card_button).to_have_text("Connect")
+ for dismiss in ("close", "escape", "outside"):
+ card_button.click()
+ expect(dialog).to_be_visible()
+ if dismiss == "close":
+ dialog.get_by_role("button", name="Close", exact=True).click()
+ elif dismiss == "escape":
+ page.keyboard.press("Escape")
+ else:
+ page.mouse.click(1, 1)
+ expect(dialog).not_to_be_visible()
+ assert not path.exists()
+ card_button.click()
+ action.click()
+ expect(dialog).not_to_be_visible()
+ expect(card_button).to_have_text("Disconnect")
+ expect(page.locator("#claudeIntegrationStatus")).to_have_text("Connected")
+ expect(page.locator("#claudeIntegrationMessage")).to_contain_text("Reload VS Code")
+ assert json.loads(path.read_text())["claudeCode.disableLoginPrompt"] is True
+ page.reload()
+ expect(card_button).to_have_text("Disconnect")
+ card_button.click()
+ expect(action).to_have_text("Disconnect")
+ expect(page.locator("#claudeIntegrationDescription")).to_contain_text("Remove")
+ page.keyboard.press("Escape")
+ assert json.loads(path.read_text())["claudeCode.disableLoginPrompt"] is True
+ card_button.click()
+ action.click()
+ expect(card_button).to_have_text("Connect")
+ assert json.loads(path.read_text()) == {}
+
+
+def test_manual_setup_and_revisit_read_the_file(page, admin_base_url, tmp_path):
+ path = tmp_path / "vscode" / "settings.json"
+ status = page.request.get(f"{admin_base_url}/admin/api/status").json()
+ vscode.configure(
+ path, f"http://localhost:{status['port']}/", "e2e-proxy-token", True
+ )
+ page.goto(f"{admin_base_url}/admin/integrations")
+ expect(page.locator("#openClaudeIntegration")).to_have_text("Disconnect")
+ page.get_by_role("button", name="Providers", exact=True).click()
+ path.write_text("{}")
+ page.get_by_role("button", name="Integrations", exact=True).click()
+ expect(page.locator("#openClaudeIntegration")).to_have_text("Connect")
+
+
+def test_invalid_settings_error_can_be_retried_and_does_not_break_admin(
+ page, admin_base_url, tmp_path
+):
+ path = tmp_path / "vscode" / "settings.json"
+ path.parent.mkdir()
+ path.write_text("{invalid}")
+ page.goto(f"{admin_base_url}/admin/integrations")
+ expect(page.locator("#claudeIntegrationMessage")).to_contain_text("Check the JSON")
+ expect(page.locator("#claudeIntegrationStatus")).to_have_text(
+ "Could not check settings"
+ )
+ page.get_by_role("button", name="Providers", exact=True).click()
+ expect(page.locator('[data-provider="nvidia_nim"]')).to_be_visible()
+ page.get_by_role("button", name="Integrations", exact=True).click()
+ path.write_text("{}")
+ page.locator("#openClaudeIntegration").click()
+ expect(page.locator("#openClaudeIntegration")).to_have_text("Connect")
+
+
+def test_save_pending_and_failure_stay_in_modal(page, admin_base_url):
+ page.goto(f"{admin_base_url}/admin/integrations")
+ page.locator("#openClaudeIntegration").click()
+ requests = []
+ page.route(
+ "**/admin/api/integrations/claude-vscode/connect",
+ lambda route: requests.append(route),
+ )
+ action = page.locator("#confirmClaudeIntegration")
+ action.click()
+ expect(action).to_be_disabled()
+ expect(action).to_have_text("Saving…")
+ requests[0].fulfill(status=503, json={"detail": "Could not save settings."})
+ expect(action).to_be_enabled()
+ expect(page.locator("#claudeIntegrationDialog")).to_be_visible()
+ expect(page.locator("#claudeIntegrationDialogMessage")).to_have_text(
+ "Could not save settings."
+ )
diff --git a/pyproject.toml b/pyproject.toml
index b06679dd..f99cc939 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "free-claude-code"
-version = "6.2.4"
+version = "6.2.5"
description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"
readme = "README.md"
requires-python = ">=3.14.0"
@@ -24,6 +24,7 @@ dependencies = [
"loguru>=0.7.0",
"aiohttp>=3.14.3",
"jsonschema>=4.25.0",
+ "json5>=0.15.0",
"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 0c25fe3b..aedc192d 100644
--- a/src/free_claude_code/api/admin_routes.py
+++ b/src/free_claude_code/api/admin_routes.py
@@ -1,7 +1,7 @@
"""Local admin UI routes and APIs."""
import asyncio
-from collections.abc import Mapping
+from collections.abc import Awaitable, Callable, Mapping
from pathlib import Path
import httpx
@@ -19,6 +19,7 @@ from pydantic import BaseModel, Field
from free_claude_code.application.connected_accounts import (
ConnectedAccountLoginMode,
)
+from free_claude_code.application.errors import ApplicationError
from free_claude_code.application.model_metadata import ProviderModelRefreshResult
from free_claude_code.config.admin.manifest import FIELD_BY_KEY
from free_claude_code.config.model_refs import configured_chat_model_refs
@@ -245,6 +246,46 @@ async def models(
return _model_options(services)
[email protected]("/admin/api/integrations/claude-vscode")
+async def claude_vscode_status(
+ request: Request,
+ services: ApiServices = Depends(get_services),
+):
+ require_loopback_admin(request)
+ return await _integration_response(services.admin.claude_vscode_status)
+
+
[email protected]("/admin/api/integrations/claude-vscode/connect")
+async def connect_claude_vscode(
+ request: Request,
+ services: ApiServices = Depends(get_services),
+):
+ require_loopback_admin(request)
+ return await _integration_response(services.admin.connect_claude_vscode)
+
+
[email protected]("/admin/api/integrations/claude-vscode/disconnect")
+async def disconnect_claude_vscode(
+ request: Request,
+ services: ApiServices = Depends(get_services),
+):
+ require_loopback_admin(request)
+ return await _integration_response(services.admin.disconnect_claude_vscode)
+
+
+async def _integration_response(
+ operation: Callable[[], Awaitable[JsonObject]],
+) -> JSONResponse:
+ try:
+ return _no_store(await operation())
+ except ApplicationError as exc:
+ return JSONResponse(
+ {"detail": exc.message},
+ status_code=exc.status_code,
+ headers={"Cache-Control": "no-store"},
+ )
+
+
@router.post("/admin/api/models/refresh")
async def refresh_models(
request: Request,
diff --git a/src/free_claude_code/api/admin_static/admin.js b/src/free_claude_code/api/admin_static/admin.js
index de7bb614..b8de65a4 100644
--- a/src/free_claude_code/api/admin_static/admin.js
+++ b/src/free_claude_code/api/admin_static/admin.js
@@ -175,6 +175,7 @@ function setActiveView(viewId, { scroll = false } = {}) {
}
if (activeView.id === "code") window.CodeSessions.activate(window.location.pathname);
else window.CodeSessions.deactivate();
+ if (activeView.id === "integrations") refreshClaudeIntegration();
}
function navigateToView(viewId) {
@@ -1244,7 +1245,80 @@ try {
}
const claudeIntegrationDialog = byId("claudeIntegrationDialog");
-byId("openClaudeIntegration").addEventListener("click", () => claudeIntegrationDialog.showModal());
+const claudeIntegration = { connected: null, busy: false };
+const claudeIntegrationPath = "/admin/api/integrations/claude-vscode";
+
+function integrationMessage(id, message, error = false) {
+ const element = byId(id);
+ element.textContent = message;
+ element.hidden = !message;
+ element.classList.toggle("error", error);
+}
+
+function renderClaudeIntegration() {
+ const { connected, busy } = claudeIntegration;
+ const action = connected ? "Disconnect" : "Connect";
+ byId("openClaudeIntegration").textContent = connected === null && !busy ? "Retry" : action;
+ byId("openClaudeIntegration").disabled = busy;
+ byId("confirmClaudeIntegration").textContent = busy ? "Saving…" : action;
+ byId("confirmClaudeIntegration").disabled = busy || connected === null;
+ const status = byId("claudeIntegrationStatus");
+ status.textContent = connected === null
+ ? (busy ? "Checking settings…" : "Could not check settings")
+ : (connected ? "Connected" : "Not connected");
+ status.className = `status-pill ${connected ? "ok" : "neutral"}`;
+ byId("claudeIntegrationDescription").textContent = connected
+ ? "Remove FCC's settings from VS Code. Other settings will stay."
+ : "Will set FCC's URL and token in VS Code settings, enable model discovery, and skip the login prompt.";
+}
+
+async function refreshClaudeIntegration() {
+ if (claudeIntegration.busy) return;
+ claudeIntegration.busy = true;
+ renderClaudeIntegration();
+ integrationMessage("claudeIntegrationMessage", "");
+ try {
+ const result = await api(claudeIntegrationPath);
+ claudeIntegration.connected = result.connected;
+ } catch (error) {
+ claudeIntegration.connected = null;
+ integrationMessage("claudeIntegrationMessage", error.message, true);
+ } finally {
+ claudeIntegration.busy = false;
+ renderClaudeIntegration();
+ }
+}
+
+byId("openClaudeIntegration").addEventListener("click", () => {
+ if (claudeIntegration.connected === null) {
+ refreshClaudeIntegration();
+ return;
+ }
+ integrationMessage("claudeIntegrationDialogMessage", "");
+ claudeIntegrationDialog.showModal();
+});
+byId("confirmClaudeIntegration").addEventListener("click", async () => {
+ if (claudeIntegration.busy || claudeIntegration.connected === null) return;
+ const disconnect = claudeIntegration.connected;
+ claudeIntegration.busy = true;
+ renderClaudeIntegration();
+ integrationMessage("claudeIntegrationDialogMessage", "");
+ integrationMessage("claudeIntegrationMessage", "");
+ try {
+ const result = await api(`${claudeIntegrationPath}/${disconnect ? "disconnect" : "connect"}`, { method: "POST" });
+ claudeIntegration.connected = result.connected;
+ claudeIntegrationDialog.close();
+ integrationMessage("claudeIntegrationMessage", disconnect
+ ? "Settings removed. Reload VS Code to disconnect."
+ : "Settings saved. Reload VS Code to connect.");
+ } catch (error) {
+ integrationMessage("claudeIntegrationDialogMessage", error.message, true);
+ integrationMessage("claudeIntegrationMessage", error.message, true);
+ } finally {
+ claudeIntegration.busy = false;
+ renderClaudeIntegration();
+ }
+});
byId("closeClaudeIntegration").addEventListener("click", () => claudeIntegrationDialog.close());
claudeIntegrationDialog.addEventListener("click", (event) => {
if (event.target !== claudeIntegrationDialog) return;
diff --git a/src/free_claude_code/api/admin_static/index.html b/src/free_claude_code/api/admin_static/index.html
index 15e003e0..0561001f 100644
--- a/src/free_claude_code/api/admin_static/index.html
+++ b/src/free_claude_code/api/admin_static/index.html
@@ -88,9 +88,11 @@
<div>
<h3>Claude Code in VS Code</h3>
<p>Use FCC's models in the Claude Code extension for VS Code.</p>
+ <span id="claudeIntegrationStatus" class="status-pill neutral" role="status">Checking settings…</span>
</div>
</div>
- <button id="openClaudeIntegration" class="primary-button" type="button">Connect</button>
+ <button id="openClaudeIntegration" class="primary-button" type="button" disabled>Connect</button>
+ <p id="claudeIntegrationMessage" class="message-area" role="status" hidden></p>
</article>
<dialog id="claudeIntegrationDialog" class="integration-dialog" aria-labelledby="claudeIntegrationTitle" aria-describedby="claudeIntegrationDescription">
<div class="section-heading">
@@ -98,7 +100,8 @@
<button id="closeClaudeIntegration" class="ghost-button" type="button" aria-label="Close" autofocus>×</button>
</div>
<p id="claudeIntegrationDescription">Will set FCC's URL and token in VS Code settings, enable model discovery, and skip the login prompt.</p>
- <button class="primary-button" type="button">Connect</button>
+ <button id="confirmClaudeIntegration" class="primary-button" type="button">Connect</button>
+ <p id="claudeIntegrationDialogMessage" 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 b7d13e3d..b2d76b54 100644
--- a/src/free_claude_code/api/ports.py
+++ b/src/free_claude_code/api/ports.py
@@ -28,6 +28,12 @@ class AdminRuntimePort(Protocol):
async def admin_status(self) -> JsonObject: ...
+ async def claude_vscode_status(self) -> JsonObject: ...
+
+ async def connect_claude_vscode(self) -> JsonObject: ...
+
+ async def disconnect_claude_vscode(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/claude_env.py b/src/free_claude_code/cli/claude_env.py
index 3c9e239f..c1f638cb 100644
--- a/src/free_claude_code/cli/claude_env.py
+++ b/src/free_claude_code/cli/claude_env.py
@@ -8,6 +8,19 @@ CLAUDE_CODE_AUTO_COMPACT_WINDOW = "190000"
CLAUDE_BINARY_NAME = "claude"
+def claude_proxy_values(proxy_root_url: str, auth_token: str) -> dict[str, str]:
+ """Settings shared by launched Claude sessions and the VS Code extension."""
+ return {
+ "ANTHROPIC_BASE_URL": proxy_root_url,
+ "ANTHROPIC_AUTH_TOKEN": auth_token,
+ "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY": "1",
+ "CLAUDE_CODE_AUTO_COMPACT_WINDOW": CLAUDE_CODE_AUTO_COMPACT_WINDOW,
+ "DISABLE_AUTOUPDATER": "1",
+ "DISABLE_FEEDBACK_COMMAND": "1",
+ "DISABLE_ERROR_REPORTING": "1",
+ }
+
+
def build_claude_proxy_env(
*,
proxy_root_url: str,
@@ -22,13 +35,5 @@ def build_claude_proxy_env(
proxy_root_url=proxy_root_url,
remove_prefixes=("ANTHROPIC_",),
remove_keys=("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC",),
- updates={
- "ANTHROPIC_BASE_URL": proxy_root_url,
- "ANTHROPIC_AUTH_TOKEN": auth_token,
- "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY": "1",
- "CLAUDE_CODE_AUTO_COMPACT_WINDOW": CLAUDE_CODE_AUTO_COMPACT_WINDOW,
- "DISABLE_AUTOUPDATER": "1",
- "DISABLE_FEEDBACK_COMMAND": "1",
- "DISABLE_ERROR_REPORTING": "1",
- },
+ updates=claude_proxy_values(proxy_root_url, auth_token),
)
diff --git a/src/free_claude_code/cli/vscode.py b/src/free_claude_code/cli/vscode.py
new file mode 100644
index 00000000..03ad5ae0
--- /dev/null
+++ b/src/free_claude_code/cli/vscode.py
@@ -0,0 +1,160 @@
+"""Read and update the standard global Claude Code settings for VS Code."""
+
+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.core.json_types import JsonObject
+
+_ENV = "claudeCode.environmentVariables"
+_LOGIN = "claudeCode.disableLoginPrompt"
+
+
+def settings_path() -> Path:
+ """Locate the current user's standard native VS Code settings."""
+ home = Path.home()
+ if sys.platform == "win32":
+ root = Path(os.environ.get("APPDATA") or home / "AppData/Roaming")
+ elif sys.platform == "darwin":
+ root = home / "Library/Application Support"
+ else:
+ root = Path(os.environ.get("XDG_CONFIG_HOME") or home / ".config")
+ if not root.is_absolute():
+ root = home / ".config"
+ return root / "Code/User/settings.json"
+
+
+def _read(path: Path, names: set[str]) -> tuple[JsonObject, list[JsonObject]]:
+ try:
+ source = path.read_text(encoding="utf-8-sig")
+ except FileNotFoundError:
+ return {}, []
+ document = json5.loads(source, allow_duplicate_keys=False)
+ if not isinstance(document, dict):
+ raise ValueError("Settings must be an object")
+ # Also reject non-finite JSON5 numbers before any operation or status result.
+ json.dumps(document, allow_nan=False)
+ entries = document.get(_ENV, [])
+ if not isinstance(entries, list):
+ raise ValueError("Environment settings must be an array")
+ seen: set[str] = set()
+ for entry in entries:
+ if (
+ not isinstance(entry, dict)
+ or not isinstance(entry.get("name"), str)
+ or not isinstance(entry.get("value"), str)
+ ):
+ raise ValueError("Environment entries require a name and value")
+ name = entry["name"]
+ if name in names and name in seen:
+ raise ValueError("Duplicate integration environment entry")
+ seen.add(name)
+ return cast(JsonObject, 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(
+ environment.get("ANTHROPIC_BASE_URL"), values["ANTHROPIC_BASE_URL"]
+ )
+ and environment.get("ANTHROPIC_AUTH_TOKEN") == values["ANTHROPIC_AUTH_TOKEN"]
+ and environment.get("CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY") == "1"
+ )
+
+
+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,
+ proxy_root_url: str,
+ auth_token: str,
+ connected: bool | None = None,
+) -> JsonObject:
+ """Inspect, connect, or disconnect; preserve unrelated values, not formatting."""
+ path = path.resolve()
+ values = claude_proxy_values(proxy_root_url, auth_token)
+ document, entries = _read(path, set(values))
+ if connected is not None:
+ 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)
+ if json.dumps(document, allow_nan=False) != before:
+ _write(
+ path,
+ json.dumps(document, indent=2, allow_nan=False) + "\n",
+ )
+ document, entries = _read(path, set(values))
+ return {"connected": _connected(document, entries, values)}
diff --git a/src/free_claude_code/runtime/application.py b/src/free_claude_code/runtime/application.py
index b3aff1bd..44e9414b 100644
--- a/src/free_claude_code/runtime/application.py
+++ b/src/free_claude_code/runtime/application.py
@@ -21,9 +21,13 @@ from free_claude_code.application.connected_accounts import (
ConnectedAccountPort,
ConnectedAccountStatus,
)
-from free_claude_code.application.errors import ApplicationUnavailableError
+from free_claude_code.application.errors import (
+ ApplicationUnavailableError,
+ InvalidRequestError,
+)
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.config.admin.persistence import (
PreparedAdminUpdate,
)
@@ -347,6 +351,43 @@ class ApplicationRuntime:
async def admin_values(self) -> ValueState:
return await self._configuration.admin_values()
+ async def claude_vscode_status(self) -> JsonObject:
+ return await self._claude_vscode(None)
+
+ async def connect_claude_vscode(self) -> JsonObject:
+ return await self._claude_vscode(True)
+
+ async def disconnect_claude_vscode(self) -> JsonObject:
+ return await self._claude_vscode(False)
+
+ async def _claude_vscode(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(
+ vscode.configure,
+ vscode.settings_path(),
+ local_proxy_root_url(settings),
+ settings.proxy_auth_token,
+ connected,
+ )
+ )
+ )
+ except ValueError, UnicodeError:
+ raise InvalidRequestError(
+ "Could not read VS Code settings. Check the JSON and environment entries."
+ ) from None
+ except OSError:
+ raise ApplicationUnavailableError(
+ "Could not access VS Code settings. 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_vscode_integration.py b/tests/api/test_vscode_integration.py
new file mode 100644
index 00000000..071c5aaa
--- /dev/null
+++ b/tests/api/test_vscode_integration.py
@@ -0,0 +1,101 @@
+import json
+
+import pytest
+from fastapi.testclient import TestClient
+
+from free_claude_code.cli import vscode
+from free_claude_code.config.settings import Settings
+from tests.api.support import create_test_app, runtime_for_app
+
+ROOT = "/admin/api/integrations/claude-vscode"
+
+
+def integration(tmp_path, monkeypatch):
+ path = tmp_path / "settings.json"
+ monkeypatch.setattr(vscode, "settings_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_read_actual_file_connect_and_disconnect(integration):
+ client, path, _ = integration
+ assert client.get(ROOT).json() == {"connected": False}
+ response = client.post(f"{ROOT}/connect")
+ assert response.status_code == 200
+ assert response.json() == {"connected": True}
+ assert response.headers["cache-control"] == "no-store"
+ data = json.loads(path.read_text())
+ environment = {
+ entry["name"]: entry["value"]
+ for entry in data["claudeCode.environmentVariables"]
+ }
+ assert environment["ANTHROPIC_BASE_URL"] == "http://127.0.0.1:4321"
+ assert environment["ANTHROPIC_AUTH_TOKEN"] == "integration-secret"
+ assert "integration-secret" not in response.text
+ assert client.get(ROOT).json() == {"connected": True}
+ path.write_text("{}")
+ assert client.get(ROOT).json() == {"connected": False}
+ assert client.post(f"{ROOT}/disconnect").json() == {"connected": False}
+
+
[email protected]("action", ["", "/connect", "/disconnect"])
+def test_invalid_file_returns_safe_uncached_error(integration, action):
+ client, path, _ = integration
+ source = '{"integration-secret": malformed}'
+ 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(vscode, "configure", fail)
+ response = client.post(f"{ROOT}/connect")
+ assert response.status_code == 503
+ 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_vscode.py b/tests/cli/test_vscode.py
new file mode 100644
index 00000000..2e5a2859
--- /dev/null
+++ b/tests/cli/test_vscode.py
@@ -0,0 +1,227 @@
+import json
+from pathlib import Path
+
+import pytest
+
+from free_claude_code.cli import vscode
+
+URL = "http://127.0.0.1:8000"
+TOKEN = "test-integration-token"
+ENV = "claudeCode.environmentVariables"
+LOGIN = "claudeCode.disableLoginPrompt"
+
+
+def operate(path, connected=None):
+ return vscode.configure(path, URL, TOKEN, connected)
+
+
+def test_connect_merges_jsonc_and_disconnect_preserves_unrelated_values(tmp_path):
+ path = tmp_path / "settings.json"
+ path.write_text(
+ """{
+ // User accepts losing this comment.
+ "editor.fontSize": 16,
+ "claudeCode.environmentVariables": [
+ {"name": "KEEP", "value": "yes"},
+ {"name": "ANTHROPIC_AUTH_TOKEN", "value": "old", "extra": "keep"},
+ ],
+ }""",
+ encoding="utf-8",
+ )
+ assert operate(path, True) == {"connected": True}
+ saved = json.loads(path.read_text(encoding="utf-8"))
+ assert saved["editor.fontSize"] == 16
+ entries = {entry["name"]: entry for entry in saved[ENV]}
+ assert set(entries) == {
+ "KEEP",
+ "ANTHROPIC_BASE_URL",
+ "ANTHROPIC_AUTH_TOKEN",
+ "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY",
+ "CLAUDE_CODE_AUTO_COMPACT_WINDOW",
+ "DISABLE_AUTOUPDATER",
+ "DISABLE_FEEDBACK_COMMAND",
+ "DISABLE_ERROR_REPORTING",
+ }
+ assert entries["ANTHROPIC_AUTH_TOKEN"] == {
+ "name": "ANTHROPIC_AUTH_TOKEN",
+ "value": TOKEN,
+ "extra": "keep",
+ }
+ assert entries["CLAUDE_CODE_AUTO_COMPACT_WINDOW"]["value"] == "190000"
+ assert "//" not in path.read_text().replace("http://", "")
+ assert operate(path, False) == {"connected": False}
+ assert json.loads(path.read_text()) == {
+ "editor.fontSize": 16,
+ ENV: [{"name": "KEEP", "value": "yes"}],
+ }
+
+
+def test_missing_file_and_idempotent_operations(tmp_path):
+ path = tmp_path / "Code" / "User" / "settings.json"
+ assert operate(path) == {"connected": False}
+ assert operate(path, False) == {"connected": False}
+ assert not path.parent.exists()
+ operate(path, True)
+ before = path.stat().st_mtime_ns
+ operate(path, True)
+ assert path.stat().st_mtime_ns == before
+ operate(path, False)
+ assert json.loads(path.read_text()) == {}
+ before = path.stat().st_mtime_ns
+ operate(path, False)
+ assert path.stat().st_mtime_ns == before
+
+
[email protected]("connected", [True, False])
+def test_escaped_unicode_survives_connect_and_disconnect(tmp_path, connected):
+ path = tmp_path / "settings.json"
+ data = {"keep": "\U0001f600"}
+ if not connected:
+ operate(path, True)
+ data.update(json.loads(path.read_text(encoding="utf-8")))
+ path.write_text(json.dumps(data), encoding="utf-8")
+ assert operate(path, connected) == {"connected": connected}
+ assert json.loads(path.read_text(encoding="utf-8"))["keep"] == "\U0001f600"
+
+
[email protected]("connected", [True, False])
[email protected]("target_exists", [True, False])
+def test_settings_symlink_is_preserved(tmp_path, connected, target_exists):
+ target = tmp_path / "dotfiles" / "settings.json"
+ link = tmp_path / "settings.json"
+ if target_exists:
+ target.parent.mkdir()
+ target.write_text('{"keep": true}')
+ if not connected:
+ operate(target, True)
+ try:
+ link.symlink_to(Path("dotfiles/settings.json"))
+ except OSError as exc:
+ if getattr(exc, "winerror", None) == 1314:
+ pytest.skip("Windows symlink creation requires Developer Mode or privilege")
+ raise
+ assert operate(link, connected) == {"connected": connected}
+ assert link.is_symlink()
+ if connected or target_exists:
+ assert target.is_file()
+ saved = json.loads(target.read_text())
+ assert saved.get(LOGIN, False) is connected
+ if target_exists:
+ assert saved["keep"] is True
+ else:
+ assert not target.exists()
+
+
[email protected]("url", ["http://localhost:8000/", URL, "http://[::1]:8000"])
+def test_manual_setup_only_requires_connection_fields(tmp_path, url):
+ path = tmp_path / "settings.json"
+ path.write_text(
+ json.dumps(
+ {
+ LOGIN: True,
+ ENV: [
+ {"name": "ANTHROPIC_BASE_URL", "value": url},
+ {"name": "ANTHROPIC_AUTH_TOKEN", "value": TOKEN},
+ {
+ "name": "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY",
+ "value": "1",
+ },
+ ],
+ }
+ )
+ )
+ assert operate(path) == {"connected": True}
+
+
+ "field,value",
+ [
+ ("ANTHROPIC_BASE_URL", "http://localhost:9000"),
+ ("ANTHROPIC_BASE_URL", "http://localhost:bad"),
+ ("ANTHROPIC_BASE_URL", "http://localhost:8000/?other=1"),
+ ("ANTHROPIC_BASE_URL", "http://user@localhost:8000"),
+ ("ANTHROPIC_AUTH_TOKEN", "other"),
+ ("CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY", "0"),
+ ],
+)
+def test_partial_or_different_setup_is_disconnected(tmp_path, field, value):
+ path = tmp_path / "settings.json"
+ operate(path, True)
+ data = json.loads(path.read_text())
+ next(entry for entry in data[ENV] if entry["name"] == field)["value"] = value
+ path.write_text(json.dumps(data))
+ assert operate(path) == {"connected": False}
+ operate(path, False)
+ assert json.loads(path.read_text()) == {}
+
+
+ "source",
+ [
+ "{invalid",
+ "[]",
+ '{"a": 1, "a": 2}',
+ '{"x": NaN}',
+ '{"claudeCode.environmentVariables": {}}',
+ '{"claudeCode.environmentVariables": [null]}',
+ '{"claudeCode.environmentVariables": [{"name": "X", "value": 3}]}',
+ '{"claudeCode.environmentVariables": ['
+ '{"name": "ANTHROPIC_AUTH_TOKEN", "value": "a"},'
+ '{"name": "ANTHROPIC_AUTH_TOKEN", "value": "b"}]}',
+ ],
+)
+def test_invalid_settings_are_never_overwritten(tmp_path, source):
+ path = tmp_path / "settings.json"
+ path.write_text(source)
+ for action in (None, True, False):
+ with pytest.raises(ValueError):
+ operate(path, action)
+ assert path.read_text() == source
+
+
[email protected]("readonly", [False, True])
+def test_failed_replace_preserves_original_and_removes_tempfile(
+ tmp_path, monkeypatch, readonly
+):
+ path = tmp_path / "settings.json"
+ path.write_text('{"keep": true}')
+ if readonly:
+ path.chmod(0o444)
+
+ def fail_replace(self, target):
+ raise PermissionError("test write failure")
+
+ monkeypatch.setattr(Path, "replace", fail_replace)
+ try:
+ with pytest.raises(OSError):
+ operate(path, True)
+ assert path.read_text() == '{"keep": true}'
+ assert list(tmp_path.iterdir()) == [path]
+ finally:
+ for item in tmp_path.iterdir():
+ item.chmod(0o600)
+
+
+ "platform,suffix",
+ [
+ ("win32", "AppData/Roaming/Code/User/settings.json"),
+ ("darwin", "Library/Application Support/Code/User/settings.json"),
+ ("linux", ".config/Code/User/settings.json"),
+ ],
+)
+def test_standard_global_path(tmp_path, monkeypatch, platform, suffix):
+ monkeypatch.setattr(vscode.sys, "platform", platform)
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.delenv("APPDATA", raising=False)
+ monkeypatch.delenv("XDG_CONFIG_HOME", raising=False)
+ assert vscode.settings_path() == tmp_path / suffix
+
+
+ "platform,variable", [("win32", "APPDATA"), ("linux", "XDG_CONFIG_HOME")]
+)
+def test_config_root_override(tmp_path, monkeypatch, platform, variable):
+ monkeypatch.setattr(vscode.sys, "platform", platform)
+ monkeypatch.setenv(variable, str(tmp_path))
+ assert vscode.settings_path() == tmp_path / "Code/User/settings.json"
diff --git a/uv.lock b/uv.lock
index 0f06f3a5..bd03487a 100644
--- a/uv.lock
+++ b/uv.lock
@@ -598,7 +598,7 @@ wheels = [
[[package]]
name = "free-claude-code"
-version = "6.2.4"
+version = "6.2.5"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },
@@ -609,6 +609,7 @@ dependencies = [
{ name = "google-auth", extra = ["requests"] },
{ name = "httpx", extra = ["socks"] },
{ name = "httpx2", extra = ["socks"] },
+ { name = "json5" },
{ name = "jsonschema" },
{ name = "loguru" },
{ name = "markdown-it-py" },
@@ -660,6 +661,7 @@ requires-dist = [
{ name = "grpcio-tools", marker = "extra == 'voice'", specifier = ">=1.81.1" },
{ name = "httpx", extras = ["socks"], specifier = ">=0.28.1" },
{ name = "httpx2", extras = ["socks"], specifier = ">=2.7.0,<3" },
+ { name = "json5", specifier = ">=0.15.0" },
{ name = "jsonschema", specifier = ">=4.25.0" },
{ name = "librosa", marker = "extra == 'voice-local'", specifier = ">=1.0.0" },
{ name = "loguru", specifier = ">=0.7.0" },
@@ -1088,6 +1090,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/7b/91/984aca2ec129e2757d1e4e3c81c3fcda9d0f85b74670a094cc443d9ee949/joblib-1.5.3-py3-none-any.whl", hash = "sha256:5fc3c5039fc5ca8c0276333a188bbd59d6b7ab37fe6632daa76bc7f9ec18e713", size = 309071, upload-time = "2025-12-15T08:41:44.973Z" },
]
+[[package]]
+name = "json5"
+version = "0.15.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/e4/7d/05c46a96a78147ae3bf99c2f4169ce144a70220b8d6fcd56f6ec368b8ce9/json5-0.15.0.tar.gz", hash = "sha256:7424d1f1eb1d56da6e3d70643f53619862b4ce81440bdb8ecfd6f875e5ba4a71", size = 53278, upload-time = "2026-06-19T20:08:27.716Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/eb/be/59527c99478aade6bb33a68d72e6e18dd4e6ff6eacfc7d01bdb15bc76912/json5-0.15.0-py3-none-any.whl", hash = "sha256:56636a30c0e8a4665fe2179c0212f32eae3796dea89ea6f649b9436ecdb39618", size = 36570, upload-time = "2026-06-19T20:08:26.748Z" },
+]
+
[[package]]
name = "jsonschema"
version = "4.26.0"