Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(providers): make CLI readiness and login truthful
Ruben Lütked5ef72c09fb3
diff --git a/jarvis/agent_cli_probe.py b/jarvis/agent_cli_probe.pyindex 95372ee5bf..d41753aa63 100644--- a/jarvis/agent_cli_probe.py+++ b/jarvis/agent_cli_probe.py@@ -80,6 +80,8 @@ def _live_version(argv: list[str]) -> str | None:proc = subprocess.run([*argv, "--version"],capture_output=True,+ encoding="utf-8",+ errors="replace",text=True,timeout=_VERSION_TIMEOUT_S,creationflags=NO_WINDOW_CREATIONFLAGS,@@ -115,7 +117,7 @@ def test_claude() -> AgentCliTestResult:status = claude_auth.ClaudeAuthService().status()if not status.installed:return _not_installed(- "claude", "Install with: npm i -g @anthropic-ai/claude-code", t0+ "claude", claude_auth.claude_install_hint(), t0)# status() already paid a fresh (cache-cleared) --version spawn; a None# version therefore means the binary exists but did not answer.@@ -169,7 +171,10 @@ def test_codex(binary_path: str | None = None) -> AgentCliTestResult:def test_antigravity() -> AgentCliTestResult:- from jarvis.google_cli.auth_service import GoogleCliAuthService+ from jarvis.google_cli.auth_service import (+ GoogleCliAuthService,+ antigravity_install_hint,+ )from jarvis.google_cli.resolver import resolve_google_clit0 = time.monotonic()@@ -178,7 +183,7 @@ def test_antigravity() -> AgentCliTestResult:if cli is None:return _not_installed("antigravity",- "Install Antigravity (agy) or the Gemini CLI (npm i -g @google/gemini-cli)",+ antigravity_install_hint(),t0,)# The resolver never runs the binary — do it here so "installed" is provendiff --git a/jarvis/brain/app_control.py b/jarvis/brain/app_control.pyindex e672986936..c91bef58ec 100644--- a/jarvis/brain/app_control.py+++ b/jarvis/brain/app_control.py@@ -646,18 +646,31 @@ async def _switch_subagent(}if canon in ANTIGRAVITY_SUBAGENT_SLUGS:+ antigravity_status = Nonetry:- from jarvis.google_cli.auth_service import GoogleCliAuthService+ from jarvis.google_cli.auth_service import (+ GoogleCliAuthService,+ antigravity_provider_ready,+ )antigravity_status = GoogleCliAuthService().status()- antigravity_connected = (- antigravity_status.connected- and antigravity_status.mode == "oauth-personal"- )- except Exception: # noqa: BLE001 — Google CLI absent is just "not connected"- antigravity_connected = False+ except Exception as exc: # noqa: BLE001 — absent CLI is a normal capability miss+ log.debug("Antigravity CLI readiness probe failed: %s", exc)has_key = bool(cfg_mod.get_jarvis_agent_secret("gemini"))- if not (antigravity_connected or has_key):+ if antigravity_status is None or not antigravity_status.installed:+ return {+ "ok": False,+ "error_kind": "subagent_unavailable",+ "error": (+ "Antigravity is not installed. Install the agy or Gemini CLI, "+ f"or select the Google Gemini {brand} provider for key-only "+ "execution."+ ),+ }+ if not antigravity_provider_ready(+ antigravity_status,+ api_key_present=has_key,+ ):return {"ok": False,"error_kind": "missing_credential",diff --git a/jarvis/claude_auth.py b/jarvis/claude_auth.pyindex ad8adbd2a6..69a44f9855 100644--- a/jarvis/claude_auth.py+++ b/jarvis/claude_auth.py@@ -47,6 +47,11 @@ from pathlib import Pathfrom typing import Anyfrom jarvis.claude_credentials import ClaudeOAuthSnapshot, freshest_claude_oauth+from jarvis.core.interactive_terminal import (+ InteractiveTerminalLaunch,+ InteractiveTerminalUnavailable,+ launch_interactive_terminal,+)from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGSlog = logging.getLogger(__name__)@@ -62,20 +67,29 @@ _BINARY_CANDIDATES: tuple[str, ...] = ("claude", "claude.cmd", "claude.exe")# status() a pure file read. A failed probe is cached too, so an absent/hanging# claude never re-pays the timeout._VERSION_CACHE: dict[str, str | None] = {}+_AUTH_LOGIN_CACHE: dict[str, bool] = {}+++def claude_install_command(platform: str | None = None) -> str:+ """Official native installer for the current OS."""+ target = platform or sys.platform+ if target == "win32":+ return "irm https://claude.ai/install.ps1 | iex"+ return "curl -fsSL https://claude.ai/install.sh | bash"+++def claude_install_hint(platform: str | None = None) -> str:+ """Display-safe native install command plus the cross-platform npm fallback."""+ return (+ f"Install with: {claude_install_command(platform)} "+ "(npm alternative: npm i -g @anthropic-ai/claude-code)."+ )def clear_version_cache() -> None:"""Drop all cached ``claude --version`` results (tests / after a re-install)."""_VERSION_CACHE.clear()---# Visible-console flag for the interactive login (Windows only). The desktop app-# runs under pythonw.exe (no console); without a fresh console the user could not-# see the login prompt.-if sys.platform == "win32":- _NEW_CONSOLE_FLAGS: int = getattr(subprocess, "CREATE_NEW_CONSOLE", 0x00000010)-else:- _NEW_CONSOLE_FLAGS = 0+ _AUTH_LOGIN_CACHE.clear()# ----------------------------------------------------------------------@@ -205,8 +219,8 @@ class ClaudeAuthService:from jarvis.core.path_augment import ensure_cli_pathsensure_cli_paths()- except Exception: # noqa: BLE001 — a probe helper must never break status- pass+ except Exception as exc: # noqa: BLE001 — probe failure must not break status+ log.debug("CLI PATH augmentation failed during Claude discovery: %s", exc)candidates = (self._binary_path, *_BINARY_CANDIDATES)for name in candidates:@@ -225,6 +239,8 @@ class ClaudeAuthService:proc = subprocess.run([binary, "--version"],capture_output=True,+ encoding="utf-8",+ errors="replace",timeout=4.0,text=True,creationflags=NO_WINDOW_CREATIONFLAGS,@@ -237,6 +253,35 @@ class ClaudeAuthService:_VERSION_CACHE[binary] = versionreturn version+ def _supports_auth_login(self, binary: str) -> bool:+ """Whether this installed CLI exposes the modern ``auth login`` command."""+ if binary in _AUTH_LOGIN_CACHE:+ return _AUTH_LOGIN_CACHE[binary]+ try:+ proc = subprocess.run(+ [binary, "auth", "login", "--help"],+ capture_output=True,+ encoding="utf-8",+ errors="replace",+ timeout=4.0,+ text=True,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ supported = proc.returncode == 0+ except (OSError, subprocess.SubprocessError):+ supported = False+ _AUTH_LOGIN_CACHE[binary] = supported+ return supported++ def _login_argv(self, binary: str) -> list[str]:+ """Capability-selected login argv, with a first-run fallback for old CLIs."""+ if self._supports_auth_login(binary):+ return [binary, "auth", "login", "--claudeai"]+ # Older Claude Code releases have no auth subcommand. A bare interactive+ # start is their documented first-run login flow; passing ``/login`` as+ # a positional argv value incorrectly treats it as an initial prompt.+ return [binary]+def _credentials_path(self) -> Path:return Path(os.path.expanduser("~/.claude/.credentials.json"))@@ -292,8 +337,7 @@ class ClaudeAuthService:connected=False,mode="unknown",message=(- "Claude CLI is not installed "- "(run: npm i -g @anthropic-ai/claude-code)."+ f"Claude CLI is not installed. {claude_install_hint()}"),binary_path=self._binary_path,error="claude binary not found",@@ -362,7 +406,7 @@ class ClaudeAuthService:"Claude login token has expired — it refreshes itself the ""next time claude runs: open a terminal and run 'claude' ""once (only if that fails, sign in again via "- "'claude /login' or add an Anthropic API key)."+ "'claude auth login --claudeai' or add an Anthropic API key)."),version=version,subscription_type=sub_type,@@ -384,30 +428,30 @@ class ClaudeAuthService:api_key_present=self._api_key_present,)- def start_login(self) -> subprocess.Popen[bytes]:+ def start_login(self) -> InteractiveTerminalLaunch:"""Spawn the ``claude`` CLI in a visible console for the OAuth sign-in.- Raises if not installed. ``claude`` runs its own browser/device OAuth- flow; we spawn it detached with a fresh console so the prompt is reachable- under pythonw.exe. Best-effort, mirroring the Codex / Antigravity login.+ Modern releases expose ``claude auth login --claudeai``. Older releases+ fall back to a bare first-run session, which prompts for authentication.+ Both paths run in a real terminal; a headless host returns an honest+ capability error instead of starting an invisible process."""binary = self._resolve_binary()if binary is None:raise FileNotFoundError(- "Claude CLI is not installed "- "(run: npm i -g @anthropic-ai/claude-code)."+ f"Claude CLI is not installed. {claude_install_hint()}"+ )+ argv = self._login_argv(binary)+ log.info("Starting Claude subscription login in an external terminal")+ try:+ return launch_interactive_terminal(argv, title="Claude sign-in")+ except InteractiveTerminalUnavailable as exc:+ manual = (+ "claude auth login --claudeai" if len(argv) > 1 else "claude")- log.info("Starting 'claude' interactive login")- if sys.platform == "win32":- kwargs: dict[str, Any] = {"creationflags": _NEW_CONSOLE_FLAGS}- else:- kwargs = {- "stdout": subprocess.DEVNULL,- "stderr": subprocess.DEVNULL,- "stdin": subprocess.DEVNULL,- "start_new_session": True,- }- return subprocess.Popen([binary, "/login"], **kwargs) # noqa: S603 — fixed argv, shell=False+ raise InteractiveTerminalUnavailable(+ f"{exc} Open a terminal and run: {manual}"+ ) from excdef logout_blocking(self) -> tuple[bool, str | None]:"""Disconnect the Claude subscription login by removing its credentials.diff --git a/jarvis/core/interactive_terminal.py b/jarvis/core/interactive_terminal.pynew file mode 100644index 0000000000..d1a1e06a27--- /dev/null+++ b/jarvis/core/interactive_terminal.py@@ -0,0 +1,221 @@+"""Open an interactive CLI in a real, user-visible terminal window.++Desktop applications do not own an interactive TTY. Starting an OAuth CLI+with all three standard streams redirected to ``DEVNULL`` therefore launches a+process the user cannot see or answer. This helper provides one capability+probe for the three supported desktop families and fails honestly on a+headless host.++The command is always supplied as an argv sequence. Linux and Windows never+invoke a shell for native executables. macOS Terminal.app accepts only a shell+command through AppleScript, so every argument and the working directory are+quoted with :mod:`shlex` before the command crosses that boundary.+"""++from __future__ import annotations++import logging+import os+import shlex+import shutil+import subprocess+import sys+from collections.abc import Sequence+from dataclasses import dataclass+from pathlib import Path++from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS++log = logging.getLogger(__name__)+++class InteractiveTerminalUnavailable(RuntimeError):+ """Raised when the current session cannot open a graphical terminal."""+++@dataclass(frozen=True)+class InteractiveTerminalLaunch:+ """Display-safe result of opening an external terminal."""++ pid: int | None+ method: str+++def _validated_argv(argv: Sequence[str]) -> list[str]:+ values = [str(value) for value in argv]+ if not values or not values[0].strip():+ raise ValueError("An interactive terminal command requires an executable.")+ if any("\x00" in value for value in values):+ raise ValueError("Interactive terminal arguments cannot contain NUL bytes.")+ return values+++def _macos_script(argv: Sequence[str], cwd: Path) -> str:+ command = f"cd {shlex.quote(str(cwd))} && {shlex.join(argv)}"+ apple_string = command.replace("\\", "\\\\").replace('"', '\\"')+ return f'tell application "Terminal"\nactivate\ndo script "{apple_string}"\nend tell'+++def _launch_macos(+ argv: Sequence[str],+ *,+ cwd: Path,+) -> InteractiveTerminalLaunch:+ osascript = shutil.which("osascript")+ if not osascript:+ raise InteractiveTerminalUnavailable(+ "macOS Terminal could not be opened because osascript is unavailable."+ )+ try:+ result = subprocess.run(+ [osascript, "-e", _macos_script(argv, cwd)],+ capture_output=True,+ text=True,+ timeout=8.0,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ except (OSError, subprocess.SubprocessError) as exc:+ raise InteractiveTerminalUnavailable(+ "macOS Terminal could not be opened from this session."+ ) from exc+ if result.returncode != 0:+ log.warning("macOS Terminal launch failed with exit code %s", result.returncode)+ raise InteractiveTerminalUnavailable(+ "macOS Terminal could not be opened from this session."+ )+ log.info("Opened interactive CLI in macOS Terminal")+ return InteractiveTerminalLaunch(pid=None, method="macos-terminal")+++def _windows_command(argv: Sequence[str]) -> list[str]:+ suffix = Path(argv[0]).suffix.lower()+ if suffix in {".cmd", ".bat"}:+ comspec = os.environ.get("COMSPEC") or shutil.which("cmd.exe") or "cmd.exe"+ return [comspec, "/d", "/k", subprocess.list2cmdline(list(argv))]+ if suffix == ".ps1":+ powershell = shutil.which("pwsh.exe") or shutil.which("powershell.exe")+ if not powershell:+ raise InteractiveTerminalUnavailable(+ "The CLI is a PowerShell script, but no PowerShell executable was found."+ )+ return [powershell, "-NoExit", "-NoLogo", "-File", *argv]+ return list(argv)+++def _launch_windows(+ argv: Sequence[str],+ *,+ cwd: Path,+) -> InteractiveTerminalLaunch:+ flags = getattr(subprocess, "CREATE_NEW_CONSOLE", 0x00000010) | getattr(+ subprocess, "CREATE_NEW_PROCESS_GROUP", 0x00000200+ )+ try:+ process = subprocess.Popen( # noqa: S603 - validated argv, shell=False+ _windows_command(argv),+ cwd=str(cwd),+ creationflags=flags,+ close_fds=True,+ )+ except OSError as exc:+ raise InteractiveTerminalUnavailable(+ "Windows could not open a visible console for the login command."+ ) from exc+ log.info("Opened interactive CLI in a Windows console")+ return InteractiveTerminalLaunch(pid=process.pid, method="windows-console")+++def _linux_terminal_command(+ name: str,+ executable: str,+ argv: Sequence[str],+ *,+ title: str,+) -> list[str]:+ if name == "gnome-terminal":+ return [executable, "--title", title, "--", *argv]+ if name == "konsole":+ return [executable, "--new-tab", "-p", f"tabtitle={title}", "-e", *argv]+ if name == "kitty":+ return [executable, "--title", title, *argv]+ if name == "alacritty":+ return [executable, "--title", title, "-e", *argv]+ if name == "xterm":+ return [executable, "-T", title, "-e", *argv]+ return [executable, "-e", *argv]+++def _launch_linux(+ argv: Sequence[str],+ *,+ cwd: Path,+ title: str,+) -> InteractiveTerminalLaunch:+ if not (os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")):+ raise InteractiveTerminalUnavailable(+ "No graphical terminal is available in this headless Linux session."+ )++ failures: list[str] = []+ for name in (+ "x-terminal-emulator",+ "gnome-terminal",+ "konsole",+ "kitty",+ "alacritty",+ "xterm",+ ):+ executable = shutil.which(name)+ if not executable:+ continue+ try:+ process = subprocess.Popen( # noqa: S603 - validated argv, shell=False+ _linux_terminal_command(name, executable, argv, title=title),+ cwd=str(cwd),+ start_new_session=True,+ close_fds=True,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ except OSError:+ failures.append(name)+ continue+ log.info("Opened interactive CLI in Linux terminal %s", name)+ return InteractiveTerminalLaunch(pid=process.pid, method=name)++ if failures:+ log.warning("Linux terminal candidates failed to start: %s", failures)+ raise InteractiveTerminalUnavailable(+ "No supported graphical terminal emulator was found in this Linux session."+ )+++def launch_interactive_terminal(+ argv: Sequence[str],+ *,+ title: str,+ cwd: Path | None = None,+) -> InteractiveTerminalLaunch:+ """Open ``argv`` in a visible terminal, or raise an honest capability error.++ Windows receives a fresh console, macOS uses Terminal.app, and Linux probes+ common terminal emulators only when a graphical display is present. A+ headless server never starts an invisible OAuth process.+ """+ command = _validated_argv(argv)+ workdir = Path(cwd) if cwd is not None else Path.home()+ if sys.platform == "win32":+ return _launch_windows(command, cwd=workdir)+ if sys.platform == "darwin":+ return _launch_macos(command, cwd=workdir)+ if sys.platform.startswith("linux"):+ return _launch_linux(command, cwd=workdir, title=title)+ raise InteractiveTerminalUnavailable(+ f"Interactive terminal launch is not supported on platform {sys.platform!r}."+ )+++__all__ = [+ "InteractiveTerminalLaunch",+ "InteractiveTerminalUnavailable",+ "launch_interactive_terminal",+]diff --git a/jarvis/core/path_augment.py b/jarvis/core/path_augment.pyindex c93304f42e..cb55d37430 100644--- a/jarvis/core/path_augment.py+++ b/jarvis/core/path_augment.py@@ -3,12 +3,12 @@GUI-launched processes do not inherit the user's shell PATH: on macOS an appstarted from Finder/Dock/launchd gets the minimal ``/usr/bin:/bin:/usr/sbin:/sbin`` (no Homebrew, no npm-global, no ``~/.local/bin``), and on Windows a-winget install appends its ``WinGet\\Links`` shim dir to the *registry* PATH,-which already-running processes never see. Every ``shutil.which``-based CLI-probe (claude / codex / gemini / node / npm, the CLI-tools catalog prober,-worker spawns) then reports a perfectly-installed binary as "not installed" —-the 2026-07-18 Mac-test-machine symptom: Claude Code installed via the shell,-the desktop app insisting it is missing.+fresh installer can update only the registry PATH or place a binary in an app-+specific user directory. Already-running processes see neither change. Every+``shutil.which``-based CLI probe (claude / codex / agy / gemini / node / npm,+the CLI-tools catalog prober, worker spawns) then reports a perfectly-installed+binary as "not installed" — the 2026-07-18 Mac-test-machine symptom: Claude+Code installed via the shell, the desktop app insisting it is missing.``ensure_cli_paths()`` appends the well-known, actually-existing install dirsto ``os.environ["PATH"]``. Existing entries keep priority — only *missing*@@ -70,6 +70,8 @@ def _windows_candidates() -> list[str]:dirs: list[str] = []local = os.environ.get("LOCALAPPDATA")if local:+ # The official Antigravity PowerShell/CMD installer uses this directory.+ dirs.append(os.path.join(local, "agy", "bin"))# winget's shim dir lands on the *registry* PATH only — a running# process (and every subprocess it spawns) misses fresh installs.dirs.append(os.path.join(local, "Microsoft", "WinGet", "Links"))diff --git a/jarvis/google_cli/auth_service.py b/jarvis/google_cli/auth_service.pyindex 224c092080..bc91472e1a 100644--- a/jarvis/google_cli/auth_service.py+++ b/jarvis/google_cli/auth_service.py@@ -15,23 +15,34 @@ from __future__ import annotationsimport jsonimport loggingimport os-import subprocessimport sysfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any+from jarvis.core.interactive_terminal import (+ InteractiveTerminalLaunch,+ InteractiveTerminalUnavailable,+ launch_interactive_terminal,+)from jarvis.google_cli.resolver import GoogleCli, resolve_google_clilog = logging.getLogger(__name__)-# Visible-console flag for the deliberate, user-initiated login (Windows only).-# The desktop app runs under pythonw.exe (no console); without a fresh console-# the user could not see the device/OAuth URL if the auto browser-open fails.-if sys.platform == "win32":- _NEW_CONSOLE_FLAGS: int = getattr(subprocess, "CREATE_NEW_CONSOLE", 0x00000010)-else:- _NEW_CONSOLE_FLAGS = 0+def antigravity_install_command(platform: str | None = None) -> str:+ """Official Antigravity installer for the current OS."""+ target = platform or sys.platform+ if target == "win32":+ return "irm https://antigravity.google/cli/install.ps1 | iex"+ return "curl -fsSL https://antigravity.google/cli/install.sh | bash"+++def antigravity_install_hint(platform: str | None = None) -> str:+ """Display-safe Antigravity command plus the cross-platform Gemini fallback."""+ return (+ f"Install Antigravity with: {antigravity_install_command(platform)} "+ "(Gemini CLI alternative: npm i -g @google/gemini-cli)."+ )def _gemini_home() -> Path:@@ -131,6 +142,21 @@ class GoogleCliAuthStatus:}+def antigravity_provider_ready(+ status: GoogleCliAuthStatus,+ *,+ api_key_present: bool,+) -> bool:+ """Whether the Antigravity CLI provider can be selected honestly.++ The separate Google Gemini provider owns key-only execution. Antigravity is+ a CLI provider, so even its optional API-key billing path must not paint the+ card ready or permit selection when no executable is installed.+ """+ oauth_connected = status.connected and status.mode == "oauth-personal"+ return status.installed and (oauth_connected or api_key_present)++class GoogleCliAuthService:"""Status / login / logout for the official Google agent CLI.@@ -145,8 +171,8 @@ class GoogleCliAuthService:from jarvis.core.path_augment import ensure_cli_pathsensure_cli_paths()- except Exception: # noqa: BLE001 — a probe helper must never break status- pass+ except Exception as exc: # noqa: BLE001 — probe failure must not break status+ log.debug("CLI PATH augmentation failed during Google discovery: %s", exc)return resolve_google_cli()def _read_json(self, name: str) -> dict[str, Any]:@@ -160,10 +186,7 @@ class GoogleCliAuthService:cli = self._resolve()if cli is None:return GoogleCliAuthStatus(- message=(- "No Google CLI found — install Antigravity (agy) or the "- "Gemini CLI, then sign in with Google."- ),+ message=f"No Google CLI found. {antigravity_install_hint()}",error="no google cli binary",)@@ -207,34 +230,30 @@ class GoogleCliAuthService:binary_path=(cli.argv_prefix[0] if cli.argv_prefix else ""),)- def start_login(self) -> subprocess.Popen[bytes]:+ def start_login(self) -> InteractiveTerminalLaunch:"""Spawn the official CLI login in a visible console. Raises if absent.Neither CLI has a dedicated ``login`` subcommand — verified 2026-06-21,``agy login`` simply HANGS (it is not a real subcommand; ``agy help``lists only changelog/help/install/models/plugin/update). Both ``agy`` andthe Gemini CLI drop into the interactive "Sign in with Google" flow on a- bare run, so we launch the bare binary. Detached with a fresh console- (Windows) / new session (POSIX) so the device/OAuth URL is reachable- under pythonw.+ bare run, so we launch the bare binary in a real external terminal. A+ headless host fails honestly instead of starting an invisible process."""cli = self._resolve()if cli is None:raise FileNotFoundError(- "No Google CLI found (install agy or the Gemini CLI)."+ f"No Google CLI found. {antigravity_install_hint()}")argv = list(cli.argv_prefix) # bare interactive run — no `login` subcommandlog.info("Starting Google CLI login (interactive bare run, kind=%s)", cli.kind)- if sys.platform == "win32":- kwargs: dict[str, Any] = {"creationflags": _NEW_CONSOLE_FLAGS}- else:- kwargs = {- "stdout": subprocess.DEVNULL,- "stderr": subprocess.DEVNULL,- "stdin": subprocess.DEVNULL,- "start_new_session": True,- }- return subprocess.Popen(argv, **kwargs) # noqa: S603 — fixed argv, shell=False+ try:+ return launch_interactive_terminal(argv, title="Google sign-in")+ except InteractiveTerminalUnavailable as exc:+ manual = "agy" if cli.kind == "agy" else "gemini"+ raise InteractiveTerminalUnavailable(+ f"{exc} Open a terminal and run: {manual}"+ ) from excdef logout_blocking(self) -> tuple[bool, str | None]:"""Disconnect by removing every on-disk OAuth login file.diff --git a/jarvis/google_cli/resolver.py b/jarvis/google_cli/resolver.pyindex 419f58dfd1..cf2968d808 100644--- a/jarvis/google_cli/resolver.py+++ b/jarvis/google_cli/resolver.py@@ -119,15 +119,18 @@ def _default_npm_bundle(return None-def _agy_winget_roots() -> list[str]:- """Well-known locations where the winget ``Google.AntigravityCLI`` package and- its PATH shim drop ``agy.exe`` (Windows). winget appends ``WinGet\\Links`` to- the user PATH only after a shell restart, so the running process / a fresh- subprocess does not see ``agy`` on PATH yet — probe the install dirs directly.+def _agy_install_roots() -> list[str]:+ """Well-known native Antigravity install locations outside the live PATH.++ The official installer uses ``~/.local/bin`` on POSIX and+ ``%LOCALAPPDATA%\\agy\\bin`` on Windows. Legacy WinGet locations remain as+ compatibility probes. Direct probing also protects worker paths that call+ this resolver without first augmenting the process PATH."""- roots: list[str] = []+ roots: list[str] = [os.path.join(os.path.expanduser("~"), ".local", "bin")]local = os.environ.get("LOCALAPPDATA")if local:+ roots.insert(0, os.path.join(local, "agy", "bin"))roots.append(os.path.join(local, "Microsoft", "WinGet", "Links"))pkgs = os.path.join(local, "Microsoft", "WinGet", "Packages")with suppress(OSError):@@ -142,11 +145,13 @@ def _default_agy_path(roots: list[str] | None = None,isfile: Callable[[str], bool] = os.path.isfile,) -> str | None:- """Path to a winget-installed ``agy.exe``, or ``None``. Best-effort, never raises."""- for root in roots if roots is not None else _agy_winget_roots():- cand = os.path.join(root, "agy.exe")- if isfile(cand):- return cand+ """Path to a native ``agy`` binary, or ``None``. Best-effort, never raises."""+ names = ("agy.exe", "agy") if sys.platform == "win32" else ("agy", "agy.exe")+ for root in roots if roots is not None else _agy_install_roots():+ for name in names:+ cand = os.path.join(root, name)+ if isfile(cand):+ return candreturn None@@ -158,7 +163,7 @@ def resolve_google_cli() -> GoogleCli | None:"""Resolve the preferred official Google CLI. ``which``/``npm_bundle``/``agy_path`` are injectable seams for tests. Order: Antigravity ``agy`` (on- PATH, then its winget install dir) > Gemini CLI (on PATH, then npm bundle)."""+ PATH, then its native install dirs) > Gemini CLI (on PATH, then npm bundle)."""for name in _AGY:path = which(name)if path:diff --git a/jarvis/ui/web/antigravity_routes.py b/jarvis/ui/web/antigravity_routes.pyindex 71d6410111..b711543443 100644--- a/jarvis/ui/web/antigravity_routes.py+++ b/jarvis/ui/web/antigravity_routes.py@@ -14,13 +14,18 @@ other routers::"""from __future__ import annotations+import asyncioimport loggingimport sysfrom typing import Anyfrom fastapi import APIRouter, HTTPException-from jarvis.google_cli.auth_service import GoogleCliAuthService+from jarvis.core.interactive_terminal import InteractiveTerminalUnavailable+from jarvis.google_cli.auth_service import (+ GoogleCliAuthService,+ antigravity_install_command,+)log = logging.getLogger(__name__)@@ -30,17 +35,12 @@ router = APIRouter(prefix="/api", tags=["antigravity"])def _install_hint() -> str:"""OS-appropriate install command for an official Google CLI.- Windows ships ``agy`` via winget (the ``curl … | bash`` script does not run- in PowerShell/cmd); macOS/Linux use the install script. The cross-platform- Gemini-CLI npm fallback works on every OS, so it is always offered too.+ Windows uses the official PowerShell installer; macOS/Linux use the official+ shell installer. The cross-platform Gemini-CLI npm fallback is always+ offered too."""npm_fallback = "npm i -g @google/gemini-cli"- if sys.platform == "win32":- return f"winget install Google.AntigravityCLI (or: {npm_fallback})"- return (- "curl -fsSL https://antigravity.google/cli/install.sh | bash"- f" (or: {npm_fallback})"- )+ return f"{antigravity_install_command(sys.platform)} (or: {npm_fallback})"@router.get("/antigravity/status")@@ -56,8 +56,6 @@ async def antigravity_test() -> dict[str, Any]:Re-augments PATH first, so a CLI installed after app start is found withouta restart. Runs off the event loop — the probe spawns the real binary."""- import asyncio-from jarvis.agent_cli_probe import test_antigravityreturn (await asyncio.to_thread(test_antigravity)).to_dict()@@ -74,15 +72,21 @@ async def antigravity_login() -> dict[str, Any]:detail={"message": "No Google CLI found", "install_command": _install_hint()},)try:- proc = service.start_login()+ launch = await asyncio.to_thread(service.start_login)except FileNotFoundError as exc:raise HTTPException(status_code=409, detail=str(exc)) from exc+ except InteractiveTerminalUnavailable as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from excexcept Exception as exc: # noqa: BLE001raise HTTPException(status_code=500,detail=f"Google login could not be started: {type(exc).__name__}: {exc}",) from exc- return {"ok": True, "pid": proc.pid, "message": "Google login was started in the terminal"}+ return {+ "ok": True,+ "pid": launch.pid,+ "message": "Google login was started in the terminal",+ }@router.post("/antigravity/logout")diff --git a/jarvis/ui/web/claude_routes.py b/jarvis/ui/web/claude_routes.pyindex aa3fa19154..a3ddaab9c3 100644--- a/jarvis/ui/web/claude_routes.py+++ b/jarvis/ui/web/claude_routes.py@@ -20,19 +20,19 @@ connection booleans."""from __future__ import annotations+import asyncioimport loggingfrom typing import Anyfrom fastapi import APIRouter, HTTPException-from jarvis.claude_auth import ClaudeAuthService+from jarvis.claude_auth import ClaudeAuthService, claude_install_command+from jarvis.core.interactive_terminal import InteractiveTerminalUnavailablelog = logging.getLogger(__name__)router = APIRouter(prefix="/api", tags=["claude"])-_INSTALL_HINT = "npm i -g @anthropic-ai/claude-code"-def _real_api_key_present() -> bool:"""True when a CLASSIC Anthropic API key (sk-ant-api…) is stored.@@ -68,8 +68,6 @@ async def claude_test() -> dict[str, Any]:Re-augments PATH first, so a CLI installed after app start is found withouta restart. Runs off the event loop — the probe spawns the real binary."""- import asyncio-from jarvis.agent_cli_probe import test_claudereturn (await asyncio.to_thread(test_claude)).to_dict()@@ -83,18 +81,27 @@ async def claude_login() -> dict[str, Any]:if not status.installed:raise HTTPException(status_code=409,- detail={"message": "Claude CLI is not installed", "install_command": _INSTALL_HINT},+ detail={+ "message": "Claude CLI is not installed",+ "install_command": claude_install_command(),+ },)try:- proc = service.start_login()+ launch = await asyncio.to_thread(service.start_login)except FileNotFoundError as exc:raise HTTPException(status_code=409, detail=str(exc)) from exc+ except InteractiveTerminalUnavailable as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from excexcept Exception as exc: # noqa: BLE001raise HTTPException(status_code=500,detail=f"Claude login could not be started: {type(exc).__name__}: {exc}",) from exc- return {"ok": True, "pid": proc.pid, "message": "Claude login was started in the terminal"}+ return {+ "ok": True,+ "pid": launch.pid,+ "message": "Claude login was started in the terminal",+ }@router.post("/claude/logout")diff --git a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsxindex ef42d04229..e0f3036375 100644--- a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx+++ b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx@@ -990,9 +990,13 @@ function AntigravityConnectionCard({const { activating, activate } = useSubagentActivate(row, onChanged);const connected = Boolean(status?.connected && status.mode === "oauth-personal");const installed = status?.installed ?? false;- const apiKeyReady = Boolean(row?.api_key_set);- const usable = connected || apiKeyReady;- const isActive = Boolean(row?.is_active_brain);+ const apiKeyReady = Boolean(installed && row?.api_key_set);+ // `/api/jarvis-agent/status.key_set` is the canonical readiness decision.+ // Keep the independent live status gate as defense against two parallel+ // responses straddling an install/uninstall. A Gemini key alone belongs to+ // the separate Google Gemini card and must never make this CLI card ready.+ const usable = Boolean(installed && row?.key_set);+ const isActive = Boolean(usable && row?.is_active_brain);const detail = connected? status?.user_email? `Connected as ${status.user_email}`@@ -1044,7 +1048,7 @@ function AntigravityConnectionCard({badge={<StatusPill state={isActive ? "active" : usable ? "ready" : "open"} />}subtitle={detail}warning={- !installed && !apiKeyReady && (+ !installed && (<CardHint icon={Terminal}>Install Antigravity or the Gemini CLI before connecting.</CardHint>@@ -1469,4 +1473,3 @@ function SubagentActiveControl({</label>);}-diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.antigravity.test.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.antigravity.test.tsxindex 5210434f0b..f7f3847e9c 100644--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.antigravity.test.tsx+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.antigravity.test.tsx@@ -301,6 +301,34 @@ describe("ApiKeysView — Antigravity (Google subscription) OAuth card", () => {).toBeTruthy();});+ it("does not show Ready when a Gemini key exists but the CLI is missing", async () => {+ const routes = routesFor(antigravityMissing());+ routes["/api/jarvis-agent/status"] = () => ({+ body: {+ ...JARVIS_AGENT_EMPTY,+ mapping: [+ {+ ...JARVIS_AGENT_EMPTY.mapping[0],+ key_set: false,+ api_key_set: true,+ is_active_brain: true,+ },+ ],+ },+ });+ installFetchMock(routes);+ render(<ApiKeysView />);+ fireEvent.click(screen.getByRole("tab", { name: /-agents$/i }));++ await waitFor(() => expect(screen.getByText("open")).toBeTruthy());+ expect(screen.queryByText("ready")).toBeNull();+ expect(screen.queryByText("active")).toBeNull();+ expect(screen.queryByRole("radio")).toBeNull();+ expect(+ screen.getByText("Install Antigravity or the Gemini CLI before connecting."),+ ).toBeTruthy();+ });+it("disconnects via POST /api/antigravity/logout", async () => {const { calls } = installFetchMock(routesFor(antigravityDescriptor()));render(<ApiKeysView />);diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex c78d91fcec..66ec43db8e 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -3011,27 +3011,37 @@ async def jarvis_agent_switch(body: SwitchBody, request: Request) -> dict[str, A"restart_required": True,}- # Antigravity (Google subscription) is a DIRECT worker over the OAuth Google- # CLI — no Jarvis-Agent worker-harness slug, no API key. Mirror of the- # codex branch: gate on the OAuth login being present, then persist the- # "antigravity" slug.+ # Antigravity is a DIRECT worker over the Google CLI, with subscription OAuth+ # or API-key billing only after that CLI capability exists. Key-only execution+ # belongs to the separate Google Gemini provider.from jarvis.missions.worker_runtime.provider_map import (ANTIGRAVITY_SUBAGENT_CANONICAL,ANTIGRAVITY_SUBAGENT_SLUGS,)if provider in ANTIGRAVITY_SUBAGENT_SLUGS:- from jarvis.google_cli.auth_service import GoogleCliAuthService-- # Dual billing (mirror of codex): the Google subscription OAuth login OR- # a Gemini API key (per token). Either is enough to run the worker.- def _antigravity_connected() -> bool:- status = GoogleCliAuthService().status()- return status.connected and status.mode == "oauth-personal"+ from jarvis.google_cli.auth_service import (+ GoogleCliAuthService,+ antigravity_provider_ready,+ )- antigravity_connected = await asyncio.to_thread(_antigravity_connected)+ # Dual billing (mirror of Codex): subscription OAuth or a Gemini API key,+ # but both paths stay gated on the local CLI provider being installed.+ antigravity_status = await asyncio.to_thread(GoogleCliAuthService().status)antigravity_key = bool(cfg_mod.get_jarvis_agent_secret("gemini"))- if not (antigravity_connected or antigravity_key):+ if not antigravity_status.installed:+ raise HTTPException(+ status_code=409,+ detail=(+ "Antigravity is not installed — install agy or the Gemini "+ "CLI, or select the separate Google Gemini provider for "+ "key-only execution."+ ),+ )+ if not antigravity_provider_ready(+ antigravity_status,+ api_key_present=antigravity_key,+ ):raise HTTPException(status_code=409,detail=(diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex 931e57dafa..f1cf70c5f7 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -1106,24 +1106,34 @@ class WebServer:# Antigravity is a DIRECT worker (GoogleCliWorker over the official# agy/Gemini CLI) with no worker slug, so it is not in MAPPINGS —# the Google sibling of Codex. Dual billing, mirror of Codex: the- # Google subscription OAuth login OR a Gemini API key (per token).- # "key_set" is true when either is present.+ # installed Google CLI plus either its subscription OAuth login or+ # a Gemini API key (per token). A key cannot replace the executable.+ antigravity_status = Nonetry:- from jarvis.google_cli.auth_service import GoogleCliAuthService+ from jarvis.google_cli.auth_service import (+ GoogleCliAuthService,+ antigravity_provider_ready,+ )antigravity_status = GoogleCliAuthService().status()- antigravity_installed = antigravity_status.installedantigravity_connected = (antigravity_status.connectedand antigravity_status.mode == "oauth-personal")except Exception: # noqa: BLE001- antigravity_installed = Falseantigravity_connected = Falsetry:antigravity_key = bool(get_jarvis_agent_secret("gemini"))except Exception: # noqa: BLE001antigravity_key = False+ antigravity_ready = (+ antigravity_provider_ready(+ antigravity_status,+ api_key_present=antigravity_key,+ )+ if antigravity_status is not None+ else False+ )mapping_rows.append({"jarvis": "antigravity",@@ -1136,8 +1146,7 @@ class WebServer:# Antigravity showed Ready although never installed, then# every run died at spawn). Mirrors the Codex row's# installed-gate below.- "key_set": antigravity_connected- or (antigravity_installed and antigravity_key),+ "key_set": antigravity_ready,"api_key_set": antigravity_key,"dedicated_key_set": False,"shared_key_set": False,diff --git a/tests/integration/test_antigravity_routes.py b/tests/integration/test_antigravity_routes.pyindex 85651f0ffb..06cd109ed9 100644--- a/tests/integration/test_antigravity_routes.py+++ b/tests/integration/test_antigravity_routes.py@@ -4,6 +4,7 @@ from __future__ import annotationsfrom fastapi import FastAPIfrom fastapi.testclient import TestClient+from jarvis.core.interactive_terminal import InteractiveTerminalUnavailablefrom jarvis.google_cli.auth_service import GoogleCliAuthStatusfrom jarvis.ui.web import antigravity_routes@@ -63,6 +64,20 @@ def test_login_ok_when_installed(monkeypatch):assert resp.json()["pid"] == 999+def test_login_409_when_no_graphical_terminal(monkeypatch):+ st = GoogleCliAuthStatus(installed=True, connected=False)+ client = _client(+ monkeypatch,+ status=st,+ login_raises=InteractiveTerminalUnavailable(+ "No graphical terminal. Open a terminal and run: agy"+ ),+ )+ resp = client.post("/api/antigravity/login")+ assert resp.status_code == 409+ assert "run: agy" in resp.json()["detail"]++def test_logout_ok(monkeypatch):st = GoogleCliAuthStatus(installed=True, connected=True)client = _client(monkeypatch, status=st)diff --git a/tests/integration/test_claude_routes.py b/tests/integration/test_claude_routes.pynew file mode 100644index 0000000000..8833341016--- /dev/null+++ b/tests/integration/test_claude_routes.py@@ -0,0 +1,77 @@+"""Routes for the Claude subscription CLI connection flow."""++from __future__ import annotations++from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.claude_auth import ClaudeAuthStatus+from jarvis.core.interactive_terminal import InteractiveTerminalUnavailable+from jarvis.ui.web import claude_routes+++def _client(monkeypatch, *, status: ClaudeAuthStatus, login_raises=None):+ class _FakeService:+ def status(self):+ return status++ def start_login(self):+ if login_raises is not None:+ raise login_raises+ return type("Launch", (), {"pid": 321})()++ def logout_blocking(self):+ return True, None++ monkeypatch.setattr(claude_routes, "_service", lambda: _FakeService())+ app = FastAPI()+ app.include_router(claude_routes.router)+ return TestClient(app)+++def test_status_surfaces_cli_snapshot(monkeypatch):+ client = _client(+ monkeypatch,+ status=ClaudeAuthStatus(+ installed=True,+ connected=True,+ mode="subscription",+ account_label="Claude Max",+ ),+ )+ response = client.get("/api/claude/status")+ assert response.status_code == 200+ assert response.json()["mode"] == "subscription"+++def test_login_rejects_missing_cli_with_install_command(monkeypatch):+ client = _client(+ monkeypatch,+ status=ClaudeAuthStatus(installed=False, connected=False),+ )+ response = client.post("/api/claude/login")+ assert response.status_code == 409+ assert response.json()["detail"]["install_command"]+++def test_login_returns_after_visible_terminal_launch(monkeypatch):+ client = _client(+ monkeypatch,+ status=ClaudeAuthStatus(installed=True, connected=False),+ )+ response = client.post("/api/claude/login")+ assert response.status_code == 200+ assert response.json()["pid"] == 321+++def test_login_headless_failure_is_an_honest_conflict(monkeypatch):+ client = _client(+ monkeypatch,+ status=ClaudeAuthStatus(installed=True, connected=False),+ login_raises=InteractiveTerminalUnavailable(+ "No graphical terminal. Open a terminal and run: claude auth login --claudeai"+ ),+ )+ response = client.post("/api/claude/login")+ assert response.status_code == 409+ assert "claude auth login" in response.json()["detail"]diff --git a/tests/integration/test_jarvis_agent_active_brain.py b/tests/integration/test_jarvis_agent_active_brain.pyindex 955c8ccb1a..5ec1d2aee2 100644--- a/tests/integration/test_jarvis_agent_active_brain.py+++ b/tests/integration/test_jarvis_agent_active_brain.py@@ -5,7 +5,7 @@ Root cause (2026-05-28): GET /api/jarvis-agent/status derived ``is_active_brain`from ``cfg.brain.primary`` — that is only the lightweight ROUTER brain(Gemini). The heavy-task subagent runs on ``[brain.sub_jarvis].provider``(claude-api -> ClaudeDirectWorker -> Claude Max OAuth). The UI therefore-showed "Google Gemini · aktiver Brain" while heavy work ran on Claude.+showed "Google Gemini · active brain" while heavy work ran on Claude.These tests pin the active brain to the subagent provider so the displayedbrain never drifts from the worker that runs (mirrors the routing source in@@ -383,10 +383,7 @@ def test_claude_api_row_key_set_via_max_oauth(monkeypatch: pytest.MonkeyPatch) -import jarvis.core.config as cfg_modmonkeypatch.setattr(cfg_mod, "get_secret", lambda *_a, **_k: None)- monkeypatch.setattr(- "jarvis.missions.isolation.env.read_live_claude_oauth_token",- lambda: "sk-ant-oat-live",- )+ _patch_claude_oauth(monkeypatch, "valid")cfg = load_config()row = next(r for r in _status(cfg)["mapping"] if r["jarvis"] == "claude-api")assert row["key_set"] is True@@ -478,6 +475,7 @@ def test_subagent_switch_409_claude_api_no_key_no_oauth(class _FakeGoogleCli:connected_value = True+ installed_value = Truedef __init__(self, *_a, **_k) -> None: # noqa: ANN002, ANN003pass@@ -486,17 +484,23 @@ class _FakeGoogleCli:from jarvis.google_cli.auth_service import GoogleCliAuthStatusreturn GoogleCliAuthStatus(- installed=True,+ installed=type(self).installed_value,connected=type(self).connected_value,mode="oauth-personal",cli_kind="agy",)-def _patch_antigravity(monkeypatch: pytest.MonkeyPatch, *, connected: bool) -> None:+def _patch_antigravity(+ monkeypatch: pytest.MonkeyPatch,+ *,+ connected: bool,+ installed: bool = True,+) -> None:"""Stub GoogleCliAuthService at its source so both the status endpoint andthe switch route (each lazy-imports it) pick up the fake."""_FakeGoogleCli.connected_value = connected+ _FakeGoogleCli.installed_value = installedmonkeypatch.setattr("jarvis.google_cli.auth_service.GoogleCliAuthService", _FakeGoogleCli)@@ -588,14 +592,33 @@ def test_antigravity_row_key_set_via_gemini_api_key(_patch_antigravity(monkeypatch, connected=False)monkeypatch.setattr(- cfg_mod, "get_secret",- lambda key, *a, **k: "AIza-fake" if key == "gemini_api_key" else None,+ cfg_mod,+ "get_jarvis_agent_secret",+ lambda provider: "AIza-fake" if provider == "gemini" else None,)cfg = load_config()row = next(r for r in _status(cfg)["mapping"] if r["jarvis"] == "antigravity")assert row["key_set"] is True+def test_antigravity_row_stays_locked_with_key_but_no_cli(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A Gemini key configures Gemini, but cannot install a missing CLI."""+ import jarvis.core.config as cfg_mod++ _patch_antigravity(monkeypatch, connected=False, installed=False)+ monkeypatch.setattr(+ cfg_mod,+ "get_jarvis_agent_secret",+ lambda provider: "AIza-fake" if provider == "gemini" else None,+ )+ cfg = load_config()+ row = next(r for r in _status(cfg)["mapping"] if r["jarvis"] == "antigravity")+ assert row["api_key_set"] is True+ assert row["key_set"] is False++def test_antigravity_row_billing_is_subscription_or_api(monkeypatch: pytest.MonkeyPatch,) -> None:@@ -617,10 +640,10 @@ def test_subagent_switch_accepts_antigravity_via_api_key(import jarvis.core.config as cfg_modimport jarvis.core.config_writer as config_writer- monkeypatch.setattr(cfg_mod, "get_provider_secret", lambda _p: None)monkeypatch.setattr(- cfg_mod, "get_secret",- lambda key, *a, **k: "AIza-fake" if key == "gemini_api_key" else None,+ cfg_mod,+ "get_jarvis_agent_secret",+ lambda provider: "AIza-fake" if provider == "gemini" else None,)_patch_antigravity(monkeypatch, connected=False)calls: list[str] = []@@ -633,3 +656,28 @@ def test_subagent_switch_accepts_antigravity_via_api_key(assert resp.status_code == 200, resp.textassert resp.json()["active"] == "antigravity"assert calls == ["antigravity"]+++def test_jarvis_agent_switch_rejects_antigravity_key_without_cli(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ import jarvis.core.config as cfg_mod+ import jarvis.core.config_writer as config_writer++ monkeypatch.setattr(+ cfg_mod,+ "get_jarvis_agent_secret",+ lambda provider: "AIza-fake" if provider == "gemini" else None,+ )+ _patch_antigravity(monkeypatch, connected=False, installed=False)+ persisted: list[str] = []+ monkeypatch.setattr(config_writer, "set_worker_provider", persisted.append)++ cfg = load_config()+ resp = _client(cfg).post(+ "/api/jarvis-agent/switch", json={"provider": "antigravity", "persist": True}+ )++ assert resp.status_code == 409+ assert "not installed" in resp.json()["detail"].lower()+ assert persisted == []diff --git a/tests/unit/core/test_interactive_terminal.py b/tests/unit/core/test_interactive_terminal.pynew file mode 100644index 0000000000..21ae258715--- /dev/null+++ b/tests/unit/core/test_interactive_terminal.py@@ -0,0 +1,152 @@+"""Cross-platform tests for the visible interactive-terminal capability."""++from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace++import pytest++from jarvis.core import interactive_terminal as terminal+++def test_macos_opens_terminal_app_with_shell_quoted_argv(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ captured: dict[str, object] = {}+ monkeypatch.setattr(terminal.sys, "platform", "darwin")+ monkeypatch.setattr(+ terminal.shutil,+ "which",+ lambda name: "/usr/bin/osascript" if name == "osascript" else None,+ )++ def fake_run(argv, **kwargs): # noqa: ANN001, ANN003+ captured["argv"] = argv+ captured["kwargs"] = kwargs+ return SimpleNamespace(returncode=0, stdout="", stderr="")++ monkeypatch.setattr(terminal.subprocess, "run", fake_run)+ launch = terminal.launch_interactive_terminal(+ ["/Users/Test User/.local/bin/claude", "auth", "login", "--claudeai"],+ title="Claude sign-in",+ cwd=Path("/Users/Test User"),+ )++ assert launch.method == "macos-terminal"+ assert launch.pid is None+ script = captured["argv"][2] # type: ignore[index]+ assert 'tell application "Terminal"' in script+ assert "'/Users/Test User/.local/bin/claude' auth login --claudeai" in script+ assert "cd '/Users/Test User'" in script+++def test_macos_launch_failure_is_honest(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(terminal.sys, "platform", "darwin")+ monkeypatch.setattr(terminal.shutil, "which", lambda _name: "/usr/bin/osascript")+ monkeypatch.setattr(+ terminal.subprocess,+ "run",+ lambda *_a, **_k: SimpleNamespace(returncode=1, stdout="", stderr="denied"),+ )++ with pytest.raises(terminal.InteractiveTerminalUnavailable, match="could not be opened"):+ terminal.launch_interactive_terminal(["claude"], title="Claude sign-in")+++def test_windows_native_binary_gets_a_fresh_visible_console(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ captured: dict[str, object] = {}+ monkeypatch.setattr(terminal.sys, "platform", "win32")++ def fake_popen(argv, **kwargs): # noqa: ANN001, ANN003+ captured["argv"] = argv+ captured["kwargs"] = kwargs+ return SimpleNamespace(pid=42)++ monkeypatch.setattr(terminal.subprocess, "Popen", fake_popen)+ launch = terminal.launch_interactive_terminal(+ [r"C:\Users\Test\.local\bin\claude.exe", "auth", "login"],+ title="Claude sign-in",+ )++ assert launch == terminal.InteractiveTerminalLaunch(42, "windows-console")+ assert captured["argv"] == [+ r"C:\Users\Test\.local\bin\claude.exe",+ "auth",+ "login",+ ]+ assert int(captured["kwargs"]["creationflags"]) & 0x00000010 # type: ignore[index]+++def test_windows_cmd_shim_runs_through_comspec(monkeypatch: pytest.MonkeyPatch) -> None:+ captured: dict[str, object] = {}+ monkeypatch.setattr(terminal.sys, "platform", "win32")+ monkeypatch.setenv("COMSPEC", r"C:\Windows\System32\cmd.exe")++ def fake_popen(argv, **_kwargs): # noqa: ANN001, ANN003+ captured["argv"] = argv+ return SimpleNamespace(pid=7)++ monkeypatch.setattr(terminal.subprocess, "Popen", fake_popen)+ terminal.launch_interactive_terminal(+ [r"C:\Users\Test\AppData\Roaming\npm\gemini.cmd"],+ title="Google sign-in",+ )++ argv = captured["argv"]+ assert argv[:3] == [r"C:\Windows\System32\cmd.exe", "/d", "/k"] # type: ignore[index]+ assert "gemini.cmd" in argv[3] # type: ignore[index]+++def test_linux_uses_available_graphical_terminal(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ captured: dict[str, object] = {}+ monkeypatch.setattr(terminal.sys, "platform", "linux")+ monkeypatch.setenv("WAYLAND_DISPLAY", "wayland-0")+ monkeypatch.delenv("DISPLAY", raising=False)+ monkeypatch.setattr(+ terminal.shutil,+ "which",+ lambda name: "/usr/bin/gnome-terminal" if name == "gnome-terminal" else None,+ )++ def fake_popen(argv, **kwargs): # noqa: ANN001, ANN003+ captured["argv"] = argv+ captured["kwargs"] = kwargs+ return SimpleNamespace(pid=91)++ monkeypatch.setattr(terminal.subprocess, "Popen", fake_popen)+ launch = terminal.launch_interactive_terminal(+ ["/home/test/.local/bin/agy"],+ title="Google sign-in",+ cwd=Path("/home/test"),+ )++ assert launch == terminal.InteractiveTerminalLaunch(91, "gnome-terminal")+ assert captured["argv"] == [+ "/usr/bin/gnome-terminal",+ "--title",+ "Google sign-in",+ "--",+ "/home/test/.local/bin/agy",+ ]+ assert captured["kwargs"]["start_new_session"] is True # type: ignore[index]+++def test_headless_linux_refuses_an_invisible_login(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(terminal.sys, "platform", "linux")+ monkeypatch.delenv("DISPLAY", raising=False)+ monkeypatch.delenv("WAYLAND_DISPLAY", raising=False)++ with pytest.raises(terminal.InteractiveTerminalUnavailable, match="headless Linux"):+ terminal.launch_interactive_terminal(["agy"], title="Google sign-in")+++def test_empty_command_is_rejected() -> None:+ with pytest.raises(ValueError, match="requires an executable"):+ terminal.launch_interactive_terminal([], title="Login")diff --git a/tests/unit/core/test_path_augment.py b/tests/unit/core/test_path_augment.pyindex 342f4ab794..55cb6ca6bb 100644--- a/tests/unit/core/test_path_augment.py+++ b/tests/unit/core/test_path_augment.py@@ -77,6 +77,17 @@ def test_candidates_are_platform_appropriate():assert any(d.endswith(os.path.join(".local", "bin")) for d in dirs)+def test_windows_candidates_cover_official_antigravity_installer(+ tmp_path, monkeypatch+):+ local = tmp_path / "LocalAppData"+ monkeypatch.setenv("LOCALAPPDATA", str(local))++ dirs = path_augment._windows_candidates()++ assert str(local / "agy" / "bin") in dirs++@pytest.mark.skipif(sys.platform == "win32", reason="POSIX candidate shape")def test_posix_candidates_cover_the_mac_report(monkeypatch):"""The 2026-07-18 Mac symptom: claude installed via npm/native installer,diff --git a/tests/unit/google_cli/test_auth_service.py b/tests/unit/google_cli/test_auth_service.pyindex d6e691f809..b50a89a22d 100644--- a/tests/unit/google_cli/test_auth_service.py+++ b/tests/unit/google_cli/test_auth_service.py@@ -159,13 +159,36 @@ def test_start_login_uses_bare_agy_not_login_subcommand(monkeypatch):svc._resolve = lambda: GoogleCli(kind="agy", argv_prefix=["agy.exe"]) # type: ignore[method-assign]captured: dict = {}- def _fake_popen(argv, **kw):+ def _fake_launch(argv, **kw):captured["argv"] = list(argv)- return object()+ captured["kwargs"] = kw+ return auth_mod.InteractiveTerminalLaunch(10, "test-terminal")- monkeypatch.setattr(auth_mod.subprocess, "Popen", _fake_popen)+ monkeypatch.setattr(auth_mod, "launch_interactive_terminal", _fake_launch)svc.start_login()assert captured["argv"] == ["agy.exe"] # bare binary, no "login"+ assert captured["kwargs"] == {"title": "Google sign-in"}+++def test_provider_ready_requires_cli_even_with_api_key():+ missing = auth_mod.GoogleCliAuthStatus(installed=False)+ assert not auth_mod.antigravity_provider_ready(missing, api_key_present=True)++ installed = auth_mod.GoogleCliAuthStatus(installed=True)+ assert auth_mod.antigravity_provider_ready(installed, api_key_present=True)++ oauth = auth_mod.GoogleCliAuthStatus(+ installed=True,+ connected=True,+ mode="oauth-personal",+ )+ assert auth_mod.antigravity_provider_ready(oauth, api_key_present=False)+++def test_install_command_is_platform_specific():+ assert auth_mod.antigravity_install_command("win32").startswith("irm ")+ assert auth_mod.antigravity_install_command("darwin").startswith("curl ")+ assert auth_mod.antigravity_install_command("linux").startswith("curl ")def test_logout_removes_creds_without_calling_agy_logout(tmp_path, monkeypatch):@@ -176,10 +199,6 @@ def test_logout_removes_creds_without_calling_agy_logout(tmp_path, monkeypatch):svc = GoogleCliAuthService()svc._resolve = lambda: GoogleCli(kind="agy", argv_prefix=["agy.exe"]) # type: ignore[method-assign]- def _no_run(*a, **k):- raise AssertionError("agy logout must not be invoked (no such subcommand)")-- monkeypatch.setattr(auth_mod.subprocess, "run", _no_run)ok, err = svc.logout_blocking()assert ok and err is Noneassert not (gem / "oauth_creds.json").is_file() # creds actually removeddiff --git a/tests/unit/google_cli/test_resolver.py b/tests/unit/google_cli/test_resolver.pyindex 3ebeb953e5..dc9933ee8e 100644--- a/tests/unit/google_cli/test_resolver.py+++ b/tests/unit/google_cli/test_resolver.py@@ -1,6 +1,8 @@"""Resolver order + fallback for the official Google agent CLI."""from __future__ import annotations+import os+from jarvis.google_cli.resolver import GoogleCli, resolve_google_cli@@ -67,10 +69,12 @@ def test_default_npm_bundle_none_when_absent(tmp_path):assert _default_npm_bundle(roots=[str(tmp_path)], which=lambda n: None) is None-def test_prefers_agy_via_winget_location_when_not_on_path(tmp_path):- """winget installs agy.exe but does not put it on the live PATH until a shell- restart, so resolve must probe the known install location (like the gemini- bundle fallback) and still PREFER agy over the gemini CLI."""+def test_prefers_agy_via_native_location_when_not_on_path(tmp_path):+ """A native install can be absent from the live GUI PATH after installation.++ The resolver must probe the known location and still prefer Antigravity over+ a Gemini CLI that happens to be on PATH.+ """agy = tmp_path / "agy.exe"agy.write_text("// stub")@@ -86,7 +90,7 @@ def test_prefers_agy_via_winget_location_when_not_on_path(tmp_path):assert cli.argv_prefix == [str(agy)]-def test_default_agy_path_finds_winget_binary(tmp_path):+def test_default_agy_path_finds_native_binary(tmp_path):from jarvis.google_cli.resolver import _default_agy_pathlinks = tmp_path / "WinGet" / "Links"@@ -94,3 +98,12 @@ def test_default_agy_path_finds_winget_binary(tmp_path):(links / "agy.exe").write_text("// stub")found = _default_agy_path(roots=[str(links)])assert found == str(links / "agy.exe")+++def test_agy_roots_include_official_windows_location(tmp_path, monkeypatch):+ from jarvis.google_cli.resolver import _agy_install_roots++ local = tmp_path / "LocalAppData"+ monkeypatch.setenv("LOCALAPPDATA", str(local))++ assert os.path.join(str(local), "agy", "bin") in _agy_install_roots()diff --git a/tests/unit/plugins/tool/test_app_control_tools.py b/tests/unit/plugins/tool/test_app_control_tools.pyindex 58d17b11ea..e38bafc20d 100644--- a/tests/unit/plugins/tool/test_app_control_tools.py+++ b/tests/unit/plugins/tool/test_app_control_tools.py@@ -208,6 +208,7 @@ async def test_switch_antigravity_allowed_as_subagent(monkeypatch, no_keys):from jarvis.brain.app_control import apply_provider_switchclass _Status:+ installed = Trueconnected = Truemode = "oauth-personal"@@ -231,6 +232,35 @@ async def test_switch_antigravity_allowed_as_subagent(monkeypatch, no_keys):assert cfg.brain.worker.provider == "antigravity"+async def test_switch_antigravity_rejects_key_without_cli(+ monkeypatch, configured_keys+):+ from jarvis.brain.app_control import apply_provider_switch++ class _Status:+ installed = False+ connected = False+ mode = "unknown"++ class _FakeGoogleCliAuthService:+ def status(self):+ return _Status()++ monkeypatch.setattr(+ "jarvis.google_cli.auth_service.GoogleCliAuthService",+ _FakeGoogleCliAuthService,+ )++ cfg = make_cfg(sub="gemini")+ res = await apply_provider_switch(+ "subagent", "antigravity", cfg=cfg, persist=False,+ )++ assert res["ok"] is False+ assert res["error_kind"] == "subagent_unavailable"+ assert cfg.brain.worker.provider == "gemini"++async def test_switch_codex_allowed_as_subagent(monkeypatch, no_keys):from jarvis.brain.app_control import apply_provider_switchdiff --git a/tests/unit/test_claude_auth.py b/tests/unit/test_claude_auth.pyindex 2dbdc572b7..5de9d61394 100644--- a/tests/unit/test_claude_auth.py+++ b/tests/unit/test_claude_auth.py@@ -144,7 +144,7 @@ def test_status_expired_subscription_is_not_connected(tmp_path, monkeypatch) ->assert st.installed is Trueassert st.connected is Falseassert "expired" in st.message.lower()- assert "/login" in st.message+ assert "auth login" in st.messagedef test_status_expired_oauth_falls_back_to_api_key(tmp_path, monkeypatch) -> None:@@ -299,3 +299,65 @@ def test_status_never_logs_secret(tmp_path, monkeypatch, caplog) -> None:with caplog.at_level("DEBUG"):svc.status()assert "sk-ant-oat01-SECRET" not in caplog.text+++def test_install_command_is_platform_specific() -> None:+ assert claude_auth.claude_install_command("win32").startswith("irm ")+ assert claude_auth.claude_install_command("darwin").startswith("curl ")+ assert claude_auth.claude_install_command("linux").startswith("curl ")+++def test_start_login_uses_modern_auth_command(monkeypatch) -> None:+ captured: dict[str, object] = {}+ svc = ClaudeAuthService()+ monkeypatch.setattr(svc, "_resolve_binary", lambda: "/opt/claude")+ monkeypatch.setattr(svc, "_supports_auth_login", lambda _binary: True)++ def fake_launch(argv, **kwargs): # noqa: ANN001, ANN003+ captured["argv"] = argv+ captured["kwargs"] = kwargs+ return claude_auth.InteractiveTerminalLaunch(17, "test-terminal")++ monkeypatch.setattr(claude_auth, "launch_interactive_terminal", fake_launch)+ launch = svc.start_login()++ assert launch.pid == 17+ assert captured["argv"] == [+ "/opt/claude",+ "auth",+ "login",+ "--claudeai",+ ]+ assert captured["kwargs"] == {"title": "Claude sign-in"}+++def test_start_login_old_cli_uses_bare_first_run(monkeypatch) -> None:+ captured: dict[str, object] = {}+ svc = ClaudeAuthService()+ monkeypatch.setattr(svc, "_resolve_binary", lambda: "/opt/claude")+ monkeypatch.setattr(svc, "_supports_auth_login", lambda _binary: False)++ def fake_launch(argv, **_kwargs): # noqa: ANN001, ANN003+ captured["argv"] = argv+ return claude_auth.InteractiveTerminalLaunch(None, "test-terminal")++ monkeypatch.setattr(claude_auth, "launch_interactive_terminal", fake_launch)+ svc.start_login()++ assert captured["argv"] == ["/opt/claude"]+++def test_start_login_headless_error_includes_manual_recovery(monkeypatch) -> None:+ svc = ClaudeAuthService()+ monkeypatch.setattr(svc, "_resolve_binary", lambda: "/opt/claude")+ monkeypatch.setattr(svc, "_supports_auth_login", lambda _binary: True)++ def unavailable(*_args, **_kwargs):+ raise claude_auth.InteractiveTerminalUnavailable("No graphical terminal.")++ monkeypatch.setattr(claude_auth, "launch_interactive_terminal", unavailable)+ with pytest.raises(+ claude_auth.InteractiveTerminalUnavailable,+ match="claude auth login --claudeai",+ ):+ svc.start_login()