Skip to content

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.

fix(desktop): repair cross-platform app registration

Ruben Lütke8d02d77d4655
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 84c58218b4..d34787b126 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,16 @@ versioning per [SemVer](https://semver.org/lang/de/).
---
+## [Unreleased]
+
+### Fixed
+
+- **Desktop installs remain discoverable after an in-app update.** Managed
+ installs now register and repair the Windows Start-menu and Installed Apps
+ entries, the macOS per-user app bundle, or the Linux application-menu entry.
+ Installer, updater, first desktop paint, and uninstaller share one guarded
+ lifecycle, while headless and developer checkouts remain untouched.
+
## [1.0.7] — 2026-07-14
### Fixed
diff --git a/install/README.md b/install/README.md
index 1bc3651619..61b9295517 100644
--- a/install/README.md
+++ b/install/README.md
@@ -29,13 +29,19 @@ app as its last action. Re-running the one-liner updates in place and never
re-runs setup. `--headless` keeps the minimal torch-free base (the tiny-VPS /
advanced path).
+GUI installs also register Personal Jarvis with the current desktop shell:
+Windows Search and Installed Apps, Spotlight via a per-user macOS app bundle,
+or the Linux application menu. The in-app updater and first desktop launch
+repair these artifacts, and uninstall removes them again. Developer checkouts
+and headless Linux hosts are deliberately not registered.
+
## File layout
| File | Stage | Responsibility |
|-------------------|-------|----------------|
| `install.ps1` | 1 | Windows bootstrap: Python+Git detect/install/re-check, clone, venv, install `rich`, exec `installer.py`. |
| `install.sh` | 1 | macOS/Linux bootstrap: same flow through native package managers, POSIX bash. |
-| `installer.py` | 2 | Python orchestrator: pip install, optional extras, model prefetch, worker CLI, launch (last). All cross-platform logic lives here. |
+| `installer.py` | 2 | Python orchestrator: pip install, optional extras, model prefetch, worker CLI, desktop registration, launch (last). |
| `README.md` | docs | This file. |
## Why two stages?
diff --git a/install/installer.py b/install/installer.py
index 4c378fb605..ca23e77668 100644
--- a/install/installer.py
+++ b/install/installer.py
@@ -15,12 +15,12 @@ continues with 4-6. Keep the numbering in sync with install.sh / install.ps1.
Phases owned here:
4/6 Dependencies — editable install + runtime deps via pip. Desktop hosts
- (Windows/macOS, or ``--with-desktop``) also get the ``[full]`` extras;
+ (Windows/macOS/Linux, or ``--with-desktop``) get the ``[full]`` extras;
headless keeps the torch-free base floor.
5/6 Voice models — prefetch everything the config needs (``python -m
jarvis --prefetch``) + verify what actually landed on disk.
- 6/6 Finish & launch — best-effort worker CLI (npm) + Windows Start-Menu
- shortcut + UI-bundle integrity check, then the flat summary, then
+ 6/6 Finish & launch — best-effort worker CLI (npm) + native desktop-shell
+ registration + UI-bundle integrity check, then the flat summary, then
launch the Desktop App / headless server as the LAST action unless
``--no-launch``.
@@ -166,12 +166,15 @@ def step_preflight() -> None:
if is_headless_linux():
note("headless Linux detected — installing the server profile")
- if sys.version_info < (3, 11):
+ if sys.version_info < (3, 11): # noqa: UP036 - Stage 2 rechecks Stage 1
console.print("[bad] Python 3.11+ required.[/]")
sys.exit(1)
if not (repo_root() / "pyproject.toml").exists():
- console.print("[bad] pyproject.toml not found — installer.py was invoked outside the repo.[/]")
+ console.print(
+ "[bad] pyproject.toml not found — installer.py was invoked "
+ "outside the repo.[/]"
+ )
sys.exit(1)
@@ -364,58 +367,43 @@ def step_worker_cli(*, dry_run: bool) -> None:
note("Jarvis-Agent worker CLI install failed - it can be added later in-app")
-def step_shortcut(*, dry_run: bool) -> None:
- """Finish & launch sub-step (Windows): Start-Menu shortcut = taskbar identity."""
- if sys.platform != "win32":
+def step_desktop_integration(*, enabled: bool, dry_run: bool) -> None:
+ """Register the managed install with the current desktop shell."""
+ if not enabled:
return
if dry_run:
- console.print("[muted] (dry-run) ensure_start_menu_shortcut()[/]")
+ console.print("[muted] (dry-run) repair desktop-shell registration[/]")
return
- probe = (
- "from jarvis.ui.icon_utils import ensure_start_menu_shortcut\n"
- "print('ok' if ensure_start_menu_shortcut() else 'skipped')\n"
- )
try:
result = subprocess.run(
- [str(venv_python()), "-c", probe], cwd=repo_root(),
+ [
+ str(venv_python()),
+ "-m",
+ "jarvis.setup.desktop_integration",
+ "--install-dir",
+ str(repo_root()),
+ "--json",
+ ],
+ cwd=repo_root(),
capture_output=True, text=True, encoding="utf-8", errors="replace",
timeout=120,
)
- outcome = (result.stdout or "").strip()
+ output = (result.stdout or "").strip().splitlines()
+ report = json.loads(output[-1]) if output else {}
except (OSError, subprocess.TimeoutExpired):
- outcome = ""
- if outcome.endswith("ok"):
- ok("Start-Menu shortcut in place (taskbar shows the Jarvis name + icon)")
+ report = {}
+ result = None
+ except (json.JSONDecodeError, TypeError, ValueError):
+ report = {}
+ if (
+ result is not None
+ and result.returncode == 0
+ and report.get("ok")
+ and report.get("attempted")
+ ):
+ ok("desktop app registered with the operating system")
else:
- note("could not create the Start-Menu shortcut - the app will retry on first launch")
-
-
-def step_macos_app(*, dry_run: bool) -> None:
- """Finish & launch sub-step (macOS): a real .app so Spotlight/Launchpad
- find Jarvis — without it, closing the app leaves no way back but the
- terminal (BUG-060)."""
- if sys.platform != "darwin":
- return
- if dry_run:
- console.print("[muted] (dry-run) ensure_macos_app_bundle()[/]")
- return
- probe = (
- "from jarvis.setup.macos_app_bundle import ensure_macos_app_bundle\n"
- "print('ok' if ensure_macos_app_bundle() else 'skipped')\n"
- )
- try:
- result = subprocess.run(
- [str(venv_python()), "-c", probe], cwd=repo_root(),
- capture_output=True, text=True, encoding="utf-8", errors="replace",
- timeout=120,
- )
- outcome = (result.stdout or "").strip()
- except (OSError, subprocess.TimeoutExpired):
- outcome = ""
- if outcome.endswith("ok"):
- ok('app installed to ~/Applications - find it via Spotlight ("Personal Jarvis")')
- else:
- note("could not create the ~/Applications app - start via the install folder")
+ note("desktop registration is incomplete - the app will retry after first paint")
def step_ui_bundle_check() -> None:
@@ -503,12 +491,18 @@ def step_summary(*, no_launch: bool, update: bool, headless: bool) -> None:
console.print(f" [ok.bold]✓ Personal Jarvis is {'updated' if update else 'ready'}.[/]")
console.print(f" [muted]Installed to[/] {repo_root()}")
if sys.platform == "win32":
- console.print(" [muted]Start again[/] [brand]run.bat[/] [muted](in the install folder)[/]")
+ console.print(
+ " [muted]Start again[/] [brand]Windows search -> \"Personal Jarvis\"[/]"
+ )
elif sys.platform == "darwin":
console.print(
" [muted]Start again[/] [brand]Spotlight → \"Personal Jarvis\"[/] "
"[muted](app in ~/Applications)[/]"
)
+ elif sys.platform.startswith("linux") and not (headless or is_headless_linux()):
+ console.print(
+ " [muted]Start again[/] [brand]app menu -> \"Personal Jarvis\"[/]"
+ )
else:
console.print(
" [muted]Start again[/] [brand].venv/bin/python -m jarvis.ui.web.launcher[/] "
@@ -575,7 +569,9 @@ def main(argv: list[str] | None = None) -> int:
if args.headless or is_headless_linux():
with_desktop = False
else:
- with_desktop = sys.platform in {"win32", "darwin"}
+ with_desktop = sys.platform in {"win32", "darwin"} or sys.platform.startswith(
+ "linux"
+ )
else:
with_desktop = True
@@ -597,8 +593,7 @@ def main(argv: list[str] | None = None) -> int:
phase("6/6", "Finish & launch")
step_worker_cli(dry_run=args.dry_run)
- step_shortcut(dry_run=args.dry_run)
- step_macos_app(dry_run=args.dry_run)
+ step_desktop_integration(enabled=with_desktop, dry_run=args.dry_run)
step_ui_bundle_check()
# Summary FIRST, launch LAST: when the app window appears, the terminal
diff --git a/install/uninstall.ps1 b/install/uninstall.ps1
index 0825669614..b927412fc3 100644
--- a/install/uninstall.ps1
+++ b/install/uninstall.ps1
@@ -5,10 +5,11 @@
# & "$env:USERPROFILE\.personal-jarvis\install\uninstall.ps1" --dry-run # preview
# & "$env:USERPROFILE\.personal-jarvis\install\uninstall.ps1" --yes # no prompt
#
-# It removes three things a plain folder-delete would miss:
+# It removes four things a plain folder-delete would miss:
# 1. the install folder (~\.personal-jarvis)
-# 2. the login-autostart entry (a logon scheduled task / Startup shortcut)
-# 3. the API keys saved in the OS keychain (Windows Credential Manager, service
+# 2. the Start-menu launcher and Installed Apps registration
+# 3. the login-autostart entry (a logon scheduled task / Startup shortcut)
+# 4. the API keys saved in the OS keychain (Windows Credential Manager, service
# "personal-jarvis")
#
# Heavy logic lives in `python -m jarvis --uninstall` (cross-platform, tested).
@@ -47,20 +48,27 @@ if (-not (Test-Path -LiteralPath $InstallDir)) {
exit 0
}
-# 1 + 2 + 3: run the tested cleanup (autostart + keys), keeping the folder so we
-# delete it ourselves below (the running venv must not self-delete).
+# 2 + 3 + 4: run the tested cleanup (app registration, autostart, and keys),
+# keeping the folder so we can delete it below.
$Rc = 0
if (Test-Path -LiteralPath $VenvPython) {
& $VenvPython -m jarvis --uninstall --keep-folder @args
$Rc = $LASTEXITCODE
} else {
Write-Err 'Python environment missing - skipping autostart/key cleanup.'
- Write-Note 'Removing the folder only; saved API keys may remain in Credential Manager.'
+ Write-Note 'The app registration and folder can still be removed; saved API keys may remain.'
if ($DryRun) { exit 0 }
if (-not $AssumeYes) {
$ans = Read-Host "Type 'yes' to delete $InstallDir"
if ($ans -ne 'yes') { Write-Note 'Cancelled.'; exit 1 }
}
+ if ($env:APPDATA) {
+ $Shortcut = Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs\Personal Jarvis.lnk'
+ Remove-Item -LiteralPath $Shortcut -Force -ErrorAction SilentlyContinue
+ }
+ Remove-Item -LiteralPath 'Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall\PersonalJarvis' -Recurse -Force -ErrorAction SilentlyContinue
+ Remove-Item -LiteralPath 'Registry::HKEY_CURRENT_USER\Software\Classes\AppUserModelId\PersonalJarvis.PersonalJarvis' -Recurse -Force -ErrorAction SilentlyContinue
+ Write-Ok 'Removed the desktop app registration.'
$Rc = 0
}
diff --git a/install/uninstall.sh b/install/uninstall.sh
index 2568185ee9..eaac17d3b4 100644
--- a/install/uninstall.sh
+++ b/install/uninstall.sh
@@ -6,10 +6,11 @@
# bash ~/.personal-jarvis/install/uninstall.sh --dry-run # preview only
# bash ~/.personal-jarvis/install/uninstall.sh --yes # no prompt
#
-# It removes three things a plain folder-delete would miss:
+# It removes four things a plain folder-delete would miss:
# 1. the install folder (~/.personal-jarvis)
-# 2. the login-autostart entry (~/.config/autostart or ~/Library/LaunchAgents)
-# 3. the API keys saved in the OS keychain (service "personal-jarvis")
+# 2. the macOS app bundle or Linux application-menu entry
+# 3. the login-autostart entry (~/.config/autostart or ~/Library/LaunchAgents)
+# 4. the API keys saved in the OS keychain (service "personal-jarvis")
#
# Heavy logic lives in `python -m jarvis --uninstall` (cross-platform, tested).
# This bootstrap runs that for the autostart + keys (it asks for confirmation),
@@ -44,19 +45,28 @@ if [ ! -d "$INSTALL_DIR" ]; then
exit 0
fi
-# 1 + 2 + 3: run the tested cleanup (autostart + keys), keeping the folder so we
-# can delete it ourselves below. --keep-folder means the venv is not
-# self-deleted while it is still running.
+# 2 + 3 + 4: run the tested cleanup (app registration, autostart, and keys),
+# keeping the folder so we can delete it below. --keep-folder means
+# the venv is not self-deleted while it is still running.
RC=0
if [ -x "$VENV_PYTHON" ]; then
if "$VENV_PYTHON" -m jarvis --uninstall --keep-folder "$@"; then RC=0; else RC=$?; fi
else
err "Python environment missing — skipping autostart/key cleanup."
- note "Removing the folder only; saved API keys may remain in your keychain."
+ note "The app registration and folder can still be removed; saved API keys may remain."
if [ "$DRY_RUN" -eq 1 ]; then exit 0; fi
printf 'Type '\''yes'\'' to delete %s: ' "$INSTALL_DIR"
read -r ans
[ "$ans" = "yes" ] || { note 'Cancelled.'; exit 1; }
+ case "$(uname -s)" in
+ Darwin)
+ rm -rf -- "$HOME/Applications/Personal Jarvis.app"
+ ;;
+ Linux)
+ rm -f -- "${XDG_DATA_HOME:-$HOME/.local/share}/applications/personal-jarvis.desktop"
+ ;;
+ esac
+ ok 'Removed the desktop app registration.'
RC=0
fi
diff --git a/jarvis/setup/desktop_integration.py b/jarvis/setup/desktop_integration.py
new file mode 100644
index 0000000000..113e7f6cb8
--- /dev/null
+++ b/jarvis/setup/desktop_integration.py
@@ -0,0 +1,464 @@
+"""Cross-platform desktop registration for managed Personal Jarvis installs.
+
+The public installer is source-based: it creates a virtual environment and runs
+the desktop through Python. Without explicit shell registration that leaves a
+working process which the operating system does not consider an installed app.
+
+This module owns the external, per-user artifacts as one lifecycle:
+
+* Windows: Start-menu launcher, AppUserModel identity, and Installed Apps entry.
+* macOS: ``~/Applications/Personal Jarvis.app``.
+* Linux: ``$XDG_DATA_HOME/applications/personal-jarvis.desktop``.
+
+Installer, updater, first desktop boot, and uninstaller all call this module so
+an update cannot move the code while leaving its launcher behind. Registration
+is restricted to installer-managed trees by default; a developer checkout must
+never acquire an uninstall entry which could delete the checkout.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import logging
+import os
+import subprocess
+import sys
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from typing import Any
+
+log = logging.getLogger(__name__)
+
+MANAGED_MARKER = ".jarvis-managed-install"
+WINDOWS_UNINSTALL_SUBKEY = (
+ r"Software\Microsoft\Windows\CurrentVersion\Uninstall\PersonalJarvis"
+)
+WINDOWS_APP_USER_MODEL_ID = "PersonalJarvis.PersonalJarvis"
+
+
+def _windows_aumid_subkey(aumid: str) -> str:
+ return rf"Software\Classes\AppUserModelId\{aumid}"
+
+
+@dataclass(frozen=True)
+class DesktopIntegrationReport:
+ """Serializable result shared by installer, updater, and boot repair."""
+
+ platform: str
+ managed: bool
+ attempted: bool
+ ok: bool
+ artifacts: tuple[str, ...] = ()
+ warnings: tuple[str, ...] = ()
+ skipped_reason: str | None = None
+
+ def to_dict(self) -> dict[str, Any]:
+ payload = asdict(self)
+ payload["artifacts"] = list(self.artifacts)
+ payload["warnings"] = list(self.warnings)
+ return payload
+
+
+def _install_root() -> Path:
+ import jarvis
+
+ return Path(jarvis.__file__).resolve().parent.parent
+
+
+def _version() -> str:
+ try:
+ from jarvis import __version__
+
+ return str(__version__)
+ except Exception: # noqa: BLE001 - registration remains useful without a version
+ return "0.0.0"
+
+
+def _platform(value: str | None = None) -> str:
+ raw = value or sys.platform
+ if raw == "win32":
+ return "windows"
+ if raw == "darwin":
+ return "macos"
+ if raw.startswith("linux"):
+ return "linux"
+ return raw
+
+
+def is_managed_install(install_dir: Path) -> bool:
+ """Return whether ``install_dir`` was created by the public installer."""
+
+ return (install_dir / MANAGED_MARKER).is_file()
+
+
+def _windows_uninstall_script(install_dir: Path) -> Path:
+ return install_dir / "install" / "uninstall.ps1"
+
+
+def _windows_powershell() -> str:
+ system_root = os.environ.get("SystemRoot")
+ if system_root:
+ candidate = Path(system_root) / "System32" / "WindowsPowerShell" / "v1.0" / "powershell.exe"
+ if candidate.is_file():
+ return str(candidate)
+ return "powershell.exe"
+
+
+def windows_uninstall_values(
+ install_dir: Path,
+ *,
+ version: str | None = None,
+ icon_path: Path | None = None,
+) -> dict[str, str | int]:
+ """Render the per-user Windows Installed Apps registry values.
+
+ Pure and platform-neutral so quoting and metadata stay testable on every CI
+ runner. The writer below is the only Windows-specific part.
+ """
+
+ script = _windows_uninstall_script(install_dir)
+ base = [
+ _windows_powershell(),
+ "-NoProfile",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-File",
+ str(script),
+ ]
+ values: dict[str, str | int] = {
+ "DisplayName": "Personal Jarvis",
+ "DisplayVersion": version or _version(),
+ "Publisher": "Personal Jarvis contributors",
+ "InstallLocation": str(install_dir),
+ "UninstallString": subprocess.list2cmdline(base),
+ "QuietUninstallString": subprocess.list2cmdline([*base, "--yes"]),
+ "URLInfoAbout": "https://github.com/PersonalJarvis/PersonalJarvis",
+ "NoModify": 1,
+ "NoRepair": 1,
+ }
+ if icon_path is not None and icon_path.is_file():
+ values["DisplayIcon"] = f"{icon_path},0"
+ return values
+
+
+def register_windows_installed_app(
+ install_dir: Path,
+ *,
+ registry_subkey: str = WINDOWS_UNINSTALL_SUBKEY,
+ platform: str | None = None,
+) -> bool:
+ """Create or refresh the per-user Windows Installed Apps entry."""
+
+ if _platform(platform) != "windows":
+ return False
+ script = _windows_uninstall_script(install_dir)
+ if not script.is_file():
+ log.warning("Windows app registration skipped: uninstall script is missing")
+ return False
+ try:
+ import winreg
+
+ from jarvis.ui.icon_utils import project_icon_path
+
+ values = windows_uninstall_values(
+ install_dir,
+ icon_path=project_icon_path(),
+ )
+ with winreg.CreateKeyEx(
+ winreg.HKEY_CURRENT_USER,
+ registry_subkey,
+ 0,
+ winreg.KEY_SET_VALUE,
+ ) as key:
+ for name, value in values.items():
+ kind = winreg.REG_DWORD if isinstance(value, int) else winreg.REG_SZ
+ winreg.SetValueEx(key, name, 0, kind, value)
+ return True
+ except Exception as exc: # noqa: BLE001 - shell registration is best-effort
+ log.warning("Windows Installed Apps registration failed: %s", exc)
+ return False
+
+
+def _delete_windows_registry_key(subkey: str) -> bool:
+ try:
+ import winreg
+
+ try:
+ winreg.DeleteKey(winreg.HKEY_CURRENT_USER, subkey)
+ except FileNotFoundError:
+ pass
+ return True
+ except Exception as exc: # noqa: BLE001 - uninstall continues with other artifacts
+ log.warning("Windows registry cleanup failed for %s: %s", subkey, exc)
+ return False
+
+
+def _windows_programs_dir() -> Path | None:
+ appdata = os.environ.get("APPDATA")
+ if not appdata:
+ return None
+ return Path(appdata) / "Microsoft" / "Windows" / "Start Menu" / "Programs"
+
+
+def _remove_windows_desktop_integration(
+ *,
+ programs_dir: Path | None = None,
+ registry_subkey: str = WINDOWS_UNINSTALL_SUBKEY,
+ aumid: str = WINDOWS_APP_USER_MODEL_ID,
+) -> tuple[bool, tuple[str, ...]]:
+ warnings: list[str] = []
+ programs = programs_dir or _windows_programs_dir()
+ if programs is not None:
+ shortcut = programs / "Personal Jarvis.lnk"
+ try:
+ shortcut.unlink(missing_ok=True)
+ except OSError as exc:
+ warnings.append(f"could not remove the Start-menu launcher: {exc}")
+ if not _delete_windows_registry_key(registry_subkey):
+ warnings.append("could not remove the Installed Apps registry entry")
+ if not _delete_windows_registry_key(_windows_aumid_subkey(aumid)):
+ warnings.append("could not remove the Windows app identity")
+ return not warnings, tuple(warnings)
+
+
+def _linux_applications_dir() -> Path:
+ xdg = os.environ.get("XDG_DATA_HOME", "").strip()
+ base = Path(xdg) if xdg else Path.home() / ".local" / "share"
+ return base / "applications"
+
+
+def _remove_linux_desktop_entry(applications_dir: Path | None = None) -> bool:
+ entry = (applications_dir or _linux_applications_dir()) / "personal-jarvis.desktop"
+ try:
+ entry.unlink(missing_ok=True)
+ return True
+ except OSError as exc:
+ log.warning("Linux application-menu cleanup failed: %s", exc)
+ return False
+
+
+def _linux_gui_available(applications_dir: Path | None) -> bool:
+ if applications_dir is not None:
+ return True
+ return bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"))
+
+
+def ensure_desktop_integration(
+ *,
+ install_dir: Path | None = None,
+ platform: str | None = None,
+ require_managed: bool = True,
+ windows_programs_dir: Path | None = None,
+ windows_registry_subkey: str = WINDOWS_UNINSTALL_SUBKEY,
+ windows_aumid: str = WINDOWS_APP_USER_MODEL_ID,
+ macos_applications_dir: Path | None = None,
+ linux_applications_dir: Path | None = None,
+) -> DesktopIntegrationReport:
+ """Install or repair the current platform's desktop-shell artifacts."""
+
+ root = (install_dir or _install_root()).resolve()
+ plat = _platform(platform)
+ managed = is_managed_install(root)
+ if require_managed and not managed:
+ return DesktopIntegrationReport(
+ platform=plat,
+ managed=False,
+ attempted=False,
+ ok=True,
+ skipped_reason="not an installer-managed checkout",
+ )
+
+ artifacts: list[str] = []
+ warnings: list[str] = []
+ if plat == "windows":
+ try:
+ from jarvis.ui.icon_utils import (
+ ensure_start_menu_shortcut,
+ project_icon_path,
+ register_windows_app_user_model_id,
+ )
+
+ icon = project_icon_path()
+ if ensure_start_menu_shortcut(
+ aumid=windows_aumid,
+ icon_path=icon if icon.is_file() else None,
+ programs_dir=windows_programs_dir,
+ ):
+ artifacts.append("start_menu_launcher")
+ else:
+ warnings.append("could not create the Start-menu launcher")
+ if register_windows_app_user_model_id(
+ windows_aumid,
+ icon_path=icon if icon.is_file() else None,
+ ):
+ artifacts.append("windows_app_identity")
+ else:
+ warnings.append("could not register the Windows app identity")
+ except Exception as exc: # noqa: BLE001
+ warnings.append(f"could not load Windows shell integration: {exc}")
+ if register_windows_installed_app(
+ root,
+ registry_subkey=windows_registry_subkey,
+ platform="win32",
+ ):
+ artifacts.append("installed_apps_registration")
+ else:
+ 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
+
+ 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")
+ except Exception as exc: # noqa: BLE001
+ warnings.append(f"could not create the macOS application bundle: {exc}")
+ elif plat == "linux":
+ if not _linux_gui_available(linux_applications_dir):
+ return DesktopIntegrationReport(
+ platform=plat,
+ managed=managed,
+ attempted=False,
+ ok=True,
+ skipped_reason="headless Linux session",
+ )
+ try:
+ from jarvis.ui.icon_utils import ensure_linux_desktop_entry
+
+ if ensure_linux_desktop_entry(applications_dir=linux_applications_dir):
+ artifacts.append("applications_menu_entry")
+ else:
+ warnings.append("could not create the Linux application-menu entry")
+ except Exception as exc: # noqa: BLE001
+ warnings.append(f"could not create the Linux application-menu entry: {exc}")
+ else:
+ return DesktopIntegrationReport(
+ platform=plat,
+ managed=managed,
+ attempted=False,
+ ok=True,
+ skipped_reason="unsupported desktop platform",
+ )
+
+ for warning in warnings:
+ log.warning("Desktop integration: %s", warning)
+ return DesktopIntegrationReport(
+ platform=plat,
+ managed=managed,
+ attempted=True,
+ ok=not warnings,
+ artifacts=tuple(artifacts),
+ warnings=tuple(warnings),
+ )
+
+
+def remove_desktop_integration(
+ *,
+ platform: str | None = None,
+ windows_programs_dir: Path | None = None,
+ windows_registry_subkey: str = WINDOWS_UNINSTALL_SUBKEY,
+ windows_aumid: str = WINDOWS_APP_USER_MODEL_ID,
+ macos_applications_dir: Path | None = None,
+ linux_applications_dir: Path | None = None,
+) -> DesktopIntegrationReport:
+ """Remove the current platform's external desktop-shell artifacts."""
+
+ plat = _platform(platform)
+ warnings: list[str] = []
+ artifacts: list[str] = []
+ if plat == "windows":
+ ok, found = _remove_windows_desktop_integration(
+ programs_dir=windows_programs_dir,
+ registry_subkey=windows_registry_subkey,
+ aumid=windows_aumid,
+ )
+ artifacts.extend(
+ (
+ "start_menu_launcher",
+ "installed_apps_registration",
+ "windows_app_identity",
+ )
+ )
+ if not ok:
+ warnings.extend(found)
+ elif plat == "macos":
+ try:
+ from jarvis.setup.macos_app_bundle import remove_macos_app_bundle
+
+ if remove_macos_app_bundle(applications_dir=macos_applications_dir):
+ artifacts.append("applications_bundle")
+ else:
+ warnings.append("could not remove the macOS application bundle")
+ except Exception as exc: # noqa: BLE001
+ warnings.append(f"could not remove the macOS application bundle: {exc}")
+ elif plat == "linux":
+ if _remove_linux_desktop_entry(linux_applications_dir):
+ artifacts.append("applications_menu_entry")
+ else:
+ warnings.append("could not remove the Linux application-menu entry")
+ else:
+ return DesktopIntegrationReport(
+ platform=plat,
+ managed=False,
+ attempted=False,
+ ok=True,
+ skipped_reason="unsupported desktop platform",
+ )
+ return DesktopIntegrationReport(
+ platform=plat,
+ managed=False,
+ attempted=True,
+ ok=not warnings,
+ artifacts=tuple(artifacts),
+ warnings=tuple(warnings),
+ )
+
+
+def main(argv: list[str] | None = None) -> int:
+ 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")
+ parser.add_argument("--allow-unmanaged", action="store_true")
+ parser.add_argument("--json", action="store_true")
+ args = parser.parse_args(argv)
+
+ report = (
+ remove_desktop_integration()
+ if args.remove
+ else ensure_desktop_integration(
+ install_dir=args.install_dir,
+ require_managed=not args.allow_unmanaged,
+ )
+ )
+ if args.json:
+ print(json.dumps(report.to_dict(), sort_keys=True))
+ elif report.ok:
+ print("Personal Jarvis desktop registration is ready.")
+ else:
+ print("Personal Jarvis desktop registration is incomplete.", file=sys.stderr)
+ for warning in report.warnings:
+ print(f"- {warning}", file=sys.stderr)
+ return 0 if report.ok else 1
+
+
+if __name__ == "__main__": # pragma: no cover
+ raise SystemExit(main())
+
+
+__all__ = [
+ "DesktopIntegrationReport",
+ "MANAGED_MARKER",
+ "WINDOWS_APP_USER_MODEL_ID",
+ "WINDOWS_UNINSTALL_SUBKEY",
+ "ensure_desktop_integration",
+ "is_managed_install",
+ "register_windows_installed_app",
+ "remove_desktop_integration",
+ "windows_uninstall_values",
+]
diff --git a/jarvis/setup/uninstall.py b/jarvis/setup/uninstall.py
index 0f84490e36..58f02ef436 100644
--- a/jarvis/setup/uninstall.py
+++ b/jarvis/setup/uninstall.py
@@ -1,18 +1,20 @@
"""Personal Jarvis uninstaller — remove a local install cleanly for a re-test.
-A download leaves THREE things on a machine, and a plain folder-delete only
+A download leaves FOUR things on a machine, and a plain folder-delete only
gets the first:
1. **The install folder** (``~/.personal-jarvis``) — code, the Python venv,
``jarvis.toml``, ``data/`` and the ``.setup-complete`` marker.
-2. **A login-autostart entry** next to it (a Windows logon task / a macOS
+2. **Desktop-shell registration** (Windows Start menu + Installed Apps, a
+ macOS ``.app`` bundle, or a Linux application-menu entry).
+3. **A login-autostart entry** next to it (a Windows logon task / a macOS
``LaunchAgent`` / a Linux XDG ``.desktop``) — survives a folder delete and
then points at nothing.
-3. **API keys in the OS keyring** (service ``personal-jarvis`` — Windows
+4. **API keys in the OS keyring** (service ``personal-jarvis`` — Windows
Credential Manager / macOS Keychain / Linux Secret Service) — survive a
folder delete, so a fresh install would show them as "already set".
-This module removes all three (with an explicit confirmation, a ``--dry-run``
+This module removes all four (with an explicit confirmation, a ``--dry-run``
preview and per-item ``--keep-*`` opt-outs) so "download → test → wipe → re-test"
is one command. It is intentionally cross-platform and has **no** heavy imports,
so it runs on a headless VPS as happily as on a laptop.
@@ -171,6 +173,9 @@ def _print_plan(plan: UninstallPlan, *, keep_keys: bool, keep_folder: bool) -> N
)
else:
lines.append("[brand]•[/] Login autostart: [muted]nothing to remove[/]")
+ lines.append(
+ "[brand]•[/] Remove the operating-system app launcher and registration"
+ )
if not keep_keys:
if plan.keyring_keys:
lines.append(
@@ -192,6 +197,26 @@ def _confirm() -> bool:
# ---------------------------------------------------------------- removal steps
+def _remove_desktop_registration() -> None:
+ try:
+ from jarvis.setup.desktop_integration import remove_desktop_integration
+
+ report = remove_desktop_integration()
+ if report.ok:
+ _console.print(" [ok]→ desktop app registration removed.[/]")
+ else:
+ detail = "; ".join(report.warnings)
+ _console.print(
+ f" [bad]⚠ desktop app registration cleanup was incomplete: "
+ f"{escape(detail)}[/]"
+ )
+ except Exception as exc: # noqa: BLE001 - never abort uninstall on shell cleanup
+ _console.print(
+ f" [bad]⚠ could not remove desktop app registration: "
+ f"{escape(str(exc))}[/]"
+ )
+
+
def _remove_autostart() -> None:
try:
from jarvis.autostart import make_autostart_manager
@@ -207,14 +232,6 @@ def _remove_autostart() -> None:
_console.print(" [muted]→ login autostart not supported here — skipped.[/]")
except Exception as exc: # noqa: BLE001 — never abort the uninstall on this
_console.print(f" [bad]⚠ could not remove the autostart entry: {escape(str(exc))}[/]")
- if sys.platform == "darwin":
- try:
- from jarvis.setup.macos_app_bundle import remove_macos_app_bundle
-
- if remove_macos_app_bundle():
- _console.print(" [ok]→ ~/Applications app bundle removed.[/]")
- except Exception as exc: # noqa: BLE001 — never abort the uninstall on this
- _console.print(f" [bad]⚠ could not remove the app bundle: {escape(str(exc))}[/]")
def _remove_keys(keys: list[str]) -> int:
@@ -348,9 +365,10 @@ def run_uninstall(
_console.print()
_console.print(" [brand.bold]Removing…[/]")
- # Order matters: pull the login entry and the keys FIRST (they live outside
- # the folder), then remove the folder last — on Windows the folder step may
+ # Order matters: remove every external registration and the keys FIRST, then
+ # remove the folder last — on Windows the folder step may
# end this process's ability to do further work if it self-deletes.
+ _remove_desktop_registration()
_remove_autostart()
if not keep_keys:
_remove_keys(plan.keyring_keys)
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 4e13f68273..79461c6262 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -3047,6 +3047,40 @@ class DesktopApp:
except Exception: # noqa: BLE001
pass
+ # Repair shell registration only after the first webview paint. This is
+ # deliberately off the boot-critical path (AP-26), and it is the bridge
+ # that upgrades old installations: the v1.0.7 updater itself did not run
+ # installer finalizers, but its restart loads this new boot hook.
+ self._start_desktop_integration_repair()
+
+ def _start_desktop_integration_repair(self) -> None:
+ """Repair the managed install's launcher/app bundle in the background."""
+
+ if getattr(self, "_desktop_integration_repair_started", False):
+ return
+ self._desktop_integration_repair_started = True
+
+ def _repair() -> None:
+ from loguru import logger as _log
+
+ try:
+ from jarvis.setup.desktop_integration import ensure_desktop_integration
+
+ report = ensure_desktop_integration()
+ if report.attempted and not report.ok:
+ _log.warning(
+ "Desktop registration repair incomplete: {}",
+ "; ".join(report.warnings),
+ )
+ except Exception: # noqa: BLE001 - registration never blocks the app
+ _log.opt(exception=True).debug("Desktop registration repair failed")
+
+ threading.Thread(
+ target=_repair,
+ name="jarvis-desktop-registration",
+ daemon=True,
+ ).start()
+
# ---- Backend-ready check --------------------------------------------------
def _wait_for_backend(self, timeout_s: float = 45.0) -> bool:
diff --git a/jarvis/ui/icon_utils.py b/jarvis/ui/icon_utils.py
index f1aba4b1a7..b9e5a56004 100644
--- a/jarvis/ui/icon_utils.py
+++ b/jarvis/ui/icon_utils.py
@@ -487,16 +487,26 @@ def _default_start_menu_programs_dir() -> Path | None:
return Path(appdata) / "Microsoft" / "Windows" / "Start Menu" / "Programs"
-def _shortcut_paths_are_live(lnk: Path) -> bool:
- """True only if the ``.lnk``'s icon file AND target file both exist on disk.
+def _shortcut_matches_install(
+ lnk: Path,
+ *,
+ expected_target: Path,
+ expected_icon: Path,
+ expected_arguments: str,
+) -> bool:
+ """True only when a ``.lnk`` points at this exact live installation.
The taskbar renders an AUMID-grouped button from its Start-Menu shortcut's
icon; a dangling ``IconLocation`` (install moved/renamed) silently degrades
to the target's icon (``pythonw.exe`` -> Python logo). An empty
``IconLocation`` means "use the target's icon", which is exactly the Python
- fallback, so that counts as NOT live. Best-effort: any read failure returns
- ``False`` so the caller rewrites rather than trusting a shortcut it cannot
- verify. Windows-only helper (``WScript.Shell`` is a shell COM object).
+ fallback, so that counts as NOT live.
+
+ Mere existence is not enough: an old Python installation can remain on disk
+ after Jarvis rebuilt its venv. The old check accepted that stale executable
+ forever, leaving Windows search with a launcher for the previous environment.
+ Compare target, icon, and arguments to the values this process would write.
+ Best-effort: any read failure returns ``False`` so the caller repairs it.
"""
if sys.platform != "win32":
return False
@@ -509,11 +519,23 @@ def _shortcut_paths_are_live(lnk: Path) -> bool:
sc = Dispatch("WScript.Shell").CreateShortcut(str(lnk))
# IconLocation is "<path>,<index>"; an empty path == inherit the target
# icon == the pythonw.exe fallback, so treat it as not-live.
- icon_path = (sc.IconLocation or "").rsplit(",", 1)[0].strip().strip('"')
- target = (sc.TargetPath or "").strip().strip('"')
- icon_ok = bool(icon_path) and Path(icon_path).is_file()
- target_ok = bool(target) and Path(target).is_file()
- return icon_ok and target_ok
+ icon_raw = (sc.IconLocation or "").rsplit(",", 1)[0].strip().strip('"')
+ target_raw = (sc.TargetPath or "").strip().strip('"')
+
+ def _same_path(actual: str, expected: Path) -> bool:
+ if not actual:
+ return False
+ return os.path.normcase(os.path.abspath(actual)) == os.path.normcase(
+ os.path.abspath(expected)
+ )
+
+ return (
+ Path(icon_raw).is_file()
+ and Path(target_raw).is_file()
+ and _same_path(icon_raw, expected_icon)
+ and _same_path(target_raw, expected_target)
+ and (sc.Arguments or "").strip() == expected_arguments
+ )
except Exception as exc: # noqa: BLE001
logger.debug("could not read shortcut target/icon, treating as stale: {}", exc)
return False
@@ -540,9 +562,10 @@ def ensure_start_menu_shortcut(
a *fresh* launch picks it up (an already-grouped button is not retroactively
renamed).
- Idempotent (an existing shortcut already carrying ``aumid`` is left alone),
- Windows-only, best-effort — it never raises and never blocks boot. Returns
- ``True`` only when a matching shortcut is present afterwards.
+ Idempotent (an existing shortcut carrying ``aumid`` and pointing at this
+ exact interpreter is left alone), Windows-only, best-effort - it never
+ raises and never blocks boot. Returns ``True`` only when a matching shortcut
+ is present afterwards.
"""
if sys.platform != "win32":
return False
@@ -583,7 +606,12 @@ def ensure_start_menu_shortcut(
str(lnk), None, 0, iid # GPS_DEFAULT
)
existing = ro_store.GetValue(pscon.PKEY_AppUserModel_ID).GetValue()
- if existing == aumid and _shortcut_paths_are_live(lnk):
+ if existing == aumid and _shortcut_matches_install(
+ lnk,
+ expected_target=pythonw,
+ expected_icon=ico,
+ expected_arguments=f"-m {_LAUNCHER_MODULE}",
+ ):
return True
logger.debug("stale/broken Start-Menu shortcut, rewriting: {}", lnk)
except Exception as exc: # noqa: BLE001
diff --git a/jarvis/ui/web/frontend/src/__tests__/topbarUpdateButton.test.tsx b/jarvis/ui/web/frontend/src/__tests__/topbarUpdateButton.test.tsx
index ec7ba46b9c..4583eae99a 100644
--- a/jarvis/ui/web/frontend/src/__tests__/topbarUpdateButton.test.tsx
+++ b/jarvis/ui/web/frontend/src/__tests__/topbarUpdateButton.test.tsx
@@ -3,7 +3,7 @@
* install with an available update, shows the new version, and stays hidden on
* an unmanaged checkout (the dev-tree safety guard surfaced in the UI).
*/
-import { cleanup, render, screen, waitFor } from "@testing-library/react";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { TopBar } from "@/components/layout/TopBar";
@@ -23,7 +23,7 @@ function mockUpdateStatus(body: Record<string, unknown>): void {
describe("TopBar update button", () => {
beforeEach(() => {
- useEventStore.setState({ assistantName: "Assistant" });
+ useEventStore.setState({ assistantName: "Assistant", toasts: [] });
});
afterEach(() => {
cleanup();
@@ -72,4 +72,53 @@ describe("TopBar update button", () => {
await waitFor(() => expect(screen.getByText("Restart")).toBeTruthy());
expect(screen.queryByText("Update available")).toBeNull();
});
+
+ it("warns when the update cannot fully repair desktop registration", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) => {
+ if (url.startsWith("/api/update/status")) {
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ managed: true,
+ current: "1.0.6",
+ latest: "1.0.7",
+ update_available: true,
+ notes: null,
+ }),
+ };
+ }
+ if (url === "/api/update/apply") {
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ ok: true,
+ desktop_integration_warning: "launcher repair failed",
+ }),
+ };
+ }
+ return { ok: true, status: 200, json: async () => ({ ok: true }) };
+ }),
+ );
+
+ render(<TopBar />);
+ fireEvent.click(
+ await screen.findByRole("button", { name: /update available/i }),
+ );
+
+ await waitFor(() => {
+ expect(
+ useEventStore
+ .getState()
+ .toasts.some(
+ (toast) =>
+ toast.kind === "warning" &&
+ toast.message.includes("operating system"),
+ ),
+ ).toBe(true);
+ });
+ });
});
diff --git a/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx b/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx
index df30ee2ed4..02494d1fde 100644
--- a/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx
@@ -191,6 +191,12 @@ function UpdateButton() {
if ((applyBody as { deps_warning?: string | null }).deps_warning) {
pushToast("warning", t("topbar.update_deps_warning"));
}
+ if (
+ (applyBody as { desktop_integration_warning?: string | null })
+ .desktop_integration_warning
+ ) {
+ pushToast("warning", t("topbar.update_desktop_warning"));
+ }
// 2. Restart to load it — reuse the existing route + its mission guard.
const url = force
? "/api/settings/restart-app?force=true"
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 03ac3f51cb..7172d9de4d 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -25,7 +25,8 @@
"updating": "{name} wird aktualisiert…",
"update_failed": "Update fehlgeschlagen",
"update_hint": "Neue Version herunterladen und installieren",
- "update_deps_warning": "Aktualisiert — einige Komponenten brauchen evtl. eine manuelle Neuinstallation"
+ "update_deps_warning": "Aktualisiert — einige Komponenten brauchen evtl. eine manuelle Neuinstallation",
+ "update_desktop_warning": "Aktualisiert — das Betriebssystem konnte den App-Starter nicht vollständig reparieren"
},
"nav": {
"chats": "Chats",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 7fed21d400..3defc808df 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -25,7 +25,8 @@
"updating": "Updating {name}…",
"update_failed": "Update failed",
"update_hint": "Download and install the new version",
- "update_deps_warning": "Updated — some components may need a manual reinstall"
+ "update_deps_warning": "Updated — some components may need a manual reinstall",
+ "update_desktop_warning": "Updated — the operating system could not fully repair the app launcher"
},
"nav": {
"chats": "Chats",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index ae0f785ec6..1348c42e43 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -25,7 +25,8 @@
"updating": "Actualizando {name}…",
"update_failed": "Error al actualizar",
"update_hint": "Descargar e instalar la nueva versión",
- "update_deps_warning": "Actualizado — algunos componentes pueden requerir reinstalación manual"
+ "update_deps_warning": "Actualizado — algunos componentes pueden requerir reinstalación manual",
+ "update_desktop_warning": "Actualizado — el sistema operativo no pudo reparar por completo el iniciador de la aplicación"
},
"nav": {
"chats": "Chats",
diff --git a/jarvis/ui/web/update_routes.py b/jarvis/ui/web/update_routes.py
index b3bddcda1f..40a6d92710 100644
--- a/jarvis/ui/web/update_routes.py
+++ b/jarvis/ui/web/update_routes.py
@@ -11,9 +11,10 @@ Now" button so the user never has to re-run the installer from a terminal:
update" rather than erroring, so a flaky connection never breaks the UI.
* ``POST /api/update/apply`` — pulls the new code (the same ``git fetch`` +
``git reset --hard origin/main`` the installer uses), refreshes dependencies
- only if the lockfile changed, and reports ``restart_required``. It does NOT
- restart — the caller then hits the existing ``POST /api/settings/restart-app``
- which already owns the mission-guard + cross-platform relauncher.
+ only if the lockfile changed, and repairs the platform's desktop registration
+ before reporting ``restart_required``. It does NOT restart — the caller then
+ hits the existing ``POST /api/settings/restart-app`` which already owns the
+ mission guard + cross-platform relauncher.
Safety-critical guard (the single most important thing here):
``git reset --hard`` destroys uncommitted local changes. That is fine for an
@@ -38,6 +39,7 @@ from __future__ import annotations
import asyncio
import hashlib
+import json
import logging
import re
import sys
@@ -340,6 +342,41 @@ async def _refresh_dependencies(root: Path) -> tuple[bool, str]:
return True, ""
+async def _refresh_desktop_integration(root: Path) -> tuple[bool, str]:
+ """Run the freshly pulled desktop-registration code in the install venv.
+
+ The updater process still has the old modules in memory after ``git reset``.
+ A subprocess is therefore intentional: it imports the new checkout and can
+ create a Windows Installed Apps entry, a macOS bundle, or a Linux desktop
+ entry before the current process exits. Headless Linux reports a clean skip.
+ """
+
+ py = _venv_python(root)
+ rc, out, err = await _run(
+ [
+ str(py),
+ "-m",
+ "jarvis.setup.desktop_integration",
+ "--install-dir",
+ str(root),
+ "--json",
+ ],
+ cwd=root,
+ timeout_s=120.0,
+ )
+ if rc != 0:
+ return False, (err or out or "desktop registration failed")[-400:]
+ try:
+ payload = json.loads(out.splitlines()[-1])
+ except (IndexError, json.JSONDecodeError, TypeError):
+ return False, "desktop registration returned an unreadable result"
+ if not payload.get("ok"):
+ warnings = payload.get("warnings") or []
+ detail = "; ".join(str(item) for item in warnings)
+ return False, (detail or "desktop registration is incomplete")[-400:]
+ return True, ""
+
+
# --------------------------------------------------------------------------- #
# Routes
# --------------------------------------------------------------------------- #
@@ -403,7 +440,8 @@ async def update_status(force: bool = False) -> dict[str, object]:
async def update_apply() -> dict[str, object]:
"""Pull the latest code for a managed install. Does NOT restart.
- Returns ``{ok, restart_required, version, deps_refreshed, deps_warning}``.
+ Returns update, dependency, and desktop-registration status plus
+ ``restart_required``.
The caller applies the update by then calling
``POST /api/settings/restart-app``.
"""
@@ -442,6 +480,10 @@ async def update_apply() -> dict[str, object]:
if not ok:
deps_warning = msg
+ desktop_integration_ok, desktop_integration_warning = (
+ await _refresh_desktop_integration(root)
+ )
+
new_version = _version_on_disk(root) or _running_version()
return {
"ok": True,
@@ -449,4 +491,6 @@ async def update_apply() -> dict[str, object]:
"version": new_version,
"deps_refreshed": deps_refreshed,
"deps_warning": deps_warning,
+ "desktop_integration_ok": desktop_integration_ok,
+ "desktop_integration_warning": desktop_integration_warning or None,
}
diff --git a/scripts/ci/docs_privacy_scan.py b/scripts/ci/docs_privacy_scan.py
index 445939d347..6dad7484e3 100644
--- a/scripts/ci/docs_privacy_scan.py
+++ b/scripts/ci/docs_privacy_scan.py
@@ -47,7 +47,20 @@ MANIFEST = REPO_ROOT / "scripts" / "ci" / "privacy_gate" / "references" / "pii-s
EMAIL_PLACEHOLDER = "[email protected]"
# Text-only file suffixes we look inside. Binary/image docs are skipped.
-TEXT_SUFFIXES = {".md", ".markdown", ".html", ".htm", ".txt", ".py", ".toml", ".json", ".yml", ".yaml", ".tsv", ".csv"}
+TEXT_SUFFIXES = {
+ ".md",
+ ".markdown",
+ ".html",
+ ".htm",
+ ".txt",
+ ".py",
+ ".toml",
+ ".json",
+ ".yml",
+ ".yaml",
+ ".tsv",
+ ".csv",
+}
def load_manifest() -> tuple[list[tuple[re.Pattern[str], str, str]], list[re.Pattern[str]]]:
@@ -137,7 +150,10 @@ def main() -> int:
rules, emails = load_manifest()
if args.paths:
- targets = [(Path(p) if Path(p).is_absolute() else (REPO_ROOT / p)).resolve() for p in args.paths]
+ targets = [
+ (Path(p) if Path(p).is_absolute() else (REPO_ROOT / p)).resolve()
+ for p in args.paths
+ ]
else:
targets = tracked_docs()
diff --git a/tests/integration/test_update_apply_real_git.py b/tests/integration/test_update_apply_real_git.py
index 36cb4ec15e..8889315a84 100644
--- a/tests/integration/test_update_apply_real_git.py
+++ b/tests/integration/test_update_apply_real_git.py
@@ -79,10 +79,16 @@ def test_real_apply_moves_head_to_new_tip(tmp_path: Path, monkeypatch: pytest.Mo
assert '9.9.9' in (install / "jarvis" / "__init__.py").read_text(encoding="utf-8")
monkeypatch.setattr(u, "_repo_root", lambda: install)
+
+ async def _desktop_ok(_root: Path) -> tuple[bool, None]:
+ return True, None
+
+ monkeypatch.setattr(u, "_refresh_desktop_integration", _desktop_ok)
result = asyncio.run(u.update_apply())
assert result["ok"] is True
assert result["restart_required"] is True
assert result["version"] == "9.9.10"
+ assert result["desktop_integration_ok"] is True
# The real reset --hard moved the working tree to B.
assert '9.9.10' in (install / "jarvis" / "__init__.py").read_text(encoding="utf-8")
diff --git a/tests/unit/install/test_installer_flow.py b/tests/unit/install/test_installer_flow.py
index c11ea1505a..230dc4d04e 100644
--- a/tests/unit/install/test_installer_flow.py
+++ b/tests/unit/install/test_installer_flow.py
@@ -46,7 +46,9 @@ def test_installer_prompts_only_inside_missing_prerequisite_flow() -> None:
sh_end = sh.index("# --- prerequisite-bootstrap end")
# Design amendment 2026-07-14: ONE more allowed prompt — the welcome gate
# ("Would you like to install?") BEFORE phase 1. Nothing else may ask.
- wg_begin = sh.index("# -------------------------------------------------------------- welcome gate")
+ wg_begin = sh.index(
+ "# -------------------------------------------------------------- welcome gate"
+ )
wg_end = sh.index("# -------------------------------------------------------------- preflight")
sh_outside = sh[:wg_begin] + sh[wg_end:sh_begin] + sh[sh_end:]
assert "read -r" not in sh_outside
@@ -99,6 +101,22 @@ def test_headless_pip_plan_stays_base_floor(capsys) -> None:
assert ".[desktop]" not in out
+def test_linux_gui_gets_full_profile_and_app_menu_registration(
+ monkeypatch, capsys
+) -> None:
+ """A Linux desktop is a first-class app install, not the headless floor."""
+ monkeypatch.setattr(installer.sys, "platform", "linux")
+ monkeypatch.setenv("DISPLAY", ":99")
+
+ rc = installer.main(["--dry-run", "--no-launch"])
+ out = capsys.readouterr().out
+
+ assert rc == 0
+ assert ".[full]" in out
+ assert "repair desktop-shell registration" in out
+ assert 'app menu -> "Personal Jarvis"' in out
+
+
def test_update_summary_promises_no_reonboarding(monkeypatch, capsys, tmp_path) -> None:
(tmp_path / ".jarvis-managed-install").write_text("{}", encoding="utf-8")
(tmp_path / "pyproject.toml").write_text("[project]\n", encoding="utf-8")
diff --git a/tests/unit/setup/test_desktop_integration.py b/tests/unit/setup/test_desktop_integration.py
new file mode 100644
index 0000000000..06fd4da967
--- /dev/null
+++ b/tests/unit/setup/test_desktop_integration.py
@@ -0,0 +1,175 @@
+"""Desktop-shell registration lifecycle on Windows, macOS, and Linux."""
+
+from __future__ import annotations
+
+import inspect
+import sys
+from pathlib import Path
+
+import pytest
+
+from jarvis.setup import desktop_integration as di
+
+
+def _managed_root(tmp_path: Path) -> Path:
+ root = tmp_path / "install with spaces"
+ (root / "install").mkdir(parents=True)
+ (root / di.MANAGED_MARKER).write_text("{}\n", encoding="utf-8")
+ (root / "install" / "uninstall.ps1").write_text("# test\n", encoding="utf-8")
+ return root
+
+
+def test_windows_uninstall_values_are_per_user_app_metadata(tmp_path: Path) -> None:
+ root = _managed_root(tmp_path)
+ icon = tmp_path / "app.ico"
+ icon.write_bytes(b"ico")
+
+ values = di.windows_uninstall_values(root, version="9.8.7", icon_path=icon)
+
+ assert values["DisplayName"] == "Personal Jarvis"
+ assert values["DisplayVersion"] == "9.8.7"
+ assert values["InstallLocation"] == str(root)
+ assert str(root / "install" / "uninstall.ps1") in str(values["UninstallString"])
+ assert "--yes" in str(values["QuietUninstallString"])
+ assert values["DisplayIcon"] == f"{icon},0"
+ assert values["NoModify"] == 1
+ assert values["NoRepair"] == 1
+
+
+def test_unmanaged_checkout_is_never_registered(tmp_path: Path) -> None:
+ apps = tmp_path / "applications"
+
+ report = di.ensure_desktop_integration(
+ install_dir=tmp_path,
+ platform="linux",
+ linux_applications_dir=apps,
+ )
+
+ assert report.ok is True
+ assert report.managed is False
+ assert report.attempted is False
+ assert report.skipped_reason == "not an installer-managed checkout"
+ assert not apps.exists()
+
+
+def test_linux_managed_install_gets_searchable_application_entry(tmp_path: Path) -> None:
+ root = _managed_root(tmp_path)
+ apps = tmp_path / "applications"
+
+ report = di.ensure_desktop_integration(
+ install_dir=root,
+ platform="linux",
+ linux_applications_dir=apps,
+ )
+
+ assert report.ok is True
+ assert report.artifacts == ("applications_menu_entry",)
+ entry = apps / "personal-jarvis.desktop"
+ text = entry.read_text(encoding="utf-8")
+ assert "Name=Personal Jarvis" in text
+ assert "StartupWMClass=personal-jarvis" in text
+
+
+def test_headless_linux_does_not_create_desktop_artifacts(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ root = _managed_root(tmp_path)
+ monkeypatch.delenv("DISPLAY", raising=False)
+ monkeypatch.delenv("WAYLAND_DISPLAY", raising=False)
+
+ report = di.ensure_desktop_integration(install_dir=root, platform="linux")
+
+ assert report.ok is True
+ assert report.attempted is False
+ assert report.skipped_reason == "headless Linux session"
+
+
+def test_macos_managed_install_gets_real_app_bundle(tmp_path: Path) -> 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"
+
+ report = di.ensure_desktop_integration(
+ install_dir=root,
+ platform="darwin",
+ macos_applications_dir=apps,
+ )
+
+ assert report.ok is True
+ assert report.artifacts == ("applications_bundle",)
+ assert (apps / "Personal Jarvis.app" / "Contents" / "Info.plist").is_file()
+
+
+def test_linux_uninstall_removes_application_entry(tmp_path: Path) -> None:
+ apps = tmp_path / "applications"
+ apps.mkdir()
+ entry = apps / "personal-jarvis.desktop"
+ entry.write_text("[Desktop Entry]\n", encoding="utf-8")
+
+ report = di.remove_desktop_integration(
+ platform="linux", linux_applications_dir=apps
+ )
+
+ assert report.ok is True
+ assert not entry.exists()
+
+
[email protected](sys.platform != "win32", reason="Windows registry and links only")
+def test_windows_managed_install_is_visible_to_start_and_installed_apps(
+ tmp_path: Path,
+) -> None:
+ import winreg
+
+ root = _managed_root(tmp_path)
+ programs = tmp_path / "Programs"
+ subkey = rf"Software\PersonalJarvisTests\DesktopIntegration\{tmp_path.name}"
+ aumid = f"PersonalJarvis.Test.DesktopIntegration.{tmp_path.name}"
+ aumid_subkey = rf"Software\Classes\AppUserModelId\{aumid}"
+ try:
+ report = di.ensure_desktop_integration(
+ install_dir=root,
+ platform="win32",
+ windows_programs_dir=programs,
+ windows_registry_subkey=subkey,
+ windows_aumid=aumid,
+ )
+
+ assert report.ok is True
+ assert set(report.artifacts) == {
+ "start_menu_launcher",
+ "installed_apps_registration",
+ "windows_app_identity",
+ }
+ assert (programs / "Personal Jarvis.lnk").is_file()
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, subkey) as key:
+ assert winreg.QueryValueEx(key, "DisplayName")[0] == "Personal Jarvis"
+ assert winreg.QueryValueEx(key, "InstallLocation")[0] == str(root)
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, aumid_subkey) as key:
+ assert winreg.QueryValueEx(key, "DisplayName")[0] == "Personal Jarvis"
+
+ removed = di.remove_desktop_integration(
+ platform="win32",
+ windows_programs_dir=programs,
+ windows_registry_subkey=subkey,
+ windows_aumid=aumid,
+ )
+ assert removed.ok is True
+ assert not (programs / "Personal Jarvis.lnk").exists()
+ with pytest.raises(FileNotFoundError):
+ winreg.OpenKey(winreg.HKEY_CURRENT_USER, subkey)
+ with pytest.raises(FileNotFoundError):
+ winreg.OpenKey(winreg.HKEY_CURRENT_USER, aumid_subkey)
+ finally:
+ for key in (subkey, aumid_subkey):
+ try:
+ winreg.DeleteKey(winreg.HKEY_CURRENT_USER, key)
+ except FileNotFoundError:
+ pass
+
+
+def test_desktop_boot_repairs_registration_after_first_paint() -> None:
+ import jarvis.ui.desktop_app as desktop_app
+
+ source = inspect.getsource(desktop_app.DesktopApp._inject_token)
+ assert "_start_desktop_integration_repair" in source
diff --git a/tests/unit/setup/test_uninstall.py b/tests/unit/setup/test_uninstall.py
index f6166ceec0..730d2e87f9 100644
--- a/tests/unit/setup/test_uninstall.py
+++ b/tests/unit/setup/test_uninstall.py
@@ -32,8 +32,13 @@ def _use_plan(monkeypatch: pytest.MonkeyPatch, plan: UninstallPlan) -> None:
def _record_steps(monkeypatch: pytest.MonkeyPatch) -> list[str]:
- """Replace the three removal helpers with recorders; return the shared log."""
+ """Replace the four removal helpers with recorders; return the shared log."""
called: list[str] = []
+ monkeypatch.setattr(
+ uninstall,
+ "_remove_desktop_registration",
+ lambda: called.append("desktop"),
+ )
monkeypatch.setattr(uninstall, "_remove_autostart", lambda: called.append("autostart"))
monkeypatch.setattr(uninstall, "_remove_keys", lambda k: called.append("keys"))
monkeypatch.setattr(uninstall, "_remove_folder", lambda p: called.append("folder"))
@@ -111,13 +116,18 @@ def test_confirm_requires_yes(monkeypatch: pytest.MonkeyPatch, answer: str, expe
# ---------------------------------------------------------------- happy path
-def test_assume_yes_runs_all_three_steps(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+def test_assume_yes_runs_all_four_steps(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
_use_plan(monkeypatch, _fake_plan(tmp_path, keys=["openai_api_key"]))
called = _record_steps(monkeypatch)
rc = uninstall.run_uninstall(assume_yes=True)
assert rc == 0
- assert called == ["autostart", "keys", "folder"] # order: outside-the-folder first
+ assert called == [
+ "desktop",
+ "autostart",
+ "keys",
+ "folder",
+ ] # order: outside-the-folder first
def test_keep_keys_skips_key_removal(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
@@ -138,6 +148,17 @@ def test_keep_folder_skips_folder_removal(tmp_path: Path, monkeypatch: pytest.Mo
assert "keys" in called
+def test_bootstrap_fallbacks_remove_registration_without_the_venv() -> None:
+ root = Path(__file__).resolve().parents[3]
+ windows = (root / "install" / "uninstall.ps1").read_text(encoding="utf-8")
+ posix = (root / "install" / "uninstall.sh").read_text(encoding="utf-8")
+
+ assert "CurrentVersion\\Uninstall\\PersonalJarvis" in windows
+ assert "Start Menu\\Programs\\Personal Jarvis.lnk" in windows
+ assert "$HOME/Applications/Personal Jarvis.app" in posix
+ assert "applications/personal-jarvis.desktop" in posix
+
+
# ---------------------------------------------------------------- key removal
def test_remove_keys_deletes_each_present_key(monkeypatch: pytest.MonkeyPatch) -> None:
deleted: list[str] = []
diff --git a/tests/unit/ui/test_icon_identity.py b/tests/unit/ui/test_icon_identity.py
index b063df506d..26a9bc61d4 100644
--- a/tests/unit/ui/test_icon_identity.py
+++ b/tests/unit/ui/test_icon_identity.py
@@ -233,3 +233,26 @@ def test_ensure_start_menu_shortcut_is_idempotent(tmp_path: Path) -> None:
assert first is True
assert second is True
assert (tmp_path / START_MENU_SHORTCUT_NAME).is_file()
+
+
[email protected](sys.platform != "win32", reason="shortcuts are Windows-only")
+def test_ensure_start_menu_shortcut_rewrites_a_live_but_stale_target(
+ tmp_path: Path,
+) -> None:
+ """An old Python executable may still exist after a venv migration."""
+ from win32com.client import Dispatch
+
+ assert ensure_start_menu_shortcut(aumid=_TEST_AUMID, programs_dir=tmp_path)
+ link = tmp_path / START_MENU_SHORTCUT_NAME
+ shell = Dispatch("WScript.Shell")
+ original = shell.CreateShortcut(str(link)).TargetPath
+
+ stale = tmp_path / "old-pythonw.exe"
+ stale.write_bytes(b"still exists")
+ shortcut = shell.CreateShortcut(str(link))
+ shortcut.TargetPath = str(stale)
+ shortcut.Save()
+ assert shell.CreateShortcut(str(link)).TargetPath == str(stale)
+
+ assert ensure_start_menu_shortcut(aumid=_TEST_AUMID, programs_dir=tmp_path)
+ assert shell.CreateShortcut(str(link)).TargetPath == original
diff --git a/tests/unit/ui/web/test_update_routes.py b/tests/unit/ui/web/test_update_routes.py
index e584dbf6e6..309125fc41 100644
--- a/tests/unit/ui/web/test_update_routes.py
+++ b/tests/unit/ui/web/test_update_routes.py
@@ -6,6 +6,7 @@ fail-closed on an unknown running version, and the network check is fail-open.
"""
from __future__ import annotations
+import asyncio
from pathlib import Path
import pytest
@@ -15,13 +16,20 @@ from fastapi.testclient import TestClient
import jarvis.ui.web.update_routes as u
from jarvis.ui.web.update_routes import router as update_router
+_REAL_REFRESH_DESKTOP_INTEGRATION = u._refresh_desktop_integration
+
@pytest.fixture(autouse=True)
-def _reset_cache() -> None:
+def _reset_cache(monkeypatch: pytest.MonkeyPatch) -> None:
# The status cache is module-global; clear it so each test sees a fresh check.
u._status_cache = None
u._status_cache_until = 0.0
+ async def _desktop_ok(_root: Path) -> tuple[bool, str]:
+ return True, ""
+
+ monkeypatch.setattr(u, "_refresh_desktop_integration", _desktop_ok)
+
@pytest.fixture
def client() -> TestClient:
@@ -164,6 +172,8 @@ def test_apply_happy_path_pulls_and_signals_restart(
assert body["ok"] is True
assert body["restart_required"] is True
assert body["version"] == "1.0.2"
+ assert body["desktop_integration_ok"] is True
+ assert body["desktop_integration_warning"] is None
assert ["fetch", "--depth", "1", "origin", "main"] in calls
assert ["reset", "--hard", "origin/main"] in calls
@@ -204,3 +214,56 @@ def test_apply_refreshes_deps_only_when_lockfile_changes(
body = client.post("/api/update/apply").json()
assert body["deps_refreshed"] is True
assert refreshed.get("called") is True
+
+
+def test_apply_reports_desktop_registration_failure_without_rolling_back_code(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ _patch_managed(monkeypatch, tmp_path)
+
+ async def _fake_git(args, *, cwd, timeout_s=60.0):
+ return 0, "", ""
+
+ async def _desktop_failed(_root: Path) -> tuple[bool, str]:
+ return False, "could not register the app launcher"
+
+ monkeypatch.setattr(u, "_git", _fake_git)
+ monkeypatch.setattr(u, "_version_on_disk", lambda root: "1.0.2")
+ monkeypatch.setattr(u, "_refresh_desktop_integration", _desktop_failed)
+
+ body = client.post("/api/update/apply").json()
+
+ assert body["ok"] is True
+ assert body["desktop_integration_ok"] is False
+ assert body["desktop_integration_warning"] == "could not register the app launcher"
+
+
+def test_desktop_refresh_imports_the_new_checkout_in_a_subprocess(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ calls: list[list[str]] = []
+
+ async def _fake_run(cmd, *, cwd, timeout_s):
+ calls.append(cmd)
+ return 0, '{"ok": true, "attempted": false}', ""
+
+ monkeypatch.setattr(u, "_run", _fake_run)
+
+ result = asyncio.run(_REAL_REFRESH_DESKTOP_INTEGRATION(tmp_path))
+
+ assert result == (True, "")
+ assert calls[0][1:3] == ["-m", "jarvis.setup.desktop_integration"]
+
+
+def test_desktop_refresh_reports_an_unreadable_subprocess_result(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ async def _fake_run(cmd, *, cwd, timeout_s):
+ return 0, "not-json", ""
+
+ monkeypatch.setattr(u, "_run", _fake_run)
+
+ ok, warning = asyncio.run(_REAL_REFRESH_DESKTOP_INTEGRATION(tmp_path))
+
+ assert ok is False
+ assert "unreadable" in warning