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): keep login start, version and uninstall in step with the moved app
Harald Herz0486398c7762
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex b59cd09872..5ee1fa1729 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -15375,3 +15375,57 @@ path, BUG-161); a running app is followed to its new path instead of beingrebuilt. Uninstall clears both folders, and the Keychain ownership check in`jarvis/core/control_key.py` and `jarvis permissions` accept both locations.Guard: `tests/unit/setup/test_macos_app_location.py`.++## BUG-218: after the move to /Applications the app no longer started at login, and other loose ends of "a normal Mac app" (HIGH, FIXED 2026-09-17)++**Symptom.** Checked on a real Mac the day after BUG-216's follow-up moved the+bundle into `/Applications`: the LaunchAgent still read+`open -W -a ~/Applications/Personal Jarvis.app`, a path that no longer existed.+Login autostart was silently dead. Finder's "Get Info" showed version 2.1.0 on+a 2.2.1 install. `lsregister -dump` listed about eighty+`Personal Jarvis.app` bundles under the product's bundle id — all in pytest+temp directories.++**Cause.** Four independent gaps around the bundle's life cycle:++1. *The login item did not move with the app.* The LaunchAgent names the app+ by absolute path and was only ever refreshed by the boot-time reconcile —+ which runs once the app is up. An entry aimed at the old path is what keeps+ the app from coming up at login, so the self-heal could never fire by+ itself.+2. *Same name, different app.* The notarized DMG build is also+ `Personal Jarvis.app` in `/Applications`, under its own bundle id. The+ managed installer would have taken it for a broken bundle of its own and+ rebuilt over it; the uninstaller would have deleted it. The no-venv fallback+ in `install/uninstall.sh` only knew `~/Applications` and left the+ LaunchAgent behind.+3. *Frozen metadata.* A healthy bundle is kept across source updates, so its+ `Info.plist` stayed at the version that first built it.+4. *Tests wrote to the developer's real shell databases.* On a Mac,+ `ensure_macos_app_bundle` registered every temp bundle with the real+ LaunchServices database, and `MacOSAutostart.install` ran a real+ `launchctl load` under the product's own label.++**Fix.** `ensure_macos_app_bundle` now ends by calling+`jarvis.autostart.macos.retarget_launch_agent`, which rewrites the bundle path+of an EXISTING entry (autostart that is off stays off) and deliberately does+not `launchctl load` — RunAtLoad would start the app in the middle of the+installer run. `_is_foreign_bundle` keeps a same-named app with another bundle+id from being chosen, rebuilt over, or removed, in Python and in the shell+fallback, which now also clears both folders and the LaunchAgent. Under the+certificate identity (BUG-217) the code requirement does not depend on the+bundle's bytes, so `_refresh_bundle_version` brings `Info.plist` up to date+without costing a permission; an ad-hoc bundle is never touched for it. A+moved or removed bundle is dropped from LaunchServices+(`unregister_from_launch_services`). The root `tests/conftest.py` points+`lsregister`, `mdimport`, the LaunchAgents folder and `launchctl` at nothing+for every suite.++**Guards.** `tests/unit/autostart/test_macos.py`,+`tests/unit/setup/test_macos_app_location.py`,+`tests/unit/setup/test_macos_app_bundle.py`, `tests/unit/setup/test_uninstall.py`.++**Known limit.** Spotlight answers from the per-volume metadata store. On the+Mac this was verified on, 71 of 72 apps in `/Applications` were missing from+it — a stalled system index that only `sudo mdutil -E /` repairs; `jarvis+doctor` names it. No app can fix that without an administrator password.diff --git a/docs/os-parity.md b/docs/os-parity.mdindex b5595410ff..fbcb93a8ef 100644--- a/docs/os-parity.md+++ b/docs/os-parity.md@@ -323,7 +323,10 @@ off; `--doctor` (`macos-spotlight`) additionally detects a stalled index by animport that never appears. The bundle is also installed into `/Applications`(Finder's Applications folder, Launchpad) whenever the account may write there,falling back to `~/Applications` for standard accounts; an existing per-user-install is moved over by rename, keeping its signature and TCC grants. Windows+install is moved over by rename, keeping its signature and TCC grants, and the+LaunchAgent is pointed at the new path in the same step (BUG-218). A same-named+app with another bundle id (the DMG build) is never replaced or removed, and a+certificate-signed bundle's `Info.plist` version follows source updates. Windowsand Linux areunchanged — their index announcements already feed the search the user typesinto.diff --git a/install/installer.py b/install/installer.pyindex f1866aac7b..5dd2fb692f 100644--- a/install/installer.py+++ b/install/installer.py@@ -796,7 +796,7 @@ def step_summary(*, no_launch: bool, update: bool, headless: bool) -> None:rows.append(("Start again", f'Windows search -> "{PRODUCT_NAME}"', "brand"))elif sys.platform == "darwin":rows.append(- ("Start again", f'Spotlight → "{PRODUCT_NAME}" (app in ~/Applications)', "brand")+ ("Start again", f'Launchpad or Spotlight → "{PRODUCT_NAME}"', "brand"))rows.append(("Permissions", "macOS asks on first launch - approve each prompt", "muted"))elif sys.platform.startswith("linux") and not (headless or is_headless_linux()):diff --git a/install/uninstall.sh b/install/uninstall.shindex 6749aa0bbf..a76d7c0e6c 100644--- a/install/uninstall.sh+++ b/install/uninstall.sh@@ -22,6 +22,8 @@ set -euo pipefail# available even when a broken venv prevents importing the installed package.DEFAULT_INSTALL_DIR_NAME=".personal-jarvis"MACOS_APP_DIR_NAME="Personal Jarvis.app"+MACOS_BUNDLE_ID="com.personal-jarvis.desktop"+MACOS_AUTOSTART_LABEL="com.personal-jarvis.autostart"LINUX_DESKTOP_ENTRY_FILE_NAME="personal-jarvis.desktop"KEYRING_SERVICE_NAME="personal-jarvis"@@ -130,7 +132,23 @@ elseficase "$(uname -s)" inDarwin)- rm -rf -- "$HOME/Applications/$MACOS_APP_DIR_NAME"+ # Both install locations, but only OUR bundle: the DMG build has+ # the same name and its own bundle id, and is not ours to delete.+ for apps_dir in "/Applications" "$HOME/Applications"; do+ app="$apps_dir/$MACOS_APP_DIR_NAME"+ [ -e "$app" ] || continue+ app_id=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' \+ "$app/Contents/Info.plist" 2>/dev/null || true)+ if [ -n "$app_id" ] && [ "$app_id" != "$MACOS_BUNDLE_ID" ]; then+ note "kept $app (a separately installed app)"+ continue+ fi+ rm -rf -- "$app"+ done+ # Without this the login item keeps firing at a deleted app.+ agent="$HOME/Library/LaunchAgents/${MACOS_AUTOSTART_LABEL}.plist"+ launchctl unload -w "$agent" >/dev/null 2>&1 || true+ rm -f -- "$agent";;Linux)rm -f -- "${XDG_DATA_HOME:-$HOME/.local/share}/applications/$LINUX_DESKTOP_ENTRY_FILE_NAME"diff --git a/jarvis/autostart/macos.py b/jarvis/autostart/macos.pyindex e02486734d..5b0947e464 100644--- a/jarvis/autostart/macos.py+++ b/jarvis/autostart/macos.py@@ -22,6 +22,7 @@ import subprocessimport sysfrom pathlib import Path+from jarvis.core.branding import MACOS_APP_DIR_NAME as _APP_DIR_NAMEfrom jarvis.core.branding import MACOS_AUTOSTART_LABEL as _LABELfrom .protocol import AutostartStatus, LaunchSpec@@ -73,6 +74,64 @@ def _launchctl(*argv: str) -> bool:return True+def _write_plist_atomically(path: Path, plist: dict) -> None:+ tmp = path.with_suffix(".plist.tmp")+ try:+ with tmp.open("wb") as fh:+ plistlib.dump(plist, fh)+ tmp.replace(path)+ except BaseException:+ # A half-written .plist.tmp left next to the real entry in+ # ~/Library/LaunchAgents is confusing at best; the successful+ # replace() consumes the temp file, so anything still there is+ # debris from a failed write.+ tmp.unlink(missing_ok=True)+ raise+++def retarget_launch_agent(bundle: Path) -> bool:+ """Point an existing LaunchAgent at ``bundle`` after the app moved.++ The entry names the app by absolute path. Whoever moves the bundle has to+ move the entry with it IN THE SAME STEP: the boot-time reconcile only runs+ once the app is up, and an entry aimed at the old path is exactly what+ keeps it from coming up at login — the app would stay gone from login+ until the user happened to start it by hand.++ Only ever edits an entry that already exists, so a user who switched+ autostart off keeps it off. Returns ``True`` when the entry was rewritten;+ never raises.+ """+ path = _agents_dir() / _ENTRY_NAME+ try:+ if not path.is_file():+ return False+ with path.open("rb") as fh:+ plist = plistlib.load(fh)+ arguments = plist.get("ProgramArguments")+ if not isinstance(arguments, list):+ return False+ target = str(bundle)+ updated = [+ target+ if isinstance(arg, str) and Path(arg).name == _APP_DIR_NAME and arg != target+ else arg+ for arg in arguments+ ]+ if updated == arguments:+ return False+ plist["ProgramArguments"] = updated+ _write_plist_atomically(path, plist)+ except Exception as exc: # noqa: BLE001 - the boot reconcile is the second line of defence+ log.warning("Could not point the LaunchAgent at %s: %s", bundle, exc)+ return False+ # Deliberately no ``launchctl load`` here: RunAtLoad would start the app on+ # the spot, in the middle of the installer run that moved it. launchd reads+ # the file again at the next login, which is the only moment it matters.+ log.info("macOS LaunchAgent now starts the app from %s", bundle)+ return True++class MacOSAutostart:"""LaunchAgent plist autostart manager."""@@ -132,18 +191,7 @@ class MacOSAutostart:# Keep voice and Computer-Use inside the signed-in GUI session."LimitLoadToSessionType": "Aqua",}- tmp = self._path.with_suffix(".plist.tmp")- try:- with tmp.open("wb") as fh:- plistlib.dump(plist, fh)- tmp.replace(self._path)- except BaseException:- # A half-written .plist.tmp left next to the real entry in- # ~/Library/LaunchAgents is confusing at best; the successful- # replace() consumes the temp file, so anything still there is- # debris from a failed write.- tmp.unlink(missing_ok=True)- raise+ _write_plist_atomically(self._path, plist)log.info("macOS LaunchAgent written: %s", self._path)# Re-arm in the current session so it also works before the next login.# unload WITHOUT -w (a plain refresh must not write Disabled=true into@@ -192,4 +240,4 @@ class MacOSAutostart:)-__all__ = ["MacOSAutostart"]+__all__ = ["MacOSAutostart", "retarget_launch_agent"]diff --git a/jarvis/setup/macos_app_bundle.py b/jarvis/setup/macos_app_bundle.pyindex 9b67f04e8c..08e3684421 100644--- a/jarvis/setup/macos_app_bundle.py+++ b/jarvis/setup/macos_app_bundle.py@@ -156,9 +156,31 @@ def macos_applications_dir(user = user_dir or user_applications_dir()for root in (system, user):candidate = root / APP_DIR_NAME- if candidate.exists() or candidate.is_symlink():+ if (candidate.exists() or candidate.is_symlink()) and not _is_foreign_bundle(candidate):return root- return system if os.access(system, os.W_OK) else user+ system_slot = system / APP_DIR_NAME+ if os.access(system, os.W_OK) and not (system_slot.exists() or system_slot.is_symlink()):+ return system+ return user+++def _is_foreign_bundle(candidate: Path) -> bool:+ """Whether ``candidate`` is an app of the same NAME that is not ours.++ The notarized DMG build is also called ``Personal Jarvis.app`` and is+ dragged to ``/Applications`` by hand, under its own bundle id. It is the+ user's app, not this installer's: it must never be taken for the managed+ bundle, replaced by a rebuild, or deleted by an uninstall. Only a readable+ ``Info.plist`` naming a different bundle id proves that — a damaged bundle+ of ours (no or unreadable ``Info.plist``) stays ours, so it can be repaired.+ """+ try:+ with (candidate / "Contents" / "Info.plist").open("rb") as stream:+ bundle_id = plistlib.load(stream).get("CFBundleIdentifier")+ except (OSError, ValueError, plistlib.InvalidFileException):+ # Missing or unreadable metadata proves nothing about ownership.+ return False+ return isinstance(bundle_id, str) and bool(bundle_id) and bundle_id != BUNDLE_IDdef macos_app_bundle_path(*, applications_dir: Path | None = None) -> Path:@@ -196,6 +218,7 @@ def _promote_to_system_applications(log.warning("Could not move %s to %s; keeping it in place: %s", source, system, exc)return Nonelog.info("Moved the macOS app into %s so Finder and Launchpad show it.", system)+ unregister_from_launch_services(source)return target@@ -549,6 +572,31 @@ def register_with_launch_services(bundle: Path) -> bool:return False+def unregister_from_launch_services(bundle: Path) -> bool:+ """Drop ``bundle`` from the LaunchServices database.++ A deleted or moved app otherwise lingers as a second "Personal Jarvis" in+ "Open With" and as a dead target for ``open -b`` until the next database+ rebuild. Works on a path that no longer exists. Best-effort, never raises.+ """+ if sys.platform != "darwin" or not Path(_LSREGISTER).is_file():+ return False+ try:+ result = subprocess.run( # noqa: S603 - fixed system path, no shell+ [_LSREGISTER, "-u", str(bundle)],+ timeout=60,+ stdin=subprocess.DEVNULL,+ capture_output=True,+ text=True,+ check=False,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ except (OSError, subprocess.SubprocessError) as exc:+ log.debug("LaunchServices unregistration skipped: %s", exc)+ return False+ return result.returncode == 0++def _try_build_icns(resources_dir: Path) -> str | None:"""Best-effort ``jarvis.icns`` creation; never block bundle creation."""if sys.platform != "darwin":@@ -1001,14 +1049,48 @@ def _install_native_bundle(return bundle-def _resign_bundle_in_place(bundle: Path, identity: str) -> Path:+def _bundle_version(bundle: Path) -> str | None:+ try:+ with (bundle / "Contents" / "Info.plist").open("rb") as stream:+ version = plistlib.load(stream).get("CFBundleShortVersionString")+ except (OSError, ValueError, plistlib.InvalidFileException):+ return None+ return version if isinstance(version, str) else None+++def _stamp_current_version(staged: Path) -> None:+ info_path = staged / "Contents" / "Info.plist"+ with info_path.open("rb") as stream:+ info = plistlib.load(stream)+ info["CFBundleShortVersionString"] = _version()+ info["CFBundleVersion"] = _version()+ with info_path.open("wb") as stream:+ plistlib.dump(info, stream)+++def _refresh_bundle_version(bundle: Path, identity: str) -> Path:+ """Make Finder's "Get Info" show the version that is actually installed.++ The bundle is kept across source updates, so its ``Info.plist`` froze at+ the version that first built it. Under the certificate identity the code+ requirement does not depend on the bundle's bytes, so the metadata can be+ brought up to date without costing a single permission. An ad-hoc bundle+ is never touched here — for it, any new signature is a new TCC identity.+ """+ refreshed = _resign_bundle_in_place(bundle, identity, prepare=_stamp_current_version)+ log.info("macOS app bundle metadata updated to version %s: %s", _version(), bundle)+ return refreshed+++def _resign_bundle_in_place(bundle: Path, identity: str, *, prepare=None) -> Path:"""Move a healthy ad-hoc bundle onto the certificate identity.Same files, new signature: a copy is signed beside the original andswapped in atomically, so a running instance keeps its own (old) inodeand nothing is ever half-signed on disk. This is the ONE remainingidentity change the user pays for with a final round of re-granting —- after it, no rebuild can orphan a grant again.+ after it, no rebuild can orphan a grant again. ``prepare`` may edit the+ staged copy before it is signed."""parent = bundle.parentprevious_identity = _bundle_tcc_identity(bundle)@@ -1016,6 +1098,8 @@ def _resign_bundle_in_place(bundle: Path, identity: str) -> Path:work = Path(raw_work)staged = work / bundle.nameshutil.copytree(bundle, staged, symlinks=True)+ if prepare is not None:+ prepare(staged)_sign_bundle(staged, identity)if not _signed_with_certificate(staged):raise RuntimeError("re-signing produced a bundle without a certificate identity")@@ -1032,7 +1116,6 @@ def _resign_bundle_in_place(bundle: Path, identity: str) -> Path:if previous.exists() or previous.is_symlink():previous.rename(bundle)raise- log.info("Moved the macOS app bundle onto the local signing identity: %s", bundle)_reset_or_explain(bundle, previous_identity)return bundle@@ -1075,6 +1158,30 @@ def ensure_macos_app_bundle(install_dir: Path | None = None,applications_dir: Path | None = None,create_signing_identity: bool = False,+) -> Path | None:+ """Ensure the app bundle (see ``_ensure_macos_app_bundle``) and keep the+ login item aimed at it, so a moved app still starts at login."""+ bundle = _ensure_macos_app_bundle(+ install_dir=install_dir,+ applications_dir=applications_dir,+ create_signing_identity=create_signing_identity,+ )+ if applications_dir is None and sys.platform == "darwin":+ from jarvis.autostart.macos import retarget_launch_agent++ # A repair that failed still leaves the app wherever it was moved to,+ # and login must find it there.+ target = bundle or macos_app_bundle_path()+ if target.is_dir():+ retarget_launch_agent(target)+ return bundle+++def _ensure_macos_app_bundle(+ *,+ install_dir: Path | None = None,+ applications_dir: Path | None = None,+ create_signing_identity: bool = False,) -> Path | None:"""Ensure ``/Applications/Personal Jarvis.app`` has a stable identity.@@ -1099,6 +1206,13 @@ def ensure_macos_app_bundle(try:install_root = (install_dir or _default_install_dir()).resolve()bundle = macos_app_bundle_path(applications_dir=applications_dir)+ if _is_foreign_bundle(bundle):+ # Rebuilding "repairs" by replacing; that would destroy an app the+ # user installed themselves (the DMG build shares our name).+ raise RuntimeError(+ f"{bundle} is a separately installed app with its own bundle id; "+ "it is left untouched and no second copy is written next to it"+ )diagnostics: list[str] = []identity = (ensure_local_signing_identity(create=create_signing_identity)@@ -1136,9 +1250,12 @@ def ensure_macos_app_bundle(bundle,)resigned = _resign_bundle_in_place(bundle, identity)+ log.info("Moved the macOS app bundle onto the local signing identity.")register_with_launch_services(resigned)_record_rebuild(resigned, install_root=install_root, identity=identity)return resigned+ if identity is not None and _bundle_version(bundle) != _version():+ bundle = _refresh_bundle_version(bundle, identity)# A healthy bundle is kept byte-for-byte, but LaunchServices may# still not know it — an interrupted earlier run, or a database# rebuilt since. Re-registering is a no-op when it is known, and@@ -1203,8 +1320,12 @@ def remove_macos_app_bundle(*, applications_dir: Path | None = None) -> bool:bundle = root / APP_DIR_NAMEif not bundle.exists() and not bundle.is_symlink():continue+ if _is_foreign_bundle(bundle):+ log.info("Keeping %s: it is a separately installed app, not this install's.", bundle)+ continuetry:_remove_path(bundle)+ unregister_from_launch_services(bundle)log.info("macOS app bundle removed: %s", bundle)except OSError as exc:log.warning("Could not remove %s: %s", bundle, exc)@@ -1226,4 +1347,5 @@ __all__ = ["macos_launch_services_command","register_with_launch_services","remove_macos_app_bundle",+ "unregister_from_launch_services",]diff --git a/tests/conftest.py b/tests/conftest.pyindex f52a83e23b..ad0193117b 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -115,6 +115,34 @@ def _agentic_ide_history_in_tmp(tmp_path_factory, monkeypatch): # noqa: ANN001yield root[email protected](autouse=True)+def _macos_shell_registration_in_tmp(tmp_path_factory, monkeypatch): # noqa: ANN001+ """Keep every suite away from the developer's real macOS shell databases.++ On a Mac the bundle suites build real ``Personal Jarvis.app`` bundles under+ pytest's temp directory, and ``ensure_macos_app_bundle`` then registered+ each one with the REAL LaunchServices database: one developer machine had+ collected some eighty temp bundles under the product's bundle id, every one+ a candidate for "Open With" and ``open -b``. The same call now also keeps+ the login item aimed at the bundle, which would point the developer's real+ LaunchAgent at a temp directory. Root conftest for the same reason as the+ history redirect above: the leak comes in through whichever suite nobody+ thought of. Suites that test these calls themselves patch on top of this.+ """+ import jarvis.autostart.macos as autostart_macos+ import jarvis.setup.macos_app_bundle as mab+ import jarvis.setup.macos_search_index as search_index++ agents = tmp_path_factory.mktemp("launch-agents")+ monkeypatch.setattr(autostart_macos, "_agents_dir", lambda: agents)+ # The label is the product's own, so a real ``launchctl load`` of a test+ # plist collides with — or, through RunAtLoad, starts — the installed app.+ monkeypatch.setattr(autostart_macos, "_launchctl", lambda *_argv: True)+ monkeypatch.setattr(mab, "_LSREGISTER", str(agents / "no-lsregister"))+ monkeypatch.setattr(search_index, "_MDIMPORT", str(agents / "no-mdimport"))+ yield agents++@pytest.fixture(autouse=True)def _pricing_feed_in_tmp(tmp_path_factory, monkeypatch): # noqa: ANN001"""Keep cost tracking's provider-feed refresh off the network and off thediff --git a/tests/unit/autostart/test_macos.py b/tests/unit/autostart/test_macos.pyindex 6f408ab8eb..fb738410a0 100644--- a/tests/unit/autostart/test_macos.py+++ b/tests/unit/autostart/test_macos.py@@ -111,3 +111,60 @@ def test_install_leaves_no_temp_file_when_the_plist_write_fails(MacOSAutostart().install(_spec())assert list(tmp_path.glob("*.tmp")) == []+++_OLD_APP = "/Users/u/Applications/Personal Jarvis.app"+_NEW_APP = "/Applications/Personal Jarvis.app"+++def test_a_moved_app_takes_its_login_item_along(monkeypatch, tmp_path: Path) -> None:+ """The boot reconcile cannot heal this: an entry aimed at the old path is+ what keeps the app from booting at login in the first place."""+ monkeypatch.setattr(macos, "_agents_dir", lambda: tmp_path)+ MacOSAutostart().install(_spec())++ assert macos.retarget_launch_agent(Path(_NEW_APP)) is True++ with (tmp_path / "com.personal-jarvis.autostart.plist").open("rb") as fh:+ data = plistlib.load(fh)+ assert data["ProgramArguments"] == ["/usr/bin/open", "-W", "-a", _NEW_APP]+ # Everything that is not the bundle path is the user's and stays.+ assert data["WorkingDirectory"] == "/Users/u/jarvis"+ assert data["RunAtLoad"] is True+ assert not list(tmp_path.glob("*.tmp"))+++def test_a_current_login_item_is_left_alone(monkeypatch, tmp_path: Path) -> None:+ monkeypatch.setattr(macos, "_agents_dir", lambda: tmp_path)+ MacOSAutostart().install(_spec())+ entry = tmp_path / "com.personal-jarvis.autostart.plist"+ before = entry.read_bytes()++ assert macos.retarget_launch_agent(Path(_OLD_APP)) is False+ assert entry.read_bytes() == before+++def test_moving_the_app_never_switches_autostart_back_on(monkeypatch, tmp_path: Path) -> None:+ monkeypatch.setattr(macos, "_agents_dir", lambda: tmp_path)++ assert macos.retarget_launch_agent(Path(_NEW_APP)) is False+ assert not list(tmp_path.iterdir())+++def test_moving_the_app_never_starts_it(monkeypatch, tmp_path: Path) -> None:+ """``launchctl load`` fires RunAtLoad — in the middle of an installer run."""+ monkeypatch.setattr(macos, "_agents_dir", lambda: tmp_path)+ MacOSAutostart().install(_spec())+ calls: list[tuple[str, ...]] = []+ monkeypatch.setattr(macos, "_launchctl", lambda *argv: calls.append(argv) or True)++ macos.retarget_launch_agent(Path(_NEW_APP))++ assert calls == []+++def test_an_unreadable_login_item_does_not_fail_the_move(monkeypatch, tmp_path: Path) -> None:+ monkeypatch.setattr(macos, "_agents_dir", lambda: tmp_path)+ (tmp_path / "com.personal-jarvis.autostart.plist").write_bytes(b"not a plist")++ assert macos.retarget_launch_agent(Path(_NEW_APP)) is Falsediff --git a/tests/unit/setup/test_macos_app_bundle.py b/tests/unit/setup/test_macos_app_bundle.pyindex b0d15edb47..ded35468a6 100644--- a/tests/unit/setup/test_macos_app_bundle.py+++ b/tests/unit/setup/test_macos_app_bundle.py@@ -1005,3 +1005,76 @@ def test_a_rebuild_with_the_identity_never_resets_the_grants(tmp_path: Path, monmab._reset_or_explain(tmp_path / APP_DIR_NAME, same)assert not marker.exists()+++def _healthy_darwin_bundle(tmp_path: Path, monkeypatch, *, identity: str | None):+ import jarvis.setup.macos_app_bundle as mab++ bundle = _build(tmp_path, monkeypatch)+ monkeypatch.setattr(mab.sys, "platform", "darwin")+ monkeypatch.setattr(mab, "ensure_local_signing_identity", lambda *, create: identity)+ monkeypatch.setattr(mab, "_codesign_issue", lambda _bundle: None)+ monkeypatch.setattr(mab, "_running_managed_bundle", lambda *, install_root, **_kw: None)+ monkeypatch.setattr(+ mab,+ "_runtime_identity_valid",+ lambda _bundle, *, install_root, diagnostics=None: True,+ )+ monkeypatch.setattr(mab, "_signed_with_certificate", lambda _b: identity is not None)+ monkeypatch.setattr(mab, "_bundle_tcc_identity", lambda _b: "identifier and certificate")+ monkeypatch.setattr(+ mab,+ "_install_native_bundle",+ lambda *_args, **_kwargs: pytest.fail("a healthy bundle is never rebuilt"),+ )+ return mab, bundle+++def test_an_update_brings_the_bundle_version_along(tmp_path: Path, monkeypatch) -> None:+ """Finder's "Get Info" froze at the version that first built the bundle."""+ mab, bundle = _healthy_darwin_bundle(tmp_path, monkeypatch, identity="ABCDEF")+ signed: list[str | None] = []+ monkeypatch.setattr(mab, "_sign_bundle", lambda _target, identity=None: signed.append(identity))+ monkeypatch.setattr(+ mab, "_reset_stale_tcc_grants", lambda: pytest.fail("same identity, nothing to reset")+ )+ monkeypatch.setattr(mab, "_version", lambda: "9.9.9")++ result = ensure_macos_app_bundle(+ install_dir=tmp_path / "install", applications_dir=tmp_path / "Applications"+ )++ assert result == bundle+ with (bundle / "Contents" / "Info.plist").open("rb") as stream:+ info = plistlib.load(stream)+ assert info["CFBundleShortVersionString"] == info["CFBundleVersion"] == "9.9.9"+ assert signed == ["ABCDEF"]+ assert not [p for p in bundle.parent.iterdir() if p.name.startswith(".jarvis-")]+++def test_an_adhoc_bundle_keeps_its_stale_version(tmp_path: Path, monkeypatch) -> None:+ """For an ad-hoc bundle a new signature is a new TCC identity: every grant+ would be the price of a cosmetic version string."""+ mab, bundle = _healthy_darwin_bundle(tmp_path, monkeypatch, identity=None)+ before = (bundle / "Contents" / "Info.plist").read_bytes()+ monkeypatch.setattr(+ mab, "_sign_bundle", lambda *_a, **_kw: pytest.fail("an ad-hoc bundle is never re-signed")+ )+ monkeypatch.setattr(mab, "_version", lambda: "9.9.9")++ ensure_macos_app_bundle(+ install_dir=tmp_path / "install", applications_dir=tmp_path / "Applications"+ )++ assert (bundle / "Contents" / "Info.plist").read_bytes() == before+++def test_a_removed_app_is_dropped_from_launch_services(tmp_path: Path, monkeypatch) -> None:+ import jarvis.setup.macos_app_bundle as mab++ bundle = _build(tmp_path, monkeypatch)+ unregistered: list[Path] = []+ monkeypatch.setattr(mab, "unregister_from_launch_services", unregistered.append)++ assert mab.remove_macos_app_bundle(applications_dir=bundle.parent) is True+ assert unregistered == [bundle]diff --git a/tests/unit/setup/test_macos_app_location.py b/tests/unit/setup/test_macos_app_location.pyindex cb1933ca6f..ca1bf47d29 100644--- a/tests/unit/setup/test_macos_app_location.py+++ b/tests/unit/setup/test_macos_app_location.py@@ -11,6 +11,7 @@ every TCC grant, survives a rename), and never loses the app on the way.from __future__ import annotationsimport os+import plistlibimport sysfrom pathlib import Path@@ -167,3 +168,115 @@ def test_the_running_app_is_followed_to_its_new_location(assert result == system / APP_DIR_NAMEassert registered == [system / APP_DIR_NAME]assert not launched_from.exists()+++def _foreign_bundle(root: Path) -> Path:+ """The notarized DMG build: same name, its own bundle id."""+ bundle = _bundle(root, marker="dmg-build")+ with (bundle / "Contents" / "Info.plist").open("wb") as stream:+ plistlib.dump({"CFBundleIdentifier": "ai.personaljarvis.desktop"}, stream)+ return bundle+++def test_a_separately_installed_app_is_not_taken_for_ours(roots) -> None:+ system, user = roots+ _foreign_bundle(system)+ assert macos_applications_dir(system_dir=system, user_dir=user) == user+++def test_uninstall_keeps_a_separately_installed_app(roots, monkeypatch: pytest.MonkeyPatch) -> None:+ system, user = roots+ foreign = _foreign_bundle(system)+ _bundle(user)+ monkeypatch.setattr(mab.sys, "platform", "darwin")+ monkeypatch.setattr(mab, "SYSTEM_APPLICATIONS_DIR", system)+ monkeypatch.setattr(mab, "user_applications_dir", lambda: user)++ assert remove_macos_app_bundle() is True+ assert foreign.is_dir()+ assert not (user / APP_DIR_NAME).exists()+++def test_a_repair_never_replaces_a_separately_installed_app(+ roots, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ system, _user = roots+ foreign = _foreign_bundle(system)+ monkeypatch.setattr(mab, "ensure_local_signing_identity", lambda **_kw: None)+ monkeypatch.setattr(+ mab,+ "_install_native_bundle",+ lambda *_a, **_kw: pytest.fail("a foreign app must never be rebuilt over"),+ )++ assert (+ ensure_macos_app_bundle(install_dir=tmp_path / "install", applications_dir=system) is None+ )+ assert "separately installed" in (mab.last_error() or "")+ assert (foreign / "Contents" / "MacOS" / "PersonalJarvis").read_text() == "dmg-build"+++def test_a_damaged_bundle_of_ours_is_still_ours(roots) -> None:+ """No Info.plist proves nothing about ownership — it must stay repairable."""+ system, user = roots+ _bundle(system)+ assert macos_applications_dir(system_dir=system, user_dir=user) == system+++def test_the_login_item_follows_the_moved_app(+ roots, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ import jarvis.autostart.macos as autostart_macos+ from jarvis.autostart.macos import MacOSAutostart+ from jarvis.autostart.protocol import LaunchSpec++ system, user = roots+ _bundle(user)+ launched_from = user / APP_DIR_NAME+ agents = tmp_path / "LaunchAgents"+ monkeypatch.setattr(autostart_macos, "_agents_dir", lambda: agents)+ MacOSAutostart().install(+ LaunchSpec(+ program="/usr/bin/open",+ args=("-W", "-a", str(launched_from)),+ working_dir=str(tmp_path),+ minimized=False,+ )+ )+ monkeypatch.setattr(mab.sys, "platform", "darwin")+ monkeypatch.setattr(mab, "SYSTEM_APPLICATIONS_DIR", system)+ monkeypatch.setattr(mab, "user_applications_dir", lambda: user)+ monkeypatch.setattr(mab, "ensure_local_signing_identity", lambda **_kw: None)+ monkeypatch.setattr(+ mab, "_running_managed_bundle", lambda *, install_root, **_kw: launched_from+ )+ monkeypatch.setattr(mab, "register_with_launch_services", lambda _bundle: True)++ ensure_macos_app_bundle(install_dir=tmp_path / "install")++ with (agents / "com.personal-jarvis.autostart.plist").open("rb") as fh:+ arguments = plistlib.load(fh)["ProgramArguments"]+ assert arguments == ["/usr/bin/open", "-W", "-a", str(system / APP_DIR_NAME)]+++def test_the_login_item_follows_even_when_the_repair_fails(+ roots, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """Seen live: signing failed after the move, and login kept the dead path."""+ import jarvis.autostart.macos as autostart_macos++ system, user = roots+ _bundle(user)+ monkeypatch.setattr(mab.sys, "platform", "darwin")+ monkeypatch.setattr(mab, "SYSTEM_APPLICATIONS_DIR", system)+ monkeypatch.setattr(mab, "user_applications_dir", lambda: user)++ def _signing_breaks(**_kw):+ raise RuntimeError("errSecInternalComponent")++ monkeypatch.setattr(mab, "ensure_local_signing_identity", _signing_breaks)+ retargeted: list[Path] = []+ monkeypatch.setattr(autostart_macos, "retarget_launch_agent", retargeted.append)++ assert ensure_macos_app_bundle(install_dir=tmp_path / "install") is None+ assert retargeted == [system / APP_DIR_NAME]diff --git a/tests/unit/setup/test_macos_search_index.py b/tests/unit/setup/test_macos_search_index.pyindex 2ec68f5fdf..0070c1bf1d 100644--- a/tests/unit/setup/test_macos_search_index.py+++ b/tests/unit/setup/test_macos_search_index.py@@ -57,6 +57,10 @@ def fake_tools(monkeypatch: pytest.MonkeyPatch):"""Pretend to be macOS with the metadata tools present; record every argv."""monkeypatch.setattr(sys, "platform", "darwin")monkeypatch.setattr(Path, "is_file", lambda self: True)+ # The root conftest points both tools at nothing so no suite reaches the+ # real databases; this one fakes the runner, so it names the real tools.+ monkeypatch.setattr(macos_search_index, "_MDIMPORT", "/usr/bin/mdimport")+ monkeypatch.setattr(macos_app_bundle, "_LSREGISTER", "/System/Library/Frameworks/lsregister")calls: list[list[str]] = []replies: dict[str, _Result] = {}diff --git a/tests/unit/setup/test_uninstall.py b/tests/unit/setup/test_uninstall.pyindex b7872e61e7..cfeee352b5 100644--- a/tests/unit/setup/test_uninstall.py+++ b/tests/unit/setup/test_uninstall.py@@ -165,7 +165,11 @@ def test_bootstrap_fallbacks_remove_registration_without_the_venv() -> None:assert "$WindowsUninstallRegistrySubkey" in windowsassert "$WindowsShortcutFileName" in windows- assert "$HOME/Applications/$MACOS_APP_DIR_NAME" in posix+ # Both install locations (BUG-216), never a same-named app with its own+ # bundle id, and the login item that would otherwise fire at a deleted app.+ assert 'for apps_dir in "/Applications" "$HOME/Applications"' in posix+ assert '"$app_id" != "$MACOS_BUNDLE_ID"' in posix+ assert "LaunchAgents/${MACOS_AUTOSTART_LABEL}.plist" in posixassert "applications/$LINUX_DESKTOP_ENTRY_FILE_NAME" in posix