Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(jarvisbar): follow the mouse across monitors + fix cross-monitor drag
Ruben Lütkefe0d19fb0b71
diff --git a/docs/os-parity.md b/docs/os-parity.mdindex 586c48fd5d..5b96d9459d 100644--- a/docs/os-parity.md+++ b/docs/os-parity.md@@ -50,7 +50,7 @@ experiences today.|---|---|---|---|---|---|| P-02 | Low | Awareness | Idle detection has no Wayland backend (Windows GetLastInputInfo, macOS Quartz, Linux X11 `xprintidle` all exist since 2026-07-16); Wayland exposes no global idle time without portal support | `jarvis/awareness/watchers/idle.py` | Wayland: one honest log line, watcher does not start || P-03 | Low | Awareness | Window-focus watcher has no Wayland backend (Windows event hook, macOS NSWorkspace, Linux X11 polling all exist since 2026-07-16); Wayland hides the foreground window by design | `jarvis/awareness/watchers/window.py` | Wayland: one honest log line, watcher does not start |-| P-04 | Medium | CU typing | Linux non-ASCII typing (umlauts, CJK, emoji) requires `xdotool`; pyautogui silently drops those chars without it | `jarvis/cu/actuate/posix.py:387-438` | With `xdotool` (installer provisions it since 2026-07-15): fine. Without: warning + silent char loss |+| P-04 | Medium | CU typing | Linux desktop Unicode text input needs the system `xdotool` binary (pip cannot install it); the pyautogui fallback used on Linux drops non-ASCII chars (umlauts, CJK, emoji) without it | `jarvis/cu/actuate/posix.py::type_text`, `jarvis/plugins/tool/type_text.py` | With `xdotool` (installer provisions it since 2026-07-15): fine. Without, the drop is now reported HONESTLY (2026-07-23): an all-non-ASCII text fails with an actionable "install xdotool" error, and a mixed text types its ASCII portion and warns that the rest was dropped — no more silent success || P-05 | Low | Wiki | Wiki search hard-fails (RuntimeError with actionable apt/pysqlite3 remediation) on distros whose system SQLite lacks FTS5 | `jarvis/memory/wiki/fts_index.py:279` | `python:3.11-slim` and macOS ship FTS5 — only exotic/old distros affected; message is honest. Decision 2026-07-16: kept as honest hard error — a pysqlite3 shim would rewire seven wiki modules for an exotic audience || P-07 | Low | Audio | No macOS/Linux host-API preference exists (the Windows-name-driven tables are intentionally inert off Windows — documented in-code since 2026-07-16), and headset-name heuristics are Windows-centric | `jarvis/audio/player.py`, `jarvis/audio/capture.py` | Device auto-pick falls back to OS default order — works, less clever than on Windows || P-10 | Low | Missions | macOS worker reaper: a hard SIGKILL of the orchestrator reparents the worker tree to init (Linux covered via `PR_SET_PDEATHSIG` since 2026-07-16; Windows covered by the kernel Job Object; macOS needs a kqueue `EVFILT_PROC` watcher) | `jarvis/missions/isolation/job_object.py:327-350` | macOS only, and only on orchestrator SIGKILL; normal cancel/kill paths reap correctly |@@ -59,6 +59,7 @@ experiences today.| P-14 | Info | CU extras | macOS/Linux actuation and UI trees depend on optional extras (pynput, pyobjc, pyatspi); without them everything degrades honestly to screenshot + pixel-click | `jarvis/cu/actuate/posix.py`, `jarvis/vision/tree_factory.py` | By design (§3); bare install keeps the CU loop functional || P-15 | Low | Desktop downloads | Native drag-out has Windows OLE and macOS AppKit sources but no GTK/WebKitGTK source yet | `jarvis/ui/native_drag.py` | Linux desktop: the saved-file toast keeps reliable **Show in folder** and **Open** actions but is not itself a drag handle; headless: the normal browser download path remains available || P-16 | Low | Wiki | `VaultLock` dead-owner fast-steal is POSIX-only (`os.kill(pid, 0)` liveness probe; on Windows `os.kill` cannot probe — a non-CTRL signal terminates the target) | `jarvis/memory/wiki/lock.py::_pid_alive` | Windows: a lock left by a crashed/restarted process is stolen only after the `stale_after_seconds` wall-clock window (300 s) — the pre-fix behavior everywhere; a Win32 `OpenProcess` probe could close this |+| P-17 | Low | JarvisBar | "Follow the mouse to the active monitor" has per-OS monitor backends (Windows `MonitorFromPoint`+`rcWork`, macOS Qt available-geometry / Quartz, Linux X11 `xrandr`) but no Wayland backend — Wayland exposes no reliable global monitor geometry without portal support | `jarvis/platform/monitors.py::work_area_at`, `jarvis/ui/jarvisbar/overlay.py`, `qt_overlay.py` | Wayland: `work_area_at` returns `None`, so the bar keeps the single-monitor behaviour (it does not migrate; a cross-monitor drag pins to the primary work area). The feature is a graceful no-op there, never a crash |## Maintenancediff --git a/docs/plans/jarvis-bar-overlay/DESIGN.md b/docs/plans/jarvis-bar-overlay/DESIGN.mdindex cd940a5bfd..45c558d3c8 100644--- a/docs/plans/jarvis-bar-overlay/DESIGN.md+++ b/docs/plans/jarvis-bar-overlay/DESIGN.md@@ -29,7 +29,18 @@ calm at rest.- **Default style:** `jarvis_bar`. Mascot orb (`mascot`) and `none` remain selectable.- **Position:** bottom-center by default. **Hold-left-mouse + drag** repositions it; the position- is persisted (same UX as the current draggable orb).+ is persisted (same UX as the current draggable orb). Dragging works **across monitors** — the+ drop is pinned to the monitor it lands on, not snapped back to the primary (the historical+ multi-monitor drag bug).+- **Follow the active monitor** (`ui.bar_follow_cursor_monitor`, default on): the bar hops to+ whichever monitor the mouse is on, keeping the **same relative spot** so different-sized+ monitors line up. Persistence stores that monitor-independent relative placement (`rel_x`/`rel_y`)+ as the truth, with the absolute pixel position kept for back-compat and the no-monitor-info+ fallback. Per-OS monitor geometry: Windows `MonitorFromPoint`+`rcWork`, macOS Qt+ available-geometry, Linux X11 `xrandr`; Wayland has no reliable global geometry, so the feature+ degrades to single-monitor there (see `docs/os-parity.md` P-17). Shared placement math lives in+ `interaction.py` (`relative_within` / `project_relative` / `clamp_to_work_area`), the cross-OS+ monitor probe in `jarvis/platform/monitors.py` (`work_area_at`).- **Single left-click:** starts a voice session — the same entry point as the wake word / thepush-to-talk hotkey. (Click = "tap to talk"; hold+drag = move. Disambiguated by a pressduration + movement threshold.)diff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex 14cd69fb3e..ebf7b39a87 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -1438,6 +1438,13 @@ class UIConfig(BaseModel):# screen-adaptive scale. Range mirrors renderer.USER_SIZE_MIN/MAX (0.5–2.0);# the renderer re-clamps, so this validator only sanitizes a corrupt value.bar_size_scale: float = 1.0+ # Follow the mouse across monitors: when on, the on-screen bar hops to+ # whichever monitor the mouse cursor is currently on, keeping the SAME+ # relative spot (so different-sized monitors line up). Off pins it to one+ # monitor. Default on. Works on Windows/Linux (Tk bar) and macOS (Qt bar);+ # a headless / Wayland host with no reliable per-monitor geometry keeps the+ # single-monitor behaviour. See jarvis/ui/jarvisbar/interaction.py.+ bar_follow_cursor_monitor: bool = True# Remembered "open with" choice for Outputs artifacts: an opener id# ("default" = OS default app, "browser", or an editor key like "code").# Empty = ask via the chooser dialog on first open. Desktop-only.diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.pyindex d7a4fb369b..4a2b7abac6 100644--- a/jarvis/core/config_writer.py+++ b/jarvis/core/config_writer.py@@ -748,6 +748,18 @@ def set_bar_size_scale(scale: float, *, path: Path = DEFAULT_CONFIG_FILE) -> Non_patch_table(path, "ui", "bar_size_scale", max(0.5, min(2.0, f)))+def set_bar_follow_cursor_monitor(+ enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE+) -> None:+ """Persist ``[ui] bar_follow_cursor_monitor`` (the 'follow the mouse to the+ active monitor' toggle).++ TOML-only (not drift-guarded); the Settings route applies it live to the+ running bar.+ """+ _patch_table(path, "ui", "bar_follow_cursor_monitor", bool(enabled))++def set_mute_music(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:"""Persist ``[ducking] enabled`` (the 'mute music while dictating' toggle).diff --git a/jarvis/platform/monitors.py b/jarvis/platform/monitors.pyindex 1021bb84f2..54b95d1328 100644--- a/jarvis/platform/monitors.py+++ b/jarvis/platform/monitors.py@@ -155,7 +155,7 @@ def _win_virtual_bounds() -> tuple[int, int, int, int] | None:if set_ctx is not None and prev is not None:try:set_ctx(ctypes.c_void_p(prev))- except Exception: # noqa: BLE001 — restore is best-effort+ except Exception: # noqa: BLE001,S110 — best-effort DPI-context restorepassif width <= 0 or height <= 0:return None@@ -217,6 +217,187 @@ def _x11_virtual_bounds() -> tuple[int, int, int, int] | None:return (0, 0, width, height)+def work_area_at(x: int, y: int) -> tuple[int, int, int, int] | None:+ """Work area ``(left, top, width, height)`` of the monitor containing ``(x, y)``.++ The "work area" excludes the OS taskbar/panel where the platform reports it+ (Windows ``rcWork``); on macOS/X11 it degrades to the monitor's full bounds.+ Units match the platform's input space — physical pixels on a+ per-monitor-DPI-aware Windows thread (the Jarvis Bar's Tk thread is pinned+ exactly that way, so these coordinates line up with the window geometry),+ global points on macOS.++ This is the primitive the on-screen bar uses to follow the mouse across+ monitors and to pin a cross-monitor drag to the screen it lands on. Returns+ ``None`` when it cannot be determined (headless / Wayland / missing native+ API) so callers keep the bar where it is instead of guessing. Never raises.+ """+ try:+ if sys.platform == "win32":+ return _win_work_area_at(x, y)+ if sys.platform == "darwin":+ return _macos_work_area_at(x, y)+ from jarvis.platform.probes import is_wayland # noqa: PLC0415++ if is_wayland():+ return None # no reliable global monitor geometry under Wayland+ return _x11_work_area_at(x, y)+ except Exception: # noqa: BLE001 — best-effort; a probe failure is never fatal+ return None+++def _win_work_area_at(x: int, y: int) -> tuple[int, int, int, int] | None:+ """``rcWork`` of the monitor under ``(x, y)`` via ``MonitorFromPoint``.++ Thread-scoped per-monitor DPI pin (restored afterwards), mirroring+ :func:`_win_virtual_bounds`, so the metrics are physical pixels even in an+ unaware host — matching the DPI-aware Tk thread that calls this.+ ``MONITOR_DEFAULTTONEAREST`` keeps a point just off every monitor mapped to+ the closest one rather than failing.+ """+ import ctypes # noqa: PLC0415+ from ctypes import wintypes # noqa: PLC0415++ user32 = ctypes.windll.user32++ class _RECT(ctypes.Structure):+ _fields_ = [+ ("left", ctypes.c_long), ("top", ctypes.c_long),+ ("right", ctypes.c_long), ("bottom", ctypes.c_long),+ ]++ class _MONITORINFO(ctypes.Structure):+ _fields_ = [+ ("cbSize", wintypes.DWORD), ("rcMonitor", _RECT),+ ("rcWork", _RECT), ("dwFlags", wintypes.DWORD),+ ]++ class _POINT(ctypes.Structure):+ _fields_ = [("x", ctypes.c_long), ("y", ctypes.c_long)]++ _MONITOR_DEFAULTTONEAREST = 0x00000002++ set_ctx = None+ prev = None+ try:+ set_ctx = user32.SetThreadDpiAwarenessContext+ set_ctx.restype = ctypes.c_void_p+ set_ctx.argtypes = [ctypes.c_void_p]+ for context in (-4, -3): # PER_MONITOR_AWARE_V2, then V1 (1607)+ prev = set_ctx(ctypes.c_void_p(context))+ if prev is not None:+ break+ except (OSError, AttributeError): # pre-1607: read unpinned+ set_ctx = None+ try:+ # HMONITOR is pointer-sized: without an explicit restype ctypes returns+ # a 32-bit c_int and TRUNCATES the handle on Win64. Set ONLY the restype+ # (stable, process-safe) and re-wrap the returned int as an HMONITOR when+ # passing it on — deliberately WITHOUT setting argtypes on the shared+ # GetMonitorInfoW, whose POINTER type would otherwise be bound to this+ # function-local _MONITORINFO class and break _win_primary_origin's own+ # call (a different local class) as well as the next call here.+ user32.MonitorFromPoint.restype = wintypes.HMONITOR+ hmon = user32.MonitorFromPoint(+ _POINT(int(x), int(y)), _MONITOR_DEFAULTTONEAREST+ )+ info = _MONITORINFO()+ info.cbSize = ctypes.sizeof(_MONITORINFO)+ if not user32.GetMonitorInfoW(wintypes.HMONITOR(hmon), ctypes.byref(info)):+ return None+ rc = info.rcWork+ left, top = int(rc.left), int(rc.top)+ width, height = int(rc.right - rc.left), int(rc.bottom - rc.top)+ finally:+ if set_ctx is not None and prev is not None:+ try:+ set_ctx(ctypes.c_void_p(prev))+ except Exception: # noqa: BLE001,S110 — best-effort DPI-context restore+ pass+ if width <= 0 or height <= 0:+ return None+ return (left, top, width, height)+++def _macos_work_area_at(x: int, y: int) -> tuple[int, int, int, int] | None:+ """Bounds of the ``CGGetActiveDisplayList`` display under ``(x, y)``.++ Full display bounds (not visible-frame): the macOS bar runs on Qt, which+ resolves the dock/menu-bar-aware available geometry itself, so this Quartz+ helper only needs to answer "which display" for any other caller. Returns+ ``None`` when Quartz is unavailable (headless) or no display matches.+ """+ try:+ from Quartz import ( # noqa: PLC0415+ CGDisplayBounds,+ CGGetActiveDisplayList,+ )+ except Exception: # noqa: BLE001 — pyobjc not installed+ return None+ err, display_ids, count = CGGetActiveDisplayList(16, None, None)+ if err or not display_ids or not count:+ return None+ fallback: tuple[int, int, int, int] | None = None+ for display in list(display_ids)[:count]:+ r = CGDisplayBounds(display)+ left, top = int(r.origin.x), int(r.origin.y)+ width, height = int(r.size.width), int(r.size.height)+ if width <= 0 or height <= 0:+ continue+ rect = (left, top, width, height)+ if fallback is None:+ fallback = rect+ if left <= x < left + width and top <= y < top + height:+ return rect+ return fallback+++def _x11_work_area_at(x: int, y: int) -> tuple[int, int, int, int] | None:+ """Rectangle of the ``xrandr`` monitor under ``(x, y)``.++ Full monitor geometry (no panel subtraction — X11 has no single portable+ work-area query); the bar's own bottom gap keeps it clear of a bottom+ panel in practice. Returns ``None`` when ``xrandr`` is missing or no+ monitor contains the point.+ """+ import subprocess # noqa: PLC0415++ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS # noqa: PLC0415++ if shutil.which("xrandr") is None:+ return None+ try:+ out = subprocess.run(+ ["xrandr", "--query"], capture_output=True, text=True, timeout=3.0,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ ).stdout+ except Exception: # noqa: BLE001 — xrandr missing / no display+ return None+ fallback: tuple[int, int, int, int] | None = None+ for line in out.splitlines():+ if " connected " not in line:+ continue+ for tok in line.split():+ # A geometry token looks like "3840x2160+1920+0".+ if "x" not in tok or "+" not in tok:+ continue+ try:+ size, off_x, off_y = tok.split("+")+ width, height = (int(v) for v in size.split("x"))+ left, top = int(off_x), int(off_y)+ except (IndexError, ValueError):+ break+ if width <= 0 or height <= 0:+ break+ rect = (left, top, width, height)+ if fallback is None:+ fallback = rect+ if left <= x < left + width and top <= y < top + height:+ return rect+ break # only the first geometry token on a "connected" line+ return fallback++def native_primary_origin() -> tuple[int, int] | None:"""Best-effort virtual-desktop top-left ``(x, y)`` of the OS primary monitor,or ``None`` when it cannot be determined (headless / Wayland / missing libs).diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex 36958c16e8..fc77d52c0a 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -2050,6 +2050,9 @@ class DesktopApp:accent=self.cfg.ui.bar_accent,startup_gated=gate_until_voice_ready,size_scale=getattr(self.cfg.ui, "bar_size_scale", 1.0),+ follow_cursor_monitor=getattr(+ self.cfg.ui, "bar_follow_cursor_monitor", True+ ),)surface.start_in_thread()logger.info(@@ -2099,6 +2102,9 @@ class DesktopApp:accent=self.cfg.ui.bar_accent,startup_gated=gate_until_voice_ready,size_scale=getattr(self.cfg.ui, "bar_size_scale", 1.0),+ follow_cursor_monitor=getattr(+ self.cfg.ui, "bar_follow_cursor_monitor", True+ ),)else: # "mascot" (and any legacy style value)from ui.orb.overlay import OrbOverlay@@ -2174,6 +2180,33 @@ class DesktopApp:logger.opt(exception=exc).warning("set_bar_size failed")return {"ok": True, "applied_live": False, "scale": scale}+ def set_bar_follow_cursor(self, enabled: bool) -> dict[str, object]:+ """Live-toggle 'follow the mouse to the active monitor'.++ Updates the in-memory config and calls the surface's ``set_follow_cursor``+ so the running bar starts/stops following the cursor across monitors+ immediately. Only the bar surface implements it — on the mascot /+ no-overlay style this reports ``applied_live=False`` (persisted only).+ """+ from loguru import logger++ enabled = bool(enabled)+ try:+ self.cfg.ui.bar_follow_cursor_monitor = enabled+ except Exception: # noqa: BLE001+ pass+ bar = getattr(self, "_orb", None)+ fn = getattr(bar, "set_follow_cursor", None)+ if not callable(fn):+ return {"ok": True, "applied_live": False, "enabled": enabled}+ try:+ fn(enabled)+ logger.info("bar_follow_cursor_monitor set live to {}.", enabled)+ return {"ok": True, "applied_live": True, "enabled": enabled}+ except Exception as exc: # noqa: BLE001+ logger.opt(exception=exc).warning("set_bar_follow_cursor failed")+ return {"ok": True, "applied_live": False, "enabled": enabled}+def swap_overlay(self, style: str) -> dict[str, object]:"""Apply an overlay style change at runtime *as far as is Tk-safe*.@@ -3328,16 +3361,26 @@ class DesktopApp:sys.stderr.write("Backend did not start within 45s — aborting.\n")return self.shutdown() or 2- self._window = webview.create_window(- WINDOW_TITLE,- self._url(),- width=1280,- height=800,- min_size=(900, 600),- resizable=True,- confirm_close=False,- background_color="#0a0e14",- )+ try:+ self._window = webview.create_window(+ WINDOW_TITLE,+ self._url(),+ width=1280,+ height=800,+ min_size=(900, 600),+ resizable=True,+ confirm_close=False,+ background_color="#0a0e14",+ )+ except webview.WebViewException as exc:+ # No native desktop-window backend is available. This is the Linux+ # case where pywebview needs the system GTK+WebKit packages (gi ++ # webkit2gtk) that pip cannot install; without them it raises+ # WebViewException. Degrade gracefully instead of crashing (and+ # killing the already-serving backend thread). Windows+ # (gui='edgechromium') and macOS reach this only if their native+ # backend genuinely cannot start, and behave identically otherwise.+ return self._degrade_to_browser_ui(exc)self._window_visible = True# Close button = minimize-to-tray (user decision 2026-04-20).@@ -3400,12 +3443,22 @@ class DesktopApp:# webview.start blocks the main thread. func/args gets called after# the first load (pywebview-internal), so evaluate_js hits a# DOM-ready context.- webview.start(- func=self._inject_token,- args=(self._window,),- gui=gui,- debug=debug,- )+ #+ # On Linux, webview.start selects the native GUI backend here and raises+ # WebViewException when neither GTK+WebKit nor Qt (with Python bindings)+ # is installed — a system dependency pip cannot provide. Do NOT let that+ # crash the app or tear down the backend thread that is already serving+ # the UI: degrade to the browser-UI fallback. No-op on Windows/macOS+ # where the native backend starts normally.+ try:+ webview.start(+ func=self._inject_token,+ args=(self._window,),+ gui=gui,+ debug=debug,+ )+ except webview.WebViewException as exc:+ return self._degrade_to_browser_ui(exc)# webview.start returns once the window is destroyed. A real quit (the# X, tray "Quit", or a restart) has set ``_user_requested_quit``; in that# case tear every surface down AND guarantee the process dies, so nothing@@ -3426,6 +3479,60 @@ class DesktopApp:os._exit(code)return code+ def _degrade_to_browser_ui(self, exc: BaseException) -> int:+ """Fallback when no native desktop-window backend is available.++ Reached only when pywebview cannot open a native window — in practice a+ Linux host missing the system GTK+WebKit packages (``gi`` ++ ``webkit2gtk``) that pip cannot install. The backend thread is already+ running and serving the full UI over HTTP, so instead of crashing (which+ would also kill that daemon thread) we keep it alive and point the user+ at the local URL, the packages to install, or the ``--headless`` mode.++ Blocks the main thread on the backend thread so the server keeps serving+ until the user stops it (Ctrl+C) or it exits. Windows/macOS never reach+ this while their native backend works.+ """+ from loguru import logger as _logger++ url = f"http://127.0.0.1:{self.cfg.ui.admin_api_port}"+ _logger.warning("Native desktop window unavailable: {}", exc)+ message = (+ "\n"+ "Personal Jarvis could not open a native desktop window.\n"+ f"Reason: {exc}\n"+ "\n"+ "The backend is running and already serving the full UI. To use it:\n"+ f" - Open this address in a web browser: {url}\n"+ " - Or install the system GTK 3 + WebKit2GTK packages pywebview "+ "needs and restart\n"+ " (Debian/Ubuntu, for example: "+ "'sudo apt install python3-gi gir1.2-webkit2-4.1').\n"+ " - Or re-run without a window using the '--headless' flag.\n"+ "\n"+ "Press Ctrl+C to stop the server.\n"+ )+ with suppress(Exception):+ sys.stderr.write(message)+ sys.stderr.flush()++ # Keep the already-serving backend alive by parking the main thread on+ # it. Join in short slices so a Ctrl+C (KeyboardInterrupt lands on the+ # main thread) is honoured promptly instead of after an indefinite wait.+ thread = self._backend_thread+ try:+ if thread is not None and thread is not threading.current_thread():+ while thread.is_alive():+ thread.join(timeout=1.0)+ else:+ # No separate backend handle to join (should not happen on this+ # path): park the main thread so the daemon server keeps serving.+ while True:+ time.sleep(3600)+ except KeyboardInterrupt:+ _logger.info("Interrupted — shutting the browser-UI fallback down.")+ return self.shutdown() or 0+def _start_icon_setter_thread(self) -> None:"""Polling thread: sets the taskbar/titlebar icon once the HWND exists.diff --git a/jarvis/ui/jarvisbar/host.py b/jarvis/ui/jarvisbar/host.pyindex 5d8d263f8e..bf8e751e6d 100644--- a/jarvis/ui/jarvisbar/host.py+++ b/jarvis/ui/jarvisbar/host.py@@ -96,6 +96,8 @@ def dispatch(surface: Any, msg: dict[str, Any]) -> bool:_call(surface, "set_muted", bool(msg.get("muted", False)))elif op == "set_size_scale":_call(surface, "set_size_scale", float(msg.get("scale", 1.0)))+ elif op == "set_follow_cursor":+ _call(surface, "set_follow_cursor", bool(msg.get("enabled", True)))elif op == "set_persistent":# Live flag flip — the same plain attribute write the in-process# set_bar_persistent path performs (no Tk marshal needed).@@ -307,7 +309,14 @@ def _build_surface(cfg: dict[str, Any]) -> Any:)kwargs = {key: cfg[key]- for key in ("persistent", "accent", "opacity", "startup_gated", "size_scale")+ for key in (+ "persistent",+ "accent",+ "opacity",+ "startup_gated",+ "size_scale",+ "follow_cursor_monitor",+ )if key in cfg}if sys.platform == "darwin":diff --git a/jarvis/ui/jarvisbar/interaction.py b/jarvis/ui/jarvisbar/interaction.pyindex 3c2f1c458a..b74009e04d 100644--- a/jarvis/ui/jarvisbar/interaction.py+++ b/jarvis/ui/jarvisbar/interaction.py@@ -108,11 +108,115 @@ def clamp_to_screen(return cx, cy+# --------------------------------------------------------------------------- #+# Multi-monitor placement: relative (free-space) position within a work area #+# --------------------------------------------------------------------------- #+# A monitor "work area" is ``(left, top, width, height)`` in the platform's+# input units (physical pixels on a per-monitor-DPI-aware Windows thread, Tk+# points on macOS). The bar's position is reasoned about as a RELATIVE spot+# inside that rectangle so it reproduces on a differently-sized monitor: the+# free space (work size minus the bar size) is the basis, so 0.5 is always+# "centred", 1.0 is "flush to the right/bottom edge", regardless of the+# monitor's resolution. Storing a raw pixel offset instead would fall off a+# smaller screen and drift on a larger one — the exact multi-monitor bug this+# model avoids.++WorkArea = tuple[int, int, int, int]+++def _clamp01(v: float) -> float:+ return 0.0 if v < 0.0 else 1.0 if v > 1.0 else float(v)+++def relative_within(+ x: int, y: int, *, work: WorkArea, bar_w: int, bar_h: int+) -> tuple[float, float]:+ """Bar top-left ``(x, y)`` as free-space fractions inside a work area.++ Returns ``(rel_x, rel_y)`` each clamped to ``[0, 1]``. Degenerate free+ space (a bar as large as, or larger than, the work area on an axis) yields+ ``0.0`` on that axis so the value stays finite and in range.+ """+ wl, wt, ww, wh = work+ free_w = ww - bar_w+ free_h = wh - bar_h+ rel_x = 0.0 if free_w <= 0 else (x - wl) / free_w+ rel_y = 0.0 if free_h <= 0 else (y - wt) / free_h+ return (_clamp01(rel_x), _clamp01(rel_y))+++def project_relative(+ rel_x: float, rel_y: float, *, work: WorkArea, bar_w: int, bar_h: int+) -> tuple[int, int]:+ """Inverse of :func:`relative_within`: fractions → absolute ``(x, y)``.++ Places the bar on ``work`` so its relative spot matches, keeping it fully+ inside (the projection over the clamped free space is inherently in-bounds).+ This is what migrates the bar between monitors of different sizes without+ it drifting off-screen or losing its centred/edge placement.+ """+ wl, wt, ww, wh = work+ free_w = max(0, ww - bar_w)+ free_h = max(0, wh - bar_h)+ x = wl + round(_clamp01(rel_x) * free_w)+ y = wt + round(_clamp01(rel_y) * free_h)+ return (int(x), int(y))+++def clamp_to_work_area(+ x: int, y: int, *, work: WorkArea, bar_w: int, bar_h: int, margin: int+) -> tuple[int, int]:+ """Keep the bar fully inside a work area that may have a non-zero origin.++ The generalisation of :func:`clamp_to_screen` to a specific monitor's work+ rectangle (a secondary monitor has a non-zero ``left``/``top``). Used when a+ drag is released so the drop is pinned to the monitor it landed on rather+ than snapped back to the primary monitor (the historical multi-monitor+ drag bug).+ """+ wl, wt, ww, wh = work+ min_x, min_y = wl + margin, wt + margin+ max_x = max(min_x, wl + ww - bar_w - margin)+ max_y = max(min_y, wt + wh - bar_h - margin)+ cx = min(max(int(x), min_x), max_x)+ cy = min(max(int(y), min_y), max_y)+ return cx, cy++# --------------------------------------------------------------------------- ## Position persistence ([jarvisbar] section, absolute x/y) ## --------------------------------------------------------------------------- #def load_jarvisbar_position(path: str | Path) -> tuple[int, int] | None:"""Read [jarvisbar] pos_x/pos_y. Returns None if absent/invalid."""+ section = _load_jarvisbar_section(path)+ if section is None:+ return None+ x, y = section.get("pos_x"), section.get("pos_y")+ if isinstance(x, int) and isinstance(y, int):+ return x, y+ return None+++def load_jarvisbar_relative(path: str | Path) -> tuple[float, float] | None:+ """Read [jarvisbar] rel_x/rel_y (the free-space fractions).++ This is the monitor-independent placement (see :func:`relative_within`): it+ survives a monitor being resized, unplugged, or the bar migrating to a+ differently-sized screen, whereas the absolute pos_x/pos_y is only correct+ on the monitor it was captured on. Returns ``None`` when absent/invalid so+ callers fall back to the absolute position (older configs have no rel keys).+ """+ section = _load_jarvisbar_section(path)+ if section is None:+ return None+ rx, ry = section.get("rel_x"), section.get("rel_y")+ if isinstance(rx, (int, float)) and isinstance(ry, (int, float)):+ return (_clamp01(float(rx)), _clamp01(float(ry)))+ return None+++def _load_jarvisbar_section(path: str | Path) -> dict | None:+ """Return the parsed ``[jarvisbar]`` table, or ``None`` if absent/invalid."""import tomllibtry:@@ -124,19 +228,24 @@ def load_jarvisbar_position(path: str | Path) -> tuple[int, int] | None:except (UnicodeDecodeError, tomllib.TOMLDecodeError):return Nonesection = data.get("jarvisbar")- if not isinstance(section, dict):- return None- x, y = section.get("pos_x"), section.get("pos_y")- if isinstance(x, int) and isinstance(y, int):- return x, y- return None+ return section if isinstance(section, dict) else None-def save_jarvisbar_position(path: str | Path, x: int, y: int) -> None:+def save_jarvisbar_position(+ path: str | Path,+ x: int,+ y: int,+ *,+ rel: tuple[float, float] | None = None,+) -> None:"""Atomically persist [jarvisbar] pos_x/pos_y, comment- and BOM-safe.- Reuses ``config_writer._WRITE_LOCK`` so the write serialises with every- other jarvis.toml mutation (AP-7). No-op if the config file is missing.+ When ``rel`` (the monitor-independent free-space fractions) is supplied it+ is written alongside as ``rel_x``/``rel_y`` — the primary placement truth+ for multi-monitor migration; the absolute pos stays for back-compat and the+ no-monitor-info fallback. Reuses ``config_writer._WRITE_LOCK`` so the write+ serialises with every other jarvis.toml mutation (AP-7). No-op if the config+ file is missing."""import os@@ -161,6 +270,9 @@ def save_jarvisbar_position(path: str | Path, x: int, y: int) -> None:doc["jarvisbar"] = sectionsection["pos_x"] = int(x)section["pos_y"] = int(y)+ if rel is not None:+ section["rel_x"] = round(_clamp01(rel[0]), 4)+ section["rel_y"] = round(_clamp01(rel[1]), 4)out = tomlkit.dumps(doc)if had_bom:out = bom + outdiff --git a/jarvis/ui/jarvisbar/null_overlay.py b/jarvis/ui/jarvisbar/null_overlay.pyindex c34423dd68..0faf0dc3c6 100644--- a/jarvis/ui/jarvisbar/null_overlay.py+++ b/jarvis/ui/jarvisbar/null_overlay.py@@ -17,6 +17,7 @@ class NullOverlay:def hide(self) -> None: ...def set_level(self, level: float) -> None: ...def set_size_scale(self, scale: float) -> None: ...+ def set_follow_cursor(self, enabled: bool) -> None: ...def play_animation(self, name: str, **params: Any) -> None: ...def stop_animation(self, name: str) -> None: ...def show_listening_transcript(self, text: str = "", duration_ms: int = 30000) -> None: ...diff --git a/jarvis/ui/jarvisbar/overlay.py b/jarvis/ui/jarvisbar/overlay.pyindex 3ea4b145eb..e644223edf 100644--- a/jarvis/ui/jarvisbar/overlay.py+++ b/jarvis/ui/jarvisbar/overlay.py@@ -156,6 +156,14 @@ MIN_FRAME_DELAY_MS = 1# reinterpreted as an idle-body click that immediately starts a new session.HANGUP_CLICK_GUARD_S = 1.0+# Cursor-monitor follow poll. When enabled, the bar hops to whichever monitor+# the mouse pointer is currently on (keeping its RELATIVE spot, so a bigger or+# smaller monitor lines up — see interaction.project_relative). A ~250 ms poll+# is imperceptible to the user yet costs only one global-pointer read plus one+# MonitorFromPoint per tick — well off the animation hot path. The poll never+# fights an in-progress drag and never re-derives a hidden/gated bar's spot.+CURSOR_MONITOR_POLL_MS = 250+def _primary_work_area() -> tuple[int, int, int, int] | None:"""Primary-monitor work area (left, top, right, bottom) EXCLUDING the@@ -347,6 +355,7 @@ class JarvisBarOverlay:opacity: float = BAR_ALPHA,startup_gated: bool = False,size_scale: float = 1.0,+ follow_cursor_monitor: bool = True,) -> None:self._persistent = persistentself._accent = accent@@ -393,6 +402,14 @@ class JarvisBarOverlay:self._x = 0self._y = 0self._drag: dict | None = None+ # Multi-monitor follow: when on, the bar migrates to the monitor under+ # the mouse. ``_rel_pos`` is the monitor-independent free-space fraction+ # (the persisted placement truth); ``_cur_work`` is the work area the+ # bar currently sits on, so the poll can tell when the cursor's monitor+ # differs and a migration is due. Both are seeded in ``_resolve_position``.+ self._follow_cursor = bool(follow_cursor_monitor)+ self._rel_pos: tuple[float, float] | None = None+ self._cur_work: tuple[int, int, int, int] | None = Noneself._level_unsub: Callable[[], None] | None = Noneself._on_mute_toggle: Callable[[], None] | None = None# Interaction callbacks let the macOS companion host forward actions@@ -518,6 +535,15 @@ class JarvisBarOverlay:returnself._enqueue_ui(lambda s=self._user_size_scale: self._do_apply_size(s))+ def set_follow_cursor(self, enabled: bool) -> None:+ """Live-toggle 'follow the mouse to the active monitor'.++ A plain flag the cursor-monitor poll reads each tick, so turning it off+ simply stops future migrations (the bar stays put) and turning it on+ makes the next poll place it on the monitor under the mouse. Atomic bool+ write — no Tk marshal needed, like ``set_muted``."""+ self._follow_cursor = bool(enabled)+def set_on_mute_toggle(self, callback: Callable[[], None] | None) -> None:self._on_mute_toggle = callback@@ -741,6 +767,7 @@ class JarvisBarOverlay:self._schedule_ui_queue()self._schedule_frame_watchdog() # independent anti-freeze revival loopself._schedule_z_order_guard()+ self._schedule_cursor_monitor_guard() # follow the mouse across monitorsif not self._should_start_withdrawn():self._do_show()self._started.set()@@ -764,46 +791,102 @@ class JarvisBarOverlay:# ------------------------------------------------------------------ ## Tk-thread internals ## ------------------------------------------------------------------ #- def _resolve_position(self, root: Any) -> None:+ def _cursor_global(self) -> tuple[int, int] | None:+ """Best-effort global pointer ``(x, y)`` in the bar's coordinate space.++ ``winfo_pointerxy`` reports the same DPI-aware physical pixels the+ window geometry uses (the Tk thread is pinned PER_MONITOR_AWARE), so it+ lines up with :func:`jarvis.platform.monitors.work_area_at`. ``None`` on+ any failure so callers keep the current placement."""+ root = self._root+ if root is None:+ return Nonetry:- sw = int(root.winfo_screenwidth())- sh = int(root.winfo_screenheight())+ px, py = root.winfo_pointerxy()+ return (int(px), int(py))+ except Exception: # noqa: BLE001 — pointer probe is best-effort+ return None++ def _work_area_for_point(self, x: int, y: int) -> tuple[int, int, int, int]:+ """Work area ``(left, top, width, height)`` of the monitor at ``(x, y)``.++ Degrades exactly like the old default anchor did when no per-monitor+ info is available: the Windows primary work area (taskbar excluded),+ then the full primary screen. So a headless/Wayland host keeps the+ single-monitor behaviour instead of guessing."""+ try:+ from jarvis.platform.monitors import work_area_at++ wa = work_area_at(int(x), int(y))+ if wa is not None:+ return wa+ except Exception: # noqa: BLE001 — monitor probe is best-effort+ log.debug("jarvisbar work-area probe failed", exc_info=True)+ primary = _primary_work_area()+ if primary is not None:+ wl, wt, wr, wb = primary+ return (wl, wt, wr - wl, wb - wt)+ try:+ return (+ 0,+ 0,+ int(self._root.winfo_screenwidth()),+ int(self._root.winfo_screenheight()),+ )except Exception: # noqa: BLE001- sw, sh = 1920, 1080+ return (0, 0, 1920, 1080)++ def _resolve_position(self, root: Any) -> None:+ del root # geometry is derived from the resolved monitor work areapos: tuple[int, int] | None = None+ rel: tuple[float, float] | None = Nonetry:from jarvis.core.config_writer import DEFAULT_CONFIG_FILEpos = interaction.load_jarvisbar_position(DEFAULT_CONFIG_FILE)+ rel = interaction.load_jarvisbar_relative(DEFAULT_CONFIG_FILE)except Exception: # noqa: BLE001- pos = None- if pos is not None:- self._x, self._y = interaction.clamp_to_screen(- pos[0],- pos[1],- screen_w=sw,- screen_h=sh,+ pos, rel = None, None++ # A legacy config stored only the absolute spot: recover its relative+ # placement from the monitor it belonged to, so an upgrade keeps the+ # spot (and, in follow mode, reproduces it on the cursor's monitor).+ if rel is None and pos is not None:+ pos_work = self._work_area_for_point(pos[0], pos[1])+ rel = interaction.relative_within(+ pos[0], pos[1], work=pos_work, bar_w=renderer.WIN_W, bar_h=renderer.WIN_H+ )++ # Choose the monitor to place on: follow mode boots on the monitor under+ # the mouse; pinned mode uses the monitor the saved spot belonged to.+ if self._follow_cursor:+ anchor = self._cursor_global() or pos or (0, 0)+ else:+ anchor = pos or (0, 0)+ work = self._work_area_for_point(anchor[0], anchor[1])++ if rel is not None:+ self._x, self._y = interaction.project_relative(+ rel[0], rel[1], work=work, bar_w=renderer.WIN_W, bar_h=renderer.WIN_H+ )+ else:+ # Fresh install: bottom-centre on the chosen monitor, just above its+ # taskbar (the work area already excludes the taskbar on Windows).+ wl, wt, ww, wh = work+ self._x = wl + (ww - renderer.WIN_W) // 2+ self._y = wt + wh - renderer.WIN_H - TASKBAR_GAP_PX+ self._x, self._y = interaction.clamp_to_work_area(+ self._x,+ self._y,+ work=work,bar_w=renderer.WIN_W,bar_h=renderer.WIN_H,margin=MARGIN_PX,)- else:- # Anchor just ABOVE the taskbar (work area), exactly centered —- # not on the taskbar. Fall back to the full-screen bottom if the- # work area is unavailable (non-Windows / query failure).- wa = _primary_work_area()- if wa is not None:- wl, wt, wr, wb = wa- self._x = wl + (wr - wl - renderer.WIN_W) // 2- self._y = wb - renderer.WIN_H - TASKBAR_GAP_PX- else:- self._x, self._y = interaction.default_bottom_center(- screen_w=sw,- screen_h=sh,- bar_w=renderer.WIN_W,- bar_h=renderer.WIN_H,- margin=MARGIN_PX,- )+ self._rel_pos = interaction.relative_within(+ self._x, self._y, work=work, bar_w=renderer.WIN_W, bar_h=renderer.WIN_H+ )+ self._cur_work = workdef _do_apply_size(self, user_scale: float) -> None:"""Recompute geometry for ``user_scale`` and resize the window (Tk thread).@@ -848,21 +931,27 @@ class JarvisBarOverlay:bottom_y = self._y + old_win_hnew_x = round(center_x - renderer.WIN_W / 2.0)new_y = round(bottom_y - renderer.WIN_H)- try:- sw = int(self._root.winfo_screenwidth())- sh = int(self._root.winfo_screenheight())- new_x, new_y = interaction.clamp_to_screen(- new_x,- new_y,- screen_w=sw,- screen_h=sh,- bar_w=renderer.WIN_W,- bar_h=renderer.WIN_H,- margin=MARGIN_PX,- )- except Exception: # noqa: BLE001 — clamping is best-effort- log.debug("jarvisbar resize clamp failed", exc_info=True)+ # Clamp to the monitor the bar sits on (measured at the new centre), not+ # the primary screen, so a resize near a secondary-monitor edge stays on+ # that monitor.+ work = self._work_area_for_point(+ new_x + renderer.WIN_W // 2, new_y + renderer.WIN_H // 2+ )+ new_x, new_y = interaction.clamp_to_work_area(+ new_x,+ new_y,+ work=work,+ bar_w=renderer.WIN_W,+ bar_h=renderer.WIN_H,+ margin=MARGIN_PX,+ )self._x, self._y = new_x, new_y+ # The bar size changed, so the relative-spot basis changed: refresh it+ # from the new geometry so the follow poll keeps the correct fraction.+ self._cur_work = work+ self._rel_pos = interaction.relative_within(+ self._x, self._y, work=work, bar_w=renderer.WIN_W, bar_h=renderer.WIN_H+ )if self._canvas is not None:try:self._canvas.config(width=renderer.WIN_W, height=renderer.WIN_H)@@ -895,6 +984,18 @@ class JarvisBarOverlay:# reveal over leaving a genuinely hidden bar unavailable.log.debug("jarvisbar mapped-state query failed", exc_info=True)+ # Follow mode: a bar that pops from withdrawn (a non-persistent bar on+ # wake, or the boot-gated bar's first map) should appear on the monitor+ # the mouse is on right now, not wherever it was last mapped. The move+ # runs while still withdrawn so it is invisible.+ if self._follow_cursor and self._project_onto_cursor_monitor():+ try:+ self._root.geometry(+ f"{renderer.WIN_W}x{renderer.WIN_H}+{self._x}+{self._y}"+ )+ except Exception: # noqa: BLE001+ log.debug("jarvisbar follow-monitor reveal move failed", exc_info=True)+# Reveal transaction (BUG-030): the boot-created bar can remain# withdrawn for many seconds while voice warms. Its idle renderer has# settled by then and deliberately skips byte-identical repaints. If a@@ -1210,6 +1311,78 @@ class JarvisBarOverlay:except Exception: # noqa: BLE001log.warning("JarvisBar Z-order guard re-arm skipped", exc_info=True)+ # ------------------------------------------------------------------ #+ # Follow the mouse across monitors #+ # ------------------------------------------------------------------ #+ def _project_onto_cursor_monitor(self) -> bool:+ """Re-place the bar on the monitor under the mouse, keeping its spot.++ Returns ``True`` when ``self._x/_y`` changed (the caller then applies the+ geometry). The bar's RELATIVE spot is projected onto the cursor monitor's+ work area, so a bigger or smaller monitor keeps the same centred/edge+ placement (:func:`interaction.project_relative`). Deliberately does NOT+ check the mapped state — the poll does that, while ``_do_show`` calls+ this before the window is mapped. Never persists: the relative spot is+ already the saved truth, so migrating monitors changes nothing durable."""+ if not self._follow_cursor or self._drag is not None:+ return False+ cursor = self._cursor_global()+ if cursor is None:+ return False+ work = self._work_area_for_point(cursor[0], cursor[1])+ prev_work = self._cur_work+ self._cur_work = work+ if work == prev_work:+ return False # cursor is on the monitor the bar already lives on+ rel = self._rel_pos+ if rel is None:+ rel = interaction.relative_within(+ self._x,+ self._y,+ work=prev_work or work,+ bar_w=renderer.WIN_W,+ bar_h=renderer.WIN_H,+ )+ new_x, new_y = interaction.project_relative(+ rel[0], rel[1], work=work, bar_w=renderer.WIN_W, bar_h=renderer.WIN_H+ )+ if (new_x, new_y) == (self._x, self._y):+ return False+ self._x, self._y = new_x, new_y+ return True++ def _schedule_cursor_monitor_guard(self) -> None:+ """~250 ms after-chain that follows the mouse across monitors.++ Independent of the frame loop and the Z-order guard. It acts only for a+ mapped, ungated, non-dragging bar with follow enabled; anything else is+ a pure re-arm. A single check error can never kill the loop (``finally``+ re-arms), and a deliberate ``stop()`` ends it cleanly."""+ if not self._running or self._root is None:+ return+ try:+ root = self._root+ if (+ self._follow_cursor+ and not getattr(self, "_startup_gated", False)+ and self._drag is None+ and bool(root.winfo_ismapped())+ and self._project_onto_cursor_monitor()+ ):+ root.geometry(f"{renderer.WIN_W}x{renderer.WIN_H}+{self._x}+{self._y}")+ except Exception: # noqa: BLE001 - the guard must itself never die+ log.debug("JarvisBar cursor-monitor guard check failed", exc_info=True)+ finally:+ if self._running and self._root is not None:+ try:+ self._root.after(+ CURSOR_MONITOR_POLL_MS, self._schedule_cursor_monitor_guard+ )+ except Exception: # noqa: BLE001+ log.warning(+ "JarvisBar cursor-monitor guard re-arm skipped", exc_info=True+ )+# ------------------------------------------------------------------ ## Drag (reposition) + click (start a voice session) ## ------------------------------------------------------------------ #@@ -1269,21 +1442,36 @@ class JarvisBarOverlay:self._on_click(d.get("cx", renderer.WIN_W / 2), hovered=bool(d.get("hovered")))returntry:- sw = int(self._root.winfo_screenwidth())- sh = int(self._root.winfo_screenheight())- self._x, self._y = interaction.clamp_to_screen(+ # Pin the drop to the monitor it LANDED on (measured at the bar's+ # centre), NOT the primary screen. Clamping to the primary is exactly+ # what used to snap a cross-monitor drag back to where it started —+ # the reported bug. The work-area helper degrades to the full primary+ # screen when no per-monitor info is available, so single-monitor and+ # headless hosts keep the old behaviour.+ work = self._work_area_for_point(+ self._x + renderer.WIN_W // 2,+ self._y + renderer.WIN_H // 2,+ )+ self._x, self._y = interaction.clamp_to_work_area(self._x,self._y,- screen_w=sw,- screen_h=sh,+ work=work,bar_w=renderer.WIN_W,bar_h=renderer.WIN_H,margin=MARGIN_PX,)self._root.geometry(f"{renderer.WIN_W}x{renderer.WIN_H}+{self._x}+{self._y}")+ # Remember the drop monitor + the monitor-independent relative spot so+ # the follow poll reproduces this placement on any other monitor.+ self._cur_work = work+ self._rel_pos = interaction.relative_within(+ self._x, self._y, work=work, bar_w=renderer.WIN_W, bar_h=renderer.WIN_H+ )from jarvis.core.config_writer import DEFAULT_CONFIG_FILE- interaction.save_jarvisbar_position(DEFAULT_CONFIG_FILE, self._x, self._y)+ interaction.save_jarvisbar_position(+ DEFAULT_CONFIG_FILE, self._x, self._y, rel=self._rel_pos+ )except Exception: # noqa: BLE001log.debug("jarvisbar position persist failed", exc_info=True)@@ -1430,18 +1618,35 @@ class JarvisBarOverlay:if self._root is None:returntry:- sw = int(self._root.winfo_screenwidth())- sh = int(self._root.winfo_screenheight())- self._x, self._y = interaction.default_bottom_center(- screen_w=sw,- screen_h=sh,+ # Reset onto the monitor the bar currently sits on — or, in follow+ # mode, the one under the mouse — not always the primary. The bar+ # returns to bottom-centre of the screen the user is actually on.+ cursor = self._cursor_global() if self._follow_cursor else None+ anchor = cursor or (+ self._x + renderer.WIN_W // 2,+ self._y + renderer.WIN_H // 2,+ )+ work = self._work_area_for_point(anchor[0], anchor[1])+ wl, wt, ww, wh = work+ self._x = wl + (ww - renderer.WIN_W) // 2+ self._y = wt + wh - renderer.WIN_H - TASKBAR_GAP_PX+ self._x, self._y = interaction.clamp_to_work_area(+ self._x,+ self._y,+ work=work,bar_w=renderer.WIN_W,bar_h=renderer.WIN_H,margin=MARGIN_PX,)self._root.geometry(f"{renderer.WIN_W}x{renderer.WIN_H}+{self._x}+{self._y}")+ self._cur_work = work+ self._rel_pos = interaction.relative_within(+ self._x, self._y, work=work, bar_w=renderer.WIN_W, bar_h=renderer.WIN_H+ )from jarvis.core.config_writer import DEFAULT_CONFIG_FILE- interaction.save_jarvisbar_position(DEFAULT_CONFIG_FILE, self._x, self._y)+ interaction.save_jarvisbar_position(+ DEFAULT_CONFIG_FILE, self._x, self._y, rel=self._rel_pos+ )except Exception: # noqa: BLE001log.debug("jarvisbar reset failed", exc_info=True)diff --git a/jarvis/ui/jarvisbar/qt_overlay.py b/jarvis/ui/jarvisbar/qt_overlay.pyindex de79b2744b..635a116cab 100644--- a/jarvis/ui/jarvisbar/qt_overlay.py+++ b/jarvis/ui/jarvisbar/qt_overlay.py@@ -53,6 +53,12 @@ TASKBAR_GAP_PX = 8HANGUP_CLICK_GUARD_S = 1.0_IDLE_SETTLE_TICKS = 30+# Cursor-monitor follow poll (ms). When enabled, the bar hops to whichever+# monitor the mouse is on, keeping its RELATIVE spot so a differently-sized+# monitor lines up (see interaction.project_relative). Cheap — one QCursor.pos()+# + one screenAt() per tick — and off the animation path.+CURSOR_MONITOR_POLL_MS = 250+_QT: SimpleNamespace | None = NoneGeometryBounds = tuple[int, int, int, int]@@ -376,6 +382,7 @@ class QtJarvisBarOverlay:opacity: float = BAR_ALPHA,startup_gated: bool = False,size_scale: float = 1.0,+ follow_cursor_monitor: bool = True,) -> None:self._persistent_flag = bool(persistent)self._accent = accent@@ -416,6 +423,7 @@ class QtJarvisBarOverlay:self._queue_timer: Any = Noneself._z_timer: Any = Noneself._hover_timer: Any = None+ self._cursor_timer: Any = Noneself._native_window: Any = Noneself._x = 0self._y = 0@@ -423,6 +431,14 @@ class QtJarvisBarOverlay:# location. When a hidden Dock returns, the bar retreats above it; when# the Dock hides again, the requested location is restored automatically.self._preferred_position: tuple[int, int] | None = None+ # Multi-monitor follow: migrate the bar to the monitor under the mouse.+ # ``_rel_pos`` is the monitor-independent free-space fraction (the+ # persisted placement truth); ``_cur_work`` is the work area the bar+ # currently sits on, so the poll can tell when the cursor's monitor+ # differs. Both seeded in ``_resolve_position_ui``.+ self._follow_cursor = bool(follow_cursor_monitor)+ self._rel_pos: tuple[float, float] | None = None+ self._cur_work: GeometryBounds | None = Noneself._drag: dict[str, Any] | None = Noneself._on_mute_toggle: Callable[[], None] | None = None@@ -493,6 +509,14 @@ class QtJarvisBarOverlay:self._user_size_scale = renderer.clamp_user_size(scale)self._enqueue_if_started(lambda s=self._user_size_scale: self._apply_size_ui(s))+ def set_follow_cursor(self, enabled: bool) -> None:+ """Live-toggle 'follow the mouse to the active monitor'.++ A plain flag the cursor-monitor poll reads each tick: off stops future+ migrations (the bar stays put), on makes the next poll place it on the+ monitor under the mouse. Atomic bool write, like ``set_muted``."""+ self._follow_cursor = bool(enabled)+def set_on_mute_toggle(self, callback: Callable[[], None] | None) -> None:self._on_mute_toggle = callback@@ -606,6 +630,12 @@ class QtJarvisBarOverlay:self._hover_timer.timeout.connect(self._poll_hover_ui)self._hover_timer.start()+ # Follow the mouse across monitors (own timer, off the animation path).+ self._cursor_timer = q.QtCore.QTimer(self._window)+ self._cursor_timer.setInterval(CURSOR_MONITOR_POLL_MS)+ self._cursor_timer.timeout.connect(self._poll_cursor_monitor_ui)+ self._cursor_timer.start()+# Submit a complete RGBA frame before the first map. Qt's translucent# backing already starts clear, and paintEvent replaces it atomically.self._render_frame_ui()@@ -714,6 +744,10 @@ class QtJarvisBarOverlay:def _do_show_ui(self) -> None:if self._window is None or self._startup_gated:return+ # Follow mode: a bar popping from hidden should appear on the monitor the+ # mouse is on right now, not wherever it was last shown.+ if self._follow_cursor:+ self._project_onto_cursor_monitor_ui()self._reconcile_dynamic_position_ui()self._invalidate_static_frame()self._render_frame_ui()@@ -808,6 +842,7 @@ class QtJarvisBarOverlay:self._queue_timer,self._z_timer,self._hover_timer,+ self._cursor_timer,):if timer is not None:timer.stop()@@ -979,24 +1014,70 @@ class QtJarvisBarOverlay:def _resolve_position_ui(self) -> None:position: tuple[int, int] | None = None+ rel: tuple[float, float] | None = Nonetry:from jarvis.core.config_writer import DEFAULT_CONFIG_FILE # noqa: PLC0415position = interaction.load_jarvisbar_position(DEFAULT_CONFIG_FILE)+ rel = interaction.load_jarvisbar_relative(DEFAULT_CONFIG_FILE)except Exception: # noqa: BLE001 - placement degrades to the defaultlog.debug("Qt Jarvis Bar position load failed", exc_info=True)- if position is None:- position = self._default_position_ui()- preferred_geometry = self._screen_geometry_for_point_ui(- position[0] + renderer.WIN_W // 2,- position[1] + renderer.WIN_H // 2,- respect_visible_dock=False,- )- self._preferred_position = self._clamp_to_geometry_ui(- position[0],- position[1],- preferred_geometry,- )++ # Recover a relative spot from a legacy absolute-only config so an+ # upgrade keeps the placement (and reproduces it on the follow monitor).+ if rel is None and position is not None:+ legacy_geometry = self._screen_geometry_for_point_ui(+ position[0] + renderer.WIN_W // 2,+ position[1] + renderer.WIN_H // 2,+ respect_visible_dock=False,+ )+ if legacy_geometry is not None:+ rel = interaction.relative_within(+ position[0],+ position[1],+ work=_geometry_bounds(legacy_geometry),+ bar_w=renderer.WIN_W,+ bar_h=renderer.WIN_H,+ )++ # Pick the monitor to place on: follow mode → the monitor under the+ # mouse; otherwise the monitor the saved spot belonged to.+ geometry: Any = None+ if self._follow_cursor:+ geometry = self._cursor_screen_geometry_ui(respect_visible_dock=False)+ if geometry is None:+ if position is None:+ position = self._default_position_ui()+ geometry = self._screen_geometry_for_point_ui(+ position[0] + renderer.WIN_W // 2,+ position[1] + renderer.WIN_H // 2,+ respect_visible_dock=False,+ )++ if geometry is not None and rel is not None:+ work = _geometry_bounds(geometry)+ self._preferred_position = interaction.project_relative(+ rel[0], rel[1], work=work, bar_w=renderer.WIN_W, bar_h=renderer.WIN_H+ )+ self._cur_work = work+ self._rel_pos = rel+ else:+ if position is None:+ position = self._default_position_ui()+ self._preferred_position = self._clamp_to_geometry_ui(+ position[0],+ position[1],+ geometry,+ )+ if geometry is not None:+ self._cur_work = _geometry_bounds(geometry)+ self._rel_pos = interaction.relative_within(+ self._preferred_position[0],+ self._preferred_position[1],+ work=self._cur_work,+ bar_w=renderer.WIN_W,+ bar_h=renderer.WIN_H,+ )self._x, self._y = self._preferred_positionself._reconcile_dynamic_position_ui()@@ -1033,6 +1114,9 @@ class QtJarvisBarOverlay:)window.setFixedSize(renderer.WIN_W, renderer.WIN_H)self._reconcile_dynamic_position_ui()+ # The bar size changed, so the relative-spot basis changed: refresh+ # it so the follow poll keeps the right fraction after a resize.+ self._refresh_rel_from_preferred_ui()# Repaint at the new size right away so the input mask + frame track# the slider without waiting a frame tick.self._invalidate_static_frame()@@ -1057,6 +1141,65 @@ class QtJarvisBarOverlay:self._window.move(self._x, self._y)return True+ # ------------------------------------------------------------------+ # Follow the mouse across monitors+ # ------------------------------------------------------------------+ def _cursor_screen_geometry_ui(self, *, respect_visible_dock: bool = True) -> Any:+ """Available geometry (QRect) of the screen under the mouse cursor."""+ q = _qt()+ if self._app is None:+ return None+ try:+ pos = q.QtGui.QCursor.pos()+ except Exception: # noqa: BLE001 - cursor probe is best-effort+ return None+ return self._screen_geometry_for_point_ui(+ int(pos.x()), int(pos.y()), respect_visible_dock=respect_visible_dock+ )++ def _project_onto_cursor_monitor_ui(self) -> bool:+ """Re-place the bar on the monitor under the mouse (follow mode).++ Projects the bar's RELATIVE spot onto the cursor monitor's available+ geometry and reconciles, so a bigger or smaller monitor keeps the same+ centred/edge placement (:func:`interaction.project_relative`). Returns+ whether the bar moved. Never persists — the relative spot is already the+ saved truth, so migrating monitors changes nothing durable."""+ if self._window is None or not self._follow_cursor or self._drag is not None:+ return False+ geometry = self._cursor_screen_geometry_ui()+ if geometry is None:+ return False+ work = _geometry_bounds(geometry)+ if work == self._cur_work:+ return False # cursor is on the monitor the bar already lives on+ rel = self._rel_pos+ if rel is None:+ if self._cur_work is None:+ self._cur_work = work+ return False+ base = self._preferred_position or (self._x, self._y)+ rel = interaction.relative_within(+ base[0],+ base[1],+ work=self._cur_work,+ bar_w=renderer.WIN_W,+ bar_h=renderer.WIN_H,+ )+ self._preferred_position = interaction.project_relative(+ rel[0], rel[1], work=work, bar_w=renderer.WIN_W, bar_h=renderer.WIN_H+ )+ self._cur_work = work+ return self._reconcile_dynamic_position_ui()++ def _poll_cursor_monitor_ui(self) -> None:+ """~250 ms follow tick: migrate to the monitor under the mouse."""+ if self._startup_gated or not self._desired_visible or not self._follow_cursor:+ return+ if self._drag is not None:+ return+ self._project_onto_cursor_monitor_ui()+def _mouse_press_ui(self, event: Any) -> bool:q = _qt()button = event.button()@@ -1121,6 +1264,9 @@ class QtJarvisBarOverlay:self._y,preferred_geometry,)+ # Pin to the monitor the drop LANDED on and capture its relative spot so+ # the follow poll can reproduce this placement on any other monitor.+ self._refresh_rel_from_preferred_ui()self._reconcile_dynamic_position_ui()self._persist_position_ui()return True@@ -1170,6 +1316,29 @@ class QtJarvisBarOverlay:except Exception: # noqa: BLE001 - a gesture must not kill the UI looplog.warning("Qt Jarvis Bar %s callback failed", label, exc_info=True)+ def _refresh_rel_from_preferred_ui(self) -> None:+ """Recompute ``_rel_pos``/``_cur_work`` from the preferred spot + its screen.++ The monitor-independent relative placement is derived from the current+ preferred position and the available geometry of the screen it sits on.+ Called after a drop, a reset, or a resize — anything that changes the+ absolute spot or the bar size — so the follow poll always projects the+ correct fraction. A missing screen (e.g. offscreen test plugin) leaves+ the previous value untouched."""+ base = self._preferred_position or (self._x, self._y)+ geometry = self._screen_geometry_for_point_ui(+ base[0] + renderer.WIN_W // 2,+ base[1] + renderer.WIN_H // 2,+ respect_visible_dock=False,+ )+ if geometry is None:+ return+ work = _geometry_bounds(geometry)+ self._cur_work = work+ self._rel_pos = interaction.relative_within(+ base[0], base[1], work=work, bar_w=renderer.WIN_W, bar_h=renderer.WIN_H+ )+def _persist_position_ui(self) -> None:try:from jarvis.core.config_writer import DEFAULT_CONFIG_FILE # noqa: PLC0415@@ -1179,6 +1348,7 @@ class QtJarvisBarOverlay:DEFAULT_CONFIG_FILE,position[0],position[1],+ rel=self._rel_pos,)except Exception: # noqa: BLE001 - position persistence is non-criticallog.debug("Qt Jarvis Bar position save failed", exc_info=True)@@ -1190,8 +1360,27 @@ class QtJarvisBarOverlay:self._ui_queue.put(self._reset_position_ui)def _reset_position_ui(self) -> None:- self._preferred_position = self._default_position_ui()+ # Reset onto the monitor the bar sits on — or, in follow mode, the one+ # under the mouse — not always the primary. Bottom-centre of that screen.+ geometry: Any = None+ if self._follow_cursor:+ geometry = self._cursor_screen_geometry_ui(respect_visible_dock=False)+ if geometry is None:+ base = self._preferred_position or (self._x, self._y)+ geometry = self._screen_geometry_for_point_ui(+ base[0] + renderer.WIN_W // 2,+ base[1] + renderer.WIN_H // 2,+ respect_visible_dock=False,+ )+ if geometry is not None:+ gx, gy, gw, gh = _geometry_bounds(geometry)+ x = gx + (gw - renderer.WIN_W) // 2+ y = gy + gh - renderer.WIN_H - TASKBAR_GAP_PX+ self._preferred_position = self._clamp_to_geometry_ui(x, y, geometry)+ else:+ self._preferred_position = self._default_position_ui()self._x, self._y = self._preferred_position+ self._refresh_rel_from_preferred_ui()self._reconcile_dynamic_position_ui()self._persist_position_ui()diff --git a/jarvis/ui/jarvisbar/subprocess_overlay.py b/jarvis/ui/jarvisbar/subprocess_overlay.pyindex d05bac1468..893b1f8b2b 100644--- a/jarvis/ui/jarvisbar/subprocess_overlay.py+++ b/jarvis/ui/jarvisbar/subprocess_overlay.py@@ -65,6 +65,7 @@ class SubprocessBarOverlay:opacity: float | None = None,startup_gated: bool = False,size_scale: float = 1.0,+ follow_cursor_monitor: bool = True,) -> None:self._persistent_flag = bool(persistent)self._accent = accent@@ -73,6 +74,9 @@ class SubprocessBarOverlay:# User "Bar size" multiplier, forwarded in the init line so the host# boots at the right size and a bounded respawn restores it.self._size_scale = float(size_scale)+ # "Follow the mouse to the active monitor" preference, forwarded in the+ # init line so the host boots with it and a bounded respawn restores it.+ self._follow_cursor_monitor = bool(follow_cursor_monitor)self._mode = "idle"self._muted = False# Mirror what the real host does at construction time. A persistent,@@ -198,6 +202,7 @@ class SubprocessBarOverlay:"accent": self._accent,"startup_gated": self._startup_gated,"size_scale": self._size_scale,+ "follow_cursor_monitor": self._follow_cursor_monitor,}if self._opacity is not None:init["opacity"] = float(self._opacity)@@ -250,6 +255,14 @@ class SubprocessBarOverlay:self._size_scale = float(scale)self._send({"op": "set_size_scale", "scale": self._size_scale})+ def set_follow_cursor(self, enabled: bool) -> None:+ """Forward a live 'follow the active monitor' toggle to the hosted bar.++ Stored too, so a bounded respawn re-sends the latest value in the fresh+ host's init line rather than snapping back to the boot value."""+ self._follow_cursor_monitor = bool(enabled)+ self._send({"op": "set_follow_cursor", "enabled": self._follow_cursor_monitor})+# The bar draws no text bubble and no mouth — the real surface no-ops# these, so the proxy saves the IPC round-trip and no-ops locally too.def play_animation(self, name: str, **params: Any) -> None: ...diff --git a/jarvis/ui/web/frontend/src/hooks/useBarFollowCursor.ts b/jarvis/ui/web/frontend/src/hooks/useBarFollowCursor.tsnew file mode 100644index 0000000000..0031ac6566--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/useBarFollowCursor.ts@@ -0,0 +1,54 @@+import { useCallback, useEffect, useState } from "react";++/**+ * "Follow the mouse to the active monitor" (bar_follow_cursor_monitor). On: the+ * bar hops to whichever monitor the cursor is on, keeping its relative spot.+ */+export interface BarFollowCursorResult {+ ok: boolean;+ enabled: boolean;+ persisted: boolean;+ applied_live: boolean;+ restart_required: boolean;+}++export function useBarFollowCursor() {+ const [enabled, setEnabledState] = useState<boolean | null>(null);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);++ const refetch = useCallback(async () => {+ setError(null);+ try {+ const res = await fetch("/api/settings/bar-follow-cursor");+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const data = await res.json();+ setEnabledState(Boolean(data.enabled));+ } catch (e) {+ setError((e as Error).message);+ } finally {+ setLoading(false);+ }+ }, []);++ useEffect(() => {+ void refetch();+ }, [refetch]);++ const setEnabled = useCallback(+ async (next: boolean): Promise<BarFollowCursorResult> => {+ const res = await fetch("/api/settings/bar-follow-cursor", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ enabled: next }),+ });+ const body = await res.json().catch(() => ({}));+ if (!res.ok) throw new Error(body.detail ?? `HTTP ${res.status}`);+ setEnabledState(Boolean(body.enabled));+ return body as BarFollowCursorResult;+ },+ [],+ );++ return { enabled, loading, error, refetch, setEnabled };+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex a8f8d12953..3493ac3832 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -110,6 +110,11 @@"description": "Die Bar bleibt auch im Leerlauf sichtbar. Aus: kein Standby — sie erscheint nur, wenn du dein Wake-Word sagst.","saved": "Bar-Sichtbarkeit aktualisiert."},+ "follow_cursor": {+ "title": "Der Maus zum aktiven Monitor folgen",+ "description": "Die Bar wechselt auf den Monitor, auf dem gerade deine Maus ist, und behält dieselbe Stelle. Aus: Sie bleibt auf einem Monitor.",+ "saved": "Monitor-Folgen aktualisiert."+ },"mute_music": {"title": "Musik beim Diktieren stummschalten","description": "Andere Apps (Spotify, Browser …) werden stumm, während du mit deinem Assistenten sprichst, und danach wiederhergestellt. Die eigene Stimme des Assistenten wird nie gemutet.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 7759dd199e..3f911265bd 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -110,6 +110,11 @@"description": "Keep the bar on screen even when idle. Off: no standby — it only appears when you say your wake word.","saved": "Bar visibility updated."},+ "follow_cursor": {+ "title": "Follow the mouse to the active monitor",+ "description": "The bar hops to whichever monitor your mouse is on, keeping the same spot. Off: it stays on one monitor.",+ "saved": "Follow-monitor updated."+ },"mute_music": {"title": "Mute music while dictating","description": "Mute other apps (Spotify, browser…) while you talk to your assistant, then restore them after. The assistant's own voice is never muted.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 3c61733eba..239729a348 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -110,6 +110,11 @@"description": "Mantén la barra en pantalla incluso inactiva. Desactivado: sin standby — solo aparece cuando dices tu palabra de activación.","saved": "Visibilidad de la barra actualizada."},+ "follow_cursor": {+ "title": "Seguir el ratón al monitor activo",+ "description": "La barra salta al monitor donde está tu ratón, manteniendo la misma posición. Desactivado: permanece en un solo monitor.",+ "saved": "Seguimiento de monitor actualizado."+ },"mute_music": {"title": "Silenciar música al dictar","description": "Silencia otras apps (Spotify, navegador…) mientras hablas con tu asistente y las restaura después. La voz del asistente nunca se silencia.",diff --git a/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.test.tsx b/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.test.tsxindex 6f0ae059da..c2d070dbc8 100644--- a/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.test.tsx+++ b/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.test.tsx@@ -29,6 +29,9 @@ vi.mock("@/hooks/useOverlayStyle", () => ({vi.mock("@/hooks/useBarPersistent", () => ({useBarPersistent: () => ({ enabled: true, loading: false, setEnabled: vi.fn() }),}));+vi.mock("@/hooks/useBarFollowCursor", () => ({+ useBarFollowCursor: () => ({ enabled: true, loading: false, setEnabled: vi.fn() }),+}));vi.mock("@/hooks/useMuteMusic", () => ({useMuteMusic: () => ({ enabled: false, loading: false, setEnabled: vi.fn() }),}));@@ -59,17 +62,19 @@ describe("OverlayTaskbarGroup", () => {expect(screen.getByText("taskbar_view.behavior_title")).toBeDefined();});- it("renders the overlay-style panel and all three behavior toggles", () => {+ it("renders the overlay-style panel and all four behavior toggles", () => {render(<OverlayTaskbarGroup />);expect(screen.getByText("settings_view.overlay_style.title")).toBeDefined();expect(screen.getByText("taskbar_view.bar_persistent.title")).toBeDefined();+ expect(screen.getByText("taskbar_view.follow_cursor.title")).toBeDefined();expect(screen.getByText("taskbar_view.mute_music.title")).toBeDefined();expect(screen.getByText("taskbar_view.sound_effects.title")).toBeDefined();});it("toggling the sound-effects switch calls the hook with the new value", () => {render(<OverlayTaskbarGroup />);- // Behavior block order: bar_persistent, mute_music, sound_effects.+ // Behavior block order: bar_persistent, follow_cursor, mute_music,+ // sound_effects — so the sound-effects switch is still the last one.const switches = screen.getAllByRole("switch");fireEvent.click(switches[switches.length - 1]);expect(setSoundEffects).toHaveBeenCalledWith(false);diff --git a/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.tsxindex 6a28b800e2..6a83044109 100644--- a/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.tsx+++ b/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.tsx@@ -1,9 +1,10 @@import { useEffect, useState } from "react";-import { Monitor, Eye, Volume2, Bell } from "lucide-react";+import { Monitor, Eye, Volume2, Bell, MousePointer } from "lucide-react";import { Switch } from "@/components/ui/switch";import { useOverlayStyle, type OverlayStyle } from "@/hooks/useOverlayStyle";import { StylePreview } from "@/components/overlay/OverlayStylePreviews";import { useBarPersistent } from "@/hooks/useBarPersistent";+import { useBarFollowCursor } from "@/hooks/useBarFollowCursor";import { BarSizeGroup } from "@/views/settings/BarSizeGroup";import { useMuteMusic } from "@/hooks/useMuteMusic";import { useSoundEffects } from "@/hooks/useSoundEffects";@@ -42,6 +43,8 @@ export function OverlayTaskbarGroup() {<div className="overflow-hidden rounded-lg border border-border bg-card/60"><BarPersistentRow /><div className="mx-4 border-t border-border/60" />+ <FollowCursorRow />+ <div className="mx-4 border-t border-border/60" /><MuteMusicRow /><div className="mx-4 border-t border-border/60" /><SoundEffectsRow />@@ -114,6 +117,41 @@ function BarPersistentRow() {);}+function FollowCursorRow() {+ const t = useT();+ const { enabled, loading, setEnabled } = useBarFollowCursor();+ const pushToast = useEventStore((s) => s.pushToast);+ const [saving, setSaving] = useState(false);++ async function onToggle(next: boolean) {+ setSaving(true);+ try {+ const res = await setEnabled(next);+ pushToast(+ res.applied_live ? "success" : "warning",+ res.applied_live+ ? t("taskbar_view.follow_cursor.saved")+ : t("taskbar_view.restart_required"),+ );+ } catch (e) {+ pushToast("error", (e as Error).message);+ } finally {+ setSaving(false);+ }+ }++ return (+ <ToggleRow+ icon={MousePointer}+ title={t("taskbar_view.follow_cursor.title")}+ description={t("taskbar_view.follow_cursor.description")}+ checked={enabled ?? true}+ disabled={loading || saving}+ onToggle={onToggle}+ />+ );+}+function MuteMusicRow() {const t = useT();const { enabled, loading, setEnabled } = useMuteMusic();diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.pyindex 6f3a2cfd8e..4b533d0be4 100644--- a/jarvis/ui/web/settings_routes.py+++ b/jarvis/ui/web/settings_routes.py@@ -1926,6 +1926,63 @@ async def put_bar_persistent(body: BoolToggleBody, request: Request) -> dict[str}+# ---------------------------------------------------------------------------+# "Follow the mouse to the active monitor" toggle (bar_follow_cursor_monitor):+# the on-screen bar hops to whichever monitor the mouse is on, keeping its+# relative spot. Persists to jarvis.toml and live-applies to the running bar.+# ---------------------------------------------------------------------------++[email protected]("/bar-follow-cursor")+async def get_bar_follow_cursor(request: Request) -> dict[str, object]:+ cfg = _config(request)+ ui = getattr(cfg, "ui", None)+ return {"enabled": bool(getattr(ui, "bar_follow_cursor_monitor", True))}++[email protected]("/bar-follow-cursor")+async def put_bar_follow_cursor(+ body: BoolToggleBody, request: Request+) -> dict[str, object]:+ enabled = bool(body.enabled)+ cfg = _config(request)+ ui = getattr(cfg, "ui", None)+ if ui is not None:+ try:+ ui.bar_follow_cursor_monitor = enabled # type: ignore[attr-defined]+ except Exception as exc: # noqa: BLE001+ log.debug("in-memory bar_follow_cursor_monitor update skipped: %s", exc)+ persisted = False+ try:+ from jarvis.core import config_writer++ config_writer.set_bar_follow_cursor_monitor(enabled)+ persisted = True+ except Exception as exc: # noqa: BLE001+ log.warning(+ "bar_follow_cursor_monitor persist failed (live apply still attempted): %s",+ exc,+ )+ applied_live = False+ desktop = getattr(request.app.state, "desktop_app", None)+ fn = getattr(desktop, "set_bar_follow_cursor", None)+ if callable(fn):+ try:+ res = await asyncio.to_thread(fn, enabled)+ applied_live = (+ bool(res.get("applied_live")) if isinstance(res, dict) else bool(res)+ )+ except Exception as exc: # noqa: BLE001+ log.warning("bar_follow_cursor_monitor live-apply failed: %s", exc)+ return {+ "ok": True,+ "enabled": enabled,+ "persisted": persisted,+ "applied_live": applied_live,+ "restart_required": not applied_live,+ }++# ---------------------------------------------------------------------------# "Bar size" slider (ui.bar_size_scale): a proportional multiplier for the# on-screen bar (width AND height scale together, shape preserved). Persists todiff --git a/tests/unit/ui/jarvisbar/test_follow_cursor_monitor.py b/tests/unit/ui/jarvisbar/test_follow_cursor_monitor.pynew file mode 100644index 0000000000..48d83c22ac--- /dev/null+++ b/tests/unit/ui/jarvisbar/test_follow_cursor_monitor.py@@ -0,0 +1,202 @@+"""Follow-the-active-monitor behaviour for the Jarvis Bar surfaces.++Covers the two surfaces' migration math (Tk on Windows/Linux, Qt on macOS) with+bare objects — no real window — plus the cross-platform monitor probe used by+the Tk path. The pure relative-placement helpers themselves are in+``test_interaction.py``; here we verify the surfaces call them correctly and+only migrate when the cursor's monitor actually changes.+"""+from __future__ import annotations++from jarvis.ui.jarvisbar import interaction, renderer+from jarvis.ui.jarvisbar.overlay import JarvisBarOverlay+++# --------------------------------------------------------------------------- #+# Tk surface (Windows / Linux) #+# --------------------------------------------------------------------------- #+def _bare_tk_bar(follow: bool = True) -> JarvisBarOverlay:+ bar = JarvisBarOverlay.__new__(JarvisBarOverlay)+ bar._root = None+ bar._drag = None+ bar._follow_cursor = follow+ bar._startup_gated = False+ bar._x, bar._y = 0, 0+ bar._rel_pos = None+ bar._cur_work = None+ return bar+++def test_tk_migrates_to_the_cursor_monitor_keeping_the_relative_spot(monkeypatch):+ bar = _bare_tk_bar()+ primary = (0, 0, 1920, 1080)+ secondary = (1920, 0, 2560, 1440) # a bigger monitor to the right+ # The bar sits bottom-centre on the primary monitor.+ bx = (1920 - renderer.WIN_W) // 2+ by = 1080 - renderer.WIN_H+ bar._x, bar._y = bx, by+ bar._cur_work = primary+ bar._rel_pos = interaction.relative_within(+ bx, by, work=primary, bar_w=renderer.WIN_W, bar_h=renderer.WIN_H+ )+ # Cursor is now on the secondary monitor.+ monkeypatch.setattr(bar, "_cursor_global", lambda: (2020, 200))+ monkeypatch.setattr(bar, "_work_area_for_point", lambda x, y: secondary)++ assert bar._project_onto_cursor_monitor() is True+ # Reprojected to bottom-centre of the SECONDARY monitor (same relative spot),+ # even though it is a different size — the whole point of the feature.+ assert bar._cur_work == secondary+ assert bar._x == 1920 + (2560 - renderer.WIN_W) // 2+ assert bar._y == 1440 - renderer.WIN_H+++def test_tk_does_not_migrate_while_cursor_stays_on_the_same_monitor(monkeypatch):+ bar = _bare_tk_bar()+ primary = (0, 0, 1920, 1080)+ bar._x, bar._y = 810, 1000+ bar._cur_work = primary+ bar._rel_pos = (0.5, 1.0)+ monkeypatch.setattr(bar, "_cursor_global", lambda: (500, 500))+ monkeypatch.setattr(bar, "_work_area_for_point", lambda x, y: primary)+ assert bar._project_onto_cursor_monitor() is False+ assert (bar._x, bar._y) == (810, 1000) # untouched+++def test_tk_follow_disabled_never_migrates(monkeypatch):+ bar = _bare_tk_bar(follow=False)+ bar._x, bar._y = 810, 1000+ bar._cur_work = (0, 0, 1920, 1080)+ bar._rel_pos = (0.5, 1.0)+ # Even with the cursor on another monitor, a disabled bar stays put.+ monkeypatch.setattr(bar, "_cursor_global", lambda: (2020, 500))+ monkeypatch.setattr(bar, "_work_area_for_point", lambda x, y: (1920, 0, 2560, 1440))+ assert bar._project_onto_cursor_monitor() is False+ assert (bar._x, bar._y) == (810, 1000)+++def test_tk_no_migration_during_a_drag(monkeypatch):+ bar = _bare_tk_bar()+ bar._drag = {"moved": True} # a drag in progress+ bar._cur_work = (0, 0, 1920, 1080)+ bar._rel_pos = (0.5, 1.0)+ monkeypatch.setattr(bar, "_cursor_global", lambda: (2020, 500))+ monkeypatch.setattr(bar, "_work_area_for_point", lambda x, y: (1920, 0, 2560, 1440))+ assert bar._project_onto_cursor_monitor() is False+++# --------------------------------------------------------------------------- #+# Qt surface (macOS) #+# --------------------------------------------------------------------------- #+class _FakeRect:+ """A minimal QRect-compatible double for _geometry_bounds()."""++ def __init__(self, x: int, y: int, w: int, h: int) -> None:+ self._v = (x, y, w, h)++ def x(self) -> int:+ return self._v[0]++ def y(self) -> int:+ return self._v[1]++ def width(self) -> int:+ return self._v[2]++ def height(self) -> int:+ return self._v[3]+++def test_qt_migrates_to_the_cursor_monitor(monkeypatch):+ from jarvis.ui.jarvisbar.qt_overlay import QtJarvisBarOverlay++ bar = QtJarvisBarOverlay.__new__(QtJarvisBarOverlay)+ bar._window = object()+ bar._follow_cursor = True+ bar._drag = None+ primary = (0, 0, 1920, 1080)+ secondary = (1920, 0, 2560, 1440)+ px = (1920 - renderer.WIN_W) // 2+ py = 1080 - renderer.WIN_H+ bar._preferred_position = (px, py)+ bar._x, bar._y = px, py+ bar._cur_work = primary+ bar._rel_pos = interaction.relative_within(+ px, py, work=primary, bar_w=renderer.WIN_W, bar_h=renderer.WIN_H+ )+ monkeypatch.setattr(+ bar, "_cursor_screen_geometry_ui", lambda **k: _FakeRect(*secondary)+ )+ reconciled: dict[str, object] = {}++ def _reconcile() -> bool:+ reconciled["pref"] = bar._preferred_position+ return True++ monkeypatch.setattr(bar, "_reconcile_dynamic_position_ui", _reconcile)++ assert bar._project_onto_cursor_monitor_ui() is True+ assert bar._cur_work == secondary+ assert bar._preferred_position == (+ 1920 + (2560 - renderer.WIN_W) // 2,+ 1440 - renderer.WIN_H,+ )+ assert reconciled["pref"] == bar._preferred_position # reconcile ran+++def test_qt_no_migration_when_monitor_unchanged(monkeypatch):+ from jarvis.ui.jarvisbar.qt_overlay import QtJarvisBarOverlay++ bar = QtJarvisBarOverlay.__new__(QtJarvisBarOverlay)+ bar._window = object()+ bar._follow_cursor = True+ bar._drag = None+ primary = (0, 0, 1920, 1080)+ bar._preferred_position = (810, 1000)+ bar._x, bar._y = 810, 1000+ bar._cur_work = primary+ bar._rel_pos = (0.5, 1.0)+ monkeypatch.setattr(+ bar, "_cursor_screen_geometry_ui", lambda **k: _FakeRect(*primary)+ )+ assert bar._project_onto_cursor_monitor_ui() is False+++# --------------------------------------------------------------------------- #+# Cross-platform monitor probe (Tk path) #+# --------------------------------------------------------------------------- #+def test_work_area_at_returns_none_under_wayland(monkeypatch):+ import jarvis.platform.monitors as monitors+ import jarvis.platform.probes as probes++ monkeypatch.setattr(monitors.sys, "platform", "linux")+ monkeypatch.setattr(probes, "is_wayland", lambda: True)+ assert monitors.work_area_at(10, 10) is None+++def test_x11_work_area_at_picks_the_monitor_under_the_point(monkeypatch):+ import jarvis.platform.monitors as monitors++ xrandr_out = (+ "Screen 0: minimum 320 x 200, current 5760 x 2160\n"+ "DP-1 connected primary 1920x1080+0+0 (normal) 520mm x 290mm\n"+ "HDMI-1 connected 3840x2160+1920+0 (normal) 600mm x 340mm\n"+ "DP-2 disconnected (normal left inverted right x axis y axis)\n"+ )++ class _Proc:+ returncode = 0+ stdout = xrandr_out++ monkeypatch.setattr(monitors.shutil, "which", lambda name: "/usr/bin/xrandr")+ monkeypatch.setattr(monitors.subprocess, "run", lambda *a, **k: _Proc())++ assert monitors._x11_work_area_at(2000, 100) == (1920, 0, 3840, 2160)+ assert monitors._x11_work_area_at(100, 100) == (0, 0, 1920, 1080)+++def test_x11_work_area_at_none_when_xrandr_missing(monkeypatch):+ import jarvis.platform.monitors as monitors++ monkeypatch.setattr(monitors.shutil, "which", lambda name: None)+ assert monitors._x11_work_area_at(0, 0) is Nonediff --git a/tests/unit/ui/jarvisbar/test_interaction.py b/tests/unit/ui/jarvisbar/test_interaction.pyindex b8f08058eb..073a5b9b5c 100644--- a/tests/unit/ui/jarvisbar/test_interaction.py+++ b/tests/unit/ui/jarvisbar/test_interaction.py@@ -117,3 +117,70 @@ def test_save_missing_file_is_noop(tmp_path):missing = tmp_path / "nope.toml"I.save_jarvisbar_position(missing, 1, 2) # must not raiseassert not missing.exists()+++# --------------------------------------------------------------------------- #+# Multi-monitor relative placement #+# --------------------------------------------------------------------------- #+def test_relative_within_center_and_edges():+ work = (0, 0, 1920, 1080)+ bw, bh = 300, 72+ # Bottom-centre → rel_x 0.5, rel_y ~1.0 (flush to the bottom of the free+ # space at the very bottom edge).+ x = (1920 - bw) // 2+ rel = I.relative_within(x, 1080 - bh, work=work, bar_w=bw, bar_h=bh)+ assert abs(rel[0] - 0.5) < 1e-6+ assert abs(rel[1] - 1.0) < 1e-6+ # Flush top-left → (0, 0).+ assert I.relative_within(0, 0, work=work, bar_w=bw, bar_h=bh) == (0.0, 0.0)+ # A degenerate axis (bar wider than the work area) yields 0.0, never a crash.+ assert I.relative_within(0, 0, work=(0, 0, 100, 1080), bar_w=300, bar_h=bh)[0] == 0.0+++def test_project_relative_preserves_placement_across_monitor_sizes():+ bw, bh = 300, 72+ small = (0, 0, 1920, 1080)+ big = (1920, 0, 3840, 2160) # a second monitor to the right, larger + offset+ # Bottom-centre on the small monitor…+ rel = I.relative_within((1920 - bw) // 2, 1080 - bh, work=small, bar_w=bw, bar_h=bh)+ # …reprojects to bottom-centre on the big monitor (same RELATIVE spot).+ x, y = I.project_relative(rel[0], rel[1], work=big, bar_w=bw, bar_h=bh)+ assert x == 1920 + (3840 - bw) // 2 # centred on the offset monitor+ assert y == 2160 - bh # flush to the bottom of its free space+++def test_relative_round_trip_is_identity_on_the_same_monitor():+ work = (100, 200, 2560, 1440)+ bw, bh = 284, 60+ for x, y in [(100, 200), (640, 980), (100 + 2560 - bw, 200 + 1440 - bh)]:+ rel = I.relative_within(x, y, work=work, bar_w=bw, bar_h=bh)+ assert I.project_relative(rel[0], rel[1], work=work, bar_w=bw, bar_h=bh) == (x, y)+++def test_clamp_to_work_area_pins_to_a_secondary_monitor():+ # A secondary monitor to the right: origin (1920, 0). A drop past its right+ # edge is pulled back INSIDE that monitor, not snapped to the primary — the+ # regression the cross-monitor drag fix targets.+ work = (1920, 0, 1920, 1080)+ bw, bh, margin = 300, 72, 12+ x, y = I.clamp_to_work_area(9000, 9000, work=work, bar_w=bw, bar_h=bh, margin=margin)+ assert x == 1920 + 1920 - bw - margin+ assert y == 1080 - bh - margin+ # A point already inside is unchanged.+ assert I.clamp_to_work_area(+ 2000, 500, work=work, bar_w=bw, bar_h=bh, margin=margin+ ) == (2000, 500)+++def test_relative_position_persists_and_round_trips(tmp_path):+ cfg = tmp_path / "jarvis.toml"+ cfg.write_text('[ui]\norb_style = "jarvis_bar"\n', encoding="utf-8")+ assert I.load_jarvisbar_relative(cfg) is None # not set yet+ I.save_jarvisbar_position(cfg, 640, 980, rel=(0.5, 1.0))+ assert I.load_jarvisbar_position(cfg) == (640, 980)+ rel = I.load_jarvisbar_relative(cfg)+ assert rel is not None+ assert abs(rel[0] - 0.5) < 1e-6 and abs(rel[1] - 1.0) < 1e-6+ # A save WITHOUT rel leaves the absolute position but does not require rel.+ I.save_jarvisbar_position(cfg, 100, 200)+ assert I.load_jarvisbar_position(cfg) == (100, 200)diff --git a/tests/unit/ui/jarvisbar/test_qt_overlay.py b/tests/unit/ui/jarvisbar/test_qt_overlay.pyindex d7dc2a6672..9f44cb1751 100644--- a/tests/unit/ui/jarvisbar/test_qt_overlay.py+++ b/tests/unit/ui/jarvisbar/test_qt_overlay.py@@ -271,7 +271,7 @@ def test_position_persistence_keeps_preferred_location_when_dock_is_visible(monkeypatch.setattr(qt_overlay.interaction,"save_jarvisbar_position",- lambda _path, x, y: saved.append((x, y)),+ lambda _path, x, y, rel=None: saved.append((x, y)),)surface._persist_position_ui() # noqa: SLF001diff --git a/tests/unit/ui/jarvisbar/test_subprocess_overlay.py b/tests/unit/ui/jarvisbar/test_subprocess_overlay.pyindex 5478f86d1a..adc1142ab7 100644--- a/tests/unit/ui/jarvisbar/test_subprocess_overlay.py+++ b/tests/unit/ui/jarvisbar/test_subprocess_overlay.py@@ -101,6 +101,7 @@ def test_init_line_carries_the_constructor_config(monkeypatch) -> None:"accent": "#123456","startup_gated": True,"size_scale": 1.0,+ "follow_cursor_monitor": True,}assert surface._ready.is_set() # scripted ready event consumed@@ -116,6 +117,17 @@ def test_size_scale_rides_the_init_line_and_live_op(monkeypatch) -> None:assert surface._size_scale == 0.8+def test_follow_cursor_rides_the_init_line_and_live_op(monkeypatch) -> None:+ # The follow-the-active-monitor preference is carried on the init line and a+ # later set_follow_cursor forwards a live op + updates the stored value so a+ # bounded respawn re-sends the latest choice.+ surface, proc = _started_proxy(monkeypatch, follow_cursor_monitor=False)+ assert proc.sent()[0]["follow_cursor_monitor"] is False+ surface.set_follow_cursor(True)+ assert proc.sent()[-1] == {"op": "set_follow_cursor", "enabled": True}+ assert surface._follow_cursor_monitor is True++def test_surface_calls_become_wire_ops_and_mirror_locally(monkeypatch) -> None:surface, proc = _started_proxy(monkeypatch)surface.show("speak")@@ -385,6 +397,7 @@ def test_host_death_triggers_respawn_and_reapplies_desired_state("accent": "#e7c46e","startup_gated": False,"size_scale": 1.0,+ "follow_cursor_monitor": True,}# Last known state (shown in "speak", muted, last level 0.9) re-applied.assert [m["op"] for m in sent[1:]] == ["show", "set_muted", "set_level"]@@ -513,6 +526,7 @@ def test_bar_init_payload_is_unchanged_by_the_mascot_variant(monkeypatch) -> Non"accent": "#e7c46e","startup_gated": False,"size_scale": 1.0,+ "follow_cursor_monitor": True,}assert not isinstance(surface, SubprocessMascotOverlay)diff --git a/tests/unit/ui/test_taskbar_routes.py b/tests/unit/ui/test_taskbar_routes.pyindex 164c2e534b..f59248163d 100644--- a/tests/unit/ui/test_taskbar_routes.py+++ b/tests/unit/ui/test_taskbar_routes.py@@ -9,11 +9,16 @@ from fastapi.testclient import TestClientfrom jarvis.ui.web.settings_routes import router-def _client(*, bar_persistent=True, ducking_enabled=False, desktop=None):+def _client(+ *, bar_persistent=True, follow_cursor=True, ducking_enabled=False, desktop=None+):app = FastAPI()app.include_router(router)app.state.config = SimpleNamespace(- ui=SimpleNamespace(bar_persistent=bar_persistent),+ ui=SimpleNamespace(+ bar_persistent=bar_persistent,+ bar_follow_cursor_monitor=follow_cursor,+ ),ducking=SimpleNamespace(enabled=ducking_enabled),)if desktop is not None:@@ -41,6 +46,27 @@ def test_put_bar_persistent_live(monkeypatch):assert applied["v"] is False and r.json()["applied_live"] is True+def test_get_bar_follow_cursor():+ r = _client(follow_cursor=False).get("/api/settings/bar-follow-cursor")+ assert r.status_code == 200 and r.json()["enabled"] is False+++def test_put_bar_follow_cursor_live(monkeypatch):+ import jarvis.core.config_writer as cw++ monkeypatch.setattr(cw, "set_bar_follow_cursor_monitor", lambda v, **k: None)+ applied = {}+ desktop = SimpleNamespace(+ set_bar_follow_cursor=lambda v: applied.setdefault("v", v)+ or {"applied_live": True}+ )+ r = _client(desktop=desktop).put(+ "/api/settings/bar-follow-cursor", json={"enabled": False}+ )+ assert r.status_code == 200+ assert applied["v"] is False and r.json()["applied_live"] is True++def test_get_mute_music():r = _client(ducking_enabled=False).get("/api/settings/mute-music")assert r.status_code == 200 and r.json()["enabled"] is False