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.

fix(appshot): close review gaps in HDR capture

rubenluetke10-beep8cabeae9de23
diff --git a/jarvis/appshot/hdr_recording.py b/jarvis/appshot/hdr_recording.py
index 99b99f4b6f..f020ddc225 100644
--- a/jarvis/appshot/hdr_recording.py
+++ b/jarvis/appshot/hdr_recording.py
@@ -37,8 +37,10 @@ HDR_CANDIDATES: tuple[tuple[str, str, dict[str, str]], ...] = (
)
#: AVCOL_PRI_BT2020, AVCOL_TRC_SMPTE2084, AVCOL_SPC_BT2020_NCL, AVCOL_RANGE_MPEG.
HDR10_TAGS = (9, 16, 9, 1)
-#: Stop after this many lost-and-reopened desktops in a row.
-_MAX_REOPENS = 5
+#: How long a recording waits for the desktop to come back (UAC prompt,
+#: Win+L) before it stops, and how often it looks.
+_REOPEN_PATIENCE_S = 60.0
+_REOPEN_STEP_S = 0.25
def hdr_capture_available() -> bool:
@@ -116,7 +118,7 @@ class HdrCapture:
from jarvis.platform.win_duplication import DesktopDuplication # noqa: PLC0415
self._dup = DesktopDuplication(self.device_name)
- self._dup.wait_first_frame(1500)
+ self._dup.wait_first_frame(600)
width, height = self._dup.size
x, y, w, h = self.frac
left, top = round(x * width), round(y * height)
@@ -144,14 +146,10 @@ class HdrCapture:
self._dup = None
def _run(self, encoder: Any, epoch: float) -> None:
- from jarvis.platform.win_duplication import ( # noqa: PLC0415
- AccessLost,
- DesktopDuplication,
- )
+ from jarvis.platform.win_duplication import AccessLost # noqa: PLC0415
interval = 1.0 / self.fps
due = time.perf_counter()
- reopens = 0
try:
while not self._stop.is_set():
try:
@@ -163,19 +161,16 @@ class HdrCapture:
y, uv = self._dup.read_p010(self.crop, self.out_size, sdr_white=self.sdr_white)
encoder.submit((y, uv), now - epoch)
self.frames += 1
- reopens = 0
due += interval
if due < now: # fell behind: skip, keep real timestamps
due = now + interval
if self.poster is None:
self.poster = self._make_poster()
except AccessLost:
- reopens += 1
- if reopens > _MAX_REOPENS:
- raise
+ # The last frame keeps playing while the desktop is away.
self._dup.close()
- time.sleep(0.2) # the desktop is switching; let it settle
- self._dup = DesktopDuplication(self.device_name)
+ self._reopen()
+ due = time.perf_counter()
except Exception as exc: # noqa: BLE001 - reported to the user via the sidecar
log.exception("appshot: HDR capture failed")
self.error = (
@@ -188,6 +183,35 @@ class HdrCapture:
self._dup.close()
self._dup = None
+ def _reopen(self) -> None:
+ """Wait for the desktop to return; raise when it changed or never came back."""
+ from jarvis.platform.display_color import display_color # noqa: PLC0415
+ from jarvis.platform.win_duplication import ( # noqa: PLC0415
+ DesktopDuplication,
+ DuplicationUnavailable,
+ )
+
+ size = self._dup.size
+ deadline = time.monotonic() + _REOPEN_PATIENCE_S
+ while not self._stop.is_set():
+ try:
+ self._dup = DesktopDuplication(self.device_name)
+ break
+ except DuplicationUnavailable:
+ # Secure desktop: duplication is refused until it closes.
+ if time.monotonic() > deadline:
+ raise
+ self._stop.wait(_REOPEN_STEP_S)
+ else:
+ return
+ if self._dup.size != size:
+ raise DuplicationUnavailable("The screen resolution changed during recording.")
+ colour = display_color(self.device_name)
+ if not colour.extended:
+ raise DuplicationUnavailable("HDR was switched off during recording.")
+ self.sdr_white_nits = colour.sdr_white_nits
+ self.sdr_white = max(1.0, colour.sdr_white_nits) / 80.0
+
def _make_poster(self) -> Any:
"""A small SDR picture of the first frame for the corner card."""
try:
diff --git a/jarvis/appshot/master.py b/jarvis/appshot/master.py
index ea025afa16..e41ae1825b 100644
--- a/jarvis/appshot/master.py
+++ b/jarvis/appshot/master.py
@@ -53,7 +53,7 @@ def encode_master(master: Any, markup: Any = None) -> MasterFiles:
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")
+ picture = Image.fromarray(np.ascontiguousarray(master.pixels, dtype=np.uint8))
if marked:
from jarvis.appshot.markup import apply_to_image # noqa: PLC0415
diff --git a/jarvis/appshot/service.py b/jarvis/appshot/service.py
index 486e5305bb..6200a177ae 100644
--- a/jarvis/appshot/service.py
+++ b/jarvis/appshot/service.py
@@ -244,7 +244,10 @@ async def _encode_master(shot: Appshot, markup: Any, config: Any) -> Appshot:
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)
+ store = get_store()
+ store.attach_originals(shot)
+ # A picture edited meanwhile keeps its edit; the library gets what is held.
+ shot = store.get(shot.id) or shot
await _keep_in_library(shot, config)
return shot
diff --git a/jarvis/appshot/store.py b/jarvis/appshot/store.py
index f0c04d3d41..92d3277e4c 100644
--- a/jarvis/appshot/store.py
+++ b/jarvis/appshot/store.py
@@ -150,19 +150,26 @@ class AppshotStore:
)
return edited
- def update(self, shot: Appshot) -> None:
- """Swap in a newer version of a held appshot, keeping its place and expiry."""
+ def attach_originals(self, shot: Appshot) -> None:
+ """Give a held appshot its finished lossless copies, keeping place and expiry.
+
+ Only the copies move over. When the picture was edited meanwhile, the
+ copies describe the unedited picture and are dropped instead.
+ """
+
+ def merged(held: Appshot) -> Appshot:
+ if held.image != shot.image:
+ return replace(held, master=None)
+ return replace(
+ held, original_png=shot.original_png, hdr_png=shot.hdr_png, master=None
+ )
+
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,
- )
+ self._recent[index] = (merged(held), 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
- )
+ self._pending = merged(self._pending)
def mark_delivered(self, shot_id: str, delivered_to: str) -> None:
with self._lock:
diff --git a/jarvis/platform/hdr_grab.py b/jarvis/platform/hdr_grab.py
index 34e24ecaf0..f475812a0d 100644
--- a/jarvis/platform/hdr_grab.py
+++ b/jarvis/platform/hdr_grab.py
@@ -42,8 +42,9 @@ def grab_extended(bbox: tuple[int, int, int, int]) -> ExtendedFrame | None:
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)
+ except Exception as exc: # noqa: BLE001 - the 8-bit grab is always the fallback
+ log.info("full-depth capture unavailable (%s); using the 8-bit grab", exc)
+ log.debug("full-depth capture failure", exc_info=True)
return None
@@ -92,6 +93,7 @@ def _nudge_repaint() -> None:
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)
+ # RDW_INVALIDATE | RDW_ALLCHILDREN: posts a repaint, never waits for
+ # it, so a hung foreground app cannot hold the shutter.
+ user32.RedrawWindow(hwnd, None, None, 0x0001 | 0x0080)
time.sleep(0.016)
diff --git a/jarvis/platform/hdr_image.py b/jarvis/platform/hdr_image.py
index a05f3bdace..22649906bb 100644
--- a/jarvis/platform/hdr_image.py
+++ b/jarvis/platform/hdr_image.py
@@ -180,7 +180,7 @@ def encode_png8(rgb8: Any, icc_profile: bytes | None = None) -> bytes:
from PIL import Image # noqa: PLC0415
- image = Image.fromarray(rgb8, "RGB") if not isinstance(rgb8, Image.Image) else rgb8
+ image = rgb8 if isinstance(rgb8, Image.Image) else Image.fromarray(rgb8)
buffer = io.BytesIO()
options: dict[str, Any] = {"format": "PNG", "compress_level": 6}
if icc_profile:
diff --git a/jarvis/platform/win_duplication.py b/jarvis/platform/win_duplication.py
index 9e4baa9f22..403bd762fd 100644
--- a/jarvis/platform/win_duplication.py
+++ b/jarvis/platform/win_duplication.py
@@ -127,8 +127,8 @@ float3 Fetch(float2 px) {
[numthreads(8, 8, 1)]
void main(uint3 id : SV_DispatchThreadID) {
- uint2 half = uint2(Sizes.zw) / 2;
- if (id.x >= half.x || id.y >= half.y) return;
+ uint2 halfSize = uint2(Sizes.zw) / 2;
+ if (id.x >= halfSize.x || id.y >= halfSize.y) return;
float3 acc = 0.0;
[unroll] for (uint i = 0; i < 4; i++) {
uint2 p = id.xy * 2 + uint2(i & 1, i >> 1);
diff --git a/jarvis/screen_context/service.py b/jarvis/screen_context/service.py
index f0acb098f2..5e994483ef 100644
--- a/jarvis/screen_context/service.py
+++ b/jarvis/screen_context/service.py
@@ -1273,7 +1273,9 @@ def _redacted_master(master: MasterImage, redacted: Any, hits: Any) -> MasterIma
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.
+ derived from it, so they cover the same content. Like PIL's
+ ``rectangle([x, y, x + w, y + h])`` in :mod:`redaction`, the box includes
+ its end row and column.
"""
import numpy as np # noqa: PLC0415
@@ -1286,7 +1288,7 @@ def _redacted_master(master: MasterImage, redacted: Any, hits: Any) -> MasterIma
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))
+ x1, y1 = min(width, int(left + w) + 1), min(height, int(top + h) + 1)
if x1 > x0 and y1 > y0:
pixels[y0:y1, x0:x1, :3] = 0
return replace(master, pixels=pixels)
diff --git a/tests/unit/appshot/test_appshot_master.py b/tests/unit/appshot/test_appshot_master.py
index d505bfd289..b54b652e5a 100644
--- a/tests/unit/appshot/test_appshot_master.py
+++ b/tests/unit/appshot/test_appshot_master.py
@@ -83,12 +83,20 @@ def test_a_background_frame_surrounds_the_hdr_picture() -> None:
def test_hdr_master_gets_the_same_black_boxes_as_the_model_picture() -> None:
+ from jarvis.screen_context.redaction import apply_image_redactions
+
+ region = (2, 3, 4, 2)
+ model, _hits = apply_image_redactions(
+ Image.new("RGB", (10, 10), (255, 255, 255)),
+ ((region, RedactionRule.SENSITIVE_PATTERN, "card"),),
+ )
+ model_black = (np.asarray(model) == 0).all(axis=-1)
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))
+ hit = RedactionHit(rule=RedactionRule.SENSITIVE_PATTERN, label="card", region=region)
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
+ master_black = (redacted.pixels[..., :3].astype(np.float32) == 0).all(axis=-1)
+ assert model_black.any()
+ assert np.array_equal(master_black, model_black)
assert np.asarray(master.pixels)[3, 2, 0] == 1.0 # the input is not changed
@@ -105,15 +113,25 @@ def test_an_edit_drops_the_lossless_copies_of_the_unedited_picture() -> None:
assert edited.original_png == b"" and edited.hdr_png == b""
-def test_update_swaps_in_the_finished_copy_without_moving_it() -> None:
+def test_finished_copies_attach_without_moving_the_appshot() -> 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"))
+ store.attach_originals(_shot(original_png=b"orig"))
assert store.get("a" * 32).original_png == b"orig"
assert store.latest().id == "b" * 32
+def test_copies_finishing_after_an_edit_never_undo_it() -> None:
+ store = AppshotStore()
+ store.remember(_shot(), keep_s=60)
+ store.replace_image("a" * 32, b"edited", "image/png", 4, 2)
+ store.attach_originals(_shot(original_png=b"orig", hdr_png=b"hdr"))
+ held = store.get("a" * 32)
+ assert held.image == b"edited"
+ assert held.original_png == b"" and held.hdr_png == b""
+
+
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(