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(desktop): restore dictation apps and other input tools inside the app window
Ruben Lütke320844c77357
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex f38ed31758..e6c68b2528 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -7483,3 +7483,77 @@ The user hung up via hotkey at 11:55:11.Related: BUG-102 (topology refresh), BUG-104 (rebuild seed), BUG-106(the answer itself also missed the Gulfstream G800, in service since2025 — fact-quality family, tracked there).++## BUG-109: every dictation app, text expander, and auto-type tool goes dead inside the Jarvis window — the desktop app was running elevated (HIGH, FIXED 2026-07-25)++**Symptom (desktop field report).** Dictation software — a dictation app in the+report, but the class is open: Windows Voice Access, a dictation app, Talon,+text expanders, clipboard managers, password-manager auto-type — works+everywhere on the machine except inside the Personal Jarvis desktop window.+The user speaks, the dictation app records and reports success, and no text+ever appears in the Jarvis chat box. Nothing logs an error on either side, so+from the outside it reads as "Jarvis breaks my dictation app".++**Root cause.** The desktop process was running **elevated** (HIGH integrity,+`elevated=True`), while every ordinary user application including the dictation+tool runs at MEDIUM integrity. Windows **UIPI** (User Interface Privilege+Isolation) forbids a lower-integrity process from injecting synthetic input+into, or reading the UI-Automation tree of, a higher-integrity window. Both+mechanisms every tool in this category depends on are therefore cut:++* **Field detection.** Measured against the live elevated window, a normal+ automation client saw **1** element and **0** text fields; an ordinary+ window in the same session yielded 418 elements / 80 fields.+* **Text insertion.** Microsoft documents that `SendInput` blocked by UIPI+ reports the failure through *neither* its return value *nor* `GetLastError`+ — which is exactly why the dictation app believes it succeeded.++The WebView engine was ruled out by control experiment: an identical+pywebview/WebView2 window launched **unelevated** accepted both synthetic+unicode typing and a Ctrl+V clipboard paste. Privilege level was the only+differing variable.++Two properties made this durable and invisible:++1. **Elevation is sticky.** `POST /api/settings/restart-app` spawns the+ relauncher as a child, so every in-app restart inherited the elevated+ token. Once elevated, always elevated.+2. **Nothing checked.** The app is *designed* to run unelevated — the+ autostart scheduled task pins `RunLevel=Limited` (see+ `jarvis/autostart/windows.py`) and privileged operations go through the+ separate helper in `jarvis/admin/` — but no code verified the assumption,+ so a single elevated manual start silently persisted across reboots.++**Fix.**+* `jarvis/platform/input_isolation.py` — cross-platform probe reporting+ whether outside input software can reach our window (Windows: token+ elevation; POSIX: euid 0). Fail-open: an unreadable privilege state reports+ `unknown` and warns about nothing, so no user is nagged on a guess.+* `jarvis/platform/deescalate.py` — relaunch through the elevated token's+ filtered companion token (`TokenLinkedToken` → `DuplicateTokenEx` →+ `CreateProcessWithTokenW`), landing the fresh window at ordinary integrity.+ Refuses honestly where no companion token exists (UAC disabled, built-in+ Administrator, SYSTEM) instead of quietly relaunching elevated again.+* `DesktopApp._schedule_restart(drop_elevation=...)` ++ `request_unelevated_restart()` — a failed de-escalation leaves the app UP+ and returns the reason; a restart that never comes back is worse than the+ defect.+* `GET /api/settings/input-isolation` + `POST /api/settings/restart-unelevated`+ (mission-guarded, `x-jarvis-dangerous`), hence CLI-reachable.+* `InputIsolationBanner` — app-wide alert naming the affected software in+ plain language with a one-click "restart without admin rights", localized in+ de/en/es. Renders nothing when the window is reachable.+* Boot-time warning from `_log_input_isolation()` on the background heavy-init+ task (AP-26), so a support log shows the condition.++**Regression guards.** `tests/unit/platform/test_input_isolation.py`,+`tests/unit/platform/test_deescalate.py`,+`tests/unit/ui/test_input_isolation_route.py`,+`src/components/layout/InputIsolationBanner.test.tsx`. All inject the privilege+verdict — none read the host's real state, so they hold on an elevated Windows+box, in a Linux container, and on a Mac.++**Class lesson.** "Works everywhere except in *this one app's window*" is the+signature of a privilege boundary, not of the app's UI framework. Check the+integrity levels of both processes *before* investigating the window toolkit —+the measurement takes seconds and the toolkit hypothesis costs hours.diff --git a/jarvis/platform/deescalate.py b/jarvis/platform/deescalate.pynew file mode 100644index 0000000000..ccb19f6a37--- /dev/null+++ b/jarvis/platform/deescalate.py@@ -0,0 +1,246 @@+"""Start a child process WITHOUT the elevation this process is carrying.++Why this exists: an app that was ever launched elevated stays elevated across+every in-app restart, and while elevated it is unreachable for dictation apps,+text expanders, and password-manager auto-type (see+``jarvis/platform/input_isolation.py`` for the measurement). Recovering has to+happen from inside the app — telling a user to hunt down how their app came to+be elevated is not a fix.++**How.** When UAC filters an administrator account, Windows issues *two* tokens+at logon: the full one the elevated process runs on, and a filtered+medium-integrity one hanging off it as ``TokenLinkedToken``. Duplicating that+linked token and launching through ``CreateProcessWithTokenW`` produces a child+at exactly the integrity level of any normally-started app — no Explorer COM+detour and no third-party dependency. ``CreateProcessWithTokenW`` needs+``SeImpersonatePrivilege``, which an elevated process holds.++**When it cannot work** (reported honestly, never faked): UAC disabled, the true+built-in Administrator account, or a Windows-service/SYSTEM context — there is+no filtered companion token to fall back to. POSIX hosts are a documented no-op:+dropping from root to "whoever ran sudo" is guesswork that would strand file+ownership, so we tell the user instead of guessing.+"""++from __future__ import annotations++import logging+import os+import sys+from dataclasses import dataclass++log = logging.getLogger(__name__)++#: ``CreateProcessWithTokenW`` logon flag: load the target user's profile.+_LOGON_WITH_PROFILE = 0x00000001+_CREATE_UNICODE_ENVIRONMENT = 0x00000400+_TOKEN_QUERY = 0x0008+_TOKEN_DUPLICATE = 0x0002+_TOKEN_ASSIGN_PRIMARY = 0x0001+_TOKEN_ALL_ACCESS = 0xF01FF+_TokenLinkedToken = 19+_SecurityImpersonation = 2+_TokenPrimary = 1+++@dataclass(frozen=True)+class DeescalationResult:+ """Outcome of an unelevated spawn attempt."""++ ok: bool+ pid: int | None+ detail: str+++def environment_block(env: dict[str, str]) -> str:+ """Windows ``CREATE_UNICODE_ENVIRONMENT`` block for ``env``.++ Format: ``NAME=VALUE\\0`` repeated, terminated by one extra ``\\0``. Windows+ expects the names sorted case-insensitively; an unsorted block is accepted by+ most APIs but is documented as undefined, and this runs on the restart path+ where a subtle failure is expensive to diagnose.++ Kept pure and module-level so the format is unit-testable off-Windows.+ """+ items = sorted(env.items(), key=lambda kv: kv[0].upper())+ return "".join(f"{name}={value}\0" for name, value in items) + "\0"+++def _spawn_unelevated_windows(+ argv: list[str], *, cwd: str, env: dict[str, str], creationflags: int+) -> DeescalationResult:+ import ctypes # noqa: PLC0415 — lazy so this module imports on every OS+ import subprocess # noqa: PLC0415+ from ctypes import wintypes # noqa: PLC0415++ advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)++ class STARTUPINFOW(ctypes.Structure):+ _fields_ = [+ ("cb", wintypes.DWORD),+ ("lpReserved", wintypes.LPWSTR),+ ("lpDesktop", wintypes.LPWSTR),+ ("lpTitle", wintypes.LPWSTR),+ ("dwX", wintypes.DWORD),+ ("dwY", wintypes.DWORD),+ ("dwXSize", wintypes.DWORD),+ ("dwYSize", wintypes.DWORD),+ ("dwXCountChars", wintypes.DWORD),+ ("dwYCountChars", wintypes.DWORD),+ ("dwFillAttribute", wintypes.DWORD),+ ("dwFlags", wintypes.DWORD),+ ("wShowWindow", wintypes.WORD),+ ("cbReserved2", wintypes.WORD),+ ("lpReserved2", ctypes.POINTER(ctypes.c_byte)),+ ("hStdInput", wintypes.HANDLE),+ ("hStdOutput", wintypes.HANDLE),+ ("hStdError", wintypes.HANDLE),+ ]++ class PROCESS_INFORMATION(ctypes.Structure):+ _fields_ = [+ ("hProcess", wintypes.HANDLE),+ ("hThread", wintypes.HANDLE),+ ("dwProcessId", wintypes.DWORD),+ ("dwThreadId", wintypes.DWORD),+ ]++ advapi32.CreateProcessWithTokenW.argtypes = [+ wintypes.HANDLE,+ wintypes.DWORD,+ wintypes.LPCWSTR,+ wintypes.LPWSTR,+ wintypes.DWORD,+ wintypes.LPVOID,+ wintypes.LPCWSTR,+ ctypes.POINTER(STARTUPINFOW),+ ctypes.POINTER(PROCESS_INFORMATION),+ ]+ advapi32.CreateProcessWithTokenW.restype = wintypes.BOOL++ token = wintypes.HANDLE()+ if not advapi32.OpenProcessToken(+ kernel32.GetCurrentProcess(),+ _TOKEN_QUERY | _TOKEN_DUPLICATE,+ ctypes.byref(token),+ ):+ return DeescalationResult(+ False, None, f"OpenProcessToken failed ({ctypes.get_last_error()})"+ )++ linked = wintypes.HANDLE()+ primary = wintypes.HANDLE()+ try:+ returned = wintypes.DWORD()+ if not advapi32.GetTokenInformation(+ token,+ _TokenLinkedToken,+ ctypes.byref(linked),+ ctypes.sizeof(linked),+ ctypes.byref(returned),+ ):+ # No filtered companion token: UAC off, the built-in Administrator,+ # or a SYSTEM context. Nothing to de-escalate to.+ return DeescalationResult(+ False,+ None,+ "This Windows account has no unelevated companion token "+ f"(error {ctypes.get_last_error()}), so the app cannot drop its "+ "administrator rights by itself.",+ )++ if not advapi32.DuplicateTokenEx(+ linked,+ _TOKEN_ALL_ACCESS | _TOKEN_ASSIGN_PRIMARY,+ None,+ _SecurityImpersonation,+ _TokenPrimary,+ ctypes.byref(primary),+ ):+ return DeescalationResult(+ False, None, f"DuplicateTokenEx failed ({ctypes.get_last_error()})"+ )++ startup = STARTUPINFOW()+ startup.cb = ctypes.sizeof(STARTUPINFOW)+ info = PROCESS_INFORMATION()+ block = ctypes.create_unicode_buffer(environment_block(env))+ # CreateProcessWithTokenW writes into lpCommandLine, so it must be a+ # mutable buffer, and the applicationName stays NULL so the quoted argv+ # is parsed the usual way.+ cmdline = ctypes.create_unicode_buffer(subprocess.list2cmdline(argv))++ ok = advapi32.CreateProcessWithTokenW(+ primary,+ _LOGON_WITH_PROFILE,+ None,+ cmdline,+ creationflags | _CREATE_UNICODE_ENVIRONMENT,+ ctypes.cast(block, wintypes.LPVOID),+ cwd,+ ctypes.byref(startup),+ ctypes.byref(info),+ )+ if not ok:+ return DeescalationResult(+ False,+ None,+ f"CreateProcessWithTokenW failed ({ctypes.get_last_error()})",+ )+ kernel32.CloseHandle(info.hProcess)+ kernel32.CloseHandle(info.hThread)+ return DeescalationResult(+ True, int(info.dwProcessId), "Started without administrator rights."+ )+ finally:+ for handle in (linked, primary, token):+ if handle:+ kernel32.CloseHandle(handle)+++def spawn_unelevated(+ argv: list[str],+ *,+ cwd: str,+ env: dict[str, str],+ creationflags: int = 0,+ _platform: str | None = None,+ _spawn=_spawn_unelevated_windows,+) -> DeescalationResult:+ """Launch ``argv`` stripped of this process's elevation.++ Returns an honest failure rather than silently falling back to an elevated+ spawn: a caller that quietly relaunches elevated would leave the user with a+ "repaired" app that still ignores their dictation software.+ """+ platform = sys.platform if _platform is None else _platform+ if platform != "win32":+ return DeescalationResult(+ False,+ None,+ "Dropping privileges is only supported on Windows; on this system "+ "start the app as your normal user account instead.",+ )+ try:+ return _spawn(argv, cwd=cwd, env=env, creationflags=creationflags)+ except Exception as exc: # noqa: BLE001 — a failed repair must not crash the app+ log.warning("Unelevated relaunch failed", exc_info=True)+ return DeescalationResult(False, None, f"{type(exc).__name__}: {exc}")+++def current_process_is_elevated() -> bool | None:+ """Convenience re-export so callers need only one import on this path."""+ from .input_isolation import windows_process_is_elevated # noqa: PLC0415++ if os.name != "nt":+ return None+ return windows_process_is_elevated()+++__all__ = [+ "DeescalationResult",+ "current_process_is_elevated",+ "environment_block",+ "spawn_unelevated",+]diff --git a/jarvis/platform/input_isolation.py b/jarvis/platform/input_isolation.pynew file mode 100644index 0000000000..0067357327--- /dev/null+++ b/jarvis/platform/input_isolation.py@@ -0,0 +1,230 @@+"""Can ordinary user software still type into our window?++Dictation apps (a dictation app, Windows Voice Access, a dictation app, Talon, ...),+text expanders, clipboard managers, and password-manager auto-type all work the+same way: they synthesize keystrokes or a clipboard paste into whichever window+currently has focus, and they locate the target field through the OS accessibility+tree. Both of those are privilege-gated.++**Windows UIPI (User Interface Privilege Isolation).** A process may not send+synthetic input to — nor read the automation tree of — a window owned by a+process of *higher* integrity. So the moment the desktop app runs elevated+("Run as administrator"), every one of those tools goes silently dead inside our+window while continuing to work everywhere else. Silently is literal: Microsoft+documents that ``SendInput`` blocked by UIPI reports failure through neither its+return value nor ``GetLastError``, so the dictation app believes it succeeded and+the user sees a window that simply ignores their voice.++Measured on the maintainer's box (2026-07-25), an elevated Jarvis window exposed+**1** automation element and **0** text fields to a normal-privilege client,+against 418/80 for an ordinary window; the identical WebView, launched+unelevated, accepted both synthetic typing and a Ctrl+V paste.++Nothing about this is Jarvis-specific — which is why the fix belongs here rather+than in any one feature. The app is *designed* to run unelevated (the autostart+scheduled task pins ``RunLevel=Limited``, and privileged operations go through+the separate admin helper in ``jarvis/admin/``), but an app that was ever started+elevated stays elevated across every in-app restart, so the condition is sticky+and invisible without a probe.++POSIX hosts get the honest analogue: a GUI running as root is isolated from the+user session's assistive tooling in the same spirit, but there is no safe way for+us to drop back to the original user, so we report it without promising a repair.+"""++from __future__ import annotations++import logging+import os+from dataclasses import dataclass+from enum import StrEnum+from typing import Any++from . import PlatformName, detect_platform++log = logging.getLogger(__name__)+++class InputIsolationReason(StrEnum):+ """Why third-party input software cannot reach this window."""++ #: Nothing in the way.+ NONE = "none"+ #: Windows: we run elevated, so UIPI drops input from normal-privilege apps.+ ELEVATED = "elevated"+ #: POSIX: we run as root, outside the user's assistive-tech session.+ ROOT = "root"+ #: The privilege state could not be read. Never treated as a defect.+ UNKNOWN = "unknown"+++_ELEVATED_SUMMARY = (+ "This app is running with administrator rights, so Windows blocks other "+ "programs from typing into its window. Dictation apps, text expanders, "+ "clipboard tools, and password-manager auto-type will appear to do nothing "+ "here while still working in every other app."+)+_ELEVATED_REMEDY = (+ "Restart the app without administrator rights. Nothing in normal operation "+ "needs them — privileged actions ask for elevation individually."+)+_ROOT_SUMMARY = (+ "This app is running as root, so dictation apps, text expanders, and other "+ "assistive input tools running in your normal user session cannot type into "+ "its window."+)+_ROOT_REMEDY = (+ "Start the app as your normal user account instead of with sudo/root."+)+++@dataclass(frozen=True)+class InputIsolationReport:+ """What outside input software can and cannot do with our window."""++ blocked: bool+ reason: InputIsolationReason+ platform: PlatformName+ summary: str+ remedy: str+ can_restart_unelevated: bool++ def to_dict(self) -> dict[str, Any]:+ return {+ "blocked": self.blocked,+ "reason": str(self.reason),+ "platform": self.platform,+ "summary": self.summary,+ "remedy": self.remedy,+ "can_restart_unelevated": self.can_restart_unelevated,+ }+++def windows_process_is_elevated() -> bool | None:+ """Is this process running with an elevated (administrator) token?++ ``None`` when the answer cannot be determined — including on every+ non-Windows host, where the question does not apply. Never raises: this is a+ diagnostic, and a diagnostic that can crash the app is worse than no+ diagnostic at all.+ """+ if os.name != "nt":+ return None+ try:+ import ctypes # noqa: PLC0415 — lazy: keeps this module import-clean (HN-7)+ from ctypes import wintypes # noqa: PLC0415++ TOKEN_QUERY = 0x0008+ TokenElevation = 20++ advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)++ token = wintypes.HANDLE()+ if not advapi32.OpenProcessToken(+ kernel32.GetCurrentProcess(), TOKEN_QUERY, ctypes.byref(token)+ ):+ return None+ try:+ elevated = wintypes.DWORD()+ returned = wintypes.DWORD()+ ok = advapi32.GetTokenInformation(+ token,+ TokenElevation,+ ctypes.byref(elevated),+ ctypes.sizeof(elevated),+ ctypes.byref(returned),+ )+ if not ok:+ return None+ return bool(elevated.value)+ finally:+ kernel32.CloseHandle(token)+ except Exception: # noqa: BLE001 — an unreadable token is "unknown", not fatal+ log.debug("Could not read this process's elevation state", exc_info=True)+ return None+++def _euid() -> int | None:+ """Effective user id, or ``None`` on platforms without one (Windows)."""+ getter = getattr(os, "geteuid", None)+ if getter is None:+ return None+ try:+ return int(getter())+ except OSError: # pragma: no cover — geteuid does not fail in practice+ return None+++def describe_input_isolation(+ *,+ _platform=detect_platform,+ _elevated=windows_process_is_elevated,+ _euid=_euid,+) -> InputIsolationReport:+ """Report whether outside input software can reach this app's window.++ Fail-open by design: when the privilege state cannot be read we report+ ``UNKNOWN`` and ``blocked=False``, because warning a user about a problem+ they may not have — and offering a restart they do not need — is worse than+ staying quiet. A real block is always a positive measurement.+ """+ platform = _platform()++ if platform == "win32":+ elevated = _elevated()+ if elevated is None:+ return InputIsolationReport(+ blocked=False,+ reason=InputIsolationReason.UNKNOWN,+ platform=platform,+ summary="",+ remedy="",+ can_restart_unelevated=False,+ )+ if elevated:+ return InputIsolationReport(+ blocked=True,+ reason=InputIsolationReason.ELEVATED,+ platform=platform,+ summary=_ELEVATED_SUMMARY,+ remedy=_ELEVATED_REMEDY,+ can_restart_unelevated=True,+ )+ return InputIsolationReport(+ blocked=False,+ reason=InputIsolationReason.NONE,+ platform=platform,+ summary="",+ remedy="",+ can_restart_unelevated=False,+ )++ if _euid() == 0:+ return InputIsolationReport(+ blocked=True,+ reason=InputIsolationReason.ROOT,+ platform=platform,+ summary=_ROOT_SUMMARY,+ remedy=_ROOT_REMEDY,+ # Dropping privileges to "the user who ran sudo" is guesswork and+ # would strand file ownership; the user restarts this one himself.+ can_restart_unelevated=False,+ )++ return InputIsolationReport(+ blocked=False,+ reason=InputIsolationReason.NONE,+ platform=platform,+ summary="",+ remedy="",+ can_restart_unelevated=False,+ )+++__all__ = [+ "InputIsolationReason",+ "InputIsolationReport",+ "describe_input_isolation",+ "windows_process_is_elevated",+]diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex fc77d52c0a..dea559ba22 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -258,6 +258,39 @@ def _write_meta(port: int, pid: int) -> None:pass+def _log_input_isolation() -> None:+ """Record whether outside input software can reach our window.++ Elevation is sticky (it survives every in-app restart) and invisible: while+ it lasts, Windows silently discards synthetic keystrokes and automation+ queries from ordinary user software, so dictation apps, text expanders, and+ password-manager auto-type stop working INSIDE our window with no error on+ either side. Without this line a support log gives no hint at all — the+ 2026-07-25 report reached us as "dictation just doesn't work in Jarvis".++ Runs on the background heavy-init task, never the startup critical path+ (AP-26), and is a token read costing microseconds. Fully guarded: a+ diagnostic must never be the thing that breaks boot.+ """+ try:+ from loguru import logger++ from jarvis.platform.input_isolation import describe_input_isolation++ report = describe_input_isolation()+ if report.blocked:+ logger.warning(+ "Input isolation ACTIVE (reason={}): {} Repair: {}",+ report.reason,+ report.summary,+ report.remedy,+ )+ else:+ logger.debug("Input isolation clear (reason={}).", report.reason)+ except Exception: # noqa: BLE001, S110 — never let a diagnostic break boot+ pass++def _read_meta() -> dict[str, Any] | None:"""Reads the PID sidecar. ``None`` if missing or corrupt."""try:@@ -1857,6 +1890,7 @@ class DesktopApp:# the meta file only needs the API to answer, which set_app# just made true._write_meta(self.cfg.ui.admin_api_port, os.getpid())+ _log_input_isolation()try:await server.start(start_serving=False)_db_mark("server_start")@@ -2304,42 +2338,89 @@ class DesktopApp:(no window to restart). Fully guarded — a spawn failure leaves the apprunning rather than half-quitting."""+ return self._schedule_restart(drop_elevation=False)[0]++ def request_unelevated_restart(self) -> tuple[bool, str]:+ """Restart WITHOUT the administrator rights this process is carrying.++ Recovery for the input-isolation defect: while the app runs elevated,+ Windows UIPI silently discards synthetic keystrokes and automation+ queries from ordinary user software, so dictation apps, text expanders,+ clipboard tools, and password-manager auto-type all go dead inside our+ window while working everywhere else (see+ ``jarvis/platform/input_isolation.py``). Elevation survives every normal+ in-app restart, so escaping it needs this dedicated path.++ Returns ``(scheduled, detail)``. On failure the app deliberately stays+ UP and elevated rather than quitting: a half-repaired restart that never+ comes back is strictly worse than the problem being fixed, and the+ detail string is what the UI shows instead of a silent dead button.+ """+ return self._schedule_restart(drop_elevation=True)++ def _schedule_restart(self, *, drop_elevation: bool) -> tuple[bool, str]:+ """Spawn the detached relauncher, then quit — optionally dropping+ elevation on the way out.++ ``drop_elevation`` launches the relauncher through the elevated token's+ filtered companion token, so the whole restart chain (relauncher → fresh+ launcher → window) lands at ordinary integrity. Any failure returns+ ``(False, detail)`` WITHOUT scheduling the quit.+ """import subprocessfrom loguru import loggerfrom jarvis.ui.relauncher import (detached_creationflags,+ fresh_user_env,run_restart_quit_sequence,)window = getattr(self, "_window", None)if window is None:- return False+ return (False, "no desktop window to restart")try:import jarvis as _jarvisrepo_root = str(Path(_jarvis.__file__).resolve().parent.parent)- kwargs: dict[str, Any] = {"cwd": repo_root, "close_fds": True}- if sys.platform == "win32":- kwargs["creationflags"] = detached_creationflags()+ argv = [+ sys.executable,+ "-m",+ "jarvis.ui.relauncher",+ str(os.getpid()),+ repo_root,+ ]+ if drop_elevation:+ from jarvis.platform.deescalate import spawn_unelevated++ outcome = spawn_unelevated(+ argv,+ cwd=repo_root,+ env=fresh_user_env(),+ creationflags=detached_creationflags(),+ )+ if not outcome.ok:+ logger.warning(+ "Unelevated relaunch refused — staying up elevated: {}",+ outcome.detail,+ )+ return (False, outcome.detail)else:- kwargs["start_new_session"] = True- subprocess.Popen( # noqa: S603 — fixed argv, no shell, own interpreter- [- sys.executable,- "-m",- "jarvis.ui.relauncher",- str(os.getpid()),- repo_root,- ],- **kwargs,- )+ kwargs: dict[str, Any] = {"cwd": repo_root, "close_fds": True}+ if sys.platform == "win32":+ kwargs["creationflags"] = detached_creationflags()+ else:+ kwargs["start_new_session"] = True+ subprocess.Popen( # noqa: S603 — fixed argv, no shell, own interpreter+ argv,+ **kwargs,+ )except Exception as exc: # noqa: BLE001 — never half-quit on a spawn errorlogger.opt(exception=exc).warning("relauncher spawn failed — staying up (no self-restart)")- return False+ return (False, f"{type(exc).__name__}: {exc}")def _mark_quit() -> None:self._user_requested_quit = True@@ -2359,10 +2440,11 @@ class DesktopApp:target=_quit_soon, name="jarvis-restart-quit", daemon=True).start()logger.info(- "Self-restart scheduled (relauncher spawned; quitting in ~0.2 s, "- "independent hard-exit watchdog at ~0.9 s)."+ "Self-restart scheduled (relauncher spawned{}; quitting in ~0.2 s, "+ "independent hard-exit watchdog at ~0.9 s).",+ " WITHOUT administrator rights" if drop_elevation else "",)- return True+ return (True, "restart scheduled")def request_quit(self) -> bool:"""Cleanly quit the app WITHOUT relaunching (Terms declined).diff --git a/jarvis/ui/web/frontend/src/App.tsx b/jarvis/ui/web/frontend/src/App.tsxindex eb5a91a2aa..240bf1c35b 100644--- a/jarvis/ui/web/frontend/src/App.tsx+++ b/jarvis/ui/web/frontend/src/App.tsx@@ -5,6 +5,7 @@ import { useAssistantNameSeed } from "@/hooks/useAssistantNameSeed";import { Sidebar } from "@/components/layout/Sidebar";import { TopBar } from "@/components/layout/TopBar";import { PermissionsAlertBanner } from "@/components/layout/PermissionsAlertBanner";+import { InputIsolationBanner } from "@/components/layout/InputIsolationBanner";import { VoiceWarmingBanner } from "@/components/layout/VoiceWarmingBanner";import { MainView } from "@/components/layout/MainView";import { ToastLayer } from "@/components/ToastLayer";@@ -32,6 +33,11 @@ export default function App() {{/* App-wide macOS permission alert — topmost so a missing grant isimpossible to miss on any view. No-op on other platforms. */}<PermissionsAlertBanner />+ {/* Outside input software (dictation, text expanders, auto-type) cannot+ reach an elevated window. Sits next to the permission alert because+ it is the same class of problem: an OS-level gate the user must be+ told about, since nothing else reports it. */}+ <InputIsolationBanner /><TopBar /><VoiceWarmingBanner /><div className="min-h-0 flex-1">diff --git a/jarvis/ui/web/frontend/src/components/layout/InputIsolationBanner.test.tsx b/jarvis/ui/web/frontend/src/components/layout/InputIsolationBanner.test.tsxnew file mode 100644index 0000000000..16cb010f23--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/layout/InputIsolationBanner.test.tsx@@ -0,0 +1,139 @@+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { InputIsolationReport } from "@/hooks/useInputIsolation";++const pushToast = vi.fn();+let mockReport: InputIsolationReport | null = null;++vi.mock("@/i18n", () => ({+ useT: () => (key: string) => key,+}));++vi.mock("@/store/events", () => ({+ useEventStore: (selector: (state: { pushToast: typeof pushToast }) => unknown) =>+ selector({ pushToast }),+}));++vi.mock("@/hooks/useInputIsolation", () => ({+ useInputIsolation: () => ({ report: mockReport, refetch: vi.fn() }),+}));++import { InputIsolationBanner } from "./InputIsolationBanner";++function blocked(overrides: Partial<InputIsolationReport> = {}): InputIsolationReport {+ return {+ blocked: true,+ reason: "elevated",+ platform: "win32",+ summary: "elevated",+ remedy: "restart",+ can_restart_unelevated: true,+ ...overrides,+ };+}++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ vi.unstubAllGlobals();+ mockReport = null;+});++describe("InputIsolationBanner", () => {+ it("stays invisible while outside input software can reach the window", () => {+ mockReport = blocked({ blocked: false, reason: "none" });+ render(<InputIsolationBanner />);+ expect(screen.queryByTestId("input-isolation-banner")).toBeNull();+ });++ it("stays invisible while the privilege state is still unknown", () => {+ // Never warn on a guess: a user without the problem must see nothing.+ mockReport = null;+ render(<InputIsolationBanner />);+ expect(screen.queryByTestId("input-isolation-banner")).toBeNull();+ });++ it("names the problem and offers the one-click repair when blocked", () => {+ mockReport = blocked();+ render(<InputIsolationBanner />);++ expect(screen.getByTestId("input-isolation-banner")).toBeDefined();+ expect(screen.getByText("input_isolation.title")).toBeDefined();+ expect(screen.getByText("input_isolation.impact")).toBeDefined();+ expect(screen.getByText("input_isolation.restart_now")).toBeDefined();+ });++ it("posts the unelevated restart when the repair button is clicked", async () => {+ mockReport = blocked();+ const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) });+ vi.stubGlobal("fetch", fetchMock);++ render(<InputIsolationBanner />);+ fireEvent.click(screen.getByText("input_isolation.restart_now"));++ await waitFor(() =>+ expect(fetchMock).toHaveBeenCalledWith("/api/settings/restart-unelevated", {+ method: "POST",+ }),+ );+ });++ it("explains the manual route when the app cannot drop its own privileges", () => {+ // UAC disabled / built-in Administrator: offering a button that cannot work+ // would be worse than saying what the user has to do.+ mockReport = blocked({ can_restart_unelevated: false });+ render(<InputIsolationBanner />);++ expect(screen.getByText("input_isolation.manual_hint")).toBeDefined();+ expect(screen.queryByText("input_isolation.restart_now")).toBeNull();+ });++ it("surfaces the backend reason when de-elevation fails, and stays up", async () => {+ mockReport = blocked();+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: false,+ json: async () => ({+ detail: { error: "deescalation_failed", message: "no linked token" },+ }),+ }),+ );++ render(<InputIsolationBanner />);+ fireEvent.click(screen.getByText("input_isolation.restart_now"));++ await waitFor(() => expect(pushToast).toHaveBeenCalledWith("error", "no linked token"));+ // The banner must survive a failed repair — the problem is still there.+ expect(screen.getByTestId("input-isolation-banner")).toBeDefined();+ });++ it("warns instead of killing running missions", async () => {+ mockReport = blocked();+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: false,+ json: async () => ({ detail: { error: "missions_running" } }),+ }),+ );++ render(<InputIsolationBanner />);+ fireEvent.click(screen.getByText("input_isolation.restart_now"));++ await waitFor(() =>+ expect(pushToast).toHaveBeenCalledWith(+ "warning",+ "topbar.restart_missions_running",+ ),+ );+ });++ it("can be hidden by the user without pretending the problem is solved", () => {+ mockReport = blocked();+ render(<InputIsolationBanner />);++ fireEvent.click(screen.getByLabelText("input_isolation.dismiss"));+ expect(screen.queryByTestId("input-isolation-banner")).toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/layout/InputIsolationBanner.tsx b/jarvis/ui/web/frontend/src/components/layout/InputIsolationBanner.tsxnew file mode 100644index 0000000000..12d58ab763--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/layout/InputIsolationBanner.tsx@@ -0,0 +1,102 @@+import { useState } from "react";+import { KeyboardOff, Loader2, X } from "lucide-react";+import { Button } from "@/components/ui/button";+import { useT } from "@/i18n";+import { useEventStore } from "@/store/events";+import { useInputIsolation } from "@/hooks/useInputIsolation";++/**+ * App-wide alert: outside input software cannot type into this window.+ *+ * Dictation apps (a dictation app, Voice Access, a dictation app, Talon, …), text+ * expanders, clipboard managers, and password-manager auto-type all inject+ * synthetic keystrokes into the focused window. Windows blocks that for any+ * window owned by a higher-integrity process, so while the app runs elevated+ * they appear to do nothing here while working in every other app — and neither+ * side reports an error, which is precisely what makes it undiagnosable from the+ * outside (live report 2026-07-25: "dictation just doesn't work in the Jarvis+ * window").+ *+ * Renders nothing whenever the window is reachable, which is the normal case on+ * every platform — including when the privilege state could not be read at all+ * (we never nag on a guess).+ */+export function InputIsolationBanner() {+ const t = useT();+ const pushToast = useEventStore((state) => state.pushToast);+ const { report } = useInputIsolation();+ const [dismissed, setDismissed] = useState(false);+ const [restarting, setRestarting] = useState(false);++ if (!report?.blocked || dismissed) return null;++ async function restartUnelevated() {+ if (restarting) return;+ setRestarting(true);+ try {+ const response = await fetch("/api/settings/restart-unelevated", {+ method: "POST",+ });+ if (response.ok) return; // the window closes and comes back unelevated+ const body = await response.json().catch(() => null);+ const error = body?.detail?.error;+ if (error === "missions_running") {+ pushToast("warning", t("topbar.restart_missions_running"));+ } else if (error === "deescalation_failed") {+ // Honest failure: the app is still up and still elevated.+ pushToast("error", body?.detail?.message ?? t("input_isolation.restart_failed"));+ } else {+ pushToast("error", t("input_isolation.restart_failed"));+ }+ } catch {+ pushToast("error", t("input_isolation.restart_failed"));+ }+ setRestarting(false);+ }++ return (+ <div+ data-testid="input-isolation-banner"+ data-reason={report.reason}+ role="alert"+ className="border-b-2 border-amber-500/50 bg-amber-500/10 text-amber-100"+ >+ <div className="flex items-start gap-3 px-4 py-2.5">+ <KeyboardOff className="mt-0.5 h-5 w-5 shrink-0 text-amber-400" aria-hidden />+ <div className="min-w-0 flex-1">+ <p className="text-sm font-semibold leading-tight">+ {t("input_isolation.title")}+ </p>+ <p className="mt-0.5 text-xs leading-snug text-amber-200/90">+ {t("input_isolation.impact")}+ </p>+ {!report.can_restart_unelevated && (+ <p className="mt-1 text-xs leading-snug text-amber-200/70">+ {t("input_isolation.manual_hint")}+ </p>+ )}+ </div>+ {report.can_restart_unelevated && (+ <Button+ size="sm"+ disabled={restarting}+ onClick={() => void restartUnelevated()}+ >+ {restarting && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}+ {t(restarting ? "input_isolation.restarting" : "input_isolation.restart_now")}+ </Button>+ )}+ <Button+ size="icon"+ variant="ghost"+ className="h-7 w-7 shrink-0"+ aria-label={t("input_isolation.dismiss")}+ title={t("input_isolation.dismiss")}+ onClick={() => setDismissed(true)}+ >+ <X className="h-3.5 w-3.5" aria-hidden />+ </Button>+ </div>+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/hooks/useInputIsolation.ts b/jarvis/ui/web/frontend/src/hooks/useInputIsolation.tsnew file mode 100644index 0000000000..27bda04110--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/useInputIsolation.ts@@ -0,0 +1,69 @@+import { useCallback, useEffect, useRef, useState } from "react";++/**+ * Whether outside input software can type into this app's window.+ *+ * Mirrors ``jarvis/platform/input_isolation.py``. When the desktop app runs+ * elevated, Windows discards synthetic keystrokes and automation queries coming+ * from ordinary user software, so dictation apps, text expanders, clipboard+ * managers, and password-manager auto-type all go dead inside our window while+ * still working everywhere else — and nothing reports an error.+ */+export type InputIsolationReason = "none" | "elevated" | "root" | "unknown";++export type InputIsolationReport = {+ blocked: boolean;+ reason: InputIsolationReason;+ platform: string;+ summary: string;+ remedy: string;+ can_restart_unelevated: boolean;+};++/** Backoff for the boot race: the window mounts before the API answers. */+const RETRY_DELAYS_MS = [400, 1200, 3000];++export function useInputIsolation() {+ const [report, setReport] = useState<InputIsolationReport | null>(null);+ const timers = useRef<ReturnType<typeof setTimeout>[]>([]);++ const load = useCallback(async (): Promise<boolean> => {+ try {+ const response = await fetch("/api/settings/input-isolation");+ if (!response.ok) return false;+ const body = (await response.json()) as InputIsolationReport;+ setReport(body);+ return true;+ } catch {+ return false;+ }+ }, []);++ useEffect(() => {+ let cancelled = false;+ const scheduled = timers.current;++ // A single mount-time fetch is a known trap here: the frontend routinely+ // mounts while the backend is still coming up, and a one-shot 503 would+ // leave the user with no warning at all on exactly the machine that has the+ // problem. Retry a few times, then stop — this is a diagnostic, not a poll.+ void (async () => {+ if (await load()) return;+ RETRY_DELAYS_MS.forEach((delay) => {+ scheduled.push(+ setTimeout(() => {+ if (!cancelled) void load();+ }, delay),+ );+ });+ })();++ return () => {+ cancelled = true;+ scheduled.forEach(clearTimeout);+ scheduled.length = 0;+ };+ }, [load]);++ return { report, refetch: load };+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 3ee524ecda..b2de0c3151 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -1,4 +1,13 @@{+ "input_isolation": {+ "title": "Diktier- und Tipphilfen erreichen dieses Fenster nicht",+ "impact": "Diese App läuft mit Administratorrechten, deshalb lässt Windows andere Programme nicht in ihr Fenster schreiben. Diktier-Apps, Textbausteine, Zwischenablage-Tools und das automatische Ausfüllen von Passwort-Managern scheinen hier nichts zu tun, während sie in jeder anderen App weiterhin funktionieren.",+ "manual_hint": "Die App kann die Administratorrechte auf diesem Windows-Konto nicht selbst ablegen. Schließe sie und starte sie normal neu — ohne „Als Administrator ausführen“.",+ "restart_now": "Ohne Administratorrechte neu starten",+ "restarting": "Wird neu gestartet…",+ "restart_failed": "Die App konnte nicht ohne Administratorrechte neu gestartet werden.",+ "dismiss": "Hinweis ausblenden"+ },"auth_gate": {"checking": "Zugriff wird geprüft…","starting": "Wird gestartet…",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex f4f40d492c..e9924c86e7 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -1,4 +1,13 @@{+ "input_isolation": {+ "title": "Dictation and typing tools can't reach this window",+ "impact": "This app is running with administrator rights, so Windows blocks other programs from typing into it. Dictation apps, text expanders, clipboard tools, and password-manager auto-type will seem to do nothing here, while still working in every other app.",+ "manual_hint": "This app can't drop the administrator rights by itself on this Windows account. Close it and start it again normally — without “Run as administrator”.",+ "restart_now": "Restart without admin rights",+ "restarting": "Restarting…",+ "restart_failed": "The app could not restart without administrator rights.",+ "dismiss": "Hide this notice"+ },"auth_gate": {"checking": "Checking access…","starting": "Starting up…",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 9cccaceb92..f425e21a14 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -1,4 +1,13 @@{+ "input_isolation": {+ "title": "Las herramientas de dictado y escritura no alcanzan esta ventana",+ "impact": "Esta aplicación se está ejecutando con permisos de administrador, por lo que Windows impide que otros programas escriban en ella. Las apps de dictado, los expansores de texto, los gestores de portapapeles y el autocompletado de los gestores de contraseñas parecerán no hacer nada aquí, aunque sigan funcionando en el resto de aplicaciones.",+ "manual_hint": "La aplicación no puede renunciar por sí misma a los permisos de administrador en esta cuenta de Windows. Ciérrala y vuelve a abrirla con normalidad, sin «Ejecutar como administrador».",+ "restart_now": "Reiniciar sin permisos de administrador",+ "restarting": "Reiniciando…",+ "restart_failed": "No se pudo reiniciar la aplicación sin permisos de administrador.",+ "dismiss": "Ocultar este aviso"+ },"auth_gate": {"checking": "Comprobando el acceso…","starting": "Iniciando…",diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.pyindex 00a5ea5d64..a05b9882a4 100644--- a/jarvis/ui/web/settings_routes.py+++ b/jarvis/ui/web/settings_routes.py@@ -1872,6 +1872,93 @@ async def restart_app(request: Request, force: bool = False) -> dict[str, objectreturn {"ok": True, "restarting": True}[email protected]("/input-isolation", summary="Can other apps type into this window?")+async def get_input_isolation() -> dict[str, object]:+ """Report whether outside input software can reach this app's window.++ Dictation apps (a dictation app, Voice Access, a dictation app, ...), text expanders,+ clipboard managers, and password-manager auto-type all inject synthetic+ keystrokes into the focused window and locate the field through the OS+ accessibility tree. Windows blocks BOTH for any window owned by a+ higher-integrity process — so while this app runs elevated they appear to do+ nothing here while still working in every other app, with no error anywhere+ (Windows does not report a UIPI drop to the sender).++ Deliberately cheap, uncached, and unauthenticated-safe: it reads only this+ process's own privilege state, so the desktop UI can poll it on mount.+ """+ from jarvis.platform.input_isolation import describe_input_isolation++ return describe_input_isolation().to_dict()+++ "/restart-unelevated",+ summary="Restart the app without administrator rights",+ openapi_extra={"x-jarvis-dangerous": True},+)+async def restart_unelevated(request: Request, force: bool = False) -> dict[str, object]:+ """Restart the desktop app stripped of its administrator rights.++ The repair for the condition ``GET /input-isolation`` reports: elevation+ survives every ordinary in-app restart, so a plain restart cannot escape it.+ This relaunches through the elevated token's filtered companion token, which+ lands the fresh window at the same privilege level as any normally-started+ app — and back within reach of the user's dictation software.++ Refuses with 409 when the app is not elevated (nothing to repair) or when+ privileges cannot be dropped on this account, and in that case the app stays+ UP: a restart that never returns is worse than the problem being fixed.+ Honours the same running-mission guard as ``/restart-app``.+ """+ from jarvis.platform.input_isolation import describe_input_isolation++ report = describe_input_isolation()+ if not report.can_restart_unelevated:+ raise HTTPException(+ status_code=409,+ detail={+ "error": "not_elevated"+ if not report.blocked+ else "cannot_drop_privileges",+ "report": report.to_dict(),+ },+ )++ if not force:+ kontrollierer = getattr(request.app.state, "kontrollierer", None)+ list_running = getattr(kontrollierer, "running_mission_ids", None)+ running = list(list_running()) if callable(list_running) else []+ if running:+ manager = getattr(request.app.state, "mission_manager", None)+ try:+ missions = await asyncio.wait_for(+ _running_mission_summaries(manager, running), timeout=2.0+ )+ except TimeoutError:+ missions = [{"id": mid, "title": ""} for mid in running]+ raise HTTPException(+ status_code=409,+ detail={"error": "missions_running", "missions": missions},+ )++ desktop = getattr(request.app.state, "desktop_app", None)+ fn = getattr(desktop, "request_unelevated_restart", None)+ if not callable(fn):+ raise HTTPException(+ status_code=503, detail="self-restart unavailable on this host"+ )+ # Same off-pool dispatch as /restart-app: a restart must survive a default+ # thread pool exhausted by hung threads.+ scheduled, detail = await _run_off_pool(fn)+ if not scheduled:+ raise HTTPException(+ status_code=409,+ detail={"error": "deescalation_failed", "message": detail},+ )+ return {"ok": True, "restarting": True, "unelevated": True}++class OpenExternalBody(BaseModel):url: str = Field(min_length=1, max_length=4096)diff --git a/tests/unit/platform/test_deescalate.py b/tests/unit/platform/test_deescalate.pynew file mode 100644index 0000000000..6ced740f55--- /dev/null+++ b/tests/unit/platform/test_deescalate.py@@ -0,0 +1,91 @@+"""Guards for the unelevated relaunch used to recover input reachability.++The contract that matters here is HONESTY: when privileges cannot be dropped,+the caller must learn that instead of quietly relaunching elevated again. A+"repaired" app that still ignores the user's dictation software — with a button+that reported success — is the worst possible outcome.+"""++from __future__ import annotations++from jarvis.platform.deescalate import (+ DeescalationResult,+ environment_block,+ spawn_unelevated,+)+++class TestEnvironmentBlock:+ def test_pairs_are_nul_separated_and_double_nul_terminated(self):+ block = environment_block({"A": "1", "B": "2"})+ assert block == "A=1\0B=2\0\0"++ def test_names_are_sorted_case_insensitively(self):+ """Windows documents the block as case-insensitively sorted; an+ unsorted one is 'undefined behaviour' on the restart path."""+ block = environment_block({"beta": "2", "Alpha": "1", "GAMMA": "3"})+ assert block == "Alpha=1\0beta=2\0GAMMA=3\0\0"++ def test_empty_environment_still_terminates(self):+ assert environment_block({}) == "\0"++ def test_values_containing_separators_survive_verbatim(self):+ block = environment_block({"PATH": "C:\\a;C:\\b", "Q": "x=y"})+ assert "PATH=C:\\a;C:\\b\0" in block+ assert "Q=x=y\0" in block+++class TestPlatformGating:+ def test_posix_reports_an_actionable_refusal_rather_than_pretending(self):+ result = spawn_unelevated([], cwd=".", env={}, _platform="linux")+ assert result.ok is False+ assert result.pid is None+ assert "normal user account" in result.detail++ def test_windows_path_is_delegated_with_the_caller_arguments(self):+ seen: dict[str, object] = {}++ def fake(argv, *, cwd, env, creationflags):+ seen.update(argv=argv, cwd=cwd, env=env, creationflags=creationflags)+ return DeescalationResult(True, 4242, "ok")++ result = spawn_unelevated(+ ["py", "-m", "x"],+ cwd="C:\\repo",+ env={"A": "1"},+ creationflags=8,+ _platform="win32",+ _spawn=fake,+ )+ assert result.ok is True+ assert result.pid == 4242+ assert seen == {+ "argv": ["py", "-m", "x"],+ "cwd": "C:\\repo",+ "env": {"A": "1"},+ "creationflags": 8,+ }+++class TestFailureContainment:+ def test_a_raising_spawn_becomes_a_reported_failure_not_a_crash(self):+ """This runs while the app is mid-restart; an exception escaping here+ would take down a live desktop session."""++ def boom(argv, *, cwd, env, creationflags):+ raise OSError("token duplication denied")++ result = spawn_unelevated(+ ["py"], cwd=".", env={}, _platform="win32", _spawn=boom+ )+ assert result.ok is False+ assert result.pid is None+ assert "token duplication denied" in result.detail++ def test_failure_never_reports_a_pid(self):+ def refuse(argv, *, cwd, env, creationflags):+ return DeescalationResult(False, None, "no linked token")++ assert spawn_unelevated(+ ["py"], cwd=".", env={}, _platform="win32", _spawn=refuse+ ).pid is Nonediff --git a/tests/unit/platform/test_input_isolation.py b/tests/unit/platform/test_input_isolation.pynew file mode 100644index 0000000000..f61dde0fe3--- /dev/null+++ b/tests/unit/platform/test_input_isolation.py@@ -0,0 +1,118 @@+"""Guards for the third-party-input reachability probe.++The failure this pins down (live forensic 2026-07-25): the desktop app was+running elevated, so Windows UIPI silently discarded every synthetic keystroke+and automation query coming from ordinary user software. Dictation apps (a dictation app+Flow and friends), text expanders, and password-manager auto-type all went dead+INSIDE the Jarvis window while working everywhere else — with no error anywhere,+because Windows does not report a UIPI drop to the sender.++These tests never read the host's real privilege state: they inject it, so the+same assertions hold on a maintainer's elevated Windows box, a CI container, and+a Mac.+"""++from __future__ import annotations++import pytest++from jarvis.platform.input_isolation import (+ InputIsolationReason,+ describe_input_isolation,+ windows_process_is_elevated,+)+++def _report(platform: str, elevated: bool | None):+ return describe_input_isolation(+ _platform=lambda: platform,+ _elevated=lambda: elevated,+ _euid=lambda: 1000,+ )+++class TestWindows:+ def test_elevated_window_is_reported_as_blocked(self):+ report = _report("win32", True)+ assert report.blocked is True+ assert report.reason is InputIsolationReason.ELEVATED+ assert report.can_restart_unelevated is True++ def test_normal_window_is_reachable(self):+ report = _report("win32", False)+ assert report.blocked is False+ assert report.reason is InputIsolationReason.NONE+ assert report.can_restart_unelevated is False++ def test_undecidable_privilege_state_is_reported_honestly(self):+ """An unreadable token must never masquerade as 'all good'."""+ report = _report("win32", None)+ assert report.reason is InputIsolationReason.UNKNOWN+ # Unknown is not a defect claim: we do not nag the user on a guess.+ assert report.blocked is False+ assert report.can_restart_unelevated is False+++class TestPosix:+ @pytest.mark.parametrize("platform", ["darwin", "linux"])+ def test_ordinary_user_session_is_reachable(self, platform):+ report = describe_input_isolation(+ _platform=lambda: platform,+ _elevated=lambda: None,+ _euid=lambda: 1000,+ )+ assert report.blocked is False+ assert report.reason is InputIsolationReason.NONE++ @pytest.mark.parametrize("platform", ["darwin", "linux"])+ def test_root_session_is_flagged_without_promising_a_self_repair(self, platform):+ """Running as root isolates us the same way, but dropping back to the+ original user is not something we can do safely — say so instead of+ offering a button that cannot work."""+ report = describe_input_isolation(+ _platform=lambda: platform,+ _elevated=lambda: None,+ _euid=lambda: 0,+ )+ assert report.blocked is True+ assert report.reason is InputIsolationReason.ROOT+ assert report.can_restart_unelevated is False++ def test_windows_probe_is_not_consulted_on_posix(self):+ """The ctypes token probe must never run off-Windows (it would raise)."""++ def _explode() -> bool:+ raise AssertionError("the Windows token probe ran on a POSIX host")++ report = describe_input_isolation(+ _platform=lambda: "linux", _elevated=_explode, _euid=lambda: 1000+ )+ assert report.reason is InputIsolationReason.NONE+++class TestMessaging:+ def test_blocked_report_names_the_affected_software_categories(self):+ """The user-facing text must be recognizable to someone whose dictation+ app just went quiet — not a lecture about integrity levels."""+ summary = _report("win32", True).summary.lower()+ assert "dictation" in summary+ assert "administrator" in summary or "admin" in summary++ def test_healthy_report_carries_no_remedy_noise(self):+ assert _report("win32", False).remedy == ""++ def test_report_is_json_serializable_for_the_api(self):+ payload = _report("win32", True).to_dict()+ assert payload["blocked"] is True+ assert payload["reason"] == "elevated"+ assert isinstance(payload["summary"], str)+ assert isinstance(payload["can_restart_unelevated"], bool)+++class TestRealHostProbe:+ def test_probe_never_raises_on_any_host(self):+ """Import-clean + crash-free everywhere: a diagnostic must not be the+ thing that takes the app down."""+ assert windows_process_is_elevated() in (True, False, None)+ report = describe_input_isolation()+ assert isinstance(report.blocked, bool)diff --git a/tests/unit/ui/test_input_isolation_route.py b/tests/unit/ui/test_input_isolation_route.pynew file mode 100644index 0000000000..d52a207bb6--- /dev/null+++ b/tests/unit/ui/test_input_isolation_route.py@@ -0,0 +1,200 @@+"""GET /api/settings/input-isolation + POST /api/settings/restart-unelevated.++The user-visible bug behind these routes: with the desktop app running elevated,+Windows discards every synthetic keystroke and automation query coming from+ordinary user software, so dictation apps, text expanders, and password-manager+auto-type silently stop working inside the Jarvis window. Elevation survives a+normal in-app restart, so the repair needs its own endpoint.++Every test injects the privilege verdict — none of them read the host's real+state, so they hold identically on the maintainer's Windows box and in a Linux+container.+"""++from __future__ import annotations++from types import SimpleNamespace++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.platform.input_isolation import (+ InputIsolationReason,+ InputIsolationReport,+)+from jarvis.ui.web import settings_routes+from jarvis.ui.web.settings_routes import router+++def _client(desktop=None, kontrollierer=None, mission_manager=None):+ app = FastAPI()+ app.include_router(router)+ app.state.config = SimpleNamespace(ui=SimpleNamespace())+ if desktop is not None:+ app.state.desktop_app = desktop+ if kontrollierer is not None:+ app.state.kontrollierer = kontrollierer+ if mission_manager is not None:+ app.state.mission_manager = mission_manager+ return TestClient(app)+++def _report(*, blocked: bool, reason: InputIsolationReason, repairable: bool):+ return InputIsolationReport(+ blocked=blocked,+ reason=reason,+ platform="win32",+ summary="summary" if blocked else "",+ remedy="remedy" if blocked else "",+ can_restart_unelevated=repairable,+ )+++def pin_report(monkeypatch):+ """Pin the privilege verdict the routes see."""++ def _pin(report):+ monkeypatch.setattr(+ "jarvis.platform.input_isolation.describe_input_isolation",+ lambda **_kw: report,+ )++ return _pin+++class TestStatusRoute:+ def test_reports_a_blocked_window_with_an_explanation(self, pin_report):+ pin_report(+ _report(+ blocked=True,+ reason=InputIsolationReason.ELEVATED,+ repairable=True,+ )+ )+ body = _client().get("/api/settings/input-isolation").json()+ assert body["blocked"] is True+ assert body["reason"] == "elevated"+ assert body["can_restart_unelevated"] is True+ assert body["summary"]++ def test_reports_a_healthy_window_without_noise(self, pin_report):+ pin_report(+ _report(blocked=False, reason=InputIsolationReason.NONE, repairable=False)+ )+ body = _client().get("/api/settings/input-isolation").json()+ assert body["blocked"] is False+ assert body["summary"] == ""++ def test_works_without_a_desktop_app(self, pin_report):+ """Headless hosts must still answer — the CLI reads this too."""+ pin_report(+ _report(blocked=False, reason=InputIsolationReason.NONE, repairable=False)+ )+ assert _client().get("/api/settings/input-isolation").status_code == 200+++class TestRepairRoute:+ def test_schedules_an_unelevated_restart(self, pin_report):+ pin_report(+ _report(blocked=True, reason=InputIsolationReason.ELEVATED, repairable=True)+ )+ calls = {"n": 0}++ def request_unelevated_restart():+ calls["n"] += 1+ return (True, "restart scheduled")++ r = _client(+ SimpleNamespace(request_unelevated_restart=request_unelevated_restart)+ ).post("/api/settings/restart-unelevated")+ assert r.status_code == 200+ assert r.json()["unelevated"] is True+ assert calls["n"] == 1++ def test_refuses_when_there_is_nothing_to_repair(self, pin_report):+ """Never restart a healthy app: the button must be inert, not eager."""+ pin_report(+ _report(blocked=False, reason=InputIsolationReason.NONE, repairable=False)+ )+ called = {"n": 0}+ desktop = SimpleNamespace(+ request_unelevated_restart=lambda: called.__setitem__("n", 1)+ )+ r = _client(desktop).post("/api/settings/restart-unelevated")+ assert r.status_code == 409+ assert r.json()["detail"]["error"] == "not_elevated"+ assert called["n"] == 0++ def test_refuses_when_privileges_cannot_be_dropped_on_this_account(+ self, pin_report+ ):+ """UAC disabled / built-in Administrator: report it, do not restart into+ the same broken state."""+ pin_report(+ _report(+ blocked=True, reason=InputIsolationReason.ELEVATED, repairable=False+ )+ )+ r = _client(SimpleNamespace(request_unelevated_restart=lambda: (True, "")))+ response = r.post("/api/settings/restart-unelevated")+ assert response.status_code == 409+ assert response.json()["detail"]["error"] == "cannot_drop_privileges"++ def test_keeps_the_app_up_when_de_elevation_fails(self, pin_report):+ """A failed repair must surface the reason, not leave a dead app."""+ pin_report(+ _report(blocked=True, reason=InputIsolationReason.ELEVATED, repairable=True)+ )+ desktop = SimpleNamespace(+ request_unelevated_restart=lambda: (False, "no linked token")+ )+ r = _client(desktop).post("/api/settings/restart-unelevated")+ assert r.status_code == 409+ assert r.json()["detail"]["error"] == "deescalation_failed"+ assert "no linked token" in r.json()["detail"]["message"]++ def test_503_on_a_headless_host(self, pin_report):+ pin_report(+ _report(blocked=True, reason=InputIsolationReason.ELEVATED, repairable=True)+ )+ assert _client().post("/api/settings/restart-unelevated").status_code == 503++ def test_running_missions_block_the_restart_unless_forced(self, pin_report):+ """Same guard as /restart-app — a repair must not silently kill work."""+ pin_report(+ _report(blocked=True, reason=InputIsolationReason.ELEVATED, repairable=True)+ )+ called = {"n": 0}+ desktop = SimpleNamespace(+ request_unelevated_restart=lambda: (called.__setitem__("n", 1), "")+ )+ client = _client(+ desktop,+ kontrollierer=SimpleNamespace(running_mission_ids=lambda: ["019e-aaa"]),+ mission_manager=SimpleNamespace(),+ )+ r = client.post("/api/settings/restart-unelevated")+ assert r.status_code == 409+ assert r.json()["detail"]["error"] == "missions_running"+ assert called["n"] == 0+++class TestRouteContract:+ def test_repair_route_is_marked_dangerous(self):+ """check_danger_metadata.py requires the flag on destructive routes."""+ route = next(+ r+ for r in settings_routes.router.routes+ if getattr(r, "path", "") == "/api/settings/restart-unelevated"+ )+ assert route.openapi_extra == {"x-jarvis-dangerous": True}++ def test_status_route_is_a_plain_get(self):+ route = next(+ r+ for r in settings_routes.router.routes+ if getattr(r, "path", "") == "/api/settings/input-isolation"+ )+ assert set(route.methods) == {"GET"}