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(appshot): keep a lossless, colour-exact copy of every appshot

rubenluetke10-beep7b2268e7edea
diff --git a/jarvis/appshot/card_actions.py b/jarvis/appshot/card_actions.py
index 2239ed8b7a..a8e7dabf61 100644
--- a/jarvis/appshot/card_actions.py
+++ b/jarvis/appshot/card_actions.py
@@ -121,6 +121,25 @@ def save_to_downloads(png: bytes, *, folder: Path | None = None, now: float | No
return path
+def save_shot_to_downloads(
+ shot: Any, *, folder: Path | None = None, now: float | None = None
+) -> Path:
+ """Save an appshot's lossless copy; beside it the HDR one, when there is one.
+
+ ``appshot-….png`` is the 8-bit picture every viewer shows the same way;
+ ``appshot-…-hdr.png`` keeps the HDR monitor's full range for viewers that
+ read PNG colour tags (cICP). Returns the 8-bit file's path.
+ """
+ png = shot.original_png or as_png(shot.image)
+ where = {k: v for k, v in (("folder", folder), ("now", now)) if v is not None}
+ path = save_to_downloads(png, **where)
+ if shot.hdr_png:
+ hdr = path.with_name(f"{path.stem}-hdr.png")
+ if not hdr.exists():
+ hdr.write_bytes(shot.hdr_png)
+ return path
+
+
def _held(shot_id: str):
"""The card's appshot: by id when the card names one, else the last one."""
from jarvis.appshot.store import get_store # noqa: PLC0415
@@ -129,6 +148,13 @@ def _held(shot_id: str):
return store.get(shot_id) if shot_id else store.latest()
+async def _with_originals(shot: Any) -> Any:
+ """Wait for a lossless copy that is still encoding (a second at most)."""
+ from jarvis.appshot.service import finished # noqa: PLC0415
+
+ return await finished(shot)
+
+
async def run_card_action(action: str, shot_id: str = "") -> str:
"""Do ``copy``, ``save`` or ``copy_text`` on a card's appshot; the card's status line."""
from jarvis.core.config import load_config # noqa: PLC0415
@@ -147,14 +173,15 @@ async def run_card_action(action: str, shot_id: str = "") -> str:
ok = await asyncio.to_thread(write_text, text)
return labels["text_copied"] if ok else labels["failed"]
- png = await asyncio.to_thread(as_png, shot.image)
+ shot = await _with_originals(shot)
if action == "copy":
from jarvis.platform.clipboard_image import write_png # noqa: PLC0415
+ png = shot.original_png or await asyncio.to_thread(as_png, shot.image)
ok = await asyncio.to_thread(write_png, png)
return labels["copied"] if ok else labels["failed"]
if action == "save":
- path = await asyncio.to_thread(save_to_downloads, png)
+ path = await asyncio.to_thread(save_shot_to_downloads, shot)
log.info("appshot: card saved %s", path.name)
return labels["saved"]
except Exception: # noqa: BLE001 - the card says so; nothing else depends on it
diff --git a/jarvis/appshot/hdr_recording.py b/jarvis/appshot/hdr_recording.py
index 1f5357c0a5..99b99f4b6f 100644
--- a/jarvis/appshot/hdr_recording.py
+++ b/jarvis/appshot/hdr_recording.py
@@ -193,7 +193,7 @@ class HdrCapture:
try:
from PySide6.QtGui import QImage # noqa: PLC0415
- from jarvis.appshot.hdr_image import scrgb_to_srgb8 # noqa: PLC0415
+ from jarvis.platform.hdr_image import scrgb_to_srgb8 # noqa: PLC0415
frame = self._dup.read_linear()
x, y, w, h = self.crop
diff --git a/jarvis/appshot/library.py b/jarvis/appshot/library.py
index 66179e9035..92dd57b815 100644
--- a/jarvis/appshot/library.py
+++ b/jarvis/appshot/library.py
@@ -188,18 +188,28 @@ def save(shot: Appshot) -> bool:
"""Write a freshly taken appshot. Never raises; False when nothing was kept."""
try:
folder = _folder(shot.id)
- ext = _EXTENSIONS.get(shot.mime, "jpg")
+ # The lossless copy when there is one: full resolution, PNG, the
+ # monitor's colour profile. The model's JPEG is the fallback.
+ lossless = bool(shot.original_png)
+ image = shot.original_png if lossless else shot.image
+ mime = "image/png" if lossless else shot.mime
+ ext = _EXTENSIONS.get(mime, "jpg")
+ width, height = _png_size(image) if lossless else (shot.width, shot.height)
with _lock:
folder.mkdir(parents=True, exist_ok=True)
name = f"{_stem(shot.taken_at)}.{ext}"
- (folder / name).write_bytes(shot.image)
+ (folder / name).write_bytes(image)
meta = {
**_base_meta(shot),
"file": name,
- "mime": shot.mime,
- "width": shot.width,
- "height": shot.height,
+ "mime": mime,
+ "width": width,
+ "height": height,
}
+ if shot.hdr_png:
+ hdr_name = f"{_stem(shot.taken_at)}-hdr.png"
+ (folder / hdr_name).write_bytes(shot.hdr_png)
+ meta["hdr_file"] = hdr_name
_write_meta(folder, meta)
_prune()
return True
@@ -208,6 +218,13 @@ def save(shot: Appshot) -> bool:
return False
+def _png_size(png: bytes) -> tuple[int, int]:
+ """Width and height from a PNG's IHDR, without decoding it."""
+ import struct # noqa: PLC0415
+
+ return struct.unpack(">II", png[16:24])
+
+
def save_edit(shot: Appshot) -> bool:
"""Keep the user's edit beside its original. ``shot`` carries the edited PNG.
diff --git a/jarvis/appshot/markup.py b/jarvis/appshot/markup.py
index cdd3acb562..d204920ba9 100644
--- a/jarvis/appshot/markup.py
+++ b/jarvis/appshot/markup.py
@@ -22,7 +22,7 @@ import base64
import binascii
import io
import logging
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from typing import Any
log = logging.getLogger(__name__)
@@ -126,13 +126,7 @@ def apply_to_image(image: Any, markup: Markup) -> Any:
width, height = out.size
longer = max(width, height)
for hide in markup.hides:
- fx, fy, fw, fh = hide.rect
- box = (
- round(fx * width),
- round(fy * height),
- min(width, round((fx + fw) * width)),
- min(height, round((fy + fh) * height)),
- )
+ box = _hide_box(hide, (width, height))
if box[2] - box[0] < 1 or box[3] - box[1] < 1:
continue
patch = out.crop(box)
@@ -187,6 +181,24 @@ def _gradient(size: tuple[int, int], stops: tuple[str, ...]) -> Any:
return small.resize(size, Image.Resampling.BILINEAR)
+def _hide_box(hide: Hide, size: tuple[int, int]) -> tuple[int, int, int, int]:
+ width, height = size
+ fx, fy, fw, fh = hide.rect
+ return (
+ round(fx * width),
+ round(fy * height),
+ min(width, round((fx + fw) * width)),
+ min(height, round((fy + fh) * height)),
+ )
+
+
+def _frame_layout(size: tuple[int, int], frame: Frame) -> tuple[int, int]:
+ """``(margin, corner radius)`` of the background frame around a picture of ``size``."""
+ longer = max(size)
+ unit = max(1.0, longer / 1400.0)
+ return round(longer * frame.padding), round(frame.radius * unit)
+
+
def _framed(picture: Any, frame: Frame) -> Any:
"""``picture`` on its background, as the full editor's ``renderResult`` frames it."""
from PIL import Image, ImageDraw, ImageFilter # noqa: PLC0415
@@ -194,10 +206,7 @@ def _framed(picture: Any, frame: Frame) -> Any:
from jarvis.appshot.picker.markup_model import BACKGROUND_PRESETS # noqa: PLC0415
width, height = picture.size
- longer = max(width, height)
- pad = round(longer * frame.padding)
- unit = max(1.0, longer / 1400.0)
- radius = round(frame.radius * unit)
+ pad, radius = _frame_layout((width, height), frame)
stops = dict(BACKGROUND_PRESETS).get(frame.preset) or BACKGROUND_PRESETS[0][1]
canvas = _gradient((width + pad * 2, height + pad * 2), stops).convert("RGBA")
box = (pad, pad, pad + width, pad + height)
@@ -231,6 +240,45 @@ def apply_to_bytes(image: bytes, mime: str, markup: Markup) -> bytes:
return buffer.getvalue()
+def apply_to_scrgb(scrgb: Any, markup: Markup, sdr_white_nits: float) -> Any:
+ """An HDR master (scRGB) with the markings, ``float32 (h, w, 3)``.
+
+ The markings are drawn exactly as on the 8-bit picture and land at SDR
+ white, like any UI on an HDR desktop. Every pixel they did not touch —
+ and the picture inside a background frame — keeps its full-depth value.
+ Blur and pixelate patches are replaced as a whole, never mixed.
+ """
+ import numpy as np # noqa: PLC0415
+ from PIL import Image, ImageDraw # noqa: PLC0415
+
+ from jarvis.platform.hdr_image import scrgb_to_srgb8, srgb8_to_scrgb # noqa: PLC0415
+
+ base = np.asarray(scrgb)[..., :3].astype(np.float32)
+ height, width = base.shape[:2]
+ sdr = scrgb_to_srgb8(base, sdr_white_nits)
+ marked = np.asarray(apply_to_image(Image.fromarray(sdr), replace(markup, frame=None)))
+ changed = (marked != sdr).any(axis=-1)
+ for hide in markup.hides:
+ x0, y0, x1, y1 = _hide_box(hide, (width, height))
+ changed[y0:y1, x0:x1] = True
+ out = base.copy()
+ out[changed] = srgb8_to_scrgb(marked[changed], sdr_white_nits)
+ if markup.frame is None:
+ return out
+ canvas = srgb8_to_scrgb(
+ np.asarray(_framed(Image.fromarray(marked), markup.frame)), sdr_white_nits
+ )
+ pad, radius = _frame_layout((width, height), markup.frame)
+ mask = Image.new("L", (width, height), 0)
+ ImageDraw.Draw(mask).rounded_rectangle(
+ (0, 0, width - 1, height - 1), radius=radius, fill=255
+ )
+ inside = np.asarray(mask) == 255 # soft corner pixels keep the 8-bit blend
+ window = canvas[pad : pad + height, pad : pad + width]
+ window[inside] = out[inside]
+ return canvas
+
+
def apply_to_rgb(
size: tuple[int, int], rgb: bytes, markup: Markup
) -> tuple[tuple[int, int], bytes]:
@@ -248,6 +296,7 @@ __all__ = [
"Markup",
"apply_to_bytes",
"apply_to_image",
+ "apply_to_scrgb",
"apply_to_rgb",
"parse_markup",
]
diff --git a/jarvis/appshot/master.py b/jarvis/appshot/master.py
new file mode 100644
index 0000000000..ea025afa16
--- /dev/null
+++ b/jarvis/appshot/master.py
@@ -0,0 +1,63 @@
+"""The user's own copy of an appshot: full resolution, lossless, colour-exact.
+
+The picture a model sees is a downscaled JPEG (vision budget). The user's copy
+comes from :attr:`ScreenContext.master` — the same capture, redacted the same
+way — and is encoded here once the markings are known:
+
+* ``png`` — 8-bit, lossless, full resolution. On an SDR monitor it carries
+ the monitor's ICC profile, which is the exact description of its pixels.
+ On an HDR monitor it is the SDR rendition (SDR white = sRGB white): what
+ the clipboard, chat and every SDR viewer get.
+* ``hdr_png`` — only from an HDR or wide-gamut monitor: 16-bit BT.2020 PQ
+ with ``cICP``/``cLLi`` (:mod:`jarvis.platform.hdr_image`), which keeps the
+ highlights and the gamut the monitor showed.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any
+
+
+@dataclass(frozen=True, slots=True)
+class MasterFiles:
+ png: bytes = field(repr=False)
+ width: int
+ height: int
+ hdr_png: bytes | None = field(default=None, repr=False)
+
+
+def encode_master(master: Any, markup: Any = None) -> MasterFiles:
+ """PNG bytes for a :class:`~jarvis.screen_context.models.MasterImage`.
+
+ ``markup`` (:class:`jarvis.appshot.markup.Markup`) is burnt in exactly as
+ on the model's picture. Runs for a second or two on a 4K HDR frame — call
+ it off the event loop.
+ """
+ import numpy as np # noqa: PLC0415
+
+ from jarvis.platform import hdr_image # noqa: PLC0415
+
+ marked = markup is not None and not markup.empty
+ if master.hdr:
+ scrgb = np.asarray(master.pixels)
+ if marked:
+ from jarvis.appshot.markup import apply_to_scrgb # noqa: PLC0415
+
+ scrgb = apply_to_scrgb(scrgb, markup, master.sdr_white_nits)
+ sdr = hdr_image.scrgb_to_srgb8(scrgb, master.sdr_white_nits)
+ hdr_png = hdr_image.encode_png16(
+ hdr_image.scrgb_to_pq16(scrgb), light=hdr_image.light_levels(scrgb)
+ )
+ height, width = sdr.shape[:2]
+ return MasterFiles(hdr_image.encode_png8(sdr), width, height, hdr_png)
+ from PIL import Image # noqa: PLC0415
+
+ picture = Image.fromarray(np.asarray(master.pixels, dtype=np.uint8), "RGB")
+ if marked:
+ from jarvis.appshot.markup import apply_to_image # noqa: PLC0415
+
+ picture = apply_to_image(picture, markup)
+ return MasterFiles(
+ hdr_image.encode_png8(picture, master.icc_profile), picture.width, picture.height
+ )
diff --git a/jarvis/appshot/service.py b/jarvis/appshot/service.py
index f800654c80..486e5305bb 100644
--- a/jarvis/appshot/service.py
+++ b/jarvis/appshot/service.py
@@ -75,6 +75,7 @@ def shot_from_context(context: Any, *, trigger: str) -> Appshot:
ui_text=context.ui_text,
trigger=trigger,
taken_at=time.time(),
+ master=getattr(context, "master", None),
)
@@ -125,6 +126,7 @@ async def take_appshot(
verdict=IntentVerdict(intent=VisualIntent.SCREEN, evidence=("appshot-region",)),
trace_id=trace_id or uuid.uuid4(),
region=bbox,
+ master=True,
)
finally:
shutter_markup.reset(token)
@@ -132,6 +134,7 @@ async def take_appshot(
outcome = await service.capture(
verdict=IntentVerdict(intent=VisualIntent.WINDOW, evidence=("appshot",)),
trace_id=trace_id or uuid.uuid4(),
+ master=True,
)
if outcome.status != "captured" or outcome.context is None:
return AppshotResult(
@@ -154,7 +157,9 @@ async def take_appshot(
store = get_store()
store.remember(shot, keep_s=float(config.screen_context.deck_preview_s))
- await _keep_in_library(shot, config)
+ # The lossless copy encodes in the background: the model's picture and the
+ # card must not wait a second for a 4K HDR PNG. It then goes to the library.
+ _start_master(shot, selection.markup if selection is not None else None, config)
await _attach_to_card(shot, config)
delivered_to = "turn"
if deliver:
@@ -174,8 +179,10 @@ async def take_appshot(
delivered_to,
)
if selection is not None and selection.action != "done":
- await _finish_action(selection.action, shot, bus)
- return AppshotResult(status="captured", shot=replace(shot, delivered_to=delivered_to))
+ await _finish_action(selection.action, await finished(shot), bus)
+ return AppshotResult(
+ status="captured", shot=replace(shot, delivered_to=delivered_to, master=None)
+ )
def _language(config: Any) -> str:
@@ -207,20 +214,70 @@ def _image_size(image: bytes) -> tuple[int, int]:
return picture.size
+#: Lossless copies still encoding, by appshot id.
+_MASTERS: dict[str, asyncio.Task[Appshot]] = {}
+
+
+def _start_master(shot: Appshot, markup: Any, config: Any) -> None:
+ """Encode the lossless copy, swap it into the store, then keep it in the library."""
+ if shot.master is None:
+ task = asyncio.create_task(_keep_without_master(shot, config))
+ else:
+ task = asyncio.create_task(_encode_master(shot, markup, config))
+ _MASTERS[shot.id] = task
+ task.add_done_callback(lambda _done, shot_id=shot.id: _MASTERS.pop(shot_id, None))
+
+
+async def _keep_without_master(shot: Appshot, config: Any) -> Appshot:
+ await _keep_in_library(shot, config)
+ return shot
+
+
+async def _encode_master(shot: Appshot, markup: Any, config: Any) -> Appshot:
+ from jarvis.appshot.master import encode_master # noqa: PLC0415
+
+ try:
+ files = await asyncio.to_thread(encode_master, shot.master, markup)
+ shot = replace(
+ shot, original_png=files.png, hdr_png=files.hdr_png or b"", master=None
+ )
+ except Exception: # noqa: BLE001 - the model's picture is still kept and shown
+ log.warning("appshot: the lossless copy could not be made", exc_info=True)
+ shot = replace(shot, master=None)
+ get_store().update(shot)
+ await _keep_in_library(shot, config)
+ return shot
+
+
+async def finished(shot: Appshot) -> Appshot:
+ """``shot`` with its lossless copy, waiting for it when it is still encoding."""
+ task = _MASTERS.get(shot.id)
+ if task is not None:
+ try:
+ return await asyncio.shield(task)
+ except Exception: # noqa: BLE001 - fall back to the picture we have
+ log.debug("appshot: lossless copy unavailable", exc_info=True)
+ held = get_store().get(shot.id)
+ return held if held is not None else replace(shot, master=None)
+
+
async def _finish_action(action: str, shot: Appshot, bus: Any | None) -> None:
"""Copy, save or open the appshot, as the picker's toolbar asked."""
try:
if action in ("copy", "save"):
- from jarvis.appshot.card_actions import as_png, save_to_downloads # noqa: PLC0415
+ from jarvis.appshot.card_actions import ( # noqa: PLC0415
+ as_png,
+ save_shot_to_downloads,
+ )
- png = await asyncio.to_thread(as_png, shot.image)
if action == "copy":
from jarvis.platform.clipboard_image import write_png # noqa: PLC0415
+ png = shot.original_png or await asyncio.to_thread(as_png, shot.image)
if not await asyncio.to_thread(write_png, png):
log.warning("appshot: the area could not be copied to the clipboard")
else:
- path = await asyncio.to_thread(save_to_downloads, png)
+ path = await asyncio.to_thread(save_shot_to_downloads, shot)
log.info("appshot: area saved as %s", path.name)
elif action == "edit":
from jarvis.appshot.editor_window import open_editor_window # noqa: PLC0415
diff --git a/jarvis/appshot/store.py b/jarvis/appshot/store.py
index 7fc69e0f90..f0c04d3d41 100644
--- a/jarvis/appshot/store.py
+++ b/jarvis/appshot/store.py
@@ -18,7 +18,8 @@ from __future__ import annotations
import threading
import time
-from dataclasses import dataclass, replace
+from dataclasses import dataclass, field, replace
+from typing import Any
#: How many appshots stay at hand — as many as the corner card stack shows.
MAX_RECENT = 5
@@ -46,6 +47,13 @@ class Appshot:
#: Wall-clock seconds.
taken_at: float
delivered_to: str = ""
+ #: The user's lossless copy (:mod:`jarvis.appshot.master`): the
+ #: full-resolution 8-bit PNG, and a 16-bit HDR PNG when the monitor ran
+ #: HDR. Empty until encoded, and for pictures that had no master.
+ original_png: bytes = field(default=b"", repr=False)
+ hdr_png: bytes = field(default=b"", repr=False)
+ #: The raw master on its way to those files; dropped once they exist.
+ master: Any = field(default=None, repr=False, compare=False)
def meta(self) -> dict[str, object]:
"""What the app may show about it — no pixels."""
@@ -128,13 +136,34 @@ class AppshotStore:
if index is None:
return None
shot, until = recent[index]
- edited = replace(shot, image=image, mime=mime, width=width, height=height)
+ # The edit supersedes the lossless copies of the unedited picture.
+ edited = replace(
+ shot, image=image, mime=mime, width=width, height=height,
+ original_png=b"", hdr_png=b"",
+ )
recent[index] = (edited, until)
pending = self._live_pending()
if pending is not None and pending.id == shot_id:
- self._pending = replace(pending, image=image, mime=mime, width=width, height=height)
+ self._pending = replace(
+ pending, image=image, mime=mime, width=width, height=height,
+ original_png=b"", hdr_png=b"",
+ )
return edited
+ def update(self, shot: Appshot) -> None:
+ """Swap in a newer version of a held appshot, keeping its place and expiry."""
+ with self._lock:
+ for index, (held, until) in enumerate(self._recent):
+ if held.id == shot.id:
+ self._recent[index] = (
+ replace(shot, delivered_to=held.delivered_to or shot.delivered_to),
+ until,
+ )
+ if self._pending is not None and self._pending.id == shot.id:
+ self._pending = replace(
+ shot, delivered_to=self._pending.delivered_to or shot.delivered_to
+ )
+
def mark_delivered(self, shot_id: str, delivered_to: str) -> None:
with self._lock:
for index, (shot, until) in enumerate(self._recent):
diff --git a/jarvis/platform/hdr_grab.py b/jarvis/platform/hdr_grab.py
new file mode 100644
index 0000000000..34e24ecaf0
--- /dev/null
+++ b/jarvis/platform/hdr_grab.py
@@ -0,0 +1,97 @@
+"""One full-depth still of a desktop rectangle, when the monitor needs it.
+
+:func:`grab_extended` answers a screenshot request for a rectangle in capture
+coordinates (physical pixels, the space mss and Screen Context use). When the
+rectangle lies on ONE monitor that runs HDR or a wide colour gamut, it returns
+the rectangle as scRGB (``float16``, linear, 1.0 = 80 nits) plus what is
+needed to tag it. Anything else — an SDR monitor, a rectangle across two
+monitors, macOS/Linux, a duplication failure — returns ``None`` and the
+caller keeps its 8-bit grab. Never raises.
+"""
+
+from __future__ import annotations
+
+import logging
+import sys
+import time
+from dataclasses import dataclass, field
+from typing import Any
+
+log = logging.getLogger(__name__)
+
+#: How long to wait for Windows to present a frame before nudging a repaint.
+_FIRST_WAIT_MS = 120
+_AFTER_NUDGE_MS = 600
+
+
+@dataclass(frozen=True, slots=True)
+class ExtendedFrame:
+ #: scRGB pixels of the rectangle, ``float16 (h, w, 4)``.
+ pixels: Any = field(repr=False)
+ #: Brightness of SDR white on that monitor (Windows "SDR content brightness").
+ sdr_white_nits: float
+ #: ``"hdr"`` or ``"wcg"``.
+ mode: str
+ #: Peak luminance the monitor reports, for metadata; 0 when unknown.
+ max_nits: float = 0.0
+
+
+def grab_extended(bbox: tuple[int, int, int, int]) -> ExtendedFrame | None:
+ """``bbox`` = ``(left, top, width, height)`` in physical desktop pixels."""
+ if sys.platform != "win32":
+ return None
+ try:
+ return _grab_windows(bbox)
+ except Exception: # noqa: BLE001 - the 8-bit grab is always the fallback
+ log.info("full-depth capture unavailable; using the 8-bit grab", exc_info=True)
+ return None
+
+
+def _grab_windows(bbox: tuple[int, int, int, int]) -> ExtendedFrame | None:
+ from jarvis.platform.display_color import device_at, display_color # noqa: PLC0415
+ from jarvis.platform.win_duplication import ( # noqa: PLC0415
+ DesktopDuplication,
+ DuplicationUnavailable,
+ )
+
+ left, top, width, height = (int(v) for v in bbox)
+ if width <= 0 or height <= 0:
+ return None
+ device = device_at((left + width // 2, top + height // 2))
+ colour = display_color(device)
+ if not device or not colour.extended:
+ return None
+ with DesktopDuplication(device) as dup:
+ out_left, out_top, out_right, out_bottom = dup.info.rect
+ if (
+ left < out_left or top < out_top
+ or left + width > out_right or top + height > out_bottom
+ ):
+ return None # spans monitors: one duplication cannot hold it
+ try:
+ dup.wait_first_frame(_FIRST_WAIT_MS)
+ except DuplicationUnavailable:
+ # A still desktop presents nothing. A repaint of the front window
+ # makes Windows compose one frame without changing what is shown.
+ _nudge_repaint()
+ dup.wait_first_frame(_AFTER_NUDGE_MS)
+ frame = dup.read_linear()
+ x, y = left - out_left, top - out_top
+ pixels = frame[y : y + height, x : x + width].copy()
+ return ExtendedFrame(
+ pixels=pixels,
+ sdr_white_nits=colour.sdr_white_nits,
+ mode=colour.mode,
+ max_nits=dup.info.max_nits,
+ )
+
+
+def _nudge_repaint() -> None:
+ import ctypes # noqa: PLC0415
+
+ user32 = ctypes.WinDLL("user32")
+ hwnd = user32.GetForegroundWindow()
+ if hwnd:
+ # RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN | RDW_UPDATENOW
+ user32.RedrawWindow(hwnd, None, None, 0x0001 | 0x0400 | 0x0080 | 0x0100)
+ time.sleep(0.016)
diff --git a/jarvis/appshot/hdr_image.py b/jarvis/platform/hdr_image.py
similarity index 100%
rename from jarvis/appshot/hdr_image.py
rename to jarvis/platform/hdr_image.py
diff --git a/jarvis/platform/win_duplication.py b/jarvis/platform/win_duplication.py
index bae9b65d47..9e4baa9f22 100644
--- a/jarvis/platform/win_duplication.py
+++ b/jarvis/platform/win_duplication.py
@@ -403,8 +403,14 @@ class DesktopDuplication:
self._pointer_tex: _Com | None = None
self._p010: dict[str, Any] = {}
self._shader: _Com | None = None
+ from jarvis.core.win32_dpi import per_monitor_dpi_context # noqa: PLC0415
+
try:
- self._open(device_name)
+ # Physical pixels throughout: output rectangles then match the
+ # capture coordinates mss uses, and DuplicateOutput1 refuses a
+ # DPI-unaware thread.
+ with per_monitor_dpi_context():
+ self._open(device_name)
except BaseException:
self.close()
raise
@@ -415,8 +421,6 @@ class DesktopDuplication:
return obj
def _open(self, device_name: str | None) -> None:
- from jarvis.core.win32_dpi import per_monitor_dpi_context # noqa: PLC0415
-
dxgi = ctypes.WinDLL("dxgi")
d3d11 = ctypes.WinDLL("d3d11")
factory_ptr = _out()
@@ -441,12 +445,10 @@ class DesktopDuplication:
self.info = info
formats = (ctypes.c_uint32 * 1)(_DXGI_FORMAT_R16G16B16A16_FLOAT)
dup = _out()
- # DuplicateOutput1 refuses a DPI-unaware thread.
- with per_monitor_dpi_context():
- hr = self._output5.call(
- _OUTPUT5_DUPLICATE_OUTPUT1, ctypes.c_void_p(self._device.ptr),
- ctypes.c_uint(0), ctypes.c_uint(1), formats, ctypes.byref(dup),
- )
+ hr = self._output5.call(
+ _OUTPUT5_DUPLICATE_OUTPUT1, ctypes.c_void_p(self._device.ptr),
+ ctypes.c_uint(0), ctypes.c_uint(1), formats, ctypes.byref(dup),
+ )
if hr < 0:
_raise(hr, "DuplicateOutput1")
self._dup = _Com(dup.value)
diff --git a/jarvis/screen_context/models.py b/jarvis/screen_context/models.py
index 8ca58a1ecd..88e71e79b1 100644
--- a/jarvis/screen_context/models.py
+++ b/jarvis/screen_context/models.py
@@ -18,6 +18,7 @@ from __future__ import annotations
from dataclasses import dataclass, field
from enum import StrEnum
+from typing import Any
# --------------------------------------------------------------------------
# Intent
@@ -249,6 +250,27 @@ class Degradation:
# --------------------------------------------------------------------------
+@dataclass(frozen=True, slots=True)
+class MasterImage:
+ """The same capture at full fidelity, for the user's own copy — never a model's.
+
+ Asked for with ``capture(master=True)`` (appshots). Redacted exactly like
+ :attr:`ScreenContext.image`, at the raw frame's size, before any
+ downscale or JPEG. ``pixels`` is ``uint8 (h, w, 3)`` sRGB for an SDR
+ monitor, or ``float16 (h, w, 4)`` scRGB (linear, 1.0 = 80 nits) when the
+ monitor ran HDR or a wide gamut.
+ """
+
+ pixels: Any = field(repr=False, compare=False)
+ hdr: bool = False
+ #: Brightness of SDR white on the captured monitor (HDR captures).
+ sdr_white_nits: float = 80.0
+ #: The monitor's ICC profile (SDR captures), when the OS has one.
+ icc_profile: bytes | None = field(default=None, repr=False)
+ #: Peak luminance the monitor reports (HDR captures); 0 when unknown.
+ max_nits: float = 0.0
+
+
@dataclass(frozen=True, slots=True)
class ScreenContext:
"""One capture, redacted, ready to hand to a conversation turn.
@@ -271,6 +293,9 @@ class ScreenContext:
redactions: RedactionReport = field(default_factory=RedactionReport)
degradations: tuple[Degradation, ...] = ()
captured_at_ns: int = 0
+ #: Full-fidelity copy for the user (appshots only); never stored behind a
+ #: handle and never sent to a model.
+ master: MasterImage | None = field(default=None, repr=False, compare=False)
@property
def byte_size(self) -> int:
@@ -301,6 +326,7 @@ __all__ = [
"Degradation",
"DegradationCode",
"IntentVerdict",
+ "MasterImage",
"RedactionHit",
"RedactionReport",
"RedactionRule",
diff --git a/jarvis/screen_context/service.py b/jarvis/screen_context/service.py
index a021eb9ad8..f0acb098f2 100644
--- a/jarvis/screen_context/service.py
+++ b/jarvis/screen_context/service.py
@@ -32,7 +32,7 @@ import math
import secrets
import threading
import time
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from typing import Any, Literal
from uuid import UUID, uuid4
@@ -44,6 +44,7 @@ from jarvis.screen_context.models import (
Degradation,
DegradationCode,
IntentVerdict,
+ MasterImage,
ScreenContext,
TargetKind,
TargetReason,
@@ -347,12 +348,16 @@ class ScreenContextService:
verdict: IntentVerdict | None = None,
trace_id: UUID | None = None,
region: tuple[int, int, int, int] | None = None,
+ master: bool = False,
) -> CaptureOutcome:
"""Take exactly one capture. Assumes intent is already established.
``region`` is a rectangle the user selected by hand, in capture
coordinates (``displays.monitors()``). It replaces cursor/window
targeting; permissions, the denylist and redaction apply unchanged.
+ ``master`` also returns :attr:`ScreenContext.master`, the user's
+ full-fidelity copy (HDR at full depth on an HDR monitor), redacted the
+ same way. It rides on the outcome only, never behind the handle.
"""
verdict = verdict or IntentVerdict(intent=VisualIntent.SCREEN)
if self._closed:
@@ -544,7 +549,11 @@ class ScreenContextService:
message=monitor_privacy_error,
)
try:
- size, rgb = await self._grab(target)
+ master_image = None
+ if master:
+ size, rgb, master_image = await self._grab_with_master(target)
+ else:
+ size, rgb = await self._grab(target)
except CaptureUnavailable as exc:
log.info("screen_context: capture failed — %s", exc)
return CaptureOutcome(
@@ -604,6 +613,7 @@ class ScreenContextService:
rgb=rgb,
degradations=degradations,
expected_window_handle=window_handle,
+ master=master_image,
)
if self._closed:
@@ -618,7 +628,9 @@ class ScreenContextService:
),
)
try:
- handle_id = self.store(context)
+ # The handle keeps the model's copy only; the master is large
+ # and belongs to this one caller.
+ handle_id = self.store(replace(context, master=None))
except RuntimeError:
return CaptureOutcome(
status="refused",
@@ -675,6 +687,47 @@ class ScreenContextService:
)
return size, rgb
+ async def _grab_with_master(
+ self, target: CaptureTarget
+ ) -> tuple[tuple[int, int], bytes, MasterImage]:
+ """One shutter for both copies: the model's 8-bit frame and the user's master.
+
+ On an HDR or wide-gamut monitor the rectangle is read once at full
+ depth and the 8-bit frame is DERIVED from it (SDR white = sRGB white),
+ so both show the same instant and redaction boxes line up exactly.
+ The privacy path (a denylisted window in the rectangle) and every
+ other monitor keep the normal grab; the master is then that frame
+ plus the monitor's ICC profile.
+ """
+ from jarvis.platform.display_color import display_color # noqa: PLC0415
+ from jarvis.platform.hdr_grab import grab_extended # noqa: PLC0415
+ from jarvis.platform.hdr_image import scrgb_to_srgb8 # noqa: PLC0415
+
+ rect_grab = target.window_handle is None or not await asyncio.to_thread(
+ self._rect_privacy_error, target.bbox
+ )
+ if rect_grab:
+ frame = await asyncio.to_thread(grab_extended, target.bbox)
+ if frame is not None:
+ rgb8 = await asyncio.to_thread(
+ scrgb_to_srgb8, frame.pixels, frame.sdr_white_nits
+ )
+ height, width = rgb8.shape[:2]
+ return (width, height), rgb8.tobytes(), MasterImage(
+ pixels=frame.pixels,
+ hdr=True,
+ sdr_white_nits=frame.sdr_white_nits,
+ max_nits=frame.max_nits,
+ )
+ size, rgb = await self._grab(target)
+ left, top, width, height = target.bbox
+ colour = await asyncio.to_thread(
+ display_color,
+ target.monitor_name or None,
+ point=(left + width // 2, top + height // 2),
+ )
+ return size, rgb, MasterImage(pixels=None, icc_profile=colour.icc_profile)
+
def _rect_privacy_error(self, bbox: tuple[int, int, int, int]) -> str | None:
"""Refuse a desktop-rectangle grab a denylisted window could appear in."""
if not self._settings.denylist:
@@ -738,6 +791,7 @@ class ScreenContextService:
rgb: bytes,
degradations: list[Degradation],
expected_window_handle: int | None,
+ master: MasterImage | None = None,
) -> ScreenContext:
"""Read text, redact pixels and text, encode. In that order.
@@ -854,6 +908,10 @@ class ScreenContextService:
text_hits = text_hits + ocr_hits
text_source = "ocr" if text_source == "none" else "accessibility+ocr"
+ if master is not None:
+ master = await asyncio.to_thread(
+ _redacted_master, master, image, (*region_hits, *ocr_region_hits)
+ )
image_bytes, encoded_size = _encode(image)
return ScreenContext(
@@ -870,6 +928,7 @@ class ScreenContextService:
),
degradations=tuple(degradations),
captured_at_ns=self._wall_clock(),
+ master=master,
)
def _foreground_still_matches(
@@ -1209,6 +1268,30 @@ def _safe_target_label(target: CaptureTarget) -> str:
return f"monitor {target.monitor_name}" if target.monitor_name else "selected monitor"
+def _redacted_master(master: MasterImage, redacted: Any, hits: Any) -> MasterImage:
+ """The master with the same black boxes as the model's frame, at the same pixels.
+
+ An SDR master IS the redacted raw frame. An HDR master gets every hit's
+ region filled with black (scRGB 0) — the boxes were found on the frame
+ derived from it, so they cover the same content.
+ """
+ import numpy as np # noqa: PLC0415
+
+ if not master.hdr:
+ return replace(master, pixels=np.asarray(redacted.convert("RGB")).copy())
+ pixels = np.array(master.pixels, copy=True)
+ height, width = pixels.shape[:2]
+ for hit in hits:
+ if hit.region is None:
+ continue
+ left, top, w, h = hit.region
+ x0, y0 = max(0, int(left)), max(0, int(top))
+ x1, y1 = min(width, int(left + w)), min(height, int(top + h))
+ if x1 > x0 and y1 > y0:
+ pixels[y0:y1, x0:x1, :3] = 0
+ return replace(master, pixels=pixels)
+
+
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
diff --git a/tests/unit/appshot/test_appshot_core.py b/tests/unit/appshot/test_appshot_core.py
index b0ec8dc842..51b3b3b2d6 100644
--- a/tests/unit/appshot/test_appshot_core.py
+++ b/tests/unit/appshot/test_appshot_core.py
@@ -313,7 +313,7 @@ class FakeCaptureService:
self.consumed: list[str] = []
self.verdicts: list[IntentVerdict] = []
- async def capture(self, *, verdict=None, trace_id=None):
+ async def capture(self, *, verdict=None, trace_id=None, master=False):
self.verdicts.append(verdict)
return CaptureOutcome(
status="captured", verdict=verdict, context=make_context(), handle_id="h1"
diff --git a/tests/unit/appshot/test_appshot_markup.py b/tests/unit/appshot/test_appshot_markup.py
index d957a4c4ce..48f61a45b6 100644
--- a/tests/unit/appshot/test_appshot_markup.py
+++ b/tests/unit/appshot/test_appshot_markup.py
@@ -376,7 +376,7 @@ class Capture:
self.displays = Displays()
self.markup_at_shutter: list = []
- async def capture(self, *, verdict=None, trace_id=None, region=None):
+ async def capture(self, *, verdict=None, trace_id=None, region=None, master=False):
from jarvis.appshot.effect import shutter_markup
self.markup_at_shutter.append(shutter_markup.get())
diff --git a/tests/unit/appshot/test_appshot_master.py b/tests/unit/appshot/test_appshot_master.py
new file mode 100644
index 0000000000..d505bfd289
--- /dev/null
+++ b/tests/unit/appshot/test_appshot_master.py
@@ -0,0 +1,135 @@
+"""The user's lossless copy of an appshot: encoding, redaction, markings, saving."""
+
+from __future__ import annotations
+
+import io
+import time
+
+import numpy as np
+from PIL import Image
+
+from jarvis.appshot import card_actions, library
+from jarvis.appshot.markup import Frame, Hide, Markup, apply_to_scrgb
+from jarvis.appshot.master import encode_master
+from jarvis.appshot.store import Appshot, AppshotStore
+from jarvis.platform.hdr_image import read_png_cicp
+from jarvis.screen_context.models import MasterImage, RedactionHit, RedactionRule
+from jarvis.screen_context.service import _redacted_master
+
+WHITE = 240.0
+SDR_WHITE = WHITE / 80.0
+
+
+def _shot(**fields) -> Appshot:
+ base = dict(
+ id="a" * 32, image=b"jpeg", mime="image/jpeg", width=4, height=2, label="selected area",
+ app_name="", note="", ui_text="", trigger="hotkey", taken_at=time.time(),
+ )
+ return Appshot(**{**base, **fields})
+
+
+def _overlay(size: tuple[int, int], box: tuple[int, int, int, int]) -> bytes:
+ layer = Image.new("RGBA", size, (0, 0, 0, 0))
+ layer.paste((255, 0, 0, 255), box)
+ buffer = io.BytesIO()
+ layer.save(buffer, format="PNG")
+ return buffer.getvalue()
+
+
+def test_sdr_master_is_full_resolution_png_with_the_monitor_profile() -> None:
+ profile = b"\0" * 36 + b"acsp" + b"\0" * 100
+ pixels = np.full((6, 8, 3), 77, np.uint8)
+ files = encode_master(MasterImage(pixels=pixels, icc_profile=profile))
+ picture = Image.open(io.BytesIO(files.png))
+ assert (files.width, files.height, picture.size) == (8, 6, (8, 6))
+ assert picture.info.get("icc_profile") == profile
+ assert np.asarray(picture.convert("RGB"))[0, 0].tolist() == [77, 77, 77]
+ assert files.hdr_png is None
+
+
+def test_hdr_master_gives_an_sdr_png_and_a_tagged_hdr_png() -> None:
+ scrgb = np.zeros((4, 6, 4), np.float16)
+ scrgb[..., :3] = SDR_WHITE
+ scrgb[0, 0, :3] = 2 * SDR_WHITE # a highlight above SDR white
+ files = encode_master(MasterImage(pixels=scrgb, hdr=True, sdr_white_nits=WHITE))
+ sdr = np.asarray(Image.open(io.BytesIO(files.png)).convert("RGB"))
+ assert sdr[1, 1].tolist() == [255, 255, 255]
+ assert read_png_cicp(files.hdr_png) == (9, 16, 0, 1)
+
+
+def test_markings_on_hdr_keep_untouched_pixels_at_full_depth() -> None:
+ scrgb = np.full((10, 10, 4), 2 * SDR_WHITE, np.float32) # all highlight
+ markup = Markup(overlay_png=_overlay((10, 10), (0, 0, 3, 3)))
+ out = apply_to_scrgb(scrgb, markup, WHITE)
+ assert out[5, 5].tolist() == [2 * SDR_WHITE] * 3 # untouched: HDR value kept
+ assert out[1, 1, 0] == np.float32(SDR_WHITE) # red mark at SDR white
+ assert out[1, 1, 1] == 0.0
+
+
+def test_hidden_patches_on_hdr_are_replaced_whole() -> None:
+ scrgb = np.zeros((20, 20, 4), np.float32)
+ scrgb[5:15, 5:15, :3] = 3 * SDR_WHITE # bright secret
+ markup = Markup(hides=(Hide("pixelate", (0.0, 0.0, 1.0, 1.0)),))
+ out = apply_to_scrgb(scrgb, markup, WHITE)
+ assert float(out.max()) <= SDR_WHITE + 1e-3 # no highlight survives the patch
+
+
+def test_a_background_frame_surrounds_the_hdr_picture() -> None:
+ scrgb = np.full((40, 60, 4), 2 * SDR_WHITE, np.float32)
+ framed = apply_to_scrgb(scrgb, Markup(frame=Frame("dawn", padding=0.1, radius=0)), WHITE)
+ assert framed.shape[:2] == (52, 72)
+ assert framed[26, 36].tolist() == [2 * SDR_WHITE] * 3
+ assert float(framed[0, 0].max()) <= SDR_WHITE + 1e-3
+
+
+def test_hdr_master_gets_the_same_black_boxes_as_the_model_picture() -> None:
+ master = MasterImage(pixels=np.full((10, 10, 4), 1.0, np.float16), hdr=True)
+ hit = RedactionHit(rule=RedactionRule.SENSITIVE_PATTERN, label="card", region=(2, 3, 4, 2))
+ redacted = _redacted_master(master, None, (hit,))
+ pixels = redacted.pixels.astype(np.float32)
+ assert pixels[3:5, 2:6, :3].max() == 0.0
+ assert pixels[0, 0, 0] == 1.0
+ assert np.asarray(master.pixels)[3, 2, 0] == 1.0 # the input is not changed
+
+
+def test_sdr_master_is_the_redacted_frame_itself() -> None:
+ redacted = Image.new("RGB", (3, 2), (0, 0, 0))
+ master = _redacted_master(MasterImage(pixels=None), redacted, ())
+ assert master.pixels.shape == (2, 3, 3)
+
+
+def test_an_edit_drops_the_lossless_copies_of_the_unedited_picture() -> None:
+ store = AppshotStore()
+ store.remember(_shot(original_png=b"orig", hdr_png=b"hdr"), keep_s=60)
+ edited = store.replace_image("a" * 32, b"png", "image/png", 4, 2)
+ assert edited.original_png == b"" and edited.hdr_png == b""
+
+
+def test_update_swaps_in_the_finished_copy_without_moving_it() -> None:
+ store = AppshotStore()
+ store.remember(_shot(), keep_s=60)
+ store.remember(_shot(id="b" * 32), keep_s=60)
+ store.update(_shot(original_png=b"orig"))
+ assert store.get("a" * 32).original_png == b"orig"
+ assert store.latest().id == "b" * 32
+
+
+def test_save_writes_the_lossless_png_and_the_hdr_one_beside_it(tmp_path) -> None:
+ png = encode_master(MasterImage(pixels=np.zeros((2, 4, 3), np.uint8))).png
+ path = card_actions.save_shot_to_downloads(
+ _shot(original_png=png, hdr_png=b"\x89PNGhdr"), folder=tmp_path, now=0
+ )
+ assert path.read_bytes() == png
+ assert path.with_name(f"{path.stem}-hdr.png").read_bytes() == b"\x89PNGhdr"
+
+
+def test_library_keeps_the_lossless_copy_and_the_hdr_file(tmp_path, monkeypatch) -> None:
+ monkeypatch.setattr(library, "_root_override", tmp_path)
+ png = encode_master(MasterImage(pixels=np.zeros((5, 7, 3), np.uint8))).png
+ shot = _shot(original_png=png, hdr_png=b"\x89PNGhdr")
+ assert library.save(shot)
+ folder = next(p for p in tmp_path.iterdir() if p.is_dir())
+ names = sorted(p.name for p in folder.iterdir() if p.suffix == ".png")
+ assert len(names) == 2 and any(n.endswith("-hdr.png") for n in names)
+ main = next(folder / n for n in names if not n.endswith("-hdr.png"))
+ assert main.read_bytes() == png
diff --git a/tests/unit/appshot/test_appshot_region.py b/tests/unit/appshot/test_appshot_region.py
index 38a47d289a..36cfa23fe1 100644
--- a/tests/unit/appshot/test_appshot_region.py
+++ b/tests/unit/appshot/test_appshot_region.py
@@ -145,7 +145,7 @@ class RegionCaptureService:
self.regions: list = []
self.displays = Displays()
- async def capture(self, *, verdict=None, trace_id=None, region=None):
+ async def capture(self, *, verdict=None, trace_id=None, region=None, master=False):
self.regions.append((verdict, region))
context = ScreenContext(
image=b"jpeg",
diff --git a/tests/unit/appshot/test_hdr_image.py b/tests/unit/platform/test_hdr_image.py
similarity index 99%
rename from tests/unit/appshot/test_hdr_image.py
rename to tests/unit/platform/test_hdr_image.py
index 46cda74b58..d4b4a1eaba 100644
--- a/tests/unit/appshot/test_hdr_image.py
+++ b/tests/unit/platform/test_hdr_image.py
@@ -8,7 +8,7 @@ import zlib
import numpy as np
import pytest
-from jarvis.appshot import hdr_image
+from jarvis.platform import hdr_image
def _decode_png16(data: bytes) -> tuple[np.ndarray, dict[bytes, bytes]]: