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(deck): the pictures the deck shows — last capture, and CU frames by hash
Haraldd0311adab42d
diff --git a/docs/screen-context.md b/docs/screen-context.mdindex ea72fbe6e0..3c09593773 100644--- a/docs/screen-context.md+++ b/docs/screen-context.md@@ -381,6 +381,22 @@ to `data/flight_recorder/blobs/`. That behaviour is correct for Computer-Usereplay and wrong for this feature; Screen Context therefore does not use`ScreenshotSource` at all, only the stateless `capture_region` primitive.+#### The deck preview (added 2026-08-17)++The mission deck shows the picture Jarvis just took, so the person at the+keyboard sees what was looked at. That is a second copy with its own, narrower+promise (`jarvis/screen_context/last_frame.py`):++- At most ONE frame, in memory only, replaced by the next capture.+- Gone after `[screen_context].deck_preview_s` seconds (default 120, the same+ budget as an unconsumed handle). `0` switches the preview off entirely.+- Served by `GET /api/deck/frame` with `Cache-Control: no-store`; the label+ next to it is the same scrubbed one the receipt event carries.+- The model's single-use handle above is unaffected: consuming it does not+ touch the preview, and the preview never feeds a turn.+- Cleared whenever the service is reset (a settings change tightening the+ rules must not leave the previous picture on the front page).+---## 5. MVP roadmapdiff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex e1468a21b5..83b1e38194 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -1972,6 +1972,14 @@ class ScreenContextConfig(BaseModel):#: A capture is also discarded on first use, whichever comes first.ttl_s: float = 120.0+ #: Seconds the mission deck shows the picture Jarvis just took, so the+ #: user can see what was looked at. A separate in-memory copy of ONE frame+ #: (``jarvis/screen_context/last_frame.py``), gone after this budget; the+ #: model's single-use handle above is unaffected. ``0`` switches the+ #: preview off. Read by ``ScreenContextService`` and served by+ #: ``GET /api/deck/frame``.+ deck_preview_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.diff --git a/jarvis/screen_context/last_frame.py b/jarvis/screen_context/last_frame.pynew file mode 100644index 0000000000..622e89149b--- /dev/null+++ b/jarvis/screen_context/last_frame.py@@ -0,0 +1,144 @@+"""The deck's picture of the last capture — one frame, briefly, then gone.++``ScreenContextService`` is built on "one capture, then gone": a finished+capture lives in a single-use handle and is removed on first consume or on+TTL. That contract is right for the *model's* copy of the screen and stays+untouched here.++This module is a second, deliberately narrower promise for the *user's* own+eyes: the mission deck shows the picture Jarvis just took, so the person at+the keyboard can see what was looked at (maintainer decision 2026-08-17). It+holds AT MOST ONE frame, only in memory, and drops it after+``ScreenContextSettings.deck_preview_s`` seconds — the same budget as an+unconsumed handle by default. There is no history, no disk, and a TTL of+``0`` switches the mirror off entirely.++Nothing here captures anything. The only way a frame arrives is the service+handing over the bytes it already produced for a capture the user asked for.+"""++from __future__ import annotations++import threading+import time+from dataclasses import dataclass+++@dataclass(frozen=True, slots=True)+class LastFrame:+ """One captured picture with the metadata the deck shows next to it."""++ #: Monotonic per-process counter — the deck refetches when it changes.+ seq: int+ image: bytes+ mime: str+ width: int+ height: int+ #: Which path produced it (``"screen_context"`` today; kept as a string so+ #: a second producer does not need a schema change).+ source: str+ #: What was captured, already scrubbed by the service (window title or+ #: monitor label). Never raw text from the screen.+ target_label: str+ trace_id: str+ captured_at_ns: int+ expires_at_ns: int+++class LastFrameMirror:+ """Thread-safe holder for the most recent frame, with a hard TTL.++ ``get`` is the only reader and it enforces expiry itself, so a frame that+ outlived its budget is dropped on the next look rather than by a timer —+ there is no background task to leak, and a process that never asks again+ simply keeps one stale byte string until the next ``set`` replaces it.+ """++ def __init__(+ self,+ *,+ ttl_s: float = 120.0,+ clock=time.time_ns,+ ) -> None:+ self._ttl_s = max(0.0, float(ttl_s))+ self._clock = clock+ self._lock = threading.Lock()+ self._frame: LastFrame | None = None+ self._seq = 0++ @property+ def ttl_s(self) -> float:+ return self._ttl_s++ @property+ def enabled(self) -> bool:+ return self._ttl_s > 0++ def set_ttl(self, ttl_s: float) -> None:+ """Adopt a new budget; ``0`` switches the mirror off and clears it."""+ with self._lock:+ self._ttl_s = max(0.0, float(ttl_s))+ if self._ttl_s == 0:+ self._frame = None++ def set(+ self,+ image: bytes,+ *,+ mime: str,+ width: int,+ height: int,+ source: str,+ target_label: str = "",+ trace_id: str = "",+ ) -> int:+ """Replace the held frame. Returns the new ``seq``, or 0 when off.++ A disabled mirror stores nothing and returns 0 rather than raising:+ the service calls this on the capture path, and a preference must not+ turn into an exception there.+ """+ with self._lock:+ if self._ttl_s <= 0:+ return 0+ now = self._clock()+ self._seq += 1+ self._frame = LastFrame(+ seq=self._seq,+ image=bytes(image),+ mime=mime,+ width=int(width),+ height=int(height),+ source=source,+ target_label=target_label,+ trace_id=trace_id,+ captured_at_ns=now,+ expires_at_ns=now + int(self._ttl_s * 1_000_000_000),+ )+ return self._seq++ def get(self) -> LastFrame | None:+ """The held frame, or ``None`` when there is none or it has expired."""+ with self._lock:+ frame = self._frame+ if frame is None:+ return None+ if self._clock() >= frame.expires_at_ns:+ self._frame = None+ return None+ return frame++ def clear(self) -> None:+ with self._lock:+ self._frame = None+++_mirror = LastFrameMirror()+++def get_last_frame_mirror() -> LastFrameMirror:+ """The process-wide mirror the deck route reads from."""+ return _mirror+++__all__ = ["LastFrame", "LastFrameMirror", "get_last_frame_mirror"]diff --git a/jarvis/screen_context/service.py b/jarvis/screen_context/service.pyindex 44383a5fef..976216053f 100644--- a/jarvis/screen_context/service.py+++ b/jarvis/screen_context/service.py@@ -37,6 +37,7 @@ from uuid import UUID, uuid4from jarvis.screen_context import intent as intent_modulefrom jarvis.screen_context import redaction, uitext+from jarvis.screen_context.last_frame import LastFrameMirror, get_last_frame_mirrorfrom jarvis.screen_context.models import (CaptureTarget,Degradation,@@ -99,6 +100,10 @@ class ScreenContextSettings:max_text_chars: int = 4000#: Seconds an unconsumed capture stays in memory.ttl_s: float = 120.0+ #: Seconds the mission deck may show the picture that was just taken. This+ #: is a separate, user-facing copy (see ``last_frame.py``): one frame, in+ #: memory only. ``0`` switches that preview off.+ deck_preview_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.@@ -167,11 +172,17 @@ class ScreenContextService:ui_text_reader: Any | None = None,permission_probe: Any | None = None,clock: Any | None = None,+ last_frame_mirror: LastFrameMirror | None = None,) -> None:self._settings = settings or ScreenContextSettings()self._bus = Noneif bus is not None:self.bind_bus(bus)+ # The deck's copy of the last picture. Injected in tests; the shared+ # process-wide mirror otherwise. It adopts THIS service's budget so a+ # settings change (or `0` = off) takes effect on the next capture.+ self._last_frame = last_frame_mirror or get_last_frame_mirror()+ self._last_frame.set_ttl(self._settings.deck_preview_s)# 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.@@ -607,6 +618,7 @@ class ScreenContextService:),)await self._publish_completed(context, trace_id=event_trace_id)+ self._mirror_for_deck(context, trace_id=event_trace_id)log.info("screen_context: %s", context.describe())return CaptureOutcome(status="captured",@@ -953,11 +965,36 @@ class ScreenContextService:return countdef close(self) -> int:- """Reject in-flight stores and remove every pixel held by this instance."""+ """Reject in-flight stores and remove every pixel held by this instance.++ The deck's mirror goes with it: a settings change that tightens the+ privacy rules must not leave the previous picture on the front page.+ """with self._handle_lock:self._closed = True+ self._last_frame.clear()return self.discard_all()+ def _mirror_for_deck(self, context: ScreenContext, *, trace_id: UUID) -> None:+ """Hand the finished, already-redacted picture to the deck's mirror.++ Best effort and outside the capture contract: the handle above is the+ model's copy and is unaffected. The label is the same scrubbed one the+ receipt event carries — never a raw window title.+ """+ try:+ self._last_frame.set(+ context.image,+ mime=context.mime,+ width=context.size[0],+ height=context.size[1],+ source="screen_context",+ target_label=_safe_target_label(context.target),+ trace_id=str(trace_id),+ )+ except Exception: # noqa: BLE001 - a preview must never fail the capture+ log.warning("screen_context: deck preview mirror failed", exc_info=True)+@propertydef held_count(self) -> int:with self._handle_lock:@@ -1167,6 +1204,7 @@ def settings_from_config(cfg: Any) -> ScreenContextSettings:),max_text_chars=int(getattr(block, "max_text_chars", 4000)),ttl_s=float(getattr(block, "ttl_s", 120.0)),+ deck_preview_s=float(getattr(block, "deck_preview_s", 120.0)),ocr_enabled=bool(getattr(block, "ocr_enabled", False)),main_monitor=main_monitor,)diff --git a/jarvis/ui/web/deck_routes.py b/jarvis/ui/web/deck_routes.pynew file mode 100644index 0000000000..e31f0ec606--- /dev/null+++ b/jarvis/ui/web/deck_routes.py@@ -0,0 +1,123 @@+"""REST API for the mission deck — the pictures it shows next to its numbers.++Endpoints (mounted by the WebServer in ``_build_app()``):++ GET /api/deck/frame → the last Screen-Context picture (bytes).+ GET /api/deck/frame/meta → whether one is held, and its shape.+ GET /api/deck/cu-frame/{sha} → one Computer-Use frame from the flight+ recorder, addressed by content hash.++Two producers, two shapes, one reason: the deck shows the user what Jarvis+just looked at.++* The Screen-Context picture comes from+ :mod:`jarvis.screen_context.last_frame` — at most one frame, in memory,+ gone after ``[screen_context].deck_preview_s`` seconds. The route never+ captures; it only serves what the service already produced for a capture+ the user asked for.+* Computer-Use frames are ALREADY on disk: the harness stores every+ observation under ``data/flight_recorder/blobs/<sha256>.<ext>`` for replay,+ and ``ObservationCaptured`` carries that hash. Serving by hash — validated+ as 64 hex characters, joined onto the fixed blob directory — is how the+ route stays traversal-proof without ever accepting a path.++Every response is ``Cache-Control: no-store``: a picture of the screen must+not outlive its budget in a browser cache either.+"""++from __future__ import annotations++import logging+import re+from pathlib import Path+from typing import Any++from fastapi import APIRouter, HTTPException, Response++from jarvis.screen_context.last_frame import get_last_frame_mirror++log = logging.getLogger(__name__)++router = APIRouter(prefix="/api/deck", tags=["deck"])++#: The Computer-Use harness writes here (``jarvis/cu/engine.py``) — the same+#: constant, not a lookup, so a moved recorder shows up as a test failure+#: rather than a route that silently serves nothing.+CU_BLOB_DIR = Path("data") / "flight_recorder" / "blobs"++_SHA256_RE = re.compile(r"^[0-9a-f]{64}$")+_NO_STORE = {"Cache-Control": "no-store"}+_CU_EXTENSIONS = (".jpg", ".png")+_MIME_BY_SUFFIX = {".jpg": "image/jpeg", ".png": "image/png"}++[email protected]("/frame/meta", summary="Whether a Screen-Context picture is held")+def frame_meta() -> dict[str, Any]:+ """Shape of the held picture, or ``available: false``.++ Cheap on purpose — the deck polls this after a ``ScreenCaptureCompleted``+ event and only fetches bytes when ``seq`` moved.+ """+ frame = get_last_frame_mirror().get()+ if frame is None:+ return {"available": False, "seq": 0}+ return {+ "available": True,+ "seq": frame.seq,+ "width": frame.width,+ "height": frame.height,+ "mime": frame.mime,+ "source": frame.source,+ "target_label": frame.target_label,+ "captured_at_ns": frame.captured_at_ns,+ "expires_at_ns": frame.expires_at_ns,+ }++[email protected]("/frame", summary="The last Screen-Context picture")+def frame() -> Response:+ """The held picture as bytes, or 404 when none is held (or it expired)."""+ held = get_last_frame_mirror().get()+ if held is None:+ raise HTTPException(status_code=404, detail="no_frame")+ return Response(+ content=held.image,+ media_type=held.mime,+ headers={+ **_NO_STORE,+ "X-Frame-Seq": str(held.seq),+ "X-Frame-Width": str(held.width),+ "X-Frame-Height": str(held.height),+ "X-Frame-Source": held.source,+ },+ )++[email protected]("/cu-frame/{sha}", summary="One Computer-Use frame, by content hash")+def cu_frame(sha: str) -> Response:+ """A recorded Computer-Use observation from the flight recorder.++ 404 covers both "never recorded" and "already pruned by the retention+ sweep" — the deck treats them the same (show nothing, keep going).+ """+ if not _SHA256_RE.match(sha):+ # A hash is the ONLY accepted key. Anything else — a filename, a+ # path, a shorter digest — is refused before it touches the filesystem.+ raise HTTPException(status_code=400, detail="invalid_hash")+ for ext in _CU_EXTENSIONS:+ candidate = CU_BLOB_DIR / f"{sha}{ext}"+ if candidate.is_file():+ try:+ data = candidate.read_bytes()+ except OSError:+ log.debug("deck: cu frame %s unreadable", sha, exc_info=True)+ break+ return Response(+ content=data,+ media_type=_MIME_BY_SUFFIX[ext],+ headers=_NO_STORE,+ )+ raise HTTPException(status_code=404, detail="no_frame")+++__all__ = ["router", "CU_BLOB_DIR"]diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex 08c2ab6893..c159bfae4f 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -376,6 +376,7 @@ class WebServer:from .profile_routes import router as profile_routerfrom .provider_routes import router as provider_routerfrom .review_routes import router as review_router+ from .deck_routes import router as deck_routerfrom .screen_context_routes import router as screen_context_routerfrom .self_mod_routes import router as self_mod_routerfrom .sessions_routes import router as sessions_router@@ -507,6 +508,9 @@ class WebServer:# machine with no display, so `jarvis api screen-context status` is a# valid capability probe everywhere.app.include_router(screen_context_router)+ # The mission deck's pictures: the last Screen-Context capture (one+ # frame, in memory, TTL) and Computer-Use frames by content hash.+ app.include_router(deck_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_last_frame.py b/tests/unit/screen_context/test_last_frame.pynew file mode 100644index 0000000000..5822afa4e8--- /dev/null+++ b/tests/unit/screen_context/test_last_frame.py@@ -0,0 +1,81 @@+"""The deck's mirror of the last capture: one frame, a TTL, and an off switch.++The mirror is a second, user-facing copy of a picture the service already+produced. What must hold: it never keeps more than one frame, it forgets on+its own after the budget, and a budget of zero means it keeps nothing at all —+the capture path calls ``set`` regardless and must not have to care.+"""++from __future__ import annotations++from jarvis.screen_context.last_frame import LastFrameMirror+++class _Clock:+ def __init__(self) -> None:+ self.now = 1_000_000_000++ def __call__(self) -> int:+ return self.now++ def advance_s(self, seconds: float) -> None:+ self.now += int(seconds * 1_000_000_000)+++def _mirror(ttl_s: float = 120.0) -> tuple[LastFrameMirror, _Clock]:+ clock = _Clock()+ return LastFrameMirror(ttl_s=ttl_s, clock=clock), clock+++def test_empty_mirror_holds_nothing():+ mirror, _ = _mirror()+ assert mirror.get() is None+++def test_set_then_get_returns_the_frame_with_a_moving_seq():+ mirror, _ = _mirror()+ seq1 = mirror.set(b"one", mime="image/jpeg", width=10, height=5, source="screen_context")+ seq2 = mirror.set(b"two", mime="image/jpeg", width=10, height=5, source="screen_context")++ assert (seq1, seq2) == (1, 2)+ held = mirror.get()+ assert held is not None+ # Only the newest frame survives — there is no history by construction.+ assert held.image == b"two"+ assert held.seq == 2+ assert (held.width, held.height, held.mime) == (10, 5, "image/jpeg")+++def test_frame_expires_after_the_budget():+ mirror, clock = _mirror(ttl_s=60)+ mirror.set(b"x", mime="image/png", width=1, height=1, source="screen_context")++ clock.advance_s(59)+ assert mirror.get() is not None+ clock.advance_s(2)+ # Expiry is enforced on read: no timer, no background task to leak.+ assert mirror.get() is None+ assert mirror.get() is None+++def test_zero_budget_switches_the_mirror_off():+ mirror, _ = _mirror(ttl_s=0)+ assert mirror.enabled is False+ # The capture path calls set() unconditionally; off must be a no-op, not+ # an exception, and it must report "nothing stored".+ assert mirror.set(b"x", mime="image/png", width=1, height=1, source="screen_context") == 0+ assert mirror.get() is None+++def test_lowering_the_budget_to_zero_drops_a_held_frame():+ mirror, _ = _mirror(ttl_s=120)+ mirror.set(b"x", mime="image/png", width=1, height=1, source="screen_context")+ mirror.set_ttl(0)+ assert mirror.get() is None+++def test_clear_forgets_immediately():+ mirror, _ = _mirror()+ mirror.set(b"x", mime="image/png", width=1, height=1, source="screen_context")+ mirror.clear()+ assert mirror.get() is Nonediff --git a/tests/unit/ui/web/test_deck_routes.py b/tests/unit/ui/web/test_deck_routes.pynew file mode 100644index 0000000000..3cf68fdfa6--- /dev/null+++ b/tests/unit/ui/web/test_deck_routes.py@@ -0,0 +1,111 @@+"""REST-route tests for the mission deck's pictures.++Three things must hold. The Screen-Context frame is served exactly as the+mirror holds it and disappears with it. The Computer-Use frame is addressed by+hash ONLY — a path, a filename or a short digest is refused before the+filesystem is touched, which is the whole traversal defence. And nothing is+cacheable: every image response says ``no-store``.+"""++from __future__ import annotations++from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.screen_context import last_frame as last_frame_module+from jarvis.screen_context.last_frame import LastFrameMirror+from jarvis.ui.web import deck_routes+++def mirror(monkeypatch: pytest.MonkeyPatch) -> LastFrameMirror:+ fresh = LastFrameMirror(ttl_s=120)+ monkeypatch.setattr(last_frame_module, "_mirror", fresh)+ return fresh+++def client() -> TestClient:+ app = FastAPI()+ app.include_router(deck_routes.router)+ return TestClient(app)+++def test_frame_404_when_nothing_is_held(client: TestClient, mirror: LastFrameMirror):+ assert client.get("/api/deck/frame").status_code == 404+ assert client.get("/api/deck/frame/meta").json() == {"available": False, "seq": 0}+++def test_frame_serves_the_held_picture_with_its_shape(client: TestClient, mirror: LastFrameMirror):+ mirror.set(+ b"\xff\xd8jpegbytes",+ mime="image/jpeg",+ width=1280,+ height=720,+ source="screen_context",+ target_label="Monitor 1",+ trace_id="abc",+ )++ meta = client.get("/api/deck/frame/meta").json()+ assert meta["available"] is True+ assert meta["seq"] == 1+ assert (meta["width"], meta["height"]) == (1280, 720)+ assert meta["target_label"] == "Monitor 1"++ res = client.get("/api/deck/frame")+ assert res.status_code == 200+ assert res.content == b"\xff\xd8jpegbytes"+ assert res.headers["content-type"].startswith("image/jpeg")+ assert res.headers["x-frame-seq"] == "1"+ assert res.headers["cache-control"] == "no-store"+++def test_frame_disappears_when_the_mirror_is_cleared(client: TestClient, mirror: LastFrameMirror):+ mirror.set(b"x", mime="image/png", width=1, height=1, source="screen_context")+ assert client.get("/api/deck/frame").status_code == 200+ mirror.clear()+ assert client.get("/api/deck/frame").status_code == 404+++ "bad",+ [+ "..%2F..%2Fetc%2Fpasswd",+ "abc",+ "A" * 64, # upper-case hex is not the recorder's spelling+ "0" * 63,+ "0" * 65,+ "not-a-hash.jpg",+ ],+)+def test_cu_frame_refuses_anything_that_is_not_a_hash(client: TestClient, bad: str):+ res = client.get(f"/api/deck/cu-frame/{bad}")+ assert res.status_code in (400, 404)+ # The important half: a refused key never names a real file, so the+ # message is the generic one, never an OS error with a path in it. An+ # encoded slash does not even reach the handler — the router turns it+ # away first ("Not Found"), which is the same outcome one layer earlier.+ assert res.json()["detail"] in ("invalid_hash", "no_frame", "Not Found")+++def test_cu_frame_serves_a_recorded_blob_by_hash(+ client: TestClient, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+):+ blob_dir = tmp_path / "blobs"+ blob_dir.mkdir()+ sha = "ab" * 32+ (blob_dir / f"{sha}.jpg").write_bytes(b"\xff\xd8cuframe")+ monkeypatch.setattr(deck_routes, "CU_BLOB_DIR", blob_dir)++ res = client.get(f"/api/deck/cu-frame/{sha}")+ assert res.status_code == 200+ assert res.content == b"\xff\xd8cuframe"+ assert res.headers["content-type"].startswith("image/jpeg")+ assert res.headers["cache-control"] == "no-store"++ # A hash the recorder never wrote (or already pruned) is a plain 404.+ assert client.get(f"/api/deck/cu-frame/{'cd' * 32}").status_code == 404