Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

chore: auto-save WIP via Claude stop-hook safety net (2026-07-02 19:10)

Ruben Lütke4fd1041bc7b2
diff --git a/README.md b/README.md
index 74cb246beb..df3107acf6 100644
--- a/README.md
+++ b/README.md
@@ -16,6 +16,20 @@
<b>Talk to your computer — and watch it do the work: an open-source, privacy-first voice agent with full command of your PC.</b>
</p>
+<!--
+ TODO(demo): swap the placeholder below for the real demo. Two README-safe options:
+ 1) Drop a looping demo GIF at assets/demo/hero-demo.gif (keep it under ~10 MB so
+ GitHub renders it inline) and point the <img src> at that file.
+ 2) For an MP4 with sound, upload the file to a GitHub Release or issue, then paste
+ the github user-images video URL GitHub gives you in place of this whole <a>…</a>.
+ Either way, keep width≈820 and the alt text so the layout stays put.
+-->
+<p align="center">
+ <a href="https://github.com/PersonalJarvis/PersonalJarvis#readme">
+ <img src="assets/demo/demo-placeholder.svg" alt="Personal Jarvis — watch the demo" width="820" />
+ </a>
+</p>
+
---
Personal Jarvis is not a classical voice assistant. At its core is a fast **Router-Brain**
@@ -27,6 +41,26 @@ OpenRouter with one setting), **self-modifying** (it can safely edit its own con
through an audited, reversible pipeline), and runs everywhere — from a headless server with
a browser UI to a full desktop with a tray app, an Orb overlay, and global-hotkey wake.
+## What do you actually say to it?
+
+You talk to it the way you'd hand a task to a capable assistant — then it goes and does
+it. A few things it can do today:
+
+- **"Research the best open-source vector databases and drop a comparison in my Outputs."**
+ → spawns a background mission: a worker does the digging, a critic checks the work, and
+ you get a downloadable write-up in **Outputs**.
+- **"Read the README in my current project and summarize it in three sentences."**
+ → a file-aware worker opens the files, reads them, and reports back.
+- **"Open my browser and pull up the weather in Berlin."**
+ → drives the screen directly through computer-use — real clicks and keystrokes, not a
+ canned integration.
+- **"Call the clinic on Main Street and ask for their next open appointment."**
+ → places a real outbound phone call through the optional Twilio integration.
+- **"Remember that Alex prefers Signal over email."**
+ → writes the fact to the Knowledge Wiki so it sticks across every future session.
+- **"When the download finishes, ping me on Telegram."**
+ → sets a when-this-then-that trigger and reaches you on your channel when it fires.
+
## Why it's different
| | |
@@ -234,7 +268,7 @@ straight into provider costs, infrastructure, and development time.
<p align="center">
<i>This wall is empty — for now.</i><br/>
- Want to be the first? Reach out at <a href="mailto:[email protected]">[email protected]</a>.
+ Want to be the first? Reach out on <a href="https://discord.gg/UPu6pFWrJ">Discord</a> or <a href="https://x.com/PersonalJarvis">X</a>.
</p>
| Tier | You get |
@@ -244,8 +278,7 @@ straight into provider costs, infrastructure, and development time.
| **Sponsor** | The above + your logo on the sponsor wall |
| **Partner** | The above + a seat at the roadmap table |
-> Sponsorship is being set up. Want to talk before the page is live? Email
-> [[email protected]](mailto:[email protected]), or reach out on
+> Sponsorship is being set up. Want to talk before the page is live? Reach out on
> [Discord](https://discord.gg/UPu6pFWrJ) or [X](https://x.com/PersonalJarvis).
## Contributing
diff --git a/assets/demo/demo-placeholder.svg b/assets/demo/demo-placeholder.svg
new file mode 100644
index 0000000000..c14835d36f
--- /dev/null
+++ b/assets/demo/demo-placeholder.svg
@@ -0,0 +1,24 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720" width="1280" height="720" role="img" aria-label="Personal Jarvis — demo video placeholder">
+ <defs>
+ <linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="0" stop-color="#141210"/>
+ <stop offset="1" stop-color="#0e0d0c"/>
+ </linearGradient>
+ <radialGradient id="glow" cx="50%" cy="46%" r="42%">
+ <stop offset="0" stop-color="#e7c46e" stop-opacity="0.16"/>
+ <stop offset="1" stop-color="#e7c46e" stop-opacity="0"/>
+ </radialGradient>
+ </defs>
+
+ <rect width="1280" height="720" fill="url(#bg)"/>
+ <rect width="1280" height="720" fill="url(#glow)"/>
+ <rect x="6" y="6" width="1268" height="708" rx="18" fill="none" stroke="#e7c46e" stroke-opacity="0.28" stroke-width="2"/>
+
+ <!-- play button -->
+ <circle cx="640" cy="322" r="72" fill="none" stroke="#e7c46e" stroke-width="4" stroke-opacity="0.9"/>
+ <path d="M620 288 L682 322 L620 356 Z" fill="#e7c46e"/>
+
+ <text x="640" y="470" text-anchor="middle" font-family="Segoe UI, Helvetica, Arial, sans-serif" font-size="46" font-weight="700" fill="#f4efe4" letter-spacing="0.5">Personal Jarvis — live demo</text>
+ <text x="640" y="520" text-anchor="middle" font-family="Segoe UI, Helvetica, Arial, sans-serif" font-size="26" fill="#e7c46e">Talk to your computer, and watch it do the work</text>
+ <text x="640" y="628" text-anchor="middle" font-family="Segoe UI, Helvetica, Arial, sans-serif" font-size="20" fill="#8a847a">Placeholder — the final demo clip drops in right here</text>
+</svg>
diff --git a/docs/releases/v1.0.0.md b/docs/releases/v1.0.0.md
new file mode 100644
index 0000000000..acaca12545
--- /dev/null
+++ b/docs/releases/v1.0.0.md
@@ -0,0 +1,90 @@
+# Release notes — v1.0.0
+
+> **Ready-to-paste GitHub Release body.** Everything above the `---` line is the release
+> text; everything below it is the maintainer checklist for publishing and is not part of
+> the public notes.
+
+**Personal Jarvis v1.0.0 — First public release** · 2026-06-29
+
+Talk to your computer — and watch it do the work. Personal Jarvis is an open-source,
+privacy-first voice agent that turns one spoken request into a fleet of self-checking AI
+agents.
+
+## Highlights
+
+- **Voice-first pipeline** — wake word → speech-to-text → multi-provider Brain →
+ text-to-speech, fully streaming, with honest, language-aware readbacks (`de` / `en` / `es`).
+- **Provider-agnostic by design** — every tier (router, ack, STT, TTS, worker, critic)
+ degrades or crosses provider families on a missing or dead key. No single provider is
+ load-bearing, and credentials are managed entirely in-app.
+- **Cross-platform core** — the base install boots on a headless `python:3.11-slim` VPS;
+ Windows-desktop and local-voice features live behind optional extras.
+- **Jarvis-Agents mission system** — isolated `git worktree` workers with a self-healing
+ critic loop; every deliverable lands in **Outputs** as a downloadable artifact.
+- **Plugin marketplace** (OAuth + MCP) and a cross-platform control CLI (`jarvisctl`).
+
+### Also in this release
+
+- Declared `click` as an explicit dependency so the `jarvisctl` CLI imports on a clean
+ install, restoring a green CI.
+- Restored `TRADEMARK.md` to the published tree and removed a dead documentation link.
+- Stopped defaulting the archival store to the removed `chroma` backend.
+- `pyproject` metadata rewritten for the public release: English, cross-platform
+ description and a `[project.urls]` block.
+
+## Install
+
+One command on Windows, macOS, or Linux — no Docker, no Python-version archaeology. Bring
+your own keys; nothing is bundled.
+
+**Windows** (PowerShell)
+
+```powershell
+irm https://raw.githubusercontent.com/PersonalJarvis/PersonalJarvis/main/install/install.ps1 | iex
+```
+
+**macOS · Linux**
+
+```bash
+curl -fsSL https://raw.githubusercontent.com/PersonalJarvis/PersonalJarvis/main/install/install.sh | bash
+```
+
+## Verify the release (recommended)
+
+Releases are signed and can be verified before you trust them:
+
+- **cosign / TUF** — the signed-release chain lives in [`install/`](../../install/): run
+ [`install/install-verify.sh`](../../install/install-verify.sh) (macOS/Linux) or
+ [`install/install-verify.ps1`](../../install/install-verify.ps1) (Windows) to check the
+ signature and TUF metadata against the pinned trust root in
+ [`install/TRUST_ROOT.md`](../../install/TRUST_ROOT.md) before running anything.
+- Prefer to read first? The installers only create a venv, install dependencies, and run the
+ first-run wizard — every line is open source.
+
+## Links
+
+- Discord — https://discord.gg/UPu6pFWrJ
+- X — https://x.com/PersonalJarvis
+- Full changelog — [`CHANGELOG.md`](../../CHANGELOG.md)
+
+---
+
+## Maintainer checklist — how to publish this on GitHub
+
+These are the exact clicks. Nothing here is part of the public release text above.
+
+1. Open the repository on GitHub → in the right sidebar click **Releases** → **Draft a new
+ release** (top-right button).
+2. **Choose a tag** → type `v1.0.0` → click **Create new tag: v1.0.0 on publish**. Leave
+ **Target** on `main`.
+3. **Release title:** `v1.0.0 — First public release`.
+4. **Describe this release:** copy everything from the top of this file down to the `---`
+ line and paste it into the body box.
+5. Leave **Set as a pre-release** unchecked. Tick **Set as the latest release**.
+6. *(Optional)* If you produced signed build artifacts, drag them into the
+ **Attach binaries** area so the cosign/TUF verification above has something to check.
+7. Click **Publish release**.
+
+> Note: the `v1.0.0` git tag does not exist yet — step 2 creates it on publish. The current
+> newest tag in the repo is `v0.13.0`; `pyproject.toml` and `CHANGELOG.md` already declare
+> `1.0.0`, so publishing this release is what makes the tag match the version.
diff --git a/jarvis/cu/capture.py b/jarvis/cu/capture.py
index 9447e28fbe..d84cdc4198 100644
--- a/jarvis/cu/capture.py
+++ b/jarvis/cu/capture.py
@@ -71,6 +71,36 @@ def mss_grab(bbox: dict[str, int]) -> tuple[tuple[int, int], bytes]:
return (tuple(raw.size), raw.rgb)
+def grabber_for(target: MonitorInfo) -> Grabber:
+ """The grabber for a capture target.
+
+ A window target (``window_handle`` set) prefers the platform's NATIVE
+ per-window capture (:func:`jarvis.platform.window_capture.grab_window`,
+ e.g. ScreenCaptureKit by CGWindowID on macOS) and falls back to the rect
+ grab of the window's frame — pixel-identical for the raised foreground
+ window. The native-unavailable verdict sticks for the grabber's lifetime
+ (one perception frame) so stability re-grabs don't re-probe a dead path.
+ Plain monitor rects grab via mss directly.
+ """
+ if target.window_handle is None:
+ return mss_grab
+ handle = int(target.window_handle)
+ native_alive = True
+
+ def grab(bbox: dict[str, int]) -> tuple[tuple[int, int], bytes]:
+ nonlocal native_alive
+ if native_alive:
+ from jarvis.platform import window_capture # noqa: PLC0415
+
+ raw = window_capture.grab_window(handle, bbox)
+ if raw is not None:
+ return raw
+ native_alive = False
+ return mss_grab(bbox)
+
+ return grab
+
+
@dataclass(frozen=True)
class Frame:
"""One perception frame: the image the model sees + its mapper.
@@ -250,6 +280,10 @@ def select_capture_target(
clamped_h = clamped_bottom - clamped_top
if clamped_w < _MIN_WINDOW_CAPTURE_W or clamped_h < _MIN_WINDOW_CAPTURE_H:
return monitor
+ # A native per-window grab captures the FULL window — only wire the
+ # window id through when the rect survived unclamped, so the mapper's
+ # capture rect always matches the grabbed image (aspect guard).
+ unclamped = (clamped_left, clamped_top, clamped_w, clamped_h) == rect
logger.debug(
"[cu] window-scoped capture: '%s' rect=(%d,%d %dx%d)",
(win.title or "")[:60], clamped_left, clamped_top, clamped_w, clamped_h,
@@ -260,6 +294,7 @@ def select_capture_target(
width=clamped_w,
height=clamped_h,
name=f"window:{(win.title or '')[:48]}",
+ window_handle=int(win.handle) if (win.handle and unclamped) else None,
)
@@ -302,8 +337,13 @@ def capture_stable_frame(
the screen is still changing, up to ``stability_timeout_s``. Returns the
freshest grab either way; ``Frame.stable`` records whether idle was
reached. Never raises on a merely-unstable screen — only on a failed grab.
+
+ The grabber defaults to :func:`grabber_for` — native per-window capture
+ for window targets, the mss rect grab otherwise. Whatever grabbed the
+ pixels, the frame's mapper is built from the TARGET rect in input units
+ plus the encoded image size: the one central translation.
"""
- grabber = grab or mss_grab
+ grabber = grab or grabber_for(monitor)
deadline = time.monotonic() + max(0.0, stability_timeout_s)
current = grabber(monitor.bbox)
stable = False
diff --git a/jarvis/cu/engine.py b/jarvis/cu/engine.py
index 28efa6f762..da057e0dd1 100644
--- a/jarvis/cu/engine.py
+++ b/jarvis/cu/engine.py
@@ -55,7 +55,11 @@ from jarvis.cu.capture import (
select_capture_target,
thumbs_similar,
)
-from jarvis.cu.geometry import CoordinateConvention, MonitorInfo
+from jarvis.cu.geometry import (
+ CoordinateConvention,
+ CoordinateMapper,
+ MonitorInfo,
+)
from jarvis.cu.ledger import ActionLedger
from jarvis.cu.verify import (
crop_raw,
@@ -186,8 +190,10 @@ def _wayland_refusal() -> str | None:
if is_wayland():
return (
- "cannot run on a Wayland session: screen capture and "
- "synthetic input are blocked there. Use an X11 session."
+ "cannot run on a Wayland session: Wayland blocks global "
+ "screen capture and synthetic input by design. Log into an "
+ "X11 session instead (running single apps under XWayland "
+ "is not enough — the desktop session itself must be X11)."
)
except Exception: # noqa: BLE001
return None
@@ -338,6 +344,28 @@ def _summarize_action(action: dict[str, Any]) -> str:
#: preserve surroundings better than tight boxes (MEGA-GUI / UI-Zoomer).
_REFINE_RADIUS = 220
+def _crop_norm_to_screen(
+ bbox: dict[str, int], image_size: tuple[int, int], nx: float, ny: float,
+) -> tuple[int, int]:
+ """Resolve a 0-1000 point WITHIN a zoom crop to absolute screen units.
+
+ Builds a :class:`CoordinateMapper` for the crop rect — the SAME central
+ translation every other coordinate resolves through — so the refine path
+ can never disagree with the main mapping. The image size is the crop's
+ native pixel size (2x the rect on Retina); the result is clamped inside
+ the crop rect like every other mapped coordinate.
+ """
+ mapper = CoordinateMapper(
+ capture_left=int(bbox["left"]),
+ capture_top=int(bbox["top"]),
+ capture_width=int(bbox["width"]),
+ capture_height=int(bbox["height"]),
+ image_width=int(image_size[0]),
+ image_height=int(image_size[1]),
+ )
+ return mapper.normalized_to_screen(nx, ny)
+
+
_REFINE_SYSTEM = (
"You are a precision click-refinement assistant. The attached image is a "
"ZOOMED-IN crop of the live screen, centered on a click that produced NO "
@@ -423,9 +451,7 @@ async def _zoom_refine_point(
ny = min(max(float(obj.get("y", 0)), 0.0), 1000.0)
except (TypeError, ValueError):
return None
- rx = bbox["left"] + round(nx / 1000.0 * bbox["width"])
- ry = bbox["top"] + round(ny / 1000.0 * bbox["height"])
- return (rx, ry)
+ return _crop_norm_to_screen(bbox, raw[0], nx, ny)
async def _judge_done(
@@ -514,6 +540,17 @@ async def run_cu_loop(
yield _final(stderr=f"[cu] {wl}\n", exit_code=_EXIT_OBSERVE)
return
+ # Windows: declare the process PER_MONITOR_AWARE_V2 before any geometry
+ # is read (idempotent no-op elsewhere / on later calls). The thread pin
+ # in input_space() remains the per-call enforcement; the declaration
+ # keeps window rects and monitor metrics un-virtualized process-wide.
+ try:
+ from jarvis.core.win32_dpi import ensure_dpi_awareness # noqa: PLC0415
+
+ ensure_dpi_awareness()
+ except Exception: # noqa: BLE001 — declaration is best-effort
+ log.debug("[cu] DPI awareness declaration failed", exc_info=True)
+
max_steps = max(25, int(getattr(ctx, "step_budget", 100)))
monitor_policy = str(getattr(ctx, "monitor", "primary") or "primary")
main_monitor = str(getattr(ctx, "main_monitor", "primary") or "primary")
@@ -820,6 +857,10 @@ async def run_cu_loop(
snapped = snap_point_to_element(
resolved_xy[0], resolved_xy[1], clickables,
capture_area=monitor.width * monitor.height,
+ capture_rect=(
+ monitor.left, monitor.top,
+ monitor.width, monitor.height,
+ ),
)
if snapped is not None:
sx2, sy2, snap_label = snapped
diff --git a/jarvis/cu/geometry.py b/jarvis/cu/geometry.py
index f78748163a..b4058597ce 100644
--- a/jarvis/cu/geometry.py
+++ b/jarvis/cu/geometry.py
@@ -106,9 +106,13 @@ def input_space() -> Iterator[None]:
@dataclass(frozen=True)
class MonitorInfo:
- """One monitor's rect in input units on the virtual desktop.
+ """One capture rect in input units on the virtual desktop.
``left``/``top`` can be negative (a monitor left of / above the primary).
+ A WINDOW-scoped capture target is the same rect type with the platform
+ window id in ``window_handle`` (Win32 hwnd / macOS CGWindowID / X11
+ window id) — the id native per-window grabbers capture through. A plain
+ monitor rect carries ``None``.
"""
left: int
@@ -117,6 +121,7 @@ class MonitorInfo:
height: int
is_primary: bool = False
name: str = ""
+ window_handle: int | None = None
@property
def bbox(self) -> dict[str, int]:
diff --git a/jarvis/cu/verify.py b/jarvis/cu/verify.py
index 93590c027a..65ffcb281d 100644
--- a/jarvis/cu/verify.py
+++ b/jarvis/cu/verify.py
@@ -225,6 +225,7 @@ def snap_point_to_element(
clickables: list[tuple[str, str, tuple[int, int, int, int]]],
*,
capture_area: int,
+ capture_rect: tuple[int, int, int, int] | None = None,
) -> tuple[int, int, str] | None:
"""Snap a model-predicted point to the CENTER of the smallest clickable
element whose rect contains it — or ``None`` (keep the raw point).
@@ -234,7 +235,11 @@ def snap_point_to_element(
stops mattering, at zero added latency (the rects ride the snapshot that
already runs in parallel with the capture). The SMALLEST containing rect
wins (leaf over ancestor); rects above ``_SNAP_MAX_AREA_FRACTION`` of
- the capture area never snap (container trap). Pure; never raises.
+ the capture area never snap (container trap). When ``capture_rect``
+ (left, top, width, height) is given, an element whose center lies
+ OUTSIDE it never snaps — a window-scoped capture must not let the
+ accessibility tree push a click out of the window the model saw.
+ Pure; never raises.
"""
best: tuple[int, str, int, int] | None = None # (area, label, cx, cy)
max_area = max(1, int(capture_area * _SNAP_MAX_AREA_FRACTION))
@@ -244,8 +249,13 @@ def snap_point_to_element(
area = rw * rh
if area > max_area:
continue
+ cx, cy = rx + rw // 2, ry + rh // 2
+ if capture_rect is not None:
+ cl, ct, cw, ch = capture_rect
+ if not (cl <= cx < cl + cw and ct <= cy < ct + ch):
+ continue
if best is None or area < best[0]:
- best = (area, name, rx + rw // 2, ry + rh // 2)
+ best = (area, name, cx, cy)
if best is None:
return None
return (best[2], best[3], best[1])
@@ -322,20 +332,31 @@ def crop_raw(
cy: int,
radius: int,
) -> tuple[tuple[int, int], bytes] | None:
- """Crop a square around screen point ``(cx, cy)`` out of a raw monitor
- grab covering screen ``rect`` (left, top, width, height in input units).
+ """Crop a square around screen point ``(cx, cy)`` out of a raw grab
+ covering screen ``rect`` (left, top, width, height in input units).
``None`` when the point lies outside the grab. The grab's pixel size may
- differ from the rect (Retina: point rect, pixel grab) — the point is
- scaled into grab pixels first. Pure PIL, no re-grab — one monitor grab
- yields both the local and the global effect signal."""
+ differ from the rect (Retina: point rect, pixel grab) — the screen point
+ resolves into grab pixels through the ONE central translation
+ (:class:`jarvis.cu.geometry.CoordinateMapper`), never hand-rolled math.
+ Pure PIL, no re-grab — one grab yields both the local and the global
+ effect signal."""
+ from jarvis.cu.geometry import CoordinateMapper # noqa: PLC0415
+
(w, h), rgb = raw
rl, rt, rw, rh = rect
if rw <= 0 or rh <= 0:
return None
- px = int((int(cx) - rl) * w / rw)
- py = int((int(cy) - rt) * h / rh)
- if not (0 <= px < w and 0 <= py < h):
+ try:
+ mapper = CoordinateMapper(
+ capture_left=rl, capture_top=rt,
+ capture_width=rw, capture_height=rh,
+ image_width=w, image_height=h,
+ )
+ except ValueError: # aspect mismatch: this grab is not of this rect
+ return None
+ if not mapper.contains_screen(int(cx), int(cy)):
return None
+ px, py = mapper.screen_to_image(int(cx), int(cy))
from PIL import Image # noqa: PLC0415
# Radius in input units -> grab pixels (uniform capture scale).
diff --git a/jarvis/platform/window_capture.py b/jarvis/platform/window_capture.py
new file mode 100644
index 0000000000..d48f0fcb0f
--- /dev/null
+++ b/jarvis/platform/window_capture.py
@@ -0,0 +1,173 @@
+"""Native per-window capture seam for the window-centric Computer-Use path.
+
+:func:`grab_window` returns ``((width, height), rgb_bytes)`` for one window's
+CURRENT content, or ``None`` when no native per-window capture is available
+on this host — callers then fall back to grabbing the window's frame rect
+from the virtual desktop (mss), which is pixel-identical for the raised
+foreground window Computer-Use acts on. Whatever produced the pixels, the
+position translation stays with the ONE central
+:class:`jarvis.cu.geometry.CoordinateMapper` built from the window's frame
+rect in input units.
+
+Per platform:
+
+* **Windows** — deliberately ``None``: the DPI-pinned GDI rect grab of the
+ DWM extended frame bounds IS the native path here (physical virtual-desktop
+ pixels under PER_MONITOR_AWARE_V2). ``PrintWindow`` would add
+ occluded-window capture at the cost of per-app quirks (GPU-composited
+ windows render black) — CU always raises its target first, so the rect
+ grab sees exactly the window.
+* **macOS** — ScreenCaptureKit by CGWindowID (``SCScreenshotManager``,
+ macOS 14+; pyobjc ``[desktop-macos]`` extra): captures the window on
+ whatever display it sits, at native backing resolution, independent of
+ monitor layout. Needs the Screen-Recording permission. Anything missing
+ degrades to ``None`` (rect-grab fallback via CoreGraphics/mss).
+* **Linux/X11** — ``None``: the window is identified and its geometry
+ resolved per window id (xdotool, see
+ :func:`jarvis.platform.window_state.window_frame_rect`); the pixels come
+ from the root rect grab in the same root-pixel space. Wayland offers no
+ addressable global window capture (the portal screencast flow is
+ user-interactive) and is refused upstream with the X11/XWayland message.
+
+Import-cleanliness (HN-7): no platform-only package at module scope; pyobjc
+frameworks are imported lazily inside the darwin path. Every failure returns
+``None`` — this seam must never raise into the capture loop.
+"""
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from jarvis.platform import detect_platform
+
+log = logging.getLogger(__name__)
+
+#: Completion-handler wait ceiling for one ScreenCaptureKit screenshot. SCK
+#: answers in tens of milliseconds; a hung/denied call must not stall the
+#: perceive loop, whose own observe timeout is 12 s.
+_SCK_TIMEOUT_S = 3.0
+
+
+def grab_window(
+ handle: int, bbox: dict[str, int],
+) -> tuple[tuple[int, int], bytes] | None:
+ """Capture one window natively by its platform window id.
+
+ ``bbox`` is the window's frame rect in input units (advisory — the
+ native backends capture the window's own current bounds). Returns
+ ``None`` whenever the host has no native per-window path; never raises.
+ """
+ try:
+ plat = detect_platform()
+ if plat == "darwin":
+ return _grab_window_macos(int(handle))
+ return None
+ except Exception: # noqa: BLE001 — capture seam must never raise
+ log.debug("grab_window failed (non-fatal)", exc_info=True)
+ return None
+
+
+def _grab_window_macos(window_id: int) -> tuple[tuple[int, int], bytes] | None:
+ """One ScreenCaptureKit screenshot of the window with ``window_id``.
+
+ Blocking wrapper over the async SCK API (pyobjc bridges the completion
+ handlers): resolve the ``SCWindow`` from ``SCShareableContent``, build a
+ desktop-independent window filter, size the configuration to the
+ window's point frame times its backing scale, and decode the returned
+ ``CGImage`` to raw RGB via an NSBitmapImageRep PNG round-trip (PIL does
+ the decode — no manual bytes-per-row/BGRA handling to get subtly wrong).
+
+ Requirements probed at runtime, each miss returning ``None``:
+ pyobjc ScreenCaptureKit framework (``[desktop-macos]`` extra), macOS 14+
+ (``SCScreenshotManager``), Screen-Recording permission, window still on
+ screen.
+ """
+ import io # noqa: PLC0415
+ import threading # noqa: PLC0415
+
+ try:
+ import ScreenCaptureKit as sck # noqa: PLC0415
+ from AppKit import NSBitmapImageRep # noqa: PLC0415
+ from PIL import Image # noqa: PLC0415
+ except Exception: # noqa: BLE001 — frameworks absent (base install)
+ log.debug("ScreenCaptureKit/AppKit unavailable", exc_info=True)
+ return None
+ manager = getattr(sck, "SCScreenshotManager", None)
+ if manager is None: # pre-14 macOS: no screenshot API on this framework
+ log.debug("SCScreenshotManager unavailable (macOS < 14)")
+ return None
+
+ # -- shareable content (async -> event) -------------------------------
+ content_box: dict[str, Any] = {}
+ content_ready = threading.Event()
+
+ def _content_handler(content, error): # pragma: no cover - live macOS only
+ content_box["content"] = content
+ content_box["error"] = error
+ content_ready.set()
+
+ sck.SCShareableContent.getShareableContentWithCompletionHandler_(
+ _content_handler,
+ )
+ if not content_ready.wait(_SCK_TIMEOUT_S):
+ log.debug("SCShareableContent timed out (permission prompt pending?)")
+ return None
+ content = content_box.get("content")
+ if content is None or content_box.get("error") is not None:
+ log.debug("SCShareableContent failed: %s", content_box.get("error"))
+ return None
+
+ target = None
+ for window in content.windows() or []:
+ if int(window.windowID()) == window_id:
+ target = window
+ break
+ if target is None:
+ log.debug("SCK window id %d not on screen", window_id)
+ return None
+
+ # -- screenshot (async -> event) ---------------------------------------
+ sc_filter = sck.SCContentFilter.alloc().initWithDesktopIndependentWindow_(
+ target,
+ )
+ config = sck.SCStreamConfiguration.alloc().init()
+ frame = target.frame() # points
+ try:
+ scale = float(sc_filter.pointPixelScale())
+ except Exception: # noqa: BLE001 — attribute is macOS 14+; default 2x-safe
+ scale = 2.0
+ config.setWidth_(max(1, round(frame.size.width * scale)))
+ config.setHeight_(max(1, round(frame.size.height * scale)))
+ config.setShowsCursor_(False)
+
+ image_box: dict[str, Any] = {}
+ image_ready = threading.Event()
+
+ def _image_handler(image, error): # pragma: no cover - live macOS only
+ image_box["image"] = image
+ image_box["error"] = error
+ image_ready.set()
+
+ manager.captureImageWithFilter_configuration_completionHandler_(
+ sc_filter, config, _image_handler,
+ )
+ if not image_ready.wait(_SCK_TIMEOUT_S):
+ log.debug("SCScreenshotManager timed out")
+ return None
+ cg_image = image_box.get("image")
+ if cg_image is None or image_box.get("error") is not None:
+ log.debug("SCK screenshot failed: %s", image_box.get("error"))
+ return None
+
+ # -- CGImage -> raw RGB -------------------------------------------------
+ rep = NSBitmapImageRep.alloc().initWithCGImage_(cg_image)
+ if rep is None:
+ return None
+ png = rep.representationUsingType_properties_(4, None) # NSPNGFileType
+ if png is None:
+ return None
+ img = Image.open(io.BytesIO(bytes(png))).convert("RGB")
+ return ((img.width, img.height), img.tobytes())
+
+
+__all__ = ["grab_window"]
diff --git a/jarvis/platform/window_state.py b/jarvis/platform/window_state.py
index d7fb515cd8..03cd2d4767 100644
--- a/jarvis/platform/window_state.py
+++ b/jarvis/platform/window_state.py
@@ -699,6 +699,96 @@ def _foreground_window_windows() -> WindowInfo | None:
return WindowInfo(title=buf.value or "", handle=int(hwnd))
+def _quartz_window_list() -> list:
+ """On-screen window info dicts via Quartz, front-to-back; ``[]`` when the
+ framework is absent (base install without ``[desktop-macos]``) or the call
+ fails. Bounds and ids come in the CG global space (points, top-left
+ origin) — the SAME space Quartz mouse events and mss capture rects use,
+ so no extra conversion may ever be applied to them."""
+ try:
+ from Quartz import ( # noqa: PLC0415
+ CGWindowListCopyWindowInfo,
+ kCGNullWindowID,
+ kCGWindowListExcludeDesktopElements,
+ kCGWindowListOptionOnScreenOnly,
+ )
+ except Exception: # noqa: BLE001 — pyobjc not installed
+ return []
+ try:
+ return list(CGWindowListCopyWindowInfo(
+ kCGWindowListOptionOnScreenOnly
+ | kCGWindowListExcludeDesktopElements,
+ kCGNullWindowID,
+ ) or [])
+ except Exception: # noqa: BLE001 — permission / transient CG error
+ log.debug("CGWindowListCopyWindowInfo failed", exc_info=True)
+ return []
+
+
+def _foreground_window_macos() -> WindowInfo | None:
+ """Frontmost normal-layer window with its CGWindowID.
+
+ ``CGWindowListCopyWindowInfo`` returns windows ordered front-to-back, so
+ the first entry on layer 0 is the frontmost app window (status items,
+ the Dock and overlays live on higher layers). ``kCGWindowName`` needs
+ the Screen-Recording permission — without it the owning app's name still
+ identifies the window. Falls back to the osascript title (no handle)
+ when Quartz is unavailable.
+ """
+ for entry in _quartz_window_list():
+ try:
+ if int(entry.get("kCGWindowLayer", 0) or 0) != 0:
+ continue
+ number = int(entry.get("kCGWindowNumber", 0) or 0)
+ title = str(
+ entry.get("kCGWindowName")
+ or entry.get("kCGWindowOwnerName")
+ or ""
+ )
+ return WindowInfo(title=title, handle=number or None)
+ except (TypeError, ValueError):
+ continue
+ title = get_foreground_title()
+ return WindowInfo(title=title) if title else None
+
+
+def _foreground_window_linux() -> WindowInfo | None:
+ """Active X11 window with its window id via xdotool.
+
+ Wayland and headless sessions return ``None`` (no global window identity
+ by design there); a missing xdotool degrades to the title-only path.
+ """
+ if is_wayland() or not display_present():
+ return None
+ if shutil.which("xdotool") is None:
+ title = get_foreground_title()
+ return WindowInfo(title=title) if title else None
+ proc = subprocess.run(
+ ["xdotool", "getactivewindow"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ if proc.returncode != 0:
+ return None
+ try:
+ win_id = int((proc.stdout or "").strip() or "0")
+ except ValueError:
+ return None
+ if not win_id:
+ return None
+ name = subprocess.run(
+ ["xdotool", "getwindowname", str(win_id)],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ title = (name.stdout or "").strip() if name.returncode == 0 else ""
+ return WindowInfo(title=title, handle=win_id)
+
+
def move_window_to_primary(
win: WindowInfo, primary: dict
) -> tuple[bool, str]:
@@ -828,24 +918,34 @@ def is_shell_window(win: WindowInfo) -> bool:
def window_frame_rect(win: WindowInfo) -> tuple[int, int, int, int] | None:
- """The window's VISIBLE frame ``(left, top, width, height)`` in
- virtual-desktop coordinates, or ``None`` when unavailable.
-
- Windows: ``DwmGetWindowAttribute(DWMWA_EXTENDED_FRAME_BOUNDS)`` — the rect
- the user actually sees. Plain ``GetWindowRect`` includes the invisible
- DWM resize-shadow border (~7 px per side), which would leak wallpaper
- into a window-scoped capture and skew every mapped click. Falls back to
- ``GetWindowRect`` when DWM is unavailable.
-
- NOTE: physical-pixel correctness on mixed-DPI desktops requires the
- calling thread to hold a per-monitor DPI context — Computer-Use callers
- invoke this inside :func:`jarvis.cu.geometry.input_space`.
-
- macOS/Linux return ``None`` today — callers keep their monitor-scope
- fallback (same graceful degrade as :func:`window_rect`).
+ """The window's VISIBLE frame ``(left, top, width, height)`` in the
+ platform's INPUT UNITS on the virtual desktop, or ``None`` when
+ unavailable. This is the rect the window-centric Computer-Use pipeline
+ captures and maps clicks into, so each backend MUST report the same
+ coordinate space the platform's input APIs consume:
+
+ * Windows — ``DwmGetWindowAttribute(DWMWA_EXTENDED_FRAME_BOUNDS)`` (the
+ rect the user actually sees; plain ``GetWindowRect`` includes the
+ invisible resize-shadow border, which would leak wallpaper into the
+ capture and skew every mapped click), physical virtual-desktop pixels.
+ Mixed-DPI correctness requires the calling thread to hold a
+ per-monitor DPI context — CU callers invoke this inside
+ :func:`jarvis.cu.geometry.input_space`.
+ * macOS — Quartz ``kCGWindowBounds`` by CGWindowID: global POINTS with a
+ top-left origin, exactly the space Quartz mouse events and mss rects
+ use (Retina backing pixels never appear here).
+ * Linux/X11 — ``xdotool getwindowgeometry`` by window id: root-window
+ pixels (the client-area rect; WM decorations are not part of it).
+ Wayland and headless sessions return ``None`` — callers fall back to
+ monitor scope and the engine's X11/XWayland refusal explains why.
"""
try:
- if detect_platform() != "win32" or not win.handle:
+ plat = detect_platform()
+ if plat == "darwin":
+ return _window_frame_rect_macos(win)
+ if plat == "linux":
+ return _window_frame_rect_linux(win)
+ if plat != "win32" or not win.handle:
return None
import ctypes # noqa: PLC0415
from ctypes import wintypes # noqa: PLC0415
@@ -876,6 +976,71 @@ def window_frame_rect(win: WindowInfo) -> tuple[int, int, int, int] | None:
return None
+def _window_frame_rect_macos(win: WindowInfo) -> tuple[int, int, int, int] | None:
+ """Window bounds by CGWindowID (or the frontmost layer-0 window when the
+ :class:`WindowInfo` carries no handle). Global points, top-left origin."""
+ target: dict | None = None
+ for entry in _quartz_window_list():
+ try:
+ if win.handle:
+ if int(entry.get("kCGWindowNumber", -1) or -1) == int(win.handle):
+ target = entry
+ break
+ elif int(entry.get("kCGWindowLayer", 0) or 0) == 0:
+ target = entry
+ break
+ except (TypeError, ValueError):
+ continue
+ if target is None:
+ return None
+ bounds = target.get("kCGWindowBounds") or {}
+ try:
+ left = int(bounds.get("X", 0))
+ top = int(bounds.get("Y", 0))
+ width = int(bounds.get("Width", 0))
+ height = int(bounds.get("Height", 0))
+ except (TypeError, ValueError):
+ return None
+ if width <= 0 or height <= 0:
+ return None
+ return (left, top, width, height)
+
+
+def _window_frame_rect_linux(win: WindowInfo) -> tuple[int, int, int, int] | None:
+ """Window geometry by X11 window id via ``xdotool getwindowgeometry
+ --shell`` (root-relative pixels). ``None`` on Wayland/headless/no tool."""
+ if is_wayland() or not display_present():
+ return None
+ if not win.handle or shutil.which("xdotool") is None:
+ return None
+ proc = subprocess.run(
+ ["xdotool", "getwindowgeometry", "--shell", str(int(win.handle))],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ if proc.returncode != 0:
+ return None
+ fields: dict[str, int] = {}
+ for line in (proc.stdout or "").splitlines():
+ key, sep, value = line.strip().partition("=")
+ if not sep:
+ continue
+ try:
+ fields[key.strip().upper()] = int(value.strip())
+ except ValueError:
+ continue
+ try:
+ left, top = fields["X"], fields["Y"]
+ width, height = fields["WIDTH"], fields["HEIGHT"]
+ except KeyError:
+ return None
+ if width <= 0 or height <= 0:
+ return None
+ return (left, top, width, height)
+
+
def window_is_maximized(win: WindowInfo) -> bool | None:
"""Whether the window is maximized; ``None`` when it cannot be read
(non-Windows today — callers must treat that as "don't touch")."""
diff --git a/jarvis/vision/screenshot.py b/jarvis/vision/screenshot.py
index 3b7da66cf2..6a5512d4be 100644
--- a/jarvis/vision/screenshot.py
+++ b/jarvis/vision/screenshot.py
@@ -24,7 +24,6 @@ import asyncio
import hashlib
import io
import logging
-import os
import time
from pathlib import Path
from typing import Literal
@@ -152,29 +151,29 @@ def select_capture_monitor(
logger.debug("select_capture_monitor: strategy=primary -> %s", primary.get("name"))
return primary
- if os.name != "nt":
- return primary
-
try:
- import ctypes # noqa: PLC0415
- from ctypes import wintypes # noqa: PLC0415
-
- hwnd = ctypes.windll.user32.GetForegroundWindow()
- if not hwnd:
+ # Cross-platform foreground follow (every OS is first-class): the
+ # window identity + frame rect come from the one platform seam
+ # (Win32 hwnd/DWM, macOS Quartz points, X11 xdotool root pixels) —
+ # the same units the mss monitor rects use on each platform.
+ from jarvis.platform import window_state as ws # noqa: PLC0415
+
+ win = ws.foreground_window()
+ if win is None:
logger.debug(
"select_capture_monitor: no foreground window — falling back to primary",
)
return primary
- rect = wintypes.RECT()
- if not ctypes.windll.user32.GetWindowRect(hwnd, ctypes.byref(rect)):
+ rect = ws.window_frame_rect(win) or ws.window_rect(win)
+ if rect is None:
logger.debug(
- "select_capture_monitor: GetWindowRect failed — falling back to primary",
+ "select_capture_monitor: foreground rect unreadable — falling back to primary",
)
return primary
- cx = (rect.left + rect.right) // 2
- cy = (rect.top + rect.bottom) // 2
+ cx = rect[0] + rect[2] // 2
+ cy = rect[1] + rect[3] // 2
for m in physical:
left, top = m["left"], m["top"]
@@ -183,7 +182,9 @@ def select_capture_monitor(
if left <= cx < right and top <= cy < bottom:
if m is not primary:
logger.info(
- "select_capture_monitor: foreground on %s (left=%d top=%d %dx%d) — capturing there instead of primary",
+ "select_capture_monitor: foreground on %s "
+ "(left=%d top=%d %dx%d) — capturing there "
+ "instead of primary",
m.get("name"),
left,
top,
@@ -200,7 +201,8 @@ def select_capture_monitor(
# Foreground center lies outside all physical monitors
# (e.g. window minimized -> rect = -32000/-32000).
logger.debug(
- "select_capture_monitor: foreground center (%d,%d) is on no monitor — falling back to primary",
+ "select_capture_monitor: foreground center (%d,%d) is on no "
+ "monitor — falling back to primary",
cx,
cy,
)
diff --git a/pyproject.toml b/pyproject.toml
index 872a7f2bbc..f5e99091c3 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -193,6 +193,9 @@ desktop-macos = [
"pyobjc-framework-Quartz>=10; sys_platform == 'darwin'",
"pyobjc-framework-ApplicationServices>=10; sys_platform == 'darwin'",
"pyobjc-framework-Accessibility>=10; sys_platform == 'darwin'",
+ # Native per-window Computer-Use capture (SCScreenshotManager by
+ # CGWindowID); runtime-probed — an absent framework degrades to rect grabs.
+ "pyobjc-framework-ScreenCaptureKit>=10; sys_platform == 'darwin'",
]
# Local (offline) voice engines. Entirely optional per the cloud-first doctrine
# (CLAUDE.md §3): the default VAD/STT/wake paths are cloud-reachable, so the base
diff --git a/tests/unit/platform/test_window_state_rects.py b/tests/unit/platform/test_window_state_rects.py
index cd212b7efa..67f6b9c34c 100644
--- a/tests/unit/platform/test_window_state_rects.py
+++ b/tests/unit/platform/test_window_state_rects.py
@@ -18,12 +18,9 @@ import subprocess
import sys
import types
-import pytest
-
from jarvis.platform import window_state as ws
from jarvis.platform.window_state import WindowInfo
-
# ---------------------------------------------------------------------------
# macOS (fake Quartz)
# ---------------------------------------------------------------------------
diff --git a/tests/unit/vision/test_select_capture_monitor.py b/tests/unit/vision/test_select_capture_monitor.py
index 1d057d1895..672411bb60 100644
--- a/tests/unit/vision/test_select_capture_monitor.py
+++ b/tests/unit/vision/test_select_capture_monitor.py
@@ -30,12 +30,31 @@ def test_primary_strategy_picks_the_origin_monitor_not_physical0() -> None:
def test_foreground_fallback_uses_true_primary(monkeypatch) -> None:
- # Off Windows / when foreground detection is unavailable, the foreground
- # strategy returns `primary` — which must be the (0,0) main monitor.
- monkeypatch.setattr("jarvis.vision.screenshot.os.name", "posix")
+ # When foreground detection is unavailable (headless probe, Wayland),
+ # the foreground strategy returns `primary` — the (0,0) main monitor.
+ # The follow probe itself is cross-platform now (one window_state seam).
+ monkeypatch.setattr(
+ "jarvis.platform.window_state.foreground_window", lambda: None,
+ )
assert select_capture_monitor(_MONITORS, strategy="foreground") is _MAIN
+def test_foreground_strategy_follows_the_window_monitor(monkeypatch) -> None:
+ # The window sits on the LEFT secondary monitor — the capture must follow
+ # it there on every platform, not pin the primary.
+ from jarvis.platform.window_state import WindowInfo
+
+ monkeypatch.setattr(
+ "jarvis.platform.window_state.foreground_window",
+ lambda: WindowInfo(title="App", handle=7),
+ )
+ monkeypatch.setattr(
+ "jarvis.platform.window_state.window_frame_rect",
+ lambda w: (-2000, 100, 800, 600),
+ )
+ assert select_capture_monitor(_MONITORS, strategy="foreground") is _LEFT
+
+
def test_explicit_is_primary_flag_still_wins() -> None:
flagged = {**_LEFT, "is_primary": True}
mons = [_VIRTUAL, flagged, _MAIN]