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(uninstall): stop the running app before deleting the install folder

Ruben Lütkecae663961753
diff --git a/install/uninstall.ps1 b/install/uninstall.ps1
index b927412fc3..e815bb8b14 100644
--- a/install/uninstall.ps1
+++ b/install/uninstall.ps1
@@ -34,6 +34,30 @@ function Write-Ok([string]$Text) { Write-Host "$Green $Chk$Rst $Dim$Text$R
function Write-Note([string]$Text) { Write-Host "$Dim $Text$Rst" }
function Write-Err([string]$Text) { Write-Host "$Red $Crs $Text$Rst" }
+function Stop-JarvisProcesses([string]$Root) {
+ # Any process whose executable lives inside the install dir is the app
+ # itself (tray, server, worker). Windows keeps a running .exe and every
+ # loaded .dll/.pyd locked, so the folder delete fails with "access denied"
+ # while one is alive. Best effort: never this PowerShell, never elevated
+ # processes we cannot see.
+ $Prefix = $Root.TrimEnd('\') + '\'
+ $Procs = @()
+ foreach ($p in (Get-Process -ErrorAction SilentlyContinue)) {
+ if ($p.Id -eq $PID) { continue }
+ $ProcPath = $null
+ try { $ProcPath = $p.Path } catch {}
+ if ($ProcPath -and $ProcPath.StartsWith($Prefix, [System.StringComparison]::OrdinalIgnoreCase)) {
+ $Procs += $p
+ }
+ }
+ if ($Procs.Count -eq 0) { return }
+ foreach ($p in $Procs) { Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue }
+ foreach ($p in $Procs) {
+ try { Wait-Process -Id $p.Id -Timeout 10 -ErrorAction SilentlyContinue } catch {}
+ }
+ Write-Ok "Stopped the running Jarvis app ($($Procs.Count) process(es))."
+}
+
$InstallDir = if ($env:JARVIS_INSTALL_DIR) { $env:JARVIS_INSTALL_DIR } else { Join-Path $env:USERPROFILE '.personal-jarvis' }
$VenvPython = Join-Path $InstallDir '.venv\Scripts\python.exe'
@@ -78,11 +102,33 @@ if ($Rc -ne 0) {
exit $Rc
}
-# 1: delete the folder from OUTSIDE the venv (nothing is locked now). Leave the
-# install dir first so it is not the current location during removal.
+# 1: delete the folder from OUTSIDE the venv. Leave the install dir first so it
+# is not the current location during removal. The Python step above already
+# stops the running app, but anything (re)started since - and the no-venv
+# fallback path - is caught here again. Windows can also hold file locks for
+# a moment after a process dies, so the delete retries before giving up, and
+# a final failure says plainly WHY instead of a red stacktrace.
if (-not $DryRun) {
Set-Location -LiteralPath $env:USERPROFILE
- Remove-Item -LiteralPath $InstallDir -Recurse -Force
+ Stop-JarvisProcesses $InstallDir
+ $Deleted = $false
+ for ($Attempt = 1; $Attempt -le 5; $Attempt++) {
+ try {
+ Remove-Item -LiteralPath $InstallDir -Recurse -Force -ErrorAction Stop
+ $Deleted = $true
+ break
+ } catch {
+ if (-not (Test-Path -LiteralPath $InstallDir)) { $Deleted = $true; break }
+ Stop-JarvisProcesses $InstallDir
+ Start-Sleep -Seconds 2
+ }
+ }
+ if (-not $Deleted -and (Test-Path -LiteralPath $InstallDir)) {
+ Write-Err "Could not fully remove $InstallDir - a program is still using files inside it."
+ Write-Note 'Close every Jarvis window (including the tray icon near the clock) and any terminal opened inside that folder, then run this uninstaller again.'
+ Write-Note 'Signing out of Windows and back in also releases leftover file locks.'
+ exit 3
+ }
Write-Ok "Removed $InstallDir"
Write-Step 'Done. Personal Jarvis has been uninstalled.'
}
diff --git a/install/uninstall.sh b/install/uninstall.sh
index eaac17d3b4..f3ef544de4 100644
--- a/install/uninstall.sh
+++ b/install/uninstall.sh
@@ -33,12 +33,64 @@ ok() { printf '%s ✓%s %s%s%s\n' "$GREEN" "$RST" "$DIM" "$1" "$RST"; }
note() { printf '%s %s%s\n' "$DIM" "$1" "$RST"; }
err() { printf '%s ✗ %s%s\n' "$RED" "$1" "$RST"; }
+# Stop every process still executing out of the install dir — the app itself
+# (tray, server, worker). On POSIX the delete would succeed anyway, but a
+# survivor would keep running from a removed tree (holding its port and mic)
+# until reboot. Never touches this shell or its parent. Best effort.
+stop_running_instances() {
+ root="$1"
+ pids=""
+ if [ -d /proc ]; then
+ # Linux: match the real executable path behind each /proc entry.
+ for exe in /proc/[0-9]*/exe; do
+ pid="${exe#/proc/}"; pid="${pid%/exe}"
+ [ "$pid" = "$$" ] && continue
+ [ "$pid" = "${PPID:-0}" ] && continue
+ target=$(readlink "$exe" 2>/dev/null) || continue
+ case "$target" in "$root"/*) pids="$pids $pid" ;; esac
+ done
+ else
+ # macOS/BSD: ps reports the full executable path in comm.
+ pids=$(ps -axo pid=,comm= 2>/dev/null | while read -r pid comm; do
+ [ "$pid" = "$$" ] && continue
+ [ "$pid" = "${PPID:-0}" ] && continue
+ case "$comm" in "$root"/*) printf '%s ' "$pid" ;; esac
+ done) || true
+ fi
+ pids=$(printf '%s' "$pids" | tr -s ' ')
+ [ -n "${pids# }" ] || return 0
+
+ # shellcheck disable=SC2086 — word-splitting the PID list is intended
+ kill $pids 2>/dev/null || true
+ alive=""
+ for _ in 1 2 3 4 5 6; do
+ alive=""
+ for pid in $pids; do
+ kill -0 "$pid" 2>/dev/null && alive="$alive $pid"
+ done
+ [ -z "$alive" ] && break
+ sleep 1
+ done
+ if [ -n "$alive" ]; then
+ # shellcheck disable=SC2086
+ kill -9 $alive 2>/dev/null || true
+ sleep 1
+ fi
+ n=$(echo "$pids" | wc -w | tr -d ' ')
+ ok "Stopped the running Jarvis app ($n process(es))."
+}
+
step 'Uninstall Personal Jarvis'
note "$INSTALL_DIR"
-# Is this a dry run? Then never touch the folder.
+# Is this a dry run? Then never touch the folder. --yes/-y skips every prompt
+# (required on a headless box where stdin is not a terminal).
DRY_RUN=0
-for a in "$@"; do [ "$a" = "--dry-run" ] && DRY_RUN=1; done
+ASSUME_YES=0
+for a in "$@"; do
+ [ "$a" = "--dry-run" ] && DRY_RUN=1
+ { [ "$a" = "--yes" ] || [ "$a" = "-y" ]; } && ASSUME_YES=1
+done
if [ ! -d "$INSTALL_DIR" ]; then
err "No install found at $INSTALL_DIR — nothing to do."
@@ -55,9 +107,11 @@ else
err "Python environment missing — skipping autostart/key cleanup."
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; }
+ if [ "$ASSUME_YES" -eq 0 ]; then
+ printf 'Type '\''yes'\'' to delete %s: ' "$INSTALL_DIR"
+ read -r ans
+ [ "$ans" = "yes" ] || { note 'Cancelled.'; exit 1; }
+ fi
case "$(uname -s)" in
Darwin)
rm -rf -- "$HOME/Applications/Personal Jarvis.app"
@@ -76,10 +130,17 @@ if [ "$RC" -ne 0 ]; then
exit "$RC"
fi
-# 1: delete the folder from OUTSIDE the venv (nothing is locked now).
+# 1: delete the folder from OUTSIDE the venv. The Python step above already
+# stops the running app; anything (re)started since - and the no-venv
+# fallback path - is caught here again. A failed delete says plainly WHY.
if [ "$DRY_RUN" -eq 0 ]; then
cd "$HOME"
- rm -rf "$INSTALL_DIR"
+ stop_running_instances "$INSTALL_DIR"
+ if ! rm -rf "$INSTALL_DIR"; then
+ err "Could not fully remove $INSTALL_DIR — something is still using files inside it."
+ note 'Close every Jarvis window, then run this uninstaller again.'
+ exit 3
+ fi
ok "Removed $INSTALL_DIR"
step 'Done. Personal Jarvis has been uninstalled.'
fi
diff --git a/jarvis/setup/uninstall.py b/jarvis/setup/uninstall.py
index 58f02ef436..f2d5bb18a6 100644
--- a/jarvis/setup/uninstall.py
+++ b/jarvis/setup/uninstall.py
@@ -31,6 +31,7 @@ the venv.
"""
from __future__ import annotations
+import contextlib
import os
import shutil
import subprocess
@@ -72,6 +73,7 @@ class UninstallPlan:
autostart_supported: bool
autostart_entry: str | None
keyring_keys: list[str] = field(default_factory=list)
+ running_pids: list[int] = field(default_factory=list)
@property
def config_file(self) -> Path:
@@ -123,6 +125,114 @@ def _keyring_keys_present() -> list[str]:
return present
+def _find_running_instances(install_dir: Path) -> list:
+ """Processes that keep the install tree busy — a still-running Jarvis app.
+
+ Matches a process when its executable lives inside ``install_dir`` (the
+ venv's python/pythonw and every console script), or when it is a Python
+ interpreter whose command line references the install dir (a system python
+ driving code from the tree). On Windows any such process keeps ``.exe`` /
+ ``.dll`` / ``.pyd`` files locked, which is exactly what made the final
+ folder delete fail with "access denied".
+
+ The current process and its whole parent chain are always excluded — the
+ uninstall itself runs from the venv when invoked as
+ ``python -m jarvis --uninstall``, and killing our own bootstrap would abort
+ the uninstall mid-flight. Best-effort: returns [] when psutil is missing.
+ """
+ try:
+ import psutil
+ except ImportError:
+ return []
+
+ root = os.path.normcase(str(install_dir.resolve())) + os.sep
+
+ def _inside(raw: str | None) -> bool:
+ if not raw:
+ return False
+ try:
+ return os.path.normcase(os.path.realpath(raw)).startswith(root)
+ except OSError:
+ return False
+
+ protected: set[int] = {os.getpid()}
+ # A broken parent probe must not stop the scan.
+ with contextlib.suppress(Exception):
+ protected.update(p.pid for p in psutil.Process().parents())
+
+ found = []
+ for proc in psutil.process_iter(["pid", "exe", "name", "cmdline"]):
+ try:
+ if proc.info["pid"] in protected:
+ continue
+ if _inside(proc.info["exe"]):
+ found.append(proc)
+ continue
+ # A system interpreter running code out of the install tree. Only
+ # python-named processes qualify so an editor or file manager that
+ # merely has the path on its command line is never touched.
+ name = (proc.info["name"] or "").lower()
+ if name.startswith("python") and any(
+ _inside(arg) for arg in (proc.info["cmdline"] or [])[1:]
+ ):
+ found.append(proc)
+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
+ continue
+ return found
+
+
+def _stop_running_instances(install_dir: Path) -> int:
+ """Stop every running Jarvis process before anything is removed.
+
+ Graceful terminate first, hard kill for stragglers. Never raises — a
+ process we cannot stop is reported and the uninstall carries on (the
+ bootstrap scripts retry the folder delete and explain what still blocks
+ it). Returns the number of processes that are gone.
+ """
+ try:
+ import psutil
+ except ImportError:
+ _console.print(
+ " [muted]→ process check unavailable (psutil missing) — "
+ "close Jarvis yourself if it is still running.[/]"
+ )
+ return 0
+
+ procs = _find_running_instances(install_dir)
+ if not procs:
+ return 0
+
+ for proc in procs:
+ try:
+ proc.terminate()
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
+ continue
+ _gone, alive = psutil.wait_procs(procs, timeout=6)
+ for proc in alive:
+ try:
+ proc.kill()
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
+ continue
+ if alive:
+ _gone, alive = psutil.wait_procs(alive, timeout=4)
+
+ stopped = len(procs) - len(alive)
+ if stopped:
+ _console.print(
+ f" [ok]→ stopped the running Jarvis app "
+ f"({stopped} process{'es' if stopped != 1 else ''}).[/]"
+ )
+ for proc in alive:
+ # Reporting must never abort the uninstall (the process may vanish
+ # between the wait and the name() lookup).
+ with contextlib.suppress(Exception):
+ _console.print(
+ f" [bad]⚠ could not stop process {proc.pid} "
+ f"({escape(proc.name())}) — it may keep files locked.[/]"
+ )
+ return stopped
+
+
def _autostart_state() -> tuple[bool, str | None]:
"""(supported, entry_path) for the current install's login-autostart entry.
@@ -143,12 +253,17 @@ def build_plan() -> UninstallPlan:
"""Inspect the machine and report what an uninstall would remove. Pure."""
install_dir = Path(cfg.PROJECT_ROOT).resolve()
supported, entry = _autostart_state()
+ try:
+ running = [p.pid for p in _find_running_instances(install_dir)]
+ except Exception: # noqa: BLE001 — a scan failure must not block the uninstall
+ running = []
return UninstallPlan(
install_dir=install_dir,
is_jarvis_install=_looks_like_jarvis_install(install_dir),
autostart_supported=supported,
autostart_entry=entry,
keyring_keys=_keyring_keys_present(),
+ running_pids=running,
)
@@ -160,6 +275,12 @@ def _print_plan(plan: UninstallPlan, *, keep_keys: bool, keep_folder: bool) -> N
"[bad]This removes Jarvis from THIS machine.[/] "
"It does not touch your accounts or anything you created elsewhere.\n",
]
+ if plan.running_pids:
+ n = len(plan.running_pids)
+ lines.append(
+ f"[brand]•[/] Stop the running Jarvis app first "
+ f"([brand.bold]{n}[/] process{'es' if n != 1 else ''} still active)"
+ )
if not keep_folder:
lines.append(
f"[brand]•[/] Delete the install folder:\n"
@@ -365,9 +486,12 @@ def run_uninstall(
_console.print()
_console.print(" [brand.bold]Removing…[/]")
- # 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.
+ # Order matters: stop the running app FIRST (a live process keeps venv
+ # files locked on Windows and the folder delete would fail), then remove
+ # every external registration and the keys, then the folder last — on
+ # Windows the folder step may end this process's ability to do further
+ # work if it self-deletes.
+ _stop_running_instances(plan.install_dir)
_remove_desktop_registration()
_remove_autostart()
if not keep_keys:
@@ -376,6 +500,13 @@ def run_uninstall(
_remove_folder(plan.install_dir)
_console.print()
- _console.print(" [ok]Done.[/] [muted]Personal Jarvis has been removed. "
- "Re-run the installer any time to start fresh.[/]\n")
+ if keep_folder:
+ # The bootstrap script (uninstall.ps1 / uninstall.sh) deletes the
+ # folder next — claiming "removed" here would be dishonest if that
+ # final step still fails.
+ _console.print(" [ok]Cleanup done.[/] [muted]Removing the install "
+ "folder itself…[/]\n")
+ else:
+ _console.print(" [ok]Done.[/] [muted]Personal Jarvis has been removed. "
+ "Re-run the installer any time to start fresh.[/]\n")
return 0
diff --git a/tests/integration/test_uninstall_bootstrap.py b/tests/integration/test_uninstall_bootstrap.py
new file mode 100644
index 0000000000..38a868369d
--- /dev/null
+++ b/tests/integration/test_uninstall_bootstrap.py
@@ -0,0 +1,164 @@
+"""End-to-end tests for the uninstall bootstraps (install/uninstall.ps1 + .sh).
+
+Regression for the locked-folder uninstall failure: with the Jarvis app still
+running, its process kept venv files locked on Windows and the bootstrap's
+final recursive delete died with a red PermissionDenied stacktrace. The
+bootstraps now stop every process running out of the install dir, retry the
+delete, and fail with an honest message instead of a crash.
+
+SAFETY — these tests run ONLY on throwaway CI runners (``CI`` env var), never
+on a developer machine: the bootstraps' no-venv fallback path removes the real
+per-user desktop registration (Start-menu shortcut + registry keys on Windows,
+the app bundle / .desktop entry on POSIX), which must never happen to a live
+personal install. Everything else is sandboxed: the "install" being removed is
+a throwaway fake directory injected via ``JARVIS_INSTALL_DIR``, populated with
+a copied system long-runner (ping/sleep) so a process is genuinely executing
+out of the tree when the bootstrap runs.
+"""
+from __future__ import annotations
+
+import os
+import shutil
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+import pytest
+
+pytestmark = [
+ pytest.mark.integration,
+ pytest.mark.skipif(
+ not os.environ.get("CI"),
+ reason=(
+ "CI runners only — the no-venv fallback path touches the real "
+ "per-user app registration, never exercise it on a developer machine"
+ ),
+ ),
+]
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+
+
+def _make_fake_install(tmp_path: Path) -> Path:
+ """A directory the bootstrap accepts as an install, WITHOUT a venv python.
+
+ The missing venv python routes the bootstrap through its fallback branch,
+ so the script's own process-stop + retry-delete logic is what does the
+ work — nothing here depends on `python -m jarvis --uninstall`.
+ """
+ fake = tmp_path / "fake-jarvis-install"
+ (fake / "jarvis").mkdir(parents=True)
+ (fake / "pyproject.toml").write_text("[project]\nname='personal-jarvis'\n", encoding="utf-8")
+ return fake
+
+
+def _start_process_from(fake: Path) -> subprocess.Popen[bytes]:
+ """Run a harmless long-runner whose executable lives inside the fake dir.
+
+ On Windows this puts real file locks on the tree — the exact condition
+ that broke the original uninstall.
+ """
+ if sys.platform == "win32":
+ bin_dir = fake / ".venv" / "Scripts"
+ bin_dir.mkdir(parents=True, exist_ok=True)
+ target = bin_dir / "jarvis-fake.exe"
+ source = Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32" / "ping.exe"
+ shutil.copy2(source, target)
+ return subprocess.Popen( # noqa: S603 — self-copied system binary
+ [str(target), "-n", "120", "127.0.0.1"],
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
+ )
+ bin_dir = fake / ".venv" / "bin"
+ bin_dir.mkdir(parents=True, exist_ok=True)
+ target = bin_dir / "jarvis-fake"
+ sleep_bin = shutil.which("sleep")
+ assert sleep_bin, "CI runner without a sleep binary"
+ shutil.copy2(sleep_bin, target)
+ target.chmod(0o755)
+ return subprocess.Popen( # noqa: S603 — self-copied system binary
+ [str(target), "120"],
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+
+
+def _run_bootstrap(fake: Path) -> subprocess.CompletedProcess[str]:
+ env = {**os.environ, "JARVIS_INSTALL_DIR": str(fake)}
+ if sys.platform == "win32":
+ shell = shutil.which("powershell") or shutil.which("pwsh")
+ assert shell, "CI runner without PowerShell"
+ cmd = [
+ shell,
+ "-NoProfile",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-File",
+ str(REPO_ROOT / "install" / "uninstall.ps1"),
+ "--yes",
+ ]
+ else:
+ cmd = ["bash", str(REPO_ROOT / "install" / "uninstall.sh"), "--yes"]
+ return subprocess.run( # noqa: S603 — repo-owned scripts against a fake dir
+ cmd,
+ env=env,
+ capture_output=True,
+ text=True,
+ timeout=180,
+ stdin=subprocess.DEVNULL,
+ )
+
+
+def test_bootstrap_removes_fake_install_despite_running_process(tmp_path: Path) -> None:
+ fake = _make_fake_install(tmp_path)
+ proc = _start_process_from(fake)
+ try:
+ time.sleep(1)
+ assert proc.poll() is None, "the fake app must be running when the bootstrap starts"
+
+ result = _run_bootstrap(fake)
+
+ assert result.returncode == 0, (
+ f"bootstrap failed\nstdout:\n{result.stdout}\nstderr:\n{result.stderr}"
+ )
+ assert not fake.exists(), "the install dir must be fully removed"
+ # The running process was stopped by the script, not by our cleanup.
+ assert proc.poll() is not None, "the bootstrap must stop the running app"
+ finally:
+ if proc.poll() is None:
+ proc.kill()
+
+
+def test_bootstrap_dry_run_touches_nothing(tmp_path: Path) -> None:
+ fake = _make_fake_install(tmp_path)
+
+ env = {**os.environ, "JARVIS_INSTALL_DIR": str(fake)}
+ if sys.platform == "win32":
+ shell = shutil.which("powershell") or shutil.which("pwsh")
+ assert shell
+ cmd = [
+ shell,
+ "-NoProfile",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-File",
+ str(REPO_ROOT / "install" / "uninstall.ps1"),
+ "--dry-run",
+ ]
+ else:
+ cmd = ["bash", str(REPO_ROOT / "install" / "uninstall.sh"), "--dry-run"]
+ result = subprocess.run( # noqa: S603
+ cmd,
+ env=env,
+ capture_output=True,
+ text=True,
+ timeout=60,
+ stdin=subprocess.DEVNULL,
+ )
+
+ assert result.returncode == 0, (
+ f"dry run failed\nstdout:\n{result.stdout}\nstderr:\n{result.stderr}"
+ )
+ assert fake.exists(), "a dry run must never delete the install dir"
diff --git a/tests/unit/setup/test_uninstall.py b/tests/unit/setup/test_uninstall.py
index 730d2e87f9..6e814a3509 100644
--- a/tests/unit/setup/test_uninstall.py
+++ b/tests/unit/setup/test_uninstall.py
@@ -6,6 +6,9 @@ are monkeypatched to recorders whenever run_uninstall() is exercised.
"""
from __future__ import annotations
+import os
+import shutil
+import subprocess
import sys
from pathlib import Path
@@ -32,8 +35,13 @@ def _use_plan(monkeypatch: pytest.MonkeyPatch, plan: UninstallPlan) -> None:
def _record_steps(monkeypatch: pytest.MonkeyPatch) -> list[str]:
- """Replace the four removal helpers with recorders; return the shared log."""
+ """Replace the five removal helpers with recorders; return the shared log."""
called: list[str] = []
+ monkeypatch.setattr(
+ uninstall,
+ "_stop_running_instances",
+ lambda p: called.append("stop") or 0,
+ )
monkeypatch.setattr(
uninstall,
"_remove_desktop_registration",
@@ -60,9 +68,10 @@ def test_looks_like_jarvis_install_false_for_random_dir(tmp_path: Path) -> None:
def test_build_plan_reflects_real_repo(monkeypatch: pytest.MonkeyPatch) -> None:
- # Keep it hermetic: no real keyring / autostart probing.
+ # Keep it hermetic: no real keyring / autostart / process probing.
monkeypatch.setattr(uninstall, "_autostart_state", lambda: (False, None))
monkeypatch.setattr(uninstall, "_keyring_keys_present", lambda: [])
+ monkeypatch.setattr(uninstall, "_find_running_instances", lambda _p: [])
plan = uninstall.build_plan()
from jarvis.core import config as cfg
@@ -123,11 +132,12 @@ def test_assume_yes_runs_all_four_steps(tmp_path: Path, monkeypatch: pytest.Monk
rc = uninstall.run_uninstall(assume_yes=True)
assert rc == 0
assert called == [
+ "stop",
"desktop",
"autostart",
"keys",
"folder",
- ] # order: outside-the-folder first
+ ] # order: stop the live app first, then outside-the-folder registrations
def test_keep_keys_skips_key_removal(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
@@ -159,6 +169,26 @@ def test_bootstrap_fallbacks_remove_registration_without_the_venv() -> None:
assert "applications/personal-jarvis.desktop" in posix
+def test_bootstraps_stop_the_running_app_and_retry_the_delete() -> None:
+ """Regression guard for the locked-folder uninstall failure: a still-running
+ Jarvis process kept venv files locked on Windows, so the final
+ ``Remove-Item -Recurse`` died with a red PermissionDenied stacktrace. Both
+ bootstraps must stop processes running out of the install dir, retry the
+ delete, and end with an honest plain-language message instead of a crash."""
+ 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 "Stop-JarvisProcesses" in windows
+ assert "$Attempt" in windows # retry loop around the folder delete
+ assert "Could not fully remove" in windows # honest failure message
+ assert "run this uninstaller again" in windows
+
+ assert "stop_running_instances" in posix
+ assert "Could not fully remove" in posix
+ assert "run this uninstaller again" in posix
+
+
# ---------------------------------------------------------------- key removal
def test_remove_keys_deletes_each_present_key(monkeypatch: pytest.MonkeyPatch) -> None:
deleted: list[str] = []
@@ -188,6 +218,89 @@ def test_running_inside_false_for_unrelated_dir(tmp_path: Path) -> None:
assert uninstall._running_inside(tmp_path) is False
+# ---------------------------------------------------------------- process stop
+#
+# Safety: these tests NEVER touch a real install. They copy a harmless system
+# long-runner (ping/sleep) into a throwaway tmp_path "install dir", start it
+# from there, and prove the stop step finds and ends exactly that process.
+
+
+def _start_fake_install_process(fake_dir: Path) -> subprocess.Popen[bytes]:
+ """Launch a long-running process whose executable lives INSIDE fake_dir.
+
+ That is precisely the condition that locked the venv files on Windows and
+ made the real uninstall fail with PermissionDenied.
+ """
+ if sys.platform == "win32":
+ bin_dir = fake_dir / ".venv" / "Scripts"
+ else:
+ bin_dir = fake_dir / ".venv" / "bin"
+ bin_dir.mkdir(parents=True, exist_ok=True)
+ if sys.platform == "win32":
+ source = Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32" / "ping.exe"
+ target = bin_dir / "jarvis-fake.exe"
+ shutil.copy2(source, target)
+ args = [str(target), "-n", "60", "127.0.0.1"]
+ flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
+ return subprocess.Popen( # noqa: S603 — self-copied system binary
+ args,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ creationflags=flags,
+ )
+ source_str = shutil.which("sleep")
+ if source_str is None:
+ pytest.skip("no 'sleep' binary available")
+ target = bin_dir / "jarvis-fake"
+ shutil.copy2(source_str, target)
+ target.chmod(0o755)
+ return subprocess.Popen( # noqa: S603 — self-copied system binary
+ [str(target), "60"],
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+
+
+def test_stop_running_instances_ends_process_from_install_dir(tmp_path: Path) -> None:
+ fake_dir = tmp_path / "fake-install"
+ try:
+ proc = _start_fake_install_process(fake_dir)
+ except OSError as exc: # hardened runner without ping/sleep copy rights
+ pytest.skip(f"cannot start sandbox process: {exc}")
+ try:
+ assert proc.poll() is None, "sandbox process must be running before the stop"
+
+ stopped = uninstall._stop_running_instances(fake_dir)
+
+ assert stopped >= 1
+ proc.wait(timeout=10)
+ assert proc.poll() is not None
+ # The point of the whole fix: with nothing running from the tree, the
+ # folder is deletable — on Windows this fails while the process lives.
+ shutil.rmtree(fake_dir)
+ assert not fake_dir.exists()
+ finally:
+ if proc.poll() is None:
+ proc.kill()
+
+
+def test_stop_running_instances_zero_when_nothing_runs(tmp_path: Path) -> None:
+ assert uninstall._stop_running_instances(tmp_path) == 0
+
+
+def test_find_running_instances_never_lists_self_or_parents() -> None:
+ """The uninstall itself runs from the venv python — killing self or the
+ bootstrap shell would abort the uninstall mid-flight. Scanning the live
+ interpreter's own directory is read-only and must exclude our chain."""
+ own_dir = Path(sys.executable).resolve().parent
+ pids = {p.pid for p in uninstall._find_running_instances(own_dir)}
+
+ import psutil
+
+ protected = {os.getpid()} | {p.pid for p in psutil.Process().parents()}
+ assert pids.isdisjoint(protected)
+
+
def test_windows_self_deleter_writes_batch_and_spawns(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None: