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
feat(install): add a cross-platform uninstall command
Ruben Lütkeb33d47981bd9
diff --git a/.gitattributes b/.gitattributesindex c1b0af8b2c..c7b0fafc34 100644--- a/.gitattributes+++ b/.gitattributes@@ -14,6 +14,10 @@ install/install.ps1 text eol=lfinstall/installer.py text eol=lfinstall/install-verify.sh text eol=lfinstall/install-verify.ps1 text eol=lf+# Uninstaller bootstraps — NOT under signature, but a CRLF shell script breaks+# `bash uninstall.sh` on macOS/Linux, so pin them to LF unconditionally too.+install/uninstall.sh text eol=lf+install/uninstall.ps1 text eol=lf# Wave 6: the hash-pinned dependency lockfile + its source `requirements.in`# are signed alongside the install scripts. Same LF-pinning discipline so# the cross-runner hash assertion (cross-runner-hash.yml) does not breakdiff --git a/README.md b/README.mdindex 91f3b0d014..06b2c84248 100644--- a/README.md+++ b/README.md@@ -122,6 +122,20 @@ curl -fsSL https://raw.githubusercontent.com/PersonalJarvis/PersonalJarvis/main/| `--no-launch` | Install only; don't start the app || `--no-wizard` | Skip the first-run key wizard |+**Uninstall** — one command removes everything a plain folder-delete would miss: the+install folder, the login-autostart entry, and the API keys saved in your OS keychain.+Add `--dry-run` to preview, or `--yes` to skip the confirmation.++```powershell+# Windows (PowerShell)+& "$env:USERPROFILE\.personal-jarvis\install\uninstall.ps1"+```++```bash+# macOS · Linux+bash ~/.personal-jarvis/install/uninstall.sh+```+<details><summary><b>Prefer pipx, or a manual clone?</b></summary>diff --git a/install/uninstall.ps1 b/install/uninstall.ps1new file mode 100644index 0000000000..ce356ef97f--- /dev/null+++ b/install/uninstall.ps1@@ -0,0 +1,80 @@+# Personal Jarvis - Windows uninstaller+#+# Usage (from PowerShell), on a machine where Jarvis is installed:+# & "$env:USERPROFILE\.personal-jarvis\install\uninstall.ps1"+# & "$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:+# 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+# "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),+# then removes the folder itself from OUTSIDE the venv so the running python.exe+# never locks its own tree.+#+# SOURCE-ENCODING RULE: served BOM-less, read as cp1252 by Windows PowerShell, so+# the source outside here-strings stays ASCII; glyphs are built from code points.++$ErrorActionPreference = 'Stop'+try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch {}++$e = [char]27+$Gold = "${e}[38;2;231;196;110m"; $Green = "${e}[38;2;122;200;140m"+$Dim = "${e}[38;2;140;140;140m"; $Red = "${e}[38;2;224;122;110m"+$Bold = "${e}[1m"; $Rst = "${e}[0m"+$Dot = [char]0x25CF; $Chk = [char]0x2713; $Crs = [char]0x2717++function Write-Step([string]$Text) { Write-Host ""; Write-Host "$Gold $Dot$Rst $Bold$Text$Rst" }+function Write-Ok([string]$Text) { Write-Host "$Green $Chk$Rst $Dim$Text$Rst" }+function Write-Note([string]$Text) { Write-Host "$Dim $Text$Rst" }+function Write-Err([string]$Text) { Write-Host "$Red $Crs $Text$Rst" }++$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'++Write-Step 'Uninstall Personal Jarvis'+Write-Note $InstallDir++$DryRun = $args -contains '--dry-run'+$AssumeYes = ($args -contains '--yes') -or ($args -contains '-y')++if (-not (Test-Path -LiteralPath $InstallDir)) {+ Write-Err "No install found at $InstallDir - nothing to do."+ 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).+$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.'+ if ($DryRun) { exit 0 }+ if (-not $AssumeYes) {+ $ans = Read-Host "Type 'yes' to delete $InstallDir"+ if ($ans -ne 'yes') { Write-Note 'Cancelled.'; exit 1 }+ }+ $Rc = 0+}++# The Python step returns 1 when the user cancels at its prompt. Respect that.+if ($Rc -ne 0) {+ Write-Note 'Cancelled - nothing was changed.'+ 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.+if (-not $DryRun) {+ Set-Location -LiteralPath $env:USERPROFILE+ Remove-Item -LiteralPath $InstallDir -Recurse -Force+ Write-Ok "Removed $InstallDir"+ Write-Step 'Done. Personal Jarvis has been uninstalled.'+}diff --git a/install/uninstall.sh b/install/uninstall.shnew file mode 100644index 0000000000..2cb3472938--- /dev/null+++ b/install/uninstall.sh@@ -0,0 +1,75 @@+#!/usr/bin/env bash+# Personal Jarvis — macOS / Linux uninstaller+#+# Usage (from any POSIX shell), on a machine where Jarvis is installed:+# bash ~/.personal-jarvis/install/uninstall.sh+# 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:+# 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")+#+# Heavy logic lives in `python -m jarvis --uninstall` (cross-platform, tested).+# This bootstrap runs that for the autostart + keys (it asks for confirmation),+# then removes the folder itself from OUTSIDE the venv so nothing is locked.++set -euo pipefail++INSTALL_DIR="${JARVIS_INSTALL_DIR:-$HOME/.personal-jarvis}"+VENV_PYTHON="$INSTALL_DIR/.venv/bin/python"++if [ -t 1 ]; then+ GOLD=$(printf '\033[38;2;231;196;110m'); GREEN=$(printf '\033[38;2;122;200;140m')+ DIM=$(printf '\033[38;2;140;140;140m'); RED=$(printf '\033[38;2;224;122;110m')+ BOLD=$(printf '\033[1m'); RST=$(printf '\033[0m')+else+ GOLD=""; GREEN=""; DIM=""; RED=""; BOLD=""; RST=""+fi+step() { printf '\n%s ●%s %s%s%s\n' "$GOLD" "$RST" "$BOLD" "$1" "$RST"; }+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"; }++step 'Uninstall Personal Jarvis'+note "$INSTALL_DIR"++# Is this a dry run? Then never touch the folder.+DRY_RUN=0+for a in "$@"; do [ "$a" = "--dry-run" ] && DRY_RUN=1; done++if [ ! -d "$INSTALL_DIR" ]; then+ err "No install found at $INSTALL_DIR — nothing to do."+ 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.+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."+ 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; }+ RC=0+fi++# The Python step returns 1 when the user cancels at its prompt. Respect that.+if [ "$RC" -ne 0 ]; then+ note 'Cancelled — nothing was changed.'+ exit "$RC"+fi++# 1: delete the folder from OUTSIDE the venv (nothing is locked now).+if [ "$DRY_RUN" -eq 0 ]; then+ cd "$HOME"+ rm -rf "$INSTALL_DIR"+ ok "Removed $INSTALL_DIR"+ step 'Done. Personal Jarvis has been uninstalled.'+fidiff --git a/jarvis/__main__.py b/jarvis/__main__.pyindex 03af361ab5..247ad98956 100644--- a/jarvis/__main__.py+++ b/jarvis/__main__.py@@ -5,6 +5,8 @@ Usage:python -m jarvis --wizard # Re-run the setup wizardpython -m jarvis --check # Show hardware analysis onlypython -m jarvis --plugins # List the plugin registry+ python -m jarvis --uninstall # Remove Jarvis from this machine (folder,+ # login-autostart entry, saved API keys)"""from __future__ import annotations@@ -63,6 +65,30 @@ def _build_parser() -> argparse.ArgumentParser:dest="reset_onboarding",help="Clear onboarding markers so the first-run guide shows again.",)+ parser.add_argument(+ "--uninstall",+ action="store_true",+ help="Remove this Jarvis install from the machine: the install folder, "+ "the login-autostart entry, and the API keys saved in the OS "+ "keychain. Asks for confirmation first.",+ )+ parser.add_argument(+ "--yes", "-y", action="store_true", dest="assume_yes",+ help="With --uninstall: skip the confirmation prompt.",+ )+ parser.add_argument(+ "--keep-keys", action="store_true", dest="keep_keys",+ help="With --uninstall: keep the saved API keys in the OS keychain.",+ )+ parser.add_argument(+ "--keep-folder", action="store_true", dest="keep_folder",+ help="With --uninstall: leave the install folder in place (used by the "+ "uninstall.ps1/.sh bootstraps, which delete it from outside the venv).",+ )+ parser.add_argument(+ "--dry-run", action="store_true", dest="dry_run",+ help="With --uninstall: show what would be removed, change nothing.",+ )parser.add_argument("command",nargs="?",@@ -308,6 +334,18 @@ def _cmd_reset_onboarding() -> int:return 0+def _cmd_uninstall(args: argparse.Namespace) -> int:+ """Remove this Jarvis install from the machine (folder + autostart + keys)."""+ from jarvis.setup import uninstall++ return uninstall.run_uninstall(+ assume_yes=args.assume_yes,+ keep_keys=args.keep_keys,+ keep_folder=args.keep_folder,+ dry_run=args.dry_run,+ )++def _cmd_install_admin_helper() -> int:"""Generates the HMAC shared secret (if missing) in the Credential Manager."""try:@@ -442,6 +480,8 @@ def main(argv: list[str] | None = None) -> int:return _cmd_doctor()if args.install_admin_helper:return _cmd_install_admin_helper()+ if args.uninstall:+ return _cmd_uninstall(args)if args.reset_onboarding:return _cmd_reset_onboarding()if args.command == "serve":diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex 0cb0897177..8840199645 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -33,7 +33,7 @@ from typing import TYPE_CHECKING, Any, Literalfrom uuid import UUID, uuid4from jarvis.core.bus import EventBus-from jarvis.core.config import JarvisConfig+from jarvis.core.config import BrainTierConfig, JarvisConfigfrom jarvis.core.events import (ActionExecuted,AnnouncementRequested,@@ -77,7 +77,6 @@ from jarvis.safety.tool_executor import ToolExecutorfrom jarvis.brain.provider_test import BILLING_LIMIT_MARKERSfrom .dispatcher import BrainDispatcher-from .healthcheck import BrainConfigErrorfrom .intent_router import RoutingDecision, classifyfrom .local_action_gate import (HARNESS_NAME,@@ -1967,10 +1966,31 @@ class BrainManager:"""tier_cfg = getattr(config.brain, tier, None)if tier_cfg is None:- raise BrainConfigError(- f"No [brain.{tier}] block in config. "- f"Tiered routing requires [brain.router] in jarvis.toml."+ # A fresh install ships NO [brain.router] block: jarvis.toml.example+ # has a [brain] table but no [brain.router] sub-table, and neither+ # the wizard, the installer, nor onboarding ever writes one. Raising+ # here left ``app.state.brain = None``, which bricked BOTH the+ # voice/chat brain AND the provider-switch route — the latter then+ # surfaced the misleading "headless mode" 503 on every "Set active"+ # click. This only ever hit downloaders: the maintainer's own+ # jarvis.toml HAS the block (textbook AP-23 "works on my machine").+ # Instead of failing, synthesize the tier from the user's REAL+ # selection. BrainTierConfig only requires ``provider``; the model is+ # filled per-provider by ``_resolve_tier_model``. Provider-agnostic —+ # it honours whatever main provider the fresh user configured, and an+ # explicit [brain.router] block still overrides this untouched.+ default_provider = (+ (config.brain.primary or "").strip()+ or (config.brain.routing_provider or "").strip()+ or "claude-api")+ log.info(+ "No [brain.%s] block in config — synthesizing a default tier from "+ "brain.primary=%r so a fresh install boots a working brain.",+ tier,+ default_provider,+ )+ tier_cfg = BrainTierConfig(provider=default_provider)local_config = config.model_copy(deep=True)requested_provider = provider_override or tier_cfg.providerdiff --git a/jarvis/setup/uninstall.py b/jarvis/setup/uninstall.pynew file mode 100644index 0000000000..cbb28dc425--- /dev/null+++ b/jarvis/setup/uninstall.py@@ -0,0 +1,355 @@+"""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+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+ ``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+ 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``+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.++Self-delete note (Windows): when invoked as ``python -m jarvis --uninstall`` the+running interpreter lives INSIDE the folder we must delete, and Windows locks a+running ``.exe``/loaded ``.dll``. We can't ``rmtree`` our own venv there, so on+Windows we hand the final folder removal to a tiny detached batch that waits for+this process to exit and then deletes the tree. On POSIX the unlink succeeds+while we run (open handles keep working from memory), so we delete directly. The+``install/uninstall.ps1`` / ``install/uninstall.sh`` bootstraps sidestep the lock+entirely: they pass ``--keep-folder`` and remove the tree themselves from OUTSIDE+the venv.+"""+from __future__ import annotations++import os+import shutil+import subprocess+import sys+import tempfile+import textwrap+from dataclasses import dataclass, field+from pathlib import Path++from rich.console import Console+from rich.markup import escape+from rich.panel import Panel+from rich.theme import Theme++from jarvis.core import config as cfg+from jarvis.setup.wizard import SECRETS++# Same Charcoal + Gold palette as install/installer.py and the first-run wizard,+# so uninstalling reads as part of the same on-brand experience. Rich strips+# color on a non-TTY (headless/CI/piped), so these calls degrade to plain text.+_THEME = Theme(+ {+ "brand": "#e7c46e",+ "brand.bold": "bold #e7c46e",+ "ok": "#7ac88c",+ "muted": "#8c8c8c",+ "bad": "#e07a6e",+ }+)+_console = Console(theme=_THEME, highlight=False)+++@dataclass(slots=True, frozen=True)+class UninstallPlan:+ """What an uninstall WOULD remove — computed without any side effect."""++ install_dir: Path+ is_jarvis_install: bool+ autostart_supported: bool+ autostart_entry: str | None+ keyring_keys: list[str] = field(default_factory=list)++ @property+ def config_file(self) -> Path:+ return self.install_dir / "jarvis.toml"++ @property+ def data_dir(self) -> Path:+ return self.install_dir / "data"+++# ---------------------------------------------------------------- discovery+def _looks_like_jarvis_install(path: Path) -> bool:+ """Safety guard: only ever touch a directory that really is a Jarvis tree.++ ``PROJECT_ROOT`` is derived from this package's own ``__file__``, so under+ normal use it is always the real install root. This guard is the+ belt-and-suspenders that stops a mis-set path (or a future caller) from+ handing ``rmtree`` an unrelated directory."""+ try:+ return (path / "jarvis").is_dir() and (path / "pyproject.toml").is_file()+ except OSError:+ return False+++def _keyring_keys_present() -> list[str]:+ """Which of Jarvis's known secret slots are actually stored in the keyring.++ Prefers a direct keyring probe (so an ENV-provided key is NOT mistaken for a+ stored one — we never delete ENV vars, they aren't ours). Falls back to the+ general getter only if the keyring module is unavailable."""+ cfg._ensure_keyring_backend()+ probe = None+ try:+ import keyring++ def probe(key: str) -> str | None:+ return keyring.get_password(cfg.KEYRING_SERVICE, key)+ except Exception: # noqa: BLE001 — no keyring module → fall back to the getter+ def probe(key: str) -> str | None:+ return cfg.get_secret(key)++ present: list[str] = []+ for spec in SECRETS:+ try:+ if probe(spec.key):+ present.append(spec.key)+ except Exception: # noqa: BLE001, S112 — a single unreadable slot must not abort+ continue+ return present+++def _autostart_state() -> tuple[bool, str | None]:+ """(supported, entry_path) for the current install's login-autostart entry.++ Best-effort and never raises — an autostart probe failure must not block the+ uninstall (the folder + keys are the important removals)."""+ try:+ from jarvis.autostart import make_autostart_manager, resolve_launch_spec+ from jarvis.platform.capabilities import detect_capabilities++ manager = make_autostart_manager(detect_capabilities())+ status = manager.status(resolve_launch_spec(None))+ return status.supported, (status.entry_path if status.installed else None)+ except Exception: # noqa: BLE001+ return False, None+++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()+ 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(),+ )+++# ---------------------------------------------------------------- presentation+def _print_plan(plan: UninstallPlan, *, keep_keys: bool, keep_folder: bool) -> None:+ _console.print()+ _console.print(" [brand.bold]Uninstall Personal Jarvis[/]")+ lines = [+ "[bad]This removes Jarvis from THIS machine.[/] "+ "It does not touch your accounts or anything you created elsewhere.\n",+ ]+ if not keep_folder:+ lines.append(+ f"[brand]•[/] Delete the install folder:\n"+ f" [muted]{escape(str(plan.install_dir))}[/]"+ )+ lines.append(" [muted](code, the Python environment, jarvis.toml, and data folder)[/]")+ if plan.autostart_entry:+ lines.append(+ f"[brand]•[/] Remove the login-autostart entry:\n"+ f" [muted]{escape(plan.autostart_entry)}[/]"+ )+ else:+ lines.append("[brand]•[/] Login autostart: [muted]nothing to remove[/]")+ if not keep_keys:+ if plan.keyring_keys:+ lines.append(+ f"[brand]•[/] Delete [brand.bold]{len(plan.keyring_keys)}[/] saved API key(s) "+ "from your system keychain"+ )+ else:+ lines.append("[brand]•[/] Saved API keys: [muted]none found in the keychain[/]")+ _console.print(Panel("\n".join(lines), border_style="brand", padding=(1, 2)))+++def _confirm() -> bool:+ """Fail-closed confirmation — the user must type 'yes' to proceed."""+ try:+ answer = input(" Type 'yes' to remove Jarvis (anything else cancels): ").strip().lower()+ except (EOFError, KeyboardInterrupt):+ return False+ return answer in ("yes", "y")+++# ---------------------------------------------------------------- removal steps+def _remove_autostart() -> None:+ try:+ from jarvis.autostart import make_autostart_manager+ from jarvis.platform.capabilities import detect_capabilities++ manager = make_autostart_manager(detect_capabilities())+ # interactive=True: on Windows removing the logon task may show one UAC+ # prompt; macOS/Linux ignore the flag (per-user entry, no elevation).+ status = manager.uninstall(interactive=True)+ if status.supported:+ _console.print(" [ok]→ login-autostart entry removed.[/]")+ else:+ _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))}[/]")+++def _remove_keys(keys: list[str]) -> int:+ deleted = 0+ for key in keys:+ if cfg.delete_secret(key):+ deleted += 1+ if deleted:+ _console.print(f" [ok]→ removed {deleted} saved key(s) from the keychain.[/]")+ elif keys:+ _console.print(" [muted]→ no keychain keys were removed.[/]")+ return deleted+++def _running_inside(path: Path) -> bool:+ """True when the current interpreter lives inside ``path`` (self-hosted).++ On Windows this means the venv ``.exe``/DLLs are locked and we cannot delete+ the tree from within our own process."""+ try:+ exe = Path(sys.executable).resolve()+ path = path.resolve()+ return path == exe or path in exe.parents+ except OSError:+ return False+++def _spawn_windows_self_deleter(target: Path) -> None:+ """Hand the folder removal to a detached batch that waits for us to exit.++ Uses ``ping`` (not ``timeout``) for its delays because ``timeout`` needs a+ console this detached process does not have. The batch retries until the+ tree is gone, then deletes itself. Spawned with CREATE_NO_WINDOW so no+ console flashes (AP-1) and DETACHED so it outlives this process."""+ pid = os.getpid()+ bat = Path(tempfile.gettempdir()) / f"jarvis_uninstall_{pid}.bat"+ script = textwrap.dedent(+ f"""\+ @echo off+ :waitloop+ tasklist /FI "PID eq {pid}" | find "{pid}" >nul+ if not errorlevel 1 (+ ping -n 2 127.0.0.1 >nul+ goto waitloop+ )+ :delloop+ rmdir /s /q "{target}" 2>nul+ if exist "{target}" (+ ping -n 2 127.0.0.1 >nul+ goto delloop+ )+ del "%~f0" >nul 2>&1+ """+ )+ bat.write_text(script, encoding="utf-8")+ creationflags = 0+ # DETACHED_PROCESS | CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP — the deleter+ # must survive our exit and never pop a window.+ for name in ("DETACHED_PROCESS", "CREATE_NO_WINDOW", "CREATE_NEW_PROCESS_GROUP"):+ creationflags |= getattr(subprocess, name, 0)+ subprocess.Popen( # noqa: S603 — fixed cmd, no shell, self-authored batch+ ["cmd", "/c", str(bat)],+ creationflags=creationflags,+ close_fds=True,+ )+++def _remove_folder(install_dir: Path) -> bool:+ """Remove the install tree. Returns True when it is gone (or scheduled to be).++ POSIX (and Windows when NOT self-hosted): direct ``rmtree``. Windows ++ self-hosted: schedule a detached deleter and report that it will finish a+ moment after we exit."""+ if sys.platform == "win32" and _running_inside(install_dir):+ try:+ _spawn_windows_self_deleter(install_dir)+ _console.print(+ " [ok]→ the install folder will be removed a moment after this "+ "window closes.[/]"+ )+ return True+ except Exception as exc: # noqa: BLE001+ _console.print(+ f" [bad]⚠ could not schedule folder removal: {escape(str(exc))}[/]\n"+ f" [muted]Delete it yourself: {escape(str(install_dir))}[/]"+ )+ return False+ try:+ shutil.rmtree(install_dir)+ _console.print(" [ok]→ install folder deleted.[/]")+ return True+ except Exception as exc: # noqa: BLE001+ _console.print(+ f" [bad]⚠ could not delete the folder: {escape(str(exc))}[/]\n"+ f" [muted]Delete it yourself: {escape(str(install_dir))}[/]"+ )+ return False+++# ---------------------------------------------------------------- orchestrator+def run_uninstall(+ *,+ assume_yes: bool = False,+ keep_keys: bool = False,+ keep_folder: bool = False,+ dry_run: bool = False,+) -> int:+ """Uninstall Personal Jarvis from this machine.++ Returns: 0 success, 1 aborted by the user, 2 not a Jarvis install.+ """+ plan = build_plan()++ if not plan.is_jarvis_install:+ _console.print(+ f"[bad]This does not look like a Personal Jarvis install:[/] "+ f"{escape(str(plan.install_dir))}\n[muted]Refusing to delete anything.[/]"+ )+ return 2++ _print_plan(plan, keep_keys=keep_keys, keep_folder=keep_folder)++ if dry_run:+ _console.print(" [muted](dry run — nothing was changed.)[/]\n")+ return 0++ if not assume_yes and not _confirm():+ _console.print(" [muted]Cancelled — nothing was changed.[/]\n")+ return 1++ _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+ # end this process's ability to do further work if it self-deletes.+ _remove_autostart()+ if not keep_keys:+ _remove_keys(plan.keyring_keys)+ if not keep_folder:+ _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")+ return 0diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex d9d0324ad3..f57c50b77a 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -1281,9 +1281,18 @@ async def delete_secret_value(key: str, request: Request) -> dict[str, Any]:async def brain_switch(body: SwitchBody, request: Request) -> dict[str, Any]:brain = getattr(request.app.state, "brain", None)if brain is None or not hasattr(brain, "switch"):+ # The brain is built on a background task after boot, so a very early+ # click can land before it is ready. It can also be genuinely absent on+ # a headless build. Either way "wait and retry" is the honest guidance —+ # the old "headless mode" wording misdiagnosed a fresh-install brain that+ # simply had not finished building yet (see BrainManager.from_tier_config+ # default-router synthesis).raise HTTPException(status_code=503,- detail="Brain-Manager nicht verfügbar (vermutlich Headless-Mode)",+ detail=(+ "Brain is still starting up or unavailable — wait a moment and "+ "try again. If it persists, check the server logs."+ ),)spec = get_spec(body.provider)diff --git a/tests/unit/brain/test_missing_router_block_default.py b/tests/unit/brain/test_missing_router_block_default.pynew file mode 100644index 0000000000..83f5dbc1ea--- /dev/null+++ b/tests/unit/brain/test_missing_router_block_default.py@@ -0,0 +1,58 @@+"""A fresh install ships no [brain.router] block — the brain must still build.++Regression (AP-23 "works on my machine"): ``jarvis.toml.example`` has a [brain]+table but NO [brain.router] sub-table, and neither the wizard, the installer,+nor onboarding writes one. ``BrainManager.from_tier_config`` used to RAISE+``BrainConfigError`` when ``config.brain.router`` was ``None``. On the desktop+that left ``app.state.brain = None``, which bricked both voice/chat AND the+provider-switch route — the latter then surfaced a misleading "headless mode"+503 on every "Set active" click. The maintainer never saw it because their own+jarvis.toml HAS the block.++The fix synthesizes a default router tier from the user's real ``brain.primary``+selection, so a fresh install boots a working brain regardless of provider.+"""+from __future__ import annotations++from jarvis.brain.manager import BrainManager+from jarvis.core.bus import EventBus+from jarvis.core.config import load_config+++def test_missing_router_block_does_not_raise_and_builds() -> None:+ # Simulate a fresh install: no [brain.router] block at all.+ cfg = load_config()+ cfg.brain.router = None+ cfg.brain.primary = "claude-api" # keyed in the test environment++ mgr = BrainManager.from_tier_config("router", cfg, EventBus())++ # It built (no BrainConfigError) and honours the configured primary.+ assert mgr.active_provider == "claude-api"+ assert mgr._config.brain.primary == "claude-api"+++def test_synthesized_tier_follows_the_users_primary_provider() -> None:+ # Provider-agnostic: the synthesized tier must follow whatever main provider+ # the fresh user configured, NOT a hardcoded claude-api (AP-6/AP-21).+ cfg = load_config()+ cfg.brain.router = None+ cfg.brain.primary = "gemini"++ mgr = BrainManager.from_tier_config("router", cfg, EventBus())++ assert mgr.active_provider == "gemini"+ assert mgr._config.brain.primary == "gemini"+++def test_missing_router_falls_back_to_routing_provider_when_primary_blank() -> None:+ # Defensive: an empty primary must not produce an empty-provider tier — it+ # falls back to routing_provider (which itself defaults to a real provider).+ cfg = load_config()+ cfg.brain.router = None+ cfg.brain.primary = ""+ cfg.brain.routing_provider = "claude-api"++ mgr = BrainManager.from_tier_config("router", cfg, EventBus())++ assert mgr.active_provider == "claude-api"diff --git a/tests/unit/setup/test_uninstall.py b/tests/unit/setup/test_uninstall.pynew file mode 100644index 0000000000..f6166ceec0--- /dev/null+++ b/tests/unit/setup/test_uninstall.py@@ -0,0 +1,191 @@+"""Unit tests for the cross-platform uninstaller (jarvis/setup/uninstall.py).++Safety: every test drives tmp_path directories or fakes — NOTHING here deletes a+real install, the real keyring, or the real autostart entry. The removal helpers+are monkeypatched to recorders whenever run_uninstall() is exercised.+"""+from __future__ import annotations++import sys+from pathlib import Path++import pytest++from jarvis.setup import uninstall+from jarvis.setup.uninstall import UninstallPlan+++def _fake_plan(+ tmp: Path, *, is_jarvis: bool = True, keys: list[str] | None = None+) -> UninstallPlan:+ return UninstallPlan(+ install_dir=tmp,+ is_jarvis_install=is_jarvis,+ autostart_supported=True,+ autostart_entry=str(tmp / "autostart.entry"),+ keyring_keys=list(keys or []),+ )+++def _use_plan(monkeypatch: pytest.MonkeyPatch, plan: UninstallPlan) -> None:+ monkeypatch.setattr(uninstall, "build_plan", lambda: plan)+++def _record_steps(monkeypatch: pytest.MonkeyPatch) -> list[str]:+ """Replace the three removal helpers with recorders; return the shared log."""+ called: list[str] = []+ 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"))+ return called+++# ---------------------------------------------------------------- guard+def test_looks_like_jarvis_install_true(tmp_path: Path) -> None:+ (tmp_path / "jarvis").mkdir()+ (tmp_path / "pyproject.toml").write_text(+ "[project]\nname='personal-jarvis'\n", encoding="utf-8"+ )+ assert uninstall._looks_like_jarvis_install(tmp_path) is True+++def test_looks_like_jarvis_install_false_for_random_dir(tmp_path: Path) -> None:+ (tmp_path / "docs").mkdir()+ assert uninstall._looks_like_jarvis_install(tmp_path) is False+++def test_build_plan_reflects_real_repo(monkeypatch: pytest.MonkeyPatch) -> None:+ # Keep it hermetic: no real keyring / autostart probing.+ monkeypatch.setattr(uninstall, "_autostart_state", lambda: (False, None))+ monkeypatch.setattr(uninstall, "_keyring_keys_present", lambda: [])+ plan = uninstall.build_plan()+ from jarvis.core import config as cfg++ assert plan.install_dir == Path(cfg.PROJECT_ROOT).resolve()+ # The repo we run from IS a Jarvis install.+ assert plan.is_jarvis_install is True+ assert plan.config_file == plan.install_dir / "jarvis.toml"+ assert plan.data_dir == plan.install_dir / "data"+++# ---------------------------------------------------------------- refusal+def test_run_uninstall_refuses_non_jarvis_dir(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ _use_plan(monkeypatch, _fake_plan(tmp_path, is_jarvis=False))+ called = _record_steps(monkeypatch)++ rc = uninstall.run_uninstall(assume_yes=True)+ assert rc == 2+ assert called == [] # refused before touching anything+++# ---------------------------------------------------------------- dry run+def test_dry_run_changes_nothing(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(dry_run=True)+ assert rc == 0+ assert called == []+++# ---------------------------------------------------------------- confirmation+def test_cancel_at_prompt_changes_nothing(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ _use_plan(monkeypatch, _fake_plan(tmp_path))+ monkeypatch.setattr(uninstall, "_confirm", lambda: False)+ called = _record_steps(monkeypatch)++ rc = uninstall.run_uninstall(assume_yes=False)+ assert rc == 1+ assert called == []+++ "answer,expected",+ [("yes", True), ("y", True), ("no", False), ("", False)],+)+def test_confirm_requires_yes(monkeypatch: pytest.MonkeyPatch, answer: str, expected: bool) -> None:+ monkeypatch.setattr("builtins.input", lambda _prompt="": answer)+ assert uninstall._confirm() is expected+++# ---------------------------------------------------------------- happy path+def test_assume_yes_runs_all_three_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+++def test_keep_keys_skips_key_removal(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ _use_plan(monkeypatch, _fake_plan(tmp_path, keys=["openai_api_key"]))+ called = _record_steps(monkeypatch)++ uninstall.run_uninstall(assume_yes=True, keep_keys=True)+ assert "keys" not in called+ assert "folder" in called+++def test_keep_folder_skips_folder_removal(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ _use_plan(monkeypatch, _fake_plan(tmp_path, keys=["openai_api_key"]))+ called = _record_steps(monkeypatch)++ uninstall.run_uninstall(assume_yes=True, keep_folder=True)+ assert "folder" not in called+ assert "keys" in called+++# ---------------------------------------------------------------- key removal+def test_remove_keys_deletes_each_present_key(monkeypatch: pytest.MonkeyPatch) -> None:+ deleted: list[str] = []+ monkeypatch.setattr(uninstall.cfg, "delete_secret", lambda key: (deleted.append(key) or True))+ n = uninstall._remove_keys(["openai_api_key", "gemini_api_key"])+ assert n == 2+ assert deleted == ["openai_api_key", "gemini_api_key"]+++# ---------------------------------------------------------------- folder removal+def test_remove_folder_direct_delete(tmp_path: Path) -> None:+ target = tmp_path / "install"+ target.mkdir()+ (target / "file.txt").write_text("x", encoding="utf-8")+ # The running interpreter is NOT inside tmp_path, so this is a direct rmtree+ # on every OS (no self-delete branch).+ assert uninstall._remove_folder(target) is True+ assert not target.exists()+++def test_running_inside_detects_self_host() -> None:+ exe_dir = Path(sys.executable).resolve().parent+ assert uninstall._running_inside(exe_dir) is True+++def test_running_inside_false_for_unrelated_dir(tmp_path: Path) -> None:+ assert uninstall._running_inside(tmp_path) is False+++def test_windows_self_deleter_writes_batch_and_spawns(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ spawned: list[list[str]] = []++ class _FakePopen:+ def __init__(self, args, **kwargs): # noqa: ANN001, ANN003+ spawned.append(args)++ monkeypatch.setattr(uninstall.subprocess, "Popen", _FakePopen)+ monkeypatch.setattr(uninstall.tempfile, "gettempdir", lambda: str(tmp_path))++ target = tmp_path / "somewhere" / ".personal-jarvis"+ uninstall._spawn_windows_self_deleter(target)++ # A batch was written and cmd was invoked on it.+ bats = list(tmp_path.glob("jarvis_uninstall_*.bat"))+ assert len(bats) == 1+ body = bats[0].read_text(encoding="utf-8")+ assert str(target) in body+ assert "rmdir /s /q" in body+ assert spawned and spawned[0][0] == "cmd"