Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(appshot): keep every appshot and edit in a gallery you can drag from

rubenluetke10-beep91781ee6999e
diff --git a/docs/appshots.md b/docs/appshots.md
index 3af63ff53f..714598d525 100644
--- a/docs/appshots.md
+++ b/docs/appshots.md
@@ -208,6 +208,32 @@ parts were hidden on purpose:
The editor says which one happened. Copy, Save and Drag never send anything
to the assistant; they are the screenshot-tool half.
+## The gallery
+
+Below the settings, **Your appshots** shows every appshot taken with the
+shortcuts, the page's buttons or the assistant's `take_appshot` tool, and every
+edit saved in the editor, newest first. An edit sits right before its original
+and wears an **Edited** badge; the **Edited** filter shows only those. A look
+a conversation turn took on its own is never kept.
+
+- **Click** a picture to open it in the editor again. Saving there keeps the
+ new edit beside the original and hands it to the assistant like any edit.
+- **Drag** a picture into a chat composer or a terminal pane to attach it.
+ The drag carries the picture's real path the way a row from the workspace
+ explorer does, so both drop targets take it unchanged. In a browser the
+ drag also carries a `DownloadURL`, so it can be dropped onto the desktop.
+ Inside the desktop shell the grip on a tile starts a native file drag that
+ reaches any other app (mail, Explorer/Finder, a browser upload).
+- **Delete** on an edited tile removes only that edit; on an original it
+ removes the appshot and its edit. **Delete all** asks once more first.
+
+The pictures live in `<data dir>/appshots/<id>/` (`original.<ext>`,
+`edited.png`, `meta.json`, small thumbnails made on first view). Only the
+finished, privacy-filtered appshot is written — never the raw frame or the
+on-screen text. The library keeps the newest 500 appshots and removes the
+oldest first. **Keep appshot history** (`[appshot].library`) turns it off;
+what is already kept stays until it is deleted.
+
## Where a shortcut appshot goes
| Destination | Running voice call | No voice call |
@@ -229,8 +255,10 @@ to the assistant; they are the screenshot-tool half.
Appshots capture through the Screen Context engine
([screen-context.md](screen-context.md)), so everything there applies
-unchanged: the app denylist, redaction of password fields and sensitive
-patterns, and no image ever written to disk. For an area, a denylisted window
+unchanged: the app denylist and redaction of password fields and sensitive
+patterns. The capture itself writes nothing to disk; the one deliberate copy
+is the gallery's history (see [The gallery](#the-gallery)), which can be
+switched off and deleted. For an area, a denylisted window
that overlaps the rectangle refuses the capture; one elsewhere on the screen
does not. The one difference: an appshot
shows no gold border before the shutter — the flash over the captured window
@@ -264,6 +292,7 @@ original any-order behaviour.
| `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 |
+| `library` | `true` | Keep every appshot and saved edit in the gallery (`<data dir>/appshots/`, newest 500) |
## Operating systems
@@ -281,7 +310,7 @@ instance) arms the shortcuts.
## Code
`jarvis/appshot/` — `service.py` (take and deliver), `store.py` (pending and
-last appshot, memory only), `gesture.py` (both-Alt watcher), `hotkey.py`
+last appshot, memory only), `library.py` (the gallery's history on disk), `gesture.py` (both-Alt watcher), `hotkey.py`
(both shortcuts' lifecycle), `region.py` (area selection and its coordinate
mapping), `picker/` (the area picker sidecar), `effect.py` (shutter hook),
`delivery.py` (voice calls). The corner card lives in the indicator sidecar
@@ -293,4 +322,5 @@ mapping), `picker/` (the area picker sidecar), `effect.py` (shutter hook),
the native clipboard in `jarvis/platform/clipboard_image.py`.
The live model's `take_appshot` tool is `jarvis/plugins/tool/appshot.py`; the
REST surface is `jarvis/ui/web/appshot_routes.py`; the page is
-`frontend/src/views/AppshotsView.tsx`.
+`frontend/src/views/AppshotsView.tsx`, its gallery
+`frontend/src/views/AppshotLibrary.tsx`.
diff --git a/jarvis/appshot/library.py b/jarvis/appshot/library.py
new file mode 100644
index 0000000000..703b3ea2bc
--- /dev/null
+++ b/jarvis/appshot/library.py
@@ -0,0 +1,408 @@
+"""The appshot library — every appshot the user took, and its edited version.
+
+The in-memory store (:mod:`jarvis.appshot.store`) only holds the last few
+pictures for minutes. The library is the history the Appshots page shows as a
+gallery: each appshot taken with the shortcuts, the page's buttons or the
+assistant's ``take_appshot`` tool is written here once, and an edit saved in
+the editor is kept beside it. A turn that looked at the screen on its own is
+never written — only what the user (or the assistant on their request) chose
+to capture.
+
+It is switchable (``[appshot].library``), capped at :data:`MAX_ENTRIES`
+(oldest removed first) and every entry can be deleted from the page; the
+pictures are the finished, privacy-filtered appshots, never a raw frame.
+
+Layout, one folder per appshot under ``<data dir>/appshots/``::
+
+ <id>/meta.json what the page shows (no pixels)
+ <id>/original.<ext> the appshot as captured
+ <id>/edited.png the last edit saved in the editor, when there is one
+ <id>/thumb-*.jpg gallery thumbnails, made on first view
+
+Nothing here is imported at boot (AP-26).
+"""
+
+from __future__ import annotations
+
+import io
+import json
+import logging
+import re
+import shutil
+import threading
+import time
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Literal
+
+from jarvis.appshot.store import Appshot
+
+log = logging.getLogger(__name__)
+
+#: How many appshots the library keeps; the oldest go first.
+MAX_ENTRIES = 500
+#: Longest edge of a gallery thumbnail, in pixels.
+THUMB_EDGE = 480
+
+Variant = Literal["original", "edited"]
+
+_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
+_EXTENSIONS = {"image/png": "png", "image/jpeg": "jpg", "image/webp": "webp"}
+_MIMES = {ext: mime for mime, ext in _EXTENSIONS.items()}
+
+_lock = threading.Lock()
+_root_override: Path | None = None
+
+
+def library_root() -> Path:
+ """``<data dir>/appshots`` — per app instance, like every runtime store."""
+ if _root_override is not None:
+ return _root_override
+ from jarvis.core.config import DATA_DIR # noqa: PLC0415
+
+ return Path(DATA_DIR) / "appshots"
+
+
+def set_root(path: Path | None) -> None:
+ """Point the library elsewhere (tests); ``None`` restores the default."""
+ global _root_override
+ _root_override = path
+
+
+@dataclass(frozen=True, slots=True)
+class LibraryItem:
+ """One picture in the gallery: an appshot, or the edit of one."""
+
+ id: str
+ variant: Variant
+ path: Path
+ mime: str
+ width: int
+ height: int
+ label: str
+ app_name: str
+ trigger: str
+ taken_at: float
+ #: When the edit was saved; ``0`` for an original.
+ edited_at: float
+ #: True for an original that also has an edited version.
+ has_edit: bool
+
+ def to_json(self) -> dict[str, object]:
+ return {
+ "id": self.id,
+ "variant": self.variant,
+ "path": str(self.path),
+ "mime": self.mime,
+ "width": self.width,
+ "height": self.height,
+ "label": self.label,
+ "app_name": self.app_name,
+ "trigger": self.trigger,
+ "taken_at": self.taken_at,
+ "edited_at": self.edited_at,
+ "has_edit": self.has_edit,
+ }
+
+
+def valid_id(shot_id: str) -> bool:
+ """Only ids this module could have written — never a path fragment."""
+ return bool(_ID_RE.match(shot_id or ""))
+
+
+def _folder(shot_id: str) -> Path:
+ if not valid_id(shot_id):
+ raise ValueError("invalid appshot id")
+ return library_root() / shot_id
+
+
+def _read_meta(folder: Path) -> dict[str, object] | None:
+ try:
+ meta = json.loads((folder / "meta.json").read_text(encoding="utf-8"))
+ except (OSError, ValueError): # a half-written or foreign folder is simply not listed
+ return None
+ return meta if isinstance(meta, dict) else None
+
+
+def _write_meta(folder: Path, meta: dict[str, object]) -> None:
+ tmp = folder / "meta.json.tmp"
+ tmp.write_text(json.dumps(meta, ensure_ascii=False), encoding="utf-8")
+ tmp.replace(folder / "meta.json")
+
+
+def _original_file(folder: Path) -> Path | None:
+ for ext in _MIMES:
+ candidate = folder / f"original.{ext}"
+ if candidate.is_file():
+ return candidate
+ return None
+
+
+def _drop_thumbs(folder: Path, variant: Variant) -> None:
+ for thumb in folder.glob(f"thumb-{variant}*.jpg"):
+ try:
+ thumb.unlink()
+ except OSError as exc:
+ log.debug("appshot library: stale thumbnail kept (%s)", exc)
+
+
+def _base_meta(shot: Appshot) -> dict[str, object]:
+ return {
+ "id": shot.id,
+ "label": shot.label,
+ "app_name": shot.app_name,
+ "trigger": shot.trigger,
+ "taken_at": shot.taken_at,
+ }
+
+
+def save(shot: Appshot) -> bool:
+ """Write a freshly taken appshot. Never raises; False when nothing was kept."""
+ try:
+ folder = _folder(shot.id)
+ ext = _EXTENSIONS.get(shot.mime, "jpg")
+ with _lock:
+ folder.mkdir(parents=True, exist_ok=True)
+ (folder / f"original.{ext}").write_bytes(shot.image)
+ meta = {
+ **_base_meta(shot),
+ "mime": shot.mime,
+ "width": shot.width,
+ "height": shot.height,
+ }
+ _write_meta(folder, meta)
+ _prune()
+ return True
+ except (OSError, ValueError) as exc:
+ log.warning("appshot library: could not keep the appshot (%s)", exc)
+ return False
+
+
+def save_edit(shot: Appshot) -> bool:
+ """Keep the user's edit beside its original. ``shot`` carries the edited PNG.
+
+ An appshot that never reached the library (taken while it was off, or a
+ turn's own look) gets an entry of its own holding just the edit.
+ """
+ try:
+ folder = _folder(shot.id)
+ with _lock:
+ folder.mkdir(parents=True, exist_ok=True)
+ (folder / "edited.png").write_bytes(shot.image)
+ meta = _read_meta(folder) or _base_meta(shot)
+ meta.update(
+ {
+ "edited_at": time.time(),
+ "edited_width": shot.width,
+ "edited_height": shot.height,
+ }
+ )
+ _write_meta(folder, meta)
+ _drop_thumbs(folder, "edited")
+ _prune()
+ return True
+ except (OSError, ValueError) as exc:
+ log.warning("appshot library: could not keep the edit (%s)", exc)
+ return False
+
+
+def _items_for(folder: Path, meta: dict[str, object]) -> list[LibraryItem]:
+ def _num(key: str, default: float = 0.0) -> float:
+ value = meta.get(key, default)
+ return float(value) if isinstance(value, (int, float)) else default
+
+ common = {
+ "id": folder.name,
+ "label": str(meta.get("label") or ""),
+ "app_name": str(meta.get("app_name") or ""),
+ "trigger": str(meta.get("trigger") or ""),
+ "taken_at": _num("taken_at"),
+ }
+ items: list[LibraryItem] = []
+ edited = folder / "edited.png"
+ has_edit = edited.is_file()
+ if has_edit:
+ items.append(
+ LibraryItem(
+ variant="edited",
+ path=edited,
+ mime="image/png",
+ width=int(_num("edited_width")),
+ height=int(_num("edited_height")),
+ edited_at=_num("edited_at"),
+ has_edit=False,
+ **common, # type: ignore[arg-type]
+ )
+ )
+ original = _original_file(folder)
+ if original is not None:
+ items.append(
+ LibraryItem(
+ variant="original",
+ path=original,
+ mime=_MIMES[original.suffix.lstrip(".")],
+ width=int(_num("width")),
+ height=int(_num("height")),
+ edited_at=0.0,
+ has_edit=has_edit,
+ **common, # type: ignore[arg-type]
+ )
+ )
+ return items
+
+
+def list_items() -> list[LibraryItem]:
+ """Every kept picture, newest appshot first; an edit right before its original."""
+ root = library_root()
+ if not root.is_dir():
+ return []
+ entries: list[tuple[float, list[LibraryItem]]] = []
+ with _lock:
+ for folder in root.iterdir():
+ if not folder.is_dir() or not valid_id(folder.name):
+ continue
+ meta = _read_meta(folder)
+ if meta is None:
+ continue
+ items = _items_for(folder, meta)
+ if items:
+ entries.append((items[0].taken_at, items))
+ entries.sort(key=lambda entry: entry[0], reverse=True)
+ return [item for _taken, items in entries for item in items]
+
+
+def get_item(shot_id: str, variant: Variant) -> LibraryItem | None:
+ if not valid_id(shot_id):
+ return None
+ folder = library_root() / shot_id
+ with _lock:
+ meta = _read_meta(folder)
+ if meta is None:
+ return None
+ return next((i for i in _items_for(folder, meta) if i.variant == variant), None)
+
+
+def thumbnail(item: LibraryItem) -> tuple[bytes, str]:
+ """A small JPEG of ``item`` for the gallery grid, made once and kept.
+
+ Falls back to the full picture where Pillow cannot decode it.
+ """
+ thumb = item.path.parent / f"thumb-{item.variant}-{THUMB_EDGE}.jpg"
+ try:
+ return thumb.read_bytes(), "image/jpeg"
+ except OSError: # no thumbnail yet: it is made below
+ pass
+ try:
+ from PIL import Image # noqa: PLC0415
+
+ with Image.open(item.path) as image:
+ image.thumbnail((THUMB_EDGE, THUMB_EDGE))
+ if image.mode not in ("RGB", "L"):
+ image = image.convert("RGB")
+ out = io.BytesIO()
+ image.save(out, "JPEG", quality=82)
+ data = out.getvalue()
+ except (OSError, ValueError, ImportError) as exc:
+ log.debug("appshot library: thumbnail failed, serving the picture (%s)", exc)
+ return item.path.read_bytes(), item.mime
+ try:
+ thumb.write_bytes(data)
+ except OSError as exc:
+ log.debug("appshot library: thumbnail not cached (%s)", exc)
+ return data, "image/jpeg"
+
+
+def load_shot(shot_id: str, variant: Variant) -> Appshot | None:
+ """A kept picture as an :class:`Appshot`, to open it in the editor again."""
+ item = get_item(shot_id, variant)
+ if item is None:
+ return None
+ try:
+ image = item.path.read_bytes()
+ except OSError: # deleted meanwhile: the route answers 404
+ return None
+ from jarvis.appshot.service import APPSHOT_PREAMBLE # noqa: PLC0415
+
+ return Appshot(
+ id=item.id,
+ image=image,
+ mime=item.mime,
+ width=item.width,
+ height=item.height,
+ label=item.label or "appshot",
+ app_name=item.app_name,
+ note=APPSHOT_PREAMBLE,
+ ui_text="",
+ trigger=item.trigger or "library",
+ taken_at=item.taken_at,
+ )
+
+
+def delete(shot_id: str, variant: Variant) -> bool:
+ """Remove the edit only, or — for the original — the whole appshot."""
+ if not valid_id(shot_id):
+ return False
+ folder = library_root() / shot_id
+ with _lock:
+ if not folder.is_dir():
+ return False
+ edited = folder / "edited.png"
+ if variant == "edited" and _original_file(folder) is not None:
+ try:
+ edited.unlink()
+ except FileNotFoundError: # already gone: the route answers 404
+ return False
+ _drop_thumbs(folder, "edited")
+ return True
+ shutil.rmtree(folder, ignore_errors=True)
+ return not folder.exists()
+
+
+def clear() -> int:
+ """Delete every kept appshot; how many were removed."""
+ root = library_root()
+ if not root.is_dir():
+ return 0
+ removed = 0
+ with _lock:
+ for folder in root.iterdir():
+ if folder.is_dir() and valid_id(folder.name):
+ shutil.rmtree(folder, ignore_errors=True)
+ removed += 1
+ return removed
+
+
+def _prune() -> None:
+ """Keep at most :data:`MAX_ENTRIES` appshots. Caller holds the lock."""
+ root = library_root()
+ dated: list[tuple[float, Path]] = []
+ for folder in root.iterdir():
+ if not folder.is_dir() or not valid_id(folder.name):
+ continue
+ meta = _read_meta(folder) or {}
+ taken = meta.get("taken_at", 0.0)
+ dated.append((float(taken) if isinstance(taken, (int, float)) else 0.0, folder))
+ if len(dated) <= MAX_ENTRIES:
+ return
+ dated.sort(key=lambda entry: entry[0])
+ for _taken, folder in dated[: len(dated) - MAX_ENTRIES]:
+ shutil.rmtree(folder, ignore_errors=True)
+
+
+__all__ = [
+ "MAX_ENTRIES",
+ "THUMB_EDGE",
+ "LibraryItem",
+ "Variant",
+ "clear",
+ "delete",
+ "get_item",
+ "library_root",
+ "list_items",
+ "load_shot",
+ "save",
+ "save_edit",
+ "set_root",
+ "thumbnail",
+ "valid_id",
+]
diff --git a/jarvis/appshot/service.py b/jarvis/appshot/service.py
index 6932fdbd8e..ec0bb69706 100644
--- a/jarvis/appshot/service.py
+++ b/jarvis/appshot/service.py
@@ -26,7 +26,7 @@ Trigger = Literal["hotkey", "voice", "tool", "button"]
Scope = Literal["window", "region"]
#: Trusted framing in front of the untrusted screen evidence block.
-_APPSHOT_PREAMBLE = (
+APPSHOT_PREAMBLE = (
"APPSHOT: the user deliberately captured their front window to give you "
"context. Use it for their request. If they only asked you to take an "
"appshot, confirm it in one short sentence and ask what they want to know."
@@ -70,7 +70,7 @@ def shot_from_context(context: Any, *, trigger: str) -> Appshot:
height=int(context.size[1]),
label=label,
app_name=str(getattr(target.window, "app_name", "") or ""),
- note=f"{_APPSHOT_PREAMBLE}\n{model_note(context)}",
+ note=f"{APPSHOT_PREAMBLE}\n{model_note(context)}",
ui_text=context.ui_text,
trigger=trigger,
taken_at=time.time(),
@@ -138,6 +138,7 @@ async def take_appshot(
store = get_store()
store.remember(shot, keep_s=float(config.screen_context.deck_preview_s))
+ await _keep_in_library(shot, config)
await _attach_to_card(shot, config)
delivered_to = "turn"
if deliver:
@@ -200,6 +201,25 @@ async def record_turn_capture(context: Any, *, bus: Any | None, trigger: Trigger
log.warning("appshot: could not record the turn's capture", exc_info=True)
+async def _keep_in_library(shot: Appshot, config: Any) -> None:
+ """Write the appshot into the gallery's history when ``[appshot].library`` is on."""
+ if not bool(getattr(config.appshot, "library", False)):
+ return
+ from jarvis.appshot import library # noqa: PLC0415
+
+ await asyncio.to_thread(library.save, shot)
+
+
+async def keep_edit_in_library(shot: Appshot) -> None:
+ """Keep a saved edit beside its original, when the library is on."""
+ config = await asyncio.to_thread(_load_config)
+ if not bool(getattr(config.appshot, "library", False)):
+ return
+ from jarvis.appshot import library # noqa: PLC0415
+
+ await asyncio.to_thread(library.save_edit, shot)
+
+
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.
@@ -292,10 +312,12 @@ def take_pending_for_turn() -> Appshot | None:
__all__ = [
+ "APPSHOT_PREAMBLE",
"EDIT_NOTE",
"AppshotResult",
"Scope",
"deliver_edit",
+ "keep_edit_in_library",
"record_turn_capture",
"shot_from_context",
"take_appshot",
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index a834e4a790..a62936be63 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -2719,6 +2719,11 @@ class AppshotConfig(BaseModel):
#: until the user closes it.
card_seconds: int = Field(default=6, ge=0, le=600)
+ #: Keep every appshot (and its saved edit) in the gallery on the Appshots
+ #: page, under ``<data dir>/appshots/`` (read by ``jarvis.appshot.service``
+ #: and ``jarvis.appshot.library``). Off: nothing new is written there.
+ library: bool = True
+
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.py
index fd287ee862..9a8f90af70 100644
--- a/jarvis/core/config_writer.py
+++ b/jarvis/core/config_writer.py
@@ -1000,7 +1000,7 @@ 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", "card_seconds"}
+ {"hotkey", "region_hotkey", "target", "sound", "effect", "card_seconds", "library"}
)
diff --git a/jarvis/ui/web/appshot_routes.py b/jarvis/ui/web/appshot_routes.py
index 102751313f..73ff76a7ae 100644
--- a/jarvis/ui/web/appshot_routes.py
+++ b/jarvis/ui/web/appshot_routes.py
@@ -16,11 +16,17 @@ Endpoints (mounted by the WebServer in ``_build_app()``):
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.
+ GET /api/appshot/library → every kept appshot and edit (the gallery).
+ GET /api/appshot/library/{id}/image → one kept picture (``thumb=1``: small).
+ POST /api/appshot/library/{id}/open → open a kept picture in the editor.
+ DELETE /api/appshot/library/{id} → delete an edit, or the whole appshot.
+ DELETE /api/appshot/library → delete the whole gallery.
Under the CLI-first contract every action here is also a
-``jarvis api appshot <op>`` command. Pixels stay in memory
-(``jarvis.appshot.store``); the only image written to disk is the one a
-user drags out of the editor (``/drag-file``, see ``jarvis.appshot.dragfile``).
+``jarvis api appshot <op>`` command. Held pictures stay in memory
+(``jarvis.appshot.store``); the gallery's history lives in
+``jarvis.appshot.library`` while ``[appshot].library`` is on, and the editor's
+drag-out writes one temporary file (``/drag-file``, ``jarvis.appshot.dragfile``).
"""
from __future__ import annotations
@@ -49,6 +55,7 @@ class SettingsPatch(BaseModel):
sound: bool | None = None
effect: bool | None = None
card_seconds: int | None = Field(default=None, ge=0, le=600)
+ library: bool | None = None
class TakeRequest(BaseModel):
@@ -109,6 +116,7 @@ def _settings_payload() -> dict[str, Any]:
"sound": bool(block.sound),
"effect": bool(block.effect),
"card_seconds": int(getattr(block, "card_seconds", 6)),
+ "library": bool(getattr(block, "library", True)),
"sound_effects_master": bool(getattr(config.ui, "sound_effects", True)),
"shortcut": _status("window"),
"region_shortcut": _status("region"),
@@ -214,9 +222,14 @@ async def latest_image(id: str = "") -> Response: # noqa: A002
from jarvis.appshot.store import get_store # noqa: PLC0415
store = get_store()
- shot = (await asyncio.to_thread(store.get, id) if id else None) or await asyncio.to_thread(
- store.latest
- )
+ shot = await asyncio.to_thread(store.get, id) if id else None
+ if shot is None and id and await asyncio.to_thread(_library_has, id):
+ # A gallery picture whose hold expired while its editor stayed open.
+ shot = await asyncio.to_thread(_hold_from_library, id, "edited") or await asyncio.to_thread(
+ _hold_from_library, id, "original"
+ )
+ if shot is None:
+ shot = await asyncio.to_thread(store.latest)
if shot is None:
raise HTTPException(status_code=404, detail="No appshot is being kept right now.")
return Response(content=shot.image, media_type=shot.mime, headers=_NO_STORE)
@@ -242,10 +255,14 @@ async def replace_latest_image(request: Request, id: str) -> dict[str, Any]: #
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 and await asyncio.to_thread(_hold_from_library, id, "original"):
+ # Edited from the gallery after its hold expired: hold it again, then edit.
+ 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.")
- from jarvis.appshot.service import deliver_edit # noqa: PLC0415
+ from jarvis.appshot.service import deliver_edit, keep_edit_in_library # noqa: PLC0415
+ await keep_edit_in_library(shot)
delivered_to = await deliver_edit(shot)
return {"ok": True, "appshot": {**shot.meta(), "delivered_to": delivered_to}}
@@ -380,3 +397,109 @@ async def forget_all() -> dict[str, Any]:
await asyncio.to_thread(get_store().clear)
return {"ok": True}
+
+
+# -- library (the gallery on the Appshots page) -------------------------------
+
+LibraryVariant = Literal["original", "edited"]
+
+_LIBRARY_CACHE = {"Cache-Control": "private, max-age=86400"}
+
+#: How long a gallery picture opened in the editor stays held, at least.
+_LIBRARY_HOLD_S = 900.0
+
+
+def _hold_from_library(shot_id: str, variant: str) -> Any | None:
+ """Put a kept picture back into the store so the editor can work on it."""
+ from jarvis.appshot import library # noqa: PLC0415
+ from jarvis.appshot.store import get_store # noqa: PLC0415
+ from jarvis.core.config import load_config # noqa: PLC0415
+
+ shot = library.load_shot(shot_id, "edited" if variant == "edited" else "original")
+ if shot is None:
+ return None
+ keep_s = max(float(load_config().screen_context.deck_preview_s), _LIBRARY_HOLD_S)
+ get_store().remember(shot, keep_s=keep_s)
+ return shot
+
+
+def _library_has(shot_id: str) -> bool:
+ from jarvis.appshot import library # noqa: PLC0415
+
+ return library.valid_id(shot_id) and (library.library_root() / shot_id).is_dir()
+
+
+def _library_id(shot_id: str) -> str:
+ from jarvis.appshot.library import valid_id # noqa: PLC0415
+
+ if not valid_id(shot_id):
+ raise HTTPException(status_code=404, detail="No such appshot.")
+ return shot_id
+
+
[email protected]("/library")
+async def library_list() -> dict[str, Any]:
+ """Every kept appshot and edit, newest first — no pixels."""
+ from jarvis.appshot import library # noqa: PLC0415
+
+ items = await asyncio.to_thread(library.list_items)
+ return {
+ "items": [item.to_json() for item in items],
+ "max_entries": library.MAX_ENTRIES,
+ }
+
+
[email protected]("/library/{shot_id}/image")
+async def library_image(
+ shot_id: str, variant: LibraryVariant = "original", thumb: bool = False
+) -> Response:
+ """One kept picture; ``thumb=1`` sends the gallery's small JPEG."""
+ from jarvis.appshot import library # noqa: PLC0415
+
+ item = await asyncio.to_thread(library.get_item, _library_id(shot_id), variant)
+ if item is None:
+ raise HTTPException(status_code=404, detail="That appshot is no longer kept.")
+ if thumb:
+ data, mime = await asyncio.to_thread(library.thumbnail, item)
+ else:
+ data, mime = await asyncio.to_thread(item.path.read_bytes), item.mime
+ # The page versions the URL by its edit time, so a cached copy is never stale.
+ return Response(content=data, media_type=mime, headers=_LIBRARY_CACHE)
+
+
+class LibraryOpenRequest(BaseModel):
+ variant: LibraryVariant = "original"
+
+
[email protected]("/library/{shot_id}/open")
+async def library_open(shot_id: str, body: LibraryOpenRequest | None = None) -> dict[str, Any]:
+ """Hold a kept picture again and open the editor on it.
+
+ ``window: false`` = the page opens its own editor on ``id``.
+ """
+ variant = (body or LibraryOpenRequest()).variant
+ shot = await asyncio.to_thread(_hold_from_library, _library_id(shot_id), variant)
+ if shot is None:
+ raise HTTPException(status_code=404, detail="That appshot is no longer kept.")
+ from jarvis.appshot.editor_window import open_editor_window # noqa: PLC0415
+
+ return {"id": shot.id, "window": await open_editor_window(shot.id)}
+
+
[email protected]("/library/{shot_id}", openapi_extra={"x-jarvis-dangerous": True})
+async def library_delete(shot_id: str, variant: LibraryVariant = "original") -> dict[str, Any]:
+ """Delete an edit only, or — for the original — the whole appshot."""
+ from jarvis.appshot import library # noqa: PLC0415
+
+ removed = await asyncio.to_thread(library.delete, _library_id(shot_id), variant)
+ if not removed:
+ raise HTTPException(status_code=404, detail="That appshot is no longer kept.")
+ return {"ok": True}
+
+
[email protected]("/library", openapi_extra={"x-jarvis-dangerous": True})
+async def library_clear() -> dict[str, Any]:
+ """Delete every kept appshot and edit."""
+ from jarvis.appshot import library # noqa: PLC0415
+
+ return {"ok": True, "removed": await asyncio.to_thread(library.clear)}
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.json
index e5053bcc48..a81f1dae43 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
@@ -76,6 +76,29 @@
"arrow_style": "Pfeilstil",
"arrow_tapered": "Spitz zulaufend",
"arrow_classic": "Klassisch",
- "arrow_double": "Zwei Spitzen"
+ "arrow_double": "Zwei Spitzen",
+ "library_title": "Deine Appshots",
+ "library_subtitle": "Jeder Appshot, den du machst, und jede Bearbeitung, die du speicherst. Zieh einen in einen Chat, ein Terminal oder eine andere App.",
+ "library_off": "Der Verlauf ist aus, neue Appshots werden nicht aufbewahrt. Schalte oben „Appshot-Verlauf behalten“ ein.",
+ "library_count": "{0} Bilder",
+ "library_filter_all": "Alle",
+ "library_filter_edited": "Bearbeitet",
+ "library_edited_badge": "Bearbeitet",
+ "library_empty": "Noch keine Appshots. Mach einen mit dem Kürzel, dann erscheint er hier.",
+ "library_empty_edited": "Noch keine bearbeiteten Appshots. Öffne einen, markiere etwas und speichere.",
+ "library_label": "Appshot-Verlauf behalten",
+ "library_hint": "Bewahrt jeden Appshot und jede Bearbeitung auf diesem Computer auf, die neuesten 500. Aus: Neues wird nicht aufbewahrt.",
+ "library_edit": "Bearbeiten",
+ "library_delete": "Löschen",
+ "library_delete_edit_hint": "Nur diese bearbeitete Fassung löschen",
+ "library_delete_original_hint": "Diesen Appshot samt Bearbeitung löschen",
+ "library_delete_all": "Alle löschen",
+ "library_delete_all_confirm": "Wirklich alle löschen?",
+ "library_deleted_all": "Appshot-Verlauf gelöscht",
+ "library_drag_hint": "Zieh ein Bild in einen Chat oder ein Terminal, um es anzuhängen. Klick es an, um es zu bearbeiten.",
+ "library_drag_out": "In eine andere App ziehen",
+ "library_show_more": "Mehr anzeigen",
+ "library_load_failed": "Die Appshots konnten nicht geladen werden: {0}",
+ "library_open_failed": "Dieser Appshot konnte nicht geöffnet werden: {0}"
}
}
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.json
index fa31e83d53..7c428c9818 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
@@ -76,6 +76,29 @@
"arrow_style": "Arrow style",
"arrow_tapered": "Tapered",
"arrow_classic": "Classic",
- "arrow_double": "Two heads"
+ "arrow_double": "Two heads",
+ "library_title": "Your appshots",
+ "library_subtitle": "Every appshot you take and every edit you save. Drag one into a chat, a terminal or another app.",
+ "library_off": "History is off, so new appshots are not kept. Turn on “Keep appshot history” above.",
+ "library_count": "{0} pictures",
+ "library_filter_all": "All",
+ "library_filter_edited": "Edited",
+ "library_edited_badge": "Edited",
+ "library_empty": "No appshots yet. Take one with the shortcut and it shows up here.",
+ "library_empty_edited": "No edited appshots yet. Open one, mark it up and save.",
+ "library_label": "Keep appshot history",
+ "library_hint": "Keeps every appshot and edit on this computer, the newest 500. Off: nothing new is kept.",
+ "library_edit": "Edit",
+ "library_delete": "Delete",
+ "library_delete_edit_hint": "Delete only this edited version",
+ "library_delete_original_hint": "Delete this appshot and its edit",
+ "library_delete_all": "Delete all",
+ "library_delete_all_confirm": "Really delete all?",
+ "library_deleted_all": "Appshot history deleted",
+ "library_drag_hint": "Drag a picture into a chat or a terminal to attach it. Click it to edit.",
+ "library_drag_out": "Drag into another app",
+ "library_show_more": "Show more",
+ "library_load_failed": "The appshots could not be loaded: {0}",
+ "library_open_failed": "This appshot could not be opened: {0}"
}
}
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.json
index edf0f4832c..e28896d86e 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
@@ -76,6 +76,29 @@
"arrow_style": "Estilo de flecha",
"arrow_tapered": "Afilada",
"arrow_classic": "Clásica",
- "arrow_double": "Dos puntas"
+ "arrow_double": "Dos puntas",
+ "library_title": "Tus appshots",
+ "library_subtitle": "Cada appshot que haces y cada edición que guardas. Arrastra uno a un chat, una terminal u otra app.",
+ "library_off": "El historial está desactivado, así que los nuevos appshots no se guardan. Activa “Guardar historial de appshots” arriba.",
+ "library_count": "{0} imágenes",
+ "library_filter_all": "Todos",
+ "library_filter_edited": "Editados",
+ "library_edited_badge": "Editado",
+ "library_empty": "Aún no hay appshots. Haz uno con el atajo y aparecerá aquí.",
+ "library_empty_edited": "Aún no hay appshots editados. Abre uno, márcalo y guárdalo.",
+ "library_label": "Guardar historial de appshots",
+ "library_hint": "Guarda cada appshot y cada edición en este equipo, los 500 más recientes. Desactivado: no se guarda nada nuevo.",
+ "library_edit": "Editar",
+ "library_delete": "Eliminar",
+ "library_delete_edit_hint": "Eliminar solo esta versión editada",
+ "library_delete_original_hint": "Eliminar este appshot y su edición",
+ "library_delete_all": "Eliminar todo",
+ "library_delete_all_confirm": "¿Eliminar todo de verdad?",
+ "library_deleted_all": "Historial de appshots eliminado",
+ "library_drag_hint": "Arrastra una imagen a un chat o una terminal para adjuntarla. Haz clic para editarla.",
+ "library_drag_out": "Arrastrar a otra app",
+ "library_show_more": "Mostrar más",
+ "library_load_failed": "No se pudieron cargar los appshots: {0}",
+ "library_open_failed": "No se pudo abrir este appshot: {0}"
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 0916bc66b7..9aa13da658 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -5980,7 +5980,7 @@
"title": "Appshots",
"subtitle": "Zeig {name} das Fenster, in dem du gerade arbeitest.",
"hero_title": "Mach einen Appshot, um {name} dein vorderstes Fenster zu zeigen",
- "hero_body": "Ein Appshot nimmt das Fenster im Vordergrund auf, Bild und sichtbaren Text, und gibt es ins Gespräch. Deine Datenschutz-Regeln gelten weiter, und nichts wird auf der Festplatte gespeichert.",
+ "hero_body": "Ein Appshot nimmt das Fenster im Vordergrund auf, Bild und sichtbaren Text, und gibt es ins Gespräch. Deine Datenschutz-Regeln gelten weiter. Nur der Verlauf unten bleibt auf diesem Computer, und du kannst ihn jederzeit löschen.",
"enabled_label": "Appshots erlauben",
"enabled_hint": "Gilt auch für Fragen wie \"Was siehst du?\". Aus heißt: {name} schaut nie auf deinen Bildschirm.",
"shortcut_label": "Tastenkürzel",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 222b78f723..b3bfc2e0fa 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -6013,7 +6013,7 @@
"title": "Appshots",
"subtitle": "Show {name} the window you are working in.",
"hero_title": "Take an appshot to show {name} your front window",
- "hero_body": "An appshot captures the window in front, picture and on-screen text, and hands it to the conversation. Your privacy rules still apply, and nothing is saved to disk.",
+ "hero_body": "An appshot captures the window in front, picture and on-screen text, and hands it to the conversation. Your privacy rules still apply. Only the history below stays on this computer, and you can delete it anytime.",
"enabled_label": "Allow appshots",
"enabled_hint": "Also covers questions like \"what do you see?\". Off means {name} never looks at your screen.",
"shortcut_label": "Keyboard shortcut",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index d92df8856a..2dee4f81ca 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -5980,7 +5980,7 @@
"title": "Appshots",
"subtitle": "Muestra a {name} la ventana en la que trabajas.",
"hero_title": "Haz un appshot para mostrar a {name} tu ventana principal",
- "hero_body": "Un appshot captura la ventana en primer plano, imagen y texto visible, y la pasa a la conversación. Tus reglas de privacidad siguen aplicándose y no se guarda nada en el disco.",
+ "hero_body": "Un appshot captura la ventana en primer plano, imagen y texto visible, y la pasa a la conversación. Tus reglas de privacidad siguen aplicándose. Solo el historial de abajo se queda en este equipo y puedes borrarlo cuando quieras.",
"enabled_label": "Permitir appshots",
"enabled_hint": "También cubre preguntas como \"¿qué ves?\". Desactivado significa que {name} nunca mira tu pantalla.",
"shortcut_label": "Atajo de teclado",
diff --git a/jarvis/ui/web/frontend/src/lib/appshotApi.ts b/jarvis/ui/web/frontend/src/lib/appshotApi.ts
index e5b4c5f98e..c1b0eed123 100644
--- a/jarvis/ui/web/frontend/src/lib/appshotApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/appshotApi.ts
@@ -1,8 +1,9 @@
/**
* Client for `/api/appshot` — the front window as conversation context.
*
- * Pixels only ever come from the two image endpoints, which the backend serves
- * with `Cache-Control: no-store`; nothing here keeps a copy.
+ * Held pixels come from the two image endpoints, which the backend serves with
+ * `Cache-Control: no-store`; nothing here keeps a copy. The gallery's pictures
+ * come from `/api/appshot/library`, versioned by their edit time.
*/
export type AppshotTarget = "auto" | "message" | "voice";
@@ -25,6 +26,8 @@ export interface AppshotSettings {
effect: boolean;
/** Seconds the corner card rests; 0 = until the user closes it. */
card_seconds: number;
+ /** Keep every appshot and edit in the gallery. Absent on an older backend. */
+ library?: boolean;
sound_effects_master: boolean;
shortcut: AppshotShortcutStatus;
region_shortcut: AppshotShortcutStatus;
@@ -50,7 +53,10 @@ export interface AppshotMeta {
}
export type AppshotSettingsPatch = Partial<
- Pick<AppshotSettings, "enabled" | "hotkey" | "region_hotkey" | "target" | "sound" | "effect" | "card_seconds">
+ Pick<
+ AppshotSettings,
+ "enabled" | "hotkey" | "region_hotkey" | "target" | "sound" | "effect" | "card_seconds" | "library"
+ >
>;
async function request<T>(url: string, init?: RequestInit): Promise<T> {
@@ -165,3 +171,77 @@ export async function openAppshotEditorWindow(id: string): Promise<boolean> {
/** How long the corner card may rest, in seconds; 0 = until closed. */
export const CARD_SECONDS_CHOICES = [3, 6, 10, 30, 60, 300, 0] as const;
+
+// -- library: the gallery of every kept appshot and edit ----------------------
+
+export type AppshotLibraryVariant = "original" | "edited";
+
+export interface AppshotLibraryItem {
+ id: string;
+ variant: AppshotLibraryVariant;
+ /** Where the picture lies on the machine running the backend. */
+ path: string;
+ mime: string;
+ width: number;
+ height: number;
+ label: string;
+ app_name: string;
+ trigger: string;
+ taken_at: number;
+ /** When the edit was saved; 0 for an original. */
+ edited_at: number;
+ /** An original that also has an edited version. */
+ has_edit: boolean;
+}
+
+export function fetchAppshotLibrary(): Promise<{ items: AppshotLibraryItem[]; max_entries: number }> {
+ return request("/api/appshot/library");
+}
+
+/** The picture's URL; `thumb` asks for the gallery's small JPEG. */
+export function appshotLibraryImageUrl(item: AppshotLibraryItem, thumb = false): string {
+ const params = new URLSearchParams({
+ variant: item.variant,
+ v: String(item.edited_at || item.taken_at),
+ });
+ if (thumb) params.set("thumb", "1");
+ return `/api/appshot/library/${encodeURIComponent(item.id)}/image?${params.toString()}`;
+}
+
+/** A file name for a dragged-out picture: `appshot-20261003-114747(-edited).png`. */
+export function appshotLibraryFileName(item: AppshotLibraryItem): string {
+ const fromPath = item.path.split(/[\\/]/).pop() ?? "";
+ const extension = fromPath.includes(".") ? fromPath.split(".").pop() : "png";
+ const stamp = new Date(item.taken_at * 1000)
+ .toISOString()
+ .replace(/[-:]/g, "")
+ .replace(/\..*$/, "")
+ .replace("T", "-");
+ return `appshot-${stamp}${item.variant === "edited" ? "-edited" : ""}.${extension}`;
+}
+
+/**
+ * Hold a kept picture again and open the editor on it. `window: false` means
+ * the page has to show its own editor on `id`.
+ */
+export function openAppshotLibraryItem(
+ item: AppshotLibraryItem,
+): Promise<{ id: string; window: boolean }> {
+ return request(`/api/appshot/library/${encodeURIComponent(item.id)}/open`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ variant: item.variant }),
+ });
+}
+
+/** An edited tile deletes only the edit; an original deletes the whole appshot. */
+export function deleteAppshotLibraryItem(item: AppshotLibraryItem): Promise<{ ok: boolean }> {
+ return request(
+ `/api/appshot/library/${encodeURIComponent(item.id)}?variant=${encodeURIComponent(item.variant)}`,
+ { method: "DELETE" },
+ );
+}
+
+export function clearAppshotLibrary(): Promise<{ ok: boolean; removed: number }> {
+ return request("/api/appshot/library", { method: "DELETE" });
+}
diff --git a/jarvis/ui/web/frontend/src/views/AppshotLibrary.test.tsx b/jarvis/ui/web/frontend/src/views/AppshotLibrary.test.tsx
new file mode 100644
index 0000000000..22586a33e3
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/AppshotLibrary.test.tsx
@@ -0,0 +1,142 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { extractPaneDrop, WORKSPACE_PATH_TYPE } from "@/components/agentic/paneDrop";
+import { loadLocaleChunk } from "@/i18n";
+import type { AppshotLibraryItem } from "@/lib/appshotApi";
+import { useAppshotEditor } from "@/store/appshotEditor";
+import { useEventStore } from "@/store/events";
+import { AppshotLibrary } from "@/views/AppshotLibrary";
+
+const ORIGINAL: AppshotLibraryItem = {
+ id: "a1",
+ variant: "original",
+ path: "C:\\Jarvis\\data\\appshots\\a1\\original.png",
+ mime: "image/png",
+ width: 1280,
+ height: 720,
+ label: "active window",
+ app_name: "Editor",
+ trigger: "hotkey",
+ taken_at: 1_790_000_000,
+ edited_at: 0,
+ has_edit: true,
+};
+const EDITED: AppshotLibraryItem = {
+ ...ORIGINAL,
+ variant: "edited",
+ path: "C:\\Jarvis\\data\\appshots\\a1\\edited.png",
+ edited_at: 1_790_000_100,
+ has_edit: false,
+};
+const OTHER: AppshotLibraryItem = { ...ORIGINAL, id: "b2", has_edit: false, app_name: "Browser" };
+
+function json(body: unknown, status = 200): Response {
+ return { ok: status < 400, status, json: async () => body } as Response;
+}
+
+class FakeDataTransfer {
+ data = new Map<string, string>();
+ effectAllowed = "";
+ dropEffect = "";
+ files = [] as unknown as FileList;
+ get types() {
+ return Array.from(this.data.keys());
+ }
+ setData(type: string, value: string) {
+ this.data.set(type, value);
+ }
+ getData(type: string) {
+ return this.data.get(type) ?? "";
+ }
+ setDragImage() {}
+}
+
+describe("AppshotLibrary", () => {
+ let fetchMock: ReturnType<typeof vi.fn>;
+ let items: AppshotLibraryItem[];
+
+ beforeEach(async () => {
+ await loadLocaleChunk("appshot_editor");
+ useEventStore.setState({ events: [], toasts: [], assistantName: "Jarvis" });
+ useAppshotEditor.setState({ openId: null, revision: 0 });
+ items = [EDITED, ORIGINAL, OTHER];
+ fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
+ if (url === "/api/appshot/library" && init?.method === "DELETE") {
+ const removed = new Set(items.map((i) => i.id)).size;
+ items = [];
+ return json({ ok: true, removed });
+ }
+ if (url === "/api/appshot/library") return json({ items, max_entries: 500 });
+ if (url.startsWith("/api/appshot/library/a1?variant=edited") && init?.method === "DELETE") {
+ items = items.filter((i) => i !== EDITED);
+ return json({ ok: true });
+ }
+ if (url === "/api/appshot/library/b2/open") return json({ id: "b2", window: false });
+ return json({}, 404);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ });
+
+ it("shows every kept picture and filters to the edited ones", async () => {
+ render(<AppshotLibrary enabled refreshKey="" />);
+ await waitFor(() => expect(screen.getAllByTestId("appshot-library-tile")).toHaveLength(3));
+ expect(screen.getByText("Edited", { selector: "span" })).toBeDefined();
+
+ fireEvent.click(screen.getByTestId("appshot-library-filter-edited"));
+ const tiles = screen.getAllByTestId("appshot-library-tile");
+ expect(tiles).toHaveLength(1);
+ expect(tiles[0].getAttribute("data-variant")).toBe("edited");
+ });
+
+ it("drags a tile as a real path the chat composer and the panes accept", async () => {
+ render(<AppshotLibrary enabled refreshKey="" />);
+ const [tile] = await screen.findAllByTestId("appshot-library-tile");
+ const dt = new FakeDataTransfer();
+ fireEvent.dragStart(tile, { dataTransfer: dt });
+
+ expect(dt.getData(WORKSPACE_PATH_TYPE)).toBe(EDITED.path);
+ expect(dt.getData("DownloadURL")).toMatch(/^image\/png:appshot-.*-edited\.png:http/);
+ // The drop side (paneDrop, shared by panes and the composer) reads it back verbatim.
+ expect(extractPaneDrop(dt as unknown as DataTransfer).paths).toEqual([EDITED.path]);
+ });
+
+ it("deletes only the edit from an edited tile", async () => {
+ render(<AppshotLibrary enabled refreshKey="" />);
+ await waitFor(() => expect(screen.getAllByTestId("appshot-library-tile")).toHaveLength(3));
+ fireEvent.click(screen.getAllByTestId("appshot-library-delete")[0]);
+ await waitFor(() => expect(screen.getAllByTestId("appshot-library-tile")).toHaveLength(2));
+ expect(
+ fetchMock.mock.calls.some(
+ ([url, init]) => url === "/api/appshot/library/a1?variant=edited" && init?.method === "DELETE",
+ ),
+ ).toBe(true);
+ });
+
+ it("asks twice before deleting the whole history", async () => {
+ render(<AppshotLibrary enabled refreshKey="" />);
+ const clear = await screen.findByTestId("appshot-library-clear");
+ fireEvent.click(clear);
+ expect(fetchMock.mock.calls.some(([, init]) => init?.method === "DELETE")).toBe(false);
+ fireEvent.click(screen.getByTestId("appshot-library-clear"));
+ await waitFor(() => expect(screen.queryAllByTestId("appshot-library-tile")).toHaveLength(0));
+ });
+
+ it("opens a picture in the page's editor when no editor window can open", async () => {
+ render(<AppshotLibrary enabled refreshKey="" />);
+ const tiles = await screen.findAllByTestId("appshot-library-tile");
+ fireEvent.click(tiles[2].querySelector("button")!);
+ await waitFor(() => expect(useAppshotEditor.getState().openId).toBe("b2"));
+ });
+
+ it("says so when the history is switched off", async () => {
+ items = [];
+ render(<AppshotLibrary enabled={false} refreshKey="" />);
+ await screen.findByText(/History is off/);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/views/AppshotLibrary.tsx b/jarvis/ui/web/frontend/src/views/AppshotLibrary.tsx
new file mode 100644
index 0000000000..29e585b708
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/AppshotLibrary.tsx
@@ -0,0 +1,396 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { GripVertical, Loader2, PenLine, Trash2 } from "lucide-react";
+
+import { setWorkspaceEntryDrag } from "@/components/agentic/explorerDrag";
+import { Button } from "@/components/ui/button";
+import { QuickTooltip } from "@/components/ui/tooltip";
+import { useLocaleChunk, useT } from "@/i18n";
+import {
+ appshotLibraryFileName,
+ appshotLibraryImageUrl,
+ clearAppshotLibrary,
+ deleteAppshotLibraryItem,
+ fetchAppshotLibrary,
+ openAppshotLibraryItem,
+ type AppshotLibraryItem,
+} from "@/lib/appshotApi";
+import { canNativeDrag, startNativeFileDrag } from "@/lib/nativeDrag";
+import { cn } from "@/lib/utils";
+import { useAppshotEditor } from "@/store/appshotEditor";
+import { useEventStore } from "@/store/events";
+
+/**
+ * The gallery on the Appshots page: every appshot the user took and every
+ * edit they saved, newest first (`jarvis.appshot.library`).
+ *
+ * A tile is a drag source for the app's own fields: it carries the picture's
+ * real path the way a row from the workspace explorer does, so the chat
+ * composer attaches it and a terminal pane hands it to its agent — the drop
+ * targets need no appshot-specific code. Inside the desktop shell the grip
+ * starts a native file drag instead, which reaches any other app as well.
+ */
+
+type Filter = "all" | "edited";
+
+/** Tiles rendered before "Show more"; the grid stays light with 500 kept. */
+const PAGE = 48;
+
+const tileKey = (item: AppshotLibraryItem) => `${item.id}:${item.variant}`;
+
+function when(item: AppshotLibraryItem): string {
+ return new Date((item.edited_at || item.taken_at) * 1000).toLocaleString([], {
+ day: "numeric",
+ month: "short",
+ hour: "2-digit",
+ minute: "2-digit",
+ });
+}
+
+function Tile({
+ item,
+ busy,
+ onOpen,
+ onDelete,
+}: {
+ item: AppshotLibraryItem;
+ busy: boolean;
+ onOpen: () => void;
+ onDelete: () => void;
+}) {
+ const t = useT();
+ const imageRef = useRef<HTMLImageElement | null>(null);
+ const where = item.app_name || item.label || t("appshots.preview_front_window");
+ const edited = item.variant === "edited";
+ const nativeDrag = canNativeDrag();
+
+ const onDragStart = (event: React.DragEvent) => {
+ // The path, a file URI and the path as text — what the panes, the chat
+ // composer and other text fields read (explorerDrag.ts). DownloadURL lets
+ // a browser drop the picture itself onto the desktop or into a folder.
+ const dt = event.dataTransfer;
+ const lastSlash = Math.max(item.path.lastIndexOf("/"), item.path.lastIndexOf("\\"));
+ setWorkspaceEntryDrag(dt, {
+ root: item.path.slice(0, lastSlash),
+ path: item.path.slice(lastSlash + 1),
+ });
+ const absoluteUrl = new URL(appshotLibraryImageUrl(item), window.location.href).toString();
+ dt.setData("DownloadURL", `${item.mime}:${appshotLibraryFileName(item)}:${absoluteUrl}`);
+ if (imageRef.current) dt.setDragImage(imageRef.current, 24, 24);
+ };
+
+ return (
+ <li
+ draggable
+ onDragStart={onDragStart}
+ data-testid="appshot-library-tile"
+ data-variant={item.variant}
+ className="group relative flex cursor-grab flex-col overflow-hidden rounded-lg border border-border bg-background active:cursor-grabbing"
+ >
+ <button
+ type="button"
+ onClick={onOpen}
+ disabled={busy}
+ aria-label={`${t("appshot_editor.library_edit")}: ${where}`}
+ className="flex aspect-[16/10] w-full items-center justify-center overflow-hidden bg-secondary/60 p-2 focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-border-strong"
+ >
+ <img
+ ref={imageRef}
+ src={appshotLibraryImageUrl(item, true)}
+ alt={t("appshots.preview_alt").replace("{0}", where)}
+ loading="lazy"
+ draggable={false}
+ className="max-h-full max-w-full rounded-sm object-contain shadow-sm ring-1 ring-border transition-opacity group-hover:opacity-90"
+ />
+ </button>
+ {edited && (
+ <span className="pointer-events-none absolute left-2 top-2 inline-flex items-center gap-1 rounded-full bg-accent px-2 py-0.5 text-xs font-medium text-accent-foreground shadow-sm">
+ <PenLine className="h-3 w-3" aria-hidden />
+ {t("appshot_editor.library_edited_badge")}
+ </span>
+ )}
+ <div className="absolute right-1.5 top-1.5 flex items-center gap-1 opacity-0 transition-opacity focus-within:opacity-100 group-hover:opacity-100">
+ {nativeDrag && (
+ <QuickTooltip content={t("appshot_editor.library_drag_out")} side="top">
+ <span
+ role="button"
+ tabIndex={-1}
+ aria-label={t("appshot_editor.library_drag_out")}
+ data-testid="appshot-library-drag-out"
+ onPointerDown={(event) => {
+ if (event.button !== 0) return;
+ event.preventDefault();
+ event.stopPropagation();
+ startNativeFileDrag(item.path);
+ }}
+ className="inline-flex h-7 w-7 cursor-grab items-center justify-center rounded-md border border-border bg-card text-muted-foreground shadow-sm hover:text-foreground"
+ >
+ <GripVertical className="h-3.5 w-3.5" aria-hidden />
+ </span>
+ </QuickTooltip>
+ )}
+ <QuickTooltip
+ content={t(
+ edited
+ ? "appshot_editor.library_delete_edit_hint"
+ : "appshot_editor.library_delete_original_hint",
+ )}
+ side="top"
+ >
+ <button
+ type="button"
+ onClick={onDelete}
+ disabled={busy}
+ aria-label={t("appshot_editor.library_delete")}
+ data-testid="appshot-library-delete"
+ className="inline-flex h-7 w-7 items-center justify-center rounded-md border border-border bg-card text-muted-foreground shadow-sm hover:text-destructive focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong"
+ >
+ <Trash2 className="h-3.5 w-3.5" aria-hidden />
+ </button>
+ </QuickTooltip>
+ </div>
+ <div className="min-w-0 px-3 py-2">
+ <p className="truncate text-sm font-medium text-foreground">{where}</p>
+ <p className="truncate text-xs text-muted-foreground">
+ {[when(item), `${item.width} × ${item.height}`].join(" · ")}
+ </p>
+ </div>
+ </li>
+ );
+}
+
+export function AppshotLibrary({
+ enabled,
+ refreshKey,
+}: {
+ /** `[appshot].library`; `undefined` while the settings load or on an older backend. */
+ enabled: boolean | undefined;
+ /** Changes whenever a new appshot was taken or an edit replaced one. */
+ refreshKey: string;
+}) {
+ const t = useT();
+ // The gallery's strings live in the editor's locale chunk.
+ const ready = useLocaleChunk("appshot_editor");
+ const pushToast = useEventStore((s) => s.pushToast);
+ const openEditor = useAppshotEditor((s) => s.open);
+ const [items, setItems] = useState<AppshotLibraryItem[] | null>(null);
+ const [error, setError] = useState("");
+ const [filter, setFilter] = useState<Filter>("all");
+ const [limit, setLimit] = useState(PAGE);
+ const [busyKey, setBusyKey] = useState("");
+ const [confirmClear, setConfirmClear] = useState(false);
+ const [clearing, setClearing] = useState(false);
+ const confirmTimer = useRef<number | null>(null);
+
+ const load = useCallback(async () => {
+ try {
+ const body = await fetchAppshotLibrary();
+ setItems(body.items);
+ setError("");
+ } catch (failure) {
+ setError((failure as Error).message);
+ setItems((current) => current ?? []);
+ }
+ }, []);
+
+ useEffect(() => {
+ void load();
+ }, [load, refreshKey]);
+
+ // The editor's own window saves while this page waits behind it; coming
+ // back to the app shows the edit.
+ useEffect(() => {
+ const onFocus = () => void load();
+ window.addEventListener("focus", onFocus);
+ return () => window.removeEventListener("focus", onFocus);
+ }, [load]);
+
+ useEffect(
+ () => () => {
+ if (confirmTimer.current !== null) window.clearTimeout(confirmTimer.current);
+ },
+ [],
+ );
+
+ const editedCount = useMemo(
+ () => (items ?? []).filter((item) => item.variant === "edited").length,
+ [items],
+ );
+ const shown = useMemo(
+ () => (items ?? []).filter((item) => filter === "all" || item.variant === "edited"),
+ [items, filter],
+ );
+
+ const open = useCallback(
+ async (item: AppshotLibraryItem) => {
+ setBusyKey(tileKey(item));
+ try {
+ const result = await openAppshotLibraryItem(item);
+ if (!result.window) openEditor(result.id);
+ } catch (failure) {
+ pushToast(
+ "error",
+ t("appshot_editor.library_open_failed").replace("{0}", (failure as Error).message),
+ );
+ void load();
+ } finally {
+ setBusyKey("");
+ }
+ },
+ [load, openEditor, pushToast, t],
+ );
+
+ const remove = useCallback(
+ async (item: AppshotLibraryItem) => {
+ setBusyKey(tileKey(item));
+ try {
+ await deleteAppshotLibraryItem(item);
+ } catch (failure) {
+ pushToast("error", (failure as Error).message);
+ } finally {
+ setBusyKey("");
+ void load();
+ }
+ },
+ [load, pushToast],
+ );
+
+ const clearAll = useCallback(async () => {
+ if (!confirmClear) {
+ // Two presses, no dialog: the first one only arms the button.
+ setConfirmClear(true);
+ confirmTimer.current = window.setTimeout(() => setConfirmClear(false), 4000);
+ return;
+ }
+ if (confirmTimer.current !== null) window.clearTimeout(confirmTimer.current);
+ setConfirmClear(false);
+ setClearing(true);
+ try {
+ await clearAppshotLibrary();
+ pushToast("success", t("appshot_editor.library_deleted_all"));
+ } catch (failure) {
+ pushToast("error", (failure as Error).message);
+ } finally {
+ setClearing(false);
+ void load();
+ }
+ }, [confirmClear, load, pushToast, t]);
+
+ const total = items?.length ?? 0;
+ const empty = items !== null && shown.length === 0;
+
+ return (
+ <section
+ data-testid="appshot-library"
+ className="mt-5 rounded-xl border border-border bg-card p-5"
+ aria-labelledby="appshot-library-title"
+ >
+ <div className="flex flex-wrap items-start justify-between gap-x-6 gap-y-3">
+ <div className="min-w-[min(100%,16rem)] flex-1">
+ <p id="appshot-library-title" className="text-base font-medium text-foreground">
+ {t("appshot_editor.library_title")}
+ {total > 0 && (
+ <span className="ml-2 text-sm font-normal text-muted-foreground">
+ {t("appshot_editor.library_count").replace("{0}", String(total))}
+ </span>
+ )}
+ </p>
+ <p className="mt-0.5 text-sm text-muted-foreground">
+ {enabled === false
+ ? t("appshot_editor.library_off")
+ : t("appshot_editor.library_subtitle")}
+ </p>
+ </div>
+ {total > 0 && (
+ <div className="ml-auto flex shrink-0 items-center gap-2">
+ <div role="tablist" className="flex items-center rounded-lg bg-secondary p-0.5">
+ {(["all", "edited"] as const).map((value) => (
+ <button
+ key={value}
+ type="button"
+ role="tab"
+ aria-selected={filter === value}
+ data-testid={`appshot-library-filter-${value}`}
+ onClick={() => {
+ setFilter(value);
+ setLimit(PAGE);
+ }}
+ className={cn(
+ "h-7 rounded-md px-3 text-sm transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong",
+ filter === value
+ ? "bg-card text-foreground shadow-sm"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ {value === "all"
+ ? t("appshot_editor.library_filter_all")
+ : `${t("appshot_editor.library_filter_edited")} ${editedCount}`}
+ </button>
+ ))}
+ </div>
+ <Button
+ type="button"
+ variant={confirmClear ? "destructive" : "ghost"}
+ size="sm"
+ disabled={clearing}
+ onClick={() => void clearAll()}
+ data-testid="appshot-library-clear"
+ >
+ {clearing ? <Loader2 className="animate-spin" aria-hidden /> : <Trash2 aria-hidden />}
+ {confirmClear
+ ? t("appshot_editor.library_delete_all_confirm")
+ : t("appshot_editor.library_delete_all")}
+ </Button>
+ </div>
+ )}
+ </div>
+
+ {error && (
+ <p className="mt-3 text-sm text-destructive" role="alert">
+ {t("appshot_editor.library_load_failed").replace("{0}", error)}
+ </p>
+ )}
+
+ {items === null || !ready ? (
+ <div className="flex h-32 items-center justify-center" role="status" aria-busy="true">
+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />
+ </div>
+ ) : empty ? (
+ !error && (
+ <p className="mt-4 rounded-lg border border-dashed border-border px-4 py-8 text-center text-sm text-muted-foreground">
+ {filter === "edited"
+ ? t("appshot_editor.library_empty_edited")
+ : t("appshot_editor.library_empty")}
+ </p>
+ )
+ ) : (
+ <>
+ <ul className="mt-4 grid grid-cols-[repeat(auto-fill,minmax(min(100%,12rem),1fr))] gap-3">
+ {shown.slice(0, limit).map((item) => (
+ <Tile
+ key={tileKey(item)}
+ item={item}
+ busy={busyKey === tileKey(item)}
+ onOpen={() => void open(item)}
+ onDelete={() => void remove(item)}
+ />
+ ))}
+ </ul>
+ <div className="mt-3 flex items-center justify-between gap-3">
+ <p className="text-xs text-muted-foreground">{t("appshot_editor.library_drag_hint")}</p>
+ {shown.length > limit && (
+ <Button
+ type="button"
+ variant="secondary"
+ size="sm"
+ onClick={() => setLimit((value) => value + PAGE)}
+ data-testid="appshot-library-more"
+ >
+ {t("appshot_editor.library_show_more")}
+ </Button>
+ )}
+ </div>
+ </>
+ )}
+ </section>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/views/AppshotsView.tsx b/jarvis/ui/web/frontend/src/views/AppshotsView.tsx
index 393c026ed1..d7bd73c121 100644
--- a/jarvis/ui/web/frontend/src/views/AppshotsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/AppshotsView.tsx
@@ -22,6 +22,7 @@ import {
} from "@/lib/appshotApi";
import { gestureFamily } from "@/lib/appshotChord";
import { cn } from "@/lib/utils";
+import { AppshotLibrary } from "@/views/AppshotLibrary";
import { AppshotShortcutField } from "@/views/AppshotShortcutField";
import { useAppshotEditor } from "@/store/appshotEditor";
import { useEventStore } from "@/store/events";
@@ -32,9 +33,10 @@ import { useEventStore } from "@/store/events";
* One page for the whole feature: the master switch (it is also the switch
* for every other screen look, `[screen_context].enabled`), the two global
* shortcuts (front window, and a dragged-out area), where a shortcut appshot
- * goes, the sound and the flash, try-it buttons, and the last appshot so the
- * user sees exactly what was handed over.
- * That picture lives in backend memory for `deck_preview_s` and is fetched
+ * goes, the sound and the flash, try-it buttons, the last appshot so the
+ * user sees exactly what was handed over, and the gallery of every appshot
+ * and edit kept so far (`AppshotLibrary`).
+ * The last picture lives in backend memory for `deck_preview_s` and is fetched
* with `no-store`; this view keeps no copy.
*/
@@ -545,6 +547,21 @@ export function AppshotsView() {
/>
}
/>
+ {typeof settings.library === "boolean" && (
+ <Row
+ label={editorReady ? t("appshot_editor.library_label") : ""}
+ hint={editorReady ? t("appshot_editor.library_hint") : ""}
+ control={
+ <Switch
+ checked={settings.library}
+ disabled={saving}
+ aria-label={editorReady ? t("appshot_editor.library_label") : ""}
+ data-testid="appshots-library"
+ onCheckedChange={(library) => void save({ library })}
+ />
+ }
+ />
+ )}
<Row
label={t("appshots.try_label")}
hint={
@@ -609,6 +626,11 @@ export function AppshotsView() {
</div>
</div>
+ <AppshotLibrary
+ enabled={settings?.library}
+ refreshKey={`${lastAppshotEvent}:${revision}`}
+ />
+
<p className="mt-5 text-sm text-muted-foreground">{t("appshots.voice_hint")}</p>
</div>
</div>
diff --git a/tests/unit/appshot/conftest.py b/tests/unit/appshot/conftest.py
new file mode 100644
index 0000000000..33ee2e6a2b
--- /dev/null
+++ b/tests/unit/appshot/conftest.py
@@ -0,0 +1,14 @@
+"""Every appshot test writes its gallery into a temporary folder, never the real data dir."""
+
+from __future__ import annotations
+
+import pytest
+
+
[email protected](autouse=True)
+def _isolated_library(tmp_path):
+ from jarvis.appshot import library
+
+ library.set_root(tmp_path / "appshot-library")
+ yield
+ library.set_root(None)
diff --git a/tests/unit/appshot/test_appshot_library.py b/tests/unit/appshot/test_appshot_library.py
new file mode 100644
index 0000000000..d7bf1ca770
--- /dev/null
+++ b/tests/unit/appshot/test_appshot_library.py
@@ -0,0 +1,173 @@
+"""The appshot gallery: every appshot and its saved edit, kept on disk."""
+
+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 library
+from jarvis.appshot import service as appshot_service
+from jarvis.appshot.store import Appshot, get_store
+
+
+def _png(width: int = 64, height: int = 48, colour=(20, 120, 200)) -> bytes:
+ buffer = io.BytesIO()
+ Image.new("RGB", (width, height), colour).save(buffer, "PNG")
+ return buffer.getvalue()
+
+
+def _shot(shot_id: str = "a1", *, taken_at: float = 10.0, image: bytes | None = None) -> Appshot:
+ return Appshot(
+ id=shot_id,
+ image=image if image is not None else _png(),
+ mime="image/png",
+ width=64,
+ height=48,
+ label="active window",
+ app_name="Editor",
+ note="APPSHOT: evidence",
+ ui_text="secret on-screen text",
+ trigger="hotkey",
+ taken_at=taken_at,
+ )
+
+
+def test_a_kept_appshot_lists_without_its_screen_text() -> None:
+ assert library.save(_shot())
+
+ [item] = library.list_items()
+ assert (item.id, item.variant, item.width, item.app_name) == ("a1", "original", 64, "Editor")
+ assert item.path.read_bytes() == _shot().image
+ stored = "".join(p.read_text("utf-8") for p in item.path.parent.glob("*.json"))
+ assert "secret on-screen text" not in stored, "the scrubbed UI text never reaches disk"
+
+
+def test_an_edit_sits_right_before_its_original_and_newest_comes_first() -> None:
+ library.save(_shot("old", taken_at=1.0))
+ library.save(_shot("new", taken_at=2.0))
+ edited = _png(32, 24, (250, 0, 0))
+ library.save_edit(_shot("old", image=edited))
+
+ rows = [(i.id, i.variant) for i in library.list_items()]
+ assert rows == [("new", "original"), ("old", "edited"), ("old", "original")]
+ edit = library.get_item("old", "edited")
+ assert edit is not None and edit.path.read_bytes() == edited
+ assert library.get_item("old", "original").has_edit
+
+
+def test_an_edit_of_an_appshot_the_library_never_saw_gets_its_own_entry() -> None:
+ library.save_edit(_shot("lone"))
+ assert [(i.id, i.variant) for i in library.list_items()] == [("lone", "edited")]
+
+
+def test_deleting_an_edit_keeps_the_original_and_deleting_the_original_removes_both() -> None:
+ library.save(_shot())
+ library.save_edit(_shot(image=_png(10, 10)))
+
+ assert library.delete("a1", "edited")
+ assert [(i.variant, i.has_edit) for i in library.list_items()] == [("original", False)]
+ library.save_edit(_shot(image=_png(10, 10)))
+ assert library.delete("a1", "original")
+ assert library.list_items() == []
+
+
+def test_the_library_is_capped_oldest_first(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(library, "MAX_ENTRIES", 3)
+ for n in range(5):
+ library.save(_shot(f"s{n}", taken_at=float(n)))
+ assert [i.id for i in library.list_items()] == ["s4", "s3", "s2"]
+
+
[email protected]("bad", ["", "../x", "a/b", "..", "x" * 65])
+def test_an_id_that_is_a_path_fragment_is_refused(bad: str) -> None:
+ assert not library.valid_id(bad)
+ assert library.get_item(bad, "original") is None
+ assert library.delete(bad, "original") is False
+
+
+def test_a_thumbnail_is_a_small_jpeg_and_is_made_once() -> None:
+ library.save(_shot(image=_png(1600, 900)))
+ item = library.get_item("a1", "original")
+
+ data, mime = library.thumbnail(item)
+ assert mime == "image/jpeg"
+ with Image.open(io.BytesIO(data)) as thumb:
+ assert max(thumb.size) <= library.THUMB_EDGE
+ assert list(item.path.parent.glob("thumb-original-*.jpg"))
+
+
+async def test_take_keeps_the_appshot_only_while_the_library_is_on(monkeypatch) -> None:
+ async def nothing(*_args, **_kwargs):
+ return None
+
+ monkeypatch.setattr(appshot_service, "_attach_to_card", nothing)
+ for switch, expected in ((False, 0), (True, 1)):
+ config = SimpleNamespace(appshot=SimpleNamespace(library=switch))
+ await appshot_service._keep_in_library(_shot(f"t{int(switch)}"), config)
+ assert len(library.list_items()) == expected
+
+
+# -- routes ---------------------------------------------------------------------
+
+
+def client():
+ from jarvis.ui.web.appshot_routes import router
+
+ app = FastAPI()
+ app.include_router(router)
+ app.state.bus = None
+ get_store().clear()
+ yield TestClient(app)
+ get_store().clear()
+
+
+def test_the_gallery_route_lists_and_serves_pictures(client) -> None:
+ library.save(_shot())
+
+ body = client.get("/api/appshot/library").json()
+ assert [i["id"] for i in body["items"]] == ["a1"]
+ full = client.get("/api/appshot/library/a1/image")
+ assert full.status_code == 200 and full.content == _shot().image
+ thumb = client.get("/api/appshot/library/a1/image?thumb=1")
+ assert thumb.headers["content-type"] == "image/jpeg"
+ assert client.get("/api/appshot/library/a1/image?variant=edited").status_code == 404
+
+
+def test_opening_a_kept_picture_holds_it_for_the_editor(client, monkeypatch) -> None:
+ from jarvis.appshot import editor_window
+
+ async def no_window(_shot_id: str) -> bool:
+ return False
+
+ monkeypatch.setattr(editor_window, "open_editor_window", no_window)
+ library.save(_shot())
+
+ response = client.post("/api/appshot/library/a1/open", json={"variant": "original"})
+ assert response.json() == {"id": "a1", "window": False}
+ assert client.get("/api/appshot/latest/image?id=a1").content == _shot().image
+
+
+def test_saving_an_edit_from_the_gallery_keeps_it_beside_the_original(client) -> None:
+ library.save(_shot())
+ edited = _png(20, 10, (0, 200, 0))
+
+ # The hold expired: the edit route holds the kept picture again by itself.
+ response = client.put("/api/appshot/latest/image?id=a1", content=edited)
+ assert response.status_code == 200, response.text
+ assert library.get_item("a1", "edited").path.read_bytes() == edited
+
+
+def test_the_gallery_can_be_deleted(client) -> None:
+ library.save(_shot("a1"))
+ library.save(_shot("a2"))
+
+ assert client.delete("/api/appshot/library/a1").status_code == 200
+ assert client.delete("/api/appshot/library/a1").status_code == 404
+ assert client.delete("/api/appshot/library").json() == {"ok": True, "removed": 1}
+ assert client.get("/api/appshot/library").json()["items"] == []