Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat: complete screen context readiness controls
Ruben Lütke44f459b37e38
diff --git a/docs/screen-context.md b/docs/screen-context.mdindex 96f3b6cc9d..1492295719 100644--- a/docs/screen-context.md+++ b/docs/screen-context.md@@ -1,6 +1,6 @@# Screen Context — architecture, flow, privacy plan, MVP roadmap-**Date:** 2026-07-29+**Date:** 2026-07-31**Status:** Production implementation complete across the brain, desktop, REST,settings, indicator, receipt, privacy, and optional OCR paths**Scope:** a local, on-demand screen-context service for the on-screen bar and@@ -49,7 +49,7 @@ them.| `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/platform/window_capture.py` | Native per-window capture (Windows Graphics 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`. |@@ -124,7 +124,7 @@ carried explicitly in `ScreenContext.degradations`.- `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`.+ `degradations`.- `RedactionReport` — what was removed and by which rule. Shipped *with* thecontext so the model is told the truth about its own evidence and the usercan see it in the receipt.@@ -164,7 +164,7 @@ user speaks[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)+[5] capture ONCE + read window facts + read UI text (accessibility first; optional OCR adds pixel boxes)│▼[6] redaction.apply() image regions blacked out, text scrubbed, report built@@ -216,7 +216,9 @@ new locale is a data entry, not code):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+Negative guards matter as much as the vocabulary. Product how-to questions+such as "How can you look at my screen?" are explicitly not capture consent.+The existing `cu_gate` learnedthis the hard way: product names containing a vehicle token ("Open AI", "contextwindow", "edge case") read as commands. Screen Context reuses that maskingapproach before matching, and adds its own: "see" in "I see" / "you see" /@@ -265,11 +267,11 @@ the target rect (a monitor capture should not carry text from a window onanother screen), stripped of `is_password` nodes at the source, and truncated toa 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.+OCR is optional and runs only when the user enables it and a backend is+installed. When enabled, it always retains line geometry so matching sensitive+text can be burned out of the pixels. Its extracted text is appended only when+the accessibility result is sparse relative to the captured area, because the+OS text is otherwise both faster and more accurate.---@@ -325,7 +327,8 @@ carries a label that appears in the redaction report.- 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.+- TTL (default 120 s) owns an active monotonic expiry callback; deletion does+ not depend on a later API call. Conversation turns consume immediately.- There is no save endpoint. Screen Context has no code path that writes imagebytes or extracted text to disk.- Nothing about a capture reaches the flight recorder except metadata: target@@ -367,6 +370,11 @@ and isolated by conversation, so a reply in another web thread or on anothersurface cannot authorize a capture. The model-facing description rides in thedispatcher's existing `turn_context` channel.+The shared `turn_planner` also assigns explicit and ambiguous visual turns to+the orchestrator. Realtime therefore uses the same deterministic capture path+in both delegate and direct-tool modes; the native live model never answers a+screen question without receiving the one-shot image.+Two decisions were made during implementation and are worth stating here,because both were wrong in the first draft:@@ -376,19 +384,19 @@ fires on on-screen *action* turns ("click the button", "close this window"),which are not look-requests but still need an image. Replacing it would blindComputer-Use. The two gates answer different questions and both stay.-**A refusal is typed, and the type decides the fallback.** The first draft-ended the turn on any refusal, which would have turned every look-request on a-headless or unpermitted host into a spoken refusal instead of a normal answer.-Refusals are now:+**A refusal is typed, but every requested look fails closed.** Policy and+diagnostic categories stay distinct so the UI can give useful remediation.+Neither category may fall through to permanent vision or Computer-Use: doing so+would bypass the one-shot consent and privacy boundary.| Kind | Cause | Ends the turn? | Fallback path ||---|---|---|---|| `policy` | denylist match, feature switched off | yes, spoken | **shut** — falling through would photograph the very window the rule protects |-| `technical-unavailable` | no display, no permission | no | **open** — the legacy path may answer normally, but its own capability gate still prevents capture |+| `technical-unavailable` | no display, no permission | yes, spoken | **shut** — the host reports the limitation without starting another screen path || `technical-failure` | unexpected classifier/capture failure | yes, spoken | **shut** — a second, unindicated screenshot attempt would violate the privacy contract |-Collapsing those two fails in one of two quiet ways: leak a protected window,-or break the feature on every machine without a screen.+Collapsing their diagnostics would hide the remediation, while opening either+fallback would risk a second, unindicated capture.An `AMBIGUOUS` turn also shuts the fallback — attaching an image while askingwhether to look at one is exactly what the three-valued verdict exists to@@ -413,15 +421,20 @@ OSes, or by a logged degradation naming why it could not be shown.### Wave 4 — settings surface ✅ *implemented*-A Screen Context group in Settings exposes the master switch, capability state,+A Screen Context group in Settings exposes the master switch, structured+end-to-end readiness (capture, permission, indicator, vision, accessibility,+and OCR),denylist and redaction-pattern editors, default-rule and OCR toggles, retention-promise, and an immediate discard action. The REST surface also exposes TTL and+promise, an immediate discard action, and a one-capture test that deletes its+own handle without returning pixels. The REST surface also exposes TTL andtext-budget settings. Multi-field changes use one atomic config replacement.### Wave 5 — OCR supplement ✅ *implemented*-Optional local OCR behind a capability probe, used only when accessibility text-is empty. Off by default, base install stays torch-free.+Optional local OCR behind a capability probe. It contributes image-local boxes+for pixel redaction on every enabled run and supplements model text only when+accessibility coverage is sparse. Off by default; the base install stays+torch-free.---diff --git a/jarvis/cu/indicator/controller.py b/jarvis/cu/indicator/controller.pyindex 0dbfb76513..6c34074472 100644--- a/jarvis/cu/indicator/controller.py+++ b/jarvis/cu/indicator/controller.py@@ -53,6 +53,11 @@ _BLANK_ACK_TIMEOUT_S = 0.15_SHOW_ACK_TIMEOUT_S = 1.2+def screen_indicator_capability() -> tuple[bool, str]:+ """Return whether the visible capture border can run on this host."""+ return CUIndicatorController._border_capability()++def _esc_binding() -> list[str]:"""The Escape key's name differs per hotkey backend (live 2026-07-16):Windows ``global-hotkeys`` only accepts ``"escape"`` (``"esc"`` raisesdiff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex cddc480bb3..71354a428d 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -1367,19 +1367,29 @@},"screen_context": {"title": "Bildschirmkontext",- "description": "Erlaubt {name}, genau einen Screenshot zu prüfen, wenn du ausdrücklich darum bittest. Vorher erscheint ein sichtbarer Rand; die Pixel bleiben im Speicher und werden einmalig verbraucht.",+ "description": "Erlaubt {name}, genau einen aktuellen Screenshot als Kontext zu verwenden, wenn du ausdrücklich darum bittest. Vorher erscheint ein sichtbarer Rand; das Bild wird in diesem Turn verbraucht und danach gelöscht.","available": "Auf {0} Monitor(en) bereit.","unavailable": "Die Bildschirmaufnahme ist nicht verfügbar. Prüfe die Systemberechtigung und Desktop-Sitzung; Headless- und Wayland-Systeme werden sicher eingeschränkt.","denylist": "Diese Apps oder Fenstertitel nie aufnehmen (ein Eintrag pro Zeile)","denylist_placeholder": "Passwortmanager\nPrivates Banking","patterns": "Zusätzliche sensible Muster (Bezeichnung:regulärer Ausdruck)","patterns_placeholder": "kunden_id:KUNDE-[0-9]+",- "default_patterns": "Eingebaute Muster für Passwörter, Karten, Tokens und persönliche Daten schwärzen",- "ocr": "Optionale Texterkennung nutzen, wenn Bedienungshilfen keinen Text liefern",+ "default_patterns": "Erkennbare Passwortfelder sowie passende Karten-, Token-, Schlüssel- und Geheimtexte schwärzen",+ "ocr": "Optionale Texterkennung für Pixelschwärzung und fehlenden Bedienungshilfen-Text verwenden",+ "capture_status": "Aufnahme-Backend",+ "indicator_status": "Sichtbarer Rand",+ "vision_status": "Vision-Modell",+ "accessibility_status": "Bedienungshilfen-Text",+ "ocr_status": "Optionale Texterkennung",+ "placeholders_are_examples": "Der Text im leeren Feld ist nur ein Beispiel und keine aktive Datenschutzregel.","retention_label": "Aufbewahrung (Sekunden, 1–600)","save_privacy": "Datenschutzregeln speichern","discard": "Gespeicherte Aufnahmen jetzt verwerfen",- "retention": "Nicht verwendete Aufnahmen verfallen nach {0} Sekunden. Es wird nichts auf die Festplatte geschrieben.",+ "test_capture": "Eine Aufnahme testen",+ "test_success": "Aufnahmetest bestanden und sofort gelöscht: {0}",+ "test_failed": "Der Aufnahmetest konnte nicht abgeschlossen werden.",+ "held": "Derzeit gespeichert: {0}.",+ "retention": "Aufnahmen aus Unterhaltungen werden sofort verbraucht. Eine ungenutzte API-Aufnahme wird nach {0} Sekunden gelöscht. Es wird nichts auf die Festplatte geschrieben.","saved": "Einstellungen für den Bildschirmkontext gespeichert.","discarded": "Alle gespeicherten Bildschirmaufnahmen wurden verworfen.","capturing": "Der Bildschirmkontext betrachtet die angeforderte Oberfläche.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 227f153de1..ef46b01143 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -1368,19 +1368,29 @@},"screen_context": {"title": "Screen Context",- "description": "Lets {name} inspect one screenshot only when you explicitly ask. A visible border appears first; pixels stay in memory and are consumed once.",+ "description": "Lets {name} use one current screenshot as context only when you explicitly ask. A visible border appears first; the image is consumed by that turn and then deleted.","available": "Ready on {0} monitor(s).","unavailable": "Screen capture is unavailable. Check the system permission and desktop session; headless and Wayland systems degrade safely.","denylist": "Never capture these apps or window titles (one per line)","denylist_placeholder": "Password Manager\nPrivate Banking","patterns": "Additional sensitive patterns (label:regular expression)","patterns_placeholder": "customer_id:CUST-[0-9]+",- "default_patterns": "Redact built-in password, card, token, and personal-data patterns",- "ocr": "Use optional OCR when accessibility text is unavailable",+ "default_patterns": "Redact detectable password fields and matching card, token, key, and secret text",+ "ocr": "Use optional OCR for pixel redaction and missing accessibility text",+ "capture_status": "Capture backend",+ "indicator_status": "Visible border",+ "vision_status": "Vision model",+ "accessibility_status": "Accessibility text",+ "ocr_status": "Optional OCR",+ "placeholders_are_examples": "The text shown in the empty field is only an example; it is not an active privacy rule.","retention_label": "Retention (seconds, 1–600)","save_privacy": "Save privacy rules","discard": "Discard held captures now",- "retention": "Unconsumed captures expire after {0} seconds. Nothing is written to disk.",+ "test_capture": "Test one capture",+ "test_success": "Capture test passed and was deleted immediately: {0}",+ "test_failed": "The capture test did not complete.",+ "held": "Currently held: {0}.",+ "retention": "Conversation captures are consumed immediately. An unused API capture is deleted after {0} seconds. Nothing is written to disk.","saved": "Screen Context settings saved.","discarded": "All held screen captures were discarded.","capturing": "Screen Context is looking at the requested surface.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 95834a4983..1401e8e6db 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -1367,19 +1367,29 @@},"screen_context": {"title": "Contexto de pantalla",- "description": "Permite que {name} revise una sola captura únicamente cuando lo pides de forma explícita. Primero aparece un borde visible; los píxeles permanecen en memoria y se consumen una vez.",+ "description": "Permite que {name} use una captura actual como contexto solo cuando lo pides de forma explícita. Primero aparece un borde visible; la imagen se consume en ese turno y después se elimina.","available": "Listo en {0} monitor(es).","unavailable": "La captura de pantalla no está disponible. Comprueba el permiso del sistema y la sesión de escritorio; los sistemas sin pantalla y Wayland se limitan de forma segura.","denylist": "No capturar nunca estas apps o títulos de ventana (uno por línea)","denylist_placeholder": "Gestor de contraseñas\nBanca privada","patterns": "Patrones sensibles adicionales (etiqueta:expresión regular)","patterns_placeholder": "id_cliente:CLIENTE-[0-9]+",- "default_patterns": "Ocultar patrones integrados de contraseñas, tarjetas, tokens y datos personales",- "ocr": "Usar OCR opcional cuando no haya texto de accesibilidad",+ "default_patterns": "Ocultar campos de contraseña detectables y texto coincidente de tarjetas, tokens, claves y secretos",+ "ocr": "Usar OCR opcional para ocultar píxeles y completar texto de accesibilidad",+ "capture_status": "Sistema de captura",+ "indicator_status": "Borde visible",+ "vision_status": "Modelo de visión",+ "accessibility_status": "Texto de accesibilidad",+ "ocr_status": "OCR opcional",+ "placeholders_are_examples": "El texto del campo vacío es solo un ejemplo y no una regla de privacidad activa.","retention_label": "Retención (segundos, 1–600)","save_privacy": "Guardar reglas de privacidad","discard": "Descartar capturas retenidas ahora",- "retention": "Las capturas no consumidas caducan tras {0} segundos. No se escribe nada en disco.",+ "test_capture": "Probar una captura",+ "test_success": "La prueba de captura terminó correctamente y se eliminó de inmediato: {0}",+ "test_failed": "La prueba de captura no pudo completarse.",+ "held": "Retenidas ahora: {0}.",+ "retention": "Las capturas de conversación se consumen de inmediato. Una captura de API sin usar se elimina tras {0} segundos. No se escribe nada en disco.","saved": "Ajustes de contexto de pantalla guardados.","discarded": "Se descartaron todas las capturas retenidas.","capturing": "El contexto de pantalla está revisando la superficie solicitada.",diff --git a/jarvis/ui/web/frontend/src/views/settings/ScreenContextGroup.test.tsx b/jarvis/ui/web/frontend/src/views/settings/ScreenContextGroup.test.tsxnew file mode 100644index 0000000000..c9e97e3c43--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/settings/ScreenContextGroup.test.tsx@@ -0,0 +1,97 @@+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++import { ScreenContextGroup } from "./ScreenContextGroup";++const SETTINGS = {+ enabled: true,+ denylist: [],+ sensitive_patterns: [],+ include_default_patterns: true,+ max_text_chars: 4000,+ ttl_s: 120,+ ocr_enabled: false,+};++function status(available: boolean) {+ return {+ enabled: true,+ available,+ blocked_reason: available ? null : "No vision-capable provider is configured.",+ blocked_reasons: available+ ? []+ : ["No vision-capable provider is configured."],+ monitor_count: 2,+ held_captures: 0,+ ttl_s: 120,+ components: {+ capture: { ready: true, detail: "" },+ indicator: { ready: true, detail: "" },+ vision: {+ ready: available,+ detail: available ? "" : "No vision-capable provider is configured.",+ },+ accessibility: { ready: true, detail: "" },+ ocr: { enabled: false, ready: false, detail: "Optional OCR is switched off." },+ },+ };+}++function response(body: unknown) {+ return { ok: true, json: async () => body };+}++afterEach(() => vi.restoreAllMocks());++describe("ScreenContextGroup", () => {+ it("shows the real blocker and labels empty-field text as examples", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async (url: string) =>+ response(url.endsWith("/settings") ? SETTINGS : status(false)),+ ),+ );++ render(<ScreenContextGroup />);++ await waitFor(() =>+ expect(+ screen.getByText("No vision-capable provider is configured."),+ ).toBeTruthy(),+ );+ expect(screen.getAllByText(/only an example/i)).toHaveLength(2);+ expect(screen.getByText("Test one capture").closest("button")?.disabled).toBe(+ true,+ );+ });++ it("tests one capture and deletes only that handle", async () => {+ const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {+ if (url.endsWith("/settings")) return response(SETTINGS);+ if (url.endsWith("/status")) return response(status(true));+ if (url.endsWith("/capture") && init?.method === "POST") {+ return response({+ status: "captured",+ id: "one-shot-handle",+ receipt: "monitor primary",+ });+ }+ if (url.endsWith("/one-shot-handle") && init?.method === "DELETE") {+ return response({ ok: true, discarded: 1 });+ }+ throw new Error(`Unexpected request: ${url}`);+ });+ vi.stubGlobal("fetch", fetchMock);+ render(<ScreenContextGroup />);++ const button = await waitFor(() => screen.getByText("Test one capture"));+ fireEvent.click(button);++ await waitFor(() =>+ expect(fetchMock).toHaveBeenCalledWith(+ "/api/screen-context/one-shot-handle",+ { method: "DELETE" },+ ),+ );+ });+});diff --git a/jarvis/ui/web/frontend/src/views/settings/ScreenContextGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/ScreenContextGroup.tsxindex 35255166f8..b5db6f44fd 100644--- a/jarvis/ui/web/frontend/src/views/settings/ScreenContextGroup.tsx+++ b/jarvis/ui/web/frontend/src/views/settings/ScreenContextGroup.tsx@@ -1,5 +1,5 @@import { useEffect, useState } from "react";-import { Eye, Loader2, Shield, Trash2 } from "lucide-react";+import { Camera, Eye, Loader2, Shield, Trash2 } from "lucide-react";import { Button } from "@/components/ui/button";import { Switch } from "@/components/ui/switch";@@ -17,8 +17,24 @@ interface ScreenContextSettings {}interface ScreenContextStatus {+ enabled: boolean;available: boolean;+ blocked_reason: string | null;+ blocked_reasons: string[];monitor_count: number;+ held_captures: number;+ ttl_s: number;+ components: Record<+ string,+ { ready: boolean; detail: string; enabled?: boolean }+ >;+}++interface CaptureTestResult {+ status: string;+ id?: string;+ receipt?: string;+ reason?: string;}async function jsonRequest<T>(url: string, init?: RequestInit): Promise<T> {@@ -60,6 +76,13 @@ export function ScreenContextGroup() {const [loading, setLoading] = useState(true);const [saving, setSaving] = useState(false);+ async function refreshStatus() {+ const nextStatus = await jsonRequest<ScreenContextStatus>(+ "/api/screen-context/status",+ );+ setStatus(nextStatus);+ }+useEffect(() => {let active = true;void Promise.all([@@ -92,7 +115,10 @@ export function ScreenContextGroup() {headers: { "content-type": "application/json" },body: JSON.stringify(patch),});- setSettings({ ...settings, ...patch });+ setSettings((current) =>+ current === null ? current : { ...current, ...patch },+ );+ await refreshStatus();pushToast("success", t("settings_view.screen_context.saved"));} catch (error) {pushToast("error", (error as Error).message);@@ -105,6 +131,7 @@ export function ScreenContextGroup() {setSaving(true);try {await jsonRequest("/api/screen-context", { method: "DELETE" });+ await refreshStatus();pushToast("success", t("settings_view.screen_context.discarded"));} catch (error) {pushToast("error", (error as Error).message);@@ -113,11 +140,54 @@ export function ScreenContextGroup() {}}+ async function testCapture() {+ setSaving(true);+ let captureId = "";+ try {+ const result = await jsonRequest<CaptureTestResult>(+ "/api/screen-context/capture",+ {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ force: true }),+ },+ );+ captureId = result.id || "";+ if (result.status !== "captured" || !captureId) {+ throw new Error(+ result.reason || t("settings_view.screen_context.test_failed"),+ );+ }+ await jsonRequest(+ `/api/screen-context/${encodeURIComponent(captureId)}`,+ { method: "DELETE" },+ );+ captureId = "";+ pushToast(+ "success",+ t("settings_view.screen_context.test_success").replace(+ "{0}",+ result.receipt || "",+ ),+ );+ await refreshStatus();+ } catch (error) {+ if (captureId) {+ await fetch(`/api/screen-context/${encodeURIComponent(captureId)}`, {+ method: "DELETE",+ }).catch(() => undefined);+ }+ pushToast("error", (error as Error).message);+ } finally {+ setSaving(false);+ }+ }+const ttlValue = Number(ttl);const ttlValid = Number.isFinite(ttlValue) && ttlValue >= 1 && ttlValue <= 600;return (- <section className="mt-2 rounded-lg border border-border bg-card/60 p-4">+ <section className="mt-2 max-w-5xl rounded-lg border border-border bg-card/60 p-4"><div className="flex items-start gap-3"><Eye className="mt-0.5 h-4 w-4 shrink-0 text-primary" /><div className="min-w-0 flex-1">@@ -137,19 +207,45 @@ export function ScreenContextGroup() {{t("settings_view.screen_context.description")}</p>{status && (- <p- className={`mt-2 text-[11px] ${- status.available ? "text-emerald-400" : "text-amber-400"- }`}- aria-live="polite"- >- {status.available- ? t("settings_view.screen_context.available").replace(- "{0}",- String(status.monitor_count),- )- : t("settings_view.screen_context.unavailable")}- </p>+ <div className="mt-2" aria-live="polite">+ <p+ className={`text-[11px] ${+ status.available ? "text-emerald-400" : "text-amber-400"+ }`}+ >+ {status.available+ ? t("settings_view.screen_context.available").replace(+ "{0}",+ String(status.monitor_count),+ )+ : status.blocked_reason ||+ t("settings_view.screen_context.unavailable")}+ </p>+ <div className="mt-2 grid max-w-3xl grid-cols-2 gap-x-5 gap-y-1 text-[11px] sm:grid-cols-3">+ {[+ ["capture", "capture_status"],+ ["indicator", "indicator_status"],+ ["vision", "vision_status"],+ ["accessibility", "accessibility_status"],+ ["ocr", "ocr_status"],+ ].map(([name, labelKey]) => {+ const component = status.components[name];+ const optionalDisabled =+ name === "ocr" && component?.enabled === false;+ const ready = component?.ready || optionalDisabled;+ return (+ <span+ key={name}+ className={ready ? "text-muted-foreground" : "text-amber-400"}+ title={component?.detail || ""}+ >+ {ready ? "✓" : "!"}{" "}+ {t(`settings_view.screen_context.${labelKey}`)}+ </span>+ );+ })}+ </div>+ </div>)}{settings && (@@ -163,6 +259,11 @@ export function ScreenContextGroup() {placeholder={t("settings_view.screen_context.denylist_placeholder")}className="mt-1.5 min-h-20 w-full resize-y rounded-md border border-border bg-background px-3 py-2 font-mono text-xs"/>+ {!denylist.trim() && (+ <span className="mt-1 block text-[11px] font-normal text-muted-foreground">+ {t("settings_view.screen_context.placeholders_are_examples")}+ </span>+ )}</label><label className="block text-xs font-medium">{t("settings_view.screen_context.patterns")}@@ -173,6 +274,11 @@ export function ScreenContextGroup() {placeholder={t("settings_view.screen_context.patterns_placeholder")}className="mt-1.5 min-h-20 w-full resize-y rounded-md border border-border bg-background px-3 py-2 font-mono text-xs"/>+ {!patterns.trim() && (+ <span className="mt-1 block text-[11px] font-normal text-muted-foreground">+ {t("settings_view.screen_context.placeholders_are_examples")}+ </span>+ )}</label><div className="flex items-center justify-between gap-4 text-xs"><span>{t("settings_view.screen_context.default_patterns")}</span>@@ -220,6 +326,15 @@ export function ScreenContextGroup() {<Shield className="mr-1.5 h-3.5 w-3.5" />{t("settings_view.screen_context.save_privacy")}</Button>+ <Button+ size="sm"+ variant="outline"+ disabled={saving || !status?.available}+ onClick={() => void testCapture()}+ >+ <Camera className="mr-1.5 h-3.5 w-3.5" />+ {t("settings_view.screen_context.test_capture")}+ </Button><Buttonsize="sm"variant="outline"@@ -235,6 +350,12 @@ export function ScreenContextGroup() {"{0}",String(settings.ttl_s),)}+ {status && status.held_captures > 0+ ? ` ${t("settings_view.screen_context.held").replace(+ "{0}",+ String(status.held_captures),+ )}`+ : ""}</p></div>)}diff --git a/jarvis/ui/web/screen_context_routes.py b/jarvis/ui/web/screen_context_routes.pyindex 97f09c24ad..bb0291b233 100644--- a/jarvis/ui/web/screen_context_routes.py+++ b/jarvis/ui/web/screen_context_routes.py@@ -32,7 +32,6 @@ from __future__ import annotationsimport base64import logging-import refrom typing import Anyfrom fastapi import APIRouter, HTTPException, Request@@ -53,6 +52,49 @@ log = logging.getLogger(__name__)router = APIRouter(prefix="/api/screen-context", tags=["screen-context"])++def _capture_backend_capability() -> tuple[bool, str]:+ import importlib.util # noqa: PLC0415++ if importlib.util.find_spec("mss") is None:+ return False, "The screen-capture package is not installed."+ return True, ""+++def _indicator_capability() -> tuple[bool, str]:+ from jarvis.cu.indicator.controller import ( # noqa: PLC0415+ screen_indicator_capability,+ )++ return screen_indicator_capability()+++def _vision_capability() -> tuple[bool, str]:+ try:+ from jarvis.brain.resolver import resolve_vision_brain # noqa: PLC0415+ from jarvis.core.config import load_config # noqa: PLC0415++ brain = resolve_vision_brain(load_config())+ except Exception: # noqa: BLE001 - readiness must never break Settings+ log.warning("screen_context: vision readiness probe failed", exc_info=True)+ return False, "Vision-provider readiness could not be checked."+ if brain is None:+ return False, "No configured provider currently advertises vision support."+ return True, ""+++def _ocr_capability(enabled: bool) -> tuple[bool, str]:+ if not enabled:+ return False, "Optional OCR is switched off."+ import importlib.util # noqa: PLC0415+ import shutil # noqa: PLC0415++ if importlib.util.find_spec("pytesseract") is None:+ return False, "The optional OCR Python package is not installed."+ if shutil.which("tesseract") is None:+ return False, "The optional Tesseract executable is not available."+ return True, ""+def _get_service(request: Request) -> ScreenContextService:return get_shared_service(bus=getattr(request.app.state, "bus", None))@@ -69,8 +111,11 @@ def _reset_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').",+ default="",+ description=(+ "Optional resolved output language. Empty uses the central turn "+ "language resolver."+ ),)@@ -79,7 +124,10 @@ class CaptureRequest(BaseModel):default="",description="User utterance. Empty with force=true for an explicit capture.",)- locale: str = Field(default="en", description="Resolved output language.")+ locale: str = Field(+ default="",+ description="Optional resolved output language; empty resolves centrally.",+ )force: bool = Field(default=True,description=(@@ -137,25 +185,107 @@ def _context_metadata(context: Any, handle_id: str | None) -> dict[str, Any]:}+def _resolved_locale(locale: str, text: str) -> str:+ """Resolve API output through the same language policy as voice/chat."""+ from jarvis.core.config import load_config # noqa: PLC0415+ from jarvis.core.turn_language import ( # noqa: PLC0415+ DEFAULT_LOCALE,+ normalize_language_tag,+ resolve_output_language,+ )++ if str(locale or "").strip():+ explicit = normalize_language_tag(locale)+ if explicit and explicit != "unknown":+ return explicit+ cfg = load_config()+ return resolve_output_language(+ getattr(cfg.brain, "reply_language", "auto"),+ getattr(cfg.stt, "language", "auto"),+ text,+ default=DEFAULT_LOCALE,+ )++@router.get("/status")async def status(request: Request) -> dict[str, Any]:"""Capability and live state — answers honestly on a machine with no screen."""import asyncio # noqa: PLC0415service = _get_service(request)- from jarvis.screen_context.ports import capture_permission_error # noqa: PLC0415+ from jarvis.screen_context.ports import ( # noqa: PLC0415+ accessibility_permission_error,+ capture_permission_error,+ )- monitors = await asyncio.to_thread(service.displays.monitors)- permission_error = await asyncio.to_thread(capture_permission_error)- cursor_readable = await asyncio.to_thread(service.cursor.position)+ (+ monitors,+ permission_error,+ cursor_point,+ capture_backend,+ indicator,+ vision,+ accessibility_error,+ ocr,+ ) = await asyncio.gather(+ asyncio.to_thread(service.displays.monitors),+ asyncio.to_thread(capture_permission_error),+ asyncio.to_thread(service.cursor.position),+ asyncio.to_thread(_capture_backend_capability),+ asyncio.to_thread(_indicator_capability),+ asyncio.to_thread(_vision_capability),+ asyncio.to_thread(accessibility_permission_error),+ asyncio.to_thread(_ocr_capability, service.settings.ocr_enabled),+ )+ # mss index 0 is only the virtual aggregate; at least one physical entry+ # must exist before the status can promise a capturable display.+ display_ready = len(monitors) > 1+ permission_ready = permission_error is None+ capture_ready, capture_reason = capture_backend+ indicator_ready, indicator_reason = indicator+ vision_ready, vision_reason = vision+ accessibility_ready = accessibility_error is None+ ocr_ready, ocr_reason = ocr+ blockers = [+ reason+ for ready, reason in (+ (service.settings.enabled, "Screen Context is switched off."),+ (display_ready, "No interactive display was found."),+ (permission_ready, str(permission_error or "")),+ (capture_ready, capture_reason),+ (indicator_ready, indicator_reason),+ (vision_ready, vision_reason),+ )+ if not ready and reason+ ]return {"enabled": service.settings.enabled,- "available": bool(monitors) and permission_error is None,- "blocked_reason": permission_error,+ "available": not blockers,+ "blocked_reason": blockers[0] if blockers else None,+ "blocked_reasons": blockers,"monitor_count": max(0, len(monitors) - 1) if monitors else 0,- "cursor_readable": cursor_readable is not None,+ "cursor_readable": cursor_point is not None,"held_captures": service.held_count,"ttl_s": service.settings.ttl_s,+ "components": {+ "display": {"ready": display_ready, "detail": ""},+ "capture": {"ready": capture_ready, "detail": capture_reason},+ "permission": {+ "ready": permission_ready,+ "detail": str(permission_error or ""),+ },+ "indicator": {"ready": indicator_ready, "detail": indicator_reason},+ "vision": {"ready": vision_ready, "detail": vision_reason},+ "accessibility": {+ "ready": accessibility_ready,+ "detail": str(accessibility_error or ""),+ },+ "ocr": {+ "enabled": service.settings.ocr_enabled,+ "ready": ocr_ready,+ "detail": ocr_reason,+ },+ },}@@ -163,7 +293,8 @@ async def status(request: Request) -> dict[str, Any]: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)+ locale = _resolved_locale(body.locale, body.text)+ verdict = service.classify(body.text, locale=locale)action = {VisualIntent.NONE: "nothing",VisualIntent.AMBIGUOUS: "ask",@@ -178,7 +309,7 @@ async def classify(request: Request, body: ClassifyRequest) -> dict[str, Any]:if verdict.needs_clarification:from jarvis.screen_context.intent import clarifying_question # noqa: PLC0415- payload["question"] = clarifying_question(body.locale)+ payload["question"] = clarifying_question(locale)return payload@@ -187,7 +318,9 @@ 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+ body.text,+ locale=_resolved_locale(body.locale, body.text),+ force=body.force,)if outcome.status == "captured" and outcome.context is not None:@@ -271,13 +404,16 @@ async def put_settings(request: Request, patch: SettingsPatch) -> dict[str, Any]for entry in patterns:_label, separator, expression = str(entry).partition(":")source = expression if separator else str(entry)- try:- re.compile(source, re.IGNORECASE)- except re.error as exc:+ from jarvis.screen_context.redaction import ( # noqa: PLC0415+ validate_pattern_source,+ )++ validation_error = validate_pattern_source(source)+ if validation_error is not None:raise HTTPException(status_code=400,- detail=f"Invalid sensitive pattern: {exc}",- ) from exc+ detail=f"Invalid sensitive pattern: {validation_error}",+ )def _write() -> None:set_screen_context_settings(changes)@@ -329,6 +465,18 @@ async def consume_capture(request: Request, capture_id: str) -> dict[str, Any]:return payload[email protected]("/{capture_id}", openapi_extra={"x-jarvis-dangerous": True})+async def discard_capture(request: Request, capture_id: str) -> dict[str, Any]:+ """Discard one held capture without returning its pixels."""+ service = _get_service(request)+ if not service.discard(capture_id):+ raise HTTPException(+ status_code=404,+ detail="That capture was already used, discarded, or expired.",+ )+ return {"ok": True, "discarded": 1}++@router.delete("", openapi_extra={"x-jarvis-dangerous": True})async def discard_all(request: Request) -> dict[str, Any]:"""Drop every held capture right now — the panic button."""diff --git a/tests/unit/brain/test_router_screen_context.py b/tests/unit/brain/test_router_screen_context.pyindex 3b017c39d7..beb1cf425f 100644--- a/tests/unit/brain/test_router_screen_context.py+++ b/tests/unit/brain/test_router_screen_context.py@@ -1,4 +1,4 @@-"""RouterBrain × Screen Context: precedence, refusal, and the fallback rule.+"""RouterBrain × Screen Context: precedence and fail-closed refusal.Pins the wiring added when Screen Context landed. The interesting cases are theones where the two screen paths meet:@@ -10,8 +10,8 @@ ones where the two screen paths meet:an image while asking whether it may look at one;* a privacy refusal must leave permanent vision shut, or the fallbackphotographs the exact window the rule protects;-* a technical failure must NOT shut it, or every look-request on a headless host- turns into a refusal instead of an answer.+* a technical failure must also shut alternate screen paths while explaining+ the host limitation honestly."""from __future__ import annotationsdiff --git a/tests/unit/web/test_screen_context_routes.py b/tests/unit/web/test_screen_context_routes.pyindex ef1895439a..e16534a091 100644--- a/tests/unit/web/test_screen_context_routes.py+++ b/tests/unit/web/test_screen_context_routes.py@@ -2,6 +2,8 @@from __future__ import annotations+from types import SimpleNamespace+from fastapi import FastAPIfrom fastapi.testclient import TestClient@@ -63,6 +65,22 @@ def test_invalid_sensitive_pattern_is_rejected_before_write(monkeypatch) -> Noneassert calls == []+def test_pathological_sensitive_pattern_is_rejected_before_write(monkeypatch) -> None:+ calls: list[dict] = []+ monkeypatch.setattr(+ "jarvis.core.config_writer.set_screen_context_settings",+ lambda values: calls.append(dict(values)),+ )++ response = TestClient(_app()).put(+ "/api/screen-context/settings",+ json={"sensitive_patterns": [r"unsafe:(a+)+$"]},+ )++ assert response.status_code == 400+ assert calls == []++def test_receipt_metadata_never_exposes_app_or_window_title() -> None:from jarvis.screen_context.models import (CaptureTarget,@@ -88,3 +106,105 @@ def test_receipt_metadata_never_exposes_app_or_window_title() -> None:assert "secret.exe" not in str(metadata)assert "private document" not in str(metadata)+++def test_status_requires_the_complete_visual_context_path(monkeypatch) -> None:+ service = SimpleNamespace(+ settings=SimpleNamespace(enabled=True, ocr_enabled=False, ttl_s=120.0),+ displays=SimpleNamespace(+ monitors=lambda: [+ {"name": "virtual"},+ {"name": "primary"},+ ]+ ),+ cursor=SimpleNamespace(position=lambda: (10, 10)),+ held_count=0,+ )+ monkeypatch.setattr(screen_context_routes, "_get_service", lambda _request: service)+ monkeypatch.setattr(+ screen_context_routes,+ "_capture_backend_capability",+ lambda: (True, ""),+ )+ monkeypatch.setattr(+ screen_context_routes,+ "_indicator_capability",+ lambda: (True, ""),+ )+ monkeypatch.setattr(+ screen_context_routes,+ "_vision_capability",+ lambda: (False, "No vision-capable provider is configured."),+ )+ monkeypatch.setattr(+ screen_context_routes,+ "_ocr_capability",+ lambda _enabled: (False, "Optional OCR is switched off."),+ )+ monkeypatch.setattr(+ "jarvis.screen_context.ports.capture_permission_error",+ lambda: None,+ )+ monkeypatch.setattr(+ "jarvis.screen_context.ports.accessibility_permission_error",+ lambda: None,+ )++ response = TestClient(_app()).get("/api/screen-context/status")++ assert response.status_code == 200+ payload = response.json()+ assert payload["available"] is False+ assert payload["components"]["capture"]["ready"] is True+ assert payload["components"]["vision"]["ready"] is False+ assert "vision" in payload["blocked_reason"].lower()+++def test_classify_resolves_language_when_api_caller_omits_locale(monkeypatch) -> None:+ from jarvis.screen_context.models import IntentVerdict, VisualIntent++ seen: list[str] = []++ class FakeService:+ def classify(self, _text: str, *, locale: str):+ seen.append(locale)+ return IntentVerdict(intent=VisualIntent.AMBIGUOUS, locale=locale)++ monkeypatch.setattr(+ screen_context_routes,+ "_get_service",+ lambda _request: FakeService(),+ )+ monkeypatch.setattr(+ "jarvis.core.config.load_config",+ lambda: SimpleNamespace(+ brain=SimpleNamespace(reply_language="auto"),+ stt=SimpleNamespace(language="auto"),+ ),+ )++ response = TestClient(_app()).post(+ "/api/screen-context/classify",+ json={"text": "Was ist das?"}, # i18n-allow: German input fixture+ )++ assert response.status_code == 200+ assert seen == ["de"]+++def test_single_capture_discard_never_returns_pixels(monkeypatch) -> None:+ class FakeService:+ def discard(self, capture_id: str) -> bool:+ return capture_id == "held-once"++ monkeypatch.setattr(+ screen_context_routes,+ "_get_service",+ lambda _request: FakeService(),+ )++ response = TestClient(_app()).delete("/api/screen-context/held-once")++ assert response.status_code == 200+ assert response.json() == {"ok": True, "discarded": 1}+ assert "image" not in response.text