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
patch: disconnect FCC editor integrations before uninstalling (#2072)
FengCiec10cafdb0aa
diff --git a/README.md b/README.mdindex 1c76eeb7..0c60e56b 100644--- a/README.md+++ b/README.md@@ -504,7 +504,16 @@ Uninstalling FCC leaves Muse Code installed.### Uninstall-Stop every running FCC command before uninstalling.+Stop every running FCC command and quit connected desktop/editor apps before uninstalling.+The uninstaller disconnects recognized FCC integrations before removing the tool,+preserving unrelated application settings. If cleanup fails, FCC and `~/.fcc/`+remain available so you can correct the problem and retry.+You can also run `fcc-doctor --disconnect-integrations` separately.+If a VS Code gateway's address or token no longer matches FCC's current settings,+cleanup stops without changing that connection; disconnect it manually before retrying.+For older FCC versions without this command, update first or disconnect through+Admin, then use `--keep-integrations` (PowerShell: `-KeepIntegrations`) to skip+automatic cleanup. This option intentionally leaves application settings unchanged.**Removes**diff --git a/scripts/uninstall.ps1 b/scripts/uninstall.ps1index e9a28297..6e50b2b7 100644--- a/scripts/uninstall.ps1+++ b/scripts/uninstall.ps1@@ -1,5 +1,6 @@param([switch] $DryRun,+ [switch] $KeepIntegrations,[switch] $Help,[Parameter(ValueFromRemainingArguments = $true)][object[]] $RemainingArgs = @()@@ -41,6 +42,7 @@ Does not remove uv, Claude Code, Codex, Pi, OpenCode, Cline, Hermes Agent, DeepSOptions:-DryRun Print commands without running them.+ -KeepIntegrations Leave editor/app integrations unchanged.-Help Show this help text."@}@@ -199,6 +201,35 @@ function Uninstall-FreeClaudeCode {throw "uv tool uninstall $PackageName failed with exit code $($result.ExitCode); ~/.fcc was not deleted."}+function Disconnect-FccIntegrations {+ if ($KeepIntegrations) {+ return+ }+ if ($DryRun) {+ Write-Host "+ fcc-doctor --disconnect-integrations"+ return+ }+ $doctorPath = $null+ foreach ($extension in @(".exe", ".cmd", ".bat", "")) {+ $candidate = Join-Path $script:UvToolBin "fcc-doctor$extension"+ if (Test-Path -LiteralPath $candidate -PathType Leaf) {+ $doctorPath = $candidate+ break+ }+ }+ if (-not $doctorPath) {+ throw "FCC's integration cleanup command is unavailable. Update FCC first, or disconnect editor/app integrations manually and rerun with -KeepIntegrations. FCC data was not deleted."+ }+ Write-Host "+ $(Format-Command -FilePath $doctorPath -Arguments @('--disconnect-integrations'))"+ $result = Invoke-NativeResult -FilePath $doctorPath -Arguments @("--disconnect-integrations")+ if (-not [string]::IsNullOrWhiteSpace($result.Output)) {+ Write-Host $result.Output+ }+ if ($result.ExitCode -ne 0) {+ throw "Editor/app integration cleanup failed. Correct the reported problem and retry. For older FCC versions, update first or disconnect manually and rerun with -KeepIntegrations. FCC and its data were not deleted."+ }+}+function Confirm-FccCommandsRemoved {if ($DryRun) {Write-Host "+ verify all Free Claude Code entry points are absent from the uv tool bin directory"@@ -324,6 +355,9 @@ Assert-NoFccProcessesRunningWrite-Step "Locating the uv-managed Free Claude Code installation"Initialize-UvContext+Write-Step "Disconnecting FCC editor/app integrations"+Disconnect-FccIntegrations+Write-Step "Removing the Free Claude Code uv tool"Uninstall-FreeClaudeCodediff --git a/scripts/uninstall.sh b/scripts/uninstall.shindex 701af612..79c3f4cf 100644--- a/scripts/uninstall.sh+++ b/scripts/uninstall.sh@@ -9,6 +9,7 @@ FCC_MACOS_OWNER_FILE=".free-claude-code-owner"FCC_COMMANDS="fcc-desktop fcc-server fcc-claude fcc-codex fcc-pi fcc-opencode fcc-cline fcc-hermes fcc-dsh fcc-grok fcc-muse fcc-aider fcc-doctor fcc-update fcc-init free-claude-code"dry_run=0+keep_integrations=0uv_tool_bin=""show_usage() {@@ -20,6 +21,7 @@ Does not remove uv, Claude Code, Codex, Pi, OpenCode, Cline, Hermes Agent, DeepSOptions:--dry-run Print commands without running them.+ --keep-integrations Leave editor/app integrations unchanged.--help Show this help text.USAGE}@@ -184,6 +186,23 @@ uninstall_free_claude_code() {fail "uv tool uninstall $PACKAGE_NAME failed with exit code $status; ~/.fcc was not deleted."}+disconnect_integrations() {+ [ "$keep_integrations" -eq 0 ] || return 0+ if [ "$dry_run" -eq 1 ]; then+ print_command fcc-doctor --disconnect-integrations+ return 0+ fi+ doctor="$uv_tool_bin/fcc-doctor"+ if [ ! -x "$doctor" ]; then+ fail "FCC's integration cleanup command is unavailable. Update FCC first, or disconnect editor/app integrations manually and rerun with --keep-integrations. FCC data was not deleted."+ fi+ print_command "$doctor" --disconnect-integrations+ if "$doctor" --disconnect-integrations; then+ return 0+ fi+ fail "Editor/app integration cleanup failed. Correct the reported problem and retry. For older FCC versions, update first or disconnect manually and rerun with --keep-integrations. FCC and its data were not deleted."+}+verify_fcc_commands_removed() {if [ "$dry_run" -eq 1 ]; thenprintf '+ verify all Free Claude Code entry points are absent from the uv tool bin directory\n'@@ -262,6 +281,9 @@ parse_args() {--dry-run)dry_run=1;;+ --keep-integrations)+ keep_integrations=1+ ;;--help|-h)show_usageexit 0@@ -284,6 +306,9 @@ assert_no_fcc_processes_runningstep "Locating the uv-managed Free Claude Code installation"initialize_uv_context+step "Disconnecting FCC editor/app integrations"+disconnect_integrations+step "Removing the Free Claude Code uv tool"uninstall_free_claude_codediff --git a/smoke/installers/test_uninstallers.py b/smoke/installers/test_uninstallers.pyindex ca1c1ba5..6066f68b 100644--- a/smoke/installers/test_uninstallers.py+++ b/smoke/installers/test_uninstallers.py@@ -45,11 +45,13 @@ def _create_windows_shortcut(powershell: str,shortcut_path: Path,target_path: Path,+ module_path: str,) -> None:shortcut_path.parent.mkdir(parents=True, exist_ok=True)env = os.environ | {"FCC_TEST_SHORTCUT": str(shortcut_path),"FCC_TEST_TARGET": str(target_path),+ "PSMODULEPATH": module_path,}subprocess.run([@@ -84,10 +86,13 @@ class PosixUninstallHarness:*args: str,fail_step: str = "",include_uv: bool = True,+ include_doctor: bool = True,) -> subprocess.CompletedProcess[str]:uv = self.bin_dir / "uv"if not include_uv and uv.exists():uv.unlink()+ if not include_doctor:+ (self.tool_bin / "fcc-doctor").unlink(missing_ok=True)return subprocess.run(["/bin/sh", str(_repo_root() / "scripts" / "uninstall.sh"), *args],check=False,@@ -117,7 +122,11 @@ printf '%s\n' "$FCC_PS_OUTPUT"awk = shutil.which("awk", path=self.env["PATH"])if awk is None:pytest.skip("awk is required for the POSIX process fallback scenario")- shutil.copy(awk, fallback_bin / "awk")+ _write_executable(+ fallback_bin / "awk",+ '#!/bin/sh\nexec "$FCC_TEST_AWK" "$@"\n',+ )+ self.env["FCC_TEST_AWK"] = awkself.env["FCC_PS_OUTPUT"] = process_lineself.env["PATH"] = str(fallback_bin)@@ -137,6 +146,22 @@ def posix_uninstall_harness(tmp_path: Path) -> PosixUninstallHarness:(fcc_home / "config.json").write_text("{}", encoding="utf-8")for name in FCC_COMMANDS:_write_executable(tool_bin / name, "#!/bin/sh\nexit 0\n")+ _write_executable(+ tool_bin / "fcc-doctor",+ """#!/bin/sh+echo "doctor:$*" >> "$CALL_LOG"+[ "$*" = "--disconnect-integrations" ] || exit 45+if [ "$FAIL_STEP" = "cleanup" ]; then+ echo "simulated integration cleanup failure" >&2+ exit 46+fi+if [ "$FAIL_STEP" = "legacy-helper" ]; then+ echo "unrecognized arguments: --disconnect-integrations" >&2+ exit 2+fi+echo "Disconnected recognized FCC editor/app integrations."+""",+ )_write_executable(bin_dir / "claude", "#!/bin/sh\nexit 0\n")_write_executable(bin_dir / "codex", "#!/bin/sh\nexit 0\n")@@ -298,6 +323,7 @@ def test_uninstall_sh_removes_and_verifies_only_fcc().read_text(encoding="utf-8") == '{"native": true}\n'assert posix_uninstall_harness.calls() == ["uv:tool dir --bin",+ "doctor:--disconnect-integrations","uv:tool uninstall free-claude-code",f"rm:-f {posix_uninstall_harness.home / 'Desktop' / 'Free Claude Code.app'}",f"rm:-rf {posix_uninstall_harness.home / 'Applications' / 'Free Claude Code.app'}",@@ -310,11 +336,71 @@ def test_uninstall_sh_is_idempotent_when_tool_is_already_absent() -> None:posix_uninstall_harness.remove_entry_points()- result = posix_uninstall_harness.run(fail_step="missing")+ result = posix_uninstall_harness.run("--keep-integrations", fail_step="missing")assert result.returncode == 0, result.stderrassert not posix_uninstall_harness.fcc_home.exists()assert "already absent" in result.stdout+ assert not any(+ call.startswith("doctor:") for call in posix_uninstall_harness.calls()+ )++[email protected]("failure", ["cleanup", "legacy-helper", "missing-helper"])+def test_uninstall_sh_preserves_tool_and_config_when_cleanup_is_unconfirmed(+ posix_uninstall_harness: PosixUninstallHarness,+ failure: str,+) -> None:+ before = (posix_uninstall_harness.fcc_home / "config.json").read_bytes()++ result = posix_uninstall_harness.run(+ fail_step=failure, include_doctor=failure != "missing-helper"+ )++ assert result.returncode != 0+ assert "--keep-integrations" in result.stderr+ assert (posix_uninstall_harness.fcc_home / "config.json").read_bytes() == before+ assert all(+ (posix_uninstall_harness.tool_bin / name).exists()+ for name in FCC_COMMANDS+ if name != "fcc-doctor" or failure != "missing-helper"+ )+ assert posix_uninstall_harness.calls() == ["uv:tool dir --bin"] + (+ [] if failure == "missing-helper" else ["doctor:--disconnect-integrations"]+ )+ assert "Free Claude Code has been removed and verified." not in result.stdout+++def test_uninstall_sh_can_explicitly_keep_integrations_without_cleanup_helper(+ posix_uninstall_harness: PosixUninstallHarness,+) -> None:+ result = posix_uninstall_harness.run("--keep-integrations", include_doctor=False)++ assert result.returncode == 0, result.stderr+ assert not posix_uninstall_harness.fcc_home.exists()+ assert all(+ not (posix_uninstall_harness.tool_bin / name).exists() for name in FCC_COMMANDS+ )+ assert posix_uninstall_harness.calls()[:2] == [+ "uv:tool dir --bin",+ "uv:tool uninstall free-claude-code",+ ]+ assert not any(+ call.startswith("doctor:") for call in posix_uninstall_harness.calls()+ )+++def test_uninstall_sh_does_not_purge_when_tool_and_cleanup_helper_are_absent(+ posix_uninstall_harness: PosixUninstallHarness,+) -> None:+ posix_uninstall_harness.remove_entry_points()++ result = posix_uninstall_harness.run(fail_step="missing")++ assert result.returncode != 0+ assert posix_uninstall_harness.fcc_home.exists()+ assert "--keep-integrations" in result.stderr+ assert posix_uninstall_harness.calls() == ["uv:tool dir --bin"]def test_uninstall_sh_preserves_unrelated_macos_desktop_link(@@ -402,17 +488,22 @@ def test_uninstall_sh_reports_purge_failure_after_verified_tool_removal(assert "Free Claude Code has been removed and verified." not in result.stdout[email protected]("include_doctor", [True, False])def test_uninstall_sh_dry_run_is_non_mutating(posix_uninstall_harness: PosixUninstallHarness,+ include_doctor: bool,) -> None:- result = posix_uninstall_harness.run("--dry-run")+ result = posix_uninstall_harness.run("--dry-run", include_doctor=include_doctor)assert result.returncode == 0, result.stderrassert posix_uninstall_harness.fcc_home.exists()assert all(- (posix_uninstall_harness.tool_bin / name).exists() for name in FCC_COMMANDS+ (posix_uninstall_harness.tool_bin / name).exists()+ for name in FCC_COMMANDS+ if name != "fcc-doctor" or include_doctor)assert posix_uninstall_harness.calls() == []+ assert "fcc-doctor --disconnect-integrations" in result.stdoutassert "Dry run complete. No changes were made." in result.stdout@@ -482,11 +573,15 @@ class PowerShellUninstallHarness:*,fail_step: str = "",include_uv: bool = True,+ include_doctor: bool = True,dry_run: bool = False,+ keep_integrations: bool = False,) -> subprocess.CompletedProcess[str]:uv = self.bin_dir / "uv.cmd"if not include_uv and uv.exists():uv.unlink()+ if not include_doctor:+ (self.tool_bin / "fcc-doctor.cmd").unlink(missing_ok=True)return subprocess.run([self.powershell,@@ -503,6 +598,7 @@ class PowerShellUninstallHarness:| {"FAIL_STEP": fail_step,"UNINSTALL_DRY_RUN": "1" if dry_run else "0",+ "UNINSTALL_KEEP_INTEGRATIONS": "1" if keep_integrations else "0",},)@@ -543,6 +639,23 @@ def powershell_uninstall_harness((tool_bin / f"{name}.cmd").write_text("@echo off\nexit /b 0\n", encoding="utf-8")+ (tool_bin / "fcc-doctor.cmd").write_text(+ r"""@echo off+echo doctor:%*>>"%CALL_LOG%"+if not "%*"=="--disconnect-integrations" exit /b 55+if "%FAIL_STEP%"=="cleanup" (+ echo simulated integration cleanup failure 1>&2+ exit /b 56+)+if "%FAIL_STEP%"=="legacy-helper" (+ echo unrecognized arguments: --disconnect-integrations 1>&2+ exit /b 2+)+echo Disconnected recognized FCC editor/app integrations.+exit /b 0+""",+ encoding="utf-8",+ )for name in ("claude","codex",@@ -579,13 +692,25 @@ if "%1"=="tool" if "%2"=="dir" if "%3"=="--bin" goto tool_binif "%1"=="tool" if "%2"=="uninstall" goto uninstallexit /b 53:tool_bin-if "%FAIL_STEP%"=="tool-dir" echo tool directory unavailable 1>&2 & exit /b 51+if "%FAIL_STEP%"=="tool-dir" (+ echo tool directory unavailable 1>&2+ exit /b 51+)echo %FAKE_TOOL_BIN%exit /b 0:uninstall-if "%FAIL_STEP%"=="uninstall" echo permission denied while removing tool 1>&2 & exit /b 52-if "%FAIL_STEP%"=="missing" echo Tool `free-claude-code` is not installed 1>&2 & exit /b 2-if "%FAIL_STEP%"=="stale-entrypoint" echo Tool `free-claude-code` is not installed 1>&2 & exit /b 2+if "%FAIL_STEP%"=="uninstall" (+ echo permission denied while removing tool 1>&2+ exit /b 52+)+if "%FAIL_STEP%"=="missing" (+ echo Tool `free-claude-code` is not installed 1>&2+ exit /b 2+)+if "%FAIL_STEP%"=="stale-entrypoint" (+ echo Tool `free-claude-code` is not installed 1>&2+ exit /b 2+)for %%C in ({uv_commands}) do del /q "%FAKE_TOOL_BIN%\%%C.cmd" 2>nulecho Uninstalled free-claude-codeexit /b 0@@ -627,12 +752,14 @@ function Get-Process {}}$installer = [scriptblock]::Create([IO.File]::ReadAllText($env:FCC_UNINSTALLER))+$uninstallOptions = @{}if ($env:UNINSTALL_DRY_RUN -eq "1") {- & $installer -DryRun+ $uninstallOptions.DryRun = $true}-else {- & $installer+if ($env:UNINSTALL_KEEP_INTEGRATIONS -eq "1") {+ $uninstallOptions.KeepIntegrations = $true}+& $installer @uninstallOptions""",encoding="utf-8",)@@ -651,6 +778,7 @@ else {powershell,shortcut,tool_bin / "fcc-desktop.cmd",+ powershell_module_paths[powershell],)system_root = os.environ["SYSTEMROOT"]@@ -672,6 +800,7 @@ else {"FCC_RUNNING_COMMAND": "","FAIL_STEP": "","UNINSTALL_DRY_RUN": "0",+ "UNINSTALL_KEEP_INTEGRATIONS": "0",})return PowerShellUninstallHarness(@@ -722,6 +851,7 @@ def test_uninstall_ps1_removes_and_verifies_only_fcc().read_text(encoding="utf-8") == '{"native": true}\n'assert powershell_uninstall_harness.calls() == ["uv:tool dir --bin",+ "doctor:--disconnect-integrations","uv:tool uninstall free-claude-code",f"remove:{Path(powershell_uninstall_harness.env['USERPROFILE']) / 'Desktop' / 'Free Claude Code.lnk'}",f"remove:{Path(powershell_uninstall_harness.env['APPDATA']) / 'Microsoft' / 'Windows' / 'Start Menu' / 'Programs' / 'Free Claude Code.lnk'}",@@ -743,6 +873,7 @@ def test_uninstall_ps1_preserves_unowned_desktop_shortcut(powershell_uninstall_harness.powershell,desktop_shortcut,unrelated_target,+ powershell_uninstall_harness.env["PSMODULEPATH"],)original_shortcut = desktop_shortcut.read_bytes()@@ -758,11 +889,78 @@ def test_uninstall_ps1_is_idempotent_when_tool_is_already_absent() -> None:powershell_uninstall_harness.remove_entry_points()- result = powershell_uninstall_harness.run(fail_step="missing")+ result = powershell_uninstall_harness.run(+ fail_step="missing", keep_integrations=True+ )assert result.returncode == 0, result.stderrassert not powershell_uninstall_harness.fcc_home.exists()assert "already absent" in result.stdout+ assert not any(+ call.startswith("doctor:") for call in powershell_uninstall_harness.calls()+ )++[email protected]("failure", ["cleanup", "legacy-helper", "missing-helper"])+def test_uninstall_ps1_preserves_tool_and_config_when_cleanup_is_unconfirmed(+ powershell_uninstall_harness: PowerShellUninstallHarness,+ failure: str,+) -> None:+ before = (powershell_uninstall_harness.fcc_home / "config.json").read_bytes()++ result = powershell_uninstall_harness.run(+ fail_step=failure, include_doctor=failure != "missing-helper"+ )++ assert result.returncode != 0+ assert "-KeepIntegrations" in result.stderr+ assert (+ powershell_uninstall_harness.fcc_home / "config.json"+ ).read_bytes() == before+ assert all(+ (powershell_uninstall_harness.tool_bin / f"{name}.cmd").exists()+ for name in FCC_COMMANDS+ if name != "fcc-doctor" or failure != "missing-helper"+ )+ assert powershell_uninstall_harness.calls() == ["uv:tool dir --bin"] + (+ [] if failure == "missing-helper" else ["doctor:--disconnect-integrations"]+ )+ assert "Free Claude Code has been removed and verified." not in result.stdout+++def test_uninstall_ps1_can_explicitly_keep_integrations_without_cleanup_helper(+ powershell_uninstall_harness: PowerShellUninstallHarness,+) -> None:+ result = powershell_uninstall_harness.run(+ keep_integrations=True, include_doctor=False+ )++ assert result.returncode == 0, result.stderr+ assert not powershell_uninstall_harness.fcc_home.exists()+ assert all(+ not (powershell_uninstall_harness.tool_bin / f"{name}.cmd").exists()+ for name in FCC_COMMANDS+ )+ assert powershell_uninstall_harness.calls()[:2] == [+ "uv:tool dir --bin",+ "uv:tool uninstall free-claude-code",+ ]+ assert not any(+ call.startswith("doctor:") for call in powershell_uninstall_harness.calls()+ )+++def test_uninstall_ps1_does_not_purge_when_tool_and_cleanup_helper_are_absent(+ powershell_uninstall_harness: PowerShellUninstallHarness,+) -> None:+ powershell_uninstall_harness.remove_entry_points()++ result = powershell_uninstall_harness.run(fail_step="missing")++ assert result.returncode != 0+ assert powershell_uninstall_harness.fcc_home.exists()+ assert "-KeepIntegrations" in result.stderr+ assert powershell_uninstall_harness.calls() == ["uv:tool dir --bin"]@pytest.mark.parametrize("failure", ["tool-dir", "uninstall", "stale-entrypoint"])@@ -805,18 +1003,24 @@ def test_uninstall_ps1_reports_purge_failure_after_verified_tool_removal(assert "Free Claude Code has been removed and verified." not in result.stdout[email protected]("include_doctor", [True, False])def test_uninstall_ps1_dry_run_is_non_mutating(powershell_uninstall_harness: PowerShellUninstallHarness,+ include_doctor: bool,) -> None:- result = powershell_uninstall_harness.run(dry_run=True)+ result = powershell_uninstall_harness.run(+ dry_run=True, include_doctor=include_doctor+ )assert result.returncode == 0, result.stderrassert powershell_uninstall_harness.fcc_home.exists()assert all((powershell_uninstall_harness.tool_bin / f"{name}.cmd").exists()for name in FCC_COMMANDS+ if name != "fcc-doctor" or include_doctor)assert powershell_uninstall_harness.calls() == []+ assert "fcc-doctor --disconnect-integrations" in result.stdoutassert "Dry run complete. No changes were made." in result.stdoutdiff --git a/src/free_claude_code/cli/doctor.py b/src/free_claude_code/cli/doctor.pyindex 6c099436..04731b0d 100644--- a/src/free_claude_code/cli/doctor.py+++ b/src/free_claude_code/cli/doctor.py@@ -11,10 +11,29 @@ from .clipboard import ClipboardUnavailable, copy_textdef main(argv: Sequence[str] | None = None) -> None:- argparse.ArgumentParser(+ parser = argparse.ArgumentParser(prog="fcc-doctor",description="Print and copy FCC diagnostics for a bug report.",- ).parse_args(argv)+ )+ parser.add_argument(+ "--disconnect-integrations",+ action="store_true",+ help="Disconnect recognized FCC editor/app integrations before uninstalling.",+ )+ args = parser.parse_args(argv)+ if args.disconnect_integrations:+ from free_claude_code.harnesses.integration_cleanup import (+ IntegrationCleanupError,+ disconnect_integrations,+ )++ try:+ disconnect_integrations()+ except IntegrationCleanupError as exc:+ print(str(exc), file=sys.stderr)+ raise SystemExit(1) from None+ print("Disconnected recognized FCC editor/app integrations.")+ returntext = json.dumps(collect_report(), indent=2, ensure_ascii=False) + "\n"sys.stdout.write(text)try:diff --git a/src/free_claude_code/harnesses/claude_integration.py b/src/free_claude_code/harnesses/claude_integration.pyindex c976bf5c..65ed707f 100644--- a/src/free_claude_code/harnesses/claude_integration.py+++ b/src/free_claude_code/harnesses/claude_integration.py@@ -105,6 +105,51 @@ def refresh_connected(path: Path, proxy_root_url: str, auth_token: str) -> bool:return _connect(path, document, entries, values)+def _disconnect(+ path: Path, document: JsonObject, entries: list[JsonObject], values: dict[str, str]+) -> None:+ before = json.dumps(document, allow_nan=False)+ document.pop(_LOGIN, None)+ retained = [entry for entry in entries if entry["name"] not in values]+ if len(retained) != len(entries):+ if retained:+ document[_ENV] = retained+ else:+ document.pop(_ENV, None)+ if json.dumps(document, allow_nan=False) != before:+ atomic_write_text(path, json.dumps(document, indent=2, allow_nan=False) + "\n")+++def disconnect_existing(+ path: Path, proxy_root_url: str | None, auth_token: str | None+) -> bool:+ """Remove a recognized connection; stop cleanup when ownership is uncertain."""+ path = path.resolve()+ values = claude_proxy_values(proxy_root_url or "", auth_token or "")+ document, entries = _read(path, set(values))+ environment = {entry["name"]: entry["value"] for entry in entries}+ matching_url = proxy_root_url is not None and same_proxy_url(+ environment.get("ANTHROPIC_BASE_URL"), proxy_root_url+ )+ matching_token = (+ auth_token is not None and environment.get("ANTHROPIC_AUTH_TOKEN") == auth_token+ )+ # Login and discovery preferences can change without changing the gateway.+ if matching_url and matching_token:+ _disconnect(path, document, entries, values)+ return True+ if (+ matching_url+ or matching_token+ or (+ document.get(_LOGIN) is True+ and environment.get("CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY") == "1"+ )+ ):+ raise ValueError("Existing gateway connection identity cannot be confirmed")+ return False++def configure(path: Path,proxy_root_url: str,@@ -118,18 +163,7 @@ def configure(if connected is True:_connect(path, document, entries, values)elif connected is False:- before = json.dumps(document, allow_nan=False)- document.pop(_LOGIN, None)- retained = [entry for entry in entries if entry["name"] not in values]- if len(retained) != len(entries):- if retained:- document[_ENV] = retained- else:- document.pop(_ENV, None)- if json.dumps(document, allow_nan=False) != before:- atomic_write_text(- path, json.dumps(document, indent=2, allow_nan=False) + "\n"- )+ _disconnect(path, document, entries, values)if connected is not None:document, entries = _read(path, set(values))result: JsonObject = {"connected": _connected(document, entries, values)}diff --git a/src/free_claude_code/harnesses/integration_cleanup.py b/src/free_claude_code/harnesses/integration_cleanup.pynew file mode 100644index 00000000..6fdf9cf0--- /dev/null+++ b/src/free_claude_code/harnesses/integration_cleanup.py@@ -0,0 +1,148 @@+"""Disconnect native integrations before removing FCC's installed commands."""++import os+from collections.abc import Callable+from dataclasses import dataclass+from pathlib import Path++from free_claude_code.config.env_files import dotenv_values_from_file+from free_claude_code.config.loader import compose_settings_snapshot+from free_claude_code.config.paths import (+ claude_desktop_disconnect_path,+ codex_model_catalog_path,+ managed_env_path,+)+from free_claude_code.config.server_urls import local_proxy_root_url+from free_claude_code.config.settings import Settings+from free_claude_code.harnesses import (+ claude_desktop_integration,+ claude_integration,+ codex_integration,+ dsh_desktop_integration,+ jetbrains_acp_integration,+ vscode_chat_integration,+)+++class IntegrationCleanupError(RuntimeError):+ """One local connection cannot safely be removed before uninstalling."""+++@dataclass(frozen=True)+class IntegrationPaths:+ env: Path+ claude_vscode: Path+ vscode_chat: Path+ codex: Path+ codex_catalog: Path+ jetbrains: Path+ desktop: Path+ desktop_disconnect: Path+ dsh: Path++ @classmethod+ def current(cls) -> IntegrationPaths:+ return cls(+ managed_env_path(),+ claude_integration.settings_path(),+ vscode_chat_integration.config_path(),+ codex_integration.config_path(),+ codex_model_catalog_path(),+ jetbrains_acp_integration.config_path(),+ claude_desktop_integration.config_root(),+ claude_desktop_disconnect_path(),+ dsh_desktop_integration.config_home(),+ )+++def _path_exists(path: Path) -> bool:+ """Treat missing paths as absent, but let access failures stop uninstall."""+ try:+ path.stat()+ except FileNotFoundError:+ return False+ return True+++def _connection_settings(path: Path) -> Settings | None:+ if not _path_exists(path):+ return None+ # Cleanup must also work when an unrelated provider or model setting is invalid.+ keys = {"HOST", "PORT", "ANTHROPIC_AUTH_TOKEN"}+ managed = {+ key: value+ for key, value in dotenv_values_from_file(path).items()+ if key in keys+ }+ process = {key: value for key, value in os.environ.items() if key in keys}+ return compose_settings_snapshot(managed, process).settings+++def disconnect_integrations(paths: IntegrationPaths | None = None) -> None:+ """Reuse each connection owner without starting a server or contacting providers.++ A failed operation leaves the installed tool and its recovery data available.+ Earlier operations are idempotent, so uninstall can safely retry.+ """+ paths = paths or IntegrationPaths.current()+ try:+ settings = _connection_settings(paths.env)+ except OSError, ValueError:+ raise IntegrationCleanupError(+ "Could not read FCC's connection settings. Correct the managed config "+ "or disconnect the integrations manually before uninstalling."+ ) from None+ url = local_proxy_root_url(settings) if settings is not None else None+ token = settings.proxy_auth_token if settings is not None else None+ operations: tuple[tuple[str, Callable[[], object]], ...] = (+ (+ "Claude Code in VS Code",+ lambda: claude_integration.disconnect_existing(+ paths.claude_vscode, url, token+ ),+ ),+ ("VS Code chat", lambda: vscode_chat_integration.disconnect(paths.vscode_chat)),+ (+ "Codex",+ lambda: codex_integration.configure(+ paths.codex, paths.codex_catalog, url or "", False+ ),+ ),+ (+ "JetBrains ACP",+ lambda: jetbrains_acp_integration.configure(+ paths.jetbrains, url or "", token or "", False+ ),+ ),+ (+ "Claude Desktop",+ lambda: (+ claude_desktop_integration.configure(+ paths.desktop,+ url or "",+ token or "",+ False,+ disconnect_path=paths.desktop_disconnect,+ )+ if _path_exists(paths.desktop) or _path_exists(paths.desktop_disconnect)+ else None+ ),+ ),+ (+ "DSH Desktop",+ lambda: (+ dsh_desktop_integration.disconnect(paths.dsh)+ if _path_exists(paths.dsh)+ else None+ ),+ ),+ )+ for name, operation in operations:+ try:+ operation()+ except OSError, ValueError:+ raise IntegrationCleanupError(+ f"Could not disconnect {name}. Check its local settings and permissions, "+ "close the app, then retry. If its connection details changed, disconnect "+ "it manually first. FCC and its recovery data were not removed."+ ) from Nonediff --git a/tests/cli/test_doctor.py b/tests/cli/test_doctor.pyindex 55c4e9c9..43dbb6d4 100644--- a/tests/cli/test_doctor.py+++ b/tests/cli/test_doctor.py@@ -445,3 +445,39 @@ def test_fallback_model_efforts_are_json_serializable_in_doctor_report():]assert report["providers"]["groq"]["referenced"] is Trueassert report["providers"]["open_router"]["referenced"] is True+++def test_disconnect_mode_does_not_collect_or_copy_diagnostics(monkeypatch, capsys):+ from free_claude_code.harnesses import integration_cleanup++ calls = []+ monkeypatch.setattr(+ integration_cleanup,+ "disconnect_integrations",+ lambda: calls.append("disconnect"),+ )++ def forbidden(*args):+ pytest.fail("cleanup must not collect diagnostics or use the clipboard")++ monkeypatch.setattr(doctor, "collect_report", forbidden)+ monkeypatch.setattr(doctor, "copy_text", forbidden)+ doctor.main(["--disconnect-integrations"])+ assert calls == ["disconnect"]+ assert capsys.readouterr() == (+ "Disconnected recognized FCC editor/app integrations.\n",+ "",+ )+++def test_disconnect_mode_reports_failure_and_nonzero_exit(monkeypatch, capsys):+ from free_claude_code.harnesses import integration_cleanup++ def fail():+ raise integration_cleanup.IntegrationCleanupError("Could not disconnect Codex.")++ monkeypatch.setattr(integration_cleanup, "disconnect_integrations", fail)+ with pytest.raises(SystemExit) as error:+ doctor.main(["--disconnect-integrations"])+ assert error.value.code == 1+ assert capsys.readouterr() == ("", "Could not disconnect Codex.\n")diff --git a/tests/harnesses/test_integration_cleanup.py b/tests/harnesses/test_integration_cleanup.pynew file mode 100644index 00000000..6577e958--- /dev/null+++ b/tests/harnesses/test_integration_cleanup.py@@ -0,0 +1,372 @@+import genericpath+import json+import os+import tomllib+from pathlib import Path++import pytest++from free_claude_code.harnesses import (+ claude_desktop_integration,+ claude_integration,+ codex_integration,+ vscode_chat_integration,+)+from free_claude_code.harnesses.dsh_config import DSH_PROVIDER_ID+from free_claude_code.harnesses.integration_cleanup import (+ IntegrationCleanupError,+ IntegrationPaths,+ disconnect_integrations,+)++URL = "http://127.0.0.1:8082"+TOKEN = "cleanup-test-token"+++def paths_at(root: Path) -> IntegrationPaths:+ return IntegrationPaths(+ root / "fcc/.env",+ root / "vscode/settings.json",+ root / "vscode/chatLanguageModels.json",+ root / "codex/config.toml",+ root / "fcc/catalog.json",+ root / "jetbrains/acp.json",+ root / "desktop",+ root / "fcc/desktop-disconnect.json",+ root / "dsh",+ )+++def paths(tmp_path, monkeypatch):+ paths = paths_at(tmp_path)+ paths.env.parent.mkdir()+ paths.env.write_text(f"PORT=8082\nANTHROPIC_AUTH_TOKEN={TOKEN}\nMODEL=invalid\n")+ for key in ("HOST", "PORT", "ANTHROPIC_AUTH_TOKEN"):+ monkeypatch.delenv(key, raising=False)+ monkeypatch.setattr(claude_desktop_integration, "check_unmanaged", lambda: None)+ return paths+++def test_cleanup_disconnects_native_connections_and_preserves_unrelated_settings(paths):+ paths.claude_vscode.parent.mkdir()+ paths.claude_vscode.write_text('{"editor.fontSize": 17}')+ claude_integration.configure(paths.claude_vscode, URL, TOKEN, True)+ paths.codex.parent.mkdir()+ paths.codex.write_text(+ '# Keep comment\nmodel="my-model"\n[model_providers.other]\nname="Other"\n'+ )+ codex_integration.configure(paths.codex, paths.codex_catalog, URL, True)+ paths.vscode_chat.write_text('[{"vendor":"other","name":"Keep"}]')+ vscode_chat_integration.configure(paths.vscode_chat, URL, TOKEN, [])+ paths.jetbrains.parent.mkdir()+ paths.jetbrains.write_text(+ json.dumps(+ {+ "agent_servers": {+ "Claude Code (FCC)": {"env": {"FCC_JETBRAINS_ACP": "1"}},+ "Other": {"command": "keep"},+ }+ }+ )+ )+ claude_desktop_integration.configure(+ paths.desktop, URL, TOKEN, True, disconnect_path=paths.desktop_disconnect+ )+ mode = paths.desktop / "claude_desktop_config.json"+ mode.write_text(json.dumps({"deploymentMode": "3p", "keep": True}))+ profile = paths.dsh / "profiles/desktop/cordis.patch.yml"+ profile.parent.mkdir(parents=True)+ profile.write_text(+ f"- id: llm-pi-ai\n config:\n providers:\n {DSH_PROVIDER_ID}:\n baseURL: http://127.0.0.1:8082/v1\n other:\n keep: true\n- id: agent-default-model\n config:\n provider: {DSH_PROVIDER_ID}\n model: test\n"+ )+ credentials = paths.dsh / ".credentials.yaml"+ credentials.write_text(+ f"version: 1\nrefs:\n FCC_DSH_DESKTOP_API_KEY: {TOKEN}\n OTHER: keep\n"+ )++ disconnect_integrations(paths)++ assert json.loads(paths.claude_vscode.read_text()) == {"editor.fontSize": 17}+ assert tomllib.loads(paths.codex.read_text()) == {+ "model": "my-model",+ "model_providers": {"other": {"name": "Other"}},+ }+ assert "# Keep comment" in paths.codex.read_text()+ assert json.loads(paths.vscode_chat.read_text()) == [+ {"vendor": "other", "name": "Keep"}+ ]+ assert json.loads(paths.jetbrains.read_text()) == {+ "agent_servers": {"Other": {"command": "keep"}}+ }+ assert json.loads(mode.read_text()) == {"deploymentMode": "1p", "keep": True}+ assert not (+ paths.desktop / f"configLibrary/{claude_desktop_integration.FCC_ID}.json"+ ).exists()+ assert not paths.desktop_disconnect.exists()+ assert f" {DSH_PROVIDER_ID}:" not in profile.read_text()+ assert " keep: true" in profile.read_text()+ assert "FCC_DSH_DESKTOP_API_KEY" not in credentials.read_text()+ assert "OTHER: keep" in credentials.read_text()+ assert paths.env.exists()+ tracked = [+ paths.claude_vscode,+ paths.codex,+ paths.vscode_chat,+ paths.jetbrains,+ mode,+ profile,+ credentials,+ ]+ before = {path: (path.read_bytes(), path.stat().st_mtime_ns) for path in tracked}+ disconnect_integrations(paths)+ assert before == {+ path: (path.read_bytes(), path.stat().st_mtime_ns) for path in tracked+ }+++def test_missing_native_configurations_create_no_files(tmp_path):+ disconnect_integrations(paths_at(tmp_path))+ assert list(tmp_path.iterdir()) == []++[email protected]("change", ["token", "url"])+def test_manually_changed_vscode_connection_is_preserved(paths, change):+ claude_integration.configure(paths.claude_vscode, URL, TOKEN, True)+ before = paths.claude_vscode.read_text().replace(+ TOKEN if change == "token" else URL,+ "another-token" if change == "token" else "https://other.example",+ )+ paths.claude_vscode.write_text(before)+ with pytest.raises(IntegrationCleanupError, match="Claude Code in VS Code"):+ disconnect_integrations(paths)+ assert paths.claude_vscode.read_text() == before+ assert paths.env.exists()+++ ("key", "value", "connected_url"),+ [+ ("PORT", "9000", "http://127.0.0.1:9000"),+ ("HOST", "192.0.2.20", "http://192.0.2.20:8082"),+ ],+)[email protected]("keep_override", [False, True])+def test_cleanup_of_connection_from_process_override(+ paths, monkeypatch, key, value, connected_url, keep_override+):+ monkeypatch.setenv(key, value)+ claude_integration.configure(paths.claude_vscode, connected_url, TOKEN, True)+ vscode_chat_integration.configure(paths.vscode_chat, connected_url, TOKEN, [])+ before = paths.claude_vscode.read_bytes()+ chat_before = paths.vscode_chat.read_bytes()+ env_before = paths.env.read_bytes()+ if keep_override:+ disconnect_integrations(paths)+ assert json.loads(paths.claude_vscode.read_text()) == {}+ assert json.loads(paths.vscode_chat.read_text()) == []+ else:+ monkeypatch.delenv(key)+ with pytest.raises(IntegrationCleanupError, match="Claude Code in VS Code"):+ disconnect_integrations(paths)+ assert paths.claude_vscode.read_bytes() == before+ assert paths.vscode_chat.read_bytes() == chat_before+ assert paths.env.read_bytes() == env_before+++ ("key", "value"),+ [+ ("claudeCode.disableLoginPrompt", False),+ ("claudeCode.disableLoginPrompt", None),+ ("CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY", "0"),+ ("CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY", None),+ ],+)+def test_unmarked_vscode_settings_are_preserved_without_blocking(paths, key, value):+ claude_integration.configure(+ paths.claude_vscode, "https://other.example", "unrelated-token", True+ )+ document = json.loads(paths.claude_vscode.read_text())+ if key == "claudeCode.disableLoginPrompt":+ if value is None:+ document.pop(key)+ else:+ document[key] = value+ else:+ entries = document["claudeCode.environmentVariables"]+ if value is None:+ document["claudeCode.environmentVariables"] = [+ entry for entry in entries if entry["name"] != key+ ]+ else:+ next(entry for entry in entries if entry["name"] == key)["value"] = value+ paths.claude_vscode.write_text(json.dumps(document))+ before = paths.claude_vscode.read_bytes()+ disconnect_integrations(paths)+ assert paths.claude_vscode.read_bytes() == before++[email protected]("change", ["login", "discovery", "both"])[email protected]("remove", [False, True])[email protected]("mismatch", [None, "url", "token"])+def test_vscode_cleanup_uses_gateway_identity_without_optional_flags(+ paths, change, remove, mismatch+):+ claude_integration.configure(paths.claude_vscode, URL, TOKEN, True)+ document = json.loads(paths.claude_vscode.read_text())+ document["editor.fontSize"] = 17+ if change in {"login", "both"}:+ if remove:+ document.pop("claudeCode.disableLoginPrompt")+ else:+ document["claudeCode.disableLoginPrompt"] = False+ entries = document["claudeCode.environmentVariables"]+ if change in {"discovery", "both"}:+ discovery = next(+ entry+ for entry in entries+ if entry["name"] == "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"+ )+ if remove:+ entries.remove(discovery)+ else:+ discovery["value"] = "0"+ if mismatch is not None:+ name, value = (+ ("ANTHROPIC_BASE_URL", "https://other.example")+ if mismatch == "url"+ else ("ANTHROPIC_AUTH_TOKEN", "changed-token")+ )+ next(entry for entry in entries if entry["name"] == name)["value"] = value+ paths.claude_vscode.write_text(json.dumps(document))+ before = paths.claude_vscode.read_bytes()++ if mismatch is None:+ disconnect_integrations(paths)+ assert json.loads(paths.claude_vscode.read_text()) == {"editor.fontSize": 17}+ else:+ with pytest.raises(IntegrationCleanupError, match="Claude Code in VS Code"):+ disconnect_integrations(paths)+ assert paths.claude_vscode.read_bytes() == before+++ ("field", "message"),+ [+ ("env", "connection settings"),+ ("desktop", "Claude Desktop"),+ ("desktop_disconnect", "Claude Desktop"),+ ("dsh", "DSH Desktop"),+ ],+)[email protected]("failure", [PermissionError, OSError])+def test_cleanup_fails_when_path_access_cannot_be_confirmed(+ paths, monkeypatch, field, message, failure+):+ blocked = getattr(paths, field)+ if field == "desktop":+ claude_desktop_integration.configure(+ paths.desktop, URL, TOKEN, True, disconnect_path=paths.desktop_disconnect+ )+ elif field == "dsh":+ paths.dsh.mkdir()+ (paths.dsh / ".credentials.yaml").write_text(+ f"version: 1\nrefs:\n FCC_DSH_DESKTOP_API_KEY: {TOKEN}\n"+ )+ elif field == "desktop_disconnect":+ blocked.write_text(+ json.dumps(+ {"root": str(paths.desktop.resolve()), "return_to_sign_in": True}+ )+ )+ before = {+ path: path.read_bytes()+ for path in paths.env.parent.parent.rglob("*")+ if path.is_file()+ }+ original_stat = os.stat++ def inaccessible(path, *args, **kwargs):+ if Path(path) == blocked:+ raise failure("private-filesystem-detail")+ return original_stat(path, *args, **kwargs)++ with monkeypatch.context() as patch:+ patch.setattr(os, "stat", inaccessible)+ # Exercise POSIX existence semantics on Windows too, where exists uses+ # a separate native fast path instead of os.stat.+ patch.setattr(os.path, "exists", genericpath.exists)+ with pytest.raises(IntegrationCleanupError, match=message) as error:+ disconnect_integrations(paths)+ assert "private-filesystem-detail" not in str(error.value)+ assert {path: path.read_bytes() for path in before} == before+++ "connected_url",+ ["http://localhost:8082/", "http://[::1]:8082", "http://127.0.0.1:8082/"],+)+def test_equivalent_loopback_connection_is_disconnected(paths, connected_url):+ claude_integration.configure(paths.claude_vscode, connected_url, TOKEN, True)+ disconnect_integrations(paths)+ assert json.loads(paths.claude_vscode.read_text()) == {}+++def test_missing_identity_does_not_claim_gateway_settings(paths):+ claude_integration.configure(paths.claude_vscode, URL, TOKEN, True)+ paths.env.unlink()+ before = paths.claude_vscode.read_bytes()+ with pytest.raises(IntegrationCleanupError, match="Claude Code in VS Code"):+ disconnect_integrations(paths)+ assert paths.claude_vscode.read_bytes() == before++[email protected]("content", ["PORT=invalid", "ANTHROPIC_AUTH_TOKEN="])+def test_invalid_connection_settings_abort_without_modifying_apps(paths, content):+ claude_integration.configure(paths.claude_vscode, URL, TOKEN, True)+ paths.env.write_text(content)+ before = paths.claude_vscode.read_bytes()+ with pytest.raises(IntegrationCleanupError, match="connection settings"):+ disconnect_integrations(paths)+ assert paths.claude_vscode.read_bytes() == before+ assert paths.env.read_text() == content+++def test_invalid_settings_error_does_not_disclose_source_text(paths):+ paths.claude_vscode.parent.mkdir()+ paths.claude_vscode.write_text('{"secret": "cleanup-secret", invalid}')+ with pytest.raises(IntegrationCleanupError) as error:+ disconnect_integrations(paths)+ assert "cleanup-secret" not in str(error.value)+ assert paths.env.exists()+++ "error", [claude_desktop_integration.ManagedDesktopError, PermissionError]+)+def test_desktop_policy_or_access_failure_preserves_recovery_data(+ paths, monkeypatch, error+):+ paths.desktop.mkdir()++ def fail():+ raise error("private-policy-data")++ monkeypatch.setattr(claude_desktop_integration, "check_unmanaged", fail)+ with pytest.raises(IntegrationCleanupError, match="Claude Desktop") as result:+ disconnect_integrations(paths)+ assert "private-policy-data" not in str(result.value)+ assert paths.env.exists()+++def test_orphan_dsh_credential_is_removed_without_creating_profile(paths):+ paths.dsh.mkdir()+ credentials = paths.dsh / ".credentials.yaml"+ credentials.write_text(+ f"version: 1\nrefs:\n FCC_DSH_DESKTOP_API_KEY: {TOKEN}\n OTHER: keep\n"+ )+ disconnect_integrations(paths)+ assert "FCC_DSH_DESKTOP_API_KEY" not in credentials.read_text()+ assert "OTHER: keep" in credentials.read_text()+ assert not (paths.dsh / "profiles").exists()