Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(appshot): editor in its own window, a card that comes back, edits that reach the assistant
rubenluetke10-beep1323dd6ab5fa
diff --git a/docs/appshots.md b/docs/appshots.mdindex c0247c852e..4fff3ff123 100644--- a/docs/appshots.md+++ b/docs/appshots.md@@ -57,12 +57,21 @@ the shutter and shows up as the last appshot.## The card in the corner, and the editorAfter the shutter the picture flies into the bottom-right corner of its-screen and rests there as a card for about six seconds (longer while the-pointer is on it):--- **Click** brings the app to the front with the **appshot editor** open- over whatever was on screen (nothing navigates away). See- [The editor](#the-editor).+screen and rests there as a card — CleanShot X's Quick Access Overlay. How+long is `[appshot].card_seconds` (Settings → Appshots → *Corner card*: 3, 6,+10 or 30 seconds, or until you close it); the pointer on it keeps it.++- **Hover** dims the picture and shows **Close** (top left), **Edit** (top+ right) and **Copy** / **Save** in the middle. Copy puts the picture on the+ clipboard and Save writes it to Downloads — both done by the main process+ (`jarvis/appshot/card_actions.py`), so the clipboard survives the overlay+ quitting on Linux; the card shows the result for a moment.+- **Click** (or Edit) opens the **appshot editor in a window of its own** in+ front of you; the app behind keeps its size and what it shows. Without a+ desktop shell (a browser, a headless host) the editor opens over the app's+ page instead. See [The editor](#the-editor).+- **Done** or **Close** in the editor window slides the picture back into+ the corner — the edited one after Done — so it stays at hand.- **Drag** the card into any app that accepts files or images (chat, mail,Explorer/Finder) to drop the picture there.- **Right-click** dismisses it.@@ -78,8 +87,10 @@ the card only opens the editor and shares nothing.The editor follows CleanShot X's annotate tool — same tools, same one-letterkeys, the same window shape — in this app's own look. It opens from the-corner card or from **Edit** on the last appshot (Settings → Appshots), as a-floating rounded window over the dimmed app; nothing navigates away.+corner card or from **Edit** on the last appshot (Settings → Appshots) — in+its own desktop window (`?view=appshot-editor`, `views/AppshotEditorWindow.tsx`),+or, without a desktop shell, as a floating rounded window over the dimmed+app. Nothing navigates away.- **Top bar:** close, crop and background, the tools as pills, the colourmenu (presets + any colour) and the size slider, then **Save** and@@ -153,6 +164,24 @@ same on Windows, macOS and Linux. The two native paths are the clipboardwithout either, Copy falls back to the browser clipboard and says so if thatfails too) and Save (`~/Downloads` on every OS).+## What the assistant gets after an edit++An appshot is two things at once: a screenshot the user keeps, and context+for the assistant. **Done** decides the second: the edited picture becomes+the appshot (`PUT /api/appshot/latest/image`), and `deliver_edit` in+`jarvis/appshot/service.py` hands it over with a note that the markings are+the user's — arrows, boxes, numbers and text point at what they mean, hidden+parts were hidden on purpose:++| Situation | Where the edit goes |+|---|---|+| A voice call runs and `target` is `auto` or `voice` | Into the call at once — even when the call already saw the original. A waiting original is withdrawn, so it does not follow later. |+| No call (or `target = message`) | Onto the next message — even when the original was sent already. |+| `target = voice` and no call | Nowhere; the edit is kept as the last appshot. |++The editor says which one happened. Copy, Save and Drag never send anything+to the assistant; they are the screenshot-tool half.+## Where a shortcut appshot goes| Destination | Running voice call | No voice call |@@ -208,6 +237,7 @@ original any-order behaviour.| `target` | `"auto"` | `auto` · `message` · `voice` (table above) || `sound` | `true` | Shutter sound; also needs `[ui].sound_effects` || `effect` | `true` | Flash and corner thumbnail |+| `card_seconds` | `6` | How long the corner card rests, 0–600 seconds; `0` = until closed |## Operating systemsdiff --git a/jarvis/appshot/card_actions.py b/jarvis/appshot/card_actions.pynew file mode 100644index 0000000000..30d971aa91--- /dev/null+++ b/jarvis/appshot/card_actions.py@@ -0,0 +1,171 @@+"""What the corner card can do besides opening the editor.++The card (a PySide6 window in the indicator sidecar) shows Copy and Save on+hover. The sidecar only reports the press; the work happens here in the main+process, on the held appshot itself:++* **Copy** goes through :mod:`jarvis.platform.clipboard_image`, which owns the+ clipboard natively on every OS. A Qt clipboard in the sidecar would lose the+ picture on Linux the moment the sidecar quits.+* **Save** writes a PNG into ``~/Downloads``, like every other save in the app.++And when the editor closes, :func:`return_to_corner` slides the (edited)+appshot back into the corner, so it stays at hand — CleanShot X's Quick Access+Overlay. Every function here returns a result and never raises.+"""++from __future__ import annotations++import asyncio+import base64+import io+import logging+import time+from pathlib import Path+from typing import Any++log = logging.getLogger(__name__)++#: Card wording — app chrome, so it follows ``[ui].language`` like the hint.+_LABELS: dict[str, dict[str, str]] = {+ "en": {+ "edit": "Edit",+ "copy": "Copy",+ "save": "Save",+ "close": "Close",+ "copied": "Copied",+ "saved": "Saved to Downloads",+ "failed": "That did not work",+ "gone": "No longer kept",+ },+ "de": {+ "edit": "Bearbeiten", # i18n-allow: product UI string+ "copy": "Kopieren", # i18n-allow: product UI string+ "save": "Speichern", # i18n-allow: product UI string+ "close": "Schließen", # i18n-allow: product UI string+ "copied": "Kopiert", # i18n-allow: product UI string+ "saved": "In Downloads gespeichert", # i18n-allow: product UI string+ "failed": "Das hat nicht geklappt", # i18n-allow: product UI string+ "gone": "Nicht mehr aufbewahrt", # i18n-allow: product UI string+ },+ "es": {+ "edit": "Editar", # i18n-allow: product UI string+ "copy": "Copiar", # i18n-allow: product UI string+ "save": "Guardar", # i18n-allow: product UI string+ "close": "Cerrar", # i18n-allow: product UI string+ "copied": "Copiado", # i18n-allow: product UI string+ "saved": "Guardado en Descargas", # i18n-allow: product UI string+ "failed": "No ha funcionado", # i18n-allow: product UI string+ "gone": "Ya no se conserva", # i18n-allow: product UI string+ },+}+++def card_labels(config: Any) -> dict[str, str]:+ language = str(getattr(getattr(config, "ui", None), "language", "") or "").lower()[:2]+ return dict(_LABELS.get(language, _LABELS["en"]))+++def card_rest_ms(config: Any) -> int:+ """How long the card stays untouched; ``0`` = until the user closes it."""+ seconds = getattr(getattr(config, "appshot", None), "card_seconds", 6)+ try:+ value = int(seconds)+ except (TypeError, ValueError):+ value = 6+ return max(0, value) * 1000+++def as_png(image: bytes) -> bytes:+ """The held picture (JPEG or PNG) as PNG bytes."""+ if image.startswith(b"\x89PNG\r\n\x1a\n"):+ return image+ from PIL import Image # noqa: PLC0415++ with Image.open(io.BytesIO(image)) as picture:+ out = io.BytesIO()+ picture.convert("RGB").save(out, format="PNG")+ return out.getvalue()+++def save_to_downloads(png: bytes, *, folder: Path | None = None, now: float | None = None) -> Path:+ """Write ``png`` into Downloads under a fresh name and return the path."""+ target = folder or (Path.home() / "Downloads")+ target.mkdir(parents=True, exist_ok=True)+ moment = time.time() if now is None else now+ stem = time.strftime("appshot-%Y%m%d-%H%M%S", time.localtime(moment))+ path = target / f"{stem}.png"+ counter = 1+ while path.exists():+ counter += 1+ path = target / f"{stem}-{counter}.png"+ path.write_bytes(png)+ return path+++async def run_card_action(action: str) -> str:+ """Do ``copy`` or ``save`` on the held appshot; the card's status line."""+ from jarvis.appshot.store import get_store # noqa: PLC0415+ from jarvis.core.config import load_config # noqa: PLC0415++ config = await asyncio.to_thread(load_config)+ labels = card_labels(config)+ shot = get_store().latest()+ if shot is None:+ return labels["gone"]+ try:+ png = await asyncio.to_thread(as_png, shot.image)+ if action == "copy":+ from jarvis.platform.clipboard_image import write_png # noqa: PLC0415++ 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)+ log.info("appshot: card saved %s", path.name)+ return labels["saved"]+ except Exception: # noqa: BLE001 - the card says so; nothing else depends on it+ log.warning("appshot: card action %r failed", action, exc_info=True)+ return labels["failed"]+ return labels["failed"]+++async def return_to_corner() -> bool:+ """Slide the held appshot back into the corner card. ``False`` = not shown."""+ try:+ from jarvis.appshot.effect import card_hint, thumbnail_from_image # noqa: PLC0415+ from jarvis.appshot.store import get_store # noqa: PLC0415+ from jarvis.core.config import load_config # noqa: PLC0415+ from jarvis.cu.indicator.controller import get_indicator_controller # noqa: PLC0415++ controller = get_indicator_controller()+ shot = get_store().latest()+ if controller is None or shot is None:+ return False+ config = await asyncio.to_thread(load_config)+ if not bool(getattr(getattr(config, "appshot", None), "effect", True)):+ return False+ thumb = await asyncio.to_thread(thumbnail_from_image, shot.image)+ keep = float(config.screen_context.deck_preview_s) > 0+ return bool(+ await controller.show_card(+ thumb_b64=base64.b64encode(thumb).decode("ascii"),+ image_b64=base64.b64encode(shot.image).decode("ascii") if keep else "",+ hint=card_hint(config),+ rest_ms=card_rest_ms(config),+ labels=card_labels(config),+ )+ )+ except Exception: # noqa: BLE001 - the card is a convenience, never a failure+ log.warning("appshot: could not return the appshot to the corner", exc_info=True)+ return False+++__all__ = [+ "as_png",+ "card_labels",+ "card_rest_ms",+ "return_to_corner",+ "run_card_action",+ "save_to_downloads",+]diff --git a/jarvis/appshot/editor_window.py b/jarvis/appshot/editor_window.pynew file mode 100644index 0000000000..4e674b0337--- /dev/null+++ b/jarvis/appshot/editor_window.py@@ -0,0 +1,63 @@+"""Open the appshot editor in a window of its own.++A click on the corner card (or "Edit" on the Appshots page) should put the+editor in front of the user, CleanShot X style — not raise the whole app and+not change what the app shows. The desktop shell can open a detached window+for that; a headless or browser-only run cannot, and then the caller falls+back to the editor inside the app's page.++The shell registers its opener at start-up (``register_window_opener``); this+module never imports the shell, so it stays importable on a bare server.+"""++from __future__ import annotations++import asyncio+import logging+import re+from collections.abc import Callable+from typing import Any++log = logging.getLogger(__name__)++#: The detached view id; mirrored by ``DETACHABLE_VIEWS`` in the desktop shell+#: and by the frontend's window entry (``view=appshot-editor``).+EDITOR_VIEW = "appshot-editor"++#: Appshot ids are uuid hex; nothing else may reach the window URL.+_ID = re.compile(r"^[0-9a-f]{8,64}$")++_opener: Callable[[str], dict[str, Any]] | None = None+++def register_window_opener(opener: Callable[[str], dict[str, Any]] | None) -> None:+ """Install (or, with ``None``, remove) the shell's window opener.++ ``opener(query)`` must open or re-point the ``appshot-editor`` window and+ may block — it is always called from a worker thread.+ """+ global _opener+ _opener = opener+++def can_open_window() -> bool:+ return _opener is not None+++async def open_editor_window(shot_id: str) -> bool:+ """Open the editor window on ``shot_id``. ``False`` = use the page instead."""+ opener = _opener+ if opener is None or not _ID.match(shot_id or ""):+ return False+ try:+ result = await asyncio.to_thread(opener, f"appshot={shot_id}")+ except Exception: # noqa: BLE001 - the page editor is the honest fallback+ log.warning("appshot: the editor window could not be opened", exc_info=True)+ return False+ ok = bool(isinstance(result, dict) and result.get("ok"))+ if not ok:+ log.info("appshot: no editor window (%s); using the page", (result or {}).get("reason"))+ return ok+++__all__ = ["EDITOR_VIEW", "can_open_window", "open_editor_window", "register_window_opener"]diff --git a/jarvis/appshot/effect.py b/jarvis/appshot/effect.pyindex 92dab95bf3..f0191308d3 100644--- a/jarvis/appshot/effect.py+++ b/jarvis/appshot/effect.py@@ -7,7 +7,10 @@ frame in memory and piped to the local indicator sidecar; it is never storedand 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+editor (in its own window where the desktop shell allows), a drag hands the+picture to another app, and on hover it offers Copy, Save, Edit and Close+(:mod:`jarvis.appshot.card_actions`). How long it rests is+``[appshot].card_seconds`` (``0`` = until closed). For that drag thefinished, privacy-filtered appshot follows (:func:`attach_card_image`) — theraw-frame thumbnail itself never leaves the sidecar."""@@ -72,6 +75,8 @@ async def _play(config = await asyncio.to_thread(load_config)if not bool(getattr(getattr(config, "appshot", None), "effect", True)):return+ from jarvis.appshot.card_actions import card_labels, card_rest_ms # noqa: PLC0415+thumb = await asyncio.to_thread(thumbnail_jpeg, size, rgb)monitor, rect = placement(bbox, monitors)shown = await controller.snap(@@ -79,6 +84,8 @@ async def _play(rect=rect,thumb_b64=base64.b64encode(thumb).decode("ascii"),hint=card_hint(config),+ rest_ms=card_rest_ms(config),+ labels=card_labels(config),)if not shown:log.info("appshot: shutter effect could not be shown on this desktop")@@ -110,6 +117,18 @@ def thumbnail_jpeg(size: tuple[int, int], rgb: bytes) -> bytes:return buffer.getvalue()+def thumbnail_from_image(image: bytes) -> bytes:+ """A small JPEG of a finished (edited) appshot, for the card coming back."""+ from PIL import Image # noqa: PLC0415++ with Image.open(io.BytesIO(image)) as picture:+ small = picture.convert("RGB")+ small.thumbnail((_THUMB_EDGE, _THUMB_EDGE), Image.Resampling.BILINEAR)+ buffer = io.BytesIO()+ small.save(buffer, format="JPEG", quality=82)+ return buffer.getvalue()++def placement(bbox: tuple[int, int, int, int], monitors: list[dict]) -> tuple[list[int], list[float]]:diff --git a/jarvis/appshot/service.py b/jarvis/appshot/service.pyindex ad36006506..c1f3966e73 100644--- a/jarvis/appshot/service.py+++ b/jarvis/appshot/service.py@@ -245,14 +245,57 @@ async def _publish(bus: Any | None, shot: Appshot, delivered_to: str) -> None:log.warning("appshot: receipt publication failed", exc_info=True)+#: Rides with an edited appshot, after its original evidence note.+EDIT_NOTE = (+ "EDITED BY THE USER: this is the same appshot with the user's own markings. "+ "Arrows, boxes, circles, numbers, highlights and text are theirs and point "+ "at what they mean; blurred or pixelated parts were hidden on purpose. Read "+ "the markings first."+)+++async def deliver_edit(shot: Appshot) -> str:+ """Hand the user's edited appshot to the assistant; where it went.++ The edit replaces the picture wherever the original still waits (the+ store already swapped it). Then: a running voice call gets the edited+ picture at once when ``[appshot].target`` allows it — including a call+ that already saw the original — and otherwise the next message carries+ it, even when the original has been sent already. ``none`` only when the+ target is voice-only and no call runs.+ """+ config = await asyncio.to_thread(_load_config)+ target = str(config.appshot.target)+ note = shot.note+ if EDIT_NOTE not in note:+ note = "\n\n".join(part for part in (note, EDIT_NOTE) if part)+ edited = replace(shot, note=note)+ store = get_store()+ from jarvis.appshot.delivery import deliver_to_live # noqa: PLC0415++ delivered_to = "none"+ if target in ("auto", "voice") and await deliver_to_live(edited.image, edited.mime, note):+ # The call has it now; the waiting original must not follow later.+ store.take_pending(shot.id)+ delivered_to = "voice"+ elif target != "voice":+ store.park(edited, ttl_s=float(config.screen_context.ttl_s))+ delivered_to = "message"+ store.mark_delivered(shot.id, delivered_to)+ log.info("appshot: edited %s -> %s", shot.label, delivered_to)+ return delivered_to++def take_pending_for_turn() -> Appshot | None:"""The appshot waiting for the next message, removed on the way out."""return get_store().take_pending()__all__ = [+ "EDIT_NOTE","AppshotResult","Scope",+ "deliver_edit","record_turn_capture","shot_from_context","take_appshot",diff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex 8bbf3d34f6..a834e4a790 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -2714,6 +2714,11 @@ class AppshotConfig(BaseModel):#: Flash and thumbnail animation on the captured window.effect: bool = True+ #: Seconds the appshot card rests in the screen corner before it slides+ #: away (read by ``jarvis.appshot.card_actions``); ``0`` keeps it there+ #: until the user closes it.+ card_seconds: int = Field(default=6, ge=0, le=600)+class ComputerUseConfig(BaseModel):"""Top-level ``[computer_use]`` config for the Computer-Use harness.diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.pyindex 1a5fa86669..fd287ee862 100644--- a/jarvis/core/config_writer.py+++ b/jarvis/core/config_writer.py@@ -1000,12 +1000,12 @@ def set_screen_context_settings(#: Keys ``[appshot]`` accepts — same allowlist reasoning as Screen Context.#: The master switch is ``[screen_context].enabled``, written by the setter above.APPSHOT_SETTING_KEYS: frozenset[str] = frozenset(- {"hotkey", "region_hotkey", "target", "sound", "effect"}+ {"hotkey", "region_hotkey", "target", "sound", "effect", "card_seconds"})def set_appshot_settings(- values: dict[str, str | bool],+ values: dict[str, str | bool | int],*,path: Path = DEFAULT_CONFIG_FILE,) -> None:diff --git a/jarvis/cu/indicator/controller.py b/jarvis/cu/indicator/controller.pyindex 48aa465d2d..89c539b9c9 100644--- a/jarvis/cu/indicator/controller.py+++ b/jarvis/cu/indicator/controller.py@@ -123,6 +123,8 @@ class CUIndicatorController:# 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+ #: The monitor the last shutter played on — where a card comes back.+ self._card_monitor: list[int] | None = None# ------------------------------------------------------------------ wiringdef wire(self) -> None:@@ -275,9 +277,20 @@ class CUIndicatorController:self._card_image_b64 = None # a new capture: the old picture is not its pictureasync def snap(- self, *, monitor: list[int], rect: list[float], thumb_b64: str, hint: str = ""+ self,+ *,+ monitor: list[int],+ rect: list[float],+ thumb_b64: str,+ hint: str = "",+ rest_ms: int = 6000,+ labels: dict[str, str] | None = None,) -> bool:- """Play the appshot shutter effect. ``False`` when it cannot run here."""+ """Play the appshot shutter effect. ``False`` when it cannot run here.++ ``rest_ms`` is how long the corner card stays untouched; ``0`` keeps it+ until the user closes it (``[appshot].card_seconds``).+ """ok, reason = self._border_capability()if not ok:log.debug("[appshot-effect] unavailable: %s", reason)@@ -291,6 +304,7 @@ class CUIndicatorController:# Without a border there was no guard yet: a later capture must# blank the resting thumbnail before its grab on every OS.capture_guard.register_hook(self._suppress_for_grab)+ self._card_monitor = list(monitor)shown = await asyncio.to_thread(self._send_and_wait,protocol.CMD_SNAP,@@ -299,6 +313,8 @@ class CUIndicatorController:rect=list(rect),thumb=thumb_b64,hint=hint,+ rest_ms=int(rest_ms),+ labels=dict(labels or {}),)image = self._card_image_b64if shown and image:@@ -308,6 +324,52 @@ class CUIndicatorController:self._schedule_idle_quit()return shown+ async def show_card(+ self,+ *,+ thumb_b64: str,+ image_b64: str,+ hint: str = "",+ rest_ms: int = 6000,+ labels: dict[str, str] | None = None,+ ) -> bool:+ """Put a picture straight back into the corner card — no flash, no flight.++ Used when the editor closes: the (edited) appshot slides back into the+ corner of the screen its shutter played on, so it stays at hand.+ """+ ok, reason = self._border_capability()+ if not ok:+ log.debug("[appshot-effect] card unavailable: %s", reason)+ return False+ self._loop = asyncio.get_running_loop()+ async with self._lock:+ self.hold_for_snap()+ self._card_image_b64 = image_b64 or None+ await asyncio.to_thread(self._spawn_sidecar)+ if self._proc is None:+ return False+ capture_guard.register_hook(self._suppress_for_grab)+ shown = await asyncio.to_thread(+ self._send_and_wait,+ protocol.CMD_CARD,+ _SHOW_ACK_TIMEOUT_S,+ monitor=list(self._card_monitor or []),+ thumb=thumb_b64,+ hint=hint,+ rest_ms=int(rest_ms),+ labels=dict(labels or {}),+ )+ if shown and image_b64:+ await asyncio.to_thread(+ self._send_and_wait,+ protocol.CMD_SNAP_IMAGE,+ _SHOW_ACK_TIMEOUT_S,+ image=image_b64,+ )+ 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.@@ -339,10 +401,33 @@ class CUIndicatorController: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")+ elif event == protocol.EVENT_CARD_ACTION:+ action = str(payload.get("action", ""))+ if action in ("copy", "save"):+ asyncio.get_running_loop().create_task(+ self._card_action(action), name="appshot-card-action"+ )++ async def _card_action(self, action: str) -> None:+ """Copy or save from the card's hover buttons, then tell the card how it went."""+ from jarvis.appshot.card_actions import run_card_action # noqa: PLC0415++ status = await run_card_action(action)+ if self._proc is None or self._proc.poll() is not None:+ return+ await asyncio.to_thread(+ self._send_and_wait, protocol.CMD_CARD_STATUS, _SHOW_ACK_TIMEOUT_S, text=status+ )async def _open_editor(self) -> None:- """The card was clicked: show the app with the appshot editor."""+ """The card was clicked: open the appshot editor in front of the user.++ In its own window where the desktop shell can open one, so the app+ behind keeps its size and what it shows; otherwise the app comes to+ the front with the editor over its page.+ """try:+ from jarvis.appshot.editor_window import open_editor_window # noqa: PLC0415from jarvis.appshot.store import get_store # noqa: PLC0415from jarvis.core.events import ( # noqa: PLC0415AppshotEditRequested,@@ -350,6 +435,8 @@ class CUIndicatorController:)shot = get_store().latest()+ if shot is not None and await open_editor_window(shot.id):+ returnawait self._bus.publish(AppshotEditRequested(source_layer="appshot", appshot_id=shot.id if shot is not None else ""diff --git a/jarvis/cu/indicator/protocol.py b/jarvis/cu/indicator/protocol.pyindex 0c1cdddbf0..daa06468f6 100644--- a/jarvis/cu/indicator/protocol.py+++ b/jarvis/cu/indicator/protocol.py@@ -41,14 +41,30 @@ CMD_UNBLANK = "unblank"CMD_QUIT = "quit"CMD_SNAP = "snap"CMD_SNAP_IMAGE = "snap_image"+#: Put a picture straight into the corner card (the editor closed).+CMD_CARD = "card"+#: A short status line on the card ("Copied", "Saved to Downloads").+CMD_CARD_STATUS = "card_status"ALL_COMMANDS = frozenset(- {CMD_SHOW, CMD_HIDE, CMD_BLANK, CMD_UNBLANK, CMD_QUIT, CMD_SNAP, CMD_SNAP_IMAGE}+ {+ CMD_SHOW,+ CMD_HIDE,+ CMD_BLANK,+ CMD_UNBLANK,+ CMD_QUIT,+ CMD_SNAP,+ CMD_SNAP_IMAGE,+ CMD_CARD,+ CMD_CARD_STATUS,+ })EVENT_CARD = "card"EVENT_SNAP_OPEN = "snap_open"-ALL_EVENTS = frozenset({EVENT_CARD, EVENT_SNAP_OPEN})+#: A hover button on the card was pressed (``action``: ``copy`` | ``save``).+EVENT_CARD_ACTION = "card_action"+ALL_EVENTS = frozenset({EVENT_CARD, EVENT_SNAP_OPEN, EVENT_CARD_ACTION})#: Sidecar exit code when no usable GUI stack exists (PySide6 missing or#: no display). The controller logs it as an expected degradation.@@ -111,12 +127,15 @@ def decode_ack(line: str) -> str | None:__all__ = ["ALL_COMMANDS","CMD_BLANK",+ "CMD_CARD",+ "CMD_CARD_STATUS","CMD_HIDE","CMD_QUIT","CMD_SHOW","CMD_SNAP","CMD_SNAP_IMAGE","EVENT_CARD",+ "EVENT_CARD_ACTION","EVENT_SNAP_OPEN","CMD_UNBLANK","EXIT_NO_GUI",diff --git a/jarvis/cu/indicator/renderer.py b/jarvis/cu/indicator/renderer.pyindex 2403ac24c4..d69b110a97 100644--- a/jarvis/cu/indicator/renderer.py+++ b/jarvis/cu/indicator/renderer.py@@ -221,6 +221,11 @@ _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+#: How long a status line ("Copied") stays on the card.+_CARD_STATUS_MS = 1600+#: Hover buttons: the Copy / Save pills and the round Close / Edit chips.+_CARD_BUTTON_H = 28.0+_CARD_ROUND = 26.0#: Drag files older than this are removed the next time one is written._DRAG_FILE_MAX_AGE_S = 3600@@ -397,12 +402,55 @@ class _SnapWindow(QWidget):painter.end()+def _card_rect(screen, thumb: QImage) -> QRectF:+ """Where the resting card sits: the bottom-right of ``screen``'s work area.++ Absolute (virtual-desktop) logical coordinates. Shared by the shutter+ flight's landing spot and a card that comes back after the editor.+ """+ aspect = thumb.height() / max(1, thumb.width()) if not thumb.isNull() else 0.6+ tw = float(_SNAP_THUMB_W)+ th = tw * aspect+ if th > _SNAP_THUMB_MAX_H:+ th = float(_SNAP_THUMB_MAX_H)+ tw = th / max(aspect, 1e-6)+ # Inside the work area, so the card never sits under the taskbar.+ avail = screen.availableGeometry()+ right = float(avail.right() + 1)+ bottom = float(avail.bottom() + 1)+ return QRectF(right - tw - _SNAP_MARGIN, bottom - th - _SNAP_MARGIN, tw, th)+++#: Default card wording; the main process sends the user's language.+_CARD_LABELS = {+ "edit": "Edit",+ "copy": "Copy",+ "save": "Save",+ "close": "Close",+}++class _CardWindow(QWidget):- """The resting thumbnail: hover keeps it, click edits, drag shares."""+ """The resting thumbnail, CleanShot X's Quick Access Overlay in small.++ Hover shows Close (top-left), Edit (top-right) and Copy / Save in the+ middle; a click anywhere else edits, a drag shares the picture, a+ right-click dismisses it. ``rest_ms`` is how long it stays untouched —+ ``0`` keeps it until the user closes it.+ """_PAD = 12 # transparent margin that holds the soft shadow- def __init__(self, rect: QRectF, thumb: QImage, hint: str, owner: Renderer) -> None:+ def __init__(+ self,+ rect: QRectF,+ thumb: QImage,+ hint: str,+ owner: Renderer,+ *,+ rest_ms: int = _CARD_REST_MS,+ labels: dict[str, str] | None = None,+ ) -> None:super().__init__(None)self.setWindowFlags(Qt.WindowType.FramelessWindowHint@@ -424,9 +472,17 @@ class _CardWindow(QWidget):self._thumb = thumbself._hint = hintself._owner = owner+ self._rest_ms = max(0, int(rest_ms))+ self._labels = {**_CARD_LABELS, **(labels or {})}self._hover = False+ self._hot = "" # the hover button under the pointerself._press: QPointF | None = None+ self._press_button = ""self._leaving = False+ self._status = ""+ self._status_timer = QTimer(self)+ self._status_timer.setSingleShot(True)+ self._status_timer.timeout.connect(self._clear_status)self._dismiss = QTimer(self)self._dismiss.setSingleShot(True)self._dismiss.timeout.connect(self.leave)@@ -436,11 +492,27 @@ class _CardWindow(QWidget):self._out.setDuration(_CARD_OUT_MS)self._out.valueChanged.connect(self._on_out)self._out.finished.connect(self._gone)+ self._in = QVariantAnimation(self)+ self._in.setStartValue(1.0)+ self._in.setEndValue(0.0)+ self._in.setDuration(_CARD_OUT_MS)+ self._in.valueChanged.connect(self._on_out)self._origin = self.pos()- def start(self) -> None:- self.show()- self._dismiss.start(_CARD_REST_MS)+ def start(self, *, slide_in: bool = False) -> None:+ if slide_in:+ # Back from the editor: slide in from the edge it leaves through.+ self._origin = self.pos()+ self._on_out(1.0)+ self.show()+ self._in.start()+ else:+ self.show()+ self._arm_dismiss(self._rest_ms)++ def _arm_dismiss(self, ms: int) -> None:+ if self._rest_ms > 0 and not self._leaving:+ self._dismiss.start(ms)# -- lifecycle -----------------------------------------------------------def leave(self) -> None:@@ -449,12 +521,14 @@ class _CardWindow(QWidget):returnself._leaving = Trueself._dismiss.stop()+ self._in.stop()self._origin = self.pos()self._out.start()def finish_now(self) -> None:self._leaving = Trueself._dismiss.stop()+ self._in.stop()self._out.stop()self._gone()@@ -470,6 +544,16 @@ class _CardWindow(QWidget):owner.card_gone(self)self.deleteLater()+ def show_status(self, text: str) -> None:+ """A short line over the card ("Copied", "Saved to Downloads")."""+ self._status = text+ self._status_timer.start(_CARD_STATUS_MS)+ self.update()++ def _clear_status(self) -> None:+ self._status = ""+ self.update()+# -- input ---------------------------------------------------------------def showEvent(self, event) -> None: # noqa: N802 (Qt override)super().showEvent(event)@@ -490,8 +574,8 @@ class _CardWindow(QWidget):def leaveEvent(self, event) -> None: # noqa: N802del eventself._hover = False- if not self._leaving:- self._dismiss.start(_CARD_AFTER_HOVER_MS)+ self._hot = ""+ self._arm_dismiss(_CARD_AFTER_HOVER_MS)self.update()def mousePressEvent(self, event) -> None: # noqa: N802@@ -499,9 +583,14 @@ class _CardWindow(QWidget):self.leave()elif event.button() == Qt.MouseButton.LeftButton:self._press = event.position()+ self._press_button = self._button_at(event.position())def mouseMoveEvent(self, event) -> None: # noqa: N802- if self._press is None or self._leaving:+ hot = self._button_at(event.position()) if self._hover else ""+ if hot != self._hot:+ self._hot = hot+ self.update()+ if self._press is None or self._leaving or self._press_button:returnmoved = event.position() - self._pressif abs(moved.x()) + abs(moved.y()) > _CARD_DRAG_SLOP:@@ -512,7 +601,18 @@ class _CardWindow(QWidget):if event.button() != Qt.MouseButton.LeftButton or self._press is None:returnself._press = None- if self._owner is not None and not self._leaving:+ pressed, self._press_button = self._press_button, ""+ if self._owner is None or self._leaving:+ return+ released = self._button_at(event.position())+ if pressed and pressed != released:+ return # pressed a button, let go elsewhere: nothing+ if pressed == "close":+ self.leave()+ elif pressed in ("copy", "save"):+ if self._owner.card_image is not None:+ self._owner.card_action(pressed)+ else: # "edit" or the picture itselfself._owner.card_clicked(self)def _start_drag(self) -> None:@@ -541,42 +641,131 @@ class _CardWindow(QWidget):self.setWindowOpacity(1.0)self.leave()+ # -- hover buttons -------------------------------------------------------+ def _card_area(self) -> QRectF:+ pad = float(self._PAD)+ return QRectF(pad, pad, self.width() - 2 * pad, self.height() - 2 * pad)++ def _buttons(self) -> dict[str, QRectF]:+ """Hit areas of the hover buttons, in widget coordinates."""+ rect = self._card_area()+ font = _card_font()+ metrics = QFontMetricsF(font)+ h = _CARD_BUTTON_H+ buttons: dict[str, QRectF] = {+ "close": QRectF(rect.left() + 8, rect.top() + 8, _CARD_ROUND, _CARD_ROUND),+ }+ edit_w = metrics.horizontalAdvance(self._labels["edit"]) + 22.0+ buttons["edit"] = QRectF(rect.right() - 8 - edit_w, rect.top() + 8, edit_w, _CARD_ROUND)+ if self._owner is not None and self._owner.card_image is not None:+ widths = [metrics.horizontalAdvance(self._labels[k]) + 28.0 for k in ("copy", "save")]+ width = max(widths + [86.0])+ gap = 8.0+ if width * 2 + gap <= rect.width() - 24:+ y = rect.center().y() - h / 2+ left = rect.center().x() - width - gap / 2+ buttons["copy"] = QRectF(left, y, width, h)+ buttons["save"] = QRectF(left + width + gap, y, width, h)+ else:+ top = rect.center().y() - h - gap / 2+ left = rect.center().x() - width / 2+ buttons["copy"] = QRectF(left, top, width, h)+ buttons["save"] = QRectF(left, top + h + gap, width, h)+ return buttons++ def _button_at(self, pos: QPointF) -> str:+ if not self._hover:+ return ""+ for name, area in self._buttons().items():+ if area.adjusted(-2, -2, 2, 2).contains(pos):+ return name+ return ""+# -- painting ------------------------------------------------------------def paintEvent(self, event) -> None: # noqa: N802 (Qt override)del eventpainter = 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)+ rect = self._card_area()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)+ if self._status:+ self._paint_scrim(painter, rect, 150)+ self._paint_centered(painter, rect, self._status)+ elif self._hover:+ self._paint_scrim(painter, rect, 105)+ self._paint_buttons(painter)+ if 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)+ def _paint_scrim(self, painter: QPainter, rect: QRectF, alpha: int) -> None:clip = QPainterPath()clip.addRoundedRect(rect, _SNAP_RADIUS, _SNAP_RADIUS)painter.save()painter.setClipPath(clip)- painter.fillRect(band, QColor(10, 10, 12, 200))+ painter.fillRect(rect, QColor(0, 0, 0, alpha))painter.restore()++ def _paint_buttons(self, painter: QPainter) -> None:+ font = _card_font()+ painter.setFont(font)+ for name, area in self._buttons().items():+ hot = name == self._hot+ painter.setPen(Qt.PenStyle.NoPen)+ if name in ("copy", "save"):+ # Light pills on the dimmed picture, like CleanShot's overlay.+ painter.setBrush(QColor(255, 255, 255, 255 if hot else 228))+ painter.drawRoundedRect(area, area.height() / 2, area.height() / 2)+ painter.setPen(QColor(20, 20, 22))+ painter.drawText(area, Qt.AlignmentFlag.AlignCenter, self._labels[name])+ continue+ painter.setBrush(QColor(28, 28, 30, 240 if hot else 200))+ painter.drawRoundedRect(area, area.height() / 2, area.height() / 2)+ if name == "close":+ pen = QPen(QColor(255, 255, 255, 235))+ pen.setWidthF(1.6)+ pen.setCapStyle(Qt.PenCapStyle.RoundCap)+ painter.setPen(pen)+ c = area.center()+ d = area.width() * 0.2+ painter.drawLine(QPointF(c.x() - d, c.y() - d), QPointF(c.x() + d, c.y() + d))+ painter.drawLine(QPointF(c.x() - d, c.y() + d), QPointF(c.x() + d, c.y() - d))+ else:+ painter.setPen(QColor(255, 255, 255, 240))+ painter.drawText(area, Qt.AlignmentFlag.AlignCenter, self._labels[name])++ def _paint_centered(self, painter: QPainter, rect: QRectF, text: str) -> None:+ font = _card_font()+ font.setPointSizeF(10.0)painter.setFont(font)- painter.setPen(QColor(255, 255, 255, 235))+ painter.setPen(QColor(255, 255, 255, 245))+ painter.drawText(rect, Qt.AlignmentFlag.AlignCenter | Qt.TextFlag.TextWordWrap, text)++ def _paint_hint(self, painter: QPainter, rect: QRectF) -> None:+ font = QFont()+ font.setPointSizeF(8.5)+ font.setWeight(QFont.Weight.Medium)+ metrics = QFontMetricsF(font)+ h = metrics.height() + 10.0+ band = QRectF(rect.x(), rect.bottom() - h, rect.width(), h)+ painter.setFont(font)+ painter.setPen(QColor(255, 255, 255, 200))painter.drawText(band, Qt.AlignmentFlag.AlignCenter, self._hint)+def _card_font() -> QFont:+ font = QFont()+ font.setPointSizeF(9.0)+ font.setWeight(QFont.Weight.DemiBold)+ return font++class Renderer(QObject):"""Owns the per-monitor windows, the animations, and the IPC slots."""@@ -587,6 +776,8 @@ class Renderer(QObject):self._snaps: list[_SnapWindow] = []self._card: _CardWindow | None = Noneself._card_hint = ""+ self._card_rest_ms = _CARD_REST_MS+ self._card_labels: dict[str, str] = {}#: The finished (redacted) picture a drag from the card hands out.self.card_image: QImage | None = Noneself._hint = ""@@ -650,6 +841,11 @@ class Renderer(QObject):self._snap(payload)elif cmd == protocol.CMD_SNAP_IMAGE:self._snap_image(payload)+ elif cmd == protocol.CMD_CARD:+ self._card_cmd(payload)+ elif cmd == protocol.CMD_CARD_STATUS:+ if self._card is not None:+ self._card.show_status(str(payload.get("text", "")))elif cmd == protocol.CMD_QUIT:_ack(cmd)self._app.quit()@@ -701,6 +897,7 @@ class Renderer(QObject):self._card.finish_now()self.card_image = Noneself._card_hint = str(payload.get("hint", "") or "")+ self._take_card_options(payload)win = _SnapWindow(screen, rect, thumb, self._snap_landed, self._snap_done)self._snaps.append(win)win.start()@@ -709,11 +906,56 @@ 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)+ def _take_card_options(self, payload: dict) -> None:+ try:+ self._card_rest_ms = max(0, int(payload.get("rest_ms", _CARD_REST_MS)))+ except (TypeError, ValueError):+ self._card_rest_ms = _CARD_REST_MS+ labels = payload.get("labels")+ self._card_labels = (+ {str(k): str(v) for k, v in labels.items()} if isinstance(labels, dict) else {}+ )++ def _new_card(self, rect: QRectF, thumb: QImage) -> _CardWindow:+ card = _CardWindow(+ rect,+ thumb,+ self._card_hint,+ self,+ rest_ms=self._card_rest_ms,+ labels=self._card_labels,+ )self._card = card_emit(protocol.EVENT_CARD, open=True)- card.start()+ return card++ def _snap_landed(self, rect: QRectF, thumb: QImage) -> None:+ self._new_card(rect, thumb).start()++ def _card_cmd(self, payload: dict) -> None:+ """The editor closed: slide the (edited) picture back into the corner."""+ thumb = QImage()+ raw = payload.get("thumb")+ if isinstance(raw, str) and raw:+ thumb.loadFromData(QByteArray.fromBase64(raw.encode("ascii")))+ if thumb.isNull():+ return+ monitor = payload.get("monitor")+ screen = _match_screen(monitor if isinstance(monitor, list) else [])+ if screen is None:+ return+ for old in list(self._snaps):+ old.finish_now()+ if self._card is not None:+ self._card.finish_now()+ self.card_image = None+ self._card_hint = str(payload.get("hint", "") or "")+ self._take_card_options(payload)+ self._new_card(_card_rect(screen, thumb), thumb).start(slide_in=True)++ def card_action(self, action: str) -> None:+ """A hover button: the main process copies or saves the held appshot."""+ _emit(protocol.EVENT_CARD_ACTION, action=action)def _snap_image(self, payload: dict) -> None:raw = payload.get("image")diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex ce5863368e..55ec2949d9 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -113,6 +113,10 @@ DETACHABLE_VIEWS: dict[str, str] = {# picture is something you keep looking at WHILE you carry on working, and# on a second monitor it stops competing with the section that produced it."visualization": "Visualization",+ # The appshot editor, CleanShot X style: a click on the corner card opens+ # it in front of the user without raising or resizing the main window.+ # Always on one appshot (``&appshot=<id>``); ONE window is reused.+ "appshot-editor": "Appshot Editor",}META_FILE_PATH = DATA_DIR / ".jarvis-running"#: Timeout for the initial lock acquire, in seconds. 0 = non-blocking,@@ -2668,6 +2672,19 @@ class DesktopApp:# handler runs on the asyncio loop and immediately thread-hops, because# pywebview calls block their calling thread (see _on_show_window_requested).server.bus.subscribe(ShowWindowRequested, self._on_show_window_requested)+ # The appshot card and the Appshots page open the editor in a window+ # of its own (jarvis.appshot.editor_window holds the opener; it is+ # always called from a worker thread, as open_detached_window needs).+ try:+ from jarvis.appshot.editor_window import EDITOR_VIEW, register_window_opener++ register_window_opener(+ lambda query: self.open_detached_window(EDITOR_VIEW, query=query)+ )+ except Exception as exc: # noqa: BLE001 - the page editor stays the fallback+ from loguru import logger as _alog++ _alog.opt(exception=exc).debug("appshot editor window wiring skipped")# The pet's pen asks for a fresh chat: the window comes up through the# very same off-loop path; the frontend opens the new chat itself.server.bus.subscribe(ComposeRequested, self._on_show_window_requested)diff --git a/jarvis/ui/web/appshot_routes.py b/jarvis/ui/web/appshot_routes.pyindex f04a9c1651..46319bca06 100644--- a/jarvis/ui/web/appshot_routes.py+++ b/jarvis/ui/web/appshot_routes.py@@ -7,7 +7,10 @@ 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.+ PUT /api/appshot/latest/image → replace it with the editor's version and+ hand that to the assistant (deliver_edit).+ POST /api/appshot/latest/card → slide it back into the corner card.+ POST /api/appshot/open-editor → open the editor in its own window.POST /api/appshot/clipboard → copy the editor's PNG natively (desktop only).POST /api/appshot/drag-file → write it for a native drag out (desktop only).GET /api/appshot/pending → the appshot waiting for the next message.@@ -45,6 +48,7 @@ class SettingsPatch(BaseModel):target: Literal["auto", "message", "voice"] | None = Nonesound: bool | None = Noneeffect: bool | None = None+ card_seconds: int | None = Field(default=None, ge=0, le=600)class TakeRequest(BaseModel):@@ -104,6 +108,7 @@ def _settings_payload() -> dict[str, Any]:"target": block.target,"sound": bool(block.sound),"effect": bool(block.effect),+ "card_seconds": int(getattr(block, "card_seconds", 6)),"sound_effects_master": bool(getattr(config.ui, "sound_effects", True)),"shortcut": _status("window"),"region_shortcut": _status("region"),@@ -231,7 +236,38 @@ async def replace_latest_image(request: Request, id: str) -> dict[str, Any]: #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()}+ from jarvis.appshot.service import deliver_edit # noqa: PLC0415++ delivered_to = await deliver_edit(shot)+ return {"ok": True, "appshot": {**shot.meta(), "delivered_to": delivered_to}}+++class OpenEditorRequest(BaseModel):+ id: str = Field(min_length=1, max_length=64)++[email protected]("/open-editor")+async def open_editor(body: OpenEditorRequest) -> dict[str, Any]:+ """Open the editor in its own window. ``window: false`` = edit in the page.++ The desktop shell opens a detached window (``jarvis.appshot.editor_window``);+ a headless or browser-only run cannot, and the page shows its own editor.+ """+ from jarvis.appshot.editor_window import open_editor_window # noqa: PLC0415++ return {"window": await open_editor_window(body.id)}++[email protected]("/latest/card")+async def return_card() -> dict[str, Any]:+ """Slide the held (edited) appshot back into the corner card.++ The editor window calls this when it closes, so the picture stays at+ hand like after the shutter. ``shown: false`` where no overlay can run.+ """+ from jarvis.appshot.card_actions import return_to_corner # noqa: PLC0415++ return {"shown": await return_to_corner()}def _png_size(data: bytes) -> tuple[int, int] | None:diff --git a/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/de.json b/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/de.jsonindex d102314284..218b8cec3c 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/de.json@@ -33,7 +33,6 @@"copy_timeout": "die Zwischenablage hat nicht geantwortet","saved_to": "Gespeichert unter {0}","save_failed": "Speichern hat nicht geklappt: {0}",- "applied": "Das bearbeitete Bild ersetzt den Appshot.","apply_failed": "Die Bearbeitung konnte nicht übernommen werden: {0}","text_placeholder": "Tippen, dann Enter","text_style": "Textstil",@@ -65,6 +64,13 @@"drag_release": "Halte den Griff gedrückt, während du ziehst.","drag_failed": "Ziehen hat nicht geklappt: {0}","zoom": "Zoom",- "zoom_fit": "Einpassen"+ "zoom_fit": "Einpassen",+ "applied_voice": "{name} sieht das bearbeitete Bild jetzt im Anruf.",+ "applied_message": "Das bearbeitete Bild geht mit deiner nächsten Nachricht an {name}.",+ "applied_none": "Bearbeitung gespeichert. Sie geht nur während eines Anrufs an {name}.",+ "card_seconds": "Karte in der Ecke",+ "card_seconds_hint": "Wie lange das Bild nach einem Appshot in der Bildschirmecke bleibt.",+ "card_seconds_option": "{0} Sekunden",+ "card_until_closed": "Bis ich sie schließe"}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/en.json b/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/en.jsonindex 7c9ddd1911..c630ac089f 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/en.json@@ -33,7 +33,6 @@"copy_timeout": "the clipboard did not answer","saved_to": "Saved to {0}","save_failed": "Saving did not work: {0}",- "applied": "The edited picture replaces the appshot.","apply_failed": "The edit could not be used: {0}","text_placeholder": "Type, then Enter","text_style": "Text style",@@ -65,6 +64,13 @@"drag_release": "Keep the handle pressed while you drag.","drag_failed": "Dragging did not work: {0}","zoom": "Zoom",- "zoom_fit": "Fit"+ "zoom_fit": "Fit",+ "applied_voice": "{name} sees the edited picture in your call now.",+ "applied_message": "The edited picture goes with your next message to {name}.",+ "applied_none": "Edit kept. It goes to {name} only during a voice call.",+ "card_seconds": "Corner card",+ "card_seconds_hint": "How long the picture rests in the screen corner after an appshot.",+ "card_seconds_option": "{0} seconds",+ "card_until_closed": "Until I close it"}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/es.json b/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/es.jsonindex c5643bed9a..1633be58e8 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/es.json@@ -33,7 +33,6 @@"copy_timeout": "el portapapeles no respondió","saved_to": "Guardado en {0}","save_failed": "No se pudo guardar: {0}",- "applied": "La imagen editada sustituye al appshot.","apply_failed": "No se pudo usar la edición: {0}","text_placeholder": "Escribe y pulsa Intro","text_style": "Estilo de texto",@@ -65,6 +64,13 @@"drag_release": "Mantén pulsada el asa mientras arrastras.","drag_failed": "No se pudo arrastrar: {0}","zoom": "Zoom",- "zoom_fit": "Ajustar"+ "zoom_fit": "Ajustar",+ "applied_voice": "{name} ya ve la imagen editada en la llamada.",+ "applied_message": "La imagen editada va con tu próximo mensaje a {name}.",+ "applied_none": "Edición guardada. Solo llega a {name} durante una llamada.",+ "card_seconds": "Tarjeta en la esquina",+ "card_seconds_hint": "Cuánto tiempo queda la imagen en la esquina de la pantalla tras un appshot.",+ "card_seconds_option": "{0} segundos",+ "card_until_closed": "Hasta que la cierre"}}diff --git a/jarvis/ui/web/frontend/src/lib/appshotApi.ts b/jarvis/ui/web/frontend/src/lib/appshotApi.tsindex fbdea2541f..fd5bf60ce1 100644--- a/jarvis/ui/web/frontend/src/lib/appshotApi.ts+++ b/jarvis/ui/web/frontend/src/lib/appshotApi.ts@@ -23,6 +23,8 @@ export interface AppshotSettings {target: AppshotTarget;sound: boolean;effect: boolean;+ /** Seconds the corner card rests; 0 = until the user closes it. */+ card_seconds: number;sound_effects_master: boolean;shortcut: AppshotShortcutStatus;region_shortcut: AppshotShortcutStatus;@@ -48,7 +50,7 @@ export interface AppshotMeta {}export type AppshotSettingsPatch = Partial<- Pick<AppshotSettings, "enabled" | "hotkey" | "region_hotkey" | "target" | "sound" | "effect">+ Pick<AppshotSettings, "enabled" | "hotkey" | "region_hotkey" | "target" | "sound" | "effect" | "card_seconds">>;async function request<T>(url: string, init?: RequestInit): Promise<T> {@@ -140,3 +142,25 @@ export function formatAppshotHotkey(hotkey: string, isMac: boolean): string {}).join(" + ");}++/**+ * Open the editor on an appshot in its own desktop window. `false` where the+ * shell cannot (a browser, a headless host): then the page shows its editor.+ */+export async function openAppshotEditorWindow(id: string): Promise<boolean> {+ try {+ const response = await fetch("/api/appshot/open-editor", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ id }),+ });+ if (!response.ok) return false;+ const body = (await response.json().catch(() => null)) as { window?: unknown } | null;+ return body?.window === true;+ } catch {+ return false;+ }+}++/** How long the corner card may rest, in seconds; 0 = until closed. */+export const CARD_SECONDS_CHOICES = [3, 6, 10, 30, 0] as const;diff --git a/jarvis/ui/web/frontend/src/main.tsx b/jarvis/ui/web/frontend/src/main.tsxindex 0e16b20754..648dfc8c9e 100644--- a/jarvis/ui/web/frontend/src/main.tsx+++ b/jarvis/ui/web/frontend/src/main.tsx@@ -129,6 +129,13 @@ const queryClient = new QueryClient({},});+// The appshot editor's own desktop window (a click on the corner card) loads+// just the editor, not the app around it. Lazy, so the app never carries it.+const AppshotEditorWindow = React.lazy(() =>+ import("./views/AppshotEditorWindow").then((m) => ({ default: m.AppshotEditorWindow })),+);+const isEditorWindow = new URLSearchParams(window.location.search).get("view") === "appshot-editor";+function renderApp(): void {ReactDOM.createRoot(document.getElementById("root")!).render(<React.StrictMode>@@ -140,7 +147,13 @@ function renderApp(): void {onRecover={() => window.location.reload()}><AuthGate>- <App />+ {isEditorWindow ? (+ <React.Suspense fallback={null}>+ <AppshotEditorWindow />+ </React.Suspense>+ ) : (+ <App />+ )}</AuthGate></ViewErrorBoundary></ThemeProvider>diff --git a/jarvis/ui/web/frontend/src/views/AppshotEditor.tsx b/jarvis/ui/web/frontend/src/views/AppshotEditor.tsxindex d4f1029441..6494b9bc18 100644--- a/jarvis/ui/web/frontend/src/views/AppshotEditor.tsx+++ b/jarvis/ui/web/frontend/src/views/AppshotEditor.tsx@@ -181,11 +181,17 @@ interface Typing {export interface AppshotEditorProps {appshotId: string;onClose: () => void;- /** The edited picture replaced the held appshot. */+ /** The edited picture replaced the held appshot (and went to the assistant). */onApplied?: () => void;+ /**+ * ``overlay``: a floating window over the app (the page editor).+ * ``window``: the editor IS its own desktop window, edge to edge, and its+ * top bar moves the window.+ */+ variant?: "overlay" | "window";}-export function AppshotEditor({ appshotId, onClose, onApplied }: AppshotEditorProps) {+export function AppshotEditor({ appshotId, onClose, onApplied, variant = "overlay" }: AppshotEditorProps) {const t = useT();const ready = useLocaleChunk("appshot_editor");const caps = useCapabilities();@@ -573,7 +579,17 @@ export function AppshotEditor({ appshotId, onClose, onApplied }: AppshotEditorPrconst body = (await response.json().catch(() => null)) as { detail?: string } | null;throw new Error(body?.detail || `HTTP ${response.status}`);}- pushToast("success", t("appshot_editor.applied"));+ const body = (await response.json().catch(() => null)) as { appshot?: { delivered_to?: string } } | null;+ const where = body?.appshot?.delivered_to;+ // Done means "this is what I meant": say where the edited picture went.+ pushToast(+ "success",+ fill(+ t(where === "voice" ? "appshot_editor.applied_voice" : where === "none" ? "appshot_editor.applied_none" : "appshot_editor.applied_message"),+ { name: assistantName },+ ),+ );+ setDirty(false);onApplied?.();onClose();} catch (error) {@@ -581,7 +597,7 @@ export function AppshotEditor({ appshotId, onClose, onApplied }: AppshotEditorPr} finally {setBusy("");}- }, [appshotId, onApplied, onClose, pushToast, render, t]);+ }, [appshotId, assistantName, onApplied, onClose, pushToast, render, t]);const requestClose = useCallback(() => {if (dirty && ops.length > 0) setConfirmDiscard(true);@@ -743,10 +759,19 @@ export function AppshotEditor({ appshotId, onClose, onApplied }: AppshotEditorPr};return (- <div className="flex h-full w-full items-center justify-center bg-black/45 p-2 backdrop-blur-[2px] sm:p-5">+ <div+ className={cn(+ "flex h-full w-full items-center justify-center",+ variant === "overlay" && "bg-black/45 p-2 backdrop-blur-[2px] sm:p-5",+ )}+ ><div- className="relative flex h-full w-full max-w-[1800px] flex-col overflow-hidden rounded-2xl border border-border bg-popover text-popover-foreground shadow-2xl"+ className={cn(+ "relative flex h-full w-full flex-col overflow-hidden bg-popover text-popover-foreground",+ variant === "overlay" && "max-w-[1800px] rounded-2xl border border-border shadow-2xl",+ )}data-testid="appshot-editor"+ data-variant={variant}>{/* Top bar: close · crop and background · tools · colour and size · Save, Done. */}<div className="flex h-12 shrink-0 items-center gap-2 border-b border-border px-3">@@ -849,7 +874,9 @@ export function AppshotEditor({ appshotId, onClose, onApplied }: AppshotEditorPr</label></QuickTooltip>- <div className="ml-auto flex shrink-0 items-center gap-1.5">+ {/* Free space: in its own window this is where the window is moved from. */}+ <div className={cn("h-full min-w-4 flex-1", variant === "window" && "pywebview-drag-region")} aria-hidden />+ <div className="flex shrink-0 items-center gap-1.5"><QuickTooltip content={`${label("save_hint")} (Ctrl+S)`} side="bottom"><buttontype="button"diff --git a/jarvis/ui/web/frontend/src/views/AppshotEditorWindow.test.tsx b/jarvis/ui/web/frontend/src/views/AppshotEditorWindow.test.tsxnew file mode 100644index 0000000000..ac7cc2e035--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/AppshotEditorWindow.test.tsx@@ -0,0 +1,80 @@+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { useEventStore } from "@/store/events";+import {+ AppshotEditorWindow,+ appshotIdFromUrl,+ isAppshotEditorWindow,+ type EditorWindowDeps,+} from "@/views/AppshotEditorWindow";++/**+ * The editor's own desktop window: opened by a click on the corner card, it+ * shows only the editor, and when it closes (Done or Close) the appshot goes+ * back into the screen corner BEFORE the window closes itself.+ */++class LoadedImage {+ naturalWidth = 400;+ naturalHeight = 300;+ onload: (() => void) | null = null;+ set src(_value: string) {+ queueMicrotask(() => this.onload?.());+ }+}++function json(body: unknown, status = 200): Response {+ return { ok: status < 400, status, json: async () => body } as Response;+}++describe("the appshot editor window", () => {+ beforeEach(() => {+ useEventStore.setState({ events: [], toasts: [], assistantName: "George" });+ vi.stubGlobal("Image", LoadedImage);+ vi.stubGlobal("fetch", vi.fn(async () => json({ native_file_actions: false, platform: "linux" })));+ window.history.replaceState(null, "", "/?view=appshot-editor&solo=1&appshot=a1b2c3d4");+ });++ afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ window.history.replaceState(null, "", "/");+ });++ it("knows it is the editor window and which appshot it edits", () => {+ expect(isAppshotEditorWindow("?view=appshot-editor&solo=1&appshot=a1b2c3d4")).toBe(true);+ expect(isAppshotEditorWindow("?view=chats")).toBe(false);+ expect(appshotIdFromUrl("?appshot=a1b2c3d4")).toBe("a1b2c3d4");+ expect(appshotIdFromUrl("?appshot=../../etc")).toBe("");+ });++ it("sends the appshot back to the corner, then closes itself", async () => {+ const order: string[] = [];+ const deps: EditorWindowDeps = {+ returnCard: async () => {+ order.push("card");+ },+ closeWindow: async () => {+ order.push("close");+ },+ };+ render(<AppshotEditorWindow deps={deps} />);+ await screen.findByTestId("appshot-editor-canvas");+ expect(screen.getByTestId("appshot-editor").getAttribute("data-variant")).toBe("window");++ fireEvent.click(screen.getByTestId("appshot-editor-close"));++ await waitFor(() => expect(order).toEqual(["card", "close"]));+ });++ it("still closes when the card cannot come back", async () => {+ const closeWindow = vi.fn(async () => undefined);+ render(<AppshotEditorWindow deps={{ returnCard: () => Promise.reject(new Error("no overlay")), closeWindow }} />);+ await screen.findByTestId("appshot-editor-canvas");++ fireEvent.keyDown(window, { key: "Escape" });++ await waitFor(() => expect(closeWindow).toHaveBeenCalledTimes(1));+ });+});diff --git a/jarvis/ui/web/frontend/src/views/AppshotEditorWindow.tsx b/jarvis/ui/web/frontend/src/views/AppshotEditorWindow.tsxnew file mode 100644index 0000000000..7c5b7bedf6--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/AppshotEditorWindow.tsx@@ -0,0 +1,67 @@+import { useCallback, useRef } from "react";++import { ToastLayer } from "@/components/ToastLayer";+import { AppshotEditor } from "@/views/AppshotEditor";++/**+ * The appshot editor as its own desktop window (`?view=appshot-editor&solo=1+ * &appshot=<id>`), opened by a click on the corner card — CleanShot X's+ * editor window. Nothing of the app is loaded around it.+ *+ * When it closes — Done or Close — the appshot slides back into the screen+ * corner (`POST /api/appshot/latest/card`), so it stays at hand, and then the+ * window closes itself through the shell (`POST /api/window/reattach`).+ */++export const APPSHOT_EDITOR_VIEW = "appshot-editor";++/** The appshot this window edits, from its URL; empty when none is named. */+export function appshotIdFromUrl(search: string): string {+ const id = new URLSearchParams(search).get("appshot") ?? "";+ return /^[0-9a-f]{8,64}$/.test(id) ? id : "";+}++/** Is this document the editor window rather than the app? */+export function isAppshotEditorWindow(search: string): boolean {+ return new URLSearchParams(search).get("view") === APPSHOT_EDITOR_VIEW;+}++export interface EditorWindowDeps {+ returnCard: () => Promise<unknown>;+ closeWindow: () => Promise<unknown>;+}++const browserDeps: EditorWindowDeps = {+ returnCard: () => fetch("/api/appshot/latest/card", { method: "POST" }),+ closeWindow: () =>+ fetch("/api/window/reattach", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ view: APPSHOT_EDITOR_VIEW }),+ }),+};++export function AppshotEditorWindow({ deps = browserDeps }: { deps?: EditorWindowDeps }) {+ const appshotId = appshotIdFromUrl(window.location.search);+ const closing = useRef(false);++ const close = useCallback(() => {+ if (closing.current) return;+ closing.current = true;+ // Back into the corner first: the window must not take the card's+ // request down with it.+ void deps+ .returnCard()+ .catch(() => undefined)+ .finally(() => {+ void deps.closeWindow().catch(() => undefined);+ });+ }, [deps]);++ return (+ <div className="h-screen w-screen overflow-hidden bg-popover" data-testid="appshot-editor-window">+ <AppshotEditor appshotId={appshotId || "missing"} onClose={close} variant="window" />+ <ToastLayer />+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/AppshotsView.test.tsx b/jarvis/ui/web/frontend/src/views/AppshotsView.test.tsxindex 64e262977b..d825e0d95d 100644--- a/jarvis/ui/web/frontend/src/views/AppshotsView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/AppshotsView.test.tsx@@ -252,17 +252,33 @@ describe("AppshotsView editor", () => {vi.unstubAllGlobals();});- it("opens the editor on the last appshot without leaving the page", async () => {+ it("edits in the page when no editor window can open", async () => {useEventStore.setState({ activeSection: "appshots" });render(<AppshotsView />);fireEvent.click(await screen.findByTestId("appshots-preview-edit"));- // AppshotEditorHost (mounted by App) draws it; the page only asks.- expect(useAppshotEditor.getState().openId).toBe("shot-1");+ // The window route answers 404 here (a browser); AppshotEditorHost+ // (mounted by App) then draws the editor — the page only asks.+ await waitFor(() => expect(useAppshotEditor.getState().openId).toBe("shot-1"));expect(useEventStore.getState().activeSection).toBe("appshots");expect(screen.queryByTestId("appshot-editor")).toBeNull();});+ it("edits in its own window where the desktop shell opens one", async () => {+ const fetchMock = fetch as unknown as ReturnType<typeof vi.fn>;+ const base = fetchMock.getMockImplementation()!;+ fetchMock.mockImplementation(async (url: string, init?: RequestInit) =>+ url === "/api/appshot/open-editor" ? json({ window: true }) : base(url, init),+ );+ render(<AppshotsView />);+ fireEvent.click(await screen.findByTestId("appshots-preview-edit"));++ await waitFor(() =>+ expect(fetchMock.mock.calls.some(([url]) => url === "/api/appshot/open-editor")).toBe(true),+ );+ expect(useAppshotEditor.getState().openId).toBeNull();+ });+it("shows the edited picture once an edit replaced the appshot", async () => {render(<AppshotsView />);await screen.findByTestId("appshots-preview-edit");diff --git a/jarvis/ui/web/frontend/src/views/AppshotsView.tsx b/jarvis/ui/web/frontend/src/views/AppshotsView.tsxindex ac2d4f2081..7127de2bfa 100644--- a/jarvis/ui/web/frontend/src/views/AppshotsView.tsx+++ b/jarvis/ui/web/frontend/src/views/AppshotsView.tsx@@ -5,7 +5,7 @@ import { PageHeader } from "@/components/layout/PageHeader";import { Button } from "@/components/ui/button";import { BrandedSelect, type BrandedSelectOption } from "@/components/ui/select";import { Switch } from "@/components/ui/switch";-import { useT } from "@/i18n";+import { useLocaleChunk, useT } from "@/i18n";import {fetchAppshotSettings,fetchLatestAppshot,@@ -17,6 +17,8 @@ import {type AppshotMeta,type AppshotSettings,type AppshotSettingsPatch,+ CARD_SECONDS_CHOICES,+ openAppshotEditorWindow,} from "@/lib/appshotApi";import { gestureFamily } from "@/lib/appshotChord";import { cn } from "@/lib/utils";@@ -331,6 +333,20 @@ export function AppshotsView() {}, [pushToast]);+ // The card and editor strings live in the editor's own locale chunk.+ const editorReady = useLocaleChunk("appshot_editor");+ const cardOptions = useMemo<BrandedSelectOption[]>(+ () =>+ CARD_SECONDS_CHOICES.map((seconds) => ({+ value: String(seconds),+ label:+ seconds === 0+ ? t("appshot_editor.card_until_closed")+ : t("appshot_editor.card_seconds_option").replace("{0}", String(seconds)),+ })),+ // `editorReady` re-labels the options once the chunk has arrived.+ [t, editorReady],+ );const targetOptions = useMemo<BrandedSelectOption[]>(() => [{ value: "auto", label: t("appshots.target_auto") },@@ -513,6 +529,20 @@ export function AppshotsView() {/>}/>+ <Row+ label={editorReady ? t("appshot_editor.card_seconds") : ""}+ hint={editorReady ? t("appshot_editor.card_seconds_hint") : ""}+ control={+ <BrandedSelect+ value={String(settings.card_seconds ?? 6)}+ options={cardOptions}+ ariaLabel={editorReady ? t("appshot_editor.card_seconds") : ""}+ disabled={disabled || saving || !settings.effect}+ testId="appshots-card-seconds"+ onValueChange={(value) => void save({ card_seconds: Number(value) })}+ />+ }+ /><Rowlabel={t("appshots.try_label")}hint={@@ -564,7 +594,12 @@ export function AppshotsView() {shot={latest}revision={revision}onForget={() => void forget()}- onEdit={() => openEditor(latest.id)}+ onEdit={() => {+ // Its own window where the desktop shell can; else over this page.+ void openAppshotEditorWindow(latest.id).then((inWindow) => {+ if (!inWindow) openEditor(latest.id);+ });+ }}/>) : (<PreviewDemo />diff --git a/tests/unit/appshot/test_appshot_card.py b/tests/unit/appshot/test_appshot_card.pynew file mode 100644index 0000000000..ff63191c6e--- /dev/null+++ b/tests/unit/appshot/test_appshot_card.py@@ -0,0 +1,278 @@+"""The appshot after the shutter: editor window, corner card, edited delivery.++A click on the corner card opens the editor in a window of its own (no+raised, resized main window); Done hands the edited picture to the assistant+and slides it back into the corner; the card's hover buttons copy and save+through the main process; ``[appshot].card_seconds`` sets how long it rests.+"""++from __future__ import annotations++import io+from types import SimpleNamespace++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient+from PIL import Image++from jarvis.appshot import card_actions, editor_window+from jarvis.appshot.store import Appshot, AppshotStore+++def _png(width: int = 40, height: int = 30) -> bytes:+ buffer = io.BytesIO()+ Image.new("RGB", (width, height), (20, 120, 220)).save(buffer, "PNG")+ return buffer.getvalue()+++def _jpeg() -> bytes:+ buffer = io.BytesIO()+ Image.new("RGB", (32, 24), (200, 30, 30)).save(buffer, "JPEG")+ return buffer.getvalue()+++def _shot(shot_id: str = "a1b2c3d4", delivered_to: str = "message") -> Appshot:+ return Appshot(+ id=shot_id,+ image=_png(),+ mime="image/png",+ width=40,+ height=30,+ label="active window",+ app_name="Editor",+ note="APPSHOT: evidence",+ ui_text="",+ trigger="hotkey",+ taken_at=1.0,+ delivered_to=delivered_to,+ )+++# -- the editor window -----------------------------------------------------------+++def opener():+ calls: list[str] = []++ def open_window(query: str) -> dict:+ calls.append(query)+ return {"ok": True}++ editor_window.register_window_opener(open_window)+ yield calls+ editor_window.register_window_opener(None)+++async def test_the_editor_opens_in_its_own_window(opener) -> None:+ assert await editor_window.open_editor_window("a1b2c3d4") is True+ assert opener == ["appshot=a1b2c3d4"]+++async def test_no_shell_means_the_page_editor() -> None:+ editor_window.register_window_opener(None)+ assert await editor_window.open_editor_window("a1b2c3d4") is False+++async def test_only_an_appshot_id_reaches_the_window_url(opener) -> None:+ assert await editor_window.open_editor_window("x&view=settings") is False+ assert opener == []+++async def test_a_shell_that_cannot_open_a_window_falls_back() -> None:+ editor_window.register_window_opener(lambda _query: {"ok": False, "reason": "no_live_window"})+ try:+ assert await editor_window.open_editor_window("a1b2c3d4") is False+ finally:+ editor_window.register_window_opener(None)+++def test_the_route_reports_where_the_editor_opened(opener) -> None:+ from jarvis.ui.web.appshot_routes import router++ app = FastAPI()+ app.include_router(router)+ client = TestClient(app)++ response = client.post("/api/appshot/open-editor", json={"id": "a1b2c3d4"})+ assert response.status_code == 200+ assert response.json() == {"window": True}+++# -- how long the card rests, and its wording ----------------------------------------++[email protected](("seconds", "expected"), [(6, 6000), (0, 0), (30, 30000), (-3, 0)])+def test_card_rest_time_follows_the_setting(seconds: int, expected: int) -> None:+ config = SimpleNamespace(appshot=SimpleNamespace(card_seconds=seconds))+ assert card_actions.card_rest_ms(config) == expected+++def test_card_seconds_is_validated_and_defaults_to_six() -> None:+ from pydantic import ValidationError++ from jarvis.core.config import AppshotConfig++ assert AppshotConfig().card_seconds == 6+ assert AppshotConfig(card_seconds=0).card_seconds == 0+ with pytest.raises(ValidationError):+ AppshotConfig(card_seconds=-1)+++def test_card_labels_follow_the_ui_language() -> None:+ german = card_actions.card_labels(SimpleNamespace(ui=SimpleNamespace(language="de")))+ unknown = card_actions.card_labels(SimpleNamespace(ui=SimpleNamespace(language="xx")))+ assert german["copy"] != unknown["copy"]+ assert set(german) == set(unknown)+ assert unknown["save"] == "Save"+++# -- the card's hover buttons ------------------------------------------------------+++def test_a_jpeg_appshot_is_copied_and_saved_as_png() -> None:+ png = card_actions.as_png(_jpeg())+ assert png.startswith(b"\x89PNG")+ assert card_actions.as_png(_png()) == _png()+++def test_save_writes_a_fresh_file_each_time(tmp_path) -> None:+ first = card_actions.save_to_downloads(_png(), folder=tmp_path, now=1_000_000.0)+ second = card_actions.save_to_downloads(_png(), folder=tmp_path, now=1_000_000.0)+ assert first != second and first.exists() and second.exists()+ assert first.suffix == ".png"+++async def test_copy_from_the_card_uses_the_native_clipboard(monkeypatch) -> None:+ from jarvis.appshot import store as store_module+ from jarvis.platform import clipboard_image++ store = AppshotStore()+ store.remember(_shot(), keep_s=60)+ monkeypatch.setattr(store_module, "_STORE", store)+ copied: list[bytes] = []+ monkeypatch.setattr(clipboard_image, "write_png", lambda png: copied.append(png) or True)+ monkeypatch.setattr(+ "jarvis.core.config.load_config", lambda: SimpleNamespace(ui=SimpleNamespace(language="en"))+ )++ assert await card_actions.run_card_action("copy") == "Copied"+ assert copied == [_png()]+++async def test_a_card_action_without_a_held_appshot_says_so(monkeypatch) -> None:+ from jarvis.appshot import store as store_module++ monkeypatch.setattr(store_module, "_STORE", AppshotStore())+ monkeypatch.setattr(+ "jarvis.core.config.load_config", lambda: SimpleNamespace(ui=SimpleNamespace(language="en"))+ )+ assert await card_actions.run_card_action("save") == "No longer kept"+++# -- what the assistant gets after Done -----------------------------------------+++def _config(target: str = "auto") -> SimpleNamespace:+ return SimpleNamespace(+ appshot=SimpleNamespace(target=target),+ screen_context=SimpleNamespace(ttl_s=120.0),+ )+++def held(monkeypatch):+ from jarvis.appshot import service+ from jarvis.appshot import store as store_module++ store = AppshotStore()+ monkeypatch.setattr(store_module, "_STORE", store)+ monkeypatch.setattr(service, "get_store", lambda: store)+ state = {"config": _config(), "call": False, "sent": []}++ async def fake_live(image: bytes, mime: str, note: str) -> bool:+ if state["call"]:+ state["sent"].append(note)+ return state["call"]++ monkeypatch.setattr(service, "_load_config", lambda: state["config"])+ monkeypatch.setattr("jarvis.appshot.delivery.deliver_to_live", fake_live)+ return store, state+++async def test_an_edit_goes_with_the_next_message_and_says_it_was_edited(held) -> None:+ from jarvis.appshot.service import EDIT_NOTE, deliver_edit++ store, _state = held+ shot = _shot(delivered_to="message")+ store.remember(shot, keep_s=60)++ assert await deliver_edit(shot) == "message"+ pending = store.take_pending()+ assert pending is not None and pending.id == shot.id+ assert pending.note.startswith("APPSHOT: evidence") and EDIT_NOTE in pending.note+++async def test_an_edit_reaches_a_running_call_even_after_the_original_did(held) -> None:+ from jarvis.appshot.service import deliver_edit++ store, state = held+ state["call"] = True+ shot = _shot(delivered_to="voice")+ store.remember(shot, keep_s=60)+ store.park(shot, ttl_s=60)++ assert await deliver_edit(shot) == "voice"+ assert len(state["sent"]) == 1+ # The waiting original must not follow into the next message as well.+ assert store.take_pending() is None+++async def test_an_edit_of_an_already_sent_appshot_waits_for_the_next_message(held) -> None:+ from jarvis.appshot.service import deliver_edit++ store, _state = held+ shot = _shot(delivered_to="turn")+ store.remember(shot, keep_s=60)++ assert await deliver_edit(shot) == "message"+ assert store.peek_pending() is not None+++async def test_a_voice_only_target_without_a_call_keeps_the_edit_to_itself(held) -> None:+ from jarvis.appshot.service import deliver_edit++ store, state = held+ state["config"] = _config("voice")+ shot = _shot()+ store.remember(shot, keep_s=60)++ assert await deliver_edit(shot) == "none"+ assert store.peek_pending() is None+++async def test_editing_twice_does_not_stack_the_note(held) -> None:+ from jarvis.appshot.service import EDIT_NOTE, deliver_edit++ store, _state = held+ shot = _shot()+ store.remember(shot, keep_s=60)+ await deliver_edit(shot)+ once = store.peek_pending()+ assert once is not None+ await deliver_edit(once)+ twice = store.peek_pending()+ assert twice is not None and twice.note.count(EDIT_NOTE) == 1+++# -- the sidecar protocol ---------------------------------------------------------+++def test_the_card_commands_and_events_are_known() -> None:+ from jarvis.cu.indicator import protocol++ assert protocol.CMD_CARD in protocol.ALL_COMMANDS+ assert protocol.CMD_CARD_STATUS in protocol.ALL_COMMANDS+ line = protocol.encode_event(protocol.EVENT_CARD_ACTION, action="copy")+ assert protocol.decode_event(line) == {"event": "card_action", "action": "copy"}