Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(macos): replace py2app with native stub launcher; surface installer errors
Joana Lütke78d90143aea8
diff --git a/.github/workflows/macos-desktop.yml b/.github/workflows/macos-desktop.ymlindex dfb04c9330..2aaec05a8a 100644--- a/.github/workflows/macos-desktop.yml+++ b/.github/workflows/macos-desktop.yml@@ -44,6 +44,14 @@ jobs:runner: macos-15architecture: arm64python: "3.13"+ # BUG-060 regression row: the stub launcher must also link against+ # a NON-framework interpreter (uv's python-build-standalone), the+ # layout py2app never supported.+ - name: Intel standalone (uv)+ runner: macos-15-intel+ architecture: x86_64+ python: "3.12"+ python-source: uv-standaloneruns-on: ${{ matrix.runner }}timeout-minutes: 45@@ -58,6 +66,24 @@ jobs:with:python-version: ${{ matrix.python }}+ # The venv created below shadows the setup-python interpreter on PATH,+ # so every later `python` invocation in this job runs the uv-managed+ # standalone (non-framework) build.+ - name: Provision a standalone (non-framework) Python via uv+ if: matrix.python-source == 'uv-standalone'+ shell: bash+ run: |+ python -m pip install uv+ uv python install ${{ matrix.python }}+ uv venv --seed --python ${{ matrix.python }} "$HOME/standalone-venv"+ echo "$HOME/standalone-venv/bin" >> "$GITHUB_PATH"++ - name: Assert the interpreter is a non-framework build+ if: matrix.python-source == 'uv-standalone'+ shell: bash+ run: |+ python -c "import sysconfig,sys; sys.exit(0 if (sysconfig.get_config_var('PYTHONFRAMEWORK') or '')=='' else 1)"+- name: Verify native architectureshell: bashrun: |diff --git a/install/installer.py b/install/installer.pyindex 3716aa6f32..9090430431 100644--- a/install/installer.py+++ b/install/installer.py@@ -500,6 +500,24 @@ def step_worker_cli(*, dry_run: bool) -> None:note("Jarvis-Agent worker CLI install failed - it can be added later in-app")+def _write_desktop_integration_log(result: object) -> Path | None:+ """Persist the registration subprocess output; return the path or None."""+ log_path = repo_root() / "data" / "logs" / "install-desktop-integration.log"+ try:+ log_path.parent.mkdir(parents=True, exist_ok=True)+ log_path.write_text(+ "--- stdout ---\n"+ + (getattr(result, "stdout", "") or "")+ + "\n--- stderr ---\n"+ + (getattr(result, "stderr", "") or "")+ + "\n",+ encoding="utf-8",+ )+ except OSError:+ return None+ return log_path++def step_desktop_integration(*, enabled: bool, dry_run: bool) -> bool:"""Register the managed install with the current desktop shell."""if not enabled:@@ -507,6 +525,8 @@ def step_desktop_integration(*, enabled: bool, dry_run: bool) -> bool:if dry_run:console.print("[muted]│ (dry-run) repair desktop-shell registration[/]")return True+ result = None+ report = {}try:result = run_captured([@@ -527,9 +547,9 @@ def step_desktop_integration(*, enabled: bool, dry_run: bool) -> bool:report = json.loads(output[-1]) if output else {}except (OSError, subprocess.TimeoutExpired):report = {}- result = Noneexcept (json.JSONDecodeError, TypeError, ValueError):report = {}+ log_path = _write_desktop_integration_log(result)if (result is not Noneand result.returncode == 0@@ -542,6 +562,17 @@ def step_desktop_integration(*, enabled: bool, dry_run: bool) -> bool:"[bad]│ ✗ desktop app registration failed — installation stopped. ""The app must have a stable launcher identity.[/]")+ warnings = report.get("warnings") if isinstance(report, dict) else None+ for warning in warnings or []:+ note(f"warning: {rich_escape(str(warning))}")+ stderr_tail = (getattr(result, "stderr", "") or "").strip().splitlines()[-15:]+ if stderr_tail:+ note("stderr tail:")+ for line in stderr_tail:+ note(rich_escape(line))+ if log_path is not None:+ note(f"full log: {log_path}")+ note("tip: re-running the installer with '--headless' installs without a desktop app")return Falsediff --git a/jarvis/setup/desktop_integration.py b/jarvis/setup/desktop_integration.pyindex 113e7f6cb8..c0d6c95c8c 100644--- a/jarvis/setup/desktop_integration.py+++ b/jarvis/setup/desktop_integration.py@@ -307,16 +307,19 @@ def ensure_desktop_integration(warnings.append("could not register Personal Jarvis in Installed Apps")elif plat == "macos":try:- from jarvis.setup.macos_app_bundle import ensure_macos_app_bundle+ from jarvis.setup import macos_app_bundle- bundle = ensure_macos_app_bundle(+ bundle = macos_app_bundle.ensure_macos_app_bundle(install_dir=root,applications_dir=macos_applications_dir,)if bundle is not None:artifacts.append("applications_bundle")else:- warnings.append("could not create the macOS application bundle")+ reason = macos_app_bundle.last_error() or "unknown error"+ warnings.append(+ f"could not create the macOS application bundle: {reason}"+ )except Exception as exc: # noqa: BLE001warnings.append(f"could not create the macOS application bundle: {exc}")elif plat == "linux":@@ -421,6 +424,9 @@ def remove_desktop_integration(def main(argv: list[str] | None = None) -> int:+ # Route log.warning detail to stderr so the installer can surface the real+ # failure reason; the --json contract stays: JSON is the last stdout line.+ logging.basicConfig(level=logging.INFO, stream=sys.stderr)parser = argparse.ArgumentParser(description="Repair Personal Jarvis desktop registration")parser.add_argument("--install-dir", type=Path, default=None)parser.add_argument("--remove", action="store_true")diff --git a/jarvis/setup/macos_app_bundle.py b/jarvis/setup/macos_app_bundle.pyindex b7e081fda7..5afc85d52d 100644--- a/jarvis/setup/macos_app_bundle.py+++ b/jarvis/setup/macos_app_bundle.py@@ -3,9 +3,11 @@The bundle's main executable must remain a Mach-O process. A shell launcherthat ``exec``s an external virtual-environment Python loses its ``NSBundle``identity and causes TCC grants to attach to Python or a terminal instead of-Personal Jarvis. The managed installer therefore uses py2app's alias mode: its-native bootstrap embeds the active Python runtime in the app process while the-source and dependencies remain in the managed checkout.+Personal Jarvis. The managed installer therefore compiles the in-repo stub+launcher (``macos_stub_launcher.c``): it embeds the active Python runtime in+the app process and runs the managed entry script, so it works with framework+AND non-framework interpreters (for example uv-managed standalone builds)+while the source and dependencies remain in the managed checkout.The locally generated app is ad-hoc signed and is preserved byte-for-byte onordinary source updates so its local TCC identity does not churn. Public binary@@ -20,6 +22,7 @@ import loggingimport osimport platformimport plistlib+import reimport shutilimport statimport subprocess@@ -48,10 +51,24 @@ _MACHO_MAGICS = frozenset(})+# The reason the most recent ensure_macos_app_bundle call returned None, so+# callers can surface the real failure instead of a generic warning.+_LAST_ERROR: str | None = None+++def last_error() -> str | None:+ """Return why the last ensure_macos_app_bundle call failed, if it did."""+ return _LAST_ERROR++_MIC_USAGE = "Personal Jarvis listens on this microphone for your wake word and voice commands."_SCREEN_CAPTURE_USAGE = ("Personal Jarvis captures the screen only when you ask it to see or control applications.")+_APPLE_EVENTS_USAGE = (+ "Personal Jarvis lowers Music/Spotify volume while you dictate and "+ "restores it afterwards."+)def _version() -> str:@@ -233,6 +250,7 @@ def _bundle_plist() -> dict[str, object]:"CFBundleVersion": _version(),"JarvisBundleFormatVersion": _BUNDLE_FORMAT_VERSION,"LSMinimumSystemVersion": "11.0",+ "NSAppleEventsUsageDescription": _APPLE_EVENTS_USAGE,"NSHighResolutionCapable": True,"NSMicrophoneUsageDescription": _MIC_USAGE,"NSScreenCaptureUsageDescription": _SCREEN_CAPTURE_USAGE,@@ -265,51 +283,201 @@ def _write_cross_platform_fixture_bundle(bundle: Path) -> Path:return bundle-def _build_py2app_alias(install_root: Path, work_dir: Path) -> Path:- """Build a native alias launcher with the managed virtual environment."""+_LINK_INFO_SCRIPT = (+ "import json, platform, sys, sysconfig\n"+ "data = {name: sysconfig.get_config_var(name) or '' for name in "+ "('PYTHONFRAMEWORK', 'LDLIBRARY', 'LIBDIR', 'PYTHONFRAMEWORKPREFIX')}\n"+ "data['base_prefix'] = sys.base_prefix\n"+ "data['include'] = sysconfig.get_paths()['include']\n"+ "data['machine'] = platform.machine()\n"+ "print(json.dumps(data))\n"+)+++def _runtime_link_info(venv_python: Path) -> dict:+ """Ask the managed venv interpreter how its runtime library is laid out."""+ try:+ result = subprocess.run(+ [str(venv_python), "-B", "-c", _LINK_INFO_SCRIPT],+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=60,+ check=False,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ except (OSError, subprocess.TimeoutExpired) as exc:+ raise RuntimeError(+ f"could not query the venv interpreter {venv_python}: {exc}"+ ) from exc+ if result.returncode != 0:+ detail = (result.stderr or result.stdout or "unknown interpreter error").strip()+ raise RuntimeError(f"venv runtime introspection failed: {detail[-1200:]}")+ try:+ return json.loads(result.stdout.strip().splitlines()[-1])+ except (ValueError, IndexError) as exc:+ raise RuntimeError(+ f"venv runtime introspection returned invalid JSON: {exc}"+ ) from exc+++# A fully versioned uv/python-build-standalone prefix directory name, for+# example ``cpython-3.12.13-macos-aarch64-none``. Group "head" keeps the+# implementation and major.minor; "tail" keeps the platform suffix.+_VERSIONED_PREFIX_RE = re.compile(r"^(?P<head>[^-]+-\d+\.\d+)\.\d+(?P<tail>-.*)?$")+++def _prefer_unversioned_runtime(dylib: Path, base_prefix: Path | None) -> Path:+ """Prefer an unversioned sibling runtime dir when one holds the dylib.++ uv keeps a ``cpython-3.12-...`` alias beside the fully versioned+ ``cpython-3.12.13-...`` install. Linking (and rpath-ing) against the+ alias keeps the bundle working across uv patch upgrades that replace the+ versioned directory.+ """+ if base_prefix is None:+ return dylib+ match = _VERSIONED_PREFIX_RE.match(base_prefix.name)+ if match is None:+ return dylib+ try:+ relative = dylib.relative_to(base_prefix)+ except ValueError:+ return dylib+ candidate = base_prefix.with_name(match.group("head") + (match.group("tail") or ""))+ sibling = candidate / relative+ try:+ if sibling.is_file():+ return sibling+ except OSError:+ return dylib+ return dylib+++def _resolve_runtime_dylib(info: dict) -> Path:+ """Locate the runtime libpython/framework dylib to link the stub against."""+ ldlibrary = str(info.get("LDLIBRARY") or "")+ if not ldlibrary:+ raise RuntimeError("the venv interpreter reported no LDLIBRARY config variable")+ roots = [+ Path(str(root))+ for root in (info.get("LIBDIR"), info.get("PYTHONFRAMEWORKPREFIX"))+ if root+ ]+ base_prefix = str(info.get("base_prefix") or "")+ if base_prefix:+ roots.append(Path(base_prefix) / "lib")+ candidates = [root / ldlibrary for root in roots]+ for candidate in candidates:+ if candidate.is_file():+ return _prefer_unversioned_runtime(+ candidate, Path(base_prefix) if base_prefix else None+ )+ listing = ", ".join(str(candidate) for candidate in candidates) or "(none)"+ raise RuntimeError(f"no linkable Python runtime library found; tried: {listing}")+++def _compile_stub(+ stub_c: Path,+ dylib: Path,+ include_dir: Path,+ machine: str,+ defines: list[str],+ out_path: Path,+) -> None:+ """Compile the in-repo stub launcher into the bundle's Mach-O executable."""+ command = [+ "/usr/bin/xcrun",+ "clang",+ "-O2",+ "-Wall",+ "-arch",+ machine,+ "-I",+ str(include_dir),+ str(stub_c),+ str(dylib),+ f"-Wl,-rpath,{dylib.parent}",+ *defines,+ "-o",+ str(out_path),+ ]+ hint = "install the Xcode Command Line Tools (xcode-select --install)"+ try:+ result = subprocess.run(+ command,+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=300,+ check=False,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ except FileNotFoundError as exc:+ raise RuntimeError(f"clang is not available ({exc}); {hint}") from exc+ except (OSError, subprocess.TimeoutExpired) as exc:+ raise RuntimeError(f"stub launcher compilation failed: {exc}; {hint}") from exc+ if result.returncode != 0:+ detail = (result.stderr or result.stdout or "unknown clang error").strip()+ raise RuntimeError(+ f"stub launcher compilation failed: {detail[-1200:]}; {hint}"+ )+++def _build_native_bundle(install_root: Path, work_dir: Path) -> Path:+ """Compile the stub launcher and lay out the app bundle in ``work_dir``."""entry = install_root / "jarvis" / "setup" / "macos_launcher_entry.py"if not entry.is_file():raise FileNotFoundError(f"macOS launcher entry is missing: {entry}")+ stub_c = Path(__file__).resolve().parent / "macos_stub_launcher.c"+ if not stub_c.is_file():+ raise FileNotFoundError(f"macOS stub launcher source is missing: {stub_c}")++ # Deliberately NOT resolve()d: the venv interpreter is a symlink chain to+ # the base runtime, and CPython's venv detection looks for pyvenv.cfg next+ # to the UNRESOLVED executable path. Resolving it would point the embedded+ # interpreter at the base install and lose the venv's site-packages.+ venv_python = _venv_python(install_root)+ info = _runtime_link_info(venv_python)+ dylib = _resolve_runtime_dylib(info)+ machine = str(info.get("machine") or "") or platform.machine()++ bundle = work_dir / APP_DIR_NAME+ macos_dir = bundle / "Contents" / "MacOS"+ resources = bundle / "Contents" / "Resources"+ macos_dir.mkdir(parents=True)+ resources.mkdir(parents=True)- resources = work_dir / "resources"- resources.mkdir()- options: dict[str, object] = {- "argv_emulation": False,- "plist": _bundle_plist(),- }+ executable_name = "PersonalJarvis"+ plist = _bundle_plist()+ plist["CFBundleExecutable"] = executable_nameicon_stem = _try_build_icns(resources)if icon_stem is not None:- options["iconfile"] = str(resources / f"{icon_stem}.icns")-- setup_source = (- "from setuptools import setup\n\n"- "setup(\n"- f" name={APP_NAME!r},\n"- f" version={_version()!r},\n"- f" app={[str(entry)]!r},\n"- f" options={{'py2app': {options!r}}},\n"- ")\n"+ plist["CFBundleIconFile"] = icon_stem++ executable = macos_dir / executable_name+ # The paths become C string literals via -D macros; subprocess passes each+ # define as one argv element, so spaces in paths survive verbatim.+ defines = [+ f'-DJARVIS_VENV_PYTHON="{venv_python}"',+ f'-DJARVIS_ENTRY_SCRIPT="{entry}"',+ ]+ _compile_stub(+ stub_c,+ dylib,+ Path(str(info.get("include") or "")),+ machine,+ defines,+ executable,)- setup_path = work_dir / "setup.py"- setup_path.write_text(setup_source, encoding="utf-8")- result = subprocess.run(- [str(_venv_python(install_root)), str(setup_path), "py2app", "--alias"],- cwd=work_dir,- capture_output=True,- text=True,- encoding="utf-8",- errors="replace",- timeout=300,- check=False,- creationflags=NO_WINDOW_CREATIONFLAGS,+ executable.chmod(+ executable.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)- if result.returncode != 0:- detail = (result.stderr or result.stdout or "unknown py2app error").strip()- raise RuntimeError(f"py2app alias build failed: {detail[-1200:]}")- candidates = tuple((work_dir / "dist").glob("*.app"))- if len(candidates) != 1:- raise RuntimeError(f"py2app produced {len(candidates)} application bundles; expected one")- return candidates[0]+ with (bundle / "Contents" / "Info.plist").open("wb") as stream:+ plistlib.dump(plist, stream)+ return bundledef _sign_bundle(bundle: Path) -> None:@@ -331,8 +499,17 @@ def _sign_bundle(bundle: Path) -> None:)-def _runtime_identity_valid(bundle: Path, *, install_root: Path) -> bool:- """Verify native identity and imports against the managed checkout."""+def _runtime_identity_valid(+ bundle: Path,+ *,+ install_root: Path,+ diagnostics: list[str] | None = None,+) -> bool:+ """Verify native identity and imports against the managed checkout.++ When ``diagnostics`` is given, human-readable probe evidence is appended+ to it so failed checks can surface the real cause to the installer.+ """if sys.platform != "darwin":return Truedescriptor, raw_probe = tempfile.mkstemp(prefix="jarvis-bundle-probe-", suffix=".json")@@ -353,9 +530,19 @@ def _runtime_identity_valid(bundle: Path, *, install_root: Path) -> bool:check=False,creationflags=NO_WINDOW_CREATIONFLAGS,)+ if diagnostics is not None:+ stderr_tail = (result.stderr or "").strip()[-500:]+ diagnostics.append(+ f"open returncode {result.returncode}, "+ f"stderr tail: {stderr_tail or '(empty)'}"+ )if result.returncode != 0 or not probe.is_file():+ if diagnostics is not None and not probe.is_file():+ diagnostics.append("probe file was not written")return Falsepayload = json.loads(probe.read_text(encoding="utf-8"))+ if diagnostics is not None:+ diagnostics.append(f"probe payload: {payload!r}")expected_bundle = bundle.resolve()reported_bundle = Path(str(payload.get("bundle_path", ""))).resolve()executable = Path(str(payload.get("executable", ""))).resolve()@@ -375,7 +562,9 @@ def _runtime_identity_valid(bundle: Path, *, install_root: Path) -> bool:== f"{sys.version_info.major}.{sys.version_info.minor}"and payload.get("machine") == platform.machine())- except (OSError, ValueError, json.JSONDecodeError, subprocess.TimeoutExpired):+ except (OSError, ValueError, json.JSONDecodeError, subprocess.TimeoutExpired) as exc:+ if diagnostics is not None:+ diagnostics.append(f"identity probe failed: {type(exc).__name__}: {exc}")return Falsefinally:probe.unlink(missing_ok=True)@@ -408,9 +597,9 @@ def _install_native_bundle(install_root: Path, bundle: Path) -> Path:"""Build beside the destination and replace it atomically with rollback."""parent = bundle.parentparent.mkdir(parents=True, exist_ok=True)- with tempfile.TemporaryDirectory(prefix=".jarvis-py2app-", dir=parent) as raw_work:+ with tempfile.TemporaryDirectory(prefix=".jarvis-native-", dir=parent) as raw_work:work = Path(raw_work)- built = _build_py2app_alias(install_root, work)+ built = _build_native_bundle(install_root, work)_sign_bundle(built)previous = work / "previous.app"if bundle.exists() or bundle.is_symlink():@@ -418,9 +607,19 @@ def _install_native_bundle(install_root: Path, bundle: Path) -> Path:try:built.rename(bundle)if not macos_app_bundle_is_launchable(bundle):- raise RuntimeError("the installed macOS application bundle is invalid")- if not _runtime_identity_valid(bundle, install_root=install_root):- raise RuntimeError("the installed app reported an unexpected runtime identity")+ raise RuntimeError(+ "the installed macOS application bundle failed the launchable "+ f"check (native executable, metadata, or signature): {bundle}"+ )+ diagnostics: list[str] = []+ if not _runtime_identity_valid(+ bundle, install_root=install_root, diagnostics=diagnostics+ ):+ detail = "; ".join(diagnostics) or "no probe diagnostics captured"+ raise RuntimeError(+ "the installed app reported an unexpected runtime identity "+ f"({detail})"+ )except Exception:_remove_path(bundle)if previous.exists() or previous.is_symlink():@@ -440,6 +639,8 @@ def ensure_macos_app_bundle(updates cannot churn its local TCC identity. Off macOS, this is a no-opunless a caller explicitly injects an applications directory for tests."""+ global _LAST_ERROR+ _LAST_ERROR = Noneif applications_dir is None:if sys.platform != "darwin":log.info("App bundle skipped: only macOS uses .app bundles.")@@ -463,6 +664,7 @@ def ensure_macos_app_bundle(log.info("Native macOS app bundle installed: %s", installed)return installedexcept Exception as exc: # noqa: BLE001 - installer consumes the None result+ _LAST_ERROR = f"{type(exc).__name__}: {exc}"log.warning("macOS app bundle could not be written: %s", exc)return None@@ -490,6 +692,7 @@ __all__ = ["APP_NAME","BUNDLE_ID","ensure_macos_app_bundle",+ "last_error","macos_app_bundle_is_launchable","macos_app_bundle_path","macos_launch_services_command",diff --git a/jarvis/setup/macos_launcher_entry.py b/jarvis/setup/macos_launcher_entry.pyindex 49b7b79fe6..da80a775ff 100644--- a/jarvis/setup/macos_launcher_entry.py+++ b/jarvis/setup/macos_launcher_entry.py@@ -1,9 +1,10 @@"""Native-bundle entry point for installer-managed macOS applications.-py2app's alias launcher embeds the active Python runtime in the Mach-O app-process and then executes this source file in place. Keeping the code outside-the bundle lets normal source updates apply without rebuilding or changing the-TCC identity of the installed application.+The compiled stub launcher (``macos_stub_launcher.c``) embeds the active+Python runtime in the Mach-O app process and then executes this source file+in place. Keeping the code outside the bundle lets normal source updates+apply without rebuilding or changing the TCC identity of the installed+application."""from __future__ import annotations@@ -39,7 +40,7 @@ def _write_identity_probe(destination: Path) -> int:}destination.write_text(json.dumps(payload, sort_keys=True), encoding="utf-8")except Exception as exc: # noqa: BLE001 - the installer treats this as failure- payload = {"error": type(exc).__name__}+ payload = {"error": type(exc).__name__, "detail": str(exc)[:500]}destination.write_text(json.dumps(payload, sort_keys=True), encoding="utf-8")return 2return 0diff --git a/jarvis/setup/macos_stub_launcher.c b/jarvis/setup/macos_stub_launcher.cnew file mode 100644index 0000000000..cd747f4b6a--- /dev/null+++ b/jarvis/setup/macos_stub_launcher.c@@ -0,0 +1,75 @@+/*+ * In-process native stub launcher for the managed-install macOS app bundle+ * (BUG-060).+ *+ * The bundle's CFBundleExecutable must stay a real Mach-O process: a shell+ * script that execs an external virtual-environment Python loses the app's+ * NSBundle identity, so TCC grants attach to "Python" or a terminal instead+ * of Personal Jarvis. This stub embeds CPython inside the app process itself+ * (libpython is linked at build time) and runs the managed entry script, so+ * the stable TCC identity is the app bundle across ordinary source updates.+ *+ * Unlike py2app's bootstrap, this works with framework AND non-framework+ * interpreters (for example uv's python-build-standalone builds): the+ * program name is pointed at the venv interpreter and CPython's own path+ * machinery (getpath + pyvenv.cfg) performs the full venv resolution.+ *+ * Compiled at install time by jarvis/setup/macos_app_bundle.py, which injects+ * the absolute paths as -D string macros:+ * JARVIS_VENV_PYTHON - the managed venv's python executable+ * JARVIS_ENTRY_SCRIPT - jarvis/setup/macos_launcher_entry.py+ */++#include <Python.h>++#include <locale.h>+#include <stdlib.h>++int main(int argc, char *argv[]) {+ /* Finder-launched apps inherit no locale, which would make CPython+ * decode paths and argv as ASCII. Mirror py2app's fix: force UTF-8. */+ if (getenv("LC_ALL") == NULL && getenv("LC_CTYPE") == NULL && getenv("LANG") == NULL) {+ setenv("LC_CTYPE", "UTF-8", 1);+ }+ setlocale(LC_ALL, "");++ PyStatus status;+ PyConfig config;+ PyConfig_InitPythonConfig(&config);++ /* CPython derives its prefixes (and the venv, via pyvenv.cfg) from the+ * program name, exactly as if the venv interpreter had been started. */+ status = PyConfig_SetBytesString(&config, &config.program_name, JARVIS_VENV_PYTHON);+ if (PyStatus_Exception(status)) {+ goto fail;+ }++ /* argv = {venv python, entry script, forwarded app arguments...} so the+ * embedded interpreter runs the entry script like a command line would. */+ char **embedded_argv = calloc((size_t)argc + 1, sizeof(char *));+ if (embedded_argv == NULL) {+ status = PyStatus_NoMemory();+ goto fail;+ }+ embedded_argv[0] = JARVIS_VENV_PYTHON;+ embedded_argv[1] = JARVIS_ENTRY_SCRIPT;+ for (int i = 1; i < argc; i++) {+ embedded_argv[i + 1] = argv[i];+ }+ status = PyConfig_SetBytesArgv(&config, argc + 1, embedded_argv);+ free(embedded_argv);+ if (PyStatus_Exception(status)) {+ goto fail;+ }++ status = Py_InitializeFromConfig(&config);+ if (PyStatus_Exception(status)) {+ goto fail;+ }+ PyConfig_Clear(&config);+ return Py_RunMain();++fail:+ PyConfig_Clear(&config);+ Py_ExitStatusException(status);+}diff --git a/pyproject.toml b/pyproject.tomlindex 3cad0f1e77..29cea889fa 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -61,7 +61,8 @@ dependencies = [# 3.11-3.13; other operating systems use the current CPU line. The portable# energy VAD is the explicit macOS 3.14 fallback.# arm64-only on macOS: no Intel-mac onnxruntime wheels anymore (BUG-061);- # Silero VAD degrades to WebRTC VAD on Intel Macs.+ # Silero VAD degrades to WebRTC VAD there (ships in [local-voice]/[full]);+ # bare base installs degrade to portable energy endpointing."onnxruntime>=1.17,<1.24; sys_platform == 'darwin' and python_version < '3.14' and platform_machine == 'arm64'","onnxruntime>=1.17; sys_platform != 'darwin'",# Any-word wake keyword spotting (vosk_kws engine, design spec 2026-07-05):@@ -254,11 +255,14 @@ desktop = [# (``apt install python3-pyatspi gir1.2-atspi-2.0``), surfaced via the# ``capabilities.has_ax_tree`` runtime probe — it is NEVER a pip dependency.desktop-macos = [- # Builds the managed-install alias bundle around a native Mach-O launcher.- # A shell CFBundleExecutable that execs external Python has no stable TCC- # identity; py2app keeps the interpreter inside the app process while the- # source/dependencies remain in the installer-managed checkout.- "py2app>=0.28.10; sys_platform == 'darwin'",+ # The managed-install app bundle keeps a native Mach-O launcher: a shell+ # CFBundleExecutable that execs external Python has no stable TCC+ # identity. The launcher is compiled at install time from the in-repo+ # stub (jarvis/setup/macos_stub_launcher.c, shipped as package data) with+ # the Xcode Command Line Tools' clang, keeping the interpreter inside the+ # app process while source/dependencies remain in the managed checkout —+ # py2app is no longer a dependency, and the stub also links against+ # non-framework (uv standalone) interpreters that py2app never supported."pyobjc-framework-Quartz>=10; sys_platform == 'darwin'","pyobjc-framework-ApplicationServices>=10; sys_platform == 'darwin'","pyobjc-framework-Accessibility>=10; sys_platform == 'darwin'",@@ -570,6 +574,9 @@ jarvis = [# "skills/builtin/**/*" so a stray local __pycache__ never rides along."skills/builtin/**/*.md","skills/builtin/**/*.txt",+ # In-repo C source for the macOS stub launcher, compiled at install time+ # by jarvis/setup/macos_app_bundle.py (BUG-060 stable TCC identity).+ "setup/*.c",][tool.setuptools.data-files]diff --git a/requirements.in b/requirements.inindex bf15ce540f..50831bbafa 100644--- a/requirements.in+++ b/requirements.in@@ -61,7 +61,9 @@ openwakeword>=0.6; sys_platform == 'linux' and platform_machine == 'x86_64' and# floor. macOS 3.14 uses Vosk/energy; other operating systems use current ONNX.# arm64-only on macOS: onnxruntime stopped shipping Intel-mac wheels (the last# x86_64 builds also require older Pythons), so a pinned version bricked the-# whole base install on Intel Macs. Silero VAD degrades to WebRTC VAD there.+# whole base install on Intel Macs. Silero VAD degrades to WebRTC VAD there+# (ships in [local-voice]/[full]); bare base installs degrade to portable+# energy endpointing.onnxruntime>=1.17,<1.24; sys_platform == 'darwin' and python_version < '3.14' and platform_machine == 'arm64'onnxruntime>=1.17; sys_platform != 'darwin'# Any-word wake keyword spotting (vosk_kws engine, 2026-07-05): torch-free,diff --git a/tests/unit/install/test_installer_update_contract.py b/tests/unit/install/test_installer_update_contract.pyindex cbb324a8f3..6f87e1c0d5 100644--- a/tests/unit/install/test_installer_update_contract.py+++ b/tests/unit/install/test_installer_update_contract.py@@ -122,7 +122,72 @@ def test_desktop_registration_failure_is_install_failure(lambda *args, **kwargs: SimpleNamespace(returncode=1,stdout='{"ok": false, "attempted": true}',+ stderr="",),)assert installer.step_desktop_integration(enabled=True, dry_run=False) is False+++def test_desktop_registration_failure_surfaces_diagnostics(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys+) -> None:+ monkeypatch.setattr(installer, "repo_root", lambda: tmp_path)+ monkeypatch.setattr(installer, "venv_python", lambda: tmp_path / "python")+ stderr = "\n".join(f"stderr-line-{index}" for index in range(20))+ report = json.dumps(+ {+ "ok": False,+ "attempted": True,+ "warnings": ["bundle identity probe failed"],+ }+ )+ monkeypatch.setattr(+ installer.subprocess,+ "run",+ lambda *args, **kwargs: SimpleNamespace(+ returncode=1,+ stdout=report,+ stderr=stderr,+ ),+ )++ assert installer.step_desktop_integration(enabled=True, dry_run=False) is False++ out = capsys.readouterr().out+ assert "bundle identity probe failed" in out+ assert "stderr-line-19" in out+ assert "stderr-line-5" in out+ # Only the last ~15 stderr lines are echoed to the console.+ assert "stderr-line-4" not in out+ assert "--headless" in out+ # The full path may be folded across lines by the console width.+ assert "full log:" in out+ log_path = tmp_path / "data" / "logs" / "install-desktop-integration.log"+ text = log_path.read_text(encoding="utf-8")+ assert "stderr-line-0" in text+ assert "bundle identity probe failed" in text+++def test_desktop_registration_success_still_writes_full_log(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ monkeypatch.setattr(installer, "repo_root", lambda: tmp_path)+ monkeypatch.setattr(installer, "venv_python", lambda: tmp_path / "python")+ monkeypatch.setattr(+ installer.subprocess,+ "run",+ lambda *args, **kwargs: SimpleNamespace(+ returncode=0,+ stdout='{"ok": true, "attempted": true}',+ stderr="probe chatter\n",+ ),+ )++ assert installer.step_desktop_integration(enabled=True, dry_run=False) is True++ text = (+ tmp_path / "data" / "logs" / "install-desktop-integration.log"+ ).read_text(encoding="utf-8")+ assert '{"ok": true, "attempted": true}' in text+ assert "probe chatter" in textdiff --git a/tests/unit/setup/test_desktop_integration.py b/tests/unit/setup/test_desktop_integration.pyindex 06fd4da967..0ebf4b09a7 100644--- a/tests/unit/setup/test_desktop_integration.py+++ b/tests/unit/setup/test_desktop_integration.py@@ -84,12 +84,23 @@ def test_headless_linux_does_not_create_desktop_artifacts(assert report.skipped_reason == "headless Linux session"-def test_macos_managed_install_gets_real_app_bundle(tmp_path: Path) -> None:+def test_macos_managed_install_gets_real_app_bundle(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:root = _managed_root(tmp_path)(root / ".venv" / "bin").mkdir(parents=True)(root / ".venv" / "bin" / "python").write_text("", encoding="utf-8")apps = tmp_path / "Applications"+ # Force the deterministic cross-platform fixture bundle on every host: the+ # fixture root has no real venv interpreter, so the native clang build can+ # never succeed against it. The REAL darwin build + LaunchServices probe is+ # covered by the dedicated "Build and self-probe" step in+ # .github/workflows/macos-desktop.yml and tests/unit/setup/test_macos_app_bundle.py.+ from jarvis.setup import macos_app_bundle as mab++ monkeypatch.setattr(mab.sys, "platform", "linux")+report = di.ensure_desktop_integration(install_dir=root,platform="darwin",@@ -101,6 +112,55 @@ def test_macos_managed_install_gets_real_app_bundle(tmp_path: Path) -> None:assert (apps / "Personal Jarvis.app" / "Contents" / "Info.plist").is_file()+def test_macos_bundle_failure_warning_carries_recorded_reason(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ import jarvis.setup.macos_app_bundle as mab++ root = _managed_root(tmp_path)++ def _fail(**_kwargs: object) -> None:+ monkeypatch.setattr(+ mab, "_LAST_ERROR", "RuntimeError: py2app alias build failed: boom"+ )+ return None++ monkeypatch.setattr(mab, "ensure_macos_app_bundle", _fail)++ report = di.ensure_desktop_integration(+ install_dir=root,+ platform="darwin",+ macos_applications_dir=tmp_path / "Applications",+ )++ assert report.ok is False+ assert report.warnings == (+ "could not create the macOS application bundle: "+ "RuntimeError: py2app alias build failed: boom",+ )+++def test_macos_bundle_failure_without_recorded_reason_says_unknown(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ import jarvis.setup.macos_app_bundle as mab++ root = _managed_root(tmp_path)+ monkeypatch.setattr(mab, "_LAST_ERROR", None)+ monkeypatch.setattr(mab, "ensure_macos_app_bundle", lambda **_kwargs: None)++ report = di.ensure_desktop_integration(+ install_dir=root,+ platform="darwin",+ macos_applications_dir=tmp_path / "Applications",+ )++ assert report.ok is False+ assert report.warnings == (+ "could not create the macOS application bundle: unknown error",+ )++def test_linux_uninstall_removes_application_entry(tmp_path: Path) -> None:apps = tmp_path / "applications"apps.mkdir()diff --git a/tests/unit/setup/test_macos_app_bundle.py b/tests/unit/setup/test_macos_app_bundle.pyindex 5176841200..f85b676922 100644--- a/tests/unit/setup/test_macos_app_bundle.py+++ b/tests/unit/setup/test_macos_app_bundle.py@@ -26,7 +26,7 @@ def _build(tmp_path: Path, monkeypatch) -> Path:import jarvis.setup.macos_app_bundle as mab# The explicit-path branch builds a structural native fixture off macOS.- # Real py2app/codesign/LaunchServices coverage lives in macOS CI.+ # Real clang/codesign/LaunchServices coverage lives in macOS CI.monkeypatch.setattr(mab.sys, "platform", "linux")install_dir = tmp_path / "install"(install_dir / ".venv" / "bin").mkdir(parents=True)@@ -50,7 +50,7 @@ def test_bundle_layout_and_plist(tmp_path: Path, monkeypatch) -> None:assert info["CFBundlePackageType"] == "APPL"assert "microphone" in info["NSMicrophoneUsageDescription"].lower()assert "screen" in info["NSScreenCaptureUsageDescription"].lower()- assert "NSAppleEventsUsageDescription" not in info+ assert "dictate" in info["NSAppleEventsUsageDescription"].lower()executable = bundle / "Contents" / "MacOS" / executable_nameassert executable.read_bytes()[:4] == b"\xcf\xfa\xed\xfe"if os.name != "nt":@@ -136,6 +136,76 @@ def test_running_canonical_app_skips_second_launchservices_probe()+def test_runtime_identity_probe_diagnoses_open_failure(+ tmp_path: Path, monkeypatch+) -> None:+ import jarvis.setup.macos_app_bundle as mab++ monkeypatch.setattr(mab.sys, "platform", "darwin")+ monkeypatch.setattr(+ mab.subprocess,+ "run",+ lambda *args, **kwargs: SimpleNamespace(+ returncode=3,+ stdout="",+ stderr="kLSNoExecutableErr: the app cannot be launched\n",+ ),+ )+ diagnostics: list[str] = []++ assert mab._runtime_identity_valid(+ tmp_path / APP_DIR_NAME,+ install_root=tmp_path,+ diagnostics=diagnostics,+ ) is False++ joined = "\n".join(diagnostics)+ assert "open returncode 3" in joined+ assert "kLSNoExecutableErr" in joined+++def test_runtime_identity_probe_diagnoses_missing_probe_file(+ tmp_path: Path, monkeypatch+) -> None:+ import jarvis.setup.macos_app_bundle as mab++ monkeypatch.setattr(mab.sys, "platform", "darwin")+ monkeypatch.setattr(+ mab.subprocess,+ "run",+ lambda *args, **kwargs: SimpleNamespace(returncode=0, stdout="", stderr=""),+ )+ diagnostics: list[str] = []++ assert mab._runtime_identity_valid(+ tmp_path / APP_DIR_NAME,+ install_root=tmp_path,+ diagnostics=diagnostics,+ ) is False++ joined = "\n".join(diagnostics)+ assert "open returncode 0" in joined+ assert "probe file was not written" in joined+++def test_ensure_bundle_records_last_error_reason(tmp_path: Path, monkeypatch) -> None:+ import jarvis.setup.macos_app_bundle as mab++ monkeypatch.setattr(mab.sys, "platform", "darwin")+ monkeypatch.setattr(mab, "macos_app_bundle_is_launchable", lambda _bundle: False)++ def _explode(_install_root: Path, _bundle: Path) -> Path:+ raise RuntimeError("stub launcher compilation failed: no cc")++ monkeypatch.setattr(mab, "_install_native_bundle", _explode)++ assert ensure_macos_app_bundle(+ install_dir=tmp_path / "install",+ applications_dir=tmp_path / "Applications",+ ) is None+ assert mab.last_error() == "RuntimeError: stub launcher compilation failed: no cc"++def test_noop_off_darwin_without_override(monkeypatch) -> None:monkeypatch.setattr("sys.platform", "linux")assert ensure_macos_app_bundle() is None@@ -234,6 +304,185 @@ def test_sign_bundle_reports_the_codesign_verify_detail(tmp_path: Path, monkeypamab._sign_bundle(tmp_path / APP_DIR_NAME)+def test_resolve_runtime_dylib_standalone_layout(tmp_path: Path) -> None:+ import jarvis.setup.macos_app_bundle as mab++ prefix = tmp_path / "cpython-3.12.13-macos-aarch64-none"+ (prefix / "lib").mkdir(parents=True)+ dylib = prefix / "lib" / "libpython3.12.dylib"+ dylib.write_bytes(b"")+ info = {+ "base_prefix": str(prefix),+ "LIBDIR": str(prefix / "lib"),+ "LDLIBRARY": "libpython3.12.dylib",+ "PYTHONFRAMEWORKPREFIX": "",+ }+ assert mab._resolve_runtime_dylib(info) == dylib+++def test_resolve_runtime_dylib_prefers_unversioned_uv_sibling(tmp_path: Path) -> None:+ import jarvis.setup.macos_app_bundle as mab++ versioned = tmp_path / "cpython-3.12.13-macos-aarch64-none"+ unversioned = tmp_path / "cpython-3.12-macos-aarch64-none"+ for prefix in (versioned, unversioned):+ (prefix / "lib").mkdir(parents=True)+ (prefix / "lib" / "libpython3.12.dylib").write_bytes(b"")+ info = {+ "base_prefix": str(versioned),+ "LIBDIR": str(versioned / "lib"),+ "LDLIBRARY": "libpython3.12.dylib",+ "PYTHONFRAMEWORKPREFIX": "",+ }+ assert mab._resolve_runtime_dylib(info) == (+ unversioned / "lib" / "libpython3.12.dylib"+ )+++def test_resolve_runtime_dylib_framework_layout(tmp_path: Path) -> None:+ import jarvis.setup.macos_app_bundle as mab++ framework_prefix = tmp_path / "Library" / "Frameworks"+ runtime = framework_prefix / "Python.framework" / "Versions" / "3.13"+ runtime.mkdir(parents=True)+ dylib = runtime / "Python"+ dylib.write_bytes(b"")+ info = {+ "base_prefix": str(runtime),+ "LIBDIR": str(runtime / "lib"),+ "LDLIBRARY": "Python.framework/Versions/3.13/Python",+ "PYTHONFRAMEWORKPREFIX": str(framework_prefix),+ }+ assert mab._resolve_runtime_dylib(info) == dylib+++def test_resolve_runtime_dylib_missing_names_every_candidate(tmp_path: Path) -> None:+ import jarvis.setup.macos_app_bundle as mab++ info = {+ "base_prefix": str(tmp_path / "prefix"),+ "LIBDIR": str(tmp_path / "lib"),+ "LDLIBRARY": "libpython3.12.dylib",+ "PYTHONFRAMEWORKPREFIX": "",+ }+ with pytest.raises(RuntimeError) as excinfo:+ mab._resolve_runtime_dylib(info)+ message = str(excinfo.value)+ assert str(tmp_path / "lib" / "libpython3.12.dylib") in message+ assert str(tmp_path / "prefix" / "lib" / "libpython3.12.dylib") in message+++def _native_build_fixture(tmp_path: Path, monkeypatch) -> SimpleNamespace:+ """Prepare a fake install root, runtime layout, and clang subprocess."""+ import jarvis.setup.macos_app_bundle as mab++ monkeypatch.setattr(mab.sys, "platform", "darwin")+ monkeypatch.setattr(mab, "_try_build_icns", lambda _resources: None)++ install_root = tmp_path / "install"+ entry = install_root / "jarvis" / "setup" / "macos_launcher_entry.py"+ entry.parent.mkdir(parents=True)+ entry.write_text("", encoding="utf-8")+ venv_python = install_root / ".venv" / "bin" / "python"+ venv_python.parent.mkdir(parents=True)+ venv_python.write_text("", encoding="utf-8")+ venv_python.chmod(0o755)++ runtime = tmp_path / "runtime"+ (runtime / "lib").mkdir(parents=True)+ dylib = runtime / "lib" / "libpython3.12.dylib"+ dylib.write_bytes(b"")+ include_dir = runtime / "include" / "python3.12"+ include_dir.mkdir(parents=True)+ info = {+ "base_prefix": str(runtime),+ "include": str(include_dir),+ "PYTHONFRAMEWORK": "",+ "LDLIBRARY": "libpython3.12.dylib",+ "LIBDIR": str(runtime / "lib"),+ "PYTHONFRAMEWORKPREFIX": "",+ "machine": "arm64",+ }+ monkeypatch.setattr(mab, "_runtime_link_info", lambda _python: info)++ commands: list[list[str]] = []++ def _fake_clang(command, **_kwargs):+ commands.append(list(command))+ output = Path(command[command.index("-o") + 1])+ output.write_bytes(b"\xcf\xfa\xed\xfe" + b"\x00" * 12)+ return SimpleNamespace(returncode=0, stdout="", stderr="")++ monkeypatch.setattr(mab.subprocess, "run", _fake_clang)+ return SimpleNamespace(+ mab=mab,+ install_root=install_root,+ entry=entry,+ venv_python=venv_python,+ dylib=dylib,+ include_dir=include_dir,+ commands=commands,+ )+++def test_build_native_bundle_layout_and_clang_invocation(+ tmp_path: Path, monkeypatch+) -> None:+ fixture = _native_build_fixture(tmp_path, monkeypatch)+ work = tmp_path / "work"+ work.mkdir()++ bundle = fixture.mab._build_native_bundle(fixture.install_root, work)++ assert bundle == work / APP_DIR_NAME+ info = plistlib.loads((bundle / "Contents" / "Info.plist").read_bytes())+ assert info["CFBundleExecutable"] == "PersonalJarvis"+ assert info["CFBundleIdentifier"] == "com.personal-jarvis.desktop"+ assert info["JarvisBundleFormatVersion"] == 1+ assert "dictate" in info["NSAppleEventsUsageDescription"].lower()+ executable = bundle / "Contents" / "MacOS" / "PersonalJarvis"+ assert executable.read_bytes()[:4] == b"\xcf\xfa\xed\xfe"+ if os.name != "nt":+ assert executable.stat().st_mode & stat.S_IXUSR+ (command,) = fixture.commands+ assert command[:2] == ["/usr/bin/xcrun", "clang"]+ assert command[command.index("-arch") + 1] == "arm64"+ assert command[command.index("-I") + 1] == str(fixture.include_dir)+ assert str(fixture.dylib) in command+ assert f"-Wl,-rpath,{fixture.dylib.parent}" in command+ assert f'-DJARVIS_VENV_PYTHON="{fixture.venv_python.resolve()}"' in command+ assert f'-DJARVIS_ENTRY_SCRIPT="{fixture.entry}"' in command+ assert command[command.index("-o") + 1] == str(executable)+++def test_missing_clang_surfaces_xcode_hint_in_last_error(+ tmp_path: Path, monkeypatch+) -> None:+ fixture = _native_build_fixture(tmp_path, monkeypatch)+ mab = fixture.mab++ def _no_clang(*_args, **_kwargs):+ raise FileNotFoundError("/usr/bin/xcrun")++ monkeypatch.setattr(mab.subprocess, "run", _no_clang)++ with pytest.raises(RuntimeError, match="xcode-select --install"):+ mab._compile_stub(+ tmp_path / "stub.c",+ fixture.dylib,+ fixture.include_dir,+ "arm64",+ [],+ tmp_path / "out",+ )++ assert ensure_macos_app_bundle(+ install_dir=fixture.install_root,+ applications_dir=tmp_path / "Applications",+ ) is None+ assert "xcode-select --install" in (mab.last_error() or "")++def test_launcher_identity_probe_uses_main_bundle(tmp_path: Path, monkeypatch) -> None:from jarvis.setup.macos_launcher_entry import main