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): a clickable, draggable appshot card in the screen corner

rubenluetke10-beep7f00165a5e53
diff --git a/jarvis/appshot/effect.py b/jarvis/appshot/effect.py
index d97460151d..92dab95bf3 100644
--- a/jarvis/appshot/effect.py
+++ b/jarvis/appshot/effect.py
@@ -5,6 +5,11 @@ moment for every look the shared service takes — a shortcut appshot, a spoken
"take an appshot", a "what do you see?". The thumbnail is cut from the raw
frame in memory and piped to the local indicator sidecar; it is never stored
and never published on the event bus.
+
+The thumbnail then rests in the corner as a card: a click opens the appshot
+editor in the app, a drag hands the picture to another app. For that drag the
+finished, privacy-filtered appshot follows (:func:`attach_card_image`) — the
+raw-frame thumbnail itself never leaves the sidecar.
"""
from __future__ import annotations
@@ -23,6 +28,19 @@ _THUMB_EDGE = 560
_tasks: set[asyncio.Task[None]] = set()
+# The card's hover line — app chrome, so it follows [ui].language; a phrase
+# table always carries every supported locale.
+_CARD_HINTS: dict[str, str] = {
+ "de": "Klicken zum Bearbeiten · Ziehen zum Teilen", # i18n-allow: product UI string
+ "en": "Click to edit · Drag to share",
+ "es": "Clic para editar · Arrastra para compartir", # i18n-allow: product UI string
+}
+
+
+def card_hint(config: Any) -> str:
+ language = str(getattr(getattr(config, "ui", None), "language", "") or "").lower()[:2]
+ return _CARD_HINTS.get(language, _CARD_HINTS["en"])
+
def on_shutter(target: Any, size: tuple[int, int], rgb: bytes, monitors: list[dict]) -> None:
"""Screen Context shutter hook — synchronous, schedules the slow part."""
@@ -60,6 +78,7 @@ async def _play(
monitor=monitor,
rect=rect,
thumb_b64=base64.b64encode(thumb).decode("ascii"),
+ hint=card_hint(config),
)
if not shown:
log.info("appshot: shutter effect could not be shown on this desktop")
@@ -67,6 +86,19 @@ async def _play(
log.warning("appshot: shutter effect failed", exc_info=True)
+async def attach_card_image(image: bytes) -> None:
+ """Give the resting card the finished picture, so a drag can share it."""
+ try:
+ from jarvis.cu.indicator.controller import get_indicator_controller # noqa: PLC0415
+
+ controller = get_indicator_controller()
+ if controller is None:
+ return
+ await controller.snap_image(base64.b64encode(image).decode("ascii"))
+ except Exception: # noqa: BLE001 - without it the card still opens the editor
+ log.warning("appshot: could not hand the picture to the card", exc_info=True)
+
+
def thumbnail_jpeg(size: tuple[int, int], rgb: bytes) -> bytes:
"""A small JPEG of the raw frame, for the local effect only."""
from PIL import Image # noqa: PLC0415
@@ -117,4 +149,4 @@ def placement(
]
-__all__ = ["on_shutter", "placement", "thumbnail_jpeg"]
+__all__ = ["attach_card_image", "card_hint", "on_shutter", "placement", "thumbnail_jpeg"]
diff --git a/jarvis/appshot/service.py b/jarvis/appshot/service.py
index e86dc9dccc..ad36006506 100644
--- a/jarvis/appshot/service.py
+++ b/jarvis/appshot/service.py
@@ -138,6 +138,7 @@ async def take_appshot(
store = get_store()
store.remember(shot, keep_s=float(config.screen_context.deck_preview_s))
+ await _attach_to_card(shot, config)
delivered_to = "turn"
if deliver:
delivered_to = await _deliver(
@@ -192,12 +193,26 @@ async def record_turn_capture(context: Any, *, bus: Any | None, trigger: Trigger
shot = shot_from_context(context, trigger=trigger)
store = get_store()
store.remember(shot, keep_s=float(config.screen_context.deck_preview_s))
+ await _attach_to_card(shot, config)
store.mark_delivered(shot.id, "turn")
await _publish(bus, shot, "turn")
except Exception: # noqa: BLE001 - the turn already has its picture
log.warning("appshot: could not record the turn's capture", exc_info=True)
+async def _attach_to_card(shot: Appshot, config: Any) -> None:
+ """The corner card may hand this picture out by drag — if it may be kept.
+
+ ``deck_preview_s = 0`` means the user wants no picture kept around, so the
+ card then only opens the editor and shares nothing.
+ """
+ if float(config.screen_context.deck_preview_s) <= 0:
+ return
+ from jarvis.appshot.effect import attach_card_image # noqa: PLC0415
+
+ await attach_card_image(shot.image)
+
+
async def _deliver(shot: Appshot, *, target: str, ttl_s: float) -> str:
from jarvis.appshot.delivery import deliver_to_live # noqa: PLC0415
diff --git a/jarvis/appshot/store.py b/jarvis/appshot/store.py
index e5cc260688..59c695e333 100644
--- a/jarvis/appshot/store.py
+++ b/jarvis/appshot/store.py
@@ -101,6 +101,28 @@ class AppshotStore:
self._latest = None
return self._latest
+ def replace_image(
+ self, shot_id: str, image: bytes, mime: str, width: int, height: int
+ ) -> Appshot | None:
+ """Swap in the user's edited picture for appshot ``shot_id``.
+
+ Updates the last appshot and, when it is still waiting for the next
+ message, the pending one too — so that message carries the edit.
+ ``None`` when that appshot is no longer held.
+ """
+ with self._lock:
+ latest = self._latest
+ if latest is not None and self._clock() >= self._latest_until:
+ latest = self._latest = None
+ if latest is None or latest.id != shot_id:
+ return None
+ edited = replace(latest, image=image, mime=mime, width=width, height=height)
+ self._latest = edited
+ 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)
+ return edited
+
def mark_delivered(self, shot_id: str, delivered_to: str) -> None:
with self._lock:
if self._latest is not None and self._latest.id == shot_id:
diff --git a/jarvis/core/events.py b/jarvis/core/events.py
index b16e2082c0..d006a10fb6 100644
--- a/jarvis/core/events.py
+++ b/jarvis/core/events.py
@@ -1337,6 +1337,17 @@ class AppshotTaken(Event):
height: int = 0
+@dataclass(frozen=True, slots=True)
+class AppshotEditRequested(Event):
+ """The user clicked the appshot card in the screen corner: open the editor.
+
+ The app shows its window and opens the appshot editor on the picture held
+ as the last appshot. ``appshot_id`` is empty when none is kept any more.
+ """
+
+ appshot_id: str = ""
+
+
@dataclass(frozen=True, slots=True)
class ActionPlanned(Event):
"""The CU loop planner proposed the next action (before execution)."""
diff --git a/jarvis/cu/indicator/controller.py b/jarvis/cu/indicator/controller.py
index fba9ea7031..48aa465d2d 100644
--- a/jarvis/cu/indicator/controller.py
+++ b/jarvis/cu/indicator/controller.py
@@ -52,8 +52,9 @@ _ESC_HINTS: dict[str, str] = {
_QUIT_GRACE_S = 1.5
_BLANK_ACK_TIMEOUT_S = 0.15
_SHOW_ACK_TIMEOUT_S = 1.2
-#: How long the sidecar stays up for one appshot shutter effect (flash, rest
-#: in the corner, slide out — see ``renderer._SNAP_TOTAL_MS``) plus slack.
+#: How long the sidecar stays up for one appshot shutter effect (flash and
+#: flight, see ``renderer._SNAP_TOTAL_MS``) plus slack. The resting card that
+#: follows reports itself open and closed, and holds the sidecar meanwhile.
_SNAP_LIFETIME_S = 3.4
@@ -116,6 +117,12 @@ class CUIndicatorController:
# Monotonic deadline until which an appshot effect owns the sidecar.
self._snap_until = 0.0
self._idle_quit_task: asyncio.Task | None = None
+ # The appshot card in the corner is up (hover / click / drag).
+ self._card_open = False
+ self._loop: asyncio.AbstractEventLoop | None = None
+ # The finished picture for the current card. It can be ready before the
+ # effect reached the sidecar, so ``snap`` re-sends it after the card.
+ self._card_image_b64: str | None = None
# ------------------------------------------------------------------ wiring
def wire(self) -> None:
@@ -236,7 +243,7 @@ class CUIndicatorController:
protocol.CMD_HIDE,
_SHOW_ACK_TIMEOUT_S,
)
- if time.monotonic() < self._snap_until:
+ if self._card_open or time.monotonic() < self._snap_until:
# An appshot effect is still on screen; quit once it has played.
self._schedule_idle_quit()
return
@@ -265,13 +272,17 @@ class CUIndicatorController:
later, and a respawn would cost the effect a second of Qt start-up.
"""
self._snap_until = max(self._snap_until, time.monotonic() + _SNAP_LIFETIME_S)
+ self._card_image_b64 = None # a new capture: the old picture is not its picture
- async def snap(self, *, monitor: list[int], rect: list[float], thumb_b64: str) -> bool:
+ async def snap(
+ self, *, monitor: list[int], rect: list[float], thumb_b64: str, hint: str = ""
+ ) -> bool:
"""Play the appshot shutter effect. ``False`` when it cannot run here."""
ok, reason = self._border_capability()
if not ok:
log.debug("[appshot-effect] unavailable: %s", reason)
return False
+ self._loop = asyncio.get_running_loop()
async with self._lock:
self.hold_for_snap()
await asyncio.to_thread(self._spawn_sidecar)
@@ -287,10 +298,69 @@ class CUIndicatorController:
monitor=list(monitor),
rect=list(rect),
thumb=thumb_b64,
+ hint=hint,
)
+ image = self._card_image_b64
+ if shown and image:
+ await asyncio.to_thread(
+ self._send_and_wait, protocol.CMD_SNAP_IMAGE, _SHOW_ACK_TIMEOUT_S, image=image
+ )
self._schedule_idle_quit()
return shown
+ async def snap_image(self, image_b64: str) -> bool:
+ """Hand the finished picture to the resting card, for a drag out.
+
+ Kept for the effect still on its way (``snap`` sends it after the card);
+ sent at once when the sidecar already runs. The picture never starts a
+ process of its own.
+ """
+ self._card_image_b64 = image_b64
+ if self._proc is None or self._proc.poll() is not None:
+ return False
+ return await asyncio.to_thread(
+ self._send_and_wait, protocol.CMD_SNAP_IMAGE, _SHOW_ACK_TIMEOUT_S, image=image_b64
+ )
+
+ def _on_sidecar_event(self, payload: dict[str, Any]) -> None:
+ """Runs on the ack-pump thread; hops to the event loop."""
+ loop = self._loop
+ if loop is None or loop.is_closed():
+ return
+ with suppress(RuntimeError):
+ loop.call_soon_threadsafe(self._handle_sidecar_event, payload)
+
+ def _handle_sidecar_event(self, payload: dict[str, Any]) -> None:
+ event = payload.get("event")
+ if event == protocol.EVENT_CARD:
+ self._card_open = bool(payload.get("open"))
+ if not self._card_open:
+ self._schedule_idle_quit()
+ elif event == protocol.EVENT_SNAP_OPEN:
+ # _open_editor logs its own failures; nothing awaits this task.
+ asyncio.get_running_loop().create_task(self._open_editor(), name="appshot-card-open")
+
+ async def _open_editor(self) -> None:
+ """The card was clicked: show the app with the appshot editor."""
+ try:
+ from jarvis.appshot.store import get_store # noqa: PLC0415
+ from jarvis.core.events import ( # noqa: PLC0415
+ AppshotEditRequested,
+ ShowWindowRequested,
+ )
+
+ shot = get_store().latest()
+ await self._bus.publish(
+ AppshotEditRequested(
+ source_layer="appshot", appshot_id=shot.id if shot is not None else ""
+ )
+ )
+ await self._bus.publish(
+ ShowWindowRequested(source_layer="appshot", source="appshot_card")
+ )
+ except Exception: # noqa: BLE001 - a lost click must not break the sidecar
+ log.warning("[appshot-effect] opening the editor failed", exc_info=True)
+
def _schedule_idle_quit(self) -> None:
task = self._idle_quit_task
if task is not None and not task.done():
@@ -308,7 +378,12 @@ class CUIndicatorController:
break
await asyncio.sleep(remaining + 0.05)
async with self._lock:
- if self._active or self._screen_active or time.monotonic() < self._snap_until:
+ if (
+ self._active
+ or self._screen_active
+ or self._card_open
+ or time.monotonic() < self._snap_until
+ ):
return
await self._quit_sidecar()
@@ -343,6 +418,7 @@ class CUIndicatorController:
NO_WINDOW_CREATIONFLAGS,
)
+ self._card_open = False # a fresh sidecar has no card yet
self._proc = subprocess.Popen(
[sys.executable, "-m", "jarvis.cu.indicator"],
stdin=subprocess.PIPE,
@@ -376,6 +452,10 @@ class CUIndicatorController:
ack = protocol.decode_ack(line)
if ack in protocol.ALL_COMMANDS:
self._acks.put(ack)
+ continue
+ event = protocol.decode_event(line)
+ if event is not None:
+ self._on_sidecar_event(event)
except Exception: # noqa: BLE001
log.debug("[cu-indicator] ack pipe closed", exc_info=True)
diff --git a/jarvis/cu/indicator/protocol.py b/jarvis/cu/indicator/protocol.py
index 0fed2596a6..0c1cdddbf0 100644
--- a/jarvis/cu/indicator/protocol.py
+++ b/jarvis/cu/indicator/protocol.py
@@ -10,12 +10,20 @@ One JSON object per line on the sidecar's stdin::
{"cmd": "quit"} # exit the sidecar
{"cmd": "snap", "monitor": [l, t, w, h], # appshot shutter effect:
"rect": [fx, fy, fw, fh], # flash the captured rect and
- "thumb": "<base64 jpeg>"} # fly its thumbnail to a corner
+ "thumb": "<base64 jpeg>", # fly its thumbnail to a corner,
+ "hint": "Click to edit · Drag to share"} # where it rests as a card
+ {"cmd": "snap_image", "image": "<b64>"} # the finished (redacted) picture
+ # a drag from the card hands out
The sidecar answers each command with one JSON line on stdout::
{"ok": "<cmd>"}
+and reports what the user does with the resting card::
+
+ {"event": "card", "open": true|false} # keep the sidecar alive meanwhile
+ {"event": "snap_open"} # the card was clicked: edit it
+
and exits on stdin EOF (parent death) even without a ``quit``. Everything
is best-effort: the controller treats a missing/late ack as "sidecar gone"
and degrades; the sidecar ignores lines it cannot parse.
@@ -32,11 +40,16 @@ CMD_BLANK = "blank"
CMD_UNBLANK = "unblank"
CMD_QUIT = "quit"
CMD_SNAP = "snap"
+CMD_SNAP_IMAGE = "snap_image"
ALL_COMMANDS = frozenset(
- {CMD_SHOW, CMD_HIDE, CMD_BLANK, CMD_UNBLANK, CMD_QUIT, CMD_SNAP}
+ {CMD_SHOW, CMD_HIDE, CMD_BLANK, CMD_UNBLANK, CMD_QUIT, CMD_SNAP, CMD_SNAP_IMAGE}
)
+EVENT_CARD = "card"
+EVENT_SNAP_OPEN = "snap_open"
+ALL_EVENTS = frozenset({EVENT_CARD, EVENT_SNAP_OPEN})
+
#: Sidecar exit code when no usable GUI stack exists (PySide6 missing or
#: no display). The controller logs it as an expected degradation.
EXIT_NO_GUI = 3
@@ -68,6 +81,22 @@ def encode_ack(cmd: str) -> str:
return json.dumps({"ok": cmd}) + "\n"
+def encode_event(event: str, **fields: Any) -> str:
+ """Serialize one sidecar → controller event line."""
+ return json.dumps({"event": event, **fields}) + "\n"
+
+
+def decode_event(line: str) -> dict[str, Any] | None:
+ """Parse one stdout line as a known event; ``None`` otherwise."""
+ try:
+ payload = json.loads(line.strip())
+ except (ValueError, TypeError):
+ return None
+ if isinstance(payload, dict) and payload.get("event") in ALL_EVENTS:
+ return payload
+ return None
+
+
def decode_ack(line: str) -> str | None:
"""Parse one ack line from the sidecar; ``None`` if it isn't one."""
try:
@@ -86,10 +115,15 @@ __all__ = [
"CMD_QUIT",
"CMD_SHOW",
"CMD_SNAP",
+ "CMD_SNAP_IMAGE",
+ "EVENT_CARD",
+ "EVENT_SNAP_OPEN",
"CMD_UNBLANK",
"EXIT_NO_GUI",
"decode_ack",
"decode_command",
"encode_ack",
+ "decode_event",
"encode_command",
+ "encode_event",
]
diff --git a/jarvis/cu/indicator/renderer.py b/jarvis/cu/indicator/renderer.py
index e1d11c3b5a..2403ac24c4 100644
--- a/jarvis/cu/indicator/renderer.py
+++ b/jarvis/cu/indicator/renderer.py
@@ -20,22 +20,31 @@ from __future__ import annotations
import os
import sys
+import tempfile
import threading
+import time
from collections import deque
from contextlib import suppress
+from pathlib import Path
from PySide6.QtCore import (
QByteArray,
QEasingCurve,
+ QMimeData,
QObject,
+ QPoint,
+ QPointF,
QRectF,
Qt,
+ QTimer,
+ QUrl,
QVariantAnimation,
Signal,
Slot,
)
from PySide6.QtGui import (
QColor,
+ QDrag,
QFont,
QFontMetricsF,
QGuiApplication,
@@ -44,11 +53,16 @@ from PySide6.QtGui import (
QPainter,
QPainterPath,
QPen,
+ QPixmap,
)
from PySide6.QtWidgets import QApplication, QWidget
from jarvis.cu.indicator import protocol
-from jarvis.cu.indicator.win32 import exclude_from_capture, harden_window
+from jarvis.cu.indicator.win32 import (
+ exclude_from_capture,
+ harden_clickable_window,
+ harden_window,
+)
# Jarvis gold — matches ui/orb BUBBLE_BORDER_HEX (#FFE500) at the crisp
# edge, falling off through the softer [ui].bar_accent gold (#e7c46e).
@@ -186,22 +200,30 @@ class _GlowWindow(QWidget):
# Appshot shutter effect — the phone-screenshot moment.
#
# A white flash over the captured surface, then the picture shrinks into the
-# bottom-right corner of that monitor, rests there as a rounded thumbnail and
-# slides out. Purely local: the thumbnail arrives over this process's stdin,
-# is painted, and is dropped with the window. Click-through like the glow.
+# bottom-right corner of that monitor. There it becomes a small interactive
+# card (``_CardWindow``): hovering keeps it, a click asks the app to open the
+# editor, a drag hands the finished picture to any app that takes a file, a
+# right-click dismisses it. The flight canvas itself stays click-through.
# ---------------------------------------------------------------------------
_SNAP_FLASH_MS = 200
_SNAP_FLY_START_MS = 90
_SNAP_FLY_MS = 430
-_SNAP_HOLD_UNTIL_MS = 2500
-_SNAP_OUT_MS = 320
-_SNAP_TOTAL_MS = _SNAP_HOLD_UNTIL_MS + _SNAP_OUT_MS
+_SNAP_TOTAL_MS = _SNAP_FLY_START_MS + _SNAP_FLY_MS
_SNAP_THUMB_W = 320
_SNAP_THUMB_MAX_H = 240
_SNAP_MARGIN = 28
_SNAP_RADIUS = 12.0
+#: The resting card: how long it stays untouched, and after the pointer left.
+_CARD_REST_MS = 6000
+_CARD_AFTER_HOVER_MS = 2500
+_CARD_OUT_MS = 240
+#: A press that moves further than this (logical px) is a drag, not a click.
+_CARD_DRAG_SLOP = 6
+#: Drag files older than this are removed the next time one is written.
+_DRAG_FILE_MAX_AGE_S = 3600
+
def _ease_out_cubic(x: float) -> float:
x = max(0.0, min(1.0, x))
@@ -240,10 +262,26 @@ def _match_screen(monitor: list[float]):
return best
+def _paint_card(painter: QPainter, rect: QRectF, thumb: QImage, radius: float, ring: float) -> None:
+ """The thumbnail with rounded corners and a white ring — flight and card."""
+ clip = QPainterPath()
+ clip.addRoundedRect(rect, radius, radius)
+ painter.save()
+ painter.setClipPath(clip)
+ painter.drawImage(rect, thumb)
+ painter.restore()
+ if ring > 0.0:
+ pen = QPen(QColor(255, 255, 255, int(235 * ring)))
+ pen.setWidthF(2.5)
+ painter.setPen(pen)
+ painter.setBrush(Qt.BrushStyle.NoBrush)
+ painter.drawRoundedRect(rect, radius, radius)
+
+
class _SnapWindow(QWidget):
- """One monitor-sized, click-through canvas for a single shutter effect."""
+ """One monitor-sized, click-through canvas for the flash and the flight."""
- def __init__(self, screen, rect_frac: list[float], thumb: QImage, on_done) -> None:
+ def __init__(self, screen, rect_frac: list[float], thumb: QImage, on_landed, on_done) -> None:
super().__init__(None)
self.setWindowFlags(
Qt.WindowType.FramelessWindowHint
@@ -262,7 +300,9 @@ class _SnapWindow(QWidget):
self.setAttribute(mac_always_show)
self.setScreen(screen)
self.setGeometry(screen.geometry())
+ self._screen_geo = screen.geometry()
self._thumb = thumb
+ self._on_landed = on_landed
self._on_done = on_done
w, h = float(screen.geometry().width()), float(screen.geometry().height())
fx, fy, fw, fh = (max(0.0, min(1.0, float(v))) for v in rect_frac)
@@ -277,20 +317,27 @@ class _SnapWindow(QWidget):
if th > _SNAP_THUMB_MAX_H:
th = float(_SNAP_THUMB_MAX_H)
tw = th / max(aspect, 1e-6)
- self._dst = QRectF(w - tw - _SNAP_MARGIN, h - th - _SNAP_MARGIN, tw, th)
+ # Land inside the work area, so the card never sits under the taskbar.
+ avail = screen.availableGeometry()
+ geo = screen.geometry()
+ right = float(avail.right() + 1 - geo.x())
+ bottom = float(avail.bottom() + 1 - geo.y())
+ self._dst = QRectF(right - tw - _SNAP_MARGIN, bottom - th - _SNAP_MARGIN, tw, th)
self._t = 0.0
self._anim = QVariantAnimation(self)
self._anim.setStartValue(0.0)
self._anim.setEndValue(float(_SNAP_TOTAL_MS))
self._anim.setDuration(_SNAP_TOTAL_MS)
self._anim.valueChanged.connect(self._on_tick)
- self._anim.finished.connect(self._finish)
+ self._anim.finished.connect(self._landed)
def start(self) -> None:
self.show()
self._anim.start()
def finish_now(self) -> None:
+ """Drop the effect without handing over to a card."""
+ self._on_landed = None
self._anim.stop()
self._finish()
@@ -298,6 +345,13 @@ class _SnapWindow(QWidget):
self._t = float(value)
self.update()
+ def _landed(self) -> None:
+ landed, self._on_landed = self._on_landed, None
+ if landed is not None and not self._thumb.isNull():
+ top_left = self._screen_geo.topLeft()
+ landed(self._dst.translated(top_left.x(), top_left.y()), self._thumb)
+ self._finish()
+
def _finish(self) -> None:
self.hide()
callback, self._on_done = self._on_done, None
@@ -319,47 +373,210 @@ class _SnapWindow(QWidget):
painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)
fly = _ease_out_cubic((t - _SNAP_FLY_START_MS) / _SNAP_FLY_MS)
- out = _ease_out_cubic((t - _SNAP_HOLD_UNTIL_MS) / _SNAP_OUT_MS)
rect = QRectF(
- _lerp(self._src.x(), self._dst.x(), fly) + 48.0 * out,
+ _lerp(self._src.x(), self._dst.x(), fly),
_lerp(self._src.y(), self._dst.y(), fly),
_lerp(self._src.width(), self._dst.width(), fly),
_lerp(self._src.height(), self._dst.height(), fly),
)
- radius = _SNAP_RADIUS * fly
- opacity = 1.0 - out
-
- if not self._thumb.isNull() and opacity > 0.0:
- painter.setOpacity(opacity)
- # Soft shadow grows in as the card lifts off the surface.
+ if not self._thumb.isNull():
if fly > 0.0:
for spread, alpha in ((10.0, 18), (5.0, 30), (2.0, 46)):
shadow = rect.adjusted(-spread, -spread + 4, spread, spread + 4)
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(QColor(0, 0, 0, int(alpha * fly)))
- painter.drawRoundedRect(shadow, radius + spread, radius + spread)
- clip = QPainterPath()
- clip.addRoundedRect(rect, radius, radius)
- painter.save()
- painter.setClipPath(clip)
- painter.drawImage(rect, self._thumb)
- painter.restore()
- if fly > 0.0:
- pen = QPen(QColor(255, 255, 255, int(235 * fly)))
- pen.setWidthF(2.5)
- painter.setPen(pen)
- painter.setBrush(Qt.BrushStyle.NoBrush)
- painter.drawRoundedRect(rect, radius, radius)
+ radius = _SNAP_RADIUS * fly + spread
+ painter.drawRoundedRect(shadow, radius, radius)
+ _paint_card(painter, rect, self._thumb, _SNAP_RADIUS * fly, fly)
flash = 1.0 - _ease_out_cubic(t / _SNAP_FLASH_MS)
if flash > 0.0:
- painter.setOpacity(1.0)
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(QColor(255, 255, 255, int(225 * flash)))
painter.drawRect(self._src)
painter.end()
+class _CardWindow(QWidget):
+ """The resting thumbnail: hover keeps it, click edits, drag shares."""
+
+ _PAD = 12 # transparent margin that holds the soft shadow
+
+ def __init__(self, rect: QRectF, thumb: QImage, hint: str, owner: Renderer) -> None:
+ super().__init__(None)
+ self.setWindowFlags(
+ Qt.WindowType.FramelessWindowHint
+ | Qt.WindowType.WindowStaysOnTopHint
+ | Qt.WindowType.WindowDoesNotAcceptFocus
+ | Qt.WindowType.Tool
+ | Qt.WindowType.NoDropShadowWindowHint
+ )
+ self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
+ self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
+ if sys.platform == "darwin":
+ mac_always_show = getattr(Qt.WidgetAttribute, "WA_MacAlwaysShowToolWindow", None)
+ if mac_always_show is not None:
+ self.setAttribute(mac_always_show)
+ pad = self._PAD
+ self.setGeometry(rect.adjusted(-pad, -pad, pad, pad).toAlignedRect())
+ self.setCursor(Qt.CursorShape.PointingHandCursor)
+ self.setMouseTracking(True)
+ self._thumb = thumb
+ self._hint = hint
+ self._owner = owner
+ self._hover = False
+ self._press: QPointF | None = None
+ self._leaving = False
+ self._dismiss = QTimer(self)
+ self._dismiss.setSingleShot(True)
+ self._dismiss.timeout.connect(self.leave)
+ self._out = QVariantAnimation(self)
+ self._out.setStartValue(0.0)
+ self._out.setEndValue(1.0)
+ self._out.setDuration(_CARD_OUT_MS)
+ self._out.valueChanged.connect(self._on_out)
+ self._out.finished.connect(self._gone)
+ self._origin = self.pos()
+
+ def start(self) -> None:
+ self.show()
+ self._dismiss.start(_CARD_REST_MS)
+
+ # -- lifecycle -----------------------------------------------------------
+ def leave(self) -> None:
+ """Slide out and go. Safe to call more than once."""
+ if self._leaving:
+ return
+ self._leaving = True
+ self._dismiss.stop()
+ self._origin = self.pos()
+ self._out.start()
+
+ def finish_now(self) -> None:
+ self._leaving = True
+ self._dismiss.stop()
+ self._out.stop()
+ self._gone()
+
+ def _on_out(self, value) -> None:
+ t = _ease_out_cubic(float(value))
+ self.move(self._origin + QPoint(int(48 * t), 0))
+ self.setWindowOpacity(1.0 - t)
+
+ def _gone(self) -> None:
+ self.hide()
+ owner, self._owner = self._owner, None
+ if owner is not None:
+ owner.card_gone(self)
+ self.deleteLater()
+
+ # -- input ---------------------------------------------------------------
+ def showEvent(self, event) -> None: # noqa: N802 (Qt override)
+ super().showEvent(event)
+ # Clickable, so no click-through hardening; layered for the
+ # see-through corners, and out of every screenshot.
+ hwnd = int(self.winId())
+ harden_clickable_window(hwnd)
+ exclude_from_capture(hwnd)
+
+ def enterEvent(self, event) -> None: # noqa: N802
+ del event
+ if self._leaving:
+ return
+ self._hover = True
+ self._dismiss.stop()
+ self.update()
+
+ def leaveEvent(self, event) -> None: # noqa: N802
+ del event
+ self._hover = False
+ if not self._leaving:
+ self._dismiss.start(_CARD_AFTER_HOVER_MS)
+ self.update()
+
+ def mousePressEvent(self, event) -> None: # noqa: N802
+ if event.button() == Qt.MouseButton.RightButton:
+ self.leave()
+ elif event.button() == Qt.MouseButton.LeftButton:
+ self._press = event.position()
+
+ def mouseMoveEvent(self, event) -> None: # noqa: N802
+ if self._press is None or self._leaving:
+ return
+ moved = event.position() - self._press
+ if abs(moved.x()) + abs(moved.y()) > _CARD_DRAG_SLOP:
+ self._press = None
+ self._start_drag()
+
+ def mouseReleaseEvent(self, event) -> None: # noqa: N802
+ if event.button() != Qt.MouseButton.LeftButton or self._press is None:
+ return
+ self._press = None
+ if self._owner is not None and not self._leaving:
+ self._owner.card_clicked(self)
+
+ def _start_drag(self) -> None:
+ owner = self._owner
+ image = owner.card_image if owner is not None else None
+ if owner is None or image is None or image.isNull():
+ # Only the finished, privacy-filtered picture may leave this
+ # process; the thumbnail is cut from the raw frame.
+ return
+ path = owner.write_drag_file(image)
+ if path is None:
+ return
+ mime = QMimeData()
+ mime.setUrls([QUrl.fromLocalFile(str(path))])
+ mime.setImageData(image)
+ drag = QDrag(self)
+ drag.setMimeData(mime)
+ preview = QPixmap.fromImage(
+ self._thumb.scaledToWidth(160, Qt.TransformationMode.SmoothTransformation)
+ )
+ drag.setPixmap(preview)
+ drag.setHotSpot(QPoint(preview.width() // 2, preview.height() // 2))
+ self._dismiss.stop()
+ self.setWindowOpacity(0.35)
+ drag.exec(Qt.DropAction.CopyAction)
+ self.setWindowOpacity(1.0)
+ self.leave()
+
+ # -- painting ------------------------------------------------------------
+ def paintEvent(self, event) -> None: # noqa: N802 (Qt override)
+ del event
+ painter = QPainter(self)
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)
+ painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)
+ pad = float(self._PAD)
+ rect = QRectF(pad, pad, self.width() - 2 * pad, self.height() - 2 * pad)
+ painter.setPen(Qt.PenStyle.NoPen)
+ for spread, alpha in ((8.0, 18), (4.0, 30), (1.5, 46)):
+ painter.setBrush(QColor(0, 0, 0, alpha))
+ shadow = rect.adjusted(-spread, -spread + 3, spread, spread + 3)
+ painter.drawRoundedRect(shadow, _SNAP_RADIUS + spread, _SNAP_RADIUS + spread)
+ _paint_card(painter, rect, self._thumb, _SNAP_RADIUS, 1.0)
+ if self._hover and self._hint:
+ self._paint_hint(painter, rect)
+ painter.end()
+
+ def _paint_hint(self, painter: QPainter, rect: QRectF) -> None:
+ font = QFont()
+ font.setPointSizeF(9.0)
+ font.setWeight(QFont.Weight.Medium)
+ metrics = QFontMetricsF(font)
+ h = metrics.height() + 12.0
+ band = QRectF(rect.x(), rect.bottom() - h, rect.width(), h)
+ clip = QPainterPath()
+ clip.addRoundedRect(rect, _SNAP_RADIUS, _SNAP_RADIUS)
+ painter.save()
+ painter.setClipPath(clip)
+ painter.fillRect(band, QColor(10, 10, 12, 200))
+ painter.restore()
+ painter.setFont(font)
+ painter.setPen(QColor(255, 255, 255, 235))
+ painter.drawText(band, Qt.AlignmentFlag.AlignCenter, self._hint)
+
+
class Renderer(QObject):
"""Owns the per-monitor windows, the animations, and the IPC slots."""
@@ -368,6 +585,10 @@ class Renderer(QObject):
self._app = app
self._windows: list[_GlowWindow] = []
self._snaps: list[_SnapWindow] = []
+ self._card: _CardWindow | None = None
+ self._card_hint = ""
+ #: The finished (redacted) picture a drag from the card hands out.
+ self.card_image: QImage | None = None
self._hint = ""
self._active = False # "show" was requested and not yet "hide"
self._blanked = False # capture guard currently hiding the border
@@ -427,6 +648,8 @@ class Renderer(QObject):
self._unblank()
elif cmd == protocol.CMD_SNAP:
self._snap(payload)
+ elif cmd == protocol.CMD_SNAP_IMAGE:
+ self._snap_image(payload)
elif cmd == protocol.CMD_QUIT:
_ack(cmd)
self._app.quit()
@@ -474,7 +697,11 @@ class Renderer(QObject):
# One effect at a time: a second appshot replaces the resting card.
for old in list(self._snaps):
old.finish_now()
- win = _SnapWindow(screen, rect, thumb, self._snap_done)
+ if self._card is not None:
+ self._card.finish_now()
+ self.card_image = None
+ self._card_hint = str(payload.get("hint", "") or "")
+ win = _SnapWindow(screen, rect, thumb, self._snap_landed, self._snap_done)
self._snaps.append(win)
win.start()
@@ -482,10 +709,59 @@ class Renderer(QObject):
with suppress(ValueError):
self._snaps.remove(win)
+ def _snap_landed(self, rect: QRectF, thumb: QImage) -> None:
+ card = _CardWindow(rect, thumb, self._card_hint, self)
+ self._card = card
+ _emit(protocol.EVENT_CARD, open=True)
+ card.start()
+
+ def _snap_image(self, payload: dict) -> None:
+ raw = payload.get("image")
+ if not isinstance(raw, str) or not raw:
+ return
+ image = QImage()
+ if image.loadFromData(QByteArray.fromBase64(raw.encode("ascii"))):
+ self.card_image = image
+
+ def card_gone(self, card: _CardWindow) -> None:
+ if self._card is card:
+ self._card = None
+ self.card_image = None
+ _emit(protocol.EVENT_CARD, open=False)
+
+ def card_clicked(self, card: _CardWindow) -> None:
+ _emit(protocol.EVENT_SNAP_OPEN)
+ card.leave()
+
+ @staticmethod
+ def write_drag_file(image: QImage) -> Path | None:
+ """Write the picture for a drag — the one moment it touches disk.
+
+ Only on the user's drag; files older than an hour are removed first,
+ so the folder never grows (see ``docs/appshots.md``).
+ """
+ folder = Path(tempfile.gettempdir()) / "jarvis-appshots"
+ try:
+ folder.mkdir(parents=True, exist_ok=True)
+ cutoff = time.time() - _DRAG_FILE_MAX_AGE_S
+ for old in folder.glob("appshot-*.png"):
+ with suppress(OSError): # a file still open elsewhere stays
+ if old.stat().st_mtime < cutoff:
+ old.unlink()
+ path = folder / time.strftime("appshot-%Y%m%d-%H%M%S.png")
+ if not image.save(str(path), "PNG"):
+ return None
+ return path
+ except OSError as exc:
+ sys.stderr.write(f"cu-indicator: drag file failed ({exc!r})\n")
+ return None
+
def _blank(self) -> None:
# A resting thumbnail must never end up inside the next capture.
for snap in list(self._snaps):
snap.finish_now()
+ if self._card is not None:
+ self._card.hide()
if not self._active:
return
self._blanked = True
@@ -493,6 +769,8 @@ class Renderer(QObject):
win.hide()
def _unblank(self) -> None:
+ if self._card is not None and not self._card.isVisible():
+ self._card.show()
if not self._active or not self._blanked:
return
self._blanked = False
@@ -564,6 +842,13 @@ class _StdinPump(QObject):
self.eof.emit()
+def _emit(event: str, **fields) -> None:
+ # A failed write means the parent is gone; the EOF path quits the app.
+ with suppress(Exception):
+ sys.stdout.write(protocol.encode_event(event, **fields))
+ sys.stdout.flush()
+
+
def _ack(cmd: str) -> None:
# A failed ack means the parent is gone; the EOF path quits the app.
with suppress(Exception):
diff --git a/jarvis/cu/indicator/win32.py b/jarvis/cu/indicator/win32.py
index 005fc0c3a0..0972badde5 100644
--- a/jarvis/cu/indicator/win32.py
+++ b/jarvis/cu/indicator/win32.py
@@ -69,6 +69,46 @@ def harden_window(hwnd: int) -> bool:
return False
+def harden_clickable_window(hwnd: int) -> bool:
+ """Layered, never-activating tool window that still takes clicks.
+
+ For the appshot card: like :func:`harden_window` minus click-through, so
+ its rounded corners are see-through and a click does not steal focus.
+ Also asks Windows 11 for no frame border and no corner rounding of its
+ own, which would otherwise draw a grey outline around the transparent
+ margin. A quiet no-op elsewhere.
+ """
+ user32 = _user32()
+ if user32 is None or not hwnd:
+ return False
+ try:
+ style = user32.GetWindowLongW(hwnd, _GWL_EXSTYLE)
+ wanted = style | _WS_EX_LAYERED | _WS_EX_NOACTIVATE | _WS_EX_TOOLWINDOW
+ wanted &= ~_WS_EX_TRANSPARENT
+ if wanted != style:
+ user32.SetWindowLongW(hwnd, _GWL_EXSTYLE, wanted)
+ except Exception: # noqa: BLE001
+ log.debug("harden_clickable_window failed for hwnd=%s", hwnd, exc_info=True)
+ return False
+ _no_dwm_frame(hwnd)
+ return True
+
+
+def _no_dwm_frame(hwnd: int) -> None:
+ import ctypes # noqa: PLC0415
+ from ctypes import wintypes # noqa: PLC0415
+
+ try:
+ dwmapi = ctypes.WinDLL("dwmapi")
+ for attribute, value in ((33, 1), (34, 0xFFFFFFFE)): # DONOTROUND, COLOR_NONE
+ data = wintypes.DWORD(value)
+ dwmapi.DwmSetWindowAttribute(
+ wintypes.HWND(hwnd), attribute, ctypes.byref(data), ctypes.sizeof(data)
+ )
+ except Exception: # noqa: BLE001 - older Windows: a thin frame stays
+ log.debug("DWM frame attributes unavailable", exc_info=True)
+
+
def exclude_from_capture(hwnd: int) -> bool:
"""Hide ``hwnd`` from all screen capture (BitBlt/mss/OBS/CU frames)."""
if os.environ.get(CAPTURABLE_ENV, "").strip() in {"1", "true", "yes"}:
@@ -93,5 +133,6 @@ __all__ = [
"CAPTURABLE_ENV",
"capture_exclusion_available",
"exclude_from_capture",
+ "harden_clickable_window",
"harden_window",
]
diff --git a/jarvis/ui/web/appshot_routes.py b/jarvis/ui/web/appshot_routes.py
index 4ba227ac6d..ff45cefd95 100644
--- a/jarvis/ui/web/appshot_routes.py
+++ b/jarvis/ui/web/appshot_routes.py
@@ -7,6 +7,7 @@ Endpoints (mounted by the WebServer in ``_build_app()``):
POST /api/appshot/take → take one appshot now (window or area).
GET /api/appshot/latest → metadata of the last appshot.
GET /api/appshot/latest/image → its picture (never cached).
+ PUT /api/appshot/latest/image → replace it with the editor's version.
GET /api/appshot/pending → the appshot waiting for the next message.
POST /api/appshot/pending/claim → hand that one to the chat composer.
DELETE /api/appshot → forget every held appshot now.
@@ -205,6 +206,45 @@ async def latest_image() -> Response:
return Response(content=shot.image, media_type=shot.mime, headers=_NO_STORE)
+#: Upper bound for an edited picture (a 4K PNG with annotations stays far below).
+_MAX_EDIT_BYTES = 20 * 1024 * 1024
+
+
[email protected]("/latest/image")
+async def replace_latest_image(request: Request, id: str) -> dict[str, Any]: # noqa: A002
+ """Store the appshot editor's result in place of the last appshot.
+
+ Body: the PNG the editor rendered. In memory only, like every appshot; the
+ next message that takes the appshot gets the edited picture.
+ """
+ from jarvis.appshot.store import get_store # noqa: PLC0415
+
+ body = await request.body()
+ if not body or len(body) > _MAX_EDIT_BYTES:
+ raise HTTPException(status_code=413, detail="The edited picture is empty or too large.")
+ size = await asyncio.to_thread(_png_size, body)
+ if size is None:
+ raise HTTPException(status_code=400, detail="The edited picture is not a PNG.")
+ shot = await asyncio.to_thread(get_store().replace_image, id, body, "image/png", *size)
+ if shot is None:
+ raise HTTPException(status_code=404, detail="That appshot is no longer kept.")
+ return {"ok": True, "appshot": shot.meta()}
+
+
+def _png_size(data: bytes) -> tuple[int, int] | None:
+ import io # noqa: PLC0415
+
+ from PIL import Image, UnidentifiedImageError # noqa: PLC0415
+
+ try:
+ with Image.open(io.BytesIO(data)) as image:
+ if image.format != "PNG":
+ return None
+ return int(image.width), int(image.height)
+ except (UnidentifiedImageError, OSError):
+ return None
+
+
@router.get("/pending")
async def pending() -> dict[str, Any]:
from jarvis.appshot.store import get_store # noqa: PLC0415
diff --git a/tests/unit/appshot/test_appshot_editor.py b/tests/unit/appshot/test_appshot_editor.py
new file mode 100644
index 0000000000..37017de5ca
--- /dev/null
+++ b/tests/unit/appshot/test_appshot_editor.py
@@ -0,0 +1,92 @@
+"""The appshot editor's way back: an edited picture replaces the held appshot."""
+
+from __future__ import annotations
+
+import io
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from PIL import Image
+
+from jarvis.appshot.store import Appshot, AppshotStore, get_store
+
+
+def _shot(shot_id: str = "s1") -> Appshot:
+ return Appshot(
+ id=shot_id,
+ image=b"jpeg",
+ mime="image/jpeg",
+ width=800,
+ height=600,
+ label="selected area",
+ app_name="Editor",
+ note="APPSHOT: evidence",
+ ui_text="",
+ trigger="hotkey",
+ taken_at=1.0,
+ )
+
+
+def _png(width: int = 40, height: int = 30) -> bytes:
+ buffer = io.BytesIO()
+ Image.new("RGB", (width, height), (200, 30, 30)).save(buffer, "PNG")
+ return buffer.getvalue()
+
+
+def test_an_edit_reaches_the_last_and_the_waiting_appshot() -> None:
+ store = AppshotStore()
+ store.remember(_shot(), keep_s=60)
+ store.park(_shot(), ttl_s=60)
+
+ edited = store.replace_image("s1", b"png", "image/png", 40, 30)
+
+ assert edited is not None and edited.note == "APPSHOT: evidence", "the context note stays"
+ assert store.latest().image == b"png" and store.latest().mime == "image/png"
+ pending = store.take_pending()
+ assert pending.image == b"png" and (pending.width, pending.height) == (40, 30)
+
+
+def test_an_edit_for_a_gone_or_other_appshot_changes_nothing() -> None:
+ store = AppshotStore()
+ store.remember(_shot("s1"), keep_s=60)
+ assert store.replace_image("other", b"png", "image/png", 1, 1) is None
+ assert store.latest().image == b"jpeg"
+ assert AppshotStore().replace_image("s1", b"png", "image/png", 1, 1) is None
+
+
+def client():
+ from jarvis.ui.web.appshot_routes import router
+
+ app = FastAPI()
+ app.include_router(router)
+ app.state.bus = None
+ store = get_store()
+ store.clear()
+ store.remember(_shot("s1"), keep_s=60)
+ yield TestClient(app)
+ store.clear()
+
+
+def test_the_route_takes_a_png_and_serves_it_back(client) -> None:
+ png = _png()
+ response = client.put("/api/appshot/latest/image?id=s1", content=png)
+
+ assert response.status_code == 200, response.text
+ assert response.json()["appshot"]["width"] == 40
+ served = client.get("/api/appshot/latest/image")
+ assert served.content == png and served.headers["content-type"] == "image/png"
+
+
+ ("body", "status"),
+ [(b"", 413), (b"not an image", 400)],
+)
+def test_the_route_refuses_what_is_not_a_png(client, body: bytes, status: int) -> None:
+ assert client.put("/api/appshot/latest/image?id=s1", content=body).status_code == status
+ assert get_store().latest().image == b"jpeg"
+
+
+def test_the_route_refuses_an_expired_appshot(client) -> None:
+ assert client.put("/api/appshot/latest/image?id=gone", content=_png()).status_code == 404
diff --git a/tests/unit/cu/indicator/test_appshot_card.py b/tests/unit/cu/indicator/test_appshot_card.py
new file mode 100644
index 0000000000..1b5d62bad7
--- /dev/null
+++ b/tests/unit/cu/indicator/test_appshot_card.py
@@ -0,0 +1,146 @@
+"""The appshot card in the screen corner: protocol, lifetime, click and drag image."""
+
+from __future__ import annotations
+
+import asyncio
+
+from jarvis.core.events import AppshotEditRequested, ShowWindowRequested
+from jarvis.cu.indicator import protocol
+from jarvis.cu.indicator.controller import CUIndicatorController
+
+
+class _Bus:
+ def __init__(self) -> None:
+ self.events: list = []
+
+ async def publish(self, event) -> None:
+ self.events.append(event)
+
+ def subscribe(self, *_args) -> None:
+ return None
+
+
+def test_card_events_round_trip_and_acks_stay_acks() -> None:
+ line = protocol.encode_event(protocol.EVENT_CARD, open=True)
+ assert protocol.decode_event(line) == {"event": "card", "open": True}
+ assert protocol.decode_event(protocol.encode_event(protocol.EVENT_SNAP_OPEN)) == {
+ "event": "snap_open"
+ }
+ assert protocol.decode_event(protocol.encode_ack("snap")) is None
+ assert protocol.decode_event('{"event": "reboot"}') is None
+ assert protocol.decode_command(
+ protocol.encode_command(protocol.CMD_SNAP_IMAGE, image="abc")
+ ) == {"cmd": "snap_image", "image": "abc"}
+
+
+async def test_an_open_card_keeps_the_sidecar_and_a_closed_one_lets_it_go(monkeypatch) -> None:
+ ctl = CUIndicatorController(_Bus())
+ ctl._loop = asyncio.get_running_loop()
+ quits: list[str] = []
+ monkeypatch.setattr(ctl, "_schedule_idle_quit", lambda: quits.append("scheduled"))
+
+ ctl._handle_sidecar_event({"event": "card", "open": True})
+ assert ctl._card_open is True and quits == []
+
+ ctl._handle_sidecar_event({"event": "card", "open": False})
+ assert ctl._card_open is False and quits == ["scheduled"]
+
+
+async def test_idle_quit_waits_while_the_card_is_open(monkeypatch) -> None:
+ ctl = CUIndicatorController(_Bus())
+ quit_calls: list[int] = []
+
+ async def fake_quit() -> None:
+ quit_calls.append(1)
+
+ monkeypatch.setattr(ctl, "_quit_sidecar", fake_quit)
+ ctl._card_open = True
+ await ctl._idle_quit()
+ assert quit_calls == []
+ ctl._card_open = False
+ await ctl._idle_quit()
+ assert quit_calls == [1]
+
+
+async def test_clicking_the_card_opens_the_editor_on_the_last_appshot(monkeypatch) -> None:
+ from jarvis.appshot.store import Appshot, get_store
+
+ store = get_store()
+ store.clear()
+ store.remember(
+ Appshot(
+ id="shot-7",
+ image=b"jpeg",
+ mime="image/jpeg",
+ width=1,
+ height=1,
+ label="selected area",
+ app_name="",
+ note="",
+ ui_text="",
+ trigger="hotkey",
+ taken_at=0.0,
+ ),
+ keep_s=60,
+ )
+ bus = _Bus()
+ ctl = CUIndicatorController(bus)
+ ctl._loop = asyncio.get_running_loop()
+ try:
+ ctl._handle_sidecar_event({"event": "snap_open"})
+ await asyncio.sleep(0.01)
+ finally:
+ store.clear()
+
+ edit = [e for e in bus.events if isinstance(e, AppshotEditRequested)]
+ show = [e for e in bus.events if isinstance(e, ShowWindowRequested)]
+ assert [e.appshot_id for e in edit] == ["shot-7"]
+ assert [e.source for e in show] == ["appshot_card"]
+
+
+async def test_the_drag_picture_waits_for_its_card_and_a_new_shutter_drops_it() -> None:
+ ctl = CUIndicatorController(_Bus())
+ assert await ctl.snap_image("b64-picture") is False, "no sidecar: nothing sent"
+ assert ctl._card_image_b64 == "b64-picture", "kept for the effect still on its way"
+ ctl.hold_for_snap()
+ assert ctl._card_image_b64 is None, "a new capture never wears the old picture"
+
+
+async def test_a_picture_that_may_not_be_kept_is_never_handed_to_the_card(monkeypatch) -> None:
+ import jarvis.appshot.effect as effect
+ from jarvis.appshot import service
+ from jarvis.appshot.store import Appshot
+
+ sent: list[bytes] = []
+
+ async def attach(image: bytes) -> None:
+ sent.append(image)
+
+ monkeypatch.setattr(effect, "attach_card_image", attach)
+
+ class Cfg:
+ class screen_context: # noqa: N801
+ deck_preview_s = 0.0
+
+ shot = Appshot(
+ id="x", image=b"jpeg", mime="image/jpeg", width=1, height=1, label="", app_name="",
+ note="", ui_text="", trigger="hotkey", taken_at=0.0,
+ )
+ await service._attach_to_card(shot, Cfg)
+ assert sent == []
+ Cfg.screen_context.deck_preview_s = 120.0
+ await service._attach_to_card(shot, Cfg)
+ assert sent == [b"jpeg"]
+
+
+def test_the_card_hint_follows_the_app_language() -> None:
+ from jarvis.appshot.effect import _CARD_HINTS, card_hint
+
+ class Cfg:
+ class ui: # noqa: N801
+ language = "de"
+
+ assert card_hint(Cfg) == _CARD_HINTS["de"]
+ Cfg.ui.language = "auto"
+ assert card_hint(Cfg) == _CARD_HINTS["en"]
+ assert set(_CARD_HINTS) == {"de", "en", "es"}