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: Check FCC version before running updates (#1917)
Ali Khokharf3ec4746edb8
diff --git a/README.md b/README.mdindex 2dadeb09..9425d445 100644--- a/README.md+++ b/README.md@@ -462,6 +462,10 @@ Stop all running FCC commands, then run:fcc-update```+If FCC is already up to date, the command stops without running the installer. Otherwise, it shows the installed and available versions before updating. If the version check fails, retry the command.++To reinstall FCC or change optional components while already up to date, run the [installer](#install) directly.+For local voice support, include `--voice-local` (macOS/Linux) or `-VoiceLocal` (Windows), plus your `--torch-backend` or `-TorchBackend` option if used.If your installation does not have `fcc-update` yet, run the [installer](#install) once to add it.diff --git a/pyproject.toml b/pyproject.tomlindex 095dd2e9..97226cdd 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -11,6 +11,7 @@ license = "AGPL-3.0-only"license-files = ["LICENSE"]requires-python = "==3.14.7"dependencies = [+ "packaging>=26.3","anyio>=4.15.1","fastapi[standard]>=0.141.1","uvicorn>=0.53.0",@@ -41,6 +42,7 @@ dependencies = [][project.scripts]+_fcc-update-check = "free_claude_code.updater.check:main"fcc-server = "free_claude_code.cli.entrypoints:serve"fcc-doctor = "free_claude_code.cli.entrypoints:doctor"fcc-claude = "free_claude_code.cli.launchers.claude:launch"@@ -89,7 +91,6 @@ explicit = true[dependency-groups]dev = [- "packaging>=26.3","pytest>=9.1.1","pytest-asyncio>=1.4.0","pytest-cov>=7.1.0",diff --git a/scripts/update/fcc-update b/scripts/update/fcc-updateindex 8fb65aa7..b7709519 100644--- a/scripts/update/fcc-update+++ b/scripts/update/fcc-update@@ -1,4 +1,11 @@#!/bin/shset -eu+status=0+"$(dirname "$0")/_fcc-update-check" || status=$?+case "$status" in+ 0) exit 0 ;;+ 10) ;;+ *) exit "$status" ;;+esacinstaller=$(curl -fsSL "https://raw.githubusercontent.com/Alishahryar1/free-claude-code/main/scripts/install.sh")exec sh -c "$installer" sh "$@"diff --git a/scripts/update/fcc-update.cmd b/scripts/update/fcc-update.cmdindex f2f6c8d5..85f06c4d 100644--- a/scripts/update/fcc-update.cmd+++ b/scripts/update/fcc-update.cmd@@ -1,4 +1,7 @@@echo off+"%~dp0_fcc-update-check.exe"+if %errorlevel%==0 exit /b 0+if not %errorlevel%==10 exit /b %errorlevel%(powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference = 'Stop'; & ([scriptblock]::Create((Invoke-RestMethod 'https://raw.githubusercontent.com/Alishahryar1/free-claude-code/main/scripts/install.ps1')))" %*call exit /b %%errorlevel%%diff --git a/src/free_claude_code/updater/__init__.py b/src/free_claude_code/updater/__init__.pynew file mode 100644index 00000000..8dbc5c6c--- /dev/null+++ b/src/free_claude_code/updater/__init__.py@@ -0,0 +1 @@+"""Standalone update preflight, independent of server and harness runtime."""diff --git a/src/free_claude_code/updater/check.py b/src/free_claude_code/updater/check.pynew file mode 100644index 00000000..d2d6368d--- /dev/null+++ b/src/free_claude_code/updater/check.py@@ -0,0 +1,53 @@+"""Standalone version preflight for the native update launchers."""++import sys+from importlib.metadata import PackageNotFoundError, version++import httpx+from packaging.version import Version++PYPI_URL = "https://pypi.org/pypi/free-claude-code/json"+UPDATE_AVAILABLE = 10+++def main() -> int:+ """Return 10 to authorize installation, 0 to skip, or 1 on check failure."""+ try:+ installed = Version(version("free-claude-code"))+ if str(installed) == "0+unknown":+ raise ValueError("installed FCC version is unknown")+ with httpx.Client(timeout=10.0) as client:+ response = client.get(PYPI_URL)+ response.raise_for_status()+ metadata = response.json()+ latest = Version(metadata["info"]["version"])+ files = metadata["urls"]+ if (+ latest.is_prerelease+ or latest.is_devrelease+ or not isinstance(files, list)+ or not any(+ isinstance(file, dict) and file.get("yanked") is False for file in files+ )+ ):+ raise ValueError("PyPI did not return an available stable FCC release")+ except (+ PackageNotFoundError,+ httpx.HTTPError,+ ValueError,+ KeyError,+ TypeError,+ ) as exc:+ print(f"Could not check for FCC updates: {exc}. Please retry.", file=sys.stderr)+ return 1++ if installed == latest:+ print(f"FCC {installed} is already up to date.")+ return 0+ if installed > latest:+ print(+ f"FCC {installed} is newer than the published version {latest}. No update needed."+ )+ return 0+ print(f"FCC update available: {installed} -> {latest}. Running the installer.")+ return UPDATE_AVAILABLEdiff --git a/tests/cli/test_entrypoints.py b/tests/cli/test_entrypoints.pyindex 20d7ab43..856dbe6d 100644--- a/tests/cli/test_entrypoints.py+++ b/tests/cli/test_entrypoints.py@@ -38,6 +38,7 @@ def test_cli_scripts_are_registered() -> None:)assert pyproject["project"]["scripts"] == {+ "_fcc-update-check": "free_claude_code.updater.check:main","fcc-server": "free_claude_code.cli.entrypoints:serve","fcc-doctor": "free_claude_code.cli.entrypoints:doctor","fcc-claude": "free_claude_code.cli.launchers.claude:launch",diff --git a/tests/cli/test_update_check.py b/tests/cli/test_update_check.pynew file mode 100644index 00000000..edeb5c62--- /dev/null+++ b/tests/cli/test_update_check.py@@ -0,0 +1,104 @@+"""The updater checks published versions before authorizing installation."""++from importlib.metadata import PackageNotFoundError++import httpx+import pytest++from free_claude_code.updater import check as update_check+++def release(version="1.10.0", *, yanked=False):+ return {"info": {"version": version}, "urls": [{"yanked": yanked}]}+++def check(monkeypatch):+ original_client = httpx.Client++ def run(installed="1.9.0", payload=None, status=200, error=None, body=None):+ monkeypatch.setattr(update_check, "version", lambda name: installed)++ def respond(request):+ assert str(request.url) == update_check.PYPI_URL+ if error is not None:+ raise error+ if body is not None:+ return httpx.Response(status, content=body)+ return httpx.Response(status, json=payload)++ monkeypatch.setattr(+ update_check.httpx,+ "Client",+ lambda **kwargs: original_client(+ transport=httpx.MockTransport(respond), **kwargs+ ),+ )+ return update_check.main()++ return run+++ ("installed", "expected"),+ [+ ("1.9.0", 10),+ ("1.10.0", 0),+ ("1.11.0", 0),+ ("1.10.0+local", 0),+ ("1.10.0.dev1", 10),+ ],+)+def test_version_comparison(check, capsys, installed, expected):+ assert check(installed, release()) == expected+ output = capsys.readouterr()+ assert installed in output.out+ assert not output.err+++ "payload",+ [+ None,+ {},+ {"info": []},+ release("invalid"),+ release("2.0rc1"),+ release("2.0.dev1"),+ release(yanked=True),+ {"info": {"version": "2.0"}, "urls": []},+ {"info": {"version": "2.0"}, "urls": [{}]},+ ],+)+def test_invalid_release_does_not_authorize_installation(check, capsys, payload):+ assert check(payload=payload) == 1+ assert capsys.readouterr().err++[email protected]("installed", ["invalid", "0+unknown"])+def test_unknown_installed_version(check, installed):+ assert check(installed, release()) == 1+++def test_missing_distribution(monkeypatch, capsys):+ def missing(name):+ raise PackageNotFoundError(name)++ monkeypatch.setattr(update_check, "version", missing)+ assert update_check.main() == 1+ assert capsys.readouterr().err+++def test_http_error(check, capsys):+ assert check(payload=release(), status=503) == 1+ assert capsys.readouterr().err+++def test_timeout(check, capsys):+ assert check(error=httpx.ReadTimeout("timed out")) == 1+ assert capsys.readouterr().err+++def test_malformed_json(check, capsys):+ assert check(body="not JSON") == 1+ assert capsys.readouterr().errdiff --git a/tests/cli/test_update_wrapper.py b/tests/cli/test_update_wrapper.pyindex 288de6ac..dcb7ac7a 100644--- a/tests/cli/test_update_wrapper.py+++ b/tests/cli/test_update_wrapper.py@@ -2,6 +2,7 @@import contextlibimport http.server+import jsonimport osimport shutilimport subprocess@@ -18,14 +19,23 @@ SCRIPTS = ("fcc-update", "fcc-update.cmd")@contextlib.contextmanager-def installer_server(body, status):+def installer_server(body, status, outcome):requests = []class Handler(http.server.BaseHTTPRequestHandler):def do_GET(self):requests.append(self.path)payload = body.encode("utf-8")- self.send_response(status)+ response_status = status+ if self.path == "/metadata":+ version = {"current": "1.0.0", "newer-installed": "0.9.0"}.get(+ outcome, "2.0.0"+ )+ payload = json.dumps(+ {"info": {"version": version}, "urls": [{"yanked": False}]}+ ).encode()+ response_status = 503 if outcome == "check-error" else 200+ self.send_response(response_status)self.send_header("Content-Type", "text/plain; charset=utf-8")self.send_header("Content-Length", str(len(payload)))self.end_headers()@@ -51,7 +61,8 @@ def fixture_wheel(area, url):with zipfile.ZipFile(wheel, "w") as archive:archive.writestr(f"{dist}.dist-info/METADATA",- "Metadata-Version: 2.1\nName: free-claude-code\nVersion: 1.0.0\n",+ "Metadata-Version: 2.1\nName: free-claude-code\nVersion: 1.0.0\n"+ "Requires-Dist: httpx>=0.28.1\nRequires-Dist: packaging>=26.3\n",)archive.writestr(f"{dist}.dist-info/WHEEL",@@ -62,6 +73,19 @@ def fixture_wheel(area, url):archive.writestr(f"{dist}.data/scripts/{name}", source.replace(INSTALL_URL, url))+ archive.writestr(+ f"{dist}.dist-info/entry_points.txt",+ "[console_scripts]\n_fcc-update-check = free_claude_code.updater.check:main\n",+ )+ for name in ("__init__.py", "updater/__init__.py", "updater/check.py"):+ source = (ROOT / "src/free_claude_code" / name).read_text(encoding="utf-8")+ archive.writestr(+ f"free_claude_code/{name}",+ source.replace(+ "https://pypi.org/pypi/free-claude-code/json",+ url.removesuffix("/install") + "/metadata",+ ),+ )archive.writestr(f"{dist}.dist-info/RECORD","".join(f"{name},,\n" for name in archive.namelist())@@ -70,7 +94,18 @@ def fixture_wheel(area, url):return wheel[email protected]("outcome", ["success", "exit", "error", "download-error"])+ "outcome",+ [+ "success",+ "exit",+ "error",+ "download-error",+ "current",+ "newer-installed",+ "check-error",+ ],+)def test_installed_update_delegates_and_survives_replacement(tmp_path, outcome):uv = shutil.which("uv")if uv is None:@@ -87,12 +122,18 @@ def test_installed_update_delegates_and_survives_replacement(tmp_path, outcome):FCC_TEST_LAUNCHER=str(area / "bin" / ("fcc-update.cmd" if os.name == "nt" else "fcc-update")),+ FCC_TEST_CHECKER=str(+ area+ / "bin"+ / ("_fcc-update-check.exe" if os.name == "nt" else "_fcc-update-check")+ ),)if os.name == "nt":body = """param([switch] $VoiceLocal, [string] $TorchBackend)$answer = Read-Host 'Continue'Write-Output "installer:$VoiceLocal|$TorchBackend|$answer"[IO.File]::WriteAllText($env:FCC_TEST_LAUNCHER, 'exit /b 99')+[IO.File]::WriteAllText($env:FCC_TEST_CHECKER, 'replaced after checker exited')"""arguments = "-VoiceLocal -TorchBackend cu130"expected = "installer:True|cu130|yes"@@ -101,11 +142,12 @@ Write-Output "installer:$VoiceLocal|$TorchBackend|$answer""exit": "exit 23","error": "throw 'installer failed'","download-error": "",- }[outcome]+ }.get(outcome, "")else:body = """read -r answerprintf 'installer:%s|%s|%s|%s\\n' "$1" "$2" "$3" "$answer"printf 'exit 99\\n' > "$FCC_TEST_LAUNCHER"+printf 'replaced after checker exited' > "$FCC_TEST_CHECKER""""arguments = ["--voice-local", "--torch-backend", "cu130"]expected = "installer:--voice-local|--torch-backend|cu130|yes"@@ -114,8 +156,10 @@ printf 'exit 99\\n' > "$FCC_TEST_LAUNCHER""exit": "exit 23","error": "exit 1","download-error": "",- }[outcome]- with installer_server(body, 503 if outcome == "download-error" else 200) as (+ }.get(outcome, "")+ with installer_server(+ body, 503 if outcome == "download-error" else 200, outcome+ ) as (url,requests,):@@ -149,8 +193,14 @@ printf 'exit 99\\n' > "$FCC_TEST_LAUNCHER"text=True,timeout=30,)- assert requests == ["/install.ps1" if os.name == "nt" else "/install.sh"]- if outcome == "download-error":+ skipped = outcome in {"current", "newer-installed", "check-error"}+ assert requests == ["/metadata"] + (+ [] if skipped else ["/install.ps1" if os.name == "nt" else "/install.sh"]+ ), result.stdout + result.stderr+ if skipped:+ assert result.returncode == (1 if outcome == "check-error" else 0)+ assert "installer:" not in result.stdout+ elif outcome == "download-error":assert result.returncode != 0assert "installer:" not in result.stdoutelse:@@ -166,3 +216,4 @@ printf 'exit 99\\n' > "$FCC_TEST_LAUNCHER")assert result.returncode == 0, result.stderrassert not any((area / "bin" / name).exists() for name in SCRIPTS)+ assert not any((area / "bin").glob("_fcc-update-check*"))diff --git a/tests/contracts/test_import_boundaries.py b/tests/contracts/test_import_boundaries.pyindex a701352a..3add3b44 100644--- a/tests/contracts/test_import_boundaries.py+++ b/tests/contracts/test_import_boundaries.py@@ -11,6 +11,7 @@ _PACKAGE_ROOT = _REPO_ROOT / "src" / "free_claude_code"_PACKAGE_NAME = "free_claude_code"ALLOWED_PACKAGE_DEPENDENCIES: dict[str, set[str]] = {+ "updater": set(),"config": {"core"},"core": set(),"application": {"config", "core"},diff --git a/uv.lock b/uv.lockindex 57d1cd29..7ccc1a04 100644--- a/uv.lock+++ b/uv.lock@@ -617,6 +617,7 @@ dependencies = [{ name = "markdown-it-py" },{ name = "nvidia-riva-client" },{ name = "openai" },+ { name = "packaging" },{ name = "pillow", marker = "sys_platform == 'darwin' or sys_platform == 'win32'" },{ name = "pydantic" },{ name = "pyperclip" },@@ -640,7 +641,6 @@ voice-local = [[package.dev-dependencies]dev = [- { name = "packaging" },{ name = "pytest" },{ name = "pytest-asyncio" },{ name = "pytest-cov" },@@ -671,6 +671,7 @@ requires-dist = [{ name = "markdown-it-py", specifier = ">=4.2.0" },{ name = "nvidia-riva-client", specifier = ">=2.26.0" },{ name = "openai", specifier = ">=3.18.0" },+ { name = "packaging", specifier = ">=26.3" },{ name = "pillow", marker = "sys_platform == 'darwin' or sys_platform == 'win32'", specifier = ">=12.0.0" },{ name = "pydantic", specifier = ">=2.13.5" },{ name = "pyperclip", specifier = ">=1.11.0" },@@ -689,7 +690,6 @@ provides-extras = ["voice-local"][package.metadata.requires-dev]dev = [- { name = "packaging", specifier = ">=26.3" },{ name = "pytest", specifier = ">=9.1.1" },{ name = "pytest-asyncio", specifier = ">=1.4.0" },{ name = "pytest-cov", specifier = ">=7.1.0" },