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: Fix macOS app menu-bar launch identity (#2095)
Ali Khokharc5239619be48
diff --git a/.github/workflows/post-merge.yml b/.github/workflows/post-merge.ymlindex ff7f0130..583c71ef 100644--- a/.github/workflows/post-merge.yml+++ b/.github/workflows/post-merge.yml@@ -22,7 +22,7 @@ concurrency:jobs:warm-dependency-cache:- name: Warm dependency cache (${{ matrix.os }})+ name: Warm dependency cache (${{ matrix.runner }})if: github.ref == 'refs/heads/main'runs-on: ${{ matrix.runner }}timeout-minutes: 15@@ -38,6 +38,10 @@ jobs:runner: windows-latest- os: macOSrunner: macos-latest+ - os: macOS+ runner: macos-26+ - os: macOS+ runner: macos-26-intelsteps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1with:@@ -82,7 +86,7 @@ jobs:publish:name: Publish to PyPIif: github.ref == 'refs/heads/main'- runs-on: ubuntu-latest+ runs-on: macos-26timeout-minutes: 15environment: pypipermissions:@@ -99,7 +103,7 @@ jobs:uses: ./.github/actions/ci-environmentwith:uv-version: ${{ env.CI_UV_VERSION }}- runner-label: ubuntu-latest+ runner-label: macos-26lookup-only: "true"sync-dependencies: "false"diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex b7a174af..f698a5c6 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -171,9 +171,74 @@ jobs:if-no-files-found: ignoreretention-days: 7+ macos-desktop:+ name: macOS desktop (${{ matrix.runner }})+ permissions:+ contents: read+ runs-on: ${{ matrix.runner }}+ timeout-minutes: 15+ strategy:+ fail-fast: false+ matrix:+ runner: [macos-26, macos-26-intel]+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1+ with:+ ref: ${{ github.event.pull_request.head.sha || github.ref }}+ repository: ${{ github.event.pull_request.head.repo.full_name || github.repository }}+ fetch-depth: 0+ - uses: ./.github/actions/ci-environment+ id: environment+ with:+ uv-version: ${{ env.CI_UV_VERSION }}+ runner-label: ${{ matrix.runner }}+ - name: Run native desktop checks+ run: sh scripts/ci.sh --only macos-desktop+ - name: Check installer and uninstaller boundaries+ env:+ FCC_LIVE_SMOKE: "1"+ run: uv run --locked pytest smoke/installers -n 0 -q --output=test-results/installer -k 'macos or removes_and_verifies_only_fcc or pins_selected_fcc_release or preserves_compatible_uv'+ - name: Upload observations+ if: always()+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a+ with:+ name: native-${{ matrix.runner }}-${{ github.run_attempt }}+ path: test-results/native/+ retention-days: 7++ sdist-rebuild:+ name: sdist rebuild (${{ matrix.runner }})+ needs: macos-desktop+ runs-on: ${{ matrix.runner }}+ timeout-minutes: 15+ permissions:+ contents: read+ strategy:+ fail-fast: false+ matrix:+ runner: [ubuntu-latest, windows-latest]+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1+ with:+ ref: ${{ github.event.pull_request.head.sha || github.ref }}+ repository: ${{ github.event.pull_request.head.repo.full_name || github.repository }}+ fetch-depth: 0+ - uses: ./.github/actions/ci-environment+ id: environment+ with:+ uv-version: ${{ env.CI_UV_VERSION }}+ runner-label: ${{ matrix.runner }}+ sync-dependencies: "false"+ - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333+ with:+ name: native-macos-26-${{ github.run_attempt }}+ path: test-results/native+ - name: Rebuild the Mac-produced sdist without a native compiler+ run: uv run --no-project --python ${{ steps.environment.outputs.python-version }} python smoke/desktop/rebuild_sdist.py test-results/native/dist+pytest-summary:name: pytest- needs: [prepare-shards, pytest-shards]+ needs: [prepare-shards, pytest-shards, macos-desktop, sdist-rebuild]if: ${{ always() }}runs-on: ubuntu-latesttimeout-minutes: 15@@ -184,8 +249,10 @@ jobs:env:PREPARATION_RESULT: ${{ needs.prepare-shards.result }}SHARDS_RESULT: ${{ needs.pytest-shards.result }}+ NATIVE_RESULT: ${{ needs.macos-desktop.result }}+ REBUILD_RESULT: ${{ needs.sdist-rebuild.result }}run: |- test "$PREPARATION_RESULT" = success && test "$SHARDS_RESULT" = success+ test "$PREPARATION_RESULT" = success && test "$SHARDS_RESULT" = success && test "$NATIVE_RESULT" = success && test "$REBUILD_RESULT" = successplaywright-summary:name: playwrightdiff --git a/.gitignore b/.gitignoreindex 73eb6aa1..4b66f468 100644--- a/.gitignore+++ b/.gitignore@@ -16,3 +16,4 @@ llama_cache.smoke-results/test-results/.vscode+/src/free_claude_code/assets/macos/fcc-desktop-*diff --git a/pyproject.toml b/pyproject.tomlindex 66c89177..335dfcd5 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -72,6 +72,9 @@ voice_local = [[tool.hatch.version]source = "vcs"+[tool.hatch.build]+artifacts = ["src/free_claude_code/assets/macos/fcc-desktop-*"]+[tool.hatch.build.targets.wheel]packages = ["src/free_claude_code"]diff --git a/scripts/build_macos_launcher.py b/scripts/build_macos_launcher.pynew file mode 100644index 00000000..cbf17a9a--- /dev/null+++ b/scripts/build_macos_launcher.py@@ -0,0 +1,57 @@+"""Build the two macOS launcher templates from this exact source checkout."""++import re+import subprocess+import sys+import tomllib+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+TARGETS = {"arm64": "11.0", "x86_64": "10.15"}+++def build() -> None:+ if sys.platform != "darwin":+ raise RuntimeError(+ "Building macOS launcher templates requires macOS and Xcode tools"+ )+ project = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8"))+ version = project["project"]["requires-python"].removeprefix("==")+ if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", version):+ raise ValueError("Expected an exact Python requirement")+ destination = ROOT / "src/free_claude_code/assets/macos"+ destination.mkdir(parents=True, exist_ok=True)+ for architecture, minimum in TARGETS.items():+ output = destination / f"fcc-desktop-{architecture}"+ subprocess.run(+ [+ "xcrun",+ "clang",+ "-arch",+ architecture,+ f"-mmacosx-version-min={minimum}",+ "-fobjc-arc",+ "-Os",+ "-Wall",+ "-Wextra",+ "-Werror",+ f'-DFCC_PYTHON_VERSION="{version}"',+ "-framework",+ "AppKit",+ "-framework",+ "Foundation",+ str(ROOT / "scripts/macos/launcher.m"),+ "-o",+ str(output),+ ],+ check=True,+ )+ subprocess.run(+ ["/usr/bin/lipo", str(output), "-verify_arch", architecture], check=True+ )+ subprocess.run(["/usr/bin/otool", "-L", str(output)], check=True)+ subprocess.run(["/usr/bin/otool", "-l", str(output)], check=True)+++if __name__ == "__main__":+ build()diff --git a/scripts/ci.ps1 b/scripts/ci.ps1index 41338aa0..c4835896 100644--- a/scripts/ci.ps1+++ b/scripts/ci.ps1@@ -16,7 +16,8 @@ $CheckOrder = @("ruff-check","ty","pytest",- "playwright"+ "playwright",+ "macos-desktop")function Show-Usage {@@ -34,6 +35,7 @@ Checks (in order):ty uv run ty checkpytest uv run pytest -v --tb=shortplaywright Install Chromium and run deterministic Admin browser tests+ macos-desktop Build and test the native app (macOS GUI required, -Only)Options:-Only ID Run only the given check (repeatable)@@ -95,6 +97,10 @@ function Assert-ValidCheckId {function Test-ShouldRunCheck {param([string] $CheckId)+ if ($CheckId -eq "macos-desktop" -and $Only.Count -eq 0) {+ return $false+ }+if ($Only.Count -gt 0 -and ($Only -notcontains $CheckId)) {return $false}@@ -187,6 +193,11 @@ function Invoke-Check {"ty" { Invoke-TyCheck }"pytest" { Invoke-PytestCheck }"playwright" { Invoke-PlaywrightCheck }+ "macos-desktop" {+ Write-Step "macOS desktop"+ Invoke-CiCommand -FilePath "uv" -Arguments @("run", "--locked", "python", "scripts/build_macos_launcher.py")+ Invoke-CiCommand -FilePath "uv" -Arguments @("run", "--locked", "pytest", "--confcutdir=smoke/desktop", "-n", "0", "-s", "-v", "smoke/desktop")+ }default { throw "unknown check id: $CheckId" }}}diff --git a/scripts/ci.sh b/scripts/ci.shindex 83bc6b2e..3ab0c1bd 100755--- a/scripts/ci.sh+++ b/scripts/ci.sh@@ -1,7 +1,7 @@#!/bin/shset -eu-CHECK_ORDER="suppressions ruff-format ruff-check ty pytest playwright"+CHECK_ORDER="suppressions ruff-format ruff-check ty pytest playwright macos-desktop"dry_run=0only_checks=""@@ -22,6 +22,7 @@ Checks (in order):ty uv run ty checkpytest uv run pytest -v --tb=shortplaywright Install Chromium and run deterministic Admin browser tests+ macos-desktop Build and test the native app (macOS GUI required, --only)Options:--only ID Run only the given check (repeatable)@@ -70,7 +71,7 @@ run() {valid_check_id() {case "$1" in- suppressions | ruff-format | ruff-check | ty | pytest | playwright) return 0 ;;+ suppressions | ruff-format | ruff-check | ty | pytest | playwright | macos-desktop) return 0 ;;*) return 1 ;;esac}@@ -93,6 +94,10 @@ contains_check_id() {should_run_check() {check_id=$1+ if [ "$check_id" = "macos-desktop" ] && [ -z "$only_checks" ]; then+ return 1+ fi+if [ -n "$only_checks" ] && ! contains_check_id "$only_checks" "$check_id"; thenreturn 1fi@@ -173,6 +178,11 @@ run_check() {ty) run_ty ;;pytest) run_pytest ;;playwright) run_playwright ;;+ macos-desktop)+ step "macOS desktop"+ run uv run --locked python scripts/build_macos_launcher.py+ run uv run --locked pytest --confcutdir=smoke/desktop -n 0 -s -v smoke/desktop+ ;;*) fail "unknown check id: $1" ;;esac}diff --git a/scripts/install.sh b/scripts/install.shindex b2843c76..79e654ad 100644--- a/scripts/install.sh+++ b/scripts/install.sh@@ -16,8 +16,6 @@ RTK_VERSION="0.44.2"HEADROOM_PACKAGE="headroom-ai[mcp]==0.40.0"RTK_RELEASE_BASE_URL="https://github.com/rtk-ai/rtk/releases/download/v$RTK_VERSION"UV_INSTALL_URL="https://astral.sh/uv/install.sh"-FCC_MACOS_BUNDLE_ID="io.github.alishahryar1.free-claude-code"-FCC_MACOS_OWNER_FILE=".free-claude-code-owner"# Include retired entry points so updates reject older FCC processes before replacement.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"@@ -1526,11 +1524,16 @@ install_free_claude_code() {assert_no_fcc_processes_runningspec=$(package_spec)- if [ -n "$torch_backend" ]; then- run uv tool install --force --refresh-package free-claude-code --python "$PYTHON_VERSION" --torch-backend "$torch_backend" "$spec"+ set -- uv tool install --force --refresh-package free-claude-code+ if [ "$(uname -s)" = "Darwin" ]; then+ set -- env -u UV_PYTHON_PREFERENCE "$@" --managed-python --python "$PYTHON_VERSION+gil"else- run uv tool install --force --refresh-package free-claude-code --python "$PYTHON_VERSION" "$spec"+ set -- "$@" --python "$PYTHON_VERSION"+ fi+ if [ -n "$torch_backend" ]; then+ set -- "$@" --torch-backend "$torch_backend"fi+ run "$@" "$spec"}configure_and_verify_free_claude_code() {@@ -1560,88 +1563,13 @@ shell_quote() {printf "'%s'" "$escaped"}-macos_app_is_fcc_owned() {- app_dir=$1- owner_file="$app_dir/Contents/$FCC_MACOS_OWNER_FILE"- [ -d "$app_dir" ] &&- [ ! -L "$app_dir" ] &&- [ -f "$owner_file" ] &&- [ "$(cat "$owner_file")" = "$FCC_MACOS_BUNDLE_ID" ]-}-install_macos_desktop_app() {[ "$(uname -s)" = "Darwin" ] || return 0-- app_dir="$HOME/Applications/Free Claude Code.app"- contents_dir="$app_dir/Contents"- owner_file="$contents_dir/$FCC_MACOS_OWNER_FILE"- executable_dir="$contents_dir/MacOS"- executable_path="$executable_dir/fcc-desktop"- resources_dir="$contents_dir/Resources"- icon_path="$resources_dir/AppIcon.icns"- desktop_dir="$HOME/Desktop"- desktop_link="$desktop_dir/Free Claude Code.app"-- if [ -e "$app_dir" ] || [ -L "$app_dir" ]; then- macos_app_is_fcc_owned "$app_dir" ||- fail "An app not managed by Free Claude Code already exists at $app_dir. Move it, then rerun the installer."- fi-if [ "$dry_run" -eq 1 ]; then- print_command mkdir -p "$executable_dir" "$resources_dir" "$desktop_dir"- print_command fcc-desktop --export-icon "$icon_path"- printf '+ write %s, %s, and %s\n' "$owner_file" "$contents_dir/Info.plist" "$executable_path"- print_command ln -s "$app_dir" "$desktop_link"- return 0- fi-- mkdir -p "$executable_dir" "$resources_dir" "$desktop_dir"- run "$tool_bin/fcc-desktop" --export-icon "$icon_path"- [ -f "$icon_path" ] || fail "Free Claude Code did not export its macOS app icon to $icon_path."- printf '%s\n' "$FCC_MACOS_BUNDLE_ID" > "$owner_file"- cat > "$contents_dir/Info.plist" <<'PLIST'-<?xml version="1.0" encoding="UTF-8"?>-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">-<plist version="1.0">-<dict>- <key>CFBundleDisplayName</key>- <string>Free Claude Code</string>- <key>CFBundleExecutable</key>- <string>fcc-desktop</string>- <key>CFBundleIdentifier</key>- <string>io.github.alishahryar1.free-claude-code</string>- <key>CFBundleIconFile</key>- <string>AppIcon</string>- <key>CFBundleName</key>- <string>Free Claude Code</string>- <key>CFBundlePackageType</key>- <string>APPL</string>- <key>LSMultipleInstancesProhibited</key>- <true/>- <key>LSUIElement</key>- <true/>-</dict>-</plist>-PLIST- desktop_command=$(shell_quote "$tool_bin/fcc-desktop")- {- printf '%s\n' '#!/bin/sh'- printf 'exec %s\n' "$desktop_command"- } > "$executable_path"- chmod +x "$executable_path"-- if [ -L "$desktop_link" ]; then- if [ "$(readlink "$desktop_link")" = "$app_dir" ]; then- rm -f "$desktop_link"- else- printf 'A non-FCC link already exists at %s; leaving it unchanged.\n' "$desktop_link"- return 0- fi- elif [ -e "$desktop_link" ]; then- printf 'A non-FCC item already exists at %s; leaving it unchanged.\n' "$desktop_link"+ print_command fcc-desktop --install-macos-appreturn 0fi- ln -s "$app_dir" "$desktop_link"+ run "$tool_bin/fcc-desktop" --install-macos-app}show_installer_next_steps() {diff --git a/scripts/macos/launcher.m b/scripts/macos/launcher.mnew file mode 100644index 00000000..711e3b86--- /dev/null+++ b/scripts/macos/launcher.m@@ -0,0 +1,105 @@+// Keep the application executable inside its bundle while running the installed FCC venv.+#import <AppKit/AppKit.h>+#include <dlfcn.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#ifndef FCC_PYTHON_VERSION+#error "Build with the Python version required by pyproject.toml"+#endif++// Public, opaque CPython 3.14 initialization API. No Python structures are embedded here.+typedef struct PyInitConfig PyInitConfig;++static int fail(NSString *reason) {+ fprintf(stderr, "Free Claude Code: %s\n", reason.UTF8String);+ [NSApplication sharedApplication];+ NSAlert *alert = [[NSAlert alloc] init];+ alert.messageText = @"Free Claude Code could not start";+ alert.informativeText = [reason stringByAppendingString:+ @"\n\nRerun the Free Claude Code installer to repair the desktop launcher."];+ [alert addButtonWithTitle:@"OK"];+ [NSApp activateIgnoringOtherApps:YES];+ [alert runModal];+ return 1;+}++static NSString *absolutePath(NSDictionary *settings, NSString *key) {+ id value = settings[key];+ return [value isKindOfClass:[NSString class]] && [value isAbsolutePath] ? value : nil;+}++int main(int argc, char **argv) {+ @autoreleasepool {+ NSURL *settingsURL = [[NSBundle mainBundle] URLForResource:@"runtime" withExtension:@"plist"];+ NSError *error = nil;+ NSDictionary *settings = settingsURL+ ? [NSDictionary dictionaryWithContentsOfURL:settingsURL error:&error] : nil;+ if (!settings) {+ return fail(@"The application's Python configuration is missing or unreadable.");+ }+ NSString *executable = absolutePath(settings, @"PythonExecutable");+ NSString *library = absolutePath(settings, @"PythonLibrary");+ NSFileManager *files = [NSFileManager defaultManager];+ if (!executable || ![files isExecutableFileAtPath:executable] ||+ !library || ![files isReadableFileAtPath:library]) {+ return fail(@"The installed Python runtime is missing or inaccessible.");+ }+ if (![settings[@"PythonVersion"] isEqual:@FCC_PYTHON_VERSION]) {+ return fail(@"The application and its Python configuration have different versions.");+ }+ void *runtime = dlopen(library.fileSystemRepresentation, RTLD_NOW | RTLD_GLOBAL);+ if (!runtime) {+ return fail([NSString stringWithFormat:@"Python could not be loaded: %s", dlerror()]);+ }++#define LOAD(result, name, arguments) \+ result (*name) arguments = (result (*) arguments)dlsym(runtime, #name); \+ if (!name) return fail(@"The installed Python runtime is incompatible (missing " @#name @").")++ LOAD(const char *, Py_GetVersion, (void));+ LOAD(PyInitConfig *, PyInitConfig_Create, (void));+ LOAD(void, PyInitConfig_Free, (PyInitConfig *));+ LOAD(int, PyInitConfig_SetInt, (PyInitConfig *, const char *, int64_t));+ LOAD(int, PyInitConfig_SetStr, (PyInitConfig *, const char *, const char *));+ LOAD(int, PyInitConfig_SetStrList, (PyInitConfig *, const char *, size_t, char *const *));+ LOAD(int, PyInitConfig_GetError, (PyInitConfig *, const char **));+ LOAD(int, Py_InitializeFromInitConfig, (PyInitConfig *));+ LOAD(int, Py_RunMain, (void));+#undef LOAD++ const char *version = Py_GetVersion();+ size_t expectedLength = strlen(FCC_PYTHON_VERSION);+ if (strncmp(version, FCC_PYTHON_VERSION, expectedLength) != 0 ||+ (version[expectedLength] != ' ' && version[expectedLength] != '\0')) {+ return fail(@"The installed Python version does not match this desktop launcher.");+ }+ unsetenv("PYTHONEXECUTABLE");+ unsetenv("__PYVENV_LAUNCHER__");+ PyInitConfig *config = PyInitConfig_Create();+ if (!config) return fail(@"Python initialization ran out of memory.");+ // Finder need not supply a locale. Isolated CPython otherwise defaults to ASCII text I/O.+ int status = PyInitConfig_SetInt(config, "utf8_mode", 1);+ if (status == 0) status = PyInitConfig_SetStr(config, "executable", executable.UTF8String);+ if (status == 0) status = PyInitConfig_SetInt(config, "parse_argv", 0);+ if (status == 0) status = PyInitConfig_SetInt(config, "site_import", 1);+ if (status == 0) status = PyInitConfig_SetInt(config, "install_signal_handlers", 1);+ if (status == 0) status = PyInitConfig_SetStrList(config, "argv", (size_t)argc, argv);+ if (status == 0) status = PyInitConfig_SetStr(config, "run_command",+ "from free_claude_code.cli.desktop_entrypoint import launch; launch()\n");+ if (status == 0) status = Py_InitializeFromInitConfig(config);+ if (status < 0) {+ const char *message = NULL;+ PyInitConfig_GetError(config, &message);+ NSString *reason = message ? [NSString stringWithUTF8String:message] : @"Python initialization failed.";+ PyInitConfig_Free(config);+ return fail(reason);+ }+ PyInitConfig_Free(config);+ int exitCode = Py_RunMain();+ if (exitCode != 0) return fail(@"Free Claude Code could not finish starting. Check its logs for details.");+ return 0;+ }+}diff --git a/scripts/publish_release.py b/scripts/publish_release.pyindex e1daf46c..981facac 100644--- a/scripts/publish_release.py+++ b/scripts/publish_release.py@@ -35,7 +35,6 @@ class Publisher:if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository):raise ValueError("Expected owner/repository")self.repository = repository- self.validator = Path(__file__).with_name("validate_release.py").resolve()def gh(self, *args: str) -> str:return command(["gh", "release", *args, "--repo", self.repository])@@ -162,7 +161,13 @@ class Publisher:def validate(self, source: Path, dist: Path, version: str) -> None:command(- [sys.executable, str(self.validator), str(dist), "--version", version],+ [+ sys.executable,+ str(source / "scripts/validate_release.py"),+ str(dist),+ "--version",+ version,+ ],cwd=source,)@@ -184,6 +189,10 @@ class Publisher:# Publication never begins until both uploaded assets are verified.for asset in assets:self.gh("delete-asset", tag, asset["name"], "--yes")+ builder = source / "scripts/build_macos_launcher.py"+ # Historical releases predate the native templates and retain their format.+ if builder.is_file():+ command([sys.executable, str(builder)], cwd=source)command(["uv", "build", "--no-sources", "--out-dir", str(dist)], cwd=source)self.validate(source, dist, version)self.gh("upload", tag, *(str(dist / name) for name in sorted(names)))diff --git a/scripts/uninstall.sh b/scripts/uninstall.shindex b36535db..701af612 100644--- a/scripts/uninstall.sh+++ b/scripts/uninstall.sh@@ -204,11 +204,13 @@ verify_fcc_commands_removed() {macos_app_is_fcc_owned() {app_dir=$1- owner_file="$app_dir/Contents/$FCC_MACOS_OWNER_FILE"- [ -d "$app_dir" ] &&- [ ! -L "$app_dir" ] &&- [ -f "$owner_file" ] &&- [ "$(cat "$owner_file")" = "$FCC_MACOS_BUNDLE_ID" ]+ [ -d "$app_dir" ] && [ ! -L "$app_dir" ] || return 1+ for owner_file in "$app_dir/Contents/Resources/$FCC_MACOS_OWNER_FILE" "$app_dir/Contents/$FCC_MACOS_OWNER_FILE"; do+ if [ -f "$owner_file" ] && [ "$(cat "$owner_file")" = "$FCC_MACOS_BUNDLE_ID" ]; then+ return 0+ fi+ done+ return 1}remove_macos_desktop_app() {diff --git a/scripts/validate_release.py b/scripts/validate_release.pyindex 69274dce..1aee0674 100644--- a/scripts/validate_release.py+++ b/scripts/validate_release.py@@ -10,6 +10,11 @@ import zipfilefrom email.parser import BytesParserfrom pathlib import Path+MACOS_TEMPLATES = {+ f"src/free_claude_code/assets/macos/fcc-desktop-{architecture}"+ for architecture in ("arm64", "x86_64")+}+def require_files(names: set[str], expected: set[str]) -> None:missing = expected - names@@ -47,6 +52,7 @@ def validate(directory: Path, version: str) -> None:sources = set(filter(None, tracked.split("\0")))if "src/free_claude_code/__init__.py" not in sources:raise ValueError("Missing tracked FCC package sources")+ sources |= MACOS_TEMPLATESwith zipfile.ZipFile(wheel_path) as archive:wheel = {file: archive.read(file)@@ -73,9 +79,22 @@ def validate(directory: Path, version: str) -> None:| {f"{stem}/scripts/update/{script}" for script in updater_names}| {f"{stem}/{file}"- for file in ("pyproject.toml", "README.md", "LICENSE", "PKG-INFO")+ for file in (+ "pyproject.toml",+ "README.md",+ "LICENSE",+ "PKG-INFO",+ "scripts/build_macos_launcher.py",+ "scripts/macos/launcher.m",+ )},)+ for template in MACOS_TEMPLATES:+ data = wheel[template.removeprefix("src/")]+ if not data or data != source[f"{stem}/{template}"]:+ raise ValueError(+ f"Native template differs between wheel and sdist: {template}"+ )for data in (wheel[f"{wheel_info}/METADATA"], source[f"{stem}/PKG-INFO"]):metadata = BytesParser().parsebytes(data)if metadata["Name"] != name or metadata["Version"] != version:diff --git a/smoke/desktop/conftest.py b/smoke/desktop/conftest.pynew file mode 100644index 00000000..4d15fce0--- /dev/null+++ b/smoke/desktop/conftest.py@@ -0,0 +1,137 @@+"""Native desktop checks use a private installed environment and application."""++import os+import plistlib+import shutil+import subprocess+import sys+import tomllib+from pathlib import Path++import pytest++ROOT = Path(__file__).resolve().parents[2]++[email protected](scope="session")+def installed_desktop(tmp_path_factory):+ if sys.platform != "darwin":+ pytest.skip("requires a macOS GUI session")+ root = tmp_path_factory.mktemp("FCC's 日本語 desktop")+ home = root / "home"+ home.mkdir()+ env = os.environ | {"HOME": str(home)}+ # CI's legacy preference option conflicts with the explicit managed-only flag.+ env.pop("UV_PYTHON_PREFERENCE", None)+ output = ROOT / "test-results/native"+ output.mkdir(parents=True, exist_ok=True)+ dist = output / "dist"+ subprocess.run(+ ["uv", "build", "--out-dir", str(dist)],+ cwd=ROOT,+ env=env | {"SETUPTOOLS_SCM_PRETEND_VERSION": "0.0.0"},+ check=True,+ timeout=120,+ )+ subprocess.run(+ [+ sys.executable,+ str(ROOT / "scripts/validate_release.py"),+ str(dist),+ "--version",+ "0.0.0",+ ],+ cwd=ROOT,+ check=True,+ timeout=30,+ )+ requirements = root / "requirements.txt"+ subprocess.run(+ [+ "uv",+ "export",+ "--locked",+ "--no-dev",+ "--no-emit-project",+ "--output-file",+ str(requirements),+ ],+ cwd=ROOT,+ check=True,+ timeout=60,+ stdout=subprocess.DEVNULL,+ )+ version = tomllib.loads((ROOT / "pyproject.toml").read_text())["project"][+ "requires-python"+ ].removeprefix("==")++ def create_venv(venv):+ subprocess.run(+ ["uv", "venv", "--managed-python", "--python", f"{version}+gil", str(venv)],+ env=env,+ check=True,+ timeout=60,+ )+ python = venv / "bin/python"+ subprocess.run(+ ["uv", "pip", "sync", "--python", str(python), str(requirements)],+ env=env,+ check=True,+ timeout=180,+ )+ wheel = next(dist.glob("*.whl"))+ subprocess.run(+ ["uv", "pip", "install", "--no-deps", "--python", str(python), str(wheel)],+ env=env,+ check=True,+ timeout=60,+ )+ packages = Path(+ subprocess.check_output(+ [str(python), "-c", "import site; print(site.getsitepackages()[0])"],+ env=env,+ text=True,+ ).strip()+ )+ for source, target in (+ ("identity_probe.py", "fcc_identity_probe.py"),+ ("lifecycle_probe.py", "fcc_native_probe.py"),+ ):+ shutil.copyfile(Path(__file__).with_name(source), packages / target)+ (packages / "zzz_fcc_native_probe.pth").write_text(+ "import fcc_native_probe; fcc_native_probe.install()\n"+ )++ venv = root / "installed venv"+ python = venv / "bin/python"+ create_venv(venv)+ subprocess.run(+ [str(venv / "bin/fcc-desktop"), "--install-macos-app"],+ env=env,+ check=True,+ timeout=30,+ )+ app = home / "Applications/Free Claude Code.app"+ with (app / "Contents/Resources/runtime.plist").open("rb") as stream:+ runtime = plistlib.load(stream)+ # Launch Services receives explicit private settings; no launchd-wide changes.+ launch_env = {+ "HOME": str(home),+ "PATH": "/usr/bin:/bin:/usr/sbin:/sbin",+ "FCC_OPEN_BROWSER": "false",+ "HOST": "127.0.0.1",+ "XDG_CONFIG_HOME": str(home / ".config"),+ "XDG_CACHE_HOME": str(home / ".cache"),+ }+ yield {+ "root": root,+ "home": home,+ "venv": venv,+ "python": python,+ "app": app,+ "output": output,+ "env": env,+ "launch_env": launch_env,+ "runtime": runtime,+ "create_venv": create_venv,+ }diff --git a/smoke/desktop/identity_probe.py b/smoke/desktop/identity_probe.pynew file mode 100644index 00000000..58d9481f--- /dev/null+++ b/smoke/desktop/identity_probe.py@@ -0,0 +1,113 @@+"""Observe real AppKit process identity and status-item geometry."""++import json+import locale+import os+import subprocess+import sys+import threading+import time+from importlib import import_module+from pathlib import Path++from PIL import Image+from pystray import Icon, Menu, MenuItem+++def write_report(output, report):+ pending = output.with_suffix(".pending")+ pending.write_text(json.dumps(report, indent=2), encoding="utf-8")+ pending.replace(output)+++def process_report():+ Foundation = import_module("Foundation")+ AppKit = import_module("AppKit")+ bundle = Foundation.NSBundle.mainBundle()+ extensions = [+ "PIL._imaging",+ "pydantic_core._pydantic_core",+ "grpc._cython.cygrpc",+ "tiktoken._tiktoken",+ ]+ for extension in extensions:+ import_module(extension)+ from free_claude_code.cli.launchers.common import server_command++ return {+ "pid": os.getpid(),+ "process_executable": subprocess.check_output(+ ["/bin/ps", "-p", str(os.getpid()), "-o", "comm="], text=True+ ).strip(),+ "executable": sys.executable,+ "text_encoding": locale.getpreferredencoding(False),+ "prefix": sys.prefix,+ "base_prefix": sys.base_prefix,+ "bundle_path": str(bundle.bundlePath()),+ "bundle_id": bundle.bundleIdentifier(),+ "application_bundle_id": AppKit.NSRunningApplication.currentApplication().bundleIdentifier(),+ "main_thread": threading.current_thread() is threading.main_thread(),+ "extensions": extensions,+ "server_command": server_command(),+ "macos_version": subprocess.check_output(+ ["/usr/bin/sw_vers", "-productVersion"], text=True+ ).strip(),+ }+++def tray_report(icon):+ Foundation = import_module("Foundation")+ item = icon._status_item+ window = item.button().window()+ screen = window.screen() if window is not None else None+ frame = window.frame() if window is not None else None+ return {+ "visible": bool(item.isVisible()),+ "button_hidden": bool(item.button().isHidden()),+ "screen": bool(screen),+ "frame": [frame.origin.x, frame.origin.y, frame.size.width, frame.size.height]+ if frame is not None+ else None,+ "intersects_screen": bool(+ frame is not None+ and screen is not None+ and Foundation.NSIntersectsRect(frame, screen.frame())+ ),+ }+++def main():+ Foundation = import_module("Foundation")+ output = Path(os.environ["FCC_MACOS_PROBE_OUTPUT"])+ report = process_report()+ write_report(output, report)+ icon = Icon(+ "fcc-launcher-probe",+ Image.new("RGB", (32, 32), "red"),+ "FCC launcher probe",+ Menu(MenuItem("Quit", lambda item: item.stop())),+ )+ # Give both launch paths the same AppKit layout observation interval.+ ready_at = time.monotonic() + 2++ def observe(_timer):+ if time.monotonic() < ready_at:+ return+ report.update(tray_report(icon))+ write_report(output, report)+ if output.with_suffix(".captured").exists():+ icon.stop()++ timer = Foundation.NSTimer.scheduledTimerWithTimeInterval_repeats_block_(+ 0.1, True, observe+ )+ try:+ icon.run()+ finally:+ timer.invalidate()+ report["loop_finished"] = True+ write_report(output, report)+++if __name__ == "__main__":+ main()diff --git a/smoke/desktop/lifecycle_probe.py b/smoke/desktop/lifecycle_probe.pynew file mode 100644index 00000000..6c8ac1c9--- /dev/null+++ b/smoke/desktop/lifecycle_probe.py@@ -0,0 +1,127 @@+"""Test-only instrumentation installed in a disposable FCC environment."""++import asyncio+import multiprocessing+import os+import sys+import traceback+from importlib import import_module+from pathlib import Path+from typing import Never+from unittest.mock import patch++_installed = False+++def _spawned_child(queue):+ import free_claude_code++ queue.put(+ {+ "executable": sys.executable,+ "prefix": sys.prefix,+ "package": free_claude_code.__file__,+ }+ )+++def subprocess_checks():+ from free_claude_code.runtime.folder_picker import NativeFolderPicker++ expected = str(Path.home())+ os.environ["FCC_NATIVE_DIALOG_RESULT"] = expected+ try:+ selected = asyncio.run(NativeFolderPicker().pick_folder(expected))+ finally:+ del os.environ["FCC_NATIVE_DIALOG_RESULT"]+ context = multiprocessing.get_context("spawn")+ queue = context.Queue()+ child = context.Process(target=_spawned_child, args=(queue,))+ child.start()+ try:+ result = queue.get(timeout=20)+ child.join(20)+ assert child.exitcode == 0+ finally:+ if child.is_alive():+ child.kill()+ child.join()+ queue.close()+ queue.join_thread()+ return {"folder": selected, "child": result}+++def install():+ global _installed+ case = os.environ.get("FCC_NATIVE_CASE")+ if not case or _installed:+ return+ _installed = True+ if "FCC_NATIVE_DIALOG_RESULT" in os.environ:+ original_exec = os.execv++ def dialog_exec(path, argv, /) -> Never:+ if path == "/usr/bin/osascript":+ print(os.environ["FCC_NATIVE_DIALOG_RESULT"], flush=True)+ raise SystemExit(0)+ original_exec(path, argv)++ patch.object(os, "execv", dialog_exec).start()+ identity = import_module("fcc_identity_probe")+ if case == "identity":+ from free_claude_code.cli import desktop_entrypoint++ desktop_entrypoint.launch = identity.main+ return+ from free_claude_code.cli.desktop_tray import PystrayDesktopTray+ from free_claude_code.runtime.integration_service import IntegrationService+ from free_claude_code.runtime.provider_manager import ProviderRuntimeManager++ # Keep the real tray/server lifecycle, with external discovery and harness writes disabled.+ ProviderRuntimeManager.start_model_list_refresh = lambda self: None++ async def no_integrations(self):+ return None++ IntegrationService.start = no_integrations+ original_run = PystrayDesktopTray.run+ Foundation = import_module("Foundation")++ def observed_run(self, setup):+ output = Path(os.environ["FCC_MACOS_PROBE_OUTPUT"])+ control = output.with_suffix(".command")+ report = identity.process_report()+ identity.write_report(output, report)++ def observe(_timer):+ try:+ report.update(identity.tray_report(self._icon))+ report["server_status"] = str(self._controller.status)+ if control.exists():+ command = control.read_text()+ control.unlink()+ if command == "subprocess":+ report["subprocess"] = subprocess_checks()+ else:+ menu = self._icon._status_item.menu()+ index = menu.indexOfItemWithTitle_(command)+ assert index >= 0, command+ menu.performActionForItemAtIndex_(index)+ report.setdefault("actions", []).append(command)+ identity.write_report(output, report)+ except Exception:+ report["error"] = traceback.format_exc()+ identity.write_report(output, report)+ self._controller.quit()++ timer = Foundation.NSTimer.scheduledTimerWithTimeInterval_repeats_block_(+ 0.1, True, observe+ )+ try:+ original_run(self, setup)+ finally:+ timer.invalidate()+ report["loop_finished"] = True+ identity.write_report(output, report)++ PystrayDesktopTray.run = observed_rundiff --git a/smoke/desktop/rebuild_sdist.py b/smoke/desktop/rebuild_sdist.pynew file mode 100644index 00000000..2efc9c61--- /dev/null+++ b/smoke/desktop/rebuild_sdist.py@@ -0,0 +1,37 @@+"""Verify a published-style sdist retains both launchers on a non-Mac builder."""++import argparse+import subprocess+import sys+import tempfile+import zipfile+from pathlib import Path+++def check(directory: Path) -> None:+ if sys.platform == "darwin":+ raise ValueError("Run this portability check on Windows or Linux")+ source = next(directory.glob("*.tar.gz"))+ original = next(directory.glob("*.whl"))+ with tempfile.TemporaryDirectory(prefix="fcc-sdist-rebuild-") as temporary:+ subprocess.run(+ ["uv", "build", "--wheel", str(source), "--out-dir", temporary],+ check=True,+ )+ rebuilt = next(Path(temporary).glob("*.whl"))+ assert rebuilt.name == original.name+ with zipfile.ZipFile(original) as before, zipfile.ZipFile(rebuilt) as after:+ for architecture in ("arm64", "x86_64"):+ name = f"free_claude_code/assets/macos/fcc-desktop-{architecture}"+ assert before.read(name) and before.read(name) == after.read(name)+ print(f"Preserved {name}: {len(after.read(name))} bytes")+ entrypoints = next(+ name for name in before.namelist() if name.endswith("/entry_points.txt")+ )+ assert before.read(entrypoints) == after.read(entrypoints)+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("directory", type=Path)+ check(parser.parse_args().directory)diff --git a/smoke/desktop/support.py b/smoke/desktop/support.pynew file mode 100644index 00000000..11256e39--- /dev/null+++ b/smoke/desktop/support.py@@ -0,0 +1,123 @@+"""Launch and observe only the disposable applications owned by a native test."""++import json+import os+import signal+import subprocess+import sys+import time+from contextlib import contextmanager, suppress+from pathlib import Path+++def pid_alive(pid):+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return False+ return True+++def wait_exit(pid):+ deadline = time.monotonic() + 10+ while pid_alive(pid) and time.monotonic() < deadline:+ time.sleep(0.1)+ assert not pid_alive(pid), f"Test process {pid} did not exit"+++def wait_report(output, predicate, process, timeout=30):+ deadline = time.monotonic() + timeout+ report = {}+ while time.monotonic() < deadline:+ if output.exists():+ report = json.loads(output.read_text())+ assert "error" not in report, report.get("error")+ if predicate(report):+ return report+ # Launch Services can stop tracking the old shell wrapper after exec.+ assert process.poll() is None or (+ report.get("pid") and pid_alive(report["pid"])+ ), f"Launcher exited before observation: {report}"+ time.sleep(0.1)+ raise AssertionError(f"Native observation timed out: {report}")+++def capture(output):+ result = subprocess.run(+ ["/usr/sbin/screencapture", "-x", str(output.with_suffix(".png"))],+ capture_output=True,+ text=True,+ timeout=10,+ check=False,+ )+ output.with_suffix(".capture.json").write_text(+ json.dumps(+ {+ "returncode": result.returncode,+ "stderr": result.stderr,+ }+ )+ )+++def process_paths():+ rows = subprocess.check_output(["/bin/ps", "-axo", "pid=,comm="], text=True)+ result = {}+ for row in rows.splitlines():+ pid, _, executable = row.strip().partition(" ")+ result[int(pid)] = executable.strip()+ return result+++def bundle_pids(app):+ return {+ pid+ for pid, executable in process_paths().items()+ if executable == str(app / "Contents/MacOS/fcc-desktop")+ }+++@contextmanager+def launched(app, output, env, *, args=(), wait=True):+ existing = set(process_paths())+ for path in (+ output,+ output.with_suffix(".captured"),+ output.with_suffix(".command"),+ ):+ path.unlink(missing_ok=True)+ command = ["/usr/bin/open", "-n"]+ if wait:+ command.append("-W")+ for key, value in (env | {"FCC_MACOS_PROBE_OUTPUT": str(output)}).items():+ command.extend(["--env", f"{key}={value}"])+ command.extend(["--stderr", str(output.with_suffix(".stderr.log")), str(app)])+ if args:+ command.extend(["--args", *args])+ with subprocess.Popen(+ command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True+ ) as process:+ try:+ yield process+ finally:+ if wait or process.poll() is None:+ owned = bundle_pids(app)+ if output.exists():+ report = json.loads(output.read_text())+ pid = report.get("pid")+ executable = process_paths().get(pid)+ if (+ executable == report.get("process_executable")+ and executable+ and Path(executable).is_relative_to(Path(env["HOME"]).parent)+ ):+ owned.add(pid)+ for pid in owned - existing:+ with suppress(ProcessLookupError):+ if sys.platform == "darwin":+ os.kill(pid, signal.SIGKILL)+ try:+ process.wait(timeout=10)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait()diff --git a/smoke/desktop/test_macos_launcher.py b/smoke/desktop/test_macos_launcher.pynew file mode 100644index 00000000..9b968084--- /dev/null+++ b/smoke/desktop/test_macos_launcher.py@@ -0,0 +1,91 @@+"""Compare the historical shell app with the installed native launcher."""++import json+import shlex+import subprocess+import sys+from pathlib import Path++import pytest++from smoke.desktop.support import capture, launched, wait_exit, wait_report++pytestmark = pytest.mark.skipif(sys.platform != "darwin", reason="requires macOS")++[email protected](scope="module")+def observed_launches(installed_desktop):+ installed = installed_desktop+ probe = Path(__file__).with_name("identity_probe.py")+ output = installed["output"] / "terminal.json"+ output.unlink(missing_ok=True)+ output.with_suffix(".captured").unlink(missing_ok=True)+ env = installed["launch_env"] | {"FCC_MACOS_PROBE_OUTPUT": str(output)}+ with subprocess.Popen([str(installed["python"]), str(probe)], env=env) as process:+ try:+ terminal = wait_report(output, lambda r: "intersects_screen" in r, process)+ capture(output)+ output.with_suffix(".captured").touch()+ assert process.wait(timeout=10) == 0+ finally:+ if process.poll() is None:+ process.kill()+ process.wait()+ # Preserve the pre-fix exec wrapper as the regression control.+ legacy = installed["home"] / "Legacy FCC.app"+ contents = legacy / "Contents"+ (contents / "MacOS").mkdir(parents=True)+ (contents / "Info.plist").write_bytes(+ (installed["app"] / "Contents/Info.plist").read_bytes()+ )+ (contents / "Resources").mkdir()+ (contents / "Resources/AppIcon.icns").write_bytes(+ (installed["app"] / "Contents/Resources/AppIcon.icns").read_bytes()+ )+ executable = contents / "MacOS/fcc-desktop"+ executable.write_text(+ f"#!/bin/sh\nexec {shlex.quote(str(installed['python']))} {shlex.quote(str(probe))}\n"+ )+ executable.chmod(0o755)+ reports = []+ for name, app, extra in (+ ("legacy", legacy, {}),+ ("native", installed["app"], {"FCC_NATIVE_CASE": "identity"}),+ ):+ output = installed["output"] / f"{name}.json"+ with launched(app, output, installed["launch_env"] | extra) as process:+ report = wait_report(output, lambda r: "intersects_screen" in r, process)+ capture(output)+ output.with_suffix(".captured").touch()+ assert process.wait(timeout=10) == 0+ wait_exit(report["pid"])+ print(json.dumps(report, indent=2))+ reports.append(report)+ return terminal, *reports+++def test_finder_launch_keeps_fcc_bundle_identity(installed_desktop, observed_launches):+ _terminal, legacy, actual = observed_launches+ assert legacy["bundle_id"] != "io.github.alishahryar1.free-claude-code"+ assert actual["bundle_id"] == "io.github.alishahryar1.free-claude-code"+ assert Path(actual["bundle_path"]).resolve() == installed_desktop["app"].resolve()+ assert (+ Path(actual["process_executable"]).resolve()+ == (installed_desktop["app"] / "Contents/MacOS/fcc-desktop").resolve()+ )+ assert actual["main_thread"]+ assert actual["text_encoding"].lower().replace("-", "") == "utf8"+ assert actual["executable"] == str(installed_desktop["python"])+ assert actual["prefix"] == str(installed_desktop["venv"])+ assert actual["server_command"] == [+ str(installed_desktop["venv"] / "bin/fcc-desktop"),+ "--auto-started",+ ]+++def test_finder_status_item_is_placed_on_screen(observed_launches):+ terminal, _legacy, actual = observed_launches+ assert terminal["intersects_screen"], terminal+ assert actual["visible"] and not actual["button_hidden"], actual+ assert actual["intersects_screen"], actual+ assert actual["frame"][2] > 0 and actual["frame"][3] > 0diff --git a/smoke/desktop/test_macos_lifecycle.py b/smoke/desktop/test_macos_lifecycle.pynew file mode 100644index 00000000..a0dff048--- /dev/null+++ b/smoke/desktop/test_macos_lifecycle.py@@ -0,0 +1,177 @@+"""The installed native app keeps FCC's server, menu, and subprocess contracts."""++import json+import plistlib+import socket+import subprocess+import sys+import time+from pathlib import Path++import httpx+import pytest++from free_claude_code.cli.commands import ServerStatus+from smoke.desktop.support import bundle_pids, capture, launched, wait_report++ROOT = Path(__file__).resolve().parents[2]+pytestmark = pytest.mark.skipif(sys.platform != "darwin", reason="requires macOS")+++def wait_status(port, *, previous=None):+ deadline = time.monotonic() + 30+ with httpx.Client(trust_env=False, timeout=1) as client:+ while time.monotonic() < deadline:+ try:+ response = client.get(f"http://127.0.0.1:{port}/admin/api/status")+ response.raise_for_status()+ status = response.json()+ if status["status"] == "running" and status["instance_id"] != previous:+ return status+ except httpx.HTTPError, ValueError:+ pass+ time.sleep(0.1)+ raise AssertionError("FCC did not serve a new running instance")+++def command(output, action):+ pending = output.with_suffix(".next-command")+ pending.write_text(action)+ pending.replace(output.with_suffix(".command"))+++def test_installed_native_app_lifecycle(installed_desktop):+ installed = installed_desktop+ with socket.socket() as reservation:+ reservation.bind(("127.0.0.1", 0))+ port = reservation.getsockname()[1]+ env = installed["launch_env"] | {"PORT": str(port), "FCC_NATIVE_CASE": "lifecycle"}+ output = installed["output"] / "lifecycle.json"+ with launched(installed["app"], output, env) as process:+ report = wait_report(+ output,+ lambda r: (+ r.get("intersects_screen")+ and r.get("server_status") == ServerStatus.RUNNING+ ),+ process,+ )+ capture(output)+ initial = wait_status(port)+ # Exercise the real process discovery in both shell scripts without uninstalling.+ for script, body in (+ ("install.sh", "assert_no_fcc_processes_running"),+ ("uninstall.sh", "fcc_process_ids fcc-desktop"),+ ):+ source = (+ (ROOT / "scripts" / script)+ .read_text()+ .split('\nparse_args "$@"\n', 1)[0]+ )+ scenario = installed["root"] / f"guard-{script}"+ scenario.write_text(source + "\n" + body + "\n")+ guard = subprocess.run(+ ["/bin/sh", str(scenario)],+ env=installed["env"],+ capture_output=True,+ text=True,+ timeout=20,+ check=False,+ )+ assert str(report["pid"]) in guard.stdout + guard.stderr+ assert (guard.returncode != 0) == (script == "install.sh")+ finder_duplicate = installed["output"] / "finder-duplicate.json"+ with launched(+ installed["app"],+ finder_duplicate,+ env,+ args=("--auto-started",),+ wait=False,+ ) as second:+ assert second.wait(timeout=10) == 0+ duplicate = installed["output"] / "duplicate.json"+ with (+ duplicate.with_suffix(".stderr.log").open("w") as errors,+ subprocess.Popen(+ [+ str(installed["app"] / "Contents/MacOS/fcc-desktop"),+ "--auto-started",+ ],+ env=env | {"FCC_MACOS_PROBE_OUTPUT": str(duplicate)},+ stdout=subprocess.DEVNULL,+ stderr=errors,+ ) as second,+ ):+ try:+ assert second.wait(timeout=30) == 0+ finally:+ if second.poll() is None:+ second.kill()+ second.wait()+ duplicate_report = json.loads(duplicate.read_text())+ assert duplicate_report["pid"] != report["pid"]+ assert duplicate_report["loop_finished"]+ assert bundle_pids(installed["app"]) == {report["pid"]}+ assert wait_status(port)["instance_id"] == initial["instance_id"]++ command(output, "subprocess")+ report = wait_report(output, lambda r: "subprocess" in r, process)+ children = report["subprocess"]+ assert children["folder"] == str(installed["home"])+ assert children["child"]["executable"] == str(installed["python"])+ assert children["child"]["prefix"] == str(installed["venv"])+ assert Path(children["child"]["package"]).is_relative_to(installed["venv"])++ command(output, "Restart Server")+ restarted = wait_status(port, previous=initial["instance_id"])+ assert restarted["instance_id"] != initial["instance_id"]+ assert process.poll() is None+ command(output, "Quit")+ assert process.wait(timeout=30) == 0+ report = json.loads(output.read_text())+ assert report["actions"] == ["Restart Server", "Quit"]+ assert report["loop_finished"]+ with socket.socket() as freed:+ assert freed.connect_ex(("127.0.0.1", port)) != 0+ assert bundle_pids(installed["app"]) == set()+ with socket.socket() as freed:+ freed.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ freed.bind(("127.0.0.1", port))+ # Locks must be available to a fresh interpreter after Quit.+ subprocess.run(+ [+ str(installed["python"]),+ "-c",+ "from pathlib import Path; from free_claude_code.core.interprocess_lock import InterprocessFileLock; "+ "locks=[InterprocessFileLock(Path.home()/'.fcc'/name) for name in ('desktop.lock','server.owner.lock')]; "+ "assert all(lock.acquire() for lock in locks); [lock.release() for lock in locks]",+ ],+ env=installed["env"],+ check=True,+ timeout=30,+ )++ updated = installed["root"] / "updated venv"+ installed["create_venv"](updated)+ subprocess.run(+ [str(updated / "bin/fcc-desktop"), "--install-macos-app"],+ env=installed["env"],+ check=True,+ timeout=30,+ )+ with (installed["app"] / "Contents/Resources/runtime.plist").open("rb") as stream:+ assert plistlib.load(stream)["PythonExecutable"] == str(updated / "bin/python")+ output = installed["output"] / "updated.json"+ with launched(installed["app"], output, env) as process:+ report = wait_report(+ output,+ lambda r: (+ r.get("intersects_screen")+ and r.get("server_status") == ServerStatus.RUNNING+ ),+ process,+ )+ assert report["executable"] == str(updated / "bin/python")+ wait_status(port)+ command(output, "Quit")+ assert process.wait(timeout=30) == 0diff --git a/smoke/installers/test_installers.py b/smoke/installers/test_installers.pyindex 1646550a..0578dc00 100644--- a/smoke/installers/test_installers.py+++ b/smoke/installers/test_installers.py@@ -825,10 +825,8 @@ echo "$name:$*" >> "$CALL_LOG"if [ "$FAIL_STEP" = "fcc-verify" ]; thenexit 36fi-if [ "$name" = "fcc-desktop" ] && [ "${1:-}" = "--export-icon" ]; then- [ "$FAIL_STEP" = "desktop-icon-export" ] && exit 37- mkdir -p "$(dirname "$2")"- printf 'fake icon\n' > "$2"+if [ "$name" = "fcc-desktop" ] && [ "${1:-}" = "--install-macos-app" ]; then+ [ "$FAIL_STEP" = "macos-app-setup" ] && exit 37fiif [ "$name" = "fcc-server" ] && [ "${1:-}" = "--version" ]; thenecho "free-claude-code 3.5.18"@@ -1604,47 +1602,69 @@ def test_install_sh_rejects_uninstalled_only_selection(_assert_uv_ready_without_fcc_install(posix_harness.calls())-def test_install_sh_creates_native_macos_app_and_desktop_link(- posix_harness: PosixHarness,-) -> None:+def test_install_sh_delegates_macos_bundle_to_installed_helper(posix_harness):posix_harness.env["FAKE_UNAME"] = "Darwin"- tool_bin = posix_harness.root / "tool's bin"- posix_harness.env["FAKE_TOOL_BIN"] = str(tool_bin)-+ posix_harness.env["FAKE_TOOL_BIN"] = str(posix_harness.root / "tool's bin")result = posix_harness.run()+ assert result.returncode == 0, result.stderr+ calls = posix_harness.calls()+ assert calls.count("fcc-desktop:--install-macos-app") == 1+ assert calls.index("fcc-server:--version") < calls.index(+ "fcc-desktop:--install-macos-app"+ )+ install = next(+ call for call in calls if "--refresh-package free-claude-code" in call+ )+ assert "--managed-python" in install and "+gil" in install++ "system,preference", [("Darwin", "unset"), ("Linux", "system")]+)+def test_install_sh_macos_python_selection_overrides_only_its_preference(+ posix_harness, system, preference+):+ posix_harness.env["FAKE_UNAME"] = system+ posix_harness.env["UV_PYTHON_PREFERENCE"] = "system"+ _write_executable(+ posix_harness.bin_dir / "uv",+ _posix_uv_command("0.12.13").replace(+ "#!/bin/sh\n",+ f'#!/bin/sh\n[ "${{UV_PYTHON_PREFERENCE-unset}}" = "{preference}" ] || exit 83\n',+ 1,+ ),+ )+ result = posix_harness.run_functions("install_free_claude_code")assert result.returncode == 0, result.stderr- app = posix_harness.root / "home" / "Applications" / "Free Claude Code.app"- plist = app / "Contents" / "Info.plist"- owner_file = app / "Contents" / ".free-claude-code-owner"- launcher = app / "Contents" / "MacOS" / "fcc-desktop"- icon = app / "Contents" / "Resources" / "AppIcon.icns"- desktop_link = posix_harness.root / "home" / "Desktop" / "Free Claude Code.app"- assert owner_file.read_text(encoding="utf-8").strip() == (- "io.github.alishahryar1.free-claude-code"- )- plist_text = plist.read_text(encoding="utf-8")- assert "<key>CFBundleIconFile</key>" in plist_text- assert "<string>AppIcon</string>" in plist_text- assert "<key>LSUIElement</key>" in plist_text- assert "<key>LSMultipleInstancesProhibited</key>" in plist_text- assert icon.read_bytes() == b"fake icon\n"- assert launcher.stat().st_mode & 0o111- expected_command = str(tool_bin / "fcc-desktop").replace("'", "'\\''")- assert f"exec '{expected_command}'" in launcher.read_text(encoding="utf-8")- assert desktop_link.is_symlink()- assert desktop_link.readlink() == app- assert any(- call == f"fcc-desktop:--export-icon {icon}" for call in posix_harness.calls()+ install = next(+ call+ for call in posix_harness.calls()+ if "--refresh-package free-claude-code" in call)+ assert ("--managed-python" in install) == (system == "Darwin")+ assert ("+gil" in install) == (system == "Darwin")++[email protected]("system,dry_run", [("Darwin", True), ("Linux", False)])+def test_install_sh_macos_helper_dry_run_and_platform_scope(+ posix_harness, system, dry_run+):+ posix_harness.env["FAKE_UNAME"] = system+ result = posix_harness.run_functions(+ f"dry_run={int(dry_run)}\ninstall_macos_desktop_app"+ )+ assert result.returncode == 0, result.stderr+ assert not any(call.startswith("fcc-desktop:") for call in posix_harness.calls())+ assert ("--install-macos-app" in result.stdout) == dry_run+ assert not (posix_harness.root / "home/Applications").exists()-def test_install_sh_stops_if_macos_icon_export_fails(+def test_install_sh_stops_if_macos_bundle_setup_fails(posix_harness: PosixHarness,) -> None:posix_harness.env["FAKE_UNAME"] = "Darwin"- result = posix_harness.run(fail_step="desktop-icon-export")+ result = posix_harness.run(fail_step="macos-app-setup")assert result.returncode != 0assert "Command failed with exit code 37" in result.stderr@@ -1656,61 +1676,20 @@ def test_install_sh_stops_if_macos_icon_export_fails().exists()-def test_install_sh_rejects_unowned_macos_app_bundle(- posix_harness: PosixHarness,-) -> None:- posix_harness.env["FAKE_UNAME"] = "Darwin"- app = posix_harness.root / "home" / "Applications" / "Free Claude Code.app"- contents = app / "Contents"- contents.mkdir(parents=True)- plist = contents / "Info.plist"- plist.write_text("foreign app", encoding="utf-8")-- result = posix_harness.run()-- assert result.returncode != 0- assert "not managed by Free Claude Code" in result.stderr- assert plist.read_text(encoding="utf-8") == "foreign app"- assert not (contents / ".free-claude-code-owner").exists()---def test_install_sh_preserves_unrelated_macos_desktop_link(- posix_harness: PosixHarness,-) -> None:- posix_harness.env["FAKE_UNAME"] = "Darwin"- desktop = posix_harness.root / "home" / "Desktop"- desktop.mkdir()- unrelated = posix_harness.root / "Unrelated.app"- unrelated.mkdir()- desktop_link = desktop / "Free Claude Code.app"- desktop_link.symlink_to(unrelated, target_is_directory=True)-- result = posix_harness.run()-- assert result.returncode == 0, result.stderr- assert "non-FCC link" in result.stdout- assert desktop_link.readlink() == unrelated--@pytest.mark.parametrize("uv_version", ("0.12.13", "0.12.13+build.1", "0.12.14"))-def test_install_sh_preserves_valid_existing_tools(- posix_harness: PosixHarness,- uv_version: str,+def test_install_sh_preserves_compatible_uv(+ posix_harness: PosixHarness, uv_version: str) -> None:- posix_harness.add_client("claude")- posix_harness.add_client("codex")- posix_harness.add_client("pi")- posix_harness.add_client("cline")- posix_harness.add_client("hermes")- posix_harness.add_client("grok")- posix_harness.add_client("muse")- posix_harness.add_client("aider")posix_harness.add_uv(uv_version)+ executable = posix_harness.bin_dir / "uv"+ original = executable.read_bytes()- result = posix_harness.run()+ result = posix_harness.run_functions("ensure_uv")assert result.returncode == 0, result.stderrassert not any(call.startswith("download:") for call in posix_harness.calls())+ assert "uv-install" not in posix_harness.calls()+ assert executable.read_bytes() == originalassert "leaving it unchanged" in result.stdoutdiff --git a/smoke/installers/test_uninstallers.py b/smoke/installers/test_uninstallers.pyindex 81a1432a..ca1c1ba5 100644--- a/smoke/installers/test_uninstallers.py+++ b/smoke/installers/test_uninstallers.py@@ -247,9 +247,16 @@ printf '%s\n' "$FAKE_UNAME"return PosixUninstallHarness(home, bin_dir, tool_bin, fcc_home, log, env)[email protected]("marker_directory", ["Contents", "Contents/Resources"])def test_uninstall_sh_removes_and_verifies_only_fcc(posix_uninstall_harness: PosixUninstallHarness,+ marker_directory: str,) -> None:+ app = posix_uninstall_harness.home / "Applications/Free Claude Code.app"+ if marker_directory != "Contents":+ destination = app / marker_directory / ".free-claude-code-owner"+ destination.parent.mkdir()+ (app / "Contents/.free-claude-code-owner").rename(destination)result = posix_uninstall_harness.run()assert result.returncode == 0, result.stderrdiff --git a/src/free_claude_code/cli/desktop_entrypoint.py b/src/free_claude_code/cli/desktop_entrypoint.pyindex 9636de74..2db45288 100644--- a/src/free_claude_code/cli/desktop_entrypoint.py+++ b/src/free_claude_code/cli/desktop_entrypoint.py@@ -1,5 +1,6 @@"""Lightweight entrypoint for the optional FCC desktop shell."""+import subprocessimport sysfrom collections.abc import Sequencefrom pathlib import Path@@ -15,6 +16,15 @@ def launch(argv: Sequence[str] | None = None) -> None:if len(args) == 2 and args[0] == "--export-icon":export_app_icon(Path(args[1]))return+ if args == ("--install-macos-app",) and sys.platform == "darwin":+ from free_claude_code.cli.macos_app import install++ try:+ install()+ except (OSError, ValueError, subprocess.CalledProcessError) as error:+ print(f"Could not install the macOS app: {error}", file=sys.stderr)+ raise SystemExit(1) from error+ returnauto_started = args == ("--auto-started",)if args and not auto_started:print("Usage: fcc-desktop [--export-icon PATH]", file=sys.stderr)diff --git a/src/free_claude_code/cli/macos_app.py b/src/free_claude_code/cli/macos_app.pynew file mode 100644index 00000000..abea7ad1--- /dev/null+++ b/src/free_claude_code/cli/macos_app.py@@ -0,0 +1,147 @@+"""Construct the macOS application around the installed managed Python runtime."""++import os+import platform+import plistlib+import shutil+import subprocess+import sys+import sysconfig+import tempfile+from importlib.metadata import metadata+from importlib.resources import files+from pathlib import Path++from packaging.specifiers import SpecifierSet++from free_claude_code.cli.desktop_assets import export_app_icon++BUNDLE_ID = "io.github.alishahryar1.free-claude-code"+OWNER_FILE = ".free-claude-code-owner"+++def runtime_settings() -> tuple[dict[str, str], str]:+ """Keep the venv executable while locating the standalone runtime's library."""+ if (+ platform.python_implementation() != "CPython"+ or sysconfig.get_config_var("Py_GIL_DISABLED")+ or sysconfig.get_config_var("Py_DEBUG")+ ):+ raise ValueError(+ "The desktop app requires a GIL-enabled CPython release build."+ )+ version = platform.python_version()+ requirement = metadata("free-claude-code")["Requires-Python"]+ if not requirement or version not in SpecifierSet(requirement):+ raise ValueError(+ "The installed Python version does not match Free Claude Code."+ )+ architecture = platform.machine()+ if architecture not in {"arm64", "x86_64"}:+ raise ValueError(f"Unsupported macOS Python architecture: {architecture}")+ # Do not resolve this symlink: CPython needs its venv path for pyvenv.cfg.+ executable = Path(sys.executable).absolute()+ if not executable.is_file() or not os.access(executable, os.X_OK):+ raise ValueError("The installed Python executable is missing or inaccessible.")+ library_name = sysconfig.get_config_var("LDLIBRARY")+ if not isinstance(library_name, str) or Path(library_name).name != library_name:+ raise ValueError("The managed Python shared library is unavailable.")+ library = Path(sys.base_prefix) / "lib" / library_name+ if not library.is_file():+ raise ValueError(f"The managed Python shared library is missing: {library}")+ return {+ "PythonExecutable": str(executable),+ "PythonLibrary": str(library.absolute()),+ "PythonVersion": version,+ }, architecture+++def is_owned(app: Path) -> bool:+ if app.is_symlink() or not app.is_dir():+ return False+ # Existing shell bundles used Contents directly. Signed bundles use Resources.+ for directory in (app / "Contents/Resources", app / "Contents"):+ marker = directory / OWNER_FILE+ if marker.is_file() and marker.read_text(encoding="utf-8").strip() == BUNDLE_ID:+ return True+ return False+++def install() -> Path:+ """Sign a complete sibling bundle before replacing an FCC-owned application."""+ if sys.platform != "darwin":+ raise ValueError("Application installation is supported only on macOS.")+ home = Path.home()+ app = home / "Applications/Free Claude Code.app"+ if (app.exists() or app.is_symlink()) and not is_owned(app):+ raise ValueError(+ f"An app not managed by Free Claude Code already exists at {app}."+ )+ settings, architecture = runtime_settings()+ template = (+ files("free_claude_code")+ .joinpath("assets", "macos", f"fcc-desktop-{architecture}")+ .read_bytes()+ )+ app.parent.mkdir(parents=True, exist_ok=True)+ root = Path(tempfile.mkdtemp(prefix=".fcc-app-", dir=app.parent))+ backup = root / "previous.app"+ published = False+ try:+ staged = root / app.name+ contents = staged / "Contents"+ resources = contents / "Resources"+ resources.mkdir(parents=True)+ (contents / "MacOS").mkdir()+ executable = contents / "MacOS/fcc-desktop"+ executable.write_bytes(template)+ executable.chmod(0o755)+ export_app_icon(resources / "AppIcon.icns")+ (resources / OWNER_FILE).write_text(BUNDLE_ID + "\n", encoding="utf-8")+ with (resources / "runtime.plist").open("wb") as stream:+ plistlib.dump(settings, stream)+ with (contents / "Info.plist").open("wb") as stream:+ plistlib.dump(+ {+ "CFBundleDisplayName": "Free Claude Code",+ "CFBundleExecutable": "fcc-desktop",+ "CFBundleIdentifier": BUNDLE_ID,+ "CFBundleIconFile": "AppIcon",+ "CFBundleName": "Free Claude Code",+ "CFBundlePackageType": "APPL",+ "LSMultipleInstancesProhibited": True,+ "LSUIElement": True,+ },+ stream,+ )+ subprocess.run(+ ["/usr/bin/codesign", "--force", "--sign", "-", str(staged)], check=True+ )+ subprocess.run(+ ["/usr/bin/codesign", "--verify", "--strict", str(staged)], check=True+ )+ if app.exists():+ app.rename(backup)+ try:+ staged.rename(app)+ except OSError:+ if backup.exists():+ backup.rename(app)+ raise+ published = True+ finally:+ if published or not backup.exists():+ shutil.rmtree(root)+ else:+ print(+ f"The previous application is preserved at {backup}.", file=sys.stderr+ )+ desktop = home / "Desktop/Free Claude Code.app"+ desktop.parent.mkdir(parents=True, exist_ok=True)+ if desktop.is_symlink() and desktop.readlink() == app:+ return app+ if desktop.exists() or desktop.is_symlink():+ print(f"A non-FCC item already exists at {desktop}; leaving it unchanged.")+ else:+ desktop.symlink_to(app, target_is_directory=True)+ return appdiff --git a/tests/cli/test_desktop_assets.py b/tests/cli/test_desktop_assets.pyindex 5dbf53d7..bda2eac0 100644--- a/tests/cli/test_desktop_assets.py+++ b/tests/cli/test_desktop_assets.py@@ -59,6 +59,30 @@ def test_desktop_entrypoint_rejects_unknown_arguments(assert "Usage: fcc-desktop" in capsys.readouterr().err+def test_macos_installer_mode_does_not_import_tray(monkeypatch):+ from free_claude_code.cli import macos_app++ installed = []+ monkeypatch.setattr(desktop_entrypoint.sys, "platform", "darwin")+ monkeypatch.setattr(macos_app, "install", lambda: installed.append(True))+ original_import = builtins.__import__++ def checked_import(name, *args, **kwargs):+ assert name not in {"pystray", "free_claude_code.cli.desktop_tray"}+ return original_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", checked_import)+ desktop_entrypoint.launch(["--install-macos-app"])+ assert installed == [True]+++def test_macos_installer_mode_is_rejected_on_windows(monkeypatch):+ monkeypatch.setattr(desktop_entrypoint.sys, "platform", "win32")+ with pytest.raises(SystemExit) as error:+ desktop_entrypoint.launch(["--install-macos-app"])+ assert error.value.code == 2++@pytest.mark.parametrize("auto_started", [False, True])def test_desktop_sets_scaling_before_importing_native_tray(monkeypatch, auto_started):calls = []diff --git a/tests/cli/test_macos_app.py b/tests/cli/test_macos_app.pynew file mode 100644index 00000000..1c301512--- /dev/null+++ b/tests/cli/test_macos_app.py@@ -0,0 +1,225 @@+"""macOS runtime discovery and transactional application installation."""++import os+import plistlib+import subprocess+from pathlib import Path++import pytest++from free_claude_code.cli import macos_app+++def runtime(tmp_path, monkeypatch):+ base = tmp_path / "managed python"+ library = base / "lib/libpython3.14.dylib"+ library.parent.mkdir(parents=True)+ library.write_bytes(b"library")+ executable = tmp_path / "venv's 日本語/bin/python"+ executable.parent.mkdir(parents=True)+ executable.write_bytes(b"python")+ executable.chmod(0o755)+ monkeypatch.setattr(macos_app.sys, "executable", str(executable))+ monkeypatch.setattr(macos_app.sys, "base_prefix", str(base))+ monkeypatch.setattr(macos_app.platform, "python_implementation", lambda: "CPython")+ monkeypatch.setattr(macos_app.platform, "python_version", lambda: "3.14.7")+ monkeypatch.setattr(macos_app.platform, "machine", lambda: "x86_64")+ variables = {"LDLIBRARY": library.name, "Py_GIL_DISABLED": 0, "Py_DEBUG": 0}+ monkeypatch.setattr(macos_app.sysconfig, "get_config_var", variables.get)+ monkeypatch.setattr(+ macos_app, "metadata", lambda name: {"Requires-Python": "==3.14.7"}+ )+ return executable, library, variables+++def test_runtime_uses_venv_executable_and_interpreter_architecture(runtime):+ executable, library, _variables = runtime+ settings, architecture = macos_app.runtime_settings()+ assert settings == {+ "PythonExecutable": str(executable),+ "PythonLibrary": str(library),+ "PythonVersion": "3.14.7",+ }+ assert architecture == "x86_64"+++def test_runtime_keeps_symlinked_venv_identity(runtime):+ executable, library, _variables = runtime+ base_executable = library.parent / "python"+ executable.rename(base_executable)+ executable.symlink_to(base_executable)+ settings, _architecture = macos_app.runtime_settings()+ assert settings["PythonExecutable"] == str(executable)+ assert Path(settings["PythonExecutable"]).resolve() == base_executable+++def test_unsupported_interpreter_architecture_is_rejected(runtime, monkeypatch):+ monkeypatch.setattr(macos_app.platform, "machine", lambda: "armv7l")+ with pytest.raises(ValueError, match="architecture"):+ macos_app.runtime_settings()++[email protected]("variable", ["Py_GIL_DISABLED", "Py_DEBUG"])+def test_unsupported_runtime_build_is_rejected(runtime, variable):+ runtime[2][variable] = 1+ with pytest.raises(ValueError, match="release"):+ macos_app.runtime_settings()+++def test_missing_runtime_library_is_rejected(runtime):+ runtime[1].unlink()+ with pytest.raises(ValueError, match="library"):+ macos_app.runtime_settings()+++def test_wrong_python_version_is_rejected(runtime, monkeypatch):+ monkeypatch.setattr(macos_app.platform, "python_version", lambda: "3.15.0")+ with pytest.raises(ValueError, match="version"):+ macos_app.runtime_settings()+++def installer(tmp_path, monkeypatch, runtime):+ home = tmp_path / "home's 日本語"+ home.mkdir()+ resources = tmp_path / "package"+ templates = resources / "assets/macos"+ templates.mkdir(parents=True)+ (templates / "fcc-desktop-x86_64").write_bytes(b"intel template")+ (templates / "fcc-desktop-arm64").write_bytes(b"arm template")+ monkeypatch.setattr(macos_app, "files", lambda package: resources)+ monkeypatch.setattr(macos_app.Path, "home", lambda: home)+ monkeypatch.setattr(macos_app.sys, "platform", "darwin")+ calls = []++ def sign(command, **kwargs):+ bundle = Path(command[-1])+ assert (bundle / "Contents/Resources/runtime.plist").is_file()+ assert (bundle / "Contents/Resources/.free-claude-code-owner").is_file()+ assert (bundle / "Contents/MacOS/fcc-desktop").read_bytes() == b"intel template"+ calls.append(command)++ monkeypatch.setattr(macos_app.subprocess, "run", sign)+ return home, resources, calls+++def test_complete_bundle_is_signed_before_publication(installer, runtime):+ home, _resources, calls = installer+ app = macos_app.install()+ assert app == home / "Applications/Free Claude Code.app"+ contents = app / "Contents"+ with (contents / "Info.plist").open("rb") as stream:+ info = plistlib.load(stream)+ assert info["CFBundleIdentifier"] == macos_app.BUNDLE_ID+ assert info["CFBundleExecutable"] == "fcc-desktop"+ assert info["LSUIElement"] and info["LSMultipleInstancesProhibited"]+ with (contents / "Resources/runtime.plist").open("rb") as stream:+ assert plistlib.load(stream)["PythonExecutable"] == str(runtime[0])+ assert (home / "Desktop/Free Claude Code.app").resolve() == app.resolve()+ assert [call[:-1] for call in calls] == [+ ["/usr/bin/codesign", "--force", "--sign", "-"],+ ["/usr/bin/codesign", "--verify", "--strict"],+ ]+ if os.name != "nt":+ assert (contents / "MacOS/fcc-desktop").stat().st_mode & 0o111 == 0o111+++def owned_app(home):+ app = home / "Applications/Free Claude Code.app"+ (app / "Contents").mkdir(parents=True)+ (app / "Contents/.free-claude-code-owner").write_text(macos_app.BUNDLE_ID)+ (app / "old").write_text("preserve on failure")+ return app+++def test_upgrade_replaces_legacy_owned_bundle_and_updates_runtime(+ installer, runtime, monkeypatch+):+ home, _resources, _calls = installer+ app = owned_app(home)+ macos_app.install()+ assert not (app / "old").exists()+ new_python = runtime[0].with_name("python-new")+ new_python.write_bytes(b"python")+ new_python.chmod(0o755)+ monkeypatch.setattr(macos_app.sys, "executable", str(new_python))+ macos_app.install()+ with (app / "Contents/Resources/runtime.plist").open("rb") as stream:+ assert plistlib.load(stream)["PythonExecutable"] == str(new_python)+ assert list(app.parent.iterdir()) == [app]++[email protected]("failure", ["sign", "publish", "resource"])+def test_failure_preserves_existing_app(installer, monkeypatch, failure):+ home, resources, _calls = installer+ app = owned_app(home)+ if failure == "sign":++ def fail(*args, **kwargs):+ raise subprocess.CalledProcessError(1, "codesign")++ monkeypatch.setattr(macos_app.subprocess, "run", fail)+ elif failure == "publish":+ rename = Path.rename++ def fail(path, destination):+ if path.name == "Free Claude Code.app" and path != app:+ raise OSError("publication failed")+ return rename(path, destination)++ monkeypatch.setattr(Path, "rename", fail)+ else:+ (resources / "assets/macos/fcc-desktop-x86_64").unlink()+ with pytest.raises((OSError, subprocess.CalledProcessError)):+ macos_app.install()+ assert (app / "old").read_text() == "preserve on failure"+ assert list(app.parent.iterdir()) == [app]+++def test_unowned_app_is_preserved(installer):+ home, _resources, calls = installer+ app = home / "Applications/Free Claude Code.app"+ app.mkdir(parents=True)+ with pytest.raises(ValueError, match="not managed"):+ macos_app.install()+ assert app.is_dir() and not calls+++def test_failed_restore_keeps_backup_for_recovery(installer, monkeypatch):+ home, _resources, _calls = installer+ app = owned_app(home)+ rename = Path.rename++ def fail(path, destination):+ if destination == app:+ raise OSError("destination unavailable")+ return rename(path, destination)++ monkeypatch.setattr(Path, "rename", fail)+ with pytest.raises(OSError):+ macos_app.install()+ backups = list(app.parent.glob(".fcc-app-*/previous.app/old"))+ assert len(backups) == 1+ assert backups[0].read_text() == "preserve on failure"+++def test_app_symlink_is_not_treated_as_owned(installer):+ home, _resources, _calls = installer+ app = owned_app(home)+ real = app.with_name("Other.app")+ app.rename(real)+ app.symlink_to(real, target_is_directory=True)+ with pytest.raises(ValueError, match="not managed"):+ macos_app.install()+ assert (real / "old").read_text() == "preserve on failure"+++def test_unrelated_desktop_item_is_preserved(installer):+ home, _resources, _calls = installer+ desktop = home / "Desktop"+ desktop.mkdir()+ item = desktop / "Free Claude Code.app"+ item.write_text("unrelated")+ macos_app.install()+ assert item.read_text() == "unrelated"diff --git a/tests/contracts/test_uv_policy.py b/tests/contracts/test_uv_policy.pyindex 37bedbc8..56cc5c0a 100644--- a/tests/contracts/test_uv_policy.py+++ b/tests/contracts/test_uv_policy.py@@ -175,7 +175,7 @@ def test_uv_workflows_share_managed_python_cache_policy() -> None:assert "uv-python-v" not in workflow-def test_shared_setup_installs_dependencies_except_for_post_merge_jobs() -> None:+def test_shared_setup_installs_dependencies_for_jobs_running_project_code() -> None:setup = yaml.safe_load(CI_SETUP.read_text(encoding="utf-8"))assert setup["inputs"]["sync-dependencies"]["default"] == "true"sync = next(@@ -187,10 +187,12 @@ def test_shared_setup_installs_dependencies_except_for_post_merge_jobs() -> Noneassert sync["if"] == "inputs.sync-dependencies == 'true'"for path in UV_WORKFLOWS:jobs = yaml.safe_load(path.read_text(encoding="utf-8"))["jobs"]- for job in jobs.values():+ for name, job in jobs.items():for step in job["steps"]:if step.get("uses") == "./.github/actions/ci-environment":assert step["with"].get("sync-dependencies", "true") == (- "false" if path.name == "post-merge.yml" else "true"+ "false"+ if path.name == "post-merge.yml" or name == "sdist-rebuild"+ else "true")assert step.get("run") != "uv sync --locked --group dev"diff --git a/tests/scripts/test_ci_scripts.py b/tests/scripts/test_ci_scripts.pyindex 67934f96..0ed727ad 100644--- a/tests/scripts/test_ci_scripts.py+++ b/tests/scripts/test_ci_scripts.py@@ -62,7 +62,8 @@ def test_ci_sh_runs_ci_checks_in_order() -> None:legacy_future_import = "from __future__ import " + "annotations"assert (- 'CHECK_ORDER="suppressions ruff-format ruff-check ty pytest playwright"' in text+ 'CHECK_ORDER="suppressions ruff-format ruff-check ty pytest playwright macos-desktop"'+ in text)assert "grep -rE" in textassert "Fix the underlying type/import issue instead" in text@@ -82,7 +83,7 @@ def test_ci_sh_runs_ci_checks_in_order() -> None:assert "--dry-run" in textassert "uv is required but was not found on PATH" in textassert "npm" not in text- assert "smoke/" not in text+ assert "--confcutdir=smoke/desktop" in textassert "uv self update" not in text@@ -134,6 +135,7 @@ def test_ci_sh_playwright_dry_run_prints_browser_and_test_commands() -> None:[("ruff-format", "+ uv run ruff format"),("ruff-check", "+ uv run ruff check --fix"),+ ("macos-desktop", "+ uv run --locked python scripts/build_macos_launcher.py"),],)def test_ci_sh_dry_run_prints_local_ruff_repair_commands(@@ -240,7 +242,7 @@ def test_ci_ps1_runs_ci_checks_in_order() -> None:assert "-DryRun" in textassert "uv is required but was not found on PATH" in textassert "npm" not in text- assert "smoke/" not in text+ assert "--confcutdir=smoke/desktop" in textassert "uv self update" not in textdiff --git a/tests/scripts/test_ci_shard_workflow.py b/tests/scripts/test_ci_shard_workflow.pyindex 42ee2d1f..0c128e1b 100644--- a/tests/scripts/test_ci_shard_workflow.py+++ b/tests/scripts/test_ci_shard_workflow.py@@ -71,23 +71,49 @@ def test_browser_artifacts_identify_each_shard_and_run_attempt():assert upload["with"]["retention-days"] == 7[email protected]("suite", ["pytest", "playwright"])[email protected]("preparation", ["success", "failure", "cancelled", "skipped"])[email protected]("shards", ["success", "failure", "cancelled", "skipped"])+ "suite,preparation,shards,native,rebuild",+ [+ (suite, preparation, shards, "success", "success")+ for suite in ("pytest", "playwright")+ for preparation in ("success", "failure", "cancelled", "skipped")+ for shards in ("success", "failure", "cancelled", "skipped")+ ]+ + [+ ("pytest", "success", "success", native, rebuild)+ for native, rebuild in (+ ("failure", "success"),+ ("cancelled", "success"),+ ("skipped", "success"),+ ("success", "failure"),+ ("success", "cancelled"),+ ("success", "skipped"),+ )+ ],+)def test_summary_only_passes_when_preparation_and_all_shards_succeed(- suite, preparation, shards+ suite, preparation, shards, native, rebuild):job = workflow()["jobs"][f"{suite}-summary"]assert job["name"] == suite- assert set(job["needs"]) == {"prepare-shards", f"{suite}-shards"}+ expected_needs = {"prepare-shards", f"{suite}-shards"}+ if suite == "pytest":+ expected_needs |= {"macos-desktop", "sdist-rebuild"}+ assert set(job["needs"]) == expected_needsassert job["if"] == "${{ always() }}"assert "continue-on-error" not in jobassert len(job["steps"]) == 1step = job["steps"][0]- assert step["env"] == {+ expected_env = {"PREPARATION_RESULT": "${{ needs.prepare-shards.result }}","SHARDS_RESULT": "${{ needs." + suite + "-shards.result }}",}+ if suite == "pytest":+ expected_env |= {+ "NATIVE_RESULT": "${{ needs.macos-desktop.result }}",+ "REBUILD_RESULT": "${{ needs.sdist-rebuild.result }}",+ }+ assert step["env"] == expected_envbash = shutil.which("bash")if os.name == "nt":# WSL's bash.exe does not inherit arbitrary Windows environment variables.@@ -101,12 +127,35 @@ def test_summary_only_passes_when_preparation_and_all_shards_succeed(pytest.skip("bash is required to execute the GitHub summary check")result = subprocess.run([bash, "--noprofile", "--norc", "-e", "-o", "pipefail", "-c", step["run"]],- env={**os.environ, "PREPARATION_RESULT": preparation, "SHARDS_RESULT": shards},+ env={+ **os.environ,+ "PREPARATION_RESULT": preparation,+ "SHARDS_RESULT": shards,+ "NATIVE_RESULT": native,+ "REBUILD_RESULT": rebuild,+ },capture_output=True,text=True,check=False,timeout=30,)- assert (result.returncode == 0) == (preparation == shards == "success"), (- result.stderr+ assert (result.returncode == 0) == (+ preparation == shards == native == rebuild == "success"+ ), result.stderr+++def test_native_checks_cover_both_macs_and_nonmac_sdist_rebuilds():+ jobs = workflow()["jobs"]+ native = jobs["macos-desktop"]+ assert native["strategy"]["matrix"]["runner"] == ["macos-26", "macos-26-intel"]+ assert any(+ step.get("run") == "sh scripts/ci.sh --only macos-desktop"+ for step in native["steps"])+ rebuild = jobs["sdist-rebuild"]+ assert rebuild["needs"] == "macos-desktop"+ assert rebuild["strategy"]["matrix"]["runner"] == [+ "ubuntu-latest",+ "windows-latest",+ ]+ assert "rebuild_sdist.py" in rebuild["steps"][-1]["run"]diff --git a/tests/scripts/test_publish_release.py b/tests/scripts/test_publish_release.pyindex 8b2f9393..ffe25bf5 100644--- a/tests/scripts/test_publish_release.py+++ b/tests/scripts/test_publish_release.py@@ -26,6 +26,8 @@ def releases_template(tmp_path_factory):tmp_path = tmp_path_factory.mktemp("publish-release-template")git(tmp_path, "init", "--template=", "-b", "main")write(tmp_path, "src/file.py", "base")+ write(tmp_path, "scripts/build_macos_launcher.py", "# target builder")+ write(tmp_path, "scripts/validate_release.py", "# target validator")base = commit(tmp_path)git(tmp_path, "tag", "v1.2.3")git(tmp_path, "update-ref", "refs/remotes/origin/main", base)@@ -72,6 +74,7 @@ class FakeRemote:self.calls = []self.fail = Noneself.builds = 0+ self.native_builds = []self.uploaded = {}self.real_command = publishing.command@@ -147,6 +150,8 @@ class FakeRemote:elif args[:2] == ["uv", "build"]:self.builds += 1assert cwd is not None+ if (Path(cwd) / "scripts/build_macos_launcher.py").is_file():+ assert self.native_builds[-1] == git(Path(cwd), "rev-parse", "HEAD")version = git(Path(cwd), "describe", "--tags", "--exact-match")[1:]out = Path(args[args.index("--out-dir") + 1])for name in publishing.distribution_names(version):@@ -161,7 +166,12 @@ class FakeRemote:self.fail = Noneraise RuntimeError("interrupted publication")elif args[0] == publishing.sys.executable:- pass # Archive validation is exercised separately using real archives.+ assert cwd is not None+ assert Path(args[1]).parent == Path(cwd) / "scripts"+ if Path(args[1]).name == "build_macos_launcher.py":+ assert Path(args[1]).read_text() == "# target builder"+ self.native_builds.append(git(Path(cwd), "rev-parse", "HEAD"))+ # Archive validation is exercised separately using real archives.else:raise AssertionError(args)return ""@@ -184,6 +194,33 @@ def test_nonrelease_never_allocates_or_builds(releases):assert not any(c[:2] == ["git", "push"] for c in remote.calls)+def test_native_preparation_uses_release_commit_despite_dirty_current_checkout(+ releases,+):+ repo, remote = releases+ head = remote.advance()+ write(+ repo, "scripts/build_macos_launcher.py", "# unrelated work in current checkout"+ )+ remote.publisher().publish(head)+ assert remote.native_builds == [head]+ assert (+ repo / "scripts/build_macos_launcher.py"+ ).read_text() == "# unrelated work in current checkout"+++def test_historical_release_without_native_builder_can_resume(releases):+ repo, remote = releases+ git(repo, "rm", "scripts/build_macos_launcher.py")+ head = remote.advance()+ remote.fail = "publish"+ with pytest.raises(RuntimeError, match="interrupted publication"):+ remote.publisher().publish(head)+ remote.publisher().publish(head)+ assert remote.native_builds == []+ assert remote.builds == 1++@pytest.mark.parametrize("existing_draft", [False, True])def test_stale_release_list_does_not_block_staging(releases, monkeypatch, existing_draft@@ -222,6 +259,7 @@ def test_retries_keep_version_and_published_bytes(releases, failure):assert not remote.releases["v1.2.4"]["draft"]assert git(repo, "rev-parse", "v1.2.4") == headassert remote.builds == (2 if failure == "stage" else 1)+ assert remote.native_builds == [head] * remote.buildsassert all(remote.uploaded[name] == value for name, value in first_uploaded.items())builds = remote.buildsremote.publisher().publish(head)diff --git a/tests/scripts/test_release_package.py b/tests/scripts/test_release_package.pyindex ab0bcde3..12d25694 100644--- a/tests/scripts/test_release_package.py+++ b/tests/scripts/test_release_package.py@@ -25,6 +25,8 @@ def release(tmp_path):"LICENSE": "license","scripts/update/fcc-update": "#!/bin/sh\n","scripts/update/fcc-update.cmd": "@echo off\n",+ "scripts/build_macos_launcher.py": "# native build\n",+ "scripts/macos/launcher.m": "// launcher\n","src/free_claude_code/__init__.py": "","src/free_claude_code/cli.py": "","src/free_claude_code/desktop.py": "",@@ -34,6 +36,11 @@ def release(tmp_path):for name, content in files.items():write(repo, name, content)git(repo, "add", ".")+ # Generated templates are deliberately absent from git ls-files.+ for architecture in ("arm64", "x86_64"):+ files[f"src/free_claude_code/assets/macos/fcc-desktop-{architecture}"] = (+ architecture+ )metadata = "Name: free-claude-code\nVersion: 1.2.3\n"wheel = {name.removeprefix("src/"): content@@ -87,7 +94,14 @@ def test_complete_release_passes(release, tmp_path):@pytest.mark.parametrize("archive", [1, 2])@pytest.mark.parametrize("suffix",- ["assets/icon.png", "scripts/fcc-update.cmd", "entry_points.txt", "METADATA"],+ [+ "assets/icon.png",+ "scripts/fcc-update.cmd",+ "entry_points.txt",+ "METADATA",+ "assets/macos/fcc-desktop-arm64",+ "assets/macos/fcc-desktop-x86_64",+ ],)def test_missing_wheel_or_sdist_content_fails(release, tmp_path, archive, suffix):if archive == 2:@@ -120,3 +134,20 @@ def test_mismatched_metadata_fails(release, tmp_path):result = validate(release, tmp_path)assert result.returncode != 0assert "metadata" in result.stdout.lower()+++def test_mismatched_native_templates_fail(release, tmp_path):+ release[1]["free_claude_code/assets/macos/fcc-desktop-arm64"] = "different"+ result = validate(release, tmp_path)+ assert result.returncode != 0+ assert "template" in result.stdout.lower()+++ "name", ["scripts/macos/launcher.m", "scripts/build_macos_launcher.py"]+)+def test_native_sources_required_in_sdist(release, tmp_path, name):+ del release[2][f"free_claude_code-1.2.3/{name}"]+ result = validate(release, tmp_path)+ assert result.returncode != 0+ assert "missing" in result.stdout.lower()diff --git a/tests/scripts/test_release_workflow.py b/tests/scripts/test_release_workflow.pyindex b7556813..6f0e34d6 100644--- a/tests/scripts/test_release_workflow.py+++ b/tests/scripts/test_release_workflow.py@@ -32,6 +32,7 @@ def test_post_merge_serializes_and_limits_publish_permissions():"macOS",}publish = config["jobs"]["publish"]+ assert publish["runs-on"] == "macos-26"assert "needs" not in publishassert publish["environment"] == "pypi"assert publish["permissions"] == {"contents": "write", "id-token": "write"}