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
minor: Add native VS Code Chat integration (#1915)
Ali Khokhard645e2e63a8b
diff --git a/README.md b/README.mdindex 9425d445..1c48940b 100644--- a/README.md+++ b/README.md@@ -26,7 +26,7 @@## What You Get- **55 ToS-friendly providers. 1.3B+ free tokens every month.** Use free, paid, subscription, and local models from one searchable UI without putting your account at risk. FCC follows provider terms and removes integrations if they stop being allowed.-- **10 coding agents. One model catalog.** Run [Claude Code](https://code.claude.com/docs/en/overview), [Codex](https://github.com/openai/codex), [Pi](https://github.com/earendil-works/pi), [OpenCode](https://github.com/anomalyco/opencode), [Cline](https://github.com/cline/cline), [Hermes](https://github.com/NousResearch/hermes-agent), [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness), [Grok Build](https://github.com/xai-org/grok-build), [Muse Code](https://research.meta.ai/blog/introducing-muse-code-and-muse-spark-1-2/), or [Aider](https://aider.chat/) with your FCC models.+- **11 coding agents. One model catalog.** Run [Claude Code](https://code.claude.com/docs/en/overview), [Codex](https://github.com/openai/codex), [Pi](https://github.com/earendil-works/pi), [OpenCode](https://github.com/anomalyco/opencode), [Cline](https://github.com/cline/cline), [Hermes](https://github.com/NousResearch/hermes-agent), [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness), [Grok Build](https://github.com/xai-org/grok-build), [Muse Code](https://research.meta.ai/blog/introducing-muse-code-and-muse-spark-1-2/), [Aider](https://aider.chat/), or [VS Code Chat](https://code.visualstudio.com/) with your FCC models.- **Keep coding through provider outages.** After retries are exhausted, FCC automatically tries your next configured model without making you restart the turn. This works across every client.- **Up to 90% fewer terminal-output tokens.** Optional [RTK](https://github.com/rtk-ai/rtk) filters common command output, while five FCC optimizations handle quota probes, command-prefix detection, titles, suggestions, and filepaths without calling a provider.- **Native Code sessions in your browser.** Choose a folder and run Codex in the browser with real-time and background support. Freely switch providers/models in the same session. Support for switching harnesses in the same session coming soon!@@ -359,6 +359,7 @@ For editor and app integrations, install the client, start FCC, then open**Admin UI → Integrations** and click **Connect** on its card.- **Claude Code in VS Code**: Install the [Claude Code extension](https://marketplace.visualstudio.com/items?itemName=anthropic.claude-code).+- **VS Code Chat**: Install the latest [VS Code](https://code.visualstudio.com/), connect, and select an FCC model in its built-in Chat model picker.- **Claude Desktop**: Install [Claude Desktop](https://claude.ai/download). Fully quit it before connecting or disconnecting, then reopen it. Disconnect returns to normal Claude sign-in.- **Codex in VS Code and App**: Install the [Codex extension](https://marketplace.visualstudio.com/items?itemName=openai.chatgpt) or Codex App.- **Claude Code in JetBrains ACP**: Install Claude Agent in JetBrains AI Assistant and start it once, then click **Connect** in FCC. Reopen the IDE, select **Claude Code (FCC)**, and start a new chat. After JetBrains updates the agent, restart FCC before starting a new chat. Requires a local IDE in its standard installation locations.diff --git a/e2e/conftest.py b/e2e/conftest.pyindex 2368f22f..76903e3c 100644--- a/e2e/conftest.py+++ b/e2e/conftest.py@@ -1,7 +1,6 @@"""Isolated browser-test composition for the local Admin UI."""import asyncio-import faulthandlerimport socketimport sysimport threading@@ -14,6 +13,7 @@ import uvicornfrom playwright.sync_api import Pagefrom e2e.code_support import CodeControl+from e2e.server_shutdown import join_serverfrom free_claude_code.api.app import create_appfrom free_claude_code.api.ports import ApiServicesfrom free_claude_code.application.model_metadata import ProviderModelInfo@@ -33,6 +33,7 @@ from free_claude_code.harnesses import (claude_integration,codex_integration,jetbrains_acp_integration,+ vscode_chat_integration,)from free_claude_code.providers.base import BaseProvider, ProviderConfigfrom free_claude_code.providers.runtime import ProviderRuntime@@ -185,6 +186,11 @@ def admin_base_url(monkeypatch.setattr(codex_integration, "config_path", lambda: tmp_path / ".codex" / "config.toml")+ monkeypatch.setattr(+ vscode_chat_integration,+ "config_path",+ lambda: tmp_path / "vscode/chatLanguageModels.json",+ )monkeypatch.setattr(claude_integration, "claude_state_path", lambda: tmp_path / ".claude.json")@@ -346,12 +352,9 @@ def admin_base_url(yield f"http://127.0.0.1:{port}"finally:server.should_exit = True- thread.join(timeout=5.0)+ join_server(thread, code_control, request)listener.close()clear_settings_cache()- if thread.is_alive():- faulthandler.dump_traceback(file=sys.stderr)- pytest.fail("Admin browser-test server did not stop")@pytest.fixture(autouse=True)diff --git a/e2e/server_shutdown.py b/e2e/server_shutdown.pynew file mode 100644index 00000000..cf131786--- /dev/null+++ b/e2e/server_shutdown.py@@ -0,0 +1,90 @@+"""Bounded cleanup for the browser fixture's server thread."""++import asyncio+import faulthandler+import inspect+import sys+import threading+import time+from concurrent.futures import Future++import pytest++from e2e.code_support import CodeControl+++def _task_snapshot(control: CodeControl) -> str:+ jobs = control.service._jobs+ lines = [f"Code jobs: {sum(not job.done() for job in jobs)}"]+ for task in asyncio.all_tasks():+ lines.append(f"Task {task.get_name()} (Code job: {task in jobs}):")+ current = task.get_coro()+ while inspect.iscoroutine(current) or inspect.isgenerator(current):+ frame = (+ current.cr_frame if inspect.iscoroutine(current) else current.gi_frame+ )+ if frame is not None:+ lines.append(+ f" {frame.f_code.co_filename}:{frame.f_lineno} in {frame.f_code.co_name}"+ )+ current = (+ current.cr_await+ if inspect.iscoroutine(current)+ else current.gi_yieldfrom+ )+ return "\n".join(lines)+++def join_server(+ thread: threading.Thread,+ control: CodeControl,+ request: pytest.FixtureRequest,+ *,+ diagnostic_after: float = 5,+ timeout: float = 30,+) -> None:+ # Native interruption can itself take five seconds before durable cleanup.+ # Diagnose at that point, but give the entire fixture shutdown its own budget.+ started = time.monotonic()+ deadline = started + timeout+ thread.join(min(diagnostic_after, timeout))+ if not thread.is_alive():+ return++ print(+ f"Server shutdown still pending after {time.monotonic() - started:.2f}s: "+ f"{request.node.nodeid}",+ file=sys.stderr,+ )+ faulthandler.dump_traceback(file=sys.stderr)+ snapshot: Future[str] = Future()++ def capture() -> None:+ try:+ snapshot.set_result(_task_snapshot(control))+ except Exception as error:+ snapshot.set_result(f"Server task snapshot failed: {type(error).__name__}")++ if control.loop is None:+ snapshot.set_result("Server loop unavailable for task snapshot")+ else:+ try:+ control.loop.call_soon_threadsafe(capture)+ except RuntimeError:+ snapshot.set_result("Server loop closed before task snapshot")++ thread.join(max(0, deadline - time.monotonic()))+ print(+ snapshot.result()+ if snapshot.done()+ else "Server loop did not provide a task snapshot",+ file=sys.stderr,+ )+ if thread.is_alive():+ reason = (+ f"Admin browser-test server did not stop within {timeout:g}s: "+ f"{request.node.nodeid}"+ )+ request.session.shouldstop = reason+ faulthandler.dump_traceback(file=sys.stderr)+ pytest.fail(reason)diff --git a/e2e/test_admin_integrations.py b/e2e/test_admin_integrations.pyindex a717468f..a5081668 100644--- a/e2e/test_admin_integrations.py+++ b/e2e/test_admin_integrations.py@@ -25,7 +25,7 @@ def test_connection_check_uses_disabled_loading_button(def hold_check(route):pending.append(route)- page.evaluate("window.integrationCheckIntercepted = true")+ page.evaluate("window.integrationChecks = (window.integrationChecks || 0) + 1")page.route(f"**/admin/api/integrations/{integration}", hold_check)page.goto(f"{admin_base_url}/admin/integrations")@@ -33,7 +33,6 @@ def test_connection_check_uses_disabled_loading_button(for visit in range(2):if visit:page.get_by_role("button", name="Providers", exact=True).click()- page.evaluate("window.integrationCheckIntercepted = false")page.get_by_role("button", name="Integrations", exact=True).click()expect(button).to_be_disabled()expect(button).to_have_text("Loading…")@@ -46,9 +45,17 @@ def test_connection_check_uses_disabled_loading_button(== "integration-spinner")expect(page.locator("#view-integrations .status-pill")).to_have_count(0)- page.wait_for_function("window.integrationCheckIntercepted === true")+ page.wait_for_function(+ "count => window.integrationChecks >= count", arg=visit + 1+ )assert len(pending) == 1- pending.pop().fulfill(json={"connected": connected, "paths": None})+ pending.pop().fulfill(+ json={+ "connected": connected,+ "paths": None,+ "update": {"state": "ready", "changed": False, "message": None},+ }+ )expect(button).to_be_enabled()expect(button).to_have_text("Disconnect" if connected else "Connect")expect(button).to_have_attribute("aria-busy", "false")@@ -63,13 +70,10 @@ def test_codex_connect_disconnect_and_modal_paths(expect(page.locator("#openClaudeIntegration")).to_be_enabled()expect(page.locator("#messageArea")).to_have_text("")cards = page.locator("#view-integrations > article")- expect(cards).to_have_count(4)+ expect(cards.first).to_be_visible()expect(page.locator("#claudeIntegrationStatus")).to_have_count(0)expect(page.locator("#openCodexIntegration")).to_be_enabled()expect(page.locator("#codexIntegrationStatus")).to_have_count(0)- expect(cards.nth(1)).to_contain_text(- "Use FCC's models in the Codex VS Code extension and desktop app."- )bounds = [card.bounding_box() for card in cards.all()]if width >= 1200:descriptions = [@@ -124,8 +128,7 @@ def test_codex_connect_disconnect_and_modal_paths(expect(opener).to_have_css("color", "rgb(239, 68, 68)")if width >= 1200:buttons = [- button.bounding_box()- for button in page.locator(".integration-card > button").all()+ card.get_by_role("button").first.bounding_box() for card in cards.all()]for _, row in groupby(range(len(bounds)), key=lambda index: bounds[index]["y"]):assert len({buttons[index]["y"] for index in row}) == 1diff --git a/e2e/test_admin_providers.py b/e2e/test_admin_providers.pyindex 76197b67..009581ea 100644--- a/e2e/test_admin_providers.py+++ b/e2e/test_admin_providers.py@@ -173,18 +173,19 @@ def test_delayed_startup_status_does_not_replace_a_manual_provider_check(route.continue_()else:startup.append(route)+ page.evaluate("window.startupRequests = (window.startupRequests || 0) + 1")++ def hold_manual(route: Route) -> None:+ manual.append(route)+ page.evaluate("window.manualRequests = (window.manualRequests || 0) + 1")page.route("**/admin/api/status", hold_first_status)- page.route(- "**/admin/api/providers/open_router/test", lambda route: manual.append(route)- )- page.expose_function("startupRequestIntercepted", lambda: bool(startup))- page.expose_function("manualRequestIntercepted", lambda: bool(manual))+ page.route("**/admin/api/providers/open_router/test", hold_manual)page.evaluate("void refreshStartup()")- page.wait_for_function("window.startupRequestIntercepted()")+ page.wait_for_function("window.startupRequests >= 1")dialog = open_provider(page, "open_router")dialog.get_by_role("button", name="Refresh models", exact=True).click()- page.wait_for_function("window.manualRequestIntercepted()")+ page.wait_for_function("window.manualRequests >= 1")expected = "Checking..."if manual_result != "pending":manual.pop().fulfill(diff --git a/e2e/test_admin_vscode_chat.py b/e2e/test_admin_vscode_chat.pynew file mode 100644index 00000000..6275886b--- /dev/null+++ b/e2e/test_admin_vscode_chat.py@@ -0,0 +1,92 @@+import json++import pytest+from playwright.sync_api import expect++from free_claude_code.harnesses import vscode_chat_integration as vscode+++def test_connect_and_disconnect_native_chat(page, admin_base_url):+ path = vscode.config_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ other = {"vendor": "customendpoint", "name": "Other", "models": []}+ path.write_text(json.dumps([other]))+ page.goto(f"{admin_base_url}/admin/integrations")+ button = page.locator("#openVSCodeChatIntegration")+ dialog = page.locator("#vscodeChatIntegrationDialog")+ expect(button).to_have_text("Connect")+ button.click()+ expect(dialog).to_be_visible()+ expect(dialog.locator("code")).to_have_text(str(path.resolve()))+ page.keyboard.press("Escape")+ expect(dialog).not_to_be_visible()+ button.click()+ dialog.get_by_role("button", name="Close", exact=True).click()+ expect(dialog).not_to_be_visible()+ button.click()+ dialog.get_by_role("button", name="Connect", exact=True).click()+ expect(button).to_have_text("Disconnect")+ expect(button).to_have_class("danger-button")+ group = json.loads(path.read_text())[1]+ assert group["apiType"] == "messages"+ assert group["models"]+ assert all(m["url"].endswith("/v1/messages") for m in group["models"])+ page.reload()+ expect(button).to_have_text("Disconnect")+ expect(page.locator("#vscodeChatIntegrationMessage")).not_to_be_visible()+ button.click()+ dialog.get_by_role("button", name="Disconnect", exact=True).click()+ expect(button).to_have_text("Connect")+ assert json.loads(path.read_text()) == [other]++[email protected]("status_read_failed", [False, True])+def test_failed_update_has_actionable_retry(page, admin_base_url, status_read_failed):+ progress: dict[str, str | bool | None] = {+ "state": "failed",+ "changed": False,+ "message": "Could not update settings.",+ }+ retries = []++ def startup(route):+ response = route.fetch()+ payload = response.json()+ payload["startup"]["integrations"]["vscode-chat"] = dict(progress)+ route.fulfill(response=response, json=payload)++ def status(route):+ if status_read_failed and progress["state"] == "failed":+ route.fulfill(status=503, json={"detail": "Could not read settings."})+ else:+ route.fulfill(+ json={"connected": True, "paths": None, "update": dict(progress)}+ )++ def retry(route):+ retries.append(route.request.method)+ progress.update(state="ready", message=None)+ route.fulfill(json={"update": dict(progress)})++ try:+ page.route("**/admin/api/status", startup)+ page.route("**/admin/api/integrations/vscode-chat", status)+ page.route("**/admin/api/integrations/vscode-chat/refresh", retry)+ page.goto(f"{admin_base_url}/admin/integrations")+ main = page.locator("#openVSCodeChatIntegration")+ secondary = page.locator("#retryVSCodeChatIntegration")+ if status_read_failed:+ expect(main).to_have_text("Retry")+ action = main+ else:+ expect(main).to_have_text("Disconnect")+ expect(secondary).to_be_visible()+ action = secondary+ with page.expect_response("**/admin/api/integrations/vscode-chat/refresh"):+ action.click()+ assert retries == ["POST"]+ expect(main).to_have_text("Disconnect")+ expect(secondary).to_be_hidden()+ expect(page.locator("#vscodeChatIntegrationMessage")).to_be_hidden()+ finally:+ page.unroute_all(behavior="wait")diff --git a/e2e/test_integration_notices.py b/e2e/test_integration_notices.pyindex 9525c6dc..eb83f338 100644--- a/e2e/test_integration_notices.py+++ b/e2e/test_integration_notices.py@@ -4,6 +4,7 @@ from playwright.sync_api import expect@pytest.fixture(params=[+ ("vscode-chat", "openVSCodeChatIntegration", "vscodeChatIntegrationMessage"),("claude-vscode", "openClaudeIntegration", "claudeIntegrationMessage"),("codex", "openCodexIntegration", "codexIntegrationMessage"),("jetbrains-acp", "openJetBrainsIntegration", "jetBrainsIntegrationMessage"),@@ -83,6 +84,68 @@ def test_notices_require_a_live_changed_completion(page, notice):expect(message).not_to_have_text("Update failed")+def test_settled_poll_after_mutation_preserves_next_action(page, notice):+ integration, button, message, observe = notice+ observe("ready")+ page.wait_for_function("!state.startupRequest && state.startupTimer === null")+ unexpected_reads = []++ def fail_status(route):+ unexpected_reads.append(route.request)+ route.fulfill(status=503, json={"detail": "Status unavailable"})++ endpoint = f"**/admin/api/integrations/{integration}"+ page.route(endpoint, fail_status)+ dialog = page.get_by_role("dialog")+ for action, connected in [("Disconnect", False), ("Connect", True)]:+ page.route(+ f"{endpoint}/{action.lower()}",+ lambda route: route.fulfill(+ json={+ "connected": route.request.url.endswith("/connect"),+ "disconnect_pending": False,+ "paths": None,+ }+ ),+ )+ button.click()+ dialog.get_by_role("button", name=action, exact=True).click()+ expect(dialog).not_to_be_visible()+ next_action = "Disconnect" if connected else "Connect"+ expect(button).to_have_text(next_action)+ button.click()+ observe("ready")+ expect(+ dialog.get_by_role("button", name=next_action, exact=True)+ ).to_be_enabled()+ assert not unexpected_reads+ dialog.get_by_role("button", name="Close", exact=True).click()+ page.unroute(endpoint, fail_status)+ observe("failed")+ expect(message).to_have_text("Update failed")+ observe("ready")+ expect(message).to_be_hidden()+++def test_missed_starting_state_still_reconciles_failure_and_recovery(page, notice):+ integration, button, message, observe = notice+ expect(message).to_be_hidden()+ observe("failed")+ expect(message).to_have_text("Update failed")+ expect(button).to_be_enabled()+ if integration == "vscode-chat":+ expect(button).to_have_text("Disconnect")+ expect(page.locator("#retryVSCodeChatIntegration")).to_be_visible()+ observe("ready", changed=True)+ expect(message).to_be_hidden()+ expect(button).to_be_enabled()+ if integration == "vscode-chat":+ expect(page.locator("#retryVSCodeChatIntegration")).to_be_hidden()+ # A repeated settled snapshot must not replay a reload notification.+ observe("ready", changed=True)+ expect(message).to_be_hidden()++@pytest.mark.parametrize("revisit_while_busy", [False, True])def test_busy_status_recovery_preserves_notice_without_replaying_it(page, notice, revisit_while_busy@@ -149,3 +212,31 @@ def test_new_server_and_off_page_completions_stay_quiet(page, notice):page.get_by_role("button", name="Integrations", exact=True).click()expect(button).to_be_enabled()expect(message).to_be_hidden()+++def test_missed_transition_during_status_read_is_reconciled(page, notice):+ integration, button, message, observe = notice+ pending = []++ def hold_status(route):+ pending.append(route)++ pattern = f"**/admin/api/integrations/{integration}"+ page.route(pattern, hold_status)+ page.get_by_role("button", name="Providers", exact=True).click()+ with page.expect_request(pattern):+ page.get_by_role("button", name="Integrations", exact=True).click()+ expect(button).to_be_disabled()+ page.wait_for_function("!state.startupRequest && state.startupTimer === null")+ observe("failed")+ assert len(pending) == 1+ page.unroute(pattern, hold_status)+ pending[0].fulfill(+ json={+ "connected": True,+ "paths": None,+ "update": {"state": "ready", "changed": False, "message": None},+ }+ )+ expect(message).to_have_text("Update failed")+ expect(button).to_be_enabled()diff --git a/src/free_claude_code/api/admin_routes.py b/src/free_claude_code/api/admin_routes.pyindex 698a4f0c..59c58de9 100644--- a/src/free_claude_code/api/admin_routes.py+++ b/src/free_claude_code/api/admin_routes.py@@ -273,6 +273,42 @@ async def claude_vscode_status(return await _integration_response(services.admin.claude_vscode_status)[email protected]("/admin/api/integrations/vscode-chat")+async def vscode_chat_status(+ request: Request,+ services: ApiServices = Depends(get_services),+):+ require_loopback_admin(request)+ return await _integration_response(services.admin.vscode_chat_status)++[email protected]("/admin/api/integrations/vscode-chat/connect")+async def connect_vscode_chat(+ request: Request,+ services: ApiServices = Depends(get_services),+):+ require_loopback_admin(request)+ return await _integration_response(services.admin.connect_vscode_chat)++[email protected]("/admin/api/integrations/vscode-chat/disconnect")+async def disconnect_vscode_chat(+ request: Request,+ services: ApiServices = Depends(get_services),+):+ require_loopback_admin(request)+ return await _integration_response(services.admin.disconnect_vscode_chat)++[email protected]("/admin/api/integrations/vscode-chat/refresh")+async def refresh_vscode_chat(+ request: Request,+ services: ApiServices = Depends(get_services),+):+ require_loopback_admin(request)+ return await _integration_response(services.admin.refresh_vscode_chat)++@router.post("/admin/api/integrations/claude-vscode/connect")async def connect_claude_vscode(request: Request,diff --git a/src/free_claude_code/api/admin_static/admin.css b/src/free_claude_code/api/admin_static/admin.cssindex 661cad28..a0b5852f 100644--- a/src/free_claude_code/api/admin_static/admin.css+++ b/src/free_claude_code/api/admin_static/admin.css@@ -266,19 +266,27 @@ textarea:focus-visible,align-items: flex-start;margin-bottom: 0;}-.integration-card > button {+.integration-actions {+ display: flex;+ gap: 8px;+ margin-top: auto;+}+.integration-card > button,+.integration-actions > button {display: inline-flex;align-items: center;gap: 8px;margin-top: auto;}.integration-card > button,+.integration-actions > button,.provider-card > .provider-actions > button {min-height: 38px;padding: 6px 14px;font-size: 13px;}.integration-card > button[aria-busy="true"]::before,+.integration-actions > button[aria-busy="true"]::before,button.startup-busy::before,.startup-spinner::before {content: "";@@ -293,7 +301,7 @@ button.startup-busy::before,to { transform: rotate(360deg); }}@media (prefers-reduced-motion: reduce) {- .integration-card > button[aria-busy="true"]::before { animation: none; }+ .integration-card button[aria-busy="true"]::before { animation: none; }}.integration-card h3 { min-height: 2lh; }.integration-dialog {diff --git a/src/free_claude_code/api/admin_static/admin.js b/src/free_claude_code/api/admin_static/admin.jsindex 4eeab646..e7281f08 100644--- a/src/free_claude_code/api/admin_static/admin.js+++ b/src/free_claude_code/api/admin_static/admin.js@@ -141,6 +141,7 @@ function renderStartup() {renderProviderCheckResult(provider.provider_id);});renderClaudeIntegration();+ renderVSCodeChatIntegration();renderJetBrainsIntegration();renderCodexIntegration();renderClaudeDesktopIntegration();@@ -291,6 +292,7 @@ function setActiveView(viewId, { scroll = false } = {}) {else window.CodeSessions.deactivate();if (activeView.id === "integrations") {refreshClaudeIntegration();+ refreshVSCodeChatIntegration();refreshJetBrainsIntegration();refreshCodexIntegration();refreshClaudeDesktopIntegration();@@ -1606,15 +1608,22 @@ function integrationUpdating(integration, id) {function refreshIntegrationUpdates(previous, current) {if (state.activeView !== "integrations") return;for (const [id, integration, refresh, messageId, message] of [+ ["vscode-chat", vscodeChatIntegration, refreshVSCodeChatIntegration, "vscodeChatIntegrationMessage", "Models updated in VS Code."],["claude-vscode", claudeIntegration, refreshClaudeIntegration, "claudeIntegrationMessage", "Settings updated. Reload VS Code."],["jetbrains-acp", jetBrainsIntegration, refreshJetBrainsIntegration, "jetBrainsIntegrationMessage", "Settings updated. Reopen JetBrains and start a new chat."],["codex", codexIntegration, refreshCodexIntegration, "codexIntegrationMessage", "Settings updated. Restart Codex."],["claude-desktop", claudeDesktopIntegration, refreshClaudeDesktopIntegration, "claudeDesktopIntegrationMessage", "Settings updated. Reopen Claude Desktop."],]) {const phase = current?.[id]?.state;+ // Successful actions clear update metadata, not the last observed state.+ const observedPhase = integration.update?.state ?? previous?.[id]?.state;+ // Polling can miss a short update. Reconcile state independently of notices.if (phase && phase !== "starting" && (- previous?.[id]?.state === "starting" || integration.update?.state === "starting"- )) void refresh(false, { background: true });+ previous?.[id]?.state === "starting" || observedPhase !== phase+ )) {+ if (integration.busy) state.startupAgain = true;+ else void refresh(false, { background: true });+ }if (previous?.[id]?.state === "starting" && phase === "ready" && current[id].changed === true) {integrationMessage(messageId, message);}@@ -1713,6 +1722,105 @@ claudeIntegrationDialog.addEventListener("click", (event) => {}});+const vscodeChatIntegrationDialog = byId("vscodeChatIntegrationDialog");+const vscodeChatIntegration = { connected: null, busy: false, paths: null, update: null };+const vscodeChatIntegrationPath = "/admin/api/integrations/vscode-chat";++function renderVSCodeChatIntegration() {+ const { connected, paths } = vscodeChatIntegration;+ const busy = vscodeChatIntegration.busy || integrationUpdating(vscodeChatIntegration, "vscode-chat");+ byId("retryVSCodeChatIntegration").hidden = connected === null || vscodeChatIntegration.update?.state !== "failed";+ byId("retryVSCodeChatIntegration").disabled = busy;+ const action = connected ? "Disconnect" : "Connect";+ byId("openVSCodeChatIntegration").textContent = busy ? "Loading…" : connected === null ? "Retry" : action;+ byId("openVSCodeChatIntegration").disabled = busy;+ byId("openVSCodeChatIntegration").setAttribute("aria-busy", String(busy));+ byId("confirmVSCodeChatIntegration").textContent = busy ? "Saving…" : action;+ byId("confirmVSCodeChatIntegration").disabled = busy || connected === null;+ byId("openVSCodeChatIntegration").className = connected && !busy ? "danger-button" : "primary-button";+ byId("confirmVSCodeChatIntegration").className = connected ? "danger-button" : "primary-button";+ byId("vscodeChatIntegrationDescription").textContent = connected+ ? "Remove FCC's model group from VS Code Chat."+ : "Add FCC models to VS Code Chat. Your selected models stay unchanged.";+ const files = byId("vscodeChatIntegrationFiles");+ files.replaceChildren();+ if (paths) {+ const targets = [paths.vscode_models];+ targets.forEach((path) => {+ const item = document.createElement("li");+ const code = document.createElement("code");+ code.textContent = path;+ item.appendChild(code);+ files.appendChild(item);+ });+ }+}++async function refreshVSCodeChatIntegration(retry = false, { background = false } = {}) {+ if (!background) integrationMessage("vscodeChatIntegrationMessage", "");+ if (vscodeChatIntegration.busy) return;+ vscodeChatIntegration.busy = true;+ renderVSCodeChatIntegration();+ try {+ if (retry) await api(`${vscodeChatIntegrationPath}/refresh`, { method: "POST" });+ const result = await api(vscodeChatIntegrationPath);+ vscodeChatIntegration.connected = result.connected;+ vscodeChatIntegration.paths = result.paths;+ vscodeChatIntegration.update = result.update;+ if (result.update?.state === "failed") integrationMessage("vscodeChatIntegrationMessage", result.update.message, true);+ else if (byId("vscodeChatIntegrationMessage").classList.contains("error")) integrationMessage("vscodeChatIntegrationMessage", "");+ } catch (error) {+ vscodeChatIntegration.connected = null;+ vscodeChatIntegration.update = null;+ integrationMessage("vscodeChatIntegrationMessage", error.message, true);+ } finally {+ vscodeChatIntegration.busy = false;+ renderVSCodeChatIntegration();+ if (vscodeChatIntegration.update?.state === "starting") void refreshStartup();+ }+}++byId("openVSCodeChatIntegration").addEventListener("click", () => {+ if (vscodeChatIntegration.connected === null) {+ refreshVSCodeChatIntegration(true);+ return;+ }+ integrationMessage("vscodeChatIntegrationDialogMessage", "");+ vscodeChatIntegrationDialog.showModal();+});+byId("retryVSCodeChatIntegration").addEventListener("click", () => refreshVSCodeChatIntegration(true));+byId("confirmVSCodeChatIntegration").addEventListener("click", async () => {+ if (byId("confirmVSCodeChatIntegration").disabled) return;+ const disconnect = vscodeChatIntegration.connected;+ vscodeChatIntegration.busy = true;+ renderVSCodeChatIntegration();+ integrationMessage("vscodeChatIntegrationDialogMessage", "");+ integrationMessage("vscodeChatIntegrationMessage", "");+ try {+ const result = await api(`${vscodeChatIntegrationPath}/${disconnect ? "disconnect" : "connect"}`, { method: "POST" });+ vscodeChatIntegration.connected = result.connected;+ vscodeChatIntegration.update = null;+ vscodeChatIntegrationDialog.close();+ integrationMessage("vscodeChatIntegrationMessage", disconnect+ ? "Settings removed. Reload VS Code to disconnect."+ : "Models saved. Select an FCC model in VS Code Chat. Reload VS Code if needed.");+ } catch (error) {+ integrationMessage("vscodeChatIntegrationDialogMessage", error.message, true);+ integrationMessage("vscodeChatIntegrationMessage", error.message, true);+ } finally {+ vscodeChatIntegration.busy = false;+ renderVSCodeChatIntegration();+ }+});+byId("closeVSCodeChatIntegration").addEventListener("click", () => vscodeChatIntegrationDialog.close());+vscodeChatIntegrationDialog.addEventListener("click", (event) => {+ if (event.target !== vscodeChatIntegrationDialog) return;+ const bounds = vscodeChatIntegrationDialog.getBoundingClientRect();+ if (event.clientX < bounds.left || event.clientX > bounds.right || event.clientY < bounds.top || event.clientY > bounds.bottom) {+ vscodeChatIntegrationDialog.close();+ }+});+const codexIntegrationDialog = byId("codexIntegrationDialog");const codexIntegration = { connected: null, busy: false, paths: null, update: null };const codexIntegrationPath = "/admin/api/integrations/codex";diff --git a/src/free_claude_code/api/admin_static/index.html b/src/free_claude_code/api/admin_static/index.htmlindex 21bf4e76..1cf05d8d 100644--- a/src/free_claude_code/api/admin_static/index.html+++ b/src/free_claude_code/api/admin_static/index.html@@ -65,6 +65,32 @@</section><section id="view-integrations" class="admin-view provider-grid" data-view="integrations" hidden>+ <article class="provider-strip integration-card">+ <div class="section-heading">+ <div>+ <h3>VS Code Chat</h3>+ <p>Use FCC models in VS Code's built-in chat and agent mode.</p>+ </div>+ </div>+ <p id="vscodeChatIntegrationMessage" class="message-area" role="status" hidden></p>+ <div class="integration-actions">+ <button id="openVSCodeChatIntegration" class="primary-button" type="button" aria-busy="true" disabled>Loading…</button>+ <button id="retryVSCodeChatIntegration" class="secondary-button" type="button" hidden>Retry</button>+ </div>+ </article>+ <dialog id="vscodeChatIntegrationDialog" class="integration-dialog" aria-labelledby="vscodeChatIntegrationTitle" aria-describedby="vscodeChatIntegrationDescription">+ <div class="section-heading">+ <h3 id="vscodeChatIntegrationTitle">VS Code Chat</h3>+ <button id="closeVSCodeChatIntegration" class="ghost-button" type="button" aria-label="Close" autofocus>×</button>+ </div>+ <p id="vscodeChatIntegrationDescription">Add FCC models to VS Code Chat. Your selected models stay unchanged.</p>+ <div class="integration-files">+ <h4>Files to modify</h4>+ <ul id="vscodeChatIntegrationFiles"></ul>+ </div>+ <button id="confirmVSCodeChatIntegration" class="primary-button" type="button">Connect</button>+ <p id="vscodeChatIntegrationDialogMessage" class="message-area error" role="alert" hidden></p>+ </dialog><article class="provider-strip integration-card"><div class="section-heading"><div>diff --git a/src/free_claude_code/api/model_catalog.py b/src/free_claude_code/api/model_catalog.pyindex b873a19e..35556d4a 100644--- a/src/free_claude_code/api/model_catalog.py+++ b/src/free_claude_code/api/model_catalog.py@@ -6,7 +6,11 @@ from typing import Literalfrom pydantic import BaseModel, Field-from free_claude_code.application.model_catalog import ModelCatalog, read_model_catalog+from free_claude_code.application.model_catalog import (+ ModelCatalog,+ context_window_for_client,+ read_model_catalog,+)from free_claude_code.application.ports import ModelCatalogPortfrom free_claude_code.config.settings import Settingsfrom free_claude_code.core.gateway_model_ids import (@@ -75,6 +79,9 @@ class ModelResponse(BaseModel):context_window_tokens: int | None = Field(default=None, serialization_alias="contextWindow")+ context_window_source: Literal["provider", "default"] | None = Field(+ default=None, serialization_alias="contextWindowSource"+ )max_output_tokens: int | None = Field(default=None, serialization_alias="maxCompletionTokens")@@ -239,7 +246,11 @@ def _build_direct_models_response(max_retries=0 if view is ModelCatalogView.RESPONSES else None,supports_reasoning=model.supports_reasoning,input_modalities=_serialize_input_modalities(model.input_modalities),- context_window_tokens=model.context_window_tokens,+ context_window_tokens=context_window_for_client(model),+ context_window_source="provider"+ if model.context_window_tokens is not None+ and model.context_window_tokens > 0+ else "default",max_output_tokens=model.max_output_tokens,supports_reasoning_effort=(allows_reasoning if view is ModelCatalogView.RESPONSES else Nonediff --git a/src/free_claude_code/api/ports.py b/src/free_claude_code/api/ports.pyindex 8e4c4cdb..34ba3f30 100644--- a/src/free_claude_code/api/ports.py+++ b/src/free_claude_code/api/ports.py@@ -34,6 +34,14 @@ class AdminRuntimePort(Protocol):async def claude_vscode_status(self) -> JsonObject: ...+ async def vscode_chat_status(self) -> JsonObject: ...++ async def connect_vscode_chat(self) -> JsonObject: ...++ async def disconnect_vscode_chat(self) -> JsonObject: ...++ async def refresh_vscode_chat(self) -> JsonObject: ...+async def connect_claude_vscode(self) -> JsonObject: ...async def disconnect_claude_vscode(self) -> JsonObject: ...diff --git a/src/free_claude_code/application/model_catalog.py b/src/free_claude_code/application/model_catalog.pyindex 8eef9982..f9665e3e 100644--- a/src/free_claude_code/application/model_catalog.py+++ b/src/free_claude_code/application/model_catalog.py@@ -4,6 +4,7 @@ from collections.abc import Sequencefrom dataclasses import dataclass, replacefrom typing import TYPE_CHECKING+from free_claude_code.config.constants import DEFAULT_MODEL_CONTEXT_TOKENSfrom free_claude_code.config.model_refs import (configured_chat_model_refs,split_provider_model_ref,@@ -40,6 +41,14 @@ class ModelCatalog:default_model_id: str+def context_window_for_client(model: CatalogModel) -> int:+ """Resolve client capacity without changing reported provider metadata."""+ context = model.context_window_tokens+ return (+ context if context is not None and context > 0 else DEFAULT_MODEL_CONTEXT_TOKENS+ )++def model_order_key(provider_model_ref: str) -> tuple[str, str, str, str]:provider, model = split_provider_model_ref(provider_model_ref)return provider.casefold(), model.casefold(), provider, modeldiff --git a/src/free_claude_code/cli/launchers/aider_config.py b/src/free_claude_code/cli/launchers/aider_config.pyindex 8df335c5..e2ec8e92 100644--- a/src/free_claude_code/cli/launchers/aider_config.py+++ b/src/free_claude_code/cli/launchers/aider_config.py@@ -3,7 +3,11 @@import refrom dataclasses import dataclass, field-from free_claude_code.application.model_catalog import CatalogModel, model_order_key+from free_claude_code.application.model_catalog import (+ CatalogModel,+ context_window_for_client,+ model_order_key,+)from free_claude_code.core.json_types import JsonObjectfrom free_claude_code.core.model_capabilities import ModelInputModality@@ -73,8 +77,7 @@ def _model_metadata(model: CatalogModel) -> JsonObject:}if model.input_modalities is not None:metadata["supports_vision"] = ModelInputModality.IMAGE in model.input_modalities- if model.context_window_tokens is not None:- metadata["max_input_tokens"] = model.context_window_tokens+ metadata["max_input_tokens"] = context_window_for_client(model)if model.max_output_tokens is not None:metadata["max_output_tokens"] = model.max_output_tokensreturn metadatadiff --git a/src/free_claude_code/cli/launchers/catalog_http.py b/src/free_claude_code/cli/launchers/catalog_http.pyindex fa8269ce..d540a61d 100644--- a/src/free_claude_code/cli/launchers/catalog_http.py+++ b/src/free_claude_code/cli/launchers/catalog_http.py@@ -89,7 +89,11 @@ def _catalog_candidates(display_name=_nonempty_string(item.get("display_name")) or model_id,supports_reasoning=_optional_boolean(item.get("supportsReasoning")),input_modalities=_input_modalities(item.get("inputModalities")),- context_window_tokens=_optional_positive_int(item.get("contextWindow")),+ context_window_tokens=(+ None+ if item.get("contextWindowSource") == "default"+ else _optional_positive_int(item.get("contextWindow"))+ ),max_output_tokens=_optional_positive_int(item.get("maxCompletionTokens")),diff --git a/src/free_claude_code/cli/launchers/cline_config.py b/src/free_claude_code/cli/launchers/cline_config.pyindex e157fadc..b9713492 100644--- a/src/free_claude_code/cli/launchers/cline_config.py+++ b/src/free_claude_code/cli/launchers/cline_config.py@@ -3,7 +3,10 @@from dataclasses import dataclass, fieldfrom datetime import UTC, datetime-from free_claude_code.application.model_catalog import CatalogModel+from free_claude_code.application.model_catalog import (+ CatalogModel,+ context_window_for_client,+)from free_claude_code.config.server_urls import proxy_v1_urlfrom free_claude_code.core.json_types import JsonObjectfrom free_claude_code.core.model_capabilities import ModelInputModality@@ -114,8 +117,7 @@ def _model_entry(model: CatalogModel) -> JsonObject:"outputModalities": ["text"],})- if model.context_window_tokens is not None:- entry["contextWindow"] = model.context_window_tokens+ entry["contextWindow"] = context_window_for_client(model)if model.max_output_tokens is not None:entry["maxTokens"] = model.max_output_tokensreturn entrydiff --git a/src/free_claude_code/cli/launchers/dsh_config.py b/src/free_claude_code/cli/launchers/dsh_config.pyindex bd7237a4..a8df724f 100644--- a/src/free_claude_code/cli/launchers/dsh_config.py+++ b/src/free_claude_code/cli/launchers/dsh_config.py@@ -3,7 +3,10 @@import mathfrom pathlib import Path-from free_claude_code.application.model_catalog import CatalogModel+from free_claude_code.application.model_catalog import (+ CatalogModel,+ context_window_for_client,+)from free_claude_code.config.server_urls import proxy_v1_urlfrom free_claude_code.core.json_types import JsonObjectfrom free_claude_code.core.model_capabilities import ModelInputModality@@ -109,8 +112,7 @@ def _model_profile(model: CatalogModel) -> JsonObject:for modality in ModelInputModalityif modality in model.input_modalities]- if model.context_window_tokens is not None:- profile["contextWindow"] = model.context_window_tokens+ profile["contextWindow"] = context_window_for_client(model)if model.max_output_tokens is not None:profile["maxTokens"] = model.max_output_tokensreturn profilediff --git a/src/free_claude_code/cli/launchers/hermes_config.py b/src/free_claude_code/cli/launchers/hermes_config.pyindex 95a2e4c1..556a26d5 100644--- a/src/free_claude_code/cli/launchers/hermes_config.py+++ b/src/free_claude_code/cli/launchers/hermes_config.py@@ -2,7 +2,10 @@from dataclasses import dataclass, field-from free_claude_code.application.model_catalog import CatalogModel+from free_claude_code.application.model_catalog import (+ CatalogModel,+ context_window_for_client,+)from free_claude_code.config.server_urls import proxy_v1_urlfrom free_claude_code.core.json_types import JsonObjectfrom free_claude_code.core.model_capabilities import ModelInputModality@@ -127,8 +130,7 @@ def _model_override(model: CatalogModel) -> JsonObject:override["supports_reasoning"] = model.supports_reasoningif model.input_modalities is not None:override["supports_vision"] = ModelInputModality.IMAGE in model.input_modalities- if model.context_window_tokens is not None:- override["context_window"] = model.context_window_tokens+ override["context_window"] = context_window_for_client(model)if model.max_output_tokens is not None:override["max_output_tokens"] = model.max_output_tokensreturn overridediff --git a/src/free_claude_code/cli/launchers/opencode_config.py b/src/free_claude_code/cli/launchers/opencode_config.pyindex fc79874d..edb0b07b 100644--- a/src/free_claude_code/cli/launchers/opencode_config.py+++ b/src/free_claude_code/cli/launchers/opencode_config.py@@ -2,7 +2,10 @@from dataclasses import dataclass-from free_claude_code.application.model_catalog import CatalogModel+from free_claude_code.application.model_catalog import (+ CatalogModel,+ context_window_for_client,+)from free_claude_code.config.server_urls import proxy_v1_urlfrom free_claude_code.core.json_types import JsonObjectfrom free_claude_code.core.model_capabilities import ModelInputModality@@ -94,8 +97,7 @@ def _model_config(model: CatalogModel) -> JsonObject:"output": ["text"],}limits: JsonObject = {}- if model.context_window_tokens is not None:- limits["context"] = model.context_window_tokens+ limits["context"] = context_window_for_client(model)if model.max_output_tokens is not None:limits["output"] = model.max_output_tokenselif model.context_window_tokens is not None:diff --git a/src/free_claude_code/cli/launchers/pi_extension.ts b/src/free_claude_code/cli/launchers/pi_extension.tsindex 21cd9246..6e9e2c3a 100644--- a/src/free_claude_code/cli/launchers/pi_extension.ts+++ b/src/free_claude_code/cli/launchers/pi_extension.ts@@ -3,7 +3,6 @@ import type { ExtensionAPI, ProviderModelConfig } from "@earendil-works/pi-codinconst API_KEY_ENV = "FCC_PI_API_KEY";const BASE_URL_ENV = "FCC_PI_BASE_URL";const CATALOG_TIMEOUT_MS = 35000;-const DEFAULT_CONTEXT_WINDOW = 128000;const DEFAULT_MAX_TOKENS = 16384;function requireEnvironment(name: string): string {@@ -53,7 +52,7 @@ function modelDefinition(providerModel: string,supportsReasoning: boolean | undefined,input: ("text" | "image")[] | undefined,- contextWindow: number | undefined,+ contextWindow: number,maxTokens: number | undefined,): ProviderModelConfig {return {@@ -62,7 +61,7 @@ function modelDefinition(reasoning: supportsReasoning ?? true,input: input ?? ["text"],cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },- contextWindow: contextWindow ?? DEFAULT_CONTEXT_WINDOW,+ contextWindow,maxTokens: maxTokens ?? DEFAULT_MAX_TOKENS,};}@@ -78,6 +77,10 @@ export function projectFccModels(payload: unknown): ProviderModelConfig[] {const id = entry.id;const providerModel = entry.provider_model_ref;if (!id.trim() || !providerModel.includes("/") || seen.has(id)) continue;+ const contextWindow = optionalPositiveInteger(entry.contextWindow);+ if (contextWindow === undefined) {+ throw new Error("FCC model context is missing or invalid. Restart the FCC server after updating.");+ }seen.add(id);models.push(modelDefinition(@@ -85,7 +88,7 @@ export function projectFccModels(payload: unknown): ProviderModelConfig[] {providerModel,optionalBoolean(entry.supportsReasoning),inputModalities(entry.inputModalities),- optionalPositiveInteger(entry.contextWindow),+ contextWindow,optionalPositiveInteger(entry.maxCompletionTokens),),);diff --git a/src/free_claude_code/config/constants.py b/src/free_claude_code/config/constants.pyindex c68a1900..1f048537 100644--- a/src/free_claude_code/config/constants.py+++ b/src/free_claude_code/config/constants.py@@ -2,6 +2,9 @@DEFAULT_MODEL = "nvidia_nim/nvidia/nemotron-3-super-120b-a12b"+# Client context allocation when the provider reports no model limit.+DEFAULT_MODEL_CONTEXT_TOKENS = 200_000+# HTTP client connect timeout (seconds).HTTP_CONNECT_TIMEOUT_DEFAULT = 10.0diff --git a/src/free_claude_code/harnesses/codex_model_catalog.py b/src/free_claude_code/harnesses/codex_model_catalog.pyindex 7ee67f3f..4adf0574 100644--- a/src/free_claude_code/harnesses/codex_model_catalog.py+++ b/src/free_claude_code/harnesses/codex_model_catalog.py@@ -3,19 +3,17 @@from collections.abc import Sequencefrom dataclasses import dataclass-from free_claude_code.application.model_catalog import CatalogModel+from free_claude_code.application.model_catalog import (+ CatalogModel,+ context_window_for_client,+)from free_claude_code.core.json_types import JsonObjectfrom free_claude_code.core.model_capabilities import ModelInputModality--SUPPORTED_REASONING_LEVELS = {- "none": "Turn reasoning off",- "low": "Fast responses with lighter reasoning",- "medium": "Balances speed and reasoning depth for everyday tasks",- "high": "Greater reasoning depth for complex problems",- "xhigh": "Extra high reasoning depth for complex problems",- "max": "Maximum reasoning effort",-}-+from free_claude_code.harnesses.model_policy import (+ DEFAULT_REASONING_LEVEL,+ SUPPORTED_REASONING_LEVELS,+ reasoning_levels,+)CODEX_BASE_INSTRUCTIONS = ("You are Codex, a coding agent. Help the user understand, modify, test, "@@ -37,13 +35,11 @@ def project_codex_models(models: Sequence[CatalogModel]) -> tuple[CodexModel, ..CodexModel(model=model,priority=priority,- reasoning_levels=(- tuple(SUPPORTED_REASONING_LEVELS)- if model.supports_reasoning is not False- else ()- ),+ reasoning_levels=reasoning_levels(model),default_reasoning_level=(- "medium" if model.supports_reasoning is not False else None+ DEFAULT_REASONING_LEVEL+ if model.supports_reasoning is not False+ else None),)for priority, model in enumerate(models)@@ -63,11 +59,7 @@ def codex_model_entry(model: CodexModel) -> JsonObject:input_modalities = candidate.input_modalitiesif input_modalities is None or ModelInputModality.TEXT not in input_modalities:input_modalities = frozenset({ModelInputModality.TEXT})- context_window = (- candidate.context_window_tokens- if candidate.context_window_tokens is not None- else 200000- )+ context_window = context_window_for_client(candidate)entry: JsonObject = {"slug": candidate.wire_slug,"display_name": candidate.display_name,diff --git a/src/free_claude_code/harnesses/config_file.py b/src/free_claude_code/harnesses/config_file.pyindex 3bd674d6..9d59d5c8 100644--- a/src/free_claude_code/harnesses/config_file.py+++ b/src/free_claude_code/harnesses/config_file.py@@ -6,7 +6,13 @@ import tempfilefrom pathlib import Path-def atomic_write_text(path: Path, content: str) -> None:+def ensure_private_permissions(path: Path) -> None:+ """Restrict POSIX access; Windows files inherit their profile directory ACL."""+ if os.name != "nt" and stat.S_IMODE(path.stat().st_mode) != 0o600:+ path.chmod(0o600)+++def atomic_write_text(path: Path, content: str, *, private: bool = False) -> None:path.parent.mkdir(parents=True, exist_ok=True)temporary: Path | None = Nonetry:@@ -23,7 +29,9 @@ def atomic_write_text(path: Path, content: str) -> None:output.write(content)output.flush()os.fsync(output.fileno())- if path.exists():+ if private and os.name != "nt":+ ensure_private_permissions(temporary)+ elif path.exists():temporary.chmod(stat.S_IMODE(path.stat().st_mode))temporary.replace(path)finally:diff --git a/src/free_claude_code/harnesses/model_policy.py b/src/free_claude_code/harnesses/model_policy.pynew file mode 100644index 00000000..77037657--- /dev/null+++ b/src/free_claude_code/harnesses/model_policy.py@@ -0,0 +1,21 @@+"""Shared effort choices for FCC-generated native client catalogs."""++from free_claude_code.application.model_catalog import CatalogModel++SUPPORTED_REASONING_LEVELS = {+ "none": "Turn reasoning off",+ "low": "Fast responses with lighter reasoning",+ "medium": "Balances speed and reasoning depth for everyday tasks",+ "high": "Greater reasoning depth for complex problems",+ "xhigh": "Extra high reasoning depth for complex problems",+ "max": "Maximum reasoning effort",+}+DEFAULT_REASONING_LEVEL = "medium"+++def reasoning_levels(model: CatalogModel) -> tuple[str, ...]:+ return (+ tuple(SUPPORTED_REASONING_LEVELS)+ if model.supports_reasoning is not False+ else ()+ )diff --git a/src/free_claude_code/harnesses/vscode_chat_integration.py b/src/free_claude_code/harnesses/vscode_chat_integration.pynew file mode 100644index 00000000..6bd261cb--- /dev/null+++ b/src/free_claude_code/harnesses/vscode_chat_integration.py@@ -0,0 +1,150 @@+"""Configure FCC's model group in the native VS Code chat model picker."""++import json+from collections.abc import Sequence+from pathlib import Path+from typing import cast++import json5++from free_claude_code.application.model_catalog import (+ CatalogModel,+ context_window_for_client,+)+from free_claude_code.config.constants import (+ ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS,+ DEFAULT_MODEL_CONTEXT_TOKENS,+)+from free_claude_code.core.json_types import JsonObject+from free_claude_code.core.model_capabilities import ModelInputModality+from free_claude_code.harnesses.claude_integration import settings_path+from free_claude_code.harnesses.config_file import (+ atomic_write_text,+ ensure_private_permissions,+)+from free_claude_code.harnesses.model_policy import (+ DEFAULT_REASONING_LEVEL,+ reasoning_levels,+)++_NAME = "Free Claude Code"+_MARKER = "fccIntegration"+++def config_path() -> Path:+ return settings_path().with_name("chatLanguageModels.json")+++def model_entry(model: CatalogModel, proxy_root_url: str) -> JsonObject:+ context = context_window_for_client(model)+ context = context if context >= 2 else DEFAULT_MODEL_CONTEXT_TOKENS+ output = model.max_output_tokens+ output = (+ output+ if output is not None and output > 0+ else ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS+ )+ output = min(output, context // 2)+ entry: JsonObject = {+ "id": model.wire_slug,+ "name": model.display_name,+ "url": proxy_root_url.rstrip("/") + "/v1/messages",+ "toolCalling": True,+ "vision": ModelInputModality.IMAGE in (model.input_modalities or ()),+ "maxInputTokens": context - output,+ "maxOutputTokens": output,+ }+ if levels := reasoning_levels(model):+ entry["supportsReasoningEffort"] = list(levels)+ entry["defaultReasoningEffort"] = DEFAULT_REASONING_LEVEL+ return entry+++def _read(path: Path) -> tuple[list[JsonObject], JsonObject | None]:+ try:+ source = path.read_text(encoding="utf-8-sig")+ except FileNotFoundError:+ return [], None+ document = json5.loads(source, allow_duplicate_keys=False)+ if not isinstance(document, list) or any(not isinstance(g, dict) for g in document):+ raise ValueError("Model configuration must be an array of groups")+ json.dumps(document, allow_nan=False)+ groups = cast(list[JsonObject], document)+ owned = [g for g in groups if g.get(_MARKER) == "vscode"]+ if len(owned) > 1:+ raise ValueError("Duplicate FCC model groups")+ group = owned[0] if owned else None+ if group is not None and (+ group.get("vendor") != "customendpoint"+ or not isinstance(group.get("name"), str)+ or not group["name"]+ ):+ raise ValueError("Invalid FCC model group")+ return groups, group+++def status(path: Path) -> JsonObject:+ path = path.resolve()+ _, group = _read(path)+ return {"connected": group is not None, "paths": {"vscode_models": str(path)}}+++def configure(+ path: Path,+ proxy_root_url: str,+ auth_token: str,+ models: Sequence[CatalogModel],+ *,+ only_existing: bool = False,+) -> bool:+ """Regenerate FCC models while preserving native preferences in group.settings."""+ path = path.resolve()+ groups, group = _read(path)+ if group is None and only_existing:+ return False+ if not auth_token.strip():+ raise ValueError("FCC's managed token is required")+ name = group["name"] if group is not None else _NAME+ if any(+ g is not group and g.get("vendor") == "customendpoint" and g.get("name") == name+ for g in groups+ ):+ raise ValueError("Rename the conflicting custom endpoint group in VS Code")+ before = json.dumps(groups, allow_nan=False)+ if group is None:+ new_group: JsonObject = {"name": _NAME}+ group = new_group+ groups.append(group)+ group.update(+ {+ "vendor": "customendpoint",+ _MARKER: "vscode",+ "apiType": "messages",+ "models": [+ {+ **model_entry(model, proxy_root_url),+ "requestHeaders": {"x-api-key": auth_token},+ }+ for model in models+ ],+ }+ )+ # A provider URL selects VS Code's discovery branch instead of these entries.+ group.pop("url", None)+ # VS Code treats group apiKey as a secret-store reference, not a raw token.+ group.pop("apiKey", None)+ if json.dumps(groups, allow_nan=False) == before:+ ensure_private_permissions(path)+ return False+ atomic_write_text(+ path, json.dumps(groups, indent=2, allow_nan=False) + "\n", private=True+ )+ return True+++def disconnect(path: Path) -> None:+ path = path.resolve()+ groups, group = _read(path)+ if group is not None:+ groups.remove(group)+ atomic_write_text(path, json.dumps(groups, indent=2, allow_nan=False) + "\n")diff --git a/src/free_claude_code/runtime/application.py b/src/free_claude_code/runtime/application.pyindex 4b6c0abf..3302c980 100644--- a/src/free_claude_code/runtime/application.py+++ b/src/free_claude_code/runtime/application.py@@ -25,6 +25,7 @@ from free_claude_code.application.errors import (ApplicationUnavailableError,InvalidRequestError,)+from free_claude_code.application.model_catalog import ModelCatalog, read_model_catalogfrom free_claude_code.application.model_metadata import ProviderModelRefreshResultfrom free_claude_code.application.ports import StopResultfrom free_claude_code.config.admin.custom_providers import CustomProviderMutation@@ -48,6 +49,7 @@ from free_claude_code.harnesses import (claude_integration,codex_integration,jetbrains_acp_integration,+ vscode_chat_integration,)from free_claude_code.messaging.platforms import factory as messaging_platform_factoryfrom free_claude_code.messaging.platforms.factory import MessagingPlatformOptions@@ -218,6 +220,8 @@ class ApplicationRuntime:self._desktop_update = _IntegrationUpdate()self._codex_update = _IntegrationUpdate()self._jetbrains_update = _IntegrationUpdate()+ self._vscode_update = _IntegrationUpdate()+ self._vscode_dirty = Falseself._http_ready = asyncio.Event()self._messaging_state = ("disabled" if self.settings.messaging_platform == "none" else "starting"@@ -251,6 +255,10 @@ class ApplicationRuntime:"Application runtime is shutting down.")self.provider_manager.start_model_list_refresh()+ self.provider_manager.set_catalog_changed_callback(+ self._queue_vscode_refresh+ )+ self._queue_vscode_refresh()await self.refresh_claude_vscode()await self.refresh_codex_integration()await self.refresh_claude_desktop()@@ -296,6 +304,7 @@ class ApplicationRuntime:def begin_shutdown(self) -> None:"""Finish indefinite observer responses before the server drains HTTP."""self._draining = True+ self.provider_manager.set_catalog_changed_callback(None)self.provider_manager.begin_shutdown()self._folder_picker.begin_shutdown()if self._code_service is not None:@@ -430,6 +439,119 @@ class ApplicationRuntime:async def admin_values(self) -> ValueState:return await self._configuration.admin_values()+ async def vscode_chat_status(self) -> JsonObject:+ return await self._vscode_chat("status")++ async def connect_vscode_chat(self) -> JsonObject:+ return await self._vscode_chat("connect")++ async def disconnect_vscode_chat(self) -> JsonObject:+ return await self._vscode_chat("disconnect")++ async def refresh_vscode_chat(self) -> JsonObject:+ self._check_integration_available()+ self._queue_vscode_refresh()+ return {"update": self._vscode_update.snapshot()}++ def _queue_vscode_refresh(self) -> None:+ if self._draining:+ return+ self._vscode_dirty = True+ update = self._vscode_update+ if update.task is not None and not update.task.done():+ return+ update.state, update.changed, update.message = "starting", False, None++ async def drain() -> None:+ while self._vscode_dirty:+ self._vscode_dirty = False+ try:+ result = await self._vscode_chat("refresh")+ update.complete(update.changed or result.get("changed") is True)+ except ApplicationError as exc:+ update.state, update.message = "failed", exc.message+ except Exception as exc:+ update.state = "failed"+ update.message = "Could not update VS Code models. Retry shortly."+ logger.warning(+ "VS Code integration update failed: exc_type={}",+ type(exc).__name__,+ )+ if self._vscode_dirty:+ update.state = "starting"++ update.task = asyncio.create_task(drain(), name="fcc-vscode-models")+ self._startup_tasks.append(update.task)+ update.task.add_done_callback(self._startup_tasks.remove)++ async def _vscode_chat(self, action: IntegrationAction) -> JsonObject:+ try:+ if action == "refresh":+ async with self._config_lock:+ self._check_integration_available()+ status = await run_sync_owned(+ lambda: vscode_chat_integration.status(+ vscode_chat_integration.config_path()+ )+ )+ if not status["connected"]:+ return {"changed": False}+ while True:+ snapshot = (+ await self.provider_manager.wait_for_catalog()+ if action in {"connect", "refresh"}+ else None+ )+ revision = self.provider_manager.catalog_status()["catalog_revision"]+ async with self._config_lock:+ self._check_integration_available()+ if snapshot is not None and (+ snapshot.current_settings() is not self.settings+ or revision+ != self.provider_manager.catalog_status()["catalog_revision"]+ or self.provider_manager.catalog_status()["catalog"] != "ready"+ ):+ continue+ catalog = (+ read_model_catalog(snapshot) if snapshot is not None else None+ )+ settings = self.settings++ def operate(+ catalog: ModelCatalog | None = catalog,+ settings: Settings = settings,+ ) -> JsonObject:+ path = vscode_chat_integration.config_path()+ changed = False+ if action == "disconnect":+ vscode_chat_integration.disconnect(path)+ elif catalog is not None:+ changed = vscode_chat_integration.configure(+ path,+ local_proxy_root_url(settings),+ settings.proxy_auth_token,+ catalog.models,+ only_existing=action == "refresh",+ )+ if action == "refresh":+ return {"changed": changed}+ return vscode_chat_integration.status(path)++ result = await run_sync_owned(operate)+ if action in {"connect", "disconnect"}:+ self._vscode_update.complete()+ if action == "status":+ result["update"] = self._vscode_update.snapshot()+ return result+ except ValueError, UnicodeError:+ raise InvalidRequestError(+ "Could not configure VS Code Chat. Check chatLanguageModels.json for invalid JSON or conflicting FCC groups."+ ) from None+ except OSError:+ raise ApplicationUnavailableError(+ "Could not access chatLanguageModels.json. Finish configuration edits, check file permissions, and retry."+ ) from None+async def claude_vscode_status(self) -> JsonObject:return await self._claude_vscode("status")@@ -744,6 +866,7 @@ class ApplicationRuntime:"message": self._messaging_error,},"integrations": {+ "vscode-chat": self._vscode_update.snapshot(),"claude-vscode": self._claude_update.snapshot(),"claude-desktop": self._desktop_update.snapshot(),"codex": self._codex_update.snapshot(),diff --git a/src/free_claude_code/runtime/diagnostics.py b/src/free_claude_code/runtime/diagnostics.pyindex 043a2b08..30008440 100644--- a/src/free_claude_code/runtime/diagnostics.py+++ b/src/free_claude_code/runtime/diagnostics.py@@ -23,6 +23,7 @@ from free_claude_code.harnesses import (claude_integration,codex_integration,jetbrains_acp_integration,+ vscode_chat_integration,)from free_claude_code.providers.github_copilot.auth import CopilotAuthManagerfrom free_claude_code.providers.openai_codex.auth import saved_connection_state@@ -206,6 +207,9 @@ def settings_report(settings: Settings, accounts: dict[str, str]) -> dict[str, Adef integration_report(settings: Settings) -> dict[str, Any]:url, token = local_proxy_root_url(settings), settings.proxy_auth_tokenreaders = {+ "vscode-chat": lambda: vscode_chat_integration.status(+ vscode_chat_integration.config_path()+ ),"claude-vscode": lambda: claude_integration.configure(claude_integration.settings_path(),claude_integration.claude_state_path(),diff --git a/src/free_claude_code/runtime/provider_manager.py b/src/free_claude_code/runtime/provider_manager.pyindex 71df8dbd..7b124d6e 100644--- a/src/free_claude_code/runtime/provider_manager.py+++ b/src/free_claude_code/runtime/provider_manager.py@@ -159,6 +159,7 @@ class ProviderRuntimeManager:self._runtime_factory = runtime_factoryself._connected_provider_ids = connected_provider_idsself._model_catalog_publisher = model_catalog_publisher+ self._catalog_changed: Callable[[], None] | None = Noneself._replace_lock = asyncio.Lock()self._publication_lock = asyncio.Lock()self._close_lock = asyncio.Lock()@@ -186,6 +187,10 @@ class ProviderRuntimeManager:def current_generation_id(self) -> int:return self._current.generation_id+ def set_catalog_changed_callback(self, callback: Callable[[], None] | None) -> None:+ """Register a nonblocking notification for application-owned consumers."""+ self._catalog_changed = callback+def _ensure_open(self) -> None:if self._closing or self._closed:raise ApplicationUnavailableError("Provider runtime is shutting down.")@@ -513,6 +518,8 @@ class ProviderRuntimeManager:)else:generation.file_state = "ready"+ if self._catalog_changed is not None and not self._closing:+ self._catalog_changed()async def replace(self, settings: Settings, *, commit: CommitConfig, reason: str = "admin_apply"diff --git a/tests/api/test_model_listing.py b/tests/api/test_model_listing.pyindex 44331c42..59093ec0 100644--- a/tests/api/test_model_listing.py+++ b/tests/api/test_model_listing.py@@ -1,3 +1,4 @@+import jsonimport mathimport pytest@@ -39,6 +40,38 @@ def _cache_models(app, provider_id: str, *model_ids: str) -> None:)[email protected]("view", ["messages", "responses"])+def test_context_fallback_round_trip_preserves_reported_capabilities(view):+ from free_claude_code.application.model_catalog import read_model_catalog+ from free_claude_code.cli.launchers.catalog_http import model_catalog_from_response+ from free_claude_code.cli.launchers.opencode_config import build_opencode_config++ app = create_test_app(_settings(model_opus=None))+ manager = provider_manager_for_app(app)+ manager.cache_model_infos(+ "deepseek", {ProviderModelInfo("known", context_window_tokens=8000)}+ )+ before = read_model_catalog(manager)+ payload = TestClient(app).get(f"/v1/models?view={view}").json()+ rows = {row["id"]: row for row in payload["data"]}+ assert rows["deepseek/deepseek-chat"]["contextWindow"] == 200000+ assert rows["deepseek/deepseek-chat"]["contextWindowSource"] == "default"+ assert rows["deepseek/known"]["contextWindow"] == 8000+ assert rows["deepseek/known"]["contextWindowSource"] == "provider"+ decoded = model_catalog_from_response(payload)+ assert decoded == before+ config = build_opencode_config(+ decoded.models,+ default_model_id=decoded.default_model_id,+ proxy_root_url="http://localhost:8082",+ )+ models = json.loads(json.dumps(config.file))["providers"]["free-claude-code"][+ "models"+ ]+ assert models["deepseek/deepseek-chat"]["limit"] == {"context": 200000}+ assert models["deepseek/known"]["limit"] == {"context": 8000, "output": 2000}++@pytest.mark.parametrize("view", ["messages", "responses"])def test_sorted_catalog_retains_an_explicit_no_thinking_server_default(view):settings = _settings(@@ -241,6 +274,8 @@ def test_direct_model_views_exclude_claude_aliases_and_duplicate_variants():"provider_model_ref": "deepseek/deepseek-chat","apiBackend": "responses","maxRetries": 0,+ "contextWindow": 200000,+ "contextWindowSource": "default","supportsReasoningEffort": True,"reasoningEfforts": ["none",@@ -305,7 +340,8 @@ def test_direct_model_views_serialize_known_capabilities_and_omit_unknowns():assert "maxCompletionTokens" not in messages["open_router/text-only"]assert "supportsReasoning" not in messages["open_router/unknown"]assert "inputModalities" not in messages["open_router/unknown"]- assert "contextWindow" not in messages["open_router/unknown"]+ assert messages["open_router/unknown"]["contextWindow"] == 200000+ assert messages["open_router/unknown"]["contextWindowSource"] == "default"assert "maxCompletionTokens" not in messages["open_router/unknown"]assert responses["open_router/text-only"]["supportsReasoningEffort"] is Falseassert "reasoningEfforts" not in responses["open_router/text-only"]@@ -363,7 +399,7 @@ def test_muse_model_catalog_marks_every_routable_model_visible():metadata = row["metadata"]["muse-code"]assert metadata["is_hidden"] is Falseassert metadata["name"] == row["display_name"]- assert "limit" not in metadata+ assert metadata["limit"] == {"context": 200000}original = {key: value for key, value in row.items() if key != "metadata"}assert original in responses.json()["data"]assert [row["id"] for row in muse.json()["data"]] == [@@ -411,6 +447,7 @@ def test_muse_catalog_uses_native_metadata_for_known_limits_and_reasoning():assert rows["deepseek/deepseek-chat"] == {"name": "deepseek/deepseek-chat","is_hidden": False,+ "limit": {"context": 200000},}diff --git a/tests/api/test_vscode_chat_routes.py b/tests/api/test_vscode_chat_routes.pynew file mode 100644index 00000000..02eb3997--- /dev/null+++ b/tests/api/test_vscode_chat_routes.py@@ -0,0 +1,85 @@+import json++import pytest+from fastapi.testclient import TestClient++from free_claude_code.config.settings import Settings+from free_claude_code.harnesses import vscode_chat_integration as vscode+from tests.api.support import create_test_app, runtime_for_app++ROOT = "/admin/api/integrations/vscode-chat"+++def integration():+ 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, vscode.config_path(), runtime_for_app(app)+++def test_connect_disconnect_and_doctor_status(integration):+ from free_claude_code.runtime.diagnostics import integration_report++ client, path, runtime = integration+ result = client.get(ROOT)+ assert result.json()["paths"]["vscode_models"] == str(path.resolve())+ assert not path.exists()+ result = client.post(ROOT + "/connect")+ assert result.status_code == 200+ assert result.json()["connected"]+ assert result.headers["cache-control"] == "no-store"+ assert "integration-secret" not in result.text+ group = json.loads(path.read_text())[0]+ # VS Code resolves group apiKey through its secret store, even for plain text.+ # Explicit model headers reach the Messages endpoint without that lookup.+ assert "apiKey" not in group+ headers = group["models"][0]["requestHeaders"]+ assert headers == {"x-api-key": "integration-secret"}+ assert client.head("/v1/messages", headers=headers).status_code == 204+ assert group["models"][0]["url"] == "http://127.0.0.1:4321/v1/messages"+ assert integration_report(runtime.settings)["vscode-chat"] == {+ "status": "available",+ "connected": True,+ }+ assert not client.post(ROOT + "/disconnect").json()["connected"]++[email protected]("action", ["", "/connect", "/disconnect", "/refresh"])+ "headers", [{"Host": "evil.test"}, {"Origin": "https://evil.test"}]+)+def test_local_admin_security(integration, action, headers):+ client, path, _ = integration+ assert (+ client.request(+ "GET" if not action else "POST", ROOT + action, headers=headers+ ).status_code+ == 403+ )+ assert not path.exists()+++def test_bad_configuration_errors_do_not_leak_credentials(integration):+ client, path, _ = integration+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text('{"integration-secret":bad}')+ for action in ("", "/connect", "/disconnect"):+ response = client.request("GET" if not action else "POST", ROOT + action)+ assert response.status_code == 400+ assert "integration-secret" not in response.text+ assert response.headers["cache-control"] == "no-store"+ assert path.read_text() == '{"integration-secret":bad}'+++def test_pending_restart_and_shutdown_reject_writes(integration):+ client, path, runtime = integration+ runtime._pending_fields = ["PORT"]+ assert client.post(ROOT + "/connect").status_code == 503+ runtime._pending_fields = []+ runtime.begin_shutdown()+ assert client.post(ROOT + "/disconnect").status_code == 503+ assert not path.exists()diff --git a/tests/cli/test_aider_config.py b/tests/cli/test_aider_config.pyindex 2bc3b139..987ddf25 100644--- a/tests/cli/test_aider_config.py+++ b/tests/cli/test_aider_config.py@@ -59,9 +59,11 @@ def test_aider_config_projects_messages_route_and_canonical_catalog() -> None:"litellm_provider": "anthropic","mode": "chat","supports_vision": False,+ "max_input_tokens": 200000,"max_output_tokens": 4096,},"future_provider/unknown-model": {+ "max_input_tokens": 200000,"litellm_provider": "anthropic","mode": "chat",},diff --git a/tests/cli/test_cline_launcher.py b/tests/cli/test_cline_launcher.pyindex c7939a3e..ca0c7cfc 100644--- a/tests/cli/test_cline_launcher.py+++ b/tests/cli/test_cline_launcher.py@@ -111,6 +111,7 @@ def test_cline_config_uses_responses_and_only_known_metadata() -> None:},"future_provider/unknown-model": {"name": "Unknown model",+ "contextWindow": 200000,"capabilities": ["streaming", "tools", "reasoning"],"supportsReasoning": True,"apiFormat": "openai-responses",diff --git a/tests/cli/test_dsh_config.py b/tests/cli/test_dsh_config.pyindex d204814c..4b6f23ef 100644--- a/tests/cli/test_dsh_config.py+++ b/tests/cli/test_dsh_config.py@@ -100,12 +100,14 @@ def test_dsh_config_pins_responses_models_retries_and_private_state("id": "claude-3-freecc-no-thinking/open_router/plain-model","name": "No-thinking model","reasoningEfforts": False,+ "contextWindow": 200000,"input": ["text"],"maxTokens": 4096,},{"id": "future_provider/unknown-model","name": "Unknown model",+ "contextWindow": 200000,"reasoningEfforts": {"off": "none","minimal": "minimal",diff --git a/tests/cli/test_hermes_config.py b/tests/cli/test_hermes_config.pyindex 3342031a..eb020cc7 100644--- a/tests/cli/test_hermes_config.py+++ b/tests/cli/test_hermes_config.py@@ -84,6 +84,7 @@ def test_hermes_config_pins_responses_catalog_and_fallbacks() -> None:assert managed.config["fallback_model"] == []assert managed.config["model_overrides"] == {"custom": {+ "future_provider/unknown-model": {"context_window": 200000},"nvidia_nim/vendor/model": {"supports_reasoning": True,"supports_vision": True,@@ -93,6 +94,7 @@ def test_hermes_config_pins_responses_catalog_and_fallbacks() -> None:"claude-3-freecc-no-thinking/open_router/plain-model": {"supports_reasoning": False,"supports_vision": False,+ "context_window": 200000,"max_output_tokens": 4096,},}diff --git a/tests/cli/test_opencode_launcher.py b/tests/cli/test_opencode_launcher.pyindex 5be7706f..750bfad0 100644--- a/tests/cli/test_opencode_launcher.py+++ b/tests/cli/test_opencode_launcher.py@@ -76,10 +76,11 @@ def test_opencode_config_uses_native_responses_and_model_budgets() -> None:},"future_provider/unknown-model": {"name": "Unknown model",+ "limit": {"context": 200000},},"future_provider/output-only": {"name": "Output-only model",- "limit": {"output": 4096},+ "limit": {"context": 200000, "output": 4096},},}assert config.overlay == {@@ -120,8 +121,8 @@ def test_opencode_config_uses_native_responses_and_model_budgets() -> None:(16384, 1024, {"context": 16384, "output": 1024}, 4096),(131072, 65536, {"context": 131072, "output": 65536}, None),(200000, None, {"context": 200000, "output": 4096}, None),- (None, 4096, {"output": 4096}, None),- (None, None, None, None),+ (None, 4096, {"context": 200000, "output": 4096}, None),+ (None, None, {"context": 200000}, None),],)def test_opencode_context_reserves_fit_small_models(diff --git a/tests/cli/test_pi_extension.py b/tests/cli/test_pi_extension.pyindex bbbec6ff..2cb4e9cf 100644--- a/tests/cli/test_pi_extension.py+++ b/tests/cli/test_pi_extension.py@@ -27,7 +27,7 @@ process.env.FCC_PI_BASE_URL = "http://fcc.invalid";process.env.FCC_PI_API_KEY = "test-key";globalThis.fetch = async () => new Response(JSON.stringify({object: "list",- data: [{ id: "opencode_zen/test", provider_model_ref: "opencode_zen/test" }],+ data: [{ id: "opencode_zen/test", provider_model_ref: "opencode_zen/test", contextWindow: 200000 }],}));await extension({registerProvider() {},@@ -88,7 +88,7 @@ process.env.FCC_PI_BASE_URL = "http://fcc.invalid";process.env.FCC_PI_API_KEY = "test-key";globalThis.fetch = async () => new Response(JSON.stringify({object: "list",- data: [{ id: "github_copilot/gpt-5.6-luna", provider_model_ref: "github_copilot/gpt-5.6-luna" }],+ data: [{ id: "github_copilot/gpt-5.6-luna", provider_model_ref: "github_copilot/gpt-5.6-luna", contextWindow: 200000 }],}));await extension({registerProvider() {},@@ -294,6 +294,7 @@ def test_pi_extension_projects_known_capabilities_and_preserves_unknown_defaults{"id": "provider/unknown ","provider_model_ref": "provider/unknown ",+ "contextWindow": 200000,},],}@@ -337,5 +338,5 @@ console.log(JSON.stringify(projectFccModels(payload)));assert [(model["contextWindow"], model["maxTokens"]) for model in projected] == [(131072, 8192),(65536, 16384),- (128000, 16384),+ (200000, 16384),]diff --git a/tests/cli/test_progressive_launch.py b/tests/cli/test_progressive_launch.pyindex 4a9e507a..35410b65 100644--- a/tests/cli/test_progressive_launch.py+++ b/tests/cli/test_progressive_launch.py@@ -192,11 +192,12 @@ def test_browser_thread_start_failure_does_not_fail_fcc(monkeypatch, reuse):browser.assert_not_called()-def _run_browser_shutdown_probe(mode, outcome, directory):+def _run_browser_shutdown_probe(mode, outcome, directory, setup_delay="0"):"""Run real FCC lifecycle owners with only OS/browser/server dependencies faked."""from free_claude_code.cli import desktop, uvicorn_serverfrom free_claude_code.runtime import bootstrap+ print("probe: setup", flush=True)entered = threading.Event()patcher = pytest.MonkeyPatch()settings = Settings.model_construct(@@ -208,6 +209,7 @@ def _run_browser_shutdown_probe(mode, outcome, directory):def browser(url):assert url == "http://127.0.0.1:0/admin"+ print("probe: browser entered", flush=True)entered.set()if outcome in {"automatic", "tray", "quit", "timeout"}:threading.Event().wait() # Intentionally never released in this process.@@ -244,10 +246,10 @@ def _run_browser_shutdown_probe(mode, outcome, directory):if mode == "server":if outcome == "tray":supervisor.request_open_admin()- assert entered.wait(2)+ entered.wait() # The parent process owns the finite lifecycle deadline.supervisor.request_stop()else:- assert supervisor.stop_event.wait(3)+ supervisor.stop_event.wait()patcher.setattr(uvicorn_server, "RuntimeServer", Server)@@ -259,7 +261,7 @@ def _run_browser_shutdown_probe(mode, outcome, directory):setup()if outcome == "tray":self.controller.open_admin()- assert entered.wait(2)+ entered.wait() # The parent process owns the finite lifecycle deadline.self.controller.quit()def stop(self):@@ -305,15 +307,23 @@ def _run_browser_shutdown_probe(mode, outcome, directory):def run(self, setup):setup()- assert entered.wait(2)+ entered.wait() # The parent process owns the finite lifecycle deadline.if outcome == "quit":self.controller.quit()- assert self.stopped.wait(6 if outcome == "timeout" else 2)+ self.stopped.wait()def stop(self):self.stopped.set()lock = InterprocessFileLock(Path(directory) / "desktop.lock")+ original_acquire = InterprocessFileLock.acquire++ def acquire(instance):+ print("probe: acquiring desktop lock", flush=True)+ threading.Event().wait(float(setup_delay))+ return original_acquire(instance)++ patcher.setattr(InterprocessFileLock, "acquire", acquire)try:if mode == "reuse-desktop":assert lock.acquire()@@ -339,20 +349,33 @@ def test_reusing_desktop_process_exits_without_owning_browser(tmp_path, mode, ou_assert_browser_probe_exits(tmp_path, mode, outcome)-def _assert_browser_probe_exits(tmp_path, mode, outcome):+def test_browser_shutdown_waits_for_slow_healthy_setup(tmp_path):+ _assert_browser_probe_exits(tmp_path, "reuse-terminal", "quit", setup_delay="2.2")+++def _assert_browser_probe_exits(tmp_path, mode, outcome, setup_delay="0"):script = ("import runpy, sys; ""runpy.run_path(sys.argv[1])['_run_browser_shutdown_probe'](*sys.argv[2:])")# subprocess.run kills and reaps only this disposable child on timeout.completed = subprocess.run(- [sys.executable, "-c", script, __file__, mode, outcome, str(tmp_path)],+ [+ sys.executable,+ "-c",+ script,+ __file__,+ mode,+ outcome,+ str(tmp_path),+ setup_delay,+ ],capture_output=True,text=True,timeout=12,check=False,)- assert completed.returncode == 0, completed.stderr or completed.stdout+ assert completed.returncode == 0, completed.stdout + completed.stderrassert "FCC exited while preserving its resource ownership" in completed.stdoutdiff --git a/tests/conftest.py b/tests/conftest.pyindex 0d4c88ae..745ddca1 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -13,6 +13,7 @@ from free_claude_code.harnesses import (claude_integration,codex_integration,jetbrains_acp_integration,+ vscode_chat_integration,)from tests.providers.support import (immediate_admission,@@ -32,6 +33,11 @@ def _isolate_managed_config(monkeypatch, tmp_path):"""Keep every test away from real home, checkout, and running-server config."""config_dir = tmp_path / ".fcc"+ monkeypatch.setattr(+ vscode_chat_integration,+ "config_path",+ lambda: tmp_path / "vscode/chatLanguageModels.json",+ )monkeypatch.setattr(jetbrains_acp_integration,"config_path",diff --git a/tests/contracts/test_import_boundaries.py b/tests/contracts/test_import_boundaries.pyindex 3add3b44..d8add978 100644--- a/tests/contracts/test_import_boundaries.py+++ b/tests/contracts/test_import_boundaries.py@@ -215,6 +215,8 @@ def test_native_model_catalog_has_no_http_formatter_or_decoder_dependency() -> Nf"{_PACKAGE_NAME}.runtime.codex_app_server",f"{_PACKAGE_NAME}.runtime.codex_catalog",f"{_PACKAGE_NAME}.harnesses.codex_model_catalog",+ f"{_PACKAGE_NAME}.harnesses.vscode_chat_integration",+ f"{_PACKAGE_NAME}.harnesses.model_policy",}offenders = [record.describe()diff --git a/tests/harnesses/test_vscode_chat_integration.py b/tests/harnesses/test_vscode_chat_integration.pynew file mode 100644index 00000000..cbc87ebb--- /dev/null+++ b/tests/harnesses/test_vscode_chat_integration.py@@ -0,0 +1,288 @@+import json+import os+import stat+from dataclasses import replace++import pytest++from free_claude_code.application.model_catalog import CatalogModel+from free_claude_code.core.model_capabilities import ModelInputModality+from free_claude_code.harnesses import vscode_chat_integration as vscode++URL = "http://127.0.0.1:8082"+MODEL = CatalogModel("nim/model", "nim/model", "NIM Model", None)+native_config_path = vscode.config_path+++def test_connect_refresh_disconnect_preserves_other_groups_and_options(tmp_path):+ path = tmp_path / "chatLanguageModels.json"+ other = {"name": "Other", "vendor": "customendpoint", "apiKey": "other"}+ path.write_text(json.dumps([other]))+ assert not vscode.status(path)["connected"]+ assert vscode.configure(path, URL, "secret", (MODEL,))+ data = json.loads(path.read_text())+ assert data[0] == other+ assert data[1]["models"][0]["url"] == URL + "/v1/messages"+ data[1].update(name="My FCC", settings={"keep": True}, url="old", apiKey="old")+ path.write_text(json.dumps(data))+ assert vscode.configure(path, URL, "new", (MODEL,), only_existing=True)+ saved = json.loads(path.read_text())+ assert saved[1]["settings"] == {"keep": True}+ assert saved[1]["name"] == "My FCC"+ assert "url" not in saved[1]+ assert "apiKey" not in saved[1]+ assert saved[1]["models"][0]["requestHeaders"] == {"x-api-key": "new"}+ before = path.stat().st_mtime_ns+ assert not vscode.configure(path, URL, "new", (MODEL,), only_existing=True)+ assert path.stat().st_mtime_ns == before+ assert vscode.status(path)["connected"] is True+ assert "new" not in json.dumps(vscode.status(path))+ vscode.disconnect(path)+ assert json.loads(path.read_text()) == [other]+ assert not vscode.configure(path, URL, "new", (MODEL,), only_existing=True)+++def test_missing_file_read_refresh_disconnect_never_creates_it(tmp_path):+ path = tmp_path / "missing/chatLanguageModels.json"+ assert vscode.status(path) == {+ "connected": False,+ "paths": {"vscode_models": str(path.resolve())},+ }+ assert not vscode.configure(path, URL, "secret", (MODEL,), only_existing=True)+ vscode.disconnect(path)+ assert not path.parent.exists()+++ "source", ["{bad", "{}", "[1]", '[{"x":NaN}]', '[{"x":1,"x":2}]']+)+def test_invalid_document_is_never_overwritten(tmp_path, source):+ path = tmp_path / "models.json"+ path.write_text(source)+ for operation in (+ lambda: vscode.status(path),+ lambda: vscode.disconnect(path),+ lambda: vscode.configure(path, URL, "secret", (MODEL,)),+ ):+ with pytest.raises(ValueError):+ operation()+ assert path.read_text() == source+++def test_conflict_does_not_claim_an_unmarked_group(tmp_path):+ path = tmp_path / "models.json"+ source = '[{"name":"Free Claude Code","vendor":"customendpoint"}]'+ path.write_text(source)+ with pytest.raises(ValueError):+ vscode.configure(path, URL, "secret", (MODEL,))+ assert path.read_text() == source+ assert not vscode.status(path)["connected"]+++def test_duplicate_markers_fail_but_disconnect_recovers_name_collision(tmp_path):+ path = tmp_path / "models.json"+ vscode.configure(path, URL, "secret", (MODEL,))+ owned = json.loads(path.read_text())[0]+ path.write_text(json.dumps([owned, owned]))+ with pytest.raises(ValueError):+ vscode.disconnect(path)+ other = {"vendor": "customendpoint", "name": owned["name"]}+ path.write_text(json.dumps([owned, other]))+ with pytest.raises(ValueError):+ vscode.configure(path, URL, "secret", (MODEL,))+ assert vscode.status(path)["connected"]+ vscode.disconnect(path)+ assert json.loads(path.read_text()) == [other]+++ "context,output,expected",+ [+ (None, None, (118080, 81920)),+ (8000, None, (4000, 4000)),+ (100000, 20000, (80000, 20000)),+ (None, 1000, (199000, 1000)),+ (8192, 8192, (4096, 4096)),+ (1, 0, (118080, 81920)),+ ],+)+def test_token_allocation_and_capabilities(context, output, expected):+ model = replace(MODEL, context_window_tokens=context, max_output_tokens=output)+ entry = vscode.model_entry(model, URL)+ assert (entry["maxInputTokens"], entry["maxOutputTokens"]) == expected+ assert entry["id"] == MODEL.wire_slug+ assert entry["toolCalling"] is True+ assert entry["vision"] is False+ assert "thinking" not in entry+ assert (+ vscode.model_entry(+ replace(model, input_modalities=frozenset({ModelInputModality.IMAGE})), URL+ )["vision"]+ is True+ )+++def test_comment_input_and_order_are_preserved_semantically(tmp_path):+ path = tmp_path / "models.json"+ path.write_text('[/* comment */ {"vendor":"other", "name":"Other",},]')+ second = replace(MODEL, wire_slug="custom/z", display_name="Custom Z")+ vscode.configure(path, URL, "secret", (MODEL, second))+ assert [m["id"] for m in json.loads(path.read_text())[1]["models"]] == [+ MODEL.wire_slug,+ second.wire_slug,+ ]++[email protected]("support", [True, None, False])+def test_native_effort_capability(support):+ entry = vscode.model_entry(replace(MODEL, supports_reasoning=support), URL)+ if support is False:+ assert "supportsReasoningEffort" not in entry+ assert "defaultReasoningEffort" not in entry+ else:+ assert entry["supportsReasoningEffort"] == [+ "none",+ "low",+ "medium",+ "high",+ "xhigh",+ "max",+ ]+ assert entry["defaultReasoningEffort"] == "medium"+++def test_refresh_preserves_native_preferences_and_replaces_generated_capabilities(+ tmp_path,+):+ path = tmp_path / "models.json"+ removed = replace(MODEL, wire_slug="nim/removed")+ vscode.configure(path, URL, "old", (MODEL, removed))+ data = json.loads(path.read_text())+ preferences = {MODEL.wire_slug: {"reasoningEffort": "high"}}+ data[0]["settings"] = preferences+ data[0]["models"][0]["maxOutputTokens"] = 777+ path.write_text(json.dumps(data))+ vscode.configure(path, URL, "new", (replace(MODEL, supports_reasoning=False),))+ saved = json.loads(path.read_text())[0]+ assert saved["settings"] == preferences+ assert [m["id"] for m in saved["models"]] == [MODEL.wire_slug]+ assert saved["models"][0]["maxOutputTokens"] == 81920+ assert "supportsReasoningEffort" not in saved["models"][0]++[email protected](os.name == "nt", reason="POSIX file permissions")[email protected]("already_connected", [False, True])+def test_connect_and_unchanged_refresh_make_existing_file_private(+ tmp_path, already_connected+):+ path = tmp_path / "models.json"+ path.write_text("[]")+ if already_connected:+ vscode.configure(path, URL, "secret", (MODEL,))+ path.chmod(0o644)+ before = path.stat().st_mtime_ns+ assert vscode.configure(path, URL, "secret", (MODEL,)) is not already_connected+ assert stat.S_IMODE(path.stat().st_mode) == 0o600+ if already_connected:+ assert path.stat().st_mtime_ns == before+++ "platform,env,tail",+ [+ ("win32", "APPDATA", "Code/User/chatLanguageModels.json"),+ ("linux", "XDG_CONFIG_HOME", "Code/User/chatLanguageModels.json"),+ (+ "darwin",+ None,+ "Library/Application Support/Code/User/chatLanguageModels.json",+ ),+ ],+)+def test_native_config_paths(tmp_path, monkeypatch, platform, env, tail):+ from free_claude_code.harnesses import claude_integration++ monkeypatch.setattr(claude_integration.sys, "platform", platform)+ monkeypatch.setattr(claude_integration.Path, "home", lambda: tmp_path)+ if env:+ monkeypatch.setenv(env, str(tmp_path))+ assert native_config_path() == tmp_path / tail+++ "effort,preference,no_thinking,expected",+ [+ (effort, "client", False, effort)+ for effort in (None, "none", "low", "medium", "high", "xhigh", "max")+ ]+ + [+ ("high", "off", False, "none"),+ ("none", "high", False, "high"),+ ("high", "high", True, "none"),+ ],+)+def test_native_effort_uses_shared_routing_and_provider_encoders(+ effort, preference, no_thinking, expected+):+ from free_claude_code.application.routing import ModelRouter+ from free_claude_code.config.settings import Settings+ from free_claude_code.core.anthropic.models import MessagesRequest+ from free_claude_code.providers.anthropic_messages.request_policy import (+ MessagesModelCapabilities,+ resolve_messages_options,+ )+ from free_claude_code.providers.nvidia_nim.request_options import (+ build_nim_request_body,+ )++ settings = Settings(REASONING_POLICY=preference)+ model_id = "nvidia_nim/test"+ if no_thinking:+ model_id = "claude-3-freecc-no-thinking/" + model_id+ entry = vscode.model_entry(replace(MODEL, wire_slug=model_id), URL)+ request = MessagesRequest.model_validate(+ {+ "model": entry["id"],+ "max_tokens": entry["maxOutputTokens"],+ "messages": [{"role": "user", "content": "hello"}],+ **({"output_config": {"effort": effort}} if effort is not None else {}),+ }+ )+ routed = ModelRouter(settings).resolve_messages_request(request)+ body = build_nim_request_body(+ routed.request, settings.nim, reasoning=routed.reasoning+ )+ assert body.get("reasoning_effort") == expected+ assert body["max_tokens"] == entry["maxOutputTokens"]+ native = resolve_messages_options(+ model=routed.request.model,+ max_tokens=routed.request.max_tokens,+ reasoning=routed.reasoning,+ capabilities=MessagesModelCapabilities(+ adaptive_thinking="unsupported", supports_output_effort=False+ ),+ )+ assert native.max_tokens == entry["maxOutputTokens"]+ if routed.reasoning.requests_reasoning:+ assert native.thinking is not None+ budget = routed.reasoning.numeric_budget_tokens+ assert budget is not None+ assert native.thinking["budget_tokens"] == max(1024, budget)+ else:+ assert native.thinking is None or native.thinking["type"] == "disabled"+++def test_unchanged_permission_repair_failure_is_not_reported_as_success(+ tmp_path, monkeypatch+):+ path = tmp_path / "models.json"+ vscode.configure(path, URL, "secret", (MODEL,))+ before = path.read_bytes()++ def fail(_path):+ raise PermissionError("permission repair failed")++ monkeypatch.setattr(vscode, "ensure_private_permissions", fail)+ with pytest.raises(PermissionError, match="permission repair"):+ vscode.configure(path, URL, "secret", (MODEL,))+ assert path.read_bytes() == beforediff --git a/tests/runtime/test_vscode_chat_sync.py b/tests/runtime/test_vscode_chat_sync.pynew file mode 100644index 00000000..89e95f74--- /dev/null+++ b/tests/runtime/test_vscode_chat_sync.py@@ -0,0 +1,241 @@+import asyncio+import json+import threading+from unittest.mock import AsyncMock, MagicMock++import pytest+import pytest_asyncio++from free_claude_code.application.model_metadata import ProviderModelInfo+from free_claude_code.config.loader import ManagedConfigStore+from free_claude_code.config.settings import Settings+from free_claude_code.harnesses import vscode_chat_integration as vscode+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+++@pytest_asyncio.fixture+async def runtime(request):+ settings = Settings(+ model="nvidia_nim/one",+ nvidia_nim_api_key="test",+ proxy_auth_token="managed",+ messaging_platform="none",+ )+ provider = MagicMock(spec=BaseProvider)+ provider.list_model_infos = AsyncMock(+ return_value=frozenset({ProviderModelInfo("one")})+ )++ async def construct(*_):+ return provider++ manager = ProviderRuntimeManager(+ settings,+ runtime_factory=lambda s: ProviderRuntime(s, provider_constructor=construct),+ )+ app = ApplicationRuntime(+ manager,+ configuration=ConfigurationService(ManagedConfigStore()),+ transcriber=None,+ )+ if getattr(request, "param", False):+ vscode.configure(vscode.config_path(), "http://127.0.0.1:1", "old", ())+ await app.start()+ try:+ yield app+ finally:+ await app.close()+++async def settle(runtime):+ await runtime.provider_manager.wait_for_catalog()+ task = runtime._vscode_update.task+ if task:+ await asyncio.wait_for(asyncio.shield(task), 5)+++async def test_catalog_updates_connected_file_and_disconnect_stays_removed(runtime):+ await runtime.connect_vscode_chat()+ await settle(runtime)+ path = vscode.config_path()+ runtime.provider_manager.cache_model_infos(+ "nvidia_nim", (ProviderModelInfo("two"),)+ )+ await asyncio.gather(*runtime.provider_manager._publications)+ await settle(runtime)+ models = json.loads(path.read_text())[0]["models"]+ assert {m["id"] for m in models} == {"nvidia_nim/one", "nvidia_nim/two"}+ assert (await runtime.vscode_chat_status())["connected"]+ await runtime.disconnect_vscode_chat()+ runtime._queue_vscode_refresh()+ await settle(runtime)+ assert json.loads(path.read_text()) == []+ assert not (await runtime.vscode_chat_status())["connected"]+++async def test_update_arriving_during_write_is_not_lost(runtime, monkeypatch):+ await runtime.connect_vscode_chat()+ await settle(runtime)+ entered, release = asyncio.Event(), threading.Event()+ loop = asyncio.get_running_loop()+ original = vscode.configure+ calls = 0++ def held(*args, **kwargs):+ nonlocal calls+ calls += 1+ if calls == 1:+ loop.call_soon_threadsafe(entered.set)+ assert release.wait(5)+ return original(*args, **kwargs)++ monkeypatch.setattr(vscode, "configure", held)+ try:+ runtime._queue_vscode_refresh()+ await asyncio.wait_for(entered.wait(), 5)+ runtime.provider_manager.cache_model_infos(+ "nvidia_nim", (ProviderModelInfo("late"),)+ )+ await asyncio.gather(*runtime.provider_manager._publications)+ finally:+ release.set()+ await settle(runtime)+ assert calls >= 2+ assert "nvidia_nim/late" in [+ m["id"] for m in json.loads(vscode.config_path().read_text())[0]["models"]+ ]+++async def test_bad_file_does_not_fail_catalog_and_disconnect_needs_no_catalog(+ runtime, monkeypatch+):+ await settle(runtime)+ path = vscode.config_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("{broken")+ await runtime.refresh_vscode_chat()+ await settle(runtime)+ assert runtime._vscode_update.state == "failed"+ assert runtime.provider_manager.catalog_status()["catalog_file"] == "ready"+ path.unlink()+ await runtime.connect_vscode_chat()+ monkeypatch.setattr(+ runtime.provider_manager,+ "wait_for_catalog",+ AsyncMock(side_effect=AssertionError("Must not wait")),+ )+ assert (await runtime.disconnect_vscode_chat())["connected"] is False+++async def test_disconnected_startup_does_not_create_file(runtime):+ await settle(runtime)+ assert not vscode.config_path().exists()++[email protected]("runtime", [True], indirect=True)+async def test_startup_refreshes_owned_group_and_only_writes_once(runtime):+ await settle(runtime)+ path = vscode.config_path()+ assert (+ json.loads(path.read_text())[0]["models"][0]["requestHeaders"]["x-api-key"]+ == "managed"+ )+ assert json.loads(path.read_text())[0]["models"]+ before = path.stat().st_mtime_ns+ await runtime.refresh_vscode_chat()+ await settle(runtime)+ assert path.stat().st_mtime_ns == before+ assert not runtime._vscode_update.changed+++async def test_disconnect_while_refresh_waits_for_catalog_never_reconnects(+ runtime, monkeypatch+):+ await runtime.connect_vscode_chat()+ await settle(runtime)+ entered, release = asyncio.Event(), asyncio.Event()+ original = runtime.provider_manager.wait_for_catalog++ async def held():+ entered.set()+ await release.wait()+ return await original()++ monkeypatch.setattr(runtime.provider_manager, "wait_for_catalog", held)+ try:+ await runtime.refresh_vscode_chat()+ await asyncio.wait_for(entered.wait(), 5)+ await asyncio.wait_for(runtime.disconnect_vscode_chat(), 5)+ finally:+ release.set()+ await settle(runtime)+ assert json.loads(vscode.config_path().read_text()) == []+++async def test_replaced_generation_cannot_publish_old_url_or_token(+ runtime, monkeypatch+):+ await runtime.connect_vscode_chat()+ await settle(runtime)+ entered, release = asyncio.Event(), asyncio.Event()+ original = runtime.provider_manager.wait_for_catalog+ calls = 0++ async def held():+ nonlocal calls+ snapshot = await original()+ calls += 1+ if calls == 1:+ entered.set()+ await release.wait()+ return snapshot++ monkeypatch.setattr(runtime.provider_manager, "wait_for_catalog", held)+ try:+ await runtime.refresh_vscode_chat()+ await asyncio.wait_for(entered.wait(), 5)+ await runtime.provider_manager.replace(+ runtime.settings.model_copy(+ update={"port": 12345, "proxy_auth_token": "rotated"}+ ),+ commit=AsyncMock(),+ reason="test",+ )+ finally:+ release.set()+ await settle(runtime)+ group = json.loads(vscode.config_path().read_text())[0]+ assert all(m["requestHeaders"] == {"x-api-key": "rotated"} for m in group["models"])+ assert all(+ m["url"] == "http://127.0.0.1:12345/v1/messages" for m in group["models"]+ )+++async def test_codex_publication_failure_does_not_block_vscode(runtime):+ await runtime.connect_vscode_chat()+ await settle(runtime)+ publisher = MagicMock()+ publisher.publish.side_effect = PermissionError("denied")+ runtime.provider_manager._model_catalog_publisher = publisher+ runtime.provider_manager.cache_model_infos(+ "nvidia_nim", (ProviderModelInfo("new"),)+ )+ await asyncio.gather(*runtime.provider_manager._publications)+ await settle(runtime)+ assert runtime.provider_manager.catalog_status()["catalog_file"] == "failed"+ assert runtime._vscode_update.state == "ready"+ assert "nvidia_nim/new" in [+ m["id"] for m in json.loads(vscode.config_path().read_text())[0]["models"]+ ]diff --git a/tests/test_browser_server_shutdown.py b/tests/test_browser_server_shutdown.pynew file mode 100644index 00000000..a6e03c95--- /dev/null+++ b/tests/test_browser_server_shutdown.py@@ -0,0 +1,135 @@+import asyncio+import os+import subprocess+import sys+import threading+from pathlib import Path+from textwrap import dedent++import pytest++from e2e import server_shutdown+from e2e.code_support import CodeControl+++def test_completed_server_needs_no_diagnostics(tmp_path, request, capfd):+ thread = threading.Thread(target=lambda: None)+ thread.start()+ thread.join()+ server_shutdown.join_server(thread, CodeControl(tmp_path), request)+ assert capfd.readouterr().err == ""+++def test_slow_server_finishes_after_diagnostic_threshold(+ tmp_path, request, monkeypatch, capfd+):+ control = CodeControl(tmp_path)+ ready = threading.Event()+ gate = None++ async def serve():+ nonlocal gate+ control.loop = asyncio.get_running_loop()+ gate = asyncio.Event()+ job = asyncio.create_task(gate.wait(), name="pending-code-job")+ control.service._jobs.add(job)+ ready.set()+ await job++ snapshot = server_shutdown._task_snapshot++ def release_after_snapshot(control):+ result = snapshot(control)+ assert gate is not None+ gate.set()+ return result++ monkeypatch.setattr(server_shutdown, "_task_snapshot", release_after_snapshot)+ thread = threading.Thread(target=lambda: asyncio.run(serve()))+ thread.start()+ try:+ assert ready.wait(5)+ server_shutdown.join_server(+ thread, control, request, diagnostic_after=0.01, timeout=5+ )+ assert not thread.is_alive()+ output = capfd.readouterr().err+ assert request.node.nodeid in output+ assert "pending-code-job" in output+ assert "Code jobs: 1" in output+ assert "serve" in output+ finally:+ if thread.is_alive():+ assert control.loop is not None and gate is not None+ control.loop.call_soon_threadsafe(gate.set)+ thread.join(5)++[email protected]("workers", ["0", "1"])[email protected]("extra_failure", [False, True])+def test_shutdown_timeout_stops_later_tests(tmp_path, workers, extra_failure):+ (tmp_path / "pytest.ini").write_text("[pytest]\n", encoding="utf-8")+ (tmp_path / "test_shutdown.py").write_text(+ dedent(f"""+ import asyncio+ import threading+ from pathlib import Path+ import pytest+ from e2e.code_support import CodeControl+ from e2e.server_shutdown import join_server++ @pytest.fixture+ def owner(request, tmp_path):+ def fail_too():+ raise ValueError("additional teardown failure")+ if {extra_failure!r}:+ request.addfinalizer(fail_too)+ control = CodeControl(tmp_path)+ release = threading.Event()+ ready = threading.Event()+ async def serve():+ control.loop = asyncio.get_running_loop()+ ready.set()+ # Deliberately stall the loop so diagnostics cannot answer.+ release.wait()+ thread = threading.Thread(target=lambda: asyncio.run(serve()))+ thread.start()+ assert ready.wait(5)+ yield+ try:+ join_server(thread, control, request,+ diagnostic_after=0.01, timeout=0.05)+ finally:+ release.set()+ thread.join(5)++ def test_a(owner):+ pass++ def test_z():+ Path("later-ran.txt").write_text("ran")+ """),+ encoding="utf-8",+ )+ root = Path(__file__).resolve().parents[1]+ result = subprocess.run(+ [sys.executable, "-m", "pytest", "-p", "xdist.plugin", "-n", workers],+ cwd=tmp_path,+ env={+ **os.environ,+ "PYTHONPATH": os.pathsep.join((str(root), str(root / "src"))),+ "PYTEST_ADDOPTS": "",+ "PYTEST_PLUGINS": "",+ "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1",+ },+ capture_output=True,+ text=True,+ timeout=60,+ )+ output = result.stdout + result.stderr+ assert result.returncode != 0, output+ assert "Admin browser-test server did not stop within" in output+ assert "Server loop did not provide a task snapshot" in output+ if extra_failure:+ assert "additional teardown failure" in output+ assert not (tmp_path / "later-ran.txt").exists(), outputdiff --git a/tests/test_thread_diagnostics.py b/tests/test_thread_diagnostics.pyindex 3b015afa..90979235 100644--- a/tests/test_thread_diagnostics.py+++ b/tests/test_thread_diagnostics.py@@ -59,15 +59,48 @@ class DiagnosticOutput(io.StringIO):self.flushed.set()+def _diagnostic_probe():+ """Trace the real helper in a child the parent can always kill and reap."""+ from e2e import thread_diagnostics++ current_frames = sys._current_frames+ print_stack = thread_diagnostics.traceback.print_stack++ def traced_frames():+ print("diagnostic: acquiring frames", flush=True)+ frames = current_frames()+ print("diagnostic: acquired frames", flush=True)+ return frames++ def traced_stack(frame, *, file):+ print("diagnostic: formatting stack", flush=True)+ print_stack(frame, file=file)+ print("diagnostic: formatted stack", flush=True)++ with pytest.MonkeyPatch.context() as patcher:+ patcher.setattr(sys, "_current_frames", traced_frames)+ patcher.setattr(thread_diagnostics.traceback, "print_stack", traced_stack)+ output = DiagnosticOutput()+ with dump_threads_after(0.001, output, "slow-test"):+ assert output.flushed.wait(5)+ print("diagnostic: flushed", flush=True)+ assert "slow-test" in output.getvalue()+ assert "_diagnostic_probe" in output.getvalue()+ print("diagnostic: joining", flush=True)+ print("diagnostic: joined", flush=True)+ assert not any(t.name == "fcc-test-diagnostics" for t in threading.enumerate())++def test_slow_test_reports_stacks_without_interrupting_execution():- output = DiagnosticOutput()- with dump_threads_after(0.001, output, "slow-test"):- assert output.flushed.wait(5)- assert "slow-test" in output.getvalue()- assert "test_slow_test_reports_stacks_without_interrupting_execution" in (- output.getvalue()- )- assert not any(t.name == "fcc-test-diagnostics" for t in threading.enumerate())+ script = "import runpy, sys; runpy.run_path(sys.argv[1])['_diagnostic_probe']()"+ result = subprocess.run(+ [sys.executable, "-c", script, __file__],+ capture_output=True,+ text=True,+ timeout=15,+ )+ assert result.returncode == 0, result.stdout + result.stderr+ assert "diagnostic: joined" in result.stdout@pytest.mark.parametrize("fails", [False, True])