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.

@ feat(screen-context): look at the screen once, only when clearly asked

Ruben Lütke4c53e3dc7004
diff --git a/docs/screen-context.md b/docs/screen-context.md
new file mode 100644
index 0000000000..a48b13297f
--- /dev/null
+++ b/docs/screen-context.md
@@ -0,0 +1,414 @@
+# Screen Context — architecture, flow, privacy plan, MVP roadmap
+
+**Date:** 2026-07-29
+**Status:** design approved, Wave 1 implemented
+**Scope:** a local, on-demand screen-context service for the on-screen bar and
+the live voice session, on Windows, macOS and Linux, extensible to a fourth
+platform through the same adapter seam.
+
+---
+
+## 1. What this is
+
+When the user says something that unambiguously asks Jarvis to *look* — "can you
+see this?", "what does that say?", "look at the error" — Jarvis takes **one**
+capture of the screen the user is actually working on, enriches it with the
+active application, the window title and whatever visible UI text the platform's
+accessibility layer exposes, filters it against the user's privacy rules, and
+hands it to the running conversation. Then it is gone.
+
+Everything about that sentence is a constraint:
+
+| Constraint | Consequence in the design |
+|---|---|
+| **on demand** | One capture per trigger. No loop, no timer, no background sampler. |
+| **unambiguous** | A three-valued intent verdict. Ambiguous → Jarvis *asks*, never captures. |
+| **the screen the user is working on** | Monitor under the mouse cursor at trigger time; bar's monitor as fallback. |
+| **filtered** | Redaction runs *before* the context leaves the process. |
+| **then it is gone** | Ephemeral handle with a TTL, single consumption, no disk write without explicit consent. |
+
+### Non-goals
+
+- Continuous screen understanding / ambient awareness. That is a different
+ feature with a different consent model, and it is explicitly out of scope.
+- Driving the desktop. Acting on the screen is Computer-Use
+ (`jarvis/cu/`, gated by `jarvis/brain/cu_gate.py`); Screen Context only
+ *reads*, once, and never moves a cursor or presses a key.
+- OCR as a primary text source. OCR is a supplement, off the critical path,
+ used only where accessibility text is unavailable or empty.
+
+### Relationship to what already exists
+
+This is deliberately **not** a new capture stack. The platform primitives are
+already in the tree and battle-tested; Screen Context is the policy layer above
+them.
+
+| Reused | What it gives us |
+|---|---|
+| `jarvis/platform/mouse.py` | Cursor position, per-OS, `None` on headless/Wayland. |
+| `jarvis/platform/monitors.py` | `work_area_at`, primary resolution, virtual bounds. |
+| `jarvis/platform/window_state.py` | Foreground window, title, pid, frame rect. |
+| `jarvis/platform/window_capture.py` | Native per-window capture (macOS SCK). |
+| `jarvis/vision/screenshot.py` | `capture_region`, DPI awareness, screen-recording probe. |
+| `jarvis/vision/tree_factory.py` | `make_ui_tree_source()` → UIA / AX / AT-SPI / Null. |
+| `jarvis/platform/permissions.py` | `PermissionId.SCREEN_RECORDING`, `.ACCESSIBILITY`. |
+
+What is genuinely new: intent classification with an *ambiguous* verdict,
+cursor-first monitor targeting, redaction, and an ephemeral single-use context
+handle.
+
+---
+
+## 2. Architecture
+
+### 2.1 Layering
+
+Screen Context sits in its own package, `jarvis/screen_context/`, above the
+platform seam and below the brain. It imports platform modules; nothing in
+`jarvis/platform/` imports it. That direction is the 8-layer dependency rule
+(CLAUDE.md §5) and it is what keeps the package testable without a display.
+
+```
+ voice session / bar / REST / brain tool
+ │
+ ▼
+ ┌───────────────────────────────────────┐
+ │ ScreenContextService (service.py) │ orchestration, TTL, consent
+ └───────────────────────────────────────┘
+ │ │ │ │
+ ▼ ▼ ▼ ▼
+ intent targeting uitext redaction ← policy, pure-ish, testable
+ │ │ │ │
+ ▼ ▼ ▼ ▼
+ ┌───────────────────────────────────────┐
+ │ ports.py (Protocols) │ ← the ONE seam
+ └───────────────────────────────────────┘
+ │
+ ┌──────────┬───────┴────────┬──────────────┐
+ ▼ ▼ ▼ ▼
+ Windows macOS Linux (fourth OS)
+ UIA/GDI AX/SCK/Quartz AT-SPI/X11 new adapter only
+```
+
+### 2.2 The seam: `ports.py`
+
+Four `Protocol`s, each with a per-OS implementation and a logged null fallback.
+Adding a fourth platform means writing four small classes and one line in each
+factory — no change anywhere above the seam. That is the entire extensibility
+claim, and it is testable: the service is constructed with fakes in every unit
+test, and no test needs a screen.
+
+| Port | Question it answers | Win | macOS | Linux | Absent |
+|---|---|---|---|---|---|
+| `CursorLocator` | Where is the pointer? | `GetCursorPos` | pynput/Quartz | pynput/X11 | `None` → bar fallback |
+| `DisplayEnumerator` | Which monitors, which one holds a point? | mss + `MonitorFromPoint` | mss + Quartz | mss + xrandr | single virtual rect |
+| `WindowProbe` | What is focused, titled, where? | Win32/DWM | Quartz/AX | xdotool/EWMH | empty `WindowFacts` |
+| `SurfaceCapturer` | Give me these pixels, once. | GDI rect grab | ScreenCaptureKit | X11 root grab | `CaptureUnavailable` |
+| `UiTextReader` | What text is visible? | UIA | AXUIElement | AT-SPI | empty, flagged |
+
+Every port obeys the same two rules the existing platform seam already follows:
+**never raise into the caller** and **degrade to a value that reads as "not
+available"**, never to a value that reads as "nothing was there". The
+distinction matters — a silent empty string would let the model narrate a blank
+screen with confidence (the 2026-04-28 blank-desktop regression), so absence is
+carried explicitly in `ScreenContext.degradations`.
+
+### 2.3 Data model (`models.py`, all `frozen=True`)
+
+- `VisualIntent` — `NONE` | `AMBIGUOUS` | `SCREEN` | `WINDOW`.
+- `IntentVerdict` — the intent, the matched evidence, and the confidence signal.
+- `CaptureTarget` — what will be captured: kind (`monitor` | `window`), bbox,
+ monitor identity, window facts, and the *reason* it was chosen (for the log
+ and for the receipt the user sees).
+- `WindowFacts` — app name, window title, pid, frame rect.
+- `ScreenContext` — the finished, redacted artifact: image bytes + mime +
+ dimensions, `ui_text`, `WindowFacts`, `RedactionReport`, `captured_at_ns`,
+ `expires_at_ns`, `degradations`.
+- `RedactionReport` — what was removed and by which rule. Shipped *with* the
+ context so the model is told the truth about its own evidence and the user
+ can see it in the receipt.
+
+`ScreenContext` holds bytes in memory and never a path — a path would be a file,
+and a file is persistence.
+
+---
+
+## 3. Flow — from utterance to context
+
+```
+user speaks
+ │
+ ▼
+[1] intent.classify(text, locale)
+ ├── NONE → normal text turn. No capture. No prompt. (the common case)
+ ├── AMBIGUOUS → Jarvis asks one short question in the turn's language,
+ │ arms a short confirmation window, and STOPS. No capture.
+ └── SCREEN / WINDOW ↓
+ │
+ ▼
+[2] permission check (screen recording; accessibility for UI text)
+ ├── denied → honest, actionable message naming the OS setting. STOP.
+ └── granted ↓
+ │
+ ▼
+[3] targeting.resolve()
+ ├── WINDOW intent + a focused window → that window's frame rect
+ └── otherwise → monitor under the cursor
+ ├── cursor unavailable → monitor under the bar
+ └── bar unavailable → OS primary monitor
+ │
+ ▼
+[4] indicator.show() ← visible BEFORE the shutter, dismissed after
+ │
+ ▼
+[5] capture ONCE + read window facts + read UI text (AX first, OCR only to fill a gap)
+ │
+ ▼
+[6] redaction.apply() image regions blacked out, text scrubbed, report built
+ │
+ ▼
+[7] service stores an ephemeral handle (TTL, single consumption)
+ │
+ ▼
+[8] the turn consumes it → brain sees image + text + facts + redaction report
+ │
+ ▼
+[9] TTL expires or consumption completes → bytes dropped
+```
+
+Two details in that flow are load-bearing and easy to get wrong:
+
+**The indicator precedes the shutter.** Showing it afterwards, or concurrently,
+means there is a window in which a capture happened with no visible sign. The
+service awaits the indicator's acknowledgement (bounded by a short timeout) and
+only then grabs pixels. If the indicator cannot be shown at all, the capture
+still proceeds *only* if the user has an alternative signal configured; the
+default is to proceed and log the degradation, because a silently-failed
+indicator must not brick the feature, but the degradation is surfaced in the
+receipt. This is a deliberate trade-off, stated rather than hidden.
+
+**Ambiguity does not capture, and does not silently drop the turn either.**
+`AMBIGUOUS` produces a question, in the resolved output language, through the
+one resolver (`jarvis/core/turn_language.py`) — never a per-layer phrase table
+(CLAUDE.md §1). The user's next turn resolves it; a bare "yes" inside the
+confirmation window promotes the *previous* utterance to `SCREEN`.
+
+### 3.1 Intent classification
+
+Deterministic, regex-based, O(1), no model call. An LLM classifier on the voice
+path is exactly the latency tax AP-9 forbids, and it would make the "did it look
+at my screen?" question unanswerable after the fact.
+
+Three tiers of evidence, all defined per supported locale (de/en/es today, and a
+new locale is a data entry, not code):
+
+- **Explicit** → `SCREEN`: a look-verb bound to a screen object or a deictic
+ ("look at this", "schau dir das an", "mira esto"), a screen/window noun with
+ a demonstrative, a read-out request ("what does it say there").
+- **Window-scoped** → `WINDOW`: the same, but naming the window/app/document
+ ("in this window", "this tab", "the dialog").
+- **Weak** → `AMBIGUOUS`: a bare deictic with no visual anchor ("what is that?",
+ "and that one?"), or a look-verb with no object ("can you check?"). These are
+ precisely the utterances a capture-happy heuristic gets wrong in both
+ directions, so they get a question instead of a guess.
+- Everything else → `NONE`.
+
+Negative guards matter as much as the vocabulary. The existing `cu_gate` learned
+this the hard way: product names containing a vehicle token ("Open AI", "context
+window", "edge case") read as commands. Screen Context reuses that masking
+approach before matching, and adds its own: "see" in "I see" / "you see" /
+"let's see", "look" in "look into it" / "look for", "schauen wir mal", "a ver".
+
+### 3.2 Targeting
+
+The requirement is explicit and it differs from every existing capture path in
+the tree: **the monitor under the mouse cursor at trigger time**, not the
+foreground window's monitor. The two diverge constantly — the user reads an
+error on the right screen while the focused window sits on the left.
+
+```
+cursor position ──► monitor containing that point (MONITOR_DEFAULTTONEAREST
+ │ semantics: a point in a
+ │ layout gap maps to the
+ │ nearest screen, never fails)
+ │
+ unavailable (headless / Wayland / no pynput)
+ │
+ ▼
+bar position ─────► monitor containing the bar
+ │
+ bar not running / position unknown
+ │
+ ▼
+OS primary monitor (resolve_primary_monitor, honouring the main_monitor override)
+```
+
+The cursor is sampled **once, at trigger time**, and that sample is threaded
+through the whole capture. Re-reading it later would let a mouse move between
+decision and shutter change which screen gets captured — a race that would show
+up as "it photographed the wrong monitor" and would be nearly impossible to
+reproduce.
+
+Window preference is a narrower rule: only a `WINDOW` verdict prefers the active
+window, and only when the window's frame rect is readable and non-degenerate.
+Otherwise it falls back to the selected monitor, because a failed window probe
+must not produce a capture of nothing.
+
+### 3.3 UI text
+
+Accessibility first, through the existing `make_ui_tree_source()` factory, which
+already resolves UIA / AX / AT-SPI / Null per platform. Nodes are filtered to
+the target rect (a monitor capture should not carry text from a window on
+another screen), stripped of `is_password` nodes at the source, and truncated to
+a configured character budget.
+
+OCR is a *supplement*, and only under three conditions simultaneously: the
+accessibility path yielded (near-)nothing, an OCR backend is actually installed,
+and the user enabled it. It never runs on the accessibility-rich path, because
+it costs hundreds of milliseconds and adds transcription errors to text the OS
+already knows exactly.
+
+---
+
+## 4. Permissions and privacy plan
+
+### 4.1 Permissions
+
+| OS | Capture | UI text | Failure mode |
+|---|---|---|---|
+| Windows | none required | none required | — |
+| macOS | Screen Recording (TCC) | Accessibility (TCC) | Capture without the grant returns *wallpaper only*, with no error — so it is probed on every capture and refused honestly rather than returned as a successful blank. |
+| Linux/X11 | none required | AT-SPI session | — |
+| Linux/Wayland | no addressable global capture | AT-SPI | Refused with the X11/XWayland message; the compositor owns capture. |
+
+Permission state is never cached across captures: macOS can revoke a grant while
+the app runs. The probe is one call and it is the first thing after intent.
+
+Every denial produces a message that names the exact setting to change and is
+recoverable in-app (CLAUDE.md §3) — never a stack trace, never a silent no-op.
+
+### 4.2 Privacy rules
+
+Five layers, in the order they run:
+
+1. **Consent to the feature.** `[screen_context].enabled`. Default is on for the
+ explicit-intent path *only*; there is no configuration in which a capture
+ happens without a matching utterance.
+2. **App denylist.** If the target window's app or title matches a denylist
+ entry (default entries cover password managers, banking, and private-browsing
+ windows by title pattern), **no capture is taken at all**. Not captured and
+ redacted — not captured. The user is told which rule blocked it.
+3. **Region redaction.** Accessibility nodes marked `is_password`, plus nodes
+ whose text matches a sensitive pattern, have their bounds filled with opaque
+ black in the image before it leaves the process.
+4. **Text scrubbing.** The aggregated UI text is run through the same pattern
+ set; matches are replaced with a typed placeholder (`[redacted:card]`), never
+ silently dropped, so the model knows something was there.
+5. **Egress.** The context is handed to the session with a purpose tag, over the
+ transport the brain provider already uses (TLS to the provider, in-process
+ for a local one). Nothing is written to disk.
+
+Default patterns ship for card numbers, IBANs, API-key shapes, and
+`Authorization:`-style headers. They are configurable, additive, and each entry
+carries a label that appears in the redaction report.
+
+### 4.3 Retention
+
+- Image bytes live in memory inside a `_Handle`, keyed by an opaque id.
+- One consumption. `consume()` removes the handle; a second call gets nothing.
+- TTL (default 120 s) sweeps unconsumed handles.
+- `POST /api/screen-context/{id}/save` is the **only** path that writes a file,
+ it requires an explicit call with an explicit destination, and it records the
+ save in the session log so "I never agreed to that" is checkable.
+- Nothing about a capture reaches the flight recorder except metadata: target
+ kind, monitor identity, sizes, redaction counts, degradations. Never pixels,
+ never scrubbed text.
+
+This is a deliberate departure from `ScreenshotSource`, which writes every frame
+to `data/flight_recorder/blobs/`. That behaviour is correct for Computer-Use
+replay and wrong for this feature; Screen Context therefore does not use
+`ScreenshotSource` at all, only the stateless `capture_region` primitive.
+
+---
+
+## 5. MVP roadmap
+
+Priority order. Each wave is independently shippable and independently
+verifiable — the repo convention (`feedback_plans_as_independent_chunks`).
+
+### Wave 1 — the service and its seam ✅ *implemented*
+
+`models.py`, `ports.py`, `intent.py`, `targeting.py`, `uitext.py`,
+`redaction.py`, `service.py`, `[screen_context]` config, REST routes, unit
+tests. Fully testable with fakes, no display required. Ships the four
+non-maintainer paths: headless Linux degrades to an honest refusal, macOS
+degrades on a missing grant, a fresh install works with any single brain key,
+and no provider name appears anywhere in the package.
+
+**Done when:** `pytest tests/unit/screen_context/ -q` is green and
+`jarvis api screen-context capture` returns a redacted context on Windows and an
+honest refusal in a `python:3.11-slim` container.
+
+### Wave 2 — voice-session wiring
+
+Replace the two-valued `vision_gate.should_attach_screenshot()` call sites with
+the three-valued verdict; route `AMBIGUOUS` to a clarifying question through
+`resolve_output_language`; make the router consume a `ScreenContext` handle
+instead of the background `VisionContextProvider` observation. Add `es` to the
+marker vocabulary (today's gate is de/en only, which violates §1's
+equal-locales rule).
+
+**Done when:** an ambiguous voice turn ("what does that say?") produces a
+question, an explicit one ("look at this") produces a capture from the cursor's
+monitor, and a plain content question ("what did we discuss?") produces neither
+— verified in all three supported locales.
+
+### Wave 3 — the indicator and the receipt
+
+A capture indicator on the bar: a brief, unmistakable shutter affordance shown
+before the grab, plus a receipt line in the transcript naming what was captured
+("captured: right monitor, 2 regions redacted"). Reuses the existing
+`jarvis/cu/indicator/` sidecar shape rather than inventing a second overlay
+mechanism, extended to the non-Windows backends it currently lacks.
+
+**Done when:** every capture is preceded by a visible indicator on all three
+OSes, or by a logged degradation naming why it could not be shown.
+
+### Wave 4 — settings surface
+
+A Screen Context group in Settings: master switch, denylist editor, redaction
+pattern editor with a live test field, OCR toggle, TTL. Recoverable entirely
+in-app, no TOML editing (§3).
+
+### Wave 5 — OCR supplement
+
+Optional local OCR behind a capability probe, used only when accessibility text
+is empty. Off by default, base install stays torch-free.
+
+---
+
+## 6. Anti-patterns this design is written against
+
+| Register entry | How this design avoids it |
+|---|---|
+| AP-9 (awareness on the voice path) | Intent is regex, O(1). No model call, no network, no tree walk before the verdict. |
+| AP-21/22 (provider coupling) | The package names no provider. It produces bytes + text; whatever brain is configured consumes them. |
+| AP-23 (maintainer's box as baseline) | Every port has a null fallback; the whole package is unit-tested with fakes and imports cleanly on a slim container. |
+| AP-26 (init on the boot path) | Nothing initializes at import. Ports are constructed lazily on first capture. |
+| AP-30 (silent exception handlers) | Every degradation is both logged *and* carried in `ScreenContext.degradations` to the user. Absence is never rendered as emptiness. |
+| AP-31 (config that nothing reads) | Every `[screen_context]` key is read in Wave 1 code; the settings UI in Wave 4 adds no key that is not already wired. |
+| §1 (English artifacts) | Package, docs, log lines, errors and UI strings are English; the de/es vocabulary in `intent.py` is speech-input *matching data*, which is the closed-list exception, and it is marked as such. |
+| §4 (dynamic brand) | No user-visible string hardcodes an assistant name. |
+
+---
+
+## 7. Open questions for the maintainer
+
+1. **Indicator without a bar.** When the bar is not running (headless-ish
+ desktop, bar disabled), Wave 3 has no host for the shutter affordance.
+ Options: a transient always-on-top window of its own, or refusing capture
+ without an indicator. Current default: capture proceeds, degradation logged
+ and surfaced. Worth confirming.
+2. **Denylist defaults.** Shipping title patterns for password managers and
+ banking is a guess about what users consider sensitive. The mechanism is
+ right; the default list deserves review before it is advertised.
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index 9cc83d7943..a76c64420f 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -1850,6 +1850,55 @@ class VisionContextConfig(BaseModel):
timeout_s: float = 0.25 # mandate: 250 ms latency cap per spawn
+class ScreenContextConfig(BaseModel):
+ """Top-level ``[screen_context]`` config — one-shot, on-request screen look.
+
+ Governs ``jarvis/screen_context/``: when the user unambiguously asks Jarvis
+ to look at the screen, exactly one capture is taken of the monitor under the
+ mouse cursor, filtered, handed to the turn, and dropped. There is no setting
+ here that enables continuous or silent monitoring, because no such code path
+ exists — see ``docs/screen-context.md``.
+
+ Every key below is read by ``ScreenContextService`` (AP-31: no config that
+ nothing honours).
+ """
+ model_config = {"extra": "allow"}
+
+ #: Master switch. When off, an explicit "look at this" is answered with an
+ #: honest "screen context is switched off" rather than silently ignored.
+ enabled: bool = True
+
+ #: App names or window-title fragments that are NEVER captured — not
+ #: captured and redacted, but not captured at all. Case-insensitive
+ #: substring match against both the app name and the window title, so a
+ #: version bump ("1Password" -> "1Password 8") cannot silently stop
+ #: protecting. Empty by default: shipping a guess about what a stranger
+ #: considers sensitive is worse than letting them state it (§3).
+ denylist: list[str] = Field(default_factory=list)
+
+ #: Extra ``"label:regex"`` rules on top of the shipped set (card numbers,
+ #: IBANs, API-key shapes, auth headers, private-key headers). The label is
+ #: what the user sees in the redaction report, so it should be a word.
+ sensitive_patterns: list[str] = Field(default_factory=list)
+
+ #: Whether the shipped default patterns apply. Off only makes sense for a
+ #: user who has written a complete replacement set.
+ include_default_patterns: bool = True
+
+ #: Character budget for on-screen text handed to the model. Text beyond it
+ #: is cut and the cut is reported, never silently dropped.
+ max_text_chars: int = 4000
+
+ #: Seconds an unconsumed capture stays in memory before it is discarded.
+ #: A capture is also discarded on first use, whichever comes first.
+ ttl_s: float = 120.0
+
+ #: OCR supplement for windows whose accessibility layer exposes no text.
+ #: Off by default and dependency-free: the base install stays torch-free
+ #: (§3), so this only does anything when a local OCR engine is present.
+ ocr_enabled: bool = False
+
+
class ComputerUseConfig(BaseModel):
"""Top-level ``[computer_use]`` config for the Computer-Use harness.
@@ -3141,8 +3190,11 @@ class JarvisConfig(BaseModel):
# Wave 2 — plugin-marketplace OAuth connect (hosted vs loopback callback).
marketplace: MarketplaceConfig = Field(default_factory=MarketplaceConfig)
board: BoardConfig = Field(default_factory=BoardConfig)
- # Persona-Mandat Phase 5: top-level ``[vision]``-Section.
+ # Persona mandate, Phase 5: top-level ``[vision]`` section.
vision: VisionContextConfig = Field(default_factory=VisionContextConfig)
+ # One-shot, intent-driven screen look (jarvis/screen_context/). Distinct
+ # from ``[vision]`` above, which governs the always-on observation path.
+ screen_context: ScreenContextConfig = Field(default_factory=ScreenContextConfig)
# Phase 5/6 — Computer-Use-POAV-Harness (ADR-0008).
computer_use: ComputerUseConfig = Field(default_factory=ComputerUseConfig)
# Low-latency local-action gate. Hidden tools only; never exposed in the
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.py
index 1e6f172827..f442225e74 100644
--- a/jarvis/core/config_writer.py
+++ b/jarvis/core/config_writer.py
@@ -819,6 +819,40 @@ def set_dictation_setting(
_patch_table(path, "dictation", key, value)
+#: Keys ``[screen_context]`` accepts. An allowlist rather than a passthrough:
+#: a typo must never invent a config field that silently does nothing (AP-31),
+#: and a privacy feature is the last place to accept "whatever was posted".
+SCREEN_CONTEXT_SETTING_KEYS: frozenset[str] = frozenset(
+ {
+ "enabled",
+ "denylist",
+ "sensitive_patterns",
+ "include_default_patterns",
+ "max_text_chars",
+ "ttl_s",
+ "ocr_enabled",
+ }
+)
+
+
+def set_screen_context_setting(
+ key: str,
+ value: str | bool | int | float | list,
+ *,
+ path: Path = DEFAULT_CONFIG_FILE,
+) -> None:
+ """Persist one ``[screen_context]`` key in jarvis.toml.
+
+ Same shape as :func:`set_dictation_setting`: TOML-only atomic write, keys
+ validated against an allowlist, values validated by the caller against
+ ``ScreenContextConfig``. These keys are not part of the drift-guard's
+ reference snapshot, so the BUG-010 three-layer rule does not apply.
+ """
+ if key not in SCREEN_CONTEXT_SETTING_KEYS:
+ raise ValueError(f"unknown screen_context setting: {key!r}")
+ _patch_table(path, "screen_context", key, value)
+
+
def set_reply_language(name: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist the user-facing reply-language pin in ``[brain] reply_language``.
diff --git a/jarvis/core/events.py b/jarvis/core/events.py
index f2a111d583..6d5940b025 100644
--- a/jarvis/core/events.py
+++ b/jarvis/core/events.py
@@ -909,10 +909,47 @@ class VisionInjected(Event):
call. Telemetry for cost tracking, flight recorder, and debugging.
"""
screenshot_hash: str = ""
- bytes_size: int = 0 # Groesse des PNG-Rohdatenblocks
+ bytes_size: int = 0 # size of the raw PNG data block
capture_age_ms: int = 0 # age of the observation at inject time
+@dataclass(frozen=True, slots=True)
+class ScreenCaptureAnnounced(Event):
+ """A one-off Screen Context capture is about to happen.
+
+ Published BEFORE any pixels are grabbed, so the on-screen bar (and any
+ other subscriber) can show the capture indicator while there is still
+ something to indicate. Announcing afterwards would leave a window in which
+ a capture happened with no visible sign — which is the one thing this
+ feature must never do.
+
+ ``target_kind`` is ``"monitor"`` or ``"window"``; ``target_label`` is the
+ monitor identity or window title the user will see in the receipt.
+ """
+ target_kind: str = "monitor"
+ target_label: str = ""
+ #: Why this surface: cursor_monitor | bar_monitor | primary_monitor | ...
+ reason: str = ""
+
+
+@dataclass(frozen=True, slots=True)
+class ScreenCaptureCompleted(Event):
+ """A Screen Context capture finished — the receipt.
+
+ Carries only metadata, never pixels and never captured text: this event
+ reaches the flight recorder, and a recorder that stores screen content
+ would quietly defeat the feature's retention promise.
+ """
+ target_kind: str = "monitor"
+ target_label: str = ""
+ width: int = 0
+ height: int = 0
+ bytes_size: int = 0
+ redaction_count: int = 0
+ degradation_count: int = 0
+ ui_text_source: str = "none"
+
+
@dataclass(frozen=True, slots=True)
class ActionPlanned(Event):
"""The CU loop planner proposed the next action (before execution)."""
diff --git a/jarvis/screen_context/__init__.py b/jarvis/screen_context/__init__.py
new file mode 100644
index 0000000000..4e93cf77d0
--- /dev/null
+++ b/jarvis/screen_context/__init__.py
@@ -0,0 +1,46 @@
+"""Screen Context — one-shot, intent-driven, privacy-filtered screen capture.
+
+When a user turn unambiguously asks Jarvis to look ("can you see this?", "schau
+dir das an", "mira esto"), this package takes exactly ONE capture of the screen
+the user is working on — the monitor under the mouse cursor — enriches it with
+the active app, the window title and visible UI text from the platform's
+accessibility layer, filters it against the user's privacy rules, and hands it
+to the running conversation behind a short-lived, single-use handle.
+
+When the turn is only *possibly* about the screen, Jarvis asks instead of
+capturing. There is no configuration in which a capture happens without a
+matching request, and there is no code path that captures twice.
+
+Design, flow, privacy plan and roadmap: ``docs/screen-context.md``.
+
+Nothing is imported eagerly here beyond the data model: the platform ports load
+their native libraries on first use, so importing this package costs nothing on
+the startup path (AP-26) and stays clean on a headless container.
+"""
+from __future__ import annotations
+
+from jarvis.screen_context.models import (
+ CaptureTarget,
+ Degradation,
+ DegradationCode,
+ IntentVerdict,
+ RedactionReport,
+ ScreenContext,
+ TargetKind,
+ TargetReason,
+ VisualIntent,
+ WindowFacts,
+)
+
+__all__ = [
+ "CaptureTarget",
+ "Degradation",
+ "DegradationCode",
+ "IntentVerdict",
+ "RedactionReport",
+ "ScreenContext",
+ "TargetKind",
+ "TargetReason",
+ "VisualIntent",
+ "WindowFacts",
+]
diff --git a/jarvis/screen_context/intent.py b/jarvis/screen_context/intent.py
new file mode 100644
index 0000000000..ebe261ea87
--- /dev/null
+++ b/jarvis/screen_context/intent.py
@@ -0,0 +1,324 @@
+"""Three-valued visual-intent classification for Screen Context.
+
+Answers one question about a user turn: *did the user unambiguously ask Jarvis
+to look at the screen?* The three-valued answer is the point. A two-valued gate
+must resolve "what is that?" as either a capture or a miss, and both are wrong
+for that same sentence — it is a question about the screen roughly as often as
+it is a question about the topic under discussion. ``AMBIGUOUS`` is what lets
+Jarvis ask a one-line question instead of guessing, which is the behaviour this
+feature promises.
+
+**Deterministic by mandate.** Regex over a normalized string, O(1), no model
+call and no network. An LLM classifier here would sit on the voice path (AP-9),
+and it would make "did it look at my screen, and why?" unanswerable after the
+fact — ``IntentVerdict.evidence`` exists so that question always has an answer.
+
+**Every supported locale is equal** (CLAUDE.md §1): de, en and es are matched
+simultaneously rather than selected by the session locale, because a bilingual
+user mixes them inside one sentence and a locale-gated matcher would go deaf on
+the half it did not pick. Adding a locale is a data entry below, not code.
+
+The vocabulary is speech-recognition *input matching data* — the closed-list
+exception in §1, the same category as ``jarvis/brain/cu_gate.py``.
+"""
+from __future__ import annotations
+
+import logging
+import re
+
+from jarvis.screen_context.models import IntentVerdict, VisualIntent
+
+log = logging.getLogger(__name__)
+
+#: Cap on recorded evidence fragments — a log line, not a transcript.
+_MAX_EVIDENCE = 3
+
+
+# --------------------------------------------------------------------------
+# Normalization
+# --------------------------------------------------------------------------
+
+# German digraphs plus Spanish accent stripping, so the vocabulary below can be
+# written in plain ASCII and still match accented input. # i18n-allow
+_TRANSLITERATION = str.maketrans(
+ {
+ # i18n-allow: character-mapping data for speech-input normalization
+ "ä": "ae", "ö": "oe", "ü": "ue", "ß": "ss", # i18n-allow
+ "á": "a", "é": "e", "í": "i", "ó": "o", "ú": "u", "ñ": "n",
+ "à": "a", "è": "e", "ì": "i", "ò": "o", "ù": "u", "ç": "c",
+ }
+)
+
+
+# Idioms that CONTAIN a look-verb but are not a request to look at anything.
+# Masked out before matching rather than used as a veto: a veto would let one
+# stray idiom kill a turn that also contains a real request ("looks like an
+# error — can you see this?"), which is exactly the sentence the feature exists
+# for. Masking removes only the idiom and leaves the rest intact.
+#
+# This mirrors ``_PRODUCT_NAME_NOISE_RE`` in jarvis/brain/cu_gate.py, which
+# learned the same lesson from a live incident: a bare verb token swallowed
+# every phrase that merely contained it.
+_IDIOM_NOISE_RE: re.Pattern[str] = re.compile(
+ # --- English ---
+ # "you see" is deliberately NOT masked bare: it is the tail of "can you
+ # see this?", the single most common way to ask for a look in English.
+ # Only its parenthetical and idiomatic forms are.
+ r"\b(?:i|we|they)\s+see\b"
+ r"|\bas\s+you\s+can\s+see\b|\byou\s+see\s*,|\bsee\s+you\b"
+ r"|\blet(?:'|)s\s+see\b|\bwe(?:'|)ll\s+see\b|\bsee\s+if\b|\bsee\s+whether\b"
+ r"|\blook(?:s|ed|ing)?\s+(?:for|into|up|like|after|forward)\b"
+ r"|\bloo?ks?\s+(?:good|bad|fine|great|ok|okay)\b"
+ r"|\bsee\s+(?:to\s+it|about)\b"
+ # --- German --- i18n-allow: German speech-input matching data
+ # "mal sehen" is NOT masked: "kannst du mal sehen?" is one of the two
+ # phrasings this feature is specified around. On its own it matches no
+ # request pattern anyway, so masking it would only cost the real request.
+ r"|\bschauen\s+wir\b|\bsehen\s+wir\b"
+ r"|\bwir\s+sehen\b|\bich\s+sehe\b|\bich\s+seh\b|\bwie\s+gesagt\b"
+ r"|\bsieht\s+(?:aus|so\s+aus|gut\s+aus|schlecht\s+aus)\b|\baussehen\b"
+ r"|\bsieh\s+zu,?\s+dass\b|\bschau\s+(?:nach|ob)\b" # i18n-allow: DE input
+ # --- Spanish --- i18n-allow: Spanish speech-input matching data
+ r"|\bvamos\s+a\s+ver\b|\ba\s+ver\s+si\b|\bya\s+veo\b|\bveremos\b"
+ r"|\bse\s+ve\b|\bmira\s+que\b|\bmira,?\s+(?:pero|es\s+que)\b",
+ re.IGNORECASE,
+)
+
+
+def _normalize(text: str) -> str:
+ """Casefold, transliterate, then blank out non-visual idioms.
+
+ Substitutes a space rather than the empty string so surrounding word
+ boundaries survive and a genuine request in the same sentence still
+ matches.
+ """
+ folded = (text or "").casefold().translate(_TRANSLITERATION)
+ return _IDIOM_NOISE_RE.sub(" ", folded)
+
+
+# --------------------------------------------------------------------------
+# Level 1 — window-scoped, unambiguous
+# --------------------------------------------------------------------------
+
+# A window/tab/dialog/app noun bound to a demonstrative or "active/current".
+# The demonstrative is mandatory: a bare "window" is a common noun in every one
+# of these languages ("a window of opportunity", "Fenster zum Hof"), and the
+# whole point of this level is that the user pointed at something specific.
+_WINDOW_SCOPE_RE: re.Pattern[str] = re.compile(
+ r"(?:"
+ # --- English ---
+ r"\b(?:this|that|the\s+(?:active|current|front|open))\s+"
+ r"(?:window|tab|dialog|dialogue|app|application|document|file|page|sheet)\b"
+ r"|\bin\s+(?:this|that)\s+(?:window|tab|dialog|app|document|page)\b"
+ r"|\bthe\s+(?:window|tab|dialog|app)\s+(?:i(?:'|)m|i\s+am)\s+(?:in|on)\b"
+ # --- German --- i18n-allow: German speech-input matching data
+ r"|\b(?:diese[srmn]?|das|der|die)\s+" # i18n-allow: DE input
+ r"(?:fenster|tab|reiter|dialog|dialogfeld|anwendung|programm|dokument|seite)\b"
+ r"(?=\s|$|[.,!?])"
+ r"|\bim\s+(?:aktiven|aktuellen|offenen|vorderen)\s+fenster\b"
+ r"|\bin\s+(?:diesem|dem)\s+(?:fenster|tab|reiter|dialog|dokument|programm)\b"
+ # --- Spanish --- i18n-allow: Spanish speech-input matching data
+ r"|\b(?:esta|esa|est[ae]\s+misma)\s+"
+ r"(?:ventana|pestana|pagina|aplicacion|hoja)\b"
+ r"|\b(?:este|ese)\s+(?:dialogo|documento|programa|archivo)\b"
+ r"|\ben\s+(?:esta|esa)\s+(?:ventana|pestana|pagina|aplicacion)\b"
+ r")",
+ re.IGNORECASE,
+)
+
+
+# The German branch above deliberately requires a word boundary AFTER the noun
+# via lookahead, because "die Seite" is also "the side/page of a book" — the
+# demonstrative + noun pair is the signal, and a trailing genitive ("die Seite
+# des Vertrags") should not scope a capture to a window.
+
+
+# --------------------------------------------------------------------------
+# Level 2 — screen-scoped, unambiguous
+# --------------------------------------------------------------------------
+
+_SCREEN_INTENT_RE: re.Pattern[str] = re.compile(
+ r"(?:"
+ # ---------------- English ----------------
+ # look/see verb bound to a deictic or to the screen itself
+ r"\b(?:look|looking)\s+at\s+(?:this|that|it|the\s+screen|my\s+screen|the\s+error)\b"
+ r"|\btake\s+a\s+look\s+at\s+(?:this|that|it|the|my)\b"
+ r"|\bhave\s+a\s+look\b|\bcheck\s+(?:this|that|it)\s+out\b"
+ r"|\bcan\s+you\s+see\s+(?:this|that|it|my\s+screen|the\s+screen)\b"
+ r"|\bdo\s+you\s+see\s+(?:this|that|it)\b"
+ r"|\bsee\s+(?:this|that)\s+(?:here|error|message|window|screen)\b"
+ r"|\bwhat\s+(?:do\s+you\s+see|am\s+i\s+looking\s+at)\b"
+ # screen nouns with a possessive/demonstrative
+ r"|\b(?:on|at)\s+(?:my|the|this)\s+screen\b|\bmy\s+screen\b"
+ r"|\bwhat(?:'|)s\s+on\s+(?:my|the)\s+screen\b"
+ r"|\b(?:this|that)\s+(?:error|error\s+message|message|button|menu|popup)\b"
+ # read-out requests
+ r"|\bwhat\s+does\s+(?:it|this|that|the\s+\w+)\s+say\b"
+ r"|\bread\s+(?:this|that|it|the\s+\w+)\s*(?:out|aloud|to\s+me)?\b"
+ r"|\bwhat\s+does\s+(?:this|that)\s+mean\s+(?:here|on\s+screen)\b"
+
+ # ---------------- German ---------------- i18n-allow: German speech-input matching data
+ # The two phrasings the feature is specified around, plus their variants.
+ # ``dies\w*`` on purpose: "schau dir DIESES Fenster an" is the natural
+ # phrasing, and a bare ``dies\b`` would only match the rarer "schau dir
+ # dies an" — costing the common case to save nothing.
+ r"|\bschau(?:e|st)?\s+(?:dir\s+)?(?:das|dies\w*|es|mal\s+das|hier)\b"
+ r"|\bschau\s+mal\b|\bschau\s+her\b|\bguck\s+mal\b|\bguck\s+(?:dir\s+)?das\b"
+ r"|\bsieh\s+(?:dir\s+)?(?:das|dies\w*)\b|\bsieh\s+mal\b"
+ r"|\bkannst\s+du\s+(?:mal\s+)?(?:kurz\s+)?(?:sehen|schauen|gucken|draufschauen)\b"
+ r"|\bkannst\s+du\s+(?:das|dies|es|meinen\s+bildschirm)\s+sehen\b"
+ r"|\bsiehst\s+du\s+(?:das|dies|meinen\s+bildschirm|den\s+fehler)\b" # i18n-allow: DE input
+ r"|\bwas\s+siehst\s+du\b"
+ # screen nouns
+ r"|\bauf\s+(?:dem|meinem)\s+bildschirm\b|\bam\s+bildschirm\b|\bmein\s+bildschirm\b"
+ r"|\bauf\s+dem\s+schirm\b|\bhier\s+auf\s+dem\b" # i18n-allow: DE input
+ r"|\b(?:diese|die)\s+fehlermeldung\b" # i18n-allow: DE input
+ r"|\b(?:dieser|der)\s+fehler\s+(?:hier|da)\b" # i18n-allow: DE input
+ r"|\b(?:dieser|der)\s+knopf\b|\b(?:dieses|das)\s+menue\b" # i18n-allow: DE input
+ # read-out requests
+ r"|\bwas\s+steht\s+(?:da|hier|dort|drin)\b|\bda\s+steht\b"
+ r"|\blies\s+(?:mir\s+)?(?:das|dies|es|die\s+\w+)\b|\bvorlesen\b" # i18n-allow: DE input
+ r"|\bwas\s+ist\s+das\s+(?:hier|da\s+auf)\b" # i18n-allow: DE input
+
+ # ---------------- Spanish ---------------- i18n-allow: Spanish speech-input matching data
+ r"|\bmira\s+(?:esto|eso|esta|la\s+pantalla|mi\s+pantalla|el\s+error)\b"
+ r"|\bmirar\s+(?:esto|eso)\b|\becha(?:le)?\s+un\s+vistazo\b"
+ r"|\bpuedes\s+ver\s+(?:esto|eso|mi\s+pantalla|la\s+pantalla)\b"
+ r"|\bves\s+(?:esto|eso|mi\s+pantalla)\b|\bque\s+ves\b"
+ r"|\ben\s+(?:mi|la)\s+pantalla\b|\bmi\s+pantalla\b"
+ r"|\bque\s+dice\s+(?:ahi|aqui|esto|eso)\b"
+ r"|\blee\s+(?:esto|eso|el\s+\w+)\b"
+ r"|\beste\s+error\b|\besta\s+ventana\s+de\s+error\b"
+ r")",
+ re.IGNORECASE,
+)
+
+
+# --------------------------------------------------------------------------
+# Level 3 — weak signals: ask, never capture
+# --------------------------------------------------------------------------
+
+# A bare deictic with no visual anchor, or an objectless look-verb. These are
+# the sentences a capture-happy heuristic gets wrong in BOTH directions, so
+# they earn a question rather than a guess.
+_AMBIGUOUS_RE: re.Pattern[str] = re.compile(
+ r"(?:"
+ # --- English ---
+ r"\bwhat\s+(?:is|'s)\s+(?:this|that)\b(?!\s+(?:mean|word|called))"
+ r"|\bwhat\s+about\s+(?:this|that)\b|\band\s+(?:this|that)\s+one\b"
+ r"|\bwhy\s+is\s+(?:this|that)\b|\bis\s+(?:this|that)\s+(?:right|correct|ok|okay)\b"
+ r"|\bcan\s+you\s+(?:check|have\s+a\s+look)\b|\bcheck\s+(?:this|that)\b"
+ r"|\bwhat\s+does\s+(?:this|that)\s+mean\b"
+ # --- German --- i18n-allow: German speech-input matching data
+ r"|\bwas\s+ist\s+(?:das|dies)\b(?!\s+(?:fuer\s+ein|denn\s+fuer))" # i18n-allow: DE input
+ r"|\bund\s+(?:das|dies)\s*(?:da|hier)?\s*[.?!]?\s*$"
+ r"|\bwarum\s+ist\s+(?:das|dies)\b|\bstimmt\s+(?:das|dies)\b" # i18n-allow: DE input
+ r"|\bkannst\s+du\s+(?:das|dies)\s+(?:mal\s+)?(?:pruefen|checken|kontrollieren)\b"
+ r"|\bwas\s+(?:bedeutet|heisst)\s+(?:das|dies)\b"
+ r"|\bschau\s+(?:da\s+)?(?:mal\s+)?drauf\b"
+ # --- Spanish --- i18n-allow: Spanish speech-input matching data
+ r"|\bque\s+es\s+(?:esto|eso)\b|\by\s+(?:esto|eso)\b"
+ r"|\bpor\s+que\s+es\s+(?:esto|eso)\b|\besta\s+bien\s+(?:esto|eso)\b"
+ r"|\bpuedes\s+(?:revisar|comprobar)\b|\bque\s+significa\s+(?:esto|eso)\b"
+ r")",
+ re.IGNORECASE,
+)
+
+
+def _evidence(pattern: re.Pattern[str], text: str) -> tuple[str, ...]:
+ """Up to ``_MAX_EVIDENCE`` matched fragments, whitespace-collapsed."""
+ found: list[str] = []
+ for match in pattern.finditer(text):
+ fragment = " ".join(match.group(0).split())
+ if fragment and fragment not in found:
+ found.append(fragment)
+ if len(found) >= _MAX_EVIDENCE:
+ break
+ return tuple(found)
+
+
+def classify(text: str, *, locale: str = "") -> IntentVerdict:
+ """Classify one user turn's visual intent.
+
+ Precedence is most-specific-first: a window-scoped reference wins over a
+ plain screen reference (it says *which* surface), and any unambiguous
+ reference wins over a weak one. An empty or whitespace-only turn is
+ ``NONE`` — non-conversational callers (REST, a scheduled task) reach the
+ service without an utterance and must not be read as having asked to look.
+ """
+ normalized = _normalize(text).strip()
+ if not normalized:
+ return IntentVerdict(intent=VisualIntent.NONE, locale=locale)
+
+ window_hits = _evidence(_WINDOW_SCOPE_RE, normalized)
+ screen_hits = _evidence(_SCREEN_INTENT_RE, normalized)
+
+ # A window noun alone is only a scope, not a request. It upgrades an
+ # unambiguous screen request to window scope, and on its own ("close this
+ # window") it is a desktop command for Computer-Use, not a look request.
+ if window_hits and screen_hits:
+ return IntentVerdict(
+ intent=VisualIntent.WINDOW,
+ evidence=(window_hits + screen_hits)[:_MAX_EVIDENCE],
+ locale=locale,
+ )
+ if screen_hits:
+ return IntentVerdict(
+ intent=VisualIntent.SCREEN, evidence=screen_hits, locale=locale
+ )
+
+ ambiguous_hits = _evidence(_AMBIGUOUS_RE, normalized)
+ # A window reference with no look verb is weak, not absent: "is this tab
+ # right?" plausibly wants a look. Ask.
+ if window_hits or ambiguous_hits:
+ return IntentVerdict(
+ intent=VisualIntent.AMBIGUOUS,
+ evidence=(ambiguous_hits + window_hits)[:_MAX_EVIDENCE],
+ locale=locale,
+ )
+
+ return IntentVerdict(intent=VisualIntent.NONE, locale=locale)
+
+
+# --------------------------------------------------------------------------
+# The clarifying question
+# --------------------------------------------------------------------------
+
+# One entry per supported locale, keyed by the BCP-47 base tag. Adding a locale
+# means adding a line here AND to the matcher above — never a de/en-only table
+# (CLAUDE.md §1.3). The phrasing is deliberately a yes/no question about
+# looking, so a bare "yes" in the next turn is a complete answer.
+# i18n-allow: this IS the runtime multilingual product surface (§1 category 1)
+_CLARIFY_QUESTION: dict[str, str] = {
+ "en": "Should I take a look at your screen?",
+ "de": "Soll ich einmal auf deinen Bildschirm schauen?", # i18n-allow: spoken
+ "es": "¿Quieres que eche un vistazo a tu pantalla?",
+}
+
+#: Fallback locale for a language with no entry — the repo-wide default.
+_FALLBACK_LOCALE = "en"
+
+
+def clarifying_question(locale: str) -> str:
+ """The question Jarvis asks on an ``AMBIGUOUS`` verdict, in ``locale``.
+
+ Takes an ALREADY-RESOLVED locale. This function must never re-derive the
+ output language from the utterance — that is
+ ``jarvis.core.turn_language.resolve_output_language``'s single job, and a
+ second derivation here is exactly the mid-session language flip §1.3
+ forbids.
+ """
+ base = (locale or "").split("-")[0].split("_")[0].strip().lower()
+ return _CLARIFY_QUESTION.get(base) or _CLARIFY_QUESTION[_FALLBACK_LOCALE]
+
+
+#: Locales with a clarifying question. Used by the parity test that pins this
+#: table to the supported-locale list, so a new locale cannot ship half-wired.
+SUPPORTED_CLARIFY_LOCALES: frozenset[str] = frozenset(_CLARIFY_QUESTION)
+
+
+__all__ = [
+ "SUPPORTED_CLARIFY_LOCALES",
+ "clarifying_question",
+ "classify",
+]
diff --git a/jarvis/screen_context/models.py b/jarvis/screen_context/models.py
new file mode 100644
index 0000000000..bc228b1b38
--- /dev/null
+++ b/jarvis/screen_context/models.py
@@ -0,0 +1,306 @@
+"""Immutable data model for the Screen Context service.
+
+Every type here is ``frozen=True``: a capture is a finished fact, and the
+service, the redactor and the consumer all hand the same object around. A
+mutable context would let a later layer quietly widen what an earlier layer
+decided to redact.
+
+Two modelling choices carry the feature's privacy promise:
+
+* :class:`ScreenContext` holds image **bytes**, never a path. A path implies a
+ file, and a file is persistence — which this feature does not do without an
+ explicit, separate act of consent (see ``docs/screen-context.md``).
+* Absence is never rendered as emptiness. A capture that could not read UI text
+ carries a :class:`Degradation` saying so, so neither the model nor the user
+ can mistake "we could not look" for "there was nothing there" (AP-30).
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from enum import StrEnum
+
+# --------------------------------------------------------------------------
+# Intent
+# --------------------------------------------------------------------------
+
+
+class VisualIntent(StrEnum):
+ """How clearly the user asked Jarvis to look at the screen.
+
+ Three-valued on purpose. A two-valued gate has to resolve every unclear
+ utterance as either a capture or a miss; both are wrong for the same
+ inputs ("what is that?" — a question about the screen, or about the topic
+ under discussion?). ``AMBIGUOUS`` is what lets Jarvis ask instead of guess.
+ """
+
+ #: No screen reference at all — the overwhelmingly common case.
+ NONE = "none"
+ #: A screen reference is plausible but not established. Ask, never capture.
+ AMBIGUOUS = "ambiguous"
+ #: Unambiguous: the user wants Jarvis to look at the screen.
+ SCREEN = "screen"
+ #: Unambiguous AND scoped to the focused window/app/document.
+ WINDOW = "window"
+
+
+@dataclass(frozen=True, slots=True)
+class IntentVerdict:
+ """The classifier's answer plus the evidence it is based on.
+
+ ``evidence`` exists so a wrong verdict is debuggable from a log line alone
+ — the alternative is re-deriving the regex match by hand from a transcript
+ that may no longer exist.
+ """
+
+ intent: VisualIntent
+ #: The literal matched fragment(s) of the utterance, for logs and receipts.
+ evidence: tuple[str, ...] = ()
+ #: Locale the classification ran under (BCP-47 base, e.g. ``"de"``).
+ locale: str = ""
+
+ @property
+ def wants_capture(self) -> bool:
+ """True only for the two unambiguous verdicts."""
+ return self.intent in (VisualIntent.SCREEN, VisualIntent.WINDOW)
+
+ @property
+ def needs_clarification(self) -> bool:
+ return self.intent is VisualIntent.AMBIGUOUS
+
+
+# --------------------------------------------------------------------------
+# Targeting
+# --------------------------------------------------------------------------
+
+
+class TargetKind(StrEnum):
+ MONITOR = "monitor"
+ WINDOW = "window"
+
+
+class TargetReason(StrEnum):
+ """Why this surface was chosen — shown in the receipt, logged on capture.
+
+ The user asking "why did it photograph that screen?" deserves an answer
+ that does not require reading the source.
+ """
+
+ #: The monitor the mouse cursor was on at trigger time (the normal path).
+ CURSOR_MONITOR = "cursor_monitor"
+ #: Cursor unreadable — fell back to the monitor hosting the on-screen bar.
+ BAR_MONITOR = "bar_monitor"
+ #: Neither cursor nor bar available — fell back to the OS primary monitor.
+ PRIMARY_MONITOR = "primary_monitor"
+ #: The utterance scoped the request to the focused window.
+ FOCUSED_WINDOW = "focused_window"
+ #: Window scope was asked for but the window rect was unusable.
+ WINDOW_FALLBACK_MONITOR = "window_fallback_monitor"
+
+
+@dataclass(frozen=True, slots=True)
+class WindowFacts:
+ """What is in front, per the OS — independent of any pixels.
+
+ Populated even for a monitor-scoped capture: "which app was the user in"
+ is context the model needs and the accessibility layer answers cheaply.
+ All fields degrade to their empty value rather than raising.
+ """
+
+ app_name: str = ""
+ title: str = ""
+ pid: int = 0
+ #: ``(left, top, width, height)`` in the platform's input units.
+ frame_rect: tuple[int, int, int, int] | None = None
+
+ @property
+ def is_known(self) -> bool:
+ return bool(self.app_name or self.title)
+
+
+@dataclass(frozen=True, slots=True)
+class CaptureTarget:
+ """The exact surface a capture will grab, decided before any pixels move."""
+
+ kind: TargetKind
+ #: ``(left, top, width, height)`` in virtual-desktop coordinates.
+ bbox: tuple[int, int, int, int]
+ reason: TargetReason
+ #: Human-readable monitor identity (mss name, or a synthesized one).
+ monitor_name: str = ""
+ window: WindowFacts = field(default_factory=WindowFacts)
+ #: Native window handle when the capture is window-scoped, else ``None``.
+ window_handle: int | None = None
+
+ @property
+ def width(self) -> int:
+ return int(self.bbox[2])
+
+ @property
+ def height(self) -> int:
+ return int(self.bbox[3])
+
+ @property
+ def is_usable(self) -> bool:
+ """A degenerate rect (zero/negative extent) is never captured."""
+ return self.width > 0 and self.height > 0
+
+
+# --------------------------------------------------------------------------
+# Privacy
+# --------------------------------------------------------------------------
+
+
+class RedactionRule(StrEnum):
+ """Which rule removed something. Carried into the report, not just logged."""
+
+ #: An accessibility node the OS itself marks as a secure/password field.
+ PASSWORD_FIELD = "password_field" # noqa: S105 — a rule name, not a credential
+ #: Text matched a configured sensitive pattern.
+ SENSITIVE_PATTERN = "sensitive_pattern"
+ #: The whole capture was refused because the app is on the denylist.
+ BLOCKED_APP = "blocked_app"
+
+
+@dataclass(frozen=True, slots=True)
+class RedactionHit:
+ """One removal: which rule, which label, and where (if it had a location)."""
+
+ rule: RedactionRule
+ #: Configured label of the matching pattern, e.g. ``"card"`` or ``"iban"``.
+ label: str = ""
+ #: Image region blacked out, ``(left, top, width, height)``, image-local.
+ region: tuple[int, int, int, int] | None = None
+
+
+@dataclass(frozen=True, slots=True)
+class RedactionReport:
+ """What was removed before the context left the process.
+
+ Travels *with* the context to the model. Telling the model "two regions
+ were redacted" is strictly better than handing it a picture with black
+ boxes and no explanation, which invites it to narrate the boxes as UI.
+ """
+
+ hits: tuple[RedactionHit, ...] = ()
+
+ @property
+ def is_empty(self) -> bool:
+ return not self.hits
+
+ @property
+ def region_count(self) -> int:
+ return sum(1 for h in self.hits if h.region is not None)
+
+ @property
+ def text_count(self) -> int:
+ return sum(1 for h in self.hits if h.region is None)
+
+ def summary(self) -> str:
+ """One English line for the receipt and the model-facing note."""
+ if self.is_empty:
+ return "no redactions"
+ parts: list[str] = []
+ if self.region_count:
+ parts.append(f"{self.region_count} image region(s) blacked out")
+ if self.text_count:
+ parts.append(f"{self.text_count} text match(es) replaced")
+ labels = sorted({h.label for h in self.hits if h.label})
+ tail = f" ({', '.join(labels)})" if labels else ""
+ return "; ".join(parts) + tail
+
+
+# --------------------------------------------------------------------------
+# Degradation
+# --------------------------------------------------------------------------
+
+
+class DegradationCode(StrEnum):
+ """Named, machine-readable reasons a capture is less than complete.
+
+ A string message alone would be untestable and untranslatable; the code is
+ the contract and the message is the explanation.
+ """
+
+ NO_CURSOR = "no_cursor"
+ NO_BAR_POSITION = "no_bar_position"
+ NO_WINDOW_FACTS = "no_window_facts"
+ NO_UI_TEXT = "no_ui_text"
+ UI_TEXT_TRUNCATED = "ui_text_truncated"
+ WINDOW_RECT_UNUSABLE = "window_rect_unusable"
+ INDICATOR_UNAVAILABLE = "indicator_unavailable"
+ OCR_UNAVAILABLE = "ocr_unavailable"
+
+
+@dataclass(frozen=True, slots=True)
+class Degradation:
+ """One thing that did not work, in a form the user can be told about."""
+
+ code: DegradationCode
+ #: English, user-facing, actionable where an action exists.
+ message: str
+
+
+# --------------------------------------------------------------------------
+# The context itself
+# --------------------------------------------------------------------------
+
+
+@dataclass(frozen=True, slots=True)
+class ScreenContext:
+ """One capture, redacted, ready to hand to a conversation turn.
+
+ Held in memory by :class:`~jarvis.screen_context.service.ScreenContextService`
+ behind a single-use handle with a TTL. Contains no path: this object *is*
+ the capture, and when the last reference goes, the capture is gone.
+ """
+
+ #: Encoded image bytes (JPEG by default), already redacted.
+ image: bytes
+ mime: str
+ #: Pixel dimensions of the encoded image (post-downscale).
+ size: tuple[int, int]
+ target: CaptureTarget
+ #: Visible UI text from the accessibility layer, scrubbed and truncated.
+ ui_text: str = ""
+ #: Where ``ui_text`` came from: ``"accessibility"``, ``"ocr"``, ``"none"``.
+ ui_text_source: str = "none"
+ redactions: RedactionReport = field(default_factory=RedactionReport)
+ degradations: tuple[Degradation, ...] = ()
+ captured_at_ns: int = 0
+
+ @property
+ def byte_size(self) -> int:
+ return len(self.image)
+
+ def describe(self) -> str:
+ """One English line naming what was captured — the receipt text.
+
+ Deliberately concrete ("right monitor", the app name) rather than
+ "screen captured": the user is being told what left their machine.
+ """
+ if self.target.kind is TargetKind.WINDOW and self.target.window.is_known:
+ where = f"window '{self.target.window.title or self.target.window.app_name}'"
+ else:
+ where = f"monitor {self.target.monitor_name or '?'}"
+ bits = [f"captured {where}", f"{self.size[0]}x{self.size[1]}"]
+ if not self.redactions.is_empty:
+ bits.append(self.redactions.summary())
+ if self.degradations:
+ bits.append(f"{len(self.degradations)} limitation(s)")
+ return ", ".join(bits)
+
+
+__all__ = [
+ "CaptureTarget",
+ "Degradation",
+ "DegradationCode",
+ "IntentVerdict",
+ "RedactionHit",
+ "RedactionReport",
+ "RedactionRule",
+ "ScreenContext",
+ "TargetKind",
+ "TargetReason",
+ "VisualIntent",
+ "WindowFacts",
+]
diff --git a/jarvis/screen_context/ports.py b/jarvis/screen_context/ports.py
new file mode 100644
index 0000000000..da3eaad88b
--- /dev/null
+++ b/jarvis/screen_context/ports.py
@@ -0,0 +1,499 @@
+"""The one platform seam for Screen Context (Windows / macOS / Linux / next).
+
+Five ``Protocol``s, a per-OS implementation behind a factory, and a logged null
+fallback for each. Adding a fourth platform means writing new classes and
+extending the factories — nothing above this module changes, and nothing above
+this module imports a platform package.
+
+The contract every port obeys, without exception:
+
+1. **Never raise into the caller.** A native API that is missing, denied or
+ wedged returns the port's "unavailable" value. The single exception is
+ :class:`CaptureUnavailable`, raised only by :meth:`SurfaceCapturer.grab`,
+ because "I produced no pixels" cannot be expressed as a picture.
+2. **Unavailable is not empty.** A port that cannot answer returns ``None`` or
+ raises, so the service can record a
+ :class:`~jarvis.screen_context.models.Degradation`. Returning ``""`` or an
+ empty list would let a caller narrate a blank screen as fact (AP-30).
+3. **No module-scope platform import.** ``ctypes.windll``, ``Quartz``,
+ ``pynput``, ``mss`` and ``PIL`` are imported inside method bodies, so
+ ``import jarvis.screen_context.ports`` stays clean on ``python:3.11-slim``
+ (HN-7, mirroring ``jarvis.platform.mouse``).
+
+Nothing here initializes at import time (AP-26): the factories are called on
+the first capture, not at boot.
+"""
+from __future__ import annotations
+
+import logging
+from pathlib import Path
+from typing import Protocol, runtime_checkable
+
+from jarvis.screen_context.models import WindowFacts
+
+log = logging.getLogger(__name__)
+
+#: A point in virtual-desktop coordinates, in the platform's input units.
+Point = tuple[int, int]
+#: ``(left, top, width, height)``.
+Rect = tuple[int, int, int, int]
+
+
+class CaptureUnavailable(RuntimeError):
+ """No pixels could be produced, with a user-facing reason.
+
+ Carries an English, actionable message: this text is shown to the user and
+ read by the model, so "capture failed" is never acceptable — it must name
+ the cause and, where one exists, the setting that fixes it.
+ """
+
+
+# --------------------------------------------------------------------------
+# Cursor
+# --------------------------------------------------------------------------
+
+
+@runtime_checkable
+class CursorLocator(Protocol):
+ """Where the mouse pointer is, right now."""
+
+ name: str
+
+ def position(self) -> Point | None:
+ """Cursor ``(x, y)``, or ``None`` when unreadable. Never raises."""
+ ...
+
+
+class PlatformCursorLocator:
+ """Delegates to the existing cross-platform cursor seam.
+
+ ``jarvis.platform.mouse`` already resolves Windows ``GetCursorPos`` /
+ pynput / a null fallback and never raises, so this adapter is a thin
+ rename rather than a second implementation — two cursor backends would
+ drift.
+ """
+
+ name = "platform-cursor"
+
+ def __init__(self) -> None:
+ self._backend = None
+
+ def position(self) -> Point | None:
+ try:
+ if self._backend is None:
+ from jarvis.platform.mouse import make_cursor_backend # noqa: PLC0415
+
+ self._backend = make_cursor_backend()
+ return self._backend.position()
+ except Exception: # noqa: BLE001 — the seam must never raise
+ log.debug("cursor position probe failed", exc_info=True)
+ return None
+
+
+# --------------------------------------------------------------------------
+# Bar position (fallback target when the cursor is unreadable)
+# --------------------------------------------------------------------------
+
+
+@runtime_checkable
+class BarLocator(Protocol):
+ """Where the on-screen bar sits — the documented cursor fallback."""
+
+ name: str
+
+ def position(self) -> Point | None:
+ ...
+
+
+class PersistedBarLocator:
+ """Reads the bar's last persisted position.
+
+ The bar runs in its own process (or its own Qt/Tk thread) and exposes no
+ in-process handle, but it persists its position on every move — so the
+ persisted value is the cheapest correct answer and needs no IPC on the
+ voice path. A bar that has never been moved has no persisted position;
+ that is a ``None``, and the service falls through to the primary monitor.
+ """
+
+ name = "persisted-bar"
+
+ def position(self) -> Point | None:
+ try:
+ from jarvis.core.config_writer import DEFAULT_CONFIG_FILE # noqa: PLC0415
+ from jarvis.ui.jarvisbar import interaction # noqa: PLC0415
+
+ return interaction.load_jarvisbar_position(Path(DEFAULT_CONFIG_FILE))
+ except Exception: # noqa: BLE001 — the seam must never raise
+ log.debug("bar position probe failed", exc_info=True)
+ return None
+
+
+# --------------------------------------------------------------------------
+# Displays
+# --------------------------------------------------------------------------
+
+
+@runtime_checkable
+class DisplayEnumerator(Protocol):
+ """The monitor layout, and which monitor holds a given point."""
+
+ name: str
+
+ def monitors(self) -> list[dict]:
+ """mss-shaped list: ``[0]`` virtual bounds, ``[1:]`` physical screens.
+
+ Returns ``[]`` when no display is addressable (headless, Wayland).
+ """
+ ...
+
+
+class MssDisplayEnumerator:
+ """Enumerates displays via ``mss`` — the same source every other capture
+ path in the tree uses, so monitor identities line up across features."""
+
+ name = "mss-displays"
+
+ def monitors(self) -> list[dict]:
+ try:
+ import mss # type: ignore[import-not-found] # noqa: PLC0415
+
+ with mss.mss() as sct:
+ return [dict(m) for m in sct.monitors]
+ except Exception: # noqa: BLE001 — no display / no mss / X error
+ log.debug("display enumeration failed", exc_info=True)
+ return []
+
+
+# --------------------------------------------------------------------------
+# Windows
+# --------------------------------------------------------------------------
+
+
+@runtime_checkable
+class WindowProbe(Protocol):
+ """What application is in front, and where its window is."""
+
+ name: str
+
+ def foreground(self) -> WindowFacts | None:
+ """Facts about the focused window, or ``None`` when unreadable."""
+ ...
+
+
+class PlatformWindowProbe:
+ """Delegates to ``jarvis.platform.window_state``.
+
+ That module already resolves Win32 / Quartz+AX / xdotool behind one API
+ with per-OS fallbacks. The frame rect is preferred over the plain window
+ rect because it is the visible extent the user sees (DWM shadows excluded
+ on Windows), which is what a capture should match.
+
+ ``WindowInfo`` carries no process name, so the application name is resolved
+ from the pid when the platform filled one in. That lookup is best-effort and
+ optional on purpose: the app name feeds the denylist and the model's
+ context, and a missing one degrades to matching on the title alone rather
+ than to a hard failure.
+ """
+
+ name = "platform-window"
+
+ def foreground(self) -> WindowFacts | None:
+ try:
+ from jarvis.platform import window_state as ws # noqa: PLC0415
+
+ win = ws.foreground_window()
+ if win is None:
+ return None
+ rect = ws.window_frame_rect(win) or ws.window_rect(win)
+ pid = int(getattr(win, "pid", 0) or 0)
+ return WindowFacts(
+ app_name=_app_name_for_pid(pid),
+ title=str(getattr(win, "title", "") or ""),
+ pid=pid,
+ frame_rect=rect,
+ )
+ except Exception: # noqa: BLE001 — the seam must never raise
+ log.debug("foreground window probe failed", exc_info=True)
+ return None
+
+ def foreground_handle(self) -> int | None:
+ """The native window handle of the focused window, when the OS gives one.
+
+ Kept separate from :meth:`foreground` because a handle is only useful to
+ the capturer, and threading it through ``WindowFacts`` would put a
+ platform-specific integer into the model-facing data.
+ """
+ try:
+ from jarvis.platform import window_state as ws # noqa: PLC0415
+
+ win = ws.foreground_window()
+ handle = getattr(win, "handle", None) if win is not None else None
+ return int(handle) if handle is not None else None
+ except Exception: # noqa: BLE001
+ log.debug("foreground handle probe failed", exc_info=True)
+ return None
+
+
+def _app_name_for_pid(pid: int) -> str:
+ """Best-effort process name for ``pid``; ``""`` when it cannot be resolved.
+
+ Not every platform path fills a pid in (only the macOS foreground probe does
+ today), and ``psutil`` may be absent on a minimal install — both degrade to
+ the empty string, which the denylist treats as "match on title only".
+ """
+ if pid <= 0:
+ return ""
+ try:
+ import psutil # noqa: PLC0415
+
+ return str(psutil.Process(pid).name() or "")
+ except Exception: # noqa: BLE001 — no psutil, dead pid, access denied
+ log.debug("process name lookup failed for pid %s", pid, exc_info=True)
+ return ""
+
+
+# --------------------------------------------------------------------------
+# Capture
+# --------------------------------------------------------------------------
+
+
+@runtime_checkable
+class SurfaceCapturer(Protocol):
+ """Grabs a rectangle of the screen, once.
+
+ Returns RAW RGB — encoding happens after redaction, so black boxes are
+ burned into the pixels rather than layered over a already-encoded image
+ that still contains the secret underneath.
+ """
+
+ name: str
+
+ def grab(
+ self, bbox: Rect, *, window_handle: int | None = None
+ ) -> tuple[tuple[int, int], bytes]:
+ """``((width, height), rgb_bytes)``.
+
+ Raises :class:`CaptureUnavailable` — with an actionable English
+ message — when no pixels can be produced.
+ """
+ ...
+
+
+class NativeSurfaceCapturer:
+ """Native per-window capture where the OS offers it, rect grab otherwise.
+
+ macOS ScreenCaptureKit can capture a window wherever it sits, at backing
+ resolution, so a window-scoped request uses it. Everywhere else the
+ DPI-pinned rect grab of the raised window IS the native path (see
+ ``jarvis.platform.window_capture`` for why ``PrintWindow`` is not used on
+ Windows), so both target kinds funnel into ``mss``.
+ """
+
+ name = "native-capture"
+
+ def grab(
+ self, bbox: Rect, *, window_handle: int | None = None
+ ) -> tuple[tuple[int, int], bytes]:
+ left, top, width, height = (int(v) for v in bbox)
+ if width <= 0 or height <= 0:
+ raise CaptureUnavailable(
+ "The area to capture had no size — the window may have been "
+ "closed or minimized between the request and the capture."
+ )
+
+ if window_handle is not None:
+ try:
+ from jarvis.platform.window_capture import grab_window # noqa: PLC0415
+
+ native = grab_window(
+ int(window_handle),
+ {"left": left, "top": top, "width": width, "height": height},
+ )
+ if native is not None:
+ return native
+ except Exception: # noqa: BLE001 — fall through to the rect grab
+ log.debug("native window capture failed; using rect grab", exc_info=True)
+
+ try:
+ import mss # type: ignore[import-not-found] # noqa: PLC0415
+ except ImportError as exc:
+ raise CaptureUnavailable(
+ "Screen capture is not available because the 'mss' package is "
+ "missing from this installation."
+ ) from exc
+
+ try:
+ with mss.mss() as sct:
+ raw = sct.grab(
+ {"left": left, "top": top, "width": width, "height": height}
+ )
+ return ((int(raw.size[0]), int(raw.size[1])), bytes(raw.rgb))
+ except Exception as exc: # noqa: BLE001 — GDI/X/Quartz errors vary widely
+ raise CaptureUnavailable(
+ f"The screen could not be captured right now ({exc}). This is "
+ "usually a locked screen, a sleeping display, or a resolution "
+ "change in progress."
+ ) from exc
+
+
+# --------------------------------------------------------------------------
+# UI text
+# --------------------------------------------------------------------------
+
+
+@runtime_checkable
+class UiTextReader(Protocol):
+ """Reads visible UI text from the platform's accessibility layer."""
+
+ name: str
+
+ async def read(self, *, window_title_filter: str | None = None):
+ """Returns an ``Observation``-shaped object, or ``None`` if unreadable.
+
+ ``None`` (not an empty node list) is the signal that the accessibility
+ layer itself is unavailable — the caller must be able to tell that
+ apart from a window that genuinely has no text.
+ """
+ ...
+
+
+class AccessibilityTextReader:
+ """Delegates to ``jarvis.vision.tree_factory.make_ui_tree_source()``.
+
+ That factory already picks UIA (Windows) / AXUIElement (macOS) / AT-SPI
+ (Linux) / a null source, which is exactly the per-OS accessibility seam
+ this feature needs. The null source returns an Observation with no nodes;
+ this adapter maps that to ``None`` so "no accessibility on this host" and
+ "this window has no text" stay distinguishable.
+ """
+
+ name = "accessibility-text"
+
+ def __init__(self) -> None:
+ self._source = None
+
+ async def read(self, *, window_title_filter: str | None = None):
+ try:
+ if self._source is None:
+ from jarvis.vision.tree_factory import ( # noqa: PLC0415
+ make_ui_tree_source,
+ )
+
+ self._source = make_ui_tree_source()
+ if type(self._source).__name__ == "NullUITreeSource":
+ return None
+ return await self._source.observe(window_title_filter=window_title_filter)
+ except Exception: # noqa: BLE001 — UIA/AX/AT-SPI raise a wide variety
+ log.debug("accessibility text read failed", exc_info=True)
+ return None
+
+
+# --------------------------------------------------------------------------
+# Permission probe
+# --------------------------------------------------------------------------
+
+
+def capture_permission_error() -> str | None:
+ """``None`` when capture is permitted, else an actionable English message.
+
+ Deliberately uncached: macOS can revoke a TCC grant while Jarvis runs, and
+ a cached "granted" would produce a wallpaper-only capture that looks like a
+ successful screenshot of an empty desktop. One native call per capture is
+ the right price for not lying about what was seen.
+ """
+ try:
+ from jarvis.platform.permissions import ( # noqa: PLC0415
+ PermissionId,
+ get_system_permission_port,
+ )
+
+ port = get_system_permission_port()
+ if port.runtime_access_granted(PermissionId.SCREEN_RECORDING):
+ return None
+ return (
+ "Screen capture is blocked because this app does not have the "
+ "screen-recording permission. Grant it in your system privacy "
+ "settings (macOS: System Settings > Privacy & Security > Screen "
+ "Recording), then ask again."
+ )
+ except Exception: # noqa: BLE001 — an unavailable probe must not block Windows/Linux
+ log.debug("screen-recording permission probe failed", exc_info=True)
+ return None
+
+
+def accessibility_permission_error() -> str | None:
+ """``None`` when UI text may be read, else an actionable English message."""
+ try:
+ from jarvis.platform.permissions import ( # noqa: PLC0415
+ PermissionId,
+ get_system_permission_port,
+ )
+
+ port = get_system_permission_port()
+ if port.runtime_access_granted(PermissionId.ACCESSIBILITY):
+ return None
+ return (
+ "Visible UI text could not be read because the accessibility "
+ "permission is missing. The screen image is still available; "
+ "grant accessibility in your system privacy settings to include "
+ "on-screen text."
+ )
+ except Exception: # noqa: BLE001
+ log.debug("accessibility permission probe failed", exc_info=True)
+ return None
+
+
+# --------------------------------------------------------------------------
+# Factories — the ONE place a fourth platform is wired in
+# --------------------------------------------------------------------------
+
+
+def make_cursor_locator() -> CursorLocator:
+ return PlatformCursorLocator()
+
+
+def make_bar_locator() -> BarLocator:
+ return PersistedBarLocator()
+
+
+def make_display_enumerator() -> DisplayEnumerator:
+ return MssDisplayEnumerator()
+
+
+def make_window_probe() -> WindowProbe:
+ return PlatformWindowProbe()
+
+
+def make_surface_capturer() -> SurfaceCapturer:
+ return NativeSurfaceCapturer()
+
+
+def make_ui_text_reader() -> UiTextReader:
+ return AccessibilityTextReader()
+
+
+__all__ = [
+ "AccessibilityTextReader",
+ "BarLocator",
+ "CaptureUnavailable",
+ "CursorLocator",
+ "DisplayEnumerator",
+ "MssDisplayEnumerator",
+ "NativeSurfaceCapturer",
+ "PersistedBarLocator",
+ "PlatformCursorLocator",
+ "PlatformWindowProbe",
+ "Point",
+ "Rect",
+ "SurfaceCapturer",
+ "UiTextReader",
+ "WindowProbe",
+ "accessibility_permission_error",
+ "capture_permission_error",
+ "make_bar_locator",
+ "make_cursor_locator",
+ "make_display_enumerator",
+ "make_surface_capturer",
+ "make_ui_text_reader",
+ "make_window_probe",
+]
diff --git a/jarvis/screen_context/redaction.py b/jarvis/screen_context/redaction.py
new file mode 100644
index 0000000000..c5dba2fbe9
--- /dev/null
+++ b/jarvis/screen_context/redaction.py
@@ -0,0 +1,303 @@
+"""Privacy filtering — runs before a capture leaves the process.
+
+Three mechanisms, in escalating order of bluntness:
+
+1. **App denylist** — a window whose app or title matches is never captured at
+ all. Not captured-and-then-filtered: *not captured*. The distinction is the
+ whole point. A password manager's window is not a picture with some secrets
+ in it that can be scrubbed out; treating it as one means the secret existed
+ in a buffer, and one refactor away from a log line.
+2. **Region redaction** — accessibility nodes the OS marks as secure fields,
+ and nodes whose text matches a sensitive pattern, are filled with opaque
+ black in the raw pixels **before** encoding. Drawing on the raw frame
+ matters: layering a box over an already-encoded image leaves the original
+ bytes underneath.
+3. **Text scrubbing** — the aggregated UI text runs through the same patterns;
+ matches become a typed placeholder rather than disappearing, so the model is
+ told that something was there and does not confabulate around a gap.
+
+Patterns are configurable and additive. Each carries a label that reaches the
+:class:`~jarvis.screen_context.models.RedactionReport`, which travels with the
+context — the user can see what was removed, and the model is told rather than
+handed unexplained black rectangles to narrate as UI.
+
+Deliberately NOT here: any attempt to detect sensitive content *visually*
+(a model that spots a password field in pixels). That would be a model call on
+the capture path, it would be probabilistic where this must be deterministic,
+and it would have to see the unredacted image to decide — defeating the purpose.
+"""
+from __future__ import annotations
+
+import logging
+import re
+from collections.abc import Iterable
+from dataclasses import dataclass
+from typing import Any
+
+from jarvis.screen_context.models import (
+ RedactionHit,
+ RedactionReport,
+ RedactionRule,
+ WindowFacts,
+)
+from jarvis.screen_context.ports import Rect
+
+log = logging.getLogger(__name__)
+
+
+@dataclass(frozen=True, slots=True)
+class SensitivePattern:
+ """One labelled rule for text that must not reach the model."""
+
+ label: str
+ pattern: re.Pattern[str]
+
+ @property
+ def placeholder(self) -> str:
+ return f"[redacted:{self.label}]"
+
+
+def _compile(label: str, source: str) -> SensitivePattern | None:
+ """Compile one configured pattern; a bad regex is skipped, never fatal.
+
+ A user-supplied pattern that fails to compile must not brick the whole
+ feature — but it must also not silently reduce protection, so it is logged
+ at WARNING with the label (AP-30).
+ """
+ try:
+ return SensitivePattern(label=label, pattern=re.compile(source, re.IGNORECASE))
+ except re.error as exc:
+ log.warning(
+ "screen_context: sensitive pattern %r is not a valid regular "
+ "expression and was skipped (%s). Content matching it will NOT be "
+ "redacted.",
+ label,
+ exc,
+ )
+ return None
+
+
+# Shipped defaults. Chosen for shapes that are unambiguous enough to match
+# without a false-positive storm: a 13-19 digit run in card grouping, an IBAN's
+# country+checksum prefix, common API-key prefixes, and auth headers.
+#
+# Deliberately NOT included by default: bare email addresses and phone numbers.
+# They appear in almost every window (a mail client, a contact list), and
+# blacking them out by default would gut the feature's usefulness while the
+# user is looking at exactly the screen they asked about. They are one config
+# entry away for anyone who wants them.
+_DEFAULT_PATTERN_SOURCES: tuple[tuple[str, str], ...] = (
+ ("card", r"\b(?:\d[ -]?){13,19}\b"),
+ ("iban", r"\b[A-Z]{2}\d{2}[ ]?(?:[A-Z0-9]{4}[ ]?){2,7}[A-Z0-9]{1,4}\b"),
+ ("api_key", r"\b(?:sk|pk|rk|api|key|token)[-_][A-Za-z0-9_-]{16,}\b"),
+ # The scheme word must be consumed ALONG WITH the credential: a pattern
+ # ending at the first ``\S+`` after the colon eats only "Bearer" and leaves
+ # the token itself in the text — a redaction that reports success and
+ # removes nothing.
+ ("bearer", r"\b(?:authorization|x-api-key)\s*[:=]\s*(?:bearer\s+)?\S+"),
+ ("bearer", r"\bbearer\s+[A-Za-z0-9._~+/=-]{8,}"),
+ ("secret_assignment", r"\b(?:password|passwd|secret|passphrase)\s*[:=]\s*\S+"),
+ ("private_key", r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),
+)
+
+
+def default_patterns() -> tuple[SensitivePattern, ...]:
+ compiled = (_compile(label, source) for label, source in _DEFAULT_PATTERN_SOURCES)
+ return tuple(p for p in compiled if p is not None)
+
+
+def build_patterns(extra: Iterable[str] = (), *, include_defaults: bool = True):
+ """Default patterns plus user-configured ones.
+
+ Each extra entry is ``"label:regex"`` — the label is what the user sees in
+ the redaction report, so an unlabelled pattern gets the generic ``custom``
+ rather than showing a raw regex in the UI.
+ """
+ patterns: list[SensitivePattern] = list(default_patterns()) if include_defaults else []
+ for entry in extra:
+ raw = str(entry or "").strip()
+ if not raw:
+ continue
+ label, _, source = raw.partition(":")
+ if not source:
+ label, source = "custom", raw
+ compiled = _compile(label.strip() or "custom", source.strip())
+ if compiled is not None:
+ patterns.append(compiled)
+ return tuple(patterns)
+
+
+# --------------------------------------------------------------------------
+# Layer 1 — app denylist
+# --------------------------------------------------------------------------
+
+
+def blocked_by_denylist(facts: WindowFacts, denylist: Iterable[str]) -> str | None:
+ """The matching denylist entry, or ``None`` when capture may proceed.
+
+ Matching is a case-insensitive substring test against the app name AND the
+ window title. Substring rather than exact: the same application is
+ ``"1Password"``, ``"1Password 8"`` and ``"1Password.exe"`` depending on
+ platform and version, and an exact list would silently stop protecting
+ after an update — a failure the user would never notice.
+ """
+ app = (facts.app_name or "").casefold()
+ title = (facts.title or "").casefold()
+ if not app and not title:
+ return None
+ for entry in denylist:
+ needle = str(entry or "").strip().casefold()
+ if not needle:
+ continue
+ if needle in app or needle in title:
+ return str(entry).strip()
+ return None
+
+
+# --------------------------------------------------------------------------
+# Layer 2 — image regions
+# --------------------------------------------------------------------------
+
+
+def regions_to_redact(
+ nodes: Iterable[Any],
+ *,
+ target_bbox: Rect,
+ patterns: Iterable[SensitivePattern],
+ scale: float = 1.0,
+) -> tuple[tuple[Rect, RedactionRule, str], ...]:
+ """Image-local rectangles to black out, derived from accessibility nodes.
+
+ Pure: takes node objects with ``bounds`` / ``is_password`` / ``name`` /
+ ``value`` attributes and returns rectangles in the captured image's own
+ pixel space. Kept free of any imaging library so it can be tested exactly
+ the way it fails in production — with odd rects, off-screen nodes, and
+ HiDPI scaling.
+
+ ``scale`` converts the platform's input units to captured pixels. It is not
+ always 1: macOS reports window and monitor geometry in points while
+ ScreenCaptureKit returns backing pixels, so a Retina capture is 2x the rect
+ it was asked for. Ignoring that would place every black box at a quarter of
+ its intended size in the top-left corner — visibly wrong, and worse,
+ leaving the secret visible.
+ """
+ left, top, width, height = (int(v) for v in target_bbox)
+ out: list[tuple[Rect, RedactionRule, str]] = []
+ pattern_list = list(patterns)
+
+ for node in nodes:
+ bounds = getattr(node, "bounds", None)
+ if not bounds or len(bounds) != 4:
+ continue
+
+ rule: RedactionRule | None = None
+ label = ""
+ if bool(getattr(node, "is_password", False)):
+ rule = RedactionRule.PASSWORD_FIELD
+ label = "password_field"
+ else:
+ text = f"{getattr(node, 'name', '') or ''} {getattr(node, 'value', '') or ''}"
+ if text.strip():
+ for pattern in pattern_list:
+ if pattern.pattern.search(text):
+ rule = RedactionRule.SENSITIVE_PATTERN
+ label = pattern.label
+ break
+ if rule is None:
+ continue
+
+ nx, ny, nw, nh = (int(v) for v in bounds)
+ if nw <= 0 or nh <= 0:
+ continue
+
+ # Clip to the captured area, then translate into image-local space.
+ clipped_left = max(nx, left)
+ clipped_top = max(ny, top)
+ clipped_right = min(nx + nw, left + width)
+ clipped_bottom = min(ny + nh, top + height)
+ if clipped_right <= clipped_left or clipped_bottom <= clipped_top:
+ continue # entirely outside the captured surface
+
+ out.append(
+ (
+ (
+ int((clipped_left - left) * scale),
+ int((clipped_top - top) * scale),
+ max(1, int((clipped_right - clipped_left) * scale)),
+ max(1, int((clipped_bottom - clipped_top) * scale)),
+ ),
+ rule,
+ label,
+ )
+ )
+ return tuple(out)
+
+
+def apply_image_redactions(image: Any, regions) -> tuple[Any, tuple[RedactionHit, ...]]:
+ """Fill ``regions`` with opaque black on a Pillow image, in place.
+
+ Returns the image and the hits, so the caller never has to reconstruct what
+ was drawn. A failure to draw is NOT swallowed into a "best effort" — if a
+ region cannot be blacked out, the caller must know, because shipping the
+ image anyway would leak exactly what this function exists to hide.
+ """
+ if not regions:
+ return image, ()
+ from PIL import ImageDraw # noqa: PLC0415
+
+ draw = ImageDraw.Draw(image)
+ hits: list[RedactionHit] = []
+ for rect, rule, label in regions:
+ x, y, w, h = rect
+ draw.rectangle([x, y, x + w, y + h], fill=(0, 0, 0))
+ hits.append(RedactionHit(rule=rule, label=label, region=rect))
+ return image, tuple(hits)
+
+
+# --------------------------------------------------------------------------
+# Layer 3 — text
+# --------------------------------------------------------------------------
+
+
+def scrub_text(
+ text: str, patterns: Iterable[SensitivePattern]
+) -> tuple[str, tuple[RedactionHit, ...]]:
+ """Replace sensitive matches with typed placeholders.
+
+ A placeholder rather than deletion: a model handed text with a silent hole
+ fills the hole. ``[redacted:card]`` tells it plainly that a card number was
+ there and was withheld, which is both truthful and more useful.
+ """
+ if not text:
+ return "", ()
+ hits: list[RedactionHit] = []
+ scrubbed = text
+ for pattern in patterns:
+ found = pattern.pattern.findall(scrubbed)
+ if not found:
+ continue
+ scrubbed = pattern.pattern.sub(pattern.placeholder, scrubbed)
+ hits.extend(
+ RedactionHit(rule=RedactionRule.SENSITIVE_PATTERN, label=pattern.label)
+ for _ in range(len(found))
+ )
+ return scrubbed, tuple(hits)
+
+
+def merge_reports(*hit_groups: Iterable[RedactionHit]) -> RedactionReport:
+ merged: list[RedactionHit] = []
+ for group in hit_groups:
+ merged.extend(group)
+ return RedactionReport(hits=tuple(merged))
+
+
+__all__ = [
+ "SensitivePattern",
+ "apply_image_redactions",
+ "blocked_by_denylist",
+ "build_patterns",
+ "default_patterns",
+ "merge_reports",
+ "regions_to_redact",
+ "scrub_text",
+]
diff --git a/jarvis/screen_context/service.py b/jarvis/screen_context/service.py
new file mode 100644
index 0000000000..b2f0c8646b
--- /dev/null
+++ b/jarvis/screen_context/service.py
@@ -0,0 +1,634 @@
+"""``ScreenContextService`` — one capture, on request, then gone.
+
+This is the orchestration layer: it asks the classifier whether the user
+actually asked to look, checks permissions, picks the surface, announces the
+capture, grabs pixels exactly once, redacts them, and hands back a short-lived
+handle. Every piece of platform knowledge lives below it in ``ports.py``, so
+this module is fully unit-testable with fakes and needs no display.
+
+**Single capture, by construction.** There is no loop, no timer, no cached
+frame, and no "refresh". :meth:`ScreenContextService.capture` grabs once and
+returns; the only way to get another capture is another explicit call. That is
+not a policy the code merely follows — there is no code path here that could
+capture twice.
+
+**Retention.** A finished :class:`~jarvis.screen_context.models.ScreenContext`
+lives in a :class:`_Handle` in memory, keyed by an opaque id, and is removed on
+the first :meth:`consume` or when its TTL expires, whichever comes first.
+Nothing is written to disk. This is a deliberate departure from
+``jarvis.vision.screenshot.ScreenshotSource``, which persists every frame to
+``data/flight_recorder/blobs/`` — correct for Computer-Use replay, wrong for a
+feature whose promise is that the picture does not stick around. That is also
+why this module uses the stateless ``capture_region``-style grab through the
+port rather than reusing ``ScreenshotSource``.
+"""
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import io
+import logging
+import secrets
+import time
+from dataclasses import dataclass
+from typing import Any, Literal
+
+from jarvis.screen_context import intent as intent_module
+from jarvis.screen_context import redaction, uitext
+from jarvis.screen_context.models import (
+ CaptureTarget,
+ Degradation,
+ DegradationCode,
+ IntentVerdict,
+ ScreenContext,
+ TargetKind,
+ VisualIntent,
+)
+from jarvis.screen_context.ports import (
+ CaptureUnavailable,
+ accessibility_permission_error,
+ capture_permission_error,
+ make_bar_locator,
+ make_cursor_locator,
+ make_display_enumerator,
+ make_surface_capturer,
+ make_ui_text_reader,
+ make_window_probe,
+)
+from jarvis.screen_context.targeting import resolve_target
+
+log = logging.getLogger(__name__)
+
+#: Vision models downscale to roughly this on the long edge for token
+#: accounting, so anything larger costs bytes and latency for no added detail.
+#: Same value the existing screenshot tool settled on.
+_MAX_DIMENSION = 2048
+_JPEG_QUALITY = 85
+_MAX_IMAGE_BYTES = 500_000
+_MIN_JPEG_QUALITY = 50
+
+#: How long the announcement gets to reach a subscriber before the shutter.
+#: Short by design: a hung subscriber must not stall a voice turn, and the
+#: degradation is recorded rather than the capture being abandoned.
+_ANNOUNCE_TIMEOUT_S = 0.4
+
+CaptureStatus = Literal["captured", "clarify", "refused", "not_requested"]
+
+
+@dataclass(frozen=True, slots=True)
+class ScreenContextSettings:
+ """Everything configurable, resolved once and passed in.
+
+ A plain dataclass rather than a direct ``JarvisConfig`` read so the service
+ stays testable without a config file, and so every setting the service
+ honours is visible in one place (AP-31: no key that nothing reads).
+ """
+
+ enabled: bool = True
+ #: App names / window-title fragments that are never captured at all.
+ denylist: tuple[str, ...] = ()
+ #: Extra ``"label:regex"`` patterns on top of the shipped defaults.
+ extra_patterns: tuple[str, ...] = ()
+ include_default_patterns: bool = True
+ #: Character budget for on-screen text handed to the model.
+ max_text_chars: int = 4000
+ #: Seconds an unconsumed capture stays in memory.
+ ttl_s: float = 120.0
+ #: OCR is a supplement, off unless the user asks for it.
+ ocr_enabled: bool = False
+ #: ``[computer_use].main_monitor``-style override for the last-resort pick.
+ main_monitor: str = "primary"
+
+
+@dataclass(frozen=True, slots=True)
+class CaptureOutcome:
+ """What happened, in a shape the caller can act on without guessing.
+
+ Four statuses, and the caller must handle all four:
+
+ * ``not_requested`` — the turn contained no visual intent. Carry on.
+ * ``clarify`` — ambiguous. Ask ``question`` and capture nothing.
+ * ``refused`` — capture was not possible or not allowed. Say ``message``.
+ * ``captured`` — ``handle_id`` and ``context`` are set.
+ """
+
+ status: CaptureStatus
+ verdict: IntentVerdict
+ context: ScreenContext | None = None
+ handle_id: str | None = None
+ question: str | None = None
+ message: str | None = None
+
+
+@dataclass
+class _Handle:
+ context: ScreenContext
+ expires_at_ns: int
+
+
+class ScreenContextService:
+ """One-shot screen context for the on-screen bar and the voice session."""
+
+ def __init__(
+ self,
+ *,
+ settings: ScreenContextSettings | None = None,
+ bus: Any | None = None,
+ cursor: Any | None = None,
+ bar: Any | None = None,
+ displays: Any | None = None,
+ window_probe: Any | None = None,
+ capturer: Any | None = None,
+ ui_text_reader: Any | None = None,
+ permission_probe: Any | None = None,
+ clock: Any | None = None,
+ ) -> None:
+ self._settings = settings or ScreenContextSettings()
+ self._bus = bus
+ # Ports are constructed lazily on first use, never at import or at
+ # boot (AP-26): building a cursor backend or an accessibility source
+ # costs native library loads that must not sit on the startup path.
+ self._cursor = cursor
+ self._bar = bar
+ self._displays = displays
+ self._window_probe = window_probe
+ self._capturer = capturer
+ self._ui_text_reader = ui_text_reader
+ self._permission_probe = permission_probe or capture_permission_error
+ self._clock = clock or time.time_ns
+ self._handles: dict[str, _Handle] = {}
+ self._patterns = redaction.build_patterns(
+ self._settings.extra_patterns,
+ include_defaults=self._settings.include_default_patterns,
+ )
+
+ @property
+ def settings(self) -> ScreenContextSettings:
+ """The resolved settings this service is running with (read-only)."""
+ return self._settings
+
+ # ---- ports (lazy) ----------------------------------------------------
+
+ @property
+ def cursor(self):
+ if self._cursor is None:
+ self._cursor = make_cursor_locator()
+ return self._cursor
+
+ @property
+ def bar(self):
+ if self._bar is None:
+ self._bar = make_bar_locator()
+ return self._bar
+
+ @property
+ def displays(self):
+ if self._displays is None:
+ self._displays = make_display_enumerator()
+ return self._displays
+
+ @property
+ def window_probe(self):
+ if self._window_probe is None:
+ self._window_probe = make_window_probe()
+ return self._window_probe
+
+ @property
+ def capturer(self):
+ if self._capturer is None:
+ self._capturer = make_surface_capturer()
+ return self._capturer
+
+ @property
+ def ui_text_reader(self):
+ if self._ui_text_reader is None:
+ self._ui_text_reader = make_ui_text_reader()
+ return self._ui_text_reader
+
+ # ---- intent ----------------------------------------------------------
+
+ def classify(self, text: str, *, locale: str = "") -> IntentVerdict:
+ """Public wrapper so callers never import the matcher directly."""
+ return intent_module.classify(text, locale=locale)
+
+ # ---- the capture -----------------------------------------------------
+
+ async def capture_for_turn(
+ self, text: str, *, locale: str = "", force: bool = False
+ ) -> CaptureOutcome:
+ """Classify one user turn and capture only if it unambiguously asked.
+
+ ``locale`` must be the ALREADY-RESOLVED output language for this turn
+ (``jarvis.core.turn_language.resolve_output_language``). This service
+ never derives a language itself — a second derivation is exactly the
+ mid-session language flip CLAUDE.md §1.3 forbids.
+
+ ``force`` skips classification for callers that are not a conversation
+ turn (the REST endpoint, an explicit bar button). It never skips
+ permissions, the denylist, or redaction.
+ """
+ verdict = (
+ IntentVerdict(intent=VisualIntent.SCREEN, evidence=("forced",), locale=locale)
+ if force
+ else self.classify(text, locale=locale)
+ )
+
+ if not self._settings.enabled:
+ return CaptureOutcome(
+ status="refused",
+ verdict=verdict,
+ message=(
+ "Screen context is switched off. You can turn it back on in "
+ "Settings."
+ ),
+ )
+
+ if verdict.intent is VisualIntent.NONE:
+ return CaptureOutcome(status="not_requested", verdict=verdict)
+
+ if verdict.intent is VisualIntent.AMBIGUOUS:
+ log.info(
+ "screen_context: ambiguous visual intent (evidence=%s) — asking "
+ "instead of capturing",
+ verdict.evidence,
+ )
+ return CaptureOutcome(
+ status="clarify",
+ verdict=verdict,
+ question=intent_module.clarifying_question(locale),
+ )
+
+ return await self.capture(verdict=verdict)
+
+ async def capture(self, *, verdict: IntentVerdict | None = None) -> CaptureOutcome:
+ """Take exactly one capture. Assumes intent is already established."""
+ verdict = verdict or IntentVerdict(intent=VisualIntent.SCREEN)
+
+ permission_error = self._permission_probe()
+ if permission_error:
+ log.info("screen_context: capture refused — %s", permission_error)
+ return CaptureOutcome(
+ status="refused", verdict=verdict, message=permission_error
+ )
+
+ # The cursor is sampled ONCE, here, and threaded through. See
+ # targeting.resolve_target for why re-reading it later is a race.
+ cursor_point = self.cursor.position()
+ bar_point = self.bar.position() if cursor_point is None else None
+ window_facts = self.window_probe.foreground()
+
+ degradations: list[Degradation] = []
+ if window_facts is None:
+ degradations.append(
+ Degradation(
+ code=DegradationCode.NO_WINDOW_FACTS,
+ message=(
+ "The active application could not be identified, so the "
+ "screen was captured without app or window information."
+ ),
+ )
+ )
+
+ # Denylist BEFORE targeting and before any pixels exist.
+ if window_facts is not None:
+ blocked_by = redaction.blocked_by_denylist(
+ window_facts, self._settings.denylist
+ )
+ if blocked_by:
+ log.info(
+ "screen_context: capture blocked by denylist entry %r", blocked_by
+ )
+ return CaptureOutcome(
+ status="refused",
+ verdict=verdict,
+ message=(
+ f"I did not capture the screen: the active window matches "
+ f"your privacy rule '{blocked_by}', so screen context is "
+ "switched off for it."
+ ),
+ context=None,
+ )
+
+ window_handle = None
+ if verdict.intent is VisualIntent.WINDOW:
+ getter = getattr(self.window_probe, "foreground_handle", None)
+ if callable(getter):
+ window_handle = getter()
+
+ try:
+ target, target_degradations = resolve_target(
+ verdict.intent,
+ monitors=self.displays.monitors(),
+ cursor_point=cursor_point,
+ bar_point=bar_point,
+ window=window_facts,
+ window_handle=window_handle,
+ main_monitor_override=self._settings.main_monitor,
+ )
+ except CaptureUnavailable as exc:
+ log.info("screen_context: no capture target — %s", exc)
+ return CaptureOutcome(status="refused", verdict=verdict, message=str(exc))
+ degradations.extend(target_degradations)
+
+ # Announce BEFORE the shutter so the indicator is up while there is
+ # still something to indicate.
+ announced = await self._announce(target)
+ if not announced:
+ degradations.append(
+ Degradation(
+ code=DegradationCode.INDICATOR_UNAVAILABLE,
+ message=(
+ "The capture indicator could not be shown, so this "
+ "capture happened without an on-screen signal."
+ ),
+ )
+ )
+
+ try:
+ size, rgb = await asyncio.to_thread(
+ self.capturer.grab, target.bbox, window_handle=target.window_handle
+ )
+ except CaptureUnavailable as exc:
+ log.info("screen_context: capture failed — %s", exc)
+ return CaptureOutcome(status="refused", verdict=verdict, message=str(exc))
+ except Exception as exc: # noqa: BLE001 — a port bug must not kill the turn
+ log.error("screen_context: unexpected capture failure", exc_info=True)
+ return CaptureOutcome(
+ status="refused",
+ verdict=verdict,
+ message=f"The screen could not be captured ({exc}).",
+ )
+
+ context = await self._build_context(
+ target=target,
+ raw_size=size,
+ rgb=rgb,
+ degradations=degradations,
+ )
+
+ handle_id = self.store(context)
+ await self._publish_completed(context)
+ log.info("screen_context: %s", context.describe())
+ return CaptureOutcome(
+ status="captured", verdict=verdict, context=context, handle_id=handle_id
+ )
+
+ # ---- assembly --------------------------------------------------------
+
+ async def _build_context(
+ self,
+ *,
+ target: CaptureTarget,
+ raw_size: tuple[int, int],
+ rgb: bytes,
+ degradations: list[Degradation],
+ ) -> ScreenContext:
+ """Read text, redact pixels and text, encode. In that order.
+
+ Order is load-bearing: redaction happens on the RAW frame, before any
+ encoding or downscaling, so the black boxes are burned into the pixels
+ rather than layered over bytes that still hold the original.
+ """
+ from PIL import Image # noqa: PLC0415
+
+ image = Image.frombytes("RGB", raw_size, rgb)
+
+ # -- on-screen text -------------------------------------------------
+ text, text_source, nodes, text_degradations = "", "none", (), ()
+ access_error = accessibility_permission_error()
+ if access_error:
+ degradations.append(
+ Degradation(code=DegradationCode.NO_UI_TEXT, message=access_error)
+ )
+ else:
+ text, text_source, nodes, text_degradations = await uitext.read_ui_text(
+ self.ui_text_reader,
+ target_rect=target.bbox,
+ max_chars=self._settings.max_text_chars,
+ window_title_filter=(
+ target.window.title if target.kind is TargetKind.WINDOW else None
+ ),
+ )
+ degradations.extend(text_degradations)
+
+ # -- image redaction, on the raw frame ------------------------------
+ # macOS returns backing pixels for a rect measured in points, so the
+ # capture can be 2x the geometry it was asked for. Deriving the scale
+ # from the actual image keeps the black boxes on top of what they are
+ # meant to cover instead of a quarter of it.
+ scale = (raw_size[0] / target.width) if target.width else 1.0
+ regions = redaction.regions_to_redact(
+ nodes, target_bbox=target.bbox, patterns=self._patterns, scale=scale
+ )
+ image, region_hits = redaction.apply_image_redactions(image, regions)
+
+ # -- text scrubbing --------------------------------------------------
+ scrubbed_text, text_hits = redaction.scrub_text(text, self._patterns)
+
+ # -- OCR, only to fill a genuine gap ---------------------------------
+ if self._settings.ocr_enabled and uitext.text_is_sparse(scrubbed_text):
+ ocr_text, ocr_degradation = await asyncio.to_thread(
+ uitext.ocr_supplement, image
+ )
+ if ocr_degradation is not None:
+ degradations.append(ocr_degradation)
+ elif ocr_text:
+ ocr_scrubbed, ocr_hits = redaction.scrub_text(ocr_text, self._patterns)
+ scrubbed_text = (
+ f"{scrubbed_text}\n{ocr_scrubbed}".strip()
+ if scrubbed_text
+ else ocr_scrubbed
+ )
+ text_hits = text_hits + ocr_hits
+ text_source = "ocr" if text_source == "none" else "accessibility+ocr"
+
+ image_bytes, encoded_size = _encode(image)
+
+ return ScreenContext(
+ image=image_bytes,
+ mime="image/jpeg",
+ size=encoded_size,
+ target=target,
+ ui_text=scrubbed_text,
+ ui_text_source=text_source,
+ redactions=redaction.merge_reports(region_hits, text_hits),
+ degradations=tuple(degradations),
+ captured_at_ns=self._clock(),
+ )
+
+ # ---- handles ---------------------------------------------------------
+
+ def store(self, context: ScreenContext) -> str:
+ """Park a context behind an opaque, single-use id."""
+ self.sweep()
+ handle_id = secrets.token_urlsafe(12)
+ self._handles[handle_id] = _Handle(
+ context=context,
+ expires_at_ns=self._clock() + int(self._settings.ttl_s * 1_000_000_000),
+ )
+ return handle_id
+
+ def consume(self, handle_id: str) -> ScreenContext | None:
+ """Take a context out. A second call for the same id gets ``None``.
+
+ Single consumption is the retention promise in code: the caller cannot
+ hold an id and re-fetch the picture later, and nothing has to remember
+ to clean up.
+ """
+ self.sweep()
+ handle = self._handles.pop(handle_id, None)
+ return handle.context if handle is not None else None
+
+ def peek(self, handle_id: str) -> ScreenContext | None:
+ """Metadata read WITHOUT consuming — used by the receipt endpoint."""
+ self.sweep()
+ handle = self._handles.get(handle_id)
+ return handle.context if handle is not None else None
+
+ def sweep(self) -> int:
+ """Drop expired handles. Returns how many were dropped."""
+ now = self._clock()
+ expired = [k for k, h in self._handles.items() if h.expires_at_ns <= now]
+ for key in expired:
+ self._handles.pop(key, None)
+ if expired:
+ log.debug("screen_context: dropped %d expired capture(s)", len(expired))
+ return len(expired)
+
+ def discard_all(self) -> int:
+ """Drop every held capture immediately (the panic button)."""
+ count = len(self._handles)
+ self._handles.clear()
+ return count
+
+ @property
+ def held_count(self) -> int:
+ self.sweep()
+ return len(self._handles)
+
+ # ---- bus -------------------------------------------------------------
+
+ async def _announce(self, target: CaptureTarget) -> bool:
+ """Publish the pre-capture announcement. ``False`` if nobody heard it.
+
+ A missing or slow bus degrades to a recorded limitation rather than to
+ a refused capture: a broken indicator must not brick the feature, but
+ it must never be invisible either (AP-30).
+ """
+ if self._bus is None:
+ return False
+ try:
+ from jarvis.core.events import ScreenCaptureAnnounced # noqa: PLC0415
+
+ await asyncio.wait_for(
+ self._bus.publish(
+ ScreenCaptureAnnounced(
+ target_kind=str(target.kind),
+ target_label=(
+ target.window.title
+ if target.kind is TargetKind.WINDOW
+ else target.monitor_name
+ ),
+ reason=str(target.reason),
+ )
+ ),
+ timeout=_ANNOUNCE_TIMEOUT_S,
+ )
+ return True
+ except TimeoutError:
+ log.warning(
+ "screen_context: capture indicator did not acknowledge within "
+ "%.1fs — capturing without an on-screen signal",
+ _ANNOUNCE_TIMEOUT_S,
+ )
+ return False
+ except Exception: # noqa: BLE001 — a subscriber bug must not stop a capture
+ log.warning("screen_context: capture announcement failed", exc_info=True)
+ return False
+
+ async def _publish_completed(self, context: ScreenContext) -> None:
+ if self._bus is None:
+ return
+ with contextlib.suppress(Exception):
+ from jarvis.core.events import ScreenCaptureCompleted # noqa: PLC0415
+
+ await self._bus.publish(
+ ScreenCaptureCompleted(
+ target_kind=str(context.target.kind),
+ target_label=(
+ context.target.window.title
+ if context.target.kind is TargetKind.WINDOW
+ else context.target.monitor_name
+ ),
+ width=context.size[0],
+ height=context.size[1],
+ bytes_size=context.byte_size,
+ redaction_count=len(context.redactions.hits),
+ degradation_count=len(context.degradations),
+ ui_text_source=context.ui_text_source,
+ )
+ )
+
+
+def _encode(image: Any) -> tuple[bytes, tuple[int, int]]:
+ """Downscale to the vision budget, then JPEG within the byte ceiling."""
+ from PIL import Image # noqa: PLC0415
+
+ width, height = image.size
+ longest = max(width, height)
+ if longest > _MAX_DIMENSION:
+ factor = _MAX_DIMENSION / longest
+ image = image.resize(
+ (max(1, round(width * factor)), max(1, round(height * factor))),
+ resample=Image.Resampling.LANCZOS,
+ )
+
+ quality = _JPEG_QUALITY
+ while True:
+ buffer = io.BytesIO()
+ image.save(buffer, format="JPEG", quality=quality, optimize=True)
+ data = buffer.getvalue()
+ if len(data) <= _MAX_IMAGE_BYTES or quality <= _MIN_JPEG_QUALITY:
+ return data, image.size
+ quality -= 10
+
+
+# --------------------------------------------------------------------------
+# Config bridge
+# --------------------------------------------------------------------------
+
+
+def settings_from_config(cfg: Any) -> ScreenContextSettings:
+ """Build settings from a ``JarvisConfig``, tolerating an older config file.
+
+ Every value is read defensively: a config written by an older version has
+ no ``[screen_context]`` block at all, and that must produce working
+ defaults rather than an AttributeError on the voice path.
+ """
+ block = getattr(cfg, "screen_context", None)
+ if block is None:
+ return ScreenContextSettings()
+ main_monitor = "primary"
+ with contextlib.suppress(Exception):
+ main_monitor = str(getattr(cfg.computer_use, "main_monitor", "primary"))
+ return ScreenContextSettings(
+ enabled=bool(getattr(block, "enabled", True)),
+ denylist=tuple(getattr(block, "denylist", ()) or ()),
+ extra_patterns=tuple(getattr(block, "sensitive_patterns", ()) or ()),
+ include_default_patterns=bool(
+ getattr(block, "include_default_patterns", True)
+ ),
+ max_text_chars=int(getattr(block, "max_text_chars", 4000)),
+ ttl_s=float(getattr(block, "ttl_s", 120.0)),
+ ocr_enabled=bool(getattr(block, "ocr_enabled", False)),
+ main_monitor=main_monitor,
+ )
+
+
+__all__ = [
+ "CaptureOutcome",
+ "CaptureStatus",
+ "ScreenContextService",
+ "ScreenContextSettings",
+ "settings_from_config",
+]
diff --git a/jarvis/screen_context/targeting.py b/jarvis/screen_context/targeting.py
new file mode 100644
index 0000000000..5d06b89923
--- /dev/null
+++ b/jarvis/screen_context/targeting.py
@@ -0,0 +1,264 @@
+"""Decides WHICH surface a capture grabs — before any pixels move.
+
+The rule the feature is specified around: **the monitor the mouse cursor is on
+at trigger time**, with the on-screen bar's monitor as the fallback when no
+cursor is readable, and the OS primary as the last resort.
+
+This differs on purpose from every other capture path in the tree, which
+follows the *foreground window* (``jarvis.vision.screenshot.select_capture_monitor``).
+The two diverge constantly and visibly: the user reads an error on the right
+screen while the focused window still sits on the left. Following the window
+there captures the screen the user is not looking at — which is the single most
+confusing failure this feature can have, because the answer sounds confident and
+describes the wrong screen.
+
+Everything here is pure given its inputs. The cursor point is *passed in*, never
+read: see :func:`resolve_target` for why that is a correctness requirement and
+not a testing convenience.
+"""
+from __future__ import annotations
+
+import logging
+
+from jarvis.screen_context.models import (
+ CaptureTarget,
+ Degradation,
+ DegradationCode,
+ TargetKind,
+ TargetReason,
+ VisualIntent,
+ WindowFacts,
+)
+from jarvis.screen_context.ports import CaptureUnavailable, Point, Rect
+
+log = logging.getLogger(__name__)
+
+#: A window narrower or shorter than this is treated as unusable — a collapsed,
+#: minimized (Windows parks these at -32000) or mid-animation window would
+#: otherwise produce a capture of a sliver of nothing.
+_MIN_WINDOW_EXTENT_PX = 64
+
+
+def _rect_of(monitor: dict) -> Rect:
+ return (
+ int(monitor.get("left", 0)),
+ int(monitor.get("top", 0)),
+ int(monitor.get("width", 0)),
+ int(monitor.get("height", 0)),
+ )
+
+
+def _contains(monitor: dict, point: Point) -> bool:
+ left, top, width, height = _rect_of(monitor)
+ x, y = point
+ return left <= x < left + width and top <= y < top + height
+
+
+def _distance_to(monitor: dict, point: Point) -> int:
+ """Squared distance from ``point`` to the monitor rect (0 when inside)."""
+ left, top, width, height = _rect_of(monitor)
+ x, y = point
+ dx = max(left - x, 0, x - (left + width - 1))
+ dy = max(top - y, 0, y - (top + height - 1))
+ return dx * dx + dy * dy
+
+
+def monitor_for_point(monitors: list[dict], point: Point) -> dict | None:
+ """The monitor containing ``point``, else the nearest one.
+
+ ``monitors`` is mss-shaped: ``[0]`` is the virtual bounding box over every
+ screen, ``[1:]`` are the physical ones. Only physical screens are
+ candidates — returning the virtual box would capture every monitor at once,
+ which is precisely what "only the monitor the cursor is on" rules out.
+
+ Nearest-match rather than ``None`` for a point outside every screen: a
+ cursor can legitimately sit in an L-shaped layout gap or one pixel past an
+ edge, and refusing to capture there would be a mysterious intermittent
+ failure. This mirrors Windows' own ``MONITOR_DEFAULTTONEAREST``.
+ """
+ physical = monitors[1:] if len(monitors) > 1 else monitors
+ if not physical:
+ return None
+ for monitor in physical:
+ if _contains(monitor, point):
+ return monitor
+ nearest = min(physical, key=lambda m: _distance_to(m, point))
+ log.debug(
+ "screen_context: point %s is on no monitor — using nearest %s",
+ point,
+ nearest.get("name"),
+ )
+ return nearest
+
+
+def _primary_monitor(monitors: list[dict], *, override: str = "primary") -> dict | None:
+ """The OS primary, via the shared resolver (honours ``main_monitor``)."""
+ physical = monitors[1:] if len(monitors) > 1 else monitors
+ if not physical:
+ return None
+ try:
+ from jarvis.platform.monitors import resolve_primary_monitor # noqa: PLC0415
+
+ return resolve_primary_monitor(monitors, override=override)
+ except Exception: # noqa: BLE001 — never fail targeting over a probe
+ log.debug("primary monitor resolution failed", exc_info=True)
+ return physical[0]
+
+
+def _monitor_name(monitor: dict, monitors: list[dict]) -> str:
+ """A stable, human-readable identity for the receipt.
+
+ mss does not name monitors, so an index-based label is synthesized. It is
+ what the user is told ("captured monitor 2"), so it must be the same label
+ across captures — the index into the enumeration is, the geometry is not.
+ """
+ explicit = str(monitor.get("name", "") or "").strip()
+ if explicit:
+ return explicit
+ physical = monitors[1:] if len(monitors) > 1 else monitors
+ for index, candidate in enumerate(physical, start=1):
+ if _rect_of(candidate) == _rect_of(monitor):
+ return f"{index}"
+ return "?"
+
+
+def _window_rect_is_usable(rect: Rect | None) -> bool:
+ if rect is None:
+ return False
+ _left, _top, width, height = rect
+ return width >= _MIN_WINDOW_EXTENT_PX and height >= _MIN_WINDOW_EXTENT_PX
+
+
+def resolve_target(
+ intent: VisualIntent,
+ *,
+ monitors: list[dict],
+ cursor_point: Point | None,
+ bar_point: Point | None,
+ window: WindowFacts | None,
+ window_handle: int | None = None,
+ main_monitor_override: str = "primary",
+) -> tuple[CaptureTarget, tuple[Degradation, ...]]:
+ """Pick the surface to capture and report what had to be worked around.
+
+ ``cursor_point`` is passed in rather than read here, and that is a
+ correctness requirement: the cursor must be sampled ONCE at trigger time
+ and threaded through the whole capture. Reading it again at grab time lets
+ a mouse move between the decision and the shutter change which screen is
+ captured — a race that surfaces as "it photographed the wrong monitor" and
+ is essentially impossible to reproduce on demand.
+
+ Raises :class:`CaptureUnavailable` when the host has no addressable display
+ at all (headless server, Wayland). That is the one condition targeting
+ cannot degrade around: there is no screen to pick.
+ """
+ degradations: list[Degradation] = []
+ facts = window or WindowFacts()
+
+ if not monitors:
+ raise CaptureUnavailable(
+ "No display is available on this machine, so there is nothing to "
+ "capture. This is expected on a headless server; on Wayland, "
+ "screen capture has to go through the compositor and is not "
+ "available to the app directly."
+ )
+
+ # ---- Window scope: only when the user actually scoped it there --------
+ if intent is VisualIntent.WINDOW:
+ if _window_rect_is_usable(facts.frame_rect):
+ assert facts.frame_rect is not None # narrowed by the check above
+ return (
+ CaptureTarget(
+ kind=TargetKind.WINDOW,
+ bbox=facts.frame_rect,
+ reason=TargetReason.FOCUSED_WINDOW,
+ monitor_name=_monitor_name(
+ monitor_for_point(
+ monitors,
+ (facts.frame_rect[0], facts.frame_rect[1]),
+ )
+ or {},
+ monitors,
+ ),
+ window=facts,
+ window_handle=window_handle,
+ ),
+ (),
+ )
+ degradations.append(
+ Degradation(
+ code=DegradationCode.WINDOW_RECT_UNUSABLE,
+ message=(
+ "The focused window could not be measured (it may be "
+ "minimized or still opening), so the whole screen was "
+ "captured instead."
+ ),
+ )
+ )
+ reason_when_falling_back = TargetReason.WINDOW_FALLBACK_MONITOR
+ else:
+ reason_when_falling_back = None
+
+ # ---- Monitor scope: cursor, then bar, then primary --------------------
+ chosen: dict | None = None
+ reason = TargetReason.PRIMARY_MONITOR
+
+ if cursor_point is not None:
+ chosen = monitor_for_point(monitors, cursor_point)
+ if chosen is not None:
+ reason = TargetReason.CURSOR_MONITOR
+ else:
+ degradations.append(
+ Degradation(
+ code=DegradationCode.NO_CURSOR,
+ message=(
+ "The mouse position could not be read on this system, so "
+ "the screen showing the Jarvis bar was used instead."
+ ),
+ )
+ )
+
+ if chosen is None and bar_point is not None:
+ chosen = monitor_for_point(monitors, bar_point)
+ if chosen is not None:
+ reason = TargetReason.BAR_MONITOR
+
+ if chosen is None:
+ if cursor_point is None and bar_point is None:
+ degradations.append(
+ Degradation(
+ code=DegradationCode.NO_BAR_POSITION,
+ message=(
+ "Neither the mouse position nor the Jarvis bar position "
+ "was available, so the main screen was used."
+ ),
+ )
+ )
+ chosen = _primary_monitor(monitors, override=main_monitor_override)
+ reason = TargetReason.PRIMARY_MONITOR
+
+ if chosen is None:
+ raise CaptureUnavailable(
+ "No usable monitor could be selected on this machine, so nothing "
+ "was captured."
+ )
+
+ # A window-scoped request that fell back keeps that fact in the reason, so
+ # the receipt says "whole screen" rather than implying the window was shot.
+ if reason_when_falling_back is not None:
+ reason = reason_when_falling_back
+
+ return (
+ CaptureTarget(
+ kind=TargetKind.MONITOR,
+ bbox=_rect_of(chosen),
+ reason=reason,
+ monitor_name=_monitor_name(chosen, monitors),
+ window=facts,
+ window_handle=None,
+ ),
+ tuple(degradations),
+ )
+
+
+__all__ = ["monitor_for_point", "resolve_target"]
diff --git a/jarvis/screen_context/uitext.py b/jarvis/screen_context/uitext.py
new file mode 100644
index 0000000000..f62aa1d8c5
--- /dev/null
+++ b/jarvis/screen_context/uitext.py
@@ -0,0 +1,213 @@
+"""Visible on-screen text — accessibility first, OCR only to fill a gap.
+
+The accessibility tree is the right source and OCR is the fallback, not the
+other way around, for three reasons that all point the same way: the OS already
+knows the text exactly (no transcription errors), it knows the *structure*
+(a button's label is not body text), and it costs single-digit milliseconds
+against OCR's hundreds. A capture path that OCR'd by default would be slower and
+less accurate at the same time.
+
+OCR therefore runs only when all three hold simultaneously:
+
+* the accessibility path produced (near-)nothing,
+* the user enabled it, and
+* a backend is actually installed.
+
+That last condition is why OCR is not a dependency. The base install stays
+torch-free (CLAUDE.md §3), so this module *probes* for a backend and degrades
+with a named reason when there is none — it never pulls one in.
+"""
+from __future__ import annotations
+
+import logging
+from collections.abc import Iterable
+from typing import Any
+
+from jarvis.screen_context.models import Degradation, DegradationCode
+from jarvis.screen_context.ports import Rect
+
+log = logging.getLogger(__name__)
+
+#: Below this many characters, accessibility text counts as "nothing useful"
+#: and OCR (if enabled) may supplement it. A window legitimately can have very
+#: little text; the threshold is low enough not to trigger on those.
+_SPARSE_TEXT_THRESHOLD = 24
+
+#: Roles whose text is chrome, not content — dropped before aggregation so the
+#: budget is spent on what the user is actually looking at.
+_CHROME_ROLES: frozenset[str] = frozenset(
+ {"ScrollBar", "Separator", "Thumb", "TitleBar", "Splitter"}
+)
+
+
+def nodes_in_rect(nodes: Iterable[Any], rect: Rect) -> tuple[Any, ...]:
+ """Nodes whose bounds intersect ``rect``.
+
+ A monitor-scoped capture must not carry text from a window on a *different*
+ monitor: the accessibility tree spans the whole desktop, and handing the
+ model text it cannot see in the image is how "it described something that
+ was not on my screen" happens.
+
+ A node with no bounds is kept. Some backends report zero bounds for
+ container elements that still carry the useful label, and dropping them
+ would lose real text — the image is scoped correctly either way.
+ """
+ left, top, width, height = (int(v) for v in rect)
+ right, bottom = left + width, top + height
+ kept: list[Any] = []
+ for node in nodes:
+ bounds = getattr(node, "bounds", None)
+ if not bounds or len(bounds) != 4 or all(int(v) == 0 for v in bounds):
+ kept.append(node)
+ continue
+ nx, ny, nw, nh = (int(v) for v in bounds)
+ if nx < right and nx + nw > left and ny < bottom and ny + nh > top:
+ kept.append(node)
+ return tuple(kept)
+
+
+def aggregate_text(nodes: Iterable[Any], *, max_chars: int) -> tuple[str, bool]:
+ """Join node labels into one text block. Returns ``(text, truncated)``.
+
+ Password-marked nodes are dropped *here*, at the source, rather than
+ scrubbed later: their value should never enter the string in the first
+ place. Duplicates are collapsed because accessibility trees repeat a label
+ across a control and its wrapper, and paying tokens three times for the same
+ word crowds out text the user actually asked about.
+ """
+ seen: set[str] = set()
+ parts: list[str] = []
+ total = 0
+ truncated = False
+
+ for node in nodes:
+ if bool(getattr(node, "is_password", False)):
+ continue
+ if str(getattr(node, "role", "") or "") in _CHROME_ROLES:
+ continue
+ for raw in (getattr(node, "name", ""), getattr(node, "value", "")):
+ text = " ".join(str(raw or "").split())
+ if not text or text in seen:
+ continue
+ seen.add(text)
+ if total + len(text) + 1 > max_chars:
+ truncated = True
+ return ("\n".join(parts), truncated)
+ parts.append(text)
+ total += len(text) + 1
+
+ return ("\n".join(parts), truncated)
+
+
+async def read_ui_text(
+ reader: Any,
+ *,
+ target_rect: Rect,
+ max_chars: int,
+ window_title_filter: str | None = None,
+) -> tuple[str, str, tuple[Any, ...], tuple[Degradation, ...]]:
+ """Read visible text for ``target_rect``.
+
+ Returns ``(text, source, nodes, degradations)``. ``nodes`` is handed back
+ because the redactor needs the same node list to black out secure fields in
+ the image — reading the tree twice would be both slower and racy (the
+ second read can see a different screen).
+
+ ``source`` is ``"accessibility"``, ``"none"``, and never a lie: a host
+ without an accessibility layer gets ``"none"`` plus a degradation, so no
+ caller can mistake "we could not read" for "there was no text" (AP-30).
+ """
+ degradations: list[Degradation] = []
+
+ observation = await reader.read(window_title_filter=window_title_filter)
+ if observation is None:
+ degradations.append(
+ Degradation(
+ code=DegradationCode.NO_UI_TEXT,
+ message=(
+ "On-screen text could not be read on this system, so only "
+ "the image was used. On Linux this needs an AT-SPI session; "
+ "on macOS it needs the accessibility permission."
+ ),
+ )
+ )
+ return ("", "none", (), tuple(degradations))
+
+ nodes = nodes_in_rect(getattr(observation, "nodes", ()) or (), target_rect)
+ text, truncated = aggregate_text(nodes, max_chars=max_chars)
+ if truncated:
+ degradations.append(
+ Degradation(
+ code=DegradationCode.UI_TEXT_TRUNCATED,
+ message=(
+ f"The screen contained more text than the {max_chars}-character "
+ "limit, so it was shortened."
+ ),
+ )
+ )
+ if not text:
+ return ("", "none", nodes, tuple(degradations))
+ return (text, "accessibility", nodes, tuple(degradations))
+
+
+# --------------------------------------------------------------------------
+# OCR supplement
+# --------------------------------------------------------------------------
+
+
+def text_is_sparse(text: str) -> bool:
+ """Whether the accessibility result is thin enough to warrant OCR."""
+ return len(text.strip()) < _SPARSE_TEXT_THRESHOLD
+
+
+def ocr_supplement(image: Any) -> tuple[str, Degradation | None]:
+ """Best-effort OCR over the captured image.
+
+ Probes for an installed backend rather than depending on one: the base
+ install must stay torch-free and work on a slim container, so an absent
+ backend is a normal, named outcome — not an error and not a silent empty
+ string.
+
+ Returns ``(text, degradation)``; exactly one of them is meaningful.
+ """
+ try:
+ import pytesseract # noqa: PLC0415
+ except ImportError:
+ log.info(
+ "screen_context: OCR is enabled in settings but no OCR engine is "
+ "installed — the capture used the image only. Install one to add "
+ "text recognition for windows without an accessibility layer."
+ )
+ return (
+ "",
+ Degradation(
+ code=DegradationCode.OCR_UNAVAILABLE,
+ message=(
+ "Text recognition is switched on but no OCR engine is "
+ "installed, so only the image was used."
+ ),
+ ),
+ )
+ try:
+ return (str(pytesseract.image_to_string(image) or "").strip(), None)
+ except Exception as exc: # noqa: BLE001 — tesseract binary missing / unreadable
+ log.debug("OCR failed", exc_info=True)
+ return (
+ "",
+ Degradation(
+ code=DegradationCode.OCR_UNAVAILABLE,
+ message=(
+ f"Text recognition could not run ({exc}), so only the image "
+ "was used."
+ ),
+ ),
+ )
+
+
+__all__ = [
+ "aggregate_text",
+ "nodes_in_rect",
+ "ocr_supplement",
+ "read_ui_text",
+ "text_is_sparse",
+]
diff --git a/jarvis/ui/web/screen_context_routes.py b/jarvis/ui/web/screen_context_routes.py
new file mode 100644
index 0000000000..bec0aa617b
--- /dev/null
+++ b/jarvis/ui/web/screen_context_routes.py
@@ -0,0 +1,309 @@
+"""REST API for Screen Context — one-shot, on-request screen look.
+
+Endpoints (mounted by the WebServer in ``_build_app()``):
+
+ GET /api/screen-context/status → capability + settings + held count.
+ POST /api/screen-context/classify → what a given utterance would do.
+ POST /api/screen-context/capture → take ONE capture now.
+ GET /api/screen-context/{id} → metadata for a held capture.
+ POST /api/screen-context/{id}/consume → take the image out (single use).
+ DELETE /api/screen-context → discard every held capture.
+ GET /api/screen-context/settings → the [screen_context] block.
+ PUT /api/screen-context/settings → change one or more keys.
+
+Why REST and not only an internal service: under the CLI-first contract
+(CLAUDE.md §5) a capability that exists only inside the voice path is not
+finished. Mounting this router makes every action a
+``jarvis api screen-context <op>`` command, which is also how the feature is
+verified on a machine with no display — ``status`` answers honestly instead of
+pretending, and ``capture`` returns a named refusal rather than a stack trace.
+
+Two deliberate shapes:
+
+* ``POST /capture`` returns **metadata only**. The image comes from
+ ``/{id}/consume``, and that call removes it. Returning pixels from the
+ capture call would make the single-use contract a suggestion — anyone could
+ re-POST for a fresh copy of the same screen without a fresh trigger.
+* ``POST /classify`` captures nothing. It exists so the settings UI (and a
+ curious user) can see exactly how an utterance would be read, which is the
+ only honest way to explain a three-valued gate.
+"""
+from __future__ import annotations
+
+import base64
+import logging
+from typing import Any
+
+from fastapi import APIRouter, HTTPException, Request
+from pydantic import BaseModel, Field
+
+from jarvis.screen_context.models import VisualIntent
+from jarvis.screen_context.service import (
+ ScreenContextService,
+ settings_from_config,
+)
+
+log = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api/screen-context", tags=["screen-context"])
+
+#: Process-wide service. Built on first use, never at import (AP-26), and
+#: rebuilt whenever settings change so a config edit takes effect without a
+#: restart.
+_service: ScreenContextService | None = None
+
+
+def _get_service(request: Request) -> ScreenContextService:
+ global _service
+ if _service is None:
+ from jarvis.core.config import load_config # noqa: PLC0415
+
+ _service = ScreenContextService(
+ settings=settings_from_config(load_config()),
+ bus=getattr(request.app.state, "bus", None),
+ )
+ return _service
+
+
+def _reset_service() -> None:
+ """Drop the cached service so the next call picks up new settings.
+
+ Also discards anything it still holds: a settings change that tightens the
+ denylist must not leave a capture taken under the old rules in memory.
+ """
+ global _service
+ if _service is not None:
+ _service.discard_all()
+ _service = None
+
+
+class ClassifyRequest(BaseModel):
+ text: str = Field(default="", description="The utterance to classify.")
+ locale: str = Field(
+ default="en",
+ description="Already-resolved output language (BCP-47 base, e.g. 'de').",
+ )
+
+
+class CaptureRequest(BaseModel):
+ text: str = Field(
+ default="",
+ description="User utterance. Empty with force=true for an explicit capture.",
+ )
+ locale: str = Field(default="en", description="Resolved output language.")
+ force: bool = Field(
+ default=True,
+ description=(
+ "Skip intent classification (an explicit API call IS the intent). "
+ "Never skips permissions, the privacy denylist, or redaction."
+ ),
+ )
+
+
+class SettingsPatch(BaseModel):
+ enabled: bool | None = None
+ denylist: list[str] | None = None
+ sensitive_patterns: list[str] | None = None
+ include_default_patterns: bool | None = None
+ max_text_chars: int | None = None
+ ttl_s: float | None = None
+ ocr_enabled: bool | None = None
+
+
+def _context_metadata(context: Any, handle_id: str | None) -> dict[str, Any]:
+ """Everything about a capture EXCEPT its content.
+
+ Used for the capture response and the receipt endpoint. Image bytes and
+ captured text are deliberately absent: this payload ends up in logs and
+ the flight recorder, and screen content must not.
+ """
+ return {
+ "id": handle_id,
+ "receipt": context.describe(),
+ "target": {
+ "kind": str(context.target.kind),
+ "reason": str(context.target.reason),
+ "monitor": context.target.monitor_name,
+ "bbox": list(context.target.bbox),
+ "app": context.target.window.app_name,
+ "window_title": context.target.window.title,
+ },
+ "image": {
+ "mime": context.mime,
+ "width": context.size[0],
+ "height": context.size[1],
+ "bytes": context.byte_size,
+ },
+ "ui_text": {
+ "source": context.ui_text_source,
+ "chars": len(context.ui_text),
+ },
+ "redactions": {
+ "summary": context.redactions.summary(),
+ "image_regions": context.redactions.region_count,
+ "text_matches": context.redactions.text_count,
+ "labels": sorted({h.label for h in context.redactions.hits if h.label}),
+ },
+ "degradations": [
+ {"code": str(d.code), "message": d.message} for d in context.degradations
+ ],
+ "captured_at_ns": context.captured_at_ns,
+ }
+
+
+async def status(request: Request) -> dict[str, Any]:
+ """Capability and live state — answers honestly on a machine with no screen."""
+ service = _get_service(request)
+ from jarvis.screen_context.ports import capture_permission_error # noqa: PLC0415
+
+ monitors = service.displays.monitors()
+ permission_error = capture_permission_error()
+ return {
+ "enabled": service.settings.enabled,
+ "available": bool(monitors) and permission_error is None,
+ "blocked_reason": permission_error,
+ "monitor_count": max(0, len(monitors) - 1) if monitors else 0,
+ "cursor_readable": service.cursor.position() is not None,
+ "held_captures": service.held_count,
+ "ttl_s": service.settings.ttl_s,
+ }
+
+
[email protected]("/classify")
+async def classify(request: Request, body: ClassifyRequest) -> dict[str, Any]:
+ """What would happen for this utterance — without capturing anything."""
+ service = _get_service(request)
+ verdict = service.classify(body.text, locale=body.locale)
+ action = {
+ VisualIntent.NONE: "nothing",
+ VisualIntent.AMBIGUOUS: "ask",
+ VisualIntent.SCREEN: "capture_screen",
+ VisualIntent.WINDOW: "capture_window",
+ }[verdict.intent]
+ payload: dict[str, Any] = {
+ "intent": str(verdict.intent),
+ "action": action,
+ "evidence": list(verdict.evidence),
+ }
+ if verdict.needs_clarification:
+ from jarvis.screen_context.intent import clarifying_question # noqa: PLC0415
+
+ payload["question"] = clarifying_question(body.locale)
+ return payload
+
+
[email protected]("/capture")
+async def capture(request: Request, body: CaptureRequest) -> dict[str, Any]:
+ """Take exactly one capture. Returns metadata; the image is fetched once."""
+ service = _get_service(request)
+ outcome = await service.capture_for_turn(
+ body.text, locale=body.locale, force=body.force
+ )
+
+ if outcome.status == "captured" and outcome.context is not None:
+ return {"status": "captured", **_context_metadata(outcome.context, outcome.handle_id)}
+ if outcome.status == "clarify":
+ return {
+ "status": "clarify",
+ "question": outcome.question,
+ "evidence": list(outcome.verdict.evidence),
+ }
+ if outcome.status == "not_requested":
+ return {"status": "not_requested", "intent": str(outcome.verdict.intent)}
+ return {"status": "refused", "reason": outcome.message}
+
+
[email protected]("/settings")
+async def get_settings(request: Request) -> dict[str, Any]:
+ from jarvis.core.config import load_config # noqa: PLC0415
+
+ block = load_config().screen_context
+ return {
+ "enabled": block.enabled,
+ "denylist": list(block.denylist),
+ "sensitive_patterns": list(block.sensitive_patterns),
+ "include_default_patterns": block.include_default_patterns,
+ "max_text_chars": block.max_text_chars,
+ "ttl_s": block.ttl_s,
+ "ocr_enabled": block.ocr_enabled,
+ }
+
+
[email protected]("/settings")
+async def put_settings(request: Request, patch: SettingsPatch) -> dict[str, Any]:
+ """Change one or more keys, then rebuild the service so it takes effect."""
+ import asyncio # noqa: PLC0415
+
+ from jarvis.core.config import ScreenContextConfig # noqa: PLC0415
+ from jarvis.core.config_writer import set_screen_context_setting # noqa: PLC0415
+
+ changes = patch.model_dump(exclude_none=True)
+ if not changes:
+ raise HTTPException(status_code=400, detail="No settings were provided.")
+
+ # Validate against the model BEFORE touching the file, so a rejected value
+ # cannot leave half the patch written.
+ try:
+ ScreenContextConfig(**changes)
+ except Exception as exc: # noqa: BLE001 — pydantic raises its own type
+ raise HTTPException(
+ status_code=400, detail=f"Invalid setting: {exc}"
+ ) from exc
+
+ def _write() -> None:
+ for key, value in changes.items():
+ set_screen_context_setting(key, value)
+
+ try:
+ await asyncio.to_thread(_write)
+ except Exception as exc: # noqa: BLE001 — surface the write failure honestly
+ log.error("screen_context: settings write failed", exc_info=True)
+ raise HTTPException(
+ status_code=500, detail=f"Could not save the settings: {exc}"
+ ) from exc
+
+ _reset_service()
+ return {"ok": True, "changed": sorted(changes)}
+
+
[email protected]("/{capture_id}")
+async def get_capture(request: Request, capture_id: str) -> dict[str, Any]:
+ """Metadata for a held capture WITHOUT consuming it (the receipt)."""
+ service = _get_service(request)
+ context = service.peek(capture_id)
+ if context is None:
+ raise HTTPException(
+ status_code=404,
+ detail=(
+ "That capture is gone — it was either already used or it "
+ "expired. Captures are single-use and short-lived by design."
+ ),
+ )
+ return _context_metadata(context, capture_id)
+
+
[email protected]("/{capture_id}/consume")
+async def consume_capture(request: Request, capture_id: str) -> dict[str, Any]:
+ """Take the image and text out. The capture is removed by this call."""
+ service = _get_service(request)
+ context = service.consume(capture_id)
+ if context is None:
+ raise HTTPException(
+ status_code=404,
+ detail=(
+ "That capture is gone — it was either already used or it "
+ "expired. Captures are single-use and short-lived by design."
+ ),
+ )
+ payload = _context_metadata(context, capture_id)
+ payload["image_base64"] = base64.b64encode(context.image).decode("ascii")
+ payload["text"] = context.ui_text
+ return payload
+
+
[email protected]("", openapi_extra={"x-jarvis-dangerous": True})
+async def discard_all(request: Request) -> dict[str, Any]:
+ """Drop every held capture right now — the panic button."""
+ service = _get_service(request)
+ return {"ok": True, "discarded": service.discard_all()}
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 3a2acc365a..3e603d7d0f 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -343,6 +343,7 @@ class WebServer:
from .profile_routes import router as profile_router
from .provider_routes import router as provider_router
from .review_routes import router as review_router
+ from .screen_context_routes import router as screen_context_router
from .self_mod_routes import router as self_mod_router
from .sessions_routes import router as sessions_router
from .settings_routes import router as settings_router
@@ -457,6 +458,10 @@ class WebServer:
app.include_router(federation_proxy_router)
# Phase 8.5 — review-pipeline read-only UI (Plan §6.5).
app.include_router(review_router)
+ # One-shot, intent-driven screen look. Answers honestly (not 503) on a
+ # machine with no display, so `jarvis api screen-context status` is a
+ # valid capability probe everywhere.
+ app.include_router(screen_context_router)
# Voice-session transcription view (sidebar -> "Transcription").
# Returns 503 as long as app.state.session_store isn't set.
app.include_router(sessions_router)
diff --git a/tests/unit/screen_context/test_intent.py b/tests/unit/screen_context/test_intent.py
new file mode 100644
index 0000000000..a3edc3e9ab
--- /dev/null
+++ b/tests/unit/screen_context/test_intent.py
@@ -0,0 +1,157 @@
+"""Visual-intent classification: the three-valued verdict.
+
+The cases below are the behaviour contract, not a sample. Two of them are
+regressions waiting to happen and are pinned deliberately:
+
+* a look-verb inside an idiom ("looks like", "mal sehen", "a ver si") must not
+ capture — this is the failure mode ``jarvis/brain/cu_gate.py`` hit in
+ production with product names, and the same masking approach is used here;
+* a plain content question must produce neither a capture nor a question,
+ because a feature that interrupts to ask "shall I look?" on every third turn
+ is worse than one that never looks at all.
+"""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.screen_context.intent import (
+ SUPPORTED_CLARIFY_LOCALES,
+ clarifying_question,
+ classify,
+)
+from jarvis.screen_context.models import VisualIntent
+
+
+ "utterance",
+ [
+ # -- English
+ "can you see this?",
+ "take a look at this",
+ "look at the error",
+ "what does it say?",
+ "read this out to me",
+ "what's on my screen?",
+ "check this out",
+ # -- German (the two phrasings the feature is specified around)
+ "Kannst du mal sehen?",
+ "Schau dir das an",
+ "schau mal",
+ "guck dir das mal an",
+ "siehst du das?",
+ "was steht da?",
+ "lies mir das vor",
+ "auf dem Bildschirm ist eine Fehlermeldung", # i18n-allow: DE input
+ # -- Spanish
+ "mira esto",
+ "puedes ver esto?",
+ "que dice ahi?",
+ "echa un vistazo",
+ ],
+)
+def test_unambiguous_requests_capture(utterance: str) -> None:
+ verdict = classify(utterance)
+ assert verdict.wants_capture, f"{utterance!r} -> {verdict.intent}"
+ assert verdict.evidence, "an unambiguous verdict must record its evidence"
+
+
+ "utterance",
+ [
+ "look at this window",
+ "what does it say in this dialog?",
+ "can you see this tab?",
+ "schau dir dieses Fenster an",
+ "was steht da in diesem Dialog?",
+ "mira esta ventana",
+ ],
+)
+def test_window_scope_is_detected(utterance: str) -> None:
+ assert classify(utterance).intent is VisualIntent.WINDOW
+
+
+ "utterance",
+ [
+ "what is that?",
+ "why is this?",
+ "can you check that?",
+ "was ist das?", # i18n-allow: DE input
+ "warum ist das?", # i18n-allow: DE input
+ "kannst du das mal prüfen?", # i18n-allow: DE input
+ "que es esto?",
+ "puedes revisar?",
+ ],
+)
+def test_weak_signals_ask_instead_of_capturing(utterance: str) -> None:
+ verdict = classify(utterance)
+ assert verdict.intent is VisualIntent.AMBIGUOUS, f"{utterance!r}"
+ assert verdict.needs_clarification
+ assert not verdict.wants_capture, "an ambiguous turn must NEVER capture"
+
+
+ "utterance",
+ [
+ # Plain content questions — the overwhelmingly common case.
+ "what did we just talk about?",
+ "was haben wir besprochen?",
+ "explain recursion to me again",
+ "wie spät ist es?", # i18n-allow: DE input
+ "remind me to call the dentist tomorrow",
+ # Idioms that merely CONTAIN a look/see verb.
+ "that looks like a good plan",
+ "let's see what happens",
+ "I see, that makes sense",
+ "can you look into the billing issue?",
+ "look for a cheaper flight",
+ "mal sehen was daraus wird", # i18n-allow: DE input
+ "das sieht gut aus", # i18n-allow: DE input
+ "schauen wir mal",
+ "ya veo, gracias",
+ "vamos a ver que pasa",
+ ],
+)
+def test_non_visual_turns_are_left_alone(utterance: str) -> None:
+ verdict = classify(utterance)
+ assert verdict.intent is VisualIntent.NONE, f"{utterance!r} -> {verdict.intent}"
+
+
+def test_idiom_masking_does_not_veto_a_real_request() -> None:
+ """An idiom and a real request in one sentence must still capture.
+
+ Masking rather than vetoing is exactly what makes this work; a veto would
+ drop the request because the sentence also contains "looks like".
+ """
+ verdict = classify("that looks like an error — can you see this?")
+ assert verdict.wants_capture
+
+
+def test_empty_turn_is_never_a_request() -> None:
+ """Non-conversational callers reach the service without an utterance."""
+ assert classify("").intent is VisualIntent.NONE
+ assert classify(" ").intent is VisualIntent.NONE
+
+
+def test_umlauts_and_accents_match_without_diacritics() -> None:
+ umlaut = classify("kannst du das mal prüfen?") # i18n-allow: DE input
+ assert umlaut.intent is VisualIntent.AMBIGUOUS
+ assert classify("mira esta pestaña").intent is VisualIntent.WINDOW
+
+
[email protected]("locale", sorted(SUPPORTED_CLARIFY_LOCALES))
+def test_every_supported_locale_has_a_clarifying_question(locale: str) -> None:
+ """§1.3: a phrase table carries ALL supported languages, never de/en only."""
+ question = clarifying_question(locale)
+ assert question and question.strip().endswith("?")
+
+
+def test_clarifying_question_falls_back_for_an_unknown_locale() -> None:
+ """A locale with no entry gets the default, never an empty string."""
+ assert clarifying_question("fr") == clarifying_question("en")
+ assert clarifying_question("") == clarifying_question("en")
+
+
+def test_clarifying_question_accepts_a_full_bcp47_tag() -> None:
+ assert clarifying_question("de-DE") == clarifying_question("de")
+ assert clarifying_question("es_ES") == clarifying_question("es")
diff --git a/tests/unit/screen_context/test_redaction.py b/tests/unit/screen_context/test_redaction.py
new file mode 100644
index 0000000000..4e981b3939
--- /dev/null
+++ b/tests/unit/screen_context/test_redaction.py
@@ -0,0 +1,249 @@
+"""Privacy filtering: block, black out, scrub — in that order.
+
+The image-region cases carry the most weight. A misplaced black box does not
+fail loudly; it leaves the secret visible while the report claims it was
+removed, which is the worst possible outcome for a privacy feature. The HiDPI
+scaling case exists because that is exactly how it would happen in practice.
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from jarvis.screen_context.models import RedactionRule, WindowFacts
+from jarvis.screen_context.redaction import (
+ blocked_by_denylist,
+ build_patterns,
+ merge_reports,
+ regions_to_redact,
+ scrub_text,
+)
+
+
+@dataclass
+class FakeNode:
+ """Shaped like ``jarvis.core.protocols.UIANode`` — only what we read."""
+
+ name: str = ""
+ value: str = ""
+ bounds: tuple[int, int, int, int] = (0, 0, 0, 0)
+ is_password: bool = False
+ role: str = "Text"
+
+
+# --------------------------------------------------------------------------
+# Denylist
+# --------------------------------------------------------------------------
+
+
+def test_denylist_matches_app_name_case_insensitively() -> None:
+ facts = WindowFacts(app_name="1Password.exe", title="Vault")
+ assert blocked_by_denylist(facts, ["1password"]) == "1password"
+
+
+def test_denylist_matches_the_window_title_too() -> None:
+ """Browsers expose the sensitive part in the title, not the app name."""
+ facts = WindowFacts(app_name="chrome.exe", title="Online Banking — Private")
+ assert blocked_by_denylist(facts, ["online banking"]) == "online banking"
+
+
+def test_denylist_survives_a_version_bump() -> None:
+ """Substring, not exact: an exact list stops protecting after an update."""
+ assert blocked_by_denylist(WindowFacts(app_name="1Password 8"), ["1Password"])
+
+
+def test_unknown_window_is_not_blocked() -> None:
+ """No facts is not a match — the capture is governed by the other layers."""
+ assert blocked_by_denylist(WindowFacts(), ["1password"]) is None
+
+
+def test_empty_denylist_entries_are_ignored() -> None:
+ """A blank line in the config must not block every window."""
+ assert blocked_by_denylist(WindowFacts(app_name="editor"), ["", " "]) is None
+
+
+# --------------------------------------------------------------------------
+# Image regions
+# --------------------------------------------------------------------------
+
+
+def test_password_field_is_always_a_region() -> None:
+ nodes = [FakeNode(name="Password", bounds=(100, 200, 300, 40), is_password=True)]
+ regions = regions_to_redact(
+ nodes, target_bbox=(0, 0, 1920, 1080), patterns=build_patterns()
+ )
+ assert len(regions) == 1
+ rect, rule, _label = regions[0]
+ assert rule is RedactionRule.PASSWORD_FIELD
+ assert rect == (100, 200, 300, 40)
+
+
+def test_node_text_matching_a_pattern_is_blacked_out() -> None:
+ nodes = [FakeNode(value="4111 1111 1111 1111", bounds=(10, 20, 200, 30))]
+ regions = regions_to_redact(
+ nodes, target_bbox=(0, 0, 1920, 1080), patterns=build_patterns()
+ )
+ assert [r[2] for r in regions] == ["card"]
+
+
+def test_regions_are_translated_into_image_local_coordinates() -> None:
+ """A capture of the LEFT monitor starts at negative virtual X.
+
+ Forgetting the translation puts every box off-image — silently, because
+ Pillow happily draws outside the canvas.
+ """
+ nodes = [FakeNode(bounds=(-1800, 100, 200, 50), is_password=True)]
+ regions = regions_to_redact(
+ nodes, target_bbox=(-1920, 0, 1920, 1080), patterns=build_patterns()
+ )
+ assert regions[0][0] == (120, 100, 200, 50)
+
+
+def test_regions_scale_to_backing_pixels() -> None:
+ """macOS: geometry in points, capture in backing pixels (2x on Retina).
+
+ Without the scale the box covers a quarter of the field and the secret
+ stays visible next to it.
+ """
+ nodes = [FakeNode(bounds=(100, 100, 200, 40), is_password=True)]
+ regions = regions_to_redact(
+ nodes, target_bbox=(0, 0, 1440, 900), patterns=build_patterns(), scale=2.0
+ )
+ assert regions[0][0] == (200, 200, 400, 80)
+
+
+def test_node_outside_the_captured_area_is_dropped() -> None:
+ """A field on the OTHER monitor is not in this picture."""
+ nodes = [FakeNode(bounds=(3000, 100, 200, 40), is_password=True)]
+ regions = regions_to_redact(
+ nodes, target_bbox=(0, 0, 1920, 1080), patterns=build_patterns()
+ )
+ assert regions == ()
+
+
+def test_node_straddling_the_edge_is_clipped_not_dropped() -> None:
+ """Half a password field is still half a password field."""
+ nodes = [FakeNode(bounds=(1800, 100, 400, 40), is_password=True)]
+ regions = regions_to_redact(
+ nodes, target_bbox=(0, 0, 1920, 1080), patterns=build_patterns()
+ )
+ assert regions[0][0] == (1800, 100, 120, 40)
+
+
+def test_ordinary_nodes_are_not_redacted() -> None:
+ nodes = [FakeNode(name="Save", bounds=(10, 10, 60, 20))]
+ assert regions_to_redact(
+ nodes, target_bbox=(0, 0, 1920, 1080), patterns=build_patterns()
+ ) == ()
+
+
+# --------------------------------------------------------------------------
+# Text
+# --------------------------------------------------------------------------
+
+
+def test_sensitive_text_becomes_a_typed_placeholder() -> None:
+ """A placeholder, not a hole: a model fills holes, it reads placeholders."""
+ scrubbed, hits = scrub_text("pay with 4111 1111 1111 1111 now", build_patterns())
+ assert "4111" not in scrubbed
+ assert "[redacted:card]" in scrubbed
+ assert hits[0].label == "card"
+ assert hits[0].region is None
+
+
+def test_multiple_pattern_families_are_all_applied() -> None:
+ text = "Authorization: Bearer abc123xyz and key sk-abcdefghijklmnopqrst"
+ scrubbed, hits = scrub_text(text, build_patterns())
+ assert "abc123xyz" not in scrubbed
+ assert "sk-abcdefghijklmnopqrst" not in scrubbed
+ assert len(hits) >= 2
+
+
+def test_private_key_header_is_caught() -> None:
+ scrubbed, _ = scrub_text("-----BEGIN OPENSSH PRIVATE KEY-----", build_patterns())
+ assert "PRIVATE KEY" not in scrubbed
+
+
+def test_ordinary_text_is_untouched() -> None:
+ text = "Build failed: 3 errors in main.py at line 42"
+ scrubbed, hits = scrub_text(text, build_patterns())
+ assert scrubbed == text
+ assert hits == ()
+
+
+def test_custom_labelled_pattern_reaches_the_report() -> None:
+ patterns = build_patterns(["employee_id:EMP-\\d{5}"])
+ scrubbed, hits = scrub_text("ticket for EMP-12345", patterns)
+ assert "[redacted:employee_id]" in scrubbed
+ assert hits[0].label == "employee_id"
+
+
+def test_invalid_custom_pattern_is_skipped_not_fatal() -> None:
+ """A bad regex must not brick capture — but it must not be silent either.
+
+ (The WARNING log is the other half of this contract; see redaction._compile.)
+ """
+ patterns = build_patterns(["broken:([unclosed"])
+ scrubbed, _ = scrub_text("4111 1111 1111 1111", patterns)
+ assert "[redacted:card]" in scrubbed, "defaults must still apply"
+
+
+def test_defaults_can_be_replaced_entirely() -> None:
+ patterns = build_patterns(["only:SECRET"], include_defaults=False)
+ scrubbed, _ = scrub_text("4111 1111 1111 1111 SECRET", patterns)
+ assert "4111" in scrubbed
+ assert "[redacted:only]" in scrubbed
+
+
+# --------------------------------------------------------------------------
+# Report
+# --------------------------------------------------------------------------
+
+
+def test_report_summary_distinguishes_image_from_text() -> None:
+ _, text_hits = scrub_text("4111 1111 1111 1111", build_patterns())
+ regions = regions_to_redact(
+ [FakeNode(bounds=(0, 0, 10, 10), is_password=True)],
+ target_bbox=(0, 0, 100, 100),
+ patterns=build_patterns(),
+ )
+ from PIL import Image
+
+ from jarvis.screen_context.redaction import apply_image_redactions
+
+ _, region_hits = apply_image_redactions(
+ Image.new("RGB", (100, 100), (255, 255, 255)), regions
+ )
+ report = merge_reports(region_hits, text_hits)
+ assert report.region_count == 1
+ assert report.text_count == 1
+ summary = report.summary()
+ assert "image region" in summary and "text match" in summary
+
+
+def test_redaction_actually_blackens_the_pixels() -> None:
+ """The promise is pixels, not bookkeeping.
+
+ A report that says "redacted" over an unchanged image is the failure mode
+ that matters here, so this asserts on the canvas itself.
+ """
+ from PIL import Image
+
+ from jarvis.screen_context.redaction import apply_image_redactions
+
+ image = Image.new("RGB", (100, 100), (255, 255, 255))
+ image, hits = apply_image_redactions(
+ image, (((10, 10, 20, 20), RedactionRule.PASSWORD_FIELD, "password_field"),)
+ )
+ assert image.getpixel((15, 15)) == (0, 0, 0), "the region must be opaque black"
+ assert image.getpixel((90, 90)) == (255, 255, 255), "the rest must be untouched"
+ assert hits[0].region == (10, 10, 20, 20)
+
+
+def test_apply_image_redactions_is_a_noop_without_regions() -> None:
+ """No regions must not touch a drawing backend at all."""
+ from jarvis.screen_context.redaction import apply_image_redactions
+
+ image = object()
+ result, hits = apply_image_redactions(image, ())
+ assert result is image
+ assert hits == ()
diff --git a/tests/unit/screen_context/test_service.py b/tests/unit/screen_context/test_service.py
new file mode 100644
index 0000000000..3ee92967d5
--- /dev/null
+++ b/tests/unit/screen_context/test_service.py
@@ -0,0 +1,549 @@
+"""End-to-end service behaviour, with fakes — no display, no permissions.
+
+This file is where the feature's promises are actually pinned:
+
+* **one** capture per trigger, never two, never a loop;
+* an ambiguous turn asks and captures nothing;
+* a denylisted window is never captured *at all* (not captured-then-filtered);
+* a stored capture is consumable once, then it is gone.
+
+Fakes rather than mocks, per the repo convention (``tests/fakes/``): each one
+records what it was asked for, so "the cursor was read exactly once" is an
+assertion about behaviour rather than about call plumbing.
+"""
+from __future__ import annotations
+
+from jarvis.screen_context.models import (
+ DegradationCode,
+ RedactionRule,
+ TargetKind,
+ TargetReason,
+ WindowFacts,
+)
+from jarvis.screen_context.ports import CaptureUnavailable
+from jarvis.screen_context.service import (
+ ScreenContextService,
+ ScreenContextSettings,
+ settings_from_config,
+)
+
+MONITORS = [
+ {"left": -1920, "top": 0, "width": 3840, "height": 1080, "name": "virtual"},
+ {"left": -1920, "top": 0, "width": 1920, "height": 1080, "name": "left"},
+ {"left": 0, "top": 0, "width": 1920, "height": 1080, "name": "primary"},
+]
+
+
+class FakeCursor:
+ name = "fake-cursor"
+
+ def __init__(self, point=(-500, 400)) -> None:
+ self._point = point
+ self.reads = 0
+
+ def position(self):
+ self.reads += 1
+ return self._point
+
+
+class FakeBar:
+ name = "fake-bar"
+
+ def __init__(self, point=(900, 1000)) -> None:
+ self._point = point
+ self.reads = 0
+
+ def position(self):
+ self.reads += 1
+ return self._point
+
+
+class FakeDisplays:
+ name = "fake-displays"
+
+ def __init__(self, monitors=None) -> None:
+ self._monitors = MONITORS if monitors is None else monitors
+
+ def monitors(self):
+ return list(self._monitors)
+
+
+class FakeWindowProbe:
+ name = "fake-window"
+
+ def __init__(self, facts: WindowFacts | None = None, handle: int | None = 7) -> None:
+ self._facts = (
+ facts
+ if facts is not None
+ else WindowFacts(
+ app_name="editor", title="notes.md", pid=42, frame_rect=(10, 10, 800, 600)
+ )
+ )
+ self._handle = handle
+
+ def foreground(self):
+ return self._facts
+
+ def foreground_handle(self):
+ return self._handle
+
+
+class FakeCapturer:
+ """Returns a solid-white frame and counts every grab."""
+
+ name = "fake-capture"
+
+ def __init__(self, *, fail: Exception | None = None, scale: int = 1) -> None:
+ self.grabs: list[tuple] = []
+ self._fail = fail
+ self._scale = scale
+
+ def grab(self, bbox, *, window_handle=None):
+ self.grabs.append((tuple(bbox), window_handle))
+ if self._fail is not None:
+ raise self._fail
+ width = int(bbox[2]) * self._scale
+ height = int(bbox[3]) * self._scale
+ # Keep the fake frame small enough to encode quickly.
+ width, height = min(width, 320), min(height, 240)
+ return ((width, height), b"\xff" * (width * height * 3))
+
+
+class FakeNode:
+ def __init__(self, name="", value="", bounds=(0, 0, 0, 0), is_password=False):
+ self.name = name
+ self.value = value
+ self.bounds = bounds
+ self.is_password = is_password
+ self.role = "Text"
+
+
+class FakeObservation:
+ def __init__(self, nodes=()) -> None:
+ self.nodes = tuple(nodes)
+
+
+class FakeTextReader:
+ name = "fake-text"
+
+ def __init__(self, observation=None) -> None:
+ self._observation = observation
+ self.reads = 0
+
+ async def read(self, *, window_title_filter=None):
+ self.reads += 1
+ return self._observation
+
+
+class RecordingBus:
+ def __init__(self) -> None:
+ self.events: list = []
+
+ async def publish(self, event) -> None:
+ self.events.append(event)
+
+
+def make_service(**overrides) -> ScreenContextService:
+ kwargs = {
+ "settings": ScreenContextSettings(),
+ "cursor": FakeCursor(),
+ "bar": FakeBar(),
+ "displays": FakeDisplays(),
+ "window_probe": FakeWindowProbe(),
+ "capturer": FakeCapturer(),
+ "ui_text_reader": FakeTextReader(FakeObservation()),
+ "permission_probe": lambda: None,
+ }
+ kwargs.update(overrides)
+ return ScreenContextService(**kwargs)
+
+
+# --------------------------------------------------------------------------
+# Intent routing
+# --------------------------------------------------------------------------
+
+
+async def test_a_plain_turn_captures_nothing() -> None:
+ capturer = FakeCapturer()
+ service = make_service(capturer=capturer)
+
+ outcome = await service.capture_for_turn("what did we talk about?", locale="en")
+
+ assert outcome.status == "not_requested"
+ assert capturer.grabs == [], "a normal turn must never touch the screen"
+
+
+async def test_an_ambiguous_turn_asks_and_does_not_capture() -> None:
+ capturer = FakeCapturer()
+ service = make_service(capturer=capturer)
+
+ outcome = await service.capture_for_turn("was ist das?", locale="de") # i18n-allow: DE input
+
+ assert outcome.status == "clarify"
+ assert outcome.question and outcome.question.endswith("?")
+ assert capturer.grabs == [], "ambiguity must never resolve into a capture"
+
+
+async def test_the_clarifying_question_uses_the_resolved_locale() -> None:
+ """The turn's language is passed in, never re-derived here (§1.3)."""
+ service = make_service()
+ german = await service.capture_for_turn("what is that?", locale="de")
+ spanish = await service.capture_for_turn("what is that?", locale="es")
+ assert german.question != spanish.question
+
+
+async def test_an_explicit_request_captures_once() -> None:
+ capturer = FakeCapturer()
+ service = make_service(capturer=capturer)
+
+ outcome = await service.capture_for_turn("schau dir das an", locale="de")
+
+ assert outcome.status == "captured"
+ assert len(capturer.grabs) == 1, "exactly one capture per trigger"
+ assert outcome.context is not None
+ assert outcome.context.image, "a captured context must carry image bytes"
+ assert outcome.context.mime == "image/jpeg"
+
+
+async def test_capture_follows_the_cursor_monitor() -> None:
+ capturer = FakeCapturer()
+ service = make_service(cursor=FakeCursor((-500, 400)), capturer=capturer)
+
+ outcome = await service.capture_for_turn("can you see this?", locale="en")
+
+ assert capturer.grabs[0][0] == (-1920, 0, 1920, 1080)
+ assert outcome.context.target.reason is TargetReason.CURSOR_MONITOR
+
+
+async def test_the_cursor_is_sampled_exactly_once() -> None:
+ """Re-reading it later would let a mouse move change which screen is shot."""
+ cursor = FakeCursor()
+ service = make_service(cursor=cursor)
+
+ await service.capture_for_turn("look at this", locale="en")
+
+ assert cursor.reads == 1
+
+
+async def test_window_scoped_request_captures_the_window() -> None:
+ capturer = FakeCapturer()
+ service = make_service(capturer=capturer)
+
+ outcome = await service.capture_for_turn("look at this window", locale="en")
+
+ assert outcome.context.target.kind is TargetKind.WINDOW
+ assert capturer.grabs[0] == ((10, 10, 800, 600), 7)
+
+
+# --------------------------------------------------------------------------
+# Refusals — the paths where no pixels may exist
+# --------------------------------------------------------------------------
+
+
+async def test_denylisted_window_is_never_captured_at_all() -> None:
+ """Not captured and filtered — not captured. The buffer must not exist."""
+ capturer = FakeCapturer()
+ service = make_service(
+ settings=ScreenContextSettings(denylist=("1password",)),
+ window_probe=FakeWindowProbe(
+ WindowFacts(app_name="1Password.exe", title="Vault", frame_rect=(0, 0, 800, 600))
+ ),
+ capturer=capturer,
+ )
+
+ outcome = await service.capture_for_turn("schau dir das an", locale="de")
+
+ assert outcome.status == "refused"
+ assert capturer.grabs == [], "a blocked app must never reach the capturer"
+ assert "1password" in (outcome.message or "").lower()
+
+
+async def test_missing_permission_refuses_before_capturing() -> None:
+ capturer = FakeCapturer()
+ service = make_service(
+ capturer=capturer,
+ permission_probe=lambda: "Screen recording permission is missing.",
+ )
+
+ outcome = await service.capture_for_turn("look at this", locale="en")
+
+ assert outcome.status == "refused"
+ assert capturer.grabs == []
+ assert "permission" in (outcome.message or "").lower()
+
+
+async def test_disabled_feature_refuses_honestly() -> None:
+ """Switched off must say so, not silently behave like 'no intent'."""
+ service = make_service(settings=ScreenContextSettings(enabled=False))
+ outcome = await service.capture_for_turn("look at this", locale="en")
+ assert outcome.status == "refused"
+ assert "off" in (outcome.message or "").lower()
+
+
+async def test_headless_host_refuses_with_an_explanation() -> None:
+ service = make_service(displays=FakeDisplays([]))
+ outcome = await service.capture_for_turn("look at this", locale="en")
+ assert outcome.status == "refused"
+ assert outcome.message
+
+
+async def test_capture_failure_is_reported_not_raised() -> None:
+ service = make_service(
+ capturer=FakeCapturer(fail=CaptureUnavailable("The display is asleep."))
+ )
+ outcome = await service.capture_for_turn("look at this", locale="en")
+ assert outcome.status == "refused"
+ assert "asleep" in (outcome.message or "")
+
+
+async def test_an_unexpected_port_bug_does_not_kill_the_turn() -> None:
+ service = make_service(capturer=FakeCapturer(fail=ValueError("boom")))
+ outcome = await service.capture_for_turn("look at this", locale="en")
+ assert outcome.status == "refused"
+
+
+# --------------------------------------------------------------------------
+# Redaction on the real path
+# --------------------------------------------------------------------------
+
+
+async def test_password_field_is_redacted_in_the_delivered_context() -> None:
+ reader = FakeTextReader(
+ FakeObservation([FakeNode(name="Password", bounds=(-1900, 100, 200, 40), is_password=True)])
+ )
+ service = make_service(ui_text_reader=reader)
+
+ outcome = await service.capture_for_turn("look at this", locale="en")
+
+ hits = outcome.context.redactions.hits
+ assert any(h.rule is RedactionRule.PASSWORD_FIELD for h in hits)
+ assert outcome.context.redactions.region_count == 1
+
+
+async def test_password_node_text_never_enters_the_ui_text() -> None:
+ reader = FakeTextReader(
+ FakeObservation(
+ [
+ FakeNode(
+ name="Password",
+ value="hunter2",
+ bounds=(-1900, 100, 200, 40),
+ is_password=True,
+ ),
+ FakeNode(name="Sign in", bounds=(-1900, 200, 100, 30)),
+ ]
+ )
+ )
+ service = make_service(ui_text_reader=reader)
+
+ outcome = await service.capture_for_turn("look at this", locale="en")
+
+ assert "hunter2" not in outcome.context.ui_text
+ assert "Sign in" in outcome.context.ui_text
+
+
+async def test_sensitive_text_is_scrubbed_from_the_context() -> None:
+ reader = FakeTextReader(
+ FakeObservation([FakeNode(value="4111 1111 1111 1111", bounds=(-1900, 10, 300, 30))])
+ )
+ service = make_service(ui_text_reader=reader)
+
+ outcome = await service.capture_for_turn("look at this", locale="en")
+
+ assert "4111" not in outcome.context.ui_text
+
+
+async def test_text_from_another_monitor_is_not_included() -> None:
+ """The tree spans the desktop; the picture does not."""
+ reader = FakeTextReader(
+ FakeObservation([FakeNode(name="on the other screen", bounds=(500, 100, 200, 40))])
+ )
+ service = make_service(cursor=FakeCursor((-500, 400)), ui_text_reader=reader)
+
+ outcome = await service.capture_for_turn("look at this", locale="en")
+
+ assert "other screen" not in outcome.context.ui_text
+
+
+async def test_absent_accessibility_layer_is_reported_not_faked() -> None:
+ """"We could not read" must never look like "there was no text" (AP-30)."""
+ service = make_service(ui_text_reader=FakeTextReader(None))
+
+ outcome = await service.capture_for_turn("look at this", locale="en")
+
+ assert outcome.context.ui_text_source == "none"
+ assert DegradationCode.NO_UI_TEXT in {d.code for d in outcome.context.degradations}
+
+
+# --------------------------------------------------------------------------
+# Retention
+# --------------------------------------------------------------------------
+
+
+async def test_a_capture_is_consumable_exactly_once() -> None:
+ service = make_service()
+ outcome = await service.capture_for_turn("look at this", locale="en")
+
+ assert service.consume(outcome.handle_id) is not None
+ assert service.consume(outcome.handle_id) is None, "handles are single-use"
+
+
+async def test_an_unconsumed_capture_expires() -> None:
+ now = [1_000_000_000]
+ service = make_service(
+ settings=ScreenContextSettings(ttl_s=60.0), clock=lambda: now[0]
+ )
+ outcome = await service.capture_for_turn("look at this", locale="en")
+ assert service.peek(outcome.handle_id) is not None
+
+ now[0] += 61 * 1_000_000_000
+
+ assert service.peek(outcome.handle_id) is None
+ assert service.held_count == 0
+
+
+async def test_discard_all_drops_everything_immediately() -> None:
+ service = make_service()
+ await service.capture_for_turn("look at this", locale="en")
+ await service.capture_for_turn("look at this", locale="en")
+
+ assert service.discard_all() == 2
+ assert service.held_count == 0
+
+
+async def test_nothing_is_written_to_disk(tmp_path, monkeypatch) -> None:
+ """The context carries bytes, never a path — a path implies a file."""
+ monkeypatch.chdir(tmp_path)
+ service = make_service()
+
+ outcome = await service.capture_for_turn("look at this", locale="en")
+
+ assert not any(tmp_path.rglob("*.png")), "no image file may be written"
+ assert not any(tmp_path.rglob("*.jpg"))
+ assert not hasattr(outcome.context, "screenshot_path")
+
+
+# --------------------------------------------------------------------------
+# Bus / indicator
+# --------------------------------------------------------------------------
+
+
+async def test_the_capture_is_announced_before_the_shutter() -> None:
+ """Announcing afterwards leaves a window with no visible sign."""
+ bus = RecordingBus()
+ capturer = FakeCapturer()
+ service = make_service(bus=bus, capturer=capturer)
+
+ await service.capture_for_turn("look at this", locale="en")
+
+ names = [type(e).__name__ for e in bus.events]
+ assert names == ["ScreenCaptureAnnounced", "ScreenCaptureCompleted"]
+
+
+async def test_no_bus_means_a_reported_limitation_not_a_silent_capture() -> None:
+ service = make_service(bus=None)
+ outcome = await service.capture_for_turn("look at this", locale="en")
+ assert DegradationCode.INDICATOR_UNAVAILABLE in {
+ d.code for d in outcome.context.degradations
+ }
+
+
+async def test_the_receipt_event_carries_no_content() -> None:
+ """Metadata reaches the flight recorder; pixels and text never do."""
+ bus = RecordingBus()
+ reader = FakeTextReader(
+ FakeObservation([FakeNode(name="secret business plan", bounds=(-1900, 10, 200, 30))])
+ )
+ service = make_service(bus=bus, ui_text_reader=reader)
+
+ await service.capture_for_turn("look at this", locale="en")
+
+ # The events are slotted dataclasses, so read the declared fields rather
+ # than a __dict__ that does not exist.
+ import dataclasses
+
+ completed = bus.events[-1]
+ payload = " ".join(
+ str(getattr(completed, f.name)) for f in dataclasses.fields(completed)
+ )
+ assert "secret business plan" not in payload
+ assert completed.bytes_size > 0
+
+
+# --------------------------------------------------------------------------
+# Forced capture (REST / a bar button)
+# --------------------------------------------------------------------------
+
+
+async def test_force_skips_classification_but_not_privacy() -> None:
+ capturer = FakeCapturer()
+ service = make_service(
+ settings=ScreenContextSettings(denylist=("vault",)),
+ window_probe=FakeWindowProbe(
+ WindowFacts(app_name="pw", title="My Vault", frame_rect=(0, 0, 800, 600))
+ ),
+ capturer=capturer,
+ )
+
+ outcome = await service.capture_for_turn("", locale="en", force=True)
+
+ assert outcome.status == "refused"
+ assert capturer.grabs == [], "force must never bypass the denylist"
+
+
+async def test_force_captures_without_any_utterance() -> None:
+ service = make_service()
+ outcome = await service.capture_for_turn("", locale="en", force=True)
+ assert outcome.status == "captured"
+
+
+# --------------------------------------------------------------------------
+# Config bridge
+# --------------------------------------------------------------------------
+
+
+def test_settings_from_a_config_without_the_block_are_defaults() -> None:
+ """An older jarvis.toml has no [screen_context]; that must not explode."""
+
+ class OldConfig:
+ pass
+
+ settings = settings_from_config(OldConfig())
+ assert settings.enabled is True
+ assert settings.denylist == ()
+
+
+def test_settings_are_read_from_the_config_block() -> None:
+ from jarvis.core.config import JarvisConfig
+
+ cfg = JarvisConfig()
+ cfg.screen_context.denylist = ["1password"]
+ cfg.screen_context.ttl_s = 30.0
+ cfg.screen_context.ocr_enabled = True
+
+ settings = settings_from_config(cfg)
+
+ assert settings.denylist == ("1password",)
+ assert settings.ttl_s == 30.0
+ assert settings.ocr_enabled is True
+
+
+def test_describe_names_what_was_captured() -> None:
+ """The receipt is what the user is told; it must be concrete."""
+ from jarvis.screen_context.models import CaptureTarget, ScreenContext
+
+ context = ScreenContext(
+ image=b"x",
+ mime="image/jpeg",
+ size=(1920, 1080),
+ target=CaptureTarget(
+ kind=TargetKind.MONITOR,
+ bbox=(0, 0, 1920, 1080),
+ reason=TargetReason.CURSOR_MONITOR,
+ monitor_name="2",
+ ),
+ )
+
+ described = context.describe()
+ assert "monitor 2" in described
+ assert "1920x1080" in described
diff --git a/tests/unit/screen_context/test_targeting.py b/tests/unit/screen_context/test_targeting.py
new file mode 100644
index 0000000000..e33997967a
--- /dev/null
+++ b/tests/unit/screen_context/test_targeting.py
@@ -0,0 +1,173 @@
+"""Surface selection: cursor monitor first, bar second, primary last.
+
+The multi-monitor rule is the one behaviour a user notices immediately when it
+is wrong ("it described the other screen"), so the fallback chain and the
+divergence from the foreground-window heuristic are pinned here explicitly.
+"""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.screen_context.models import (
+ DegradationCode,
+ TargetKind,
+ TargetReason,
+ VisualIntent,
+ WindowFacts,
+)
+from jarvis.screen_context.ports import CaptureUnavailable
+from jarvis.screen_context.targeting import monitor_for_point, resolve_target
+
+# A realistic asymmetric layout: primary at the origin, a second screen to its
+# LEFT (negative virtual X) — the arrangement that breaks naive "monitors[1]"
+# and "origin == (0,0)" assumptions.
+LEFT = {"left": -1920, "top": 0, "width": 1920, "height": 1080, "name": "left"}
+PRIMARY = {"left": 0, "top": 0, "width": 2560, "height": 1440, "name": "primary"}
+VIRTUAL = {"left": -1920, "top": 0, "width": 4480, "height": 1440, "name": "virtual"}
+MONITORS = [VIRTUAL, LEFT, PRIMARY]
+
+
+def test_point_inside_a_monitor_selects_it() -> None:
+ assert monitor_for_point(MONITORS, (-800, 500)) is LEFT
+ assert monitor_for_point(MONITORS, (1000, 500)) is PRIMARY
+
+
+def test_virtual_bounding_box_is_never_selected() -> None:
+ """Returning [0] would capture every monitor — the opposite of the rule."""
+ for point in ((-800, 500), (1000, 500), (99_999, 99_999)):
+ assert monitor_for_point(MONITORS, point) is not VIRTUAL
+
+
+def test_point_outside_every_monitor_falls_to_the_nearest() -> None:
+ """A cursor in an L-shaped layout gap must not fail the capture."""
+ assert monitor_for_point(MONITORS, (-1920, 5000)) is LEFT
+ assert monitor_for_point(MONITORS, (10_000, 100)) is PRIMARY
+
+
+def test_cursor_monitor_wins_over_the_foreground_window() -> None:
+ """The whole point of the rule: the user's eyes, not the focus.
+
+ The focused window sits on the primary screen while the cursor is on the
+ left one. Every other capture path in the tree would grab the primary.
+ """
+ target, degradations = resolve_target(
+ VisualIntent.SCREEN,
+ monitors=MONITORS,
+ cursor_point=(-800, 400),
+ bar_point=(1200, 1400),
+ window=WindowFacts(title="Editor", frame_rect=(100, 100, 800, 600)),
+ )
+ assert target.kind is TargetKind.MONITOR
+ assert target.bbox == (-1920, 0, 1920, 1080)
+ assert target.reason is TargetReason.CURSOR_MONITOR
+ assert degradations == ()
+
+
+def test_bar_monitor_is_the_documented_cursor_fallback() -> None:
+ target, degradations = resolve_target(
+ VisualIntent.SCREEN,
+ monitors=MONITORS,
+ cursor_point=None,
+ bar_point=(-1000, 900),
+ window=None,
+ )
+ assert target.reason is TargetReason.BAR_MONITOR
+ assert target.bbox == (-1920, 0, 1920, 1080)
+ codes = {d.code for d in degradations}
+ assert DegradationCode.NO_CURSOR in codes, "a silent fallback is a lie (AP-30)"
+
+
+def test_primary_is_the_last_resort() -> None:
+ target, degradations = resolve_target(
+ VisualIntent.SCREEN,
+ monitors=MONITORS,
+ cursor_point=None,
+ bar_point=None,
+ window=None,
+ )
+ assert target.reason is TargetReason.PRIMARY_MONITOR
+ codes = {d.code for d in degradations}
+ assert {DegradationCode.NO_CURSOR, DegradationCode.NO_BAR_POSITION} <= codes
+
+
+def test_window_scope_captures_the_window() -> None:
+ target, _ = resolve_target(
+ VisualIntent.WINDOW,
+ monitors=MONITORS,
+ cursor_point=(1000, 500),
+ bar_point=None,
+ window=WindowFacts(title="Report.pdf", frame_rect=(200, 150, 1200, 900)),
+ window_handle=4242,
+ )
+ assert target.kind is TargetKind.WINDOW
+ assert target.bbox == (200, 150, 1200, 900)
+ assert target.window_handle == 4242
+ assert target.reason is TargetReason.FOCUSED_WINDOW
+
+
+def test_unusable_window_rect_falls_back_to_the_monitor() -> None:
+ """A minimized window (Windows parks these at -32000) must not be shot."""
+ target, degradations = resolve_target(
+ VisualIntent.WINDOW,
+ monitors=MONITORS,
+ cursor_point=(1000, 500),
+ bar_point=None,
+ window=WindowFacts(title="Mail", frame_rect=(-32000, -32000, 0, 0)),
+ )
+ assert target.kind is TargetKind.MONITOR
+ assert target.reason is TargetReason.WINDOW_FALLBACK_MONITOR
+ assert DegradationCode.WINDOW_RECT_UNUSABLE in {d.code for d in degradations}
+
+
+def test_screen_intent_never_narrows_to_the_window() -> None:
+ """"Look at this" means the screen; only a window-scoped turn narrows."""
+ target, _ = resolve_target(
+ VisualIntent.SCREEN,
+ monitors=MONITORS,
+ cursor_point=(1000, 500),
+ bar_point=None,
+ window=WindowFacts(title="Editor", frame_rect=(100, 100, 800, 600)),
+ )
+ assert target.kind is TargetKind.MONITOR
+
+
+def test_window_facts_travel_with_a_monitor_capture() -> None:
+ """"Which app was the user in" is context even for a full-screen shot."""
+ facts = WindowFacts(app_name="editor", title="notes.md", pid=99)
+ target, _ = resolve_target(
+ VisualIntent.SCREEN,
+ monitors=MONITORS,
+ cursor_point=(1000, 500),
+ bar_point=None,
+ window=facts,
+ )
+ assert target.window is facts
+
+
+def test_headless_host_refuses_instead_of_guessing() -> None:
+ with pytest.raises(CaptureUnavailable) as excinfo:
+ resolve_target(
+ VisualIntent.SCREEN,
+ monitors=[],
+ cursor_point=None,
+ bar_point=None,
+ window=None,
+ )
+ message = str(excinfo.value)
+ assert "headless" in message.lower() or "no display" in message.lower()
+
+
+def test_single_monitor_host_works() -> None:
+ """mss reports [virtual, only-screen]; both entries describe one screen."""
+ solo = [
+ {"left": 0, "top": 0, "width": 1920, "height": 1080},
+ {"left": 0, "top": 0, "width": 1920, "height": 1080},
+ ]
+ target, _ = resolve_target(
+ VisualIntent.SCREEN,
+ monitors=solo,
+ cursor_point=(500, 500),
+ bar_point=None,
+ window=None,
+ )
+ assert target.bbox == (0, 0, 1920, 1080)