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): fold the gallery to three rows and delete old captures on request

rubenluetke10-beep220bff733b71
diff --git a/jarvis/appshot/library.py b/jarvis/appshot/library.py
index 92dd57b815..4f38288f0e 100644
--- a/jarvis/appshot/library.py
+++ b/jarvis/appshot/library.py
@@ -427,9 +427,22 @@ def clear() -> int:
return removed
-def _prune() -> None:
- """Keep at most :data:`MAX_ENTRIES` appshots. Caller holds the lock."""
+def prune(keep: int) -> int:
+ """Keep only the newest ``keep`` appshots (``[appshot].keep_newest``).
+
+ ``0`` or anything above :data:`MAX_ENTRIES` keeps the usual cap. Returns
+ how many appshots were deleted.
+ """
+ with _lock:
+ return _prune(keep)
+
+
+def _prune(keep: int = 0) -> int:
+ """Keep at most ``keep`` (else :data:`MAX_ENTRIES`) appshots. Caller holds the lock."""
+ limit = keep if 0 < keep < MAX_ENTRIES else MAX_ENTRIES
root = library_root()
+ if not root.is_dir():
+ return 0
dated: list[tuple[float, Path]] = []
for folder in root.iterdir():
if not folder.is_dir() or not valid_id(folder.name):
@@ -437,11 +450,12 @@ def _prune() -> None:
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
+ if len(dated) <= limit:
+ return 0
dated.sort(key=lambda entry: entry[0])
- for _taken, folder in dated[: len(dated) - MAX_ENTRIES]:
+ for _taken, folder in dated[: len(dated) - limit]:
shutil.rmtree(folder, ignore_errors=True)
+ return len(dated) - limit
__all__ = [
@@ -455,6 +469,7 @@ __all__ = [
"library_root",
"list_items",
"load_shot",
+ "prune",
"save",
"save_edit",
"set_root",
diff --git a/jarvis/appshot/recording.py b/jarvis/appshot/recording.py
index 069a0ee25b..370dacc7ef 100644
--- a/jarvis/appshot/recording.py
+++ b/jarvis/appshot/recording.py
@@ -172,6 +172,8 @@ class RecordingService:
):
self._state.update(phase="error", message="The recorder stopped unexpectedly.")
log.warning("appshot: recorder exited with code %s", code)
+ if self._state["phase"] == "saved":
+ await _trim_old_captures()
except Exception:
log.exception("appshot: recorder monitor failed")
self._state.update(phase="error", message="The recorder connection was lost.")
@@ -215,6 +217,18 @@ class RecordingService:
_service: RecordingService | None = None
+async def _trim_old_captures() -> None:
+ """Apply ``[appshot].keep_newest`` once a recording was saved. Never raises."""
+ try:
+ from jarvis.appshot import retention
+ from jarvis.core.config import load_config
+
+ config = await asyncio.to_thread(load_config)
+ await asyncio.to_thread(retention.apply, retention.keep_newest(config))
+ except Exception: # noqa: BLE001 - the recording is saved; trimming waits for the next one
+ log.warning("appshot: could not trim old captures", exc_info=True)
+
+
def get_recording_service() -> RecordingService:
global _service
if _service is None:
diff --git a/jarvis/appshot/retention.py b/jarvis/appshot/retention.py
new file mode 100644
index 0000000000..2090fe4444
--- /dev/null
+++ b/jarvis/appshot/retention.py
@@ -0,0 +1,84 @@
+"""Delete old captures automatically — ``[appshot].keep_newest``.
+
+The gallery on the Appshots page holds two kinds of capture: screenshots (the
+library, :mod:`jarvis.appshot.library`) and screen recordings
+(:func:`jarvis.appshot.recording.recording_dir`). With ``keep_newest`` set to
+``N > 0`` only the newest ``N`` screenshots AND the newest ``N`` recordings
+stay; older ones are deleted. ``0`` keeps everything (the library's own
+:data:`~jarvis.appshot.library.MAX_ENTRIES` cap still applies to screenshots).
+
+It runs after a new screenshot or recording was kept and right after the
+setting changes. Every function here never raises: a capture that could not
+be deleted stays and goes the next time.
+
+Nothing here is imported at boot (AP-26).
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+log = logging.getLogger(__name__)
+
+
+def keep_newest(config: Any) -> int:
+ """``[appshot].keep_newest`` as a non-negative int; ``0`` = keep everything."""
+ value = getattr(getattr(config, "appshot", None), "keep_newest", 0)
+ try:
+ return max(0, int(value))
+ except (TypeError, ValueError):
+ return 0
+
+
+def prune_recordings(keep: int) -> int:
+ """Delete every finished recording but the newest ``keep``. Returns the count."""
+ if keep <= 0:
+ return 0
+ from jarvis.appshot import recording # noqa: PLC0415
+
+ # Only finished recordings with a valid id: a recording still being
+ # written is a ``.partial`` file, and foreign files in the folder stay.
+ dated = []
+ for path in recording.recording_dir().glob("*.mp4"):
+ if recording.recording_file(path.stem) is None:
+ continue
+ try:
+ dated.append((path.stat().st_mtime, path))
+ except OSError:
+ continue # Gone while listing: nothing left to delete.
+ dated.sort(reverse=True)
+ removed = 0
+ for _mtime, path in dated[keep:]:
+ try:
+ path.unlink()
+ removed += 1
+ except FileNotFoundError:
+ continue # Deleted in the meantime — the goal is reached.
+ except OSError:
+ # Open in a player, for instance; the next trim tries again.
+ log.warning("appshot: could not delete an old recording", exc_info=True)
+ return removed
+
+
+def apply(keep: int) -> int:
+ """Trim screenshots and recordings to the newest ``keep`` each. Never raises."""
+ if keep <= 0:
+ return 0
+ removed = 0
+ try:
+ from jarvis.appshot import library # noqa: PLC0415
+
+ removed += library.prune(keep)
+ except Exception: # noqa: BLE001 - a full gallery is no reason to fail a capture
+ log.warning("appshot: could not trim old screenshots", exc_info=True)
+ try:
+ removed += prune_recordings(keep)
+ except Exception: # noqa: BLE001 - same: the next capture tries again
+ log.warning("appshot: could not trim old recordings", exc_info=True)
+ if removed:
+ log.info("appshot: deleted %d old capture(s), keeping the newest %d", removed, keep)
+ return removed
+
+
+__all__ = ["apply", "keep_newest", "prune_recordings"]
diff --git a/jarvis/appshot/service.py b/jarvis/appshot/service.py
index 7d0cc7846d..77d8733a13 100644
--- a/jarvis/appshot/service.py
+++ b/jarvis/appshot/service.py
@@ -380,9 +380,10 @@ 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
+ from jarvis.appshot import library, retention # noqa: PLC0415
- await asyncio.to_thread(library.save, shot)
+ if await asyncio.to_thread(library.save, shot):
+ await asyncio.to_thread(retention.apply, retention.keep_newest(config))
async def keep_edit_in_library(shot: Appshot) -> None:
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index 72eb6dfb99..b51547cb3d 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -2727,6 +2727,11 @@ class AppshotConfig(BaseModel):
#: and ``jarvis.appshot.library``). Off: nothing new is written there.
library: bool = True
+ #: Delete old captures automatically: only the newest N screenshots and
+ #: the newest N screen recordings stay in the gallery (read by
+ #: ``jarvis.appshot.retention``). ``0`` keeps everything.
+ keep_newest: int = Field(default=0, ge=0, le=500)
+
#: Put every appshot taken by shortcut or button on the system clipboard
#: too, so Ctrl/Cmd+V pastes it into any app right away (read by
#: ``jarvis.appshot.service``). Looks the assistant takes never copy.
@@ -2782,6 +2787,12 @@ class JarvisXConfig(BaseModel):
#: Flash plus the corner thumbnail card after every capture.
effect: bool = True
+ #: Delete old captures automatically: only the newest N screenshots and
+ #: the newest N recordings stay, files included (read by
+ #: ``jarvis.jarvisx.service``). ``0`` keeps everything. Clamped to
+ #: 0..1000 where it is read.
+ keep_newest: int = 0
+
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 e60208c6af..870a016698 100644
--- a/jarvis/core/config_writer.py
+++ b/jarvis/core/config_writer.py
@@ -1000,7 +1000,8 @@ 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", "recording_hotkey", "target", "sound", "effect", "card_seconds", "library",
+ {"keep_newest",
+ "hotkey", "region_hotkey", "recording_hotkey", "target", "sound", "effect", "card_seconds", "library",
"copy_to_clipboard"}
)
@@ -1053,6 +1054,7 @@ JARVISX_SETTING_KEYS: frozenset[str] = frozenset(
"copy_to_clipboard",
"sound",
"effect",
+ "keep_newest",
}
)
diff --git a/jarvis/jarvisx/service.py b/jarvis/jarvisx/service.py
index 4de6f55e0c..f247a58e58 100644
--- a/jarvis/jarvisx/service.py
+++ b/jarvis/jarvisx/service.py
@@ -518,7 +518,18 @@ class JarvisXService:
await self.stop_recording()
# --------------------------------------------------------------- events
+ async def _trim_old(self) -> None:
+ """``[jarvisx].keep_newest``: delete the captures past the newest N."""
+ try:
+ keep = int(getattr((await self._config()).jarvisx, "keep_newest", 0) or 0)
+ if keep > 0:
+ await asyncio.to_thread(self.store.prune, keep)
+ except Exception: # noqa: BLE001 - the new capture is saved; the next one retries
+ log.warning("jarvisx: could not delete old captures", exc_info=True)
+
async def _publish_created(self, item: Item) -> None:
+ # Trim first, so the library the page reloads on this event is final.
+ await self._trim_old()
await self._publish(
_event("JarvisXItemCreated", id=item.id, kind=item.kind, mode=item.mode)
)
diff --git a/jarvis/jarvisx/store.py b/jarvis/jarvisx/store.py
index 4dbe4bcd8a..d0dc97b32f 100644
--- a/jarvis/jarvisx/store.py
+++ b/jarvis/jarvisx/store.py
@@ -167,6 +167,29 @@ class ItemStore:
conn.execute("DELETE FROM items WHERE id = ?", (item_id,))
return item
+ def prune(self, keep: int) -> int:
+ """Keep only the newest ``keep`` screenshots and newest ``keep`` videos.
+
+ ``[jarvisx].keep_newest``: older captures are deleted with their files.
+ ``0`` keeps everything; values are clamped to 0..1000. Returns the count.
+ """
+ keep = max(0, min(int(keep), 1000))
+ if keep == 0:
+ return 0
+ with self._connect() as conn:
+ old = [
+ str(row[0])
+ for kind in ("image", "video")
+ for row in conn.execute(
+ "SELECT id FROM items WHERE kind = ? ORDER BY rowid DESC LIMIT -1 OFFSET ?",
+ (kind, keep),
+ ).fetchall()
+ ]
+ removed = sum(1 for item_id in old if self.delete(item_id) is not None)
+ if removed:
+ log.info("jarvisx: deleted %d old capture(s), keeping the newest %d", removed, keep)
+ return removed
+
# ------------------------------------------------------------------ read
def get(self, item_id: str) -> Item | None:
with self._connect() as conn:
diff --git a/jarvis/ui/web/appshot_routes.py b/jarvis/ui/web/appshot_routes.py
index 64f186d097..77dc0370da 100644
--- a/jarvis/ui/web/appshot_routes.py
+++ b/jarvis/ui/web/appshot_routes.py
@@ -57,6 +57,8 @@ class SettingsPatch(BaseModel):
effect: bool | None = None
card_seconds: int | None = Field(default=None, ge=0, le=600)
library: bool | None = None
+ #: Keep only the newest N screenshots and N recordings; ``0`` keeps all.
+ keep_newest: int | None = Field(default=None, ge=0, le=500)
copy_to_clipboard: bool | None = None
@@ -120,6 +122,7 @@ def _settings_payload() -> dict[str, Any]:
"effect": bool(block.effect),
"card_seconds": int(getattr(block, "card_seconds", 6)),
"library": bool(getattr(block, "library", True)),
+ "keep_newest": int(getattr(block, "keep_newest", 0) or 0),
"copy_to_clipboard": bool(getattr(block, "copy_to_clipboard", True)),
"sound_effects_master": bool(getattr(config.ui, "sound_effects", True)),
"shortcut": _status("window"),
@@ -202,6 +205,10 @@ async def put_settings(request: Request, patch: SettingsPatch) -> dict[str, Any]
key in changes for key in ("hotkey", "region_hotkey", "recording_hotkey")
):
await shortcut.reload()
+ if changes.get("keep_newest"):
+ from jarvis.appshot import retention # noqa: PLC0415
+
+ await asyncio.to_thread(retention.apply, int(changes["keep_newest"]))
return await asyncio.to_thread(_settings_payload)
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 b716f98559..902438fb9e 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
@@ -115,6 +115,11 @@
"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_show_less": "Weniger anzeigen",
+ "keep_label": "Alte Aufnahmen löschen",
+ "keep_hint": "Behält nur die neuesten Screenshots und die neuesten Bildschirmaufnahmen in der Galerie. Ältere werden automatisch gelöscht.",
+ "keep_all": "Nie",
+ "keep_option": "Die neuesten {0} behalten",
"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 c6a6a3e7c6..01e9b0a850 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
@@ -115,6 +115,11 @@
"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_show_less": "Show less",
+ "keep_label": "Delete old captures",
+ "keep_hint": "Keeps only the newest screenshots and the newest screen recordings in the gallery. Older ones are deleted automatically.",
+ "keep_all": "Never",
+ "keep_option": "Keep the newest {0}",
"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 ac145b1382..87eb727ea5 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
@@ -115,6 +115,11 @@
"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_show_less": "Mostrar menos",
+ "keep_label": "Borrar capturas antiguas",
+ "keep_hint": "Conserva en la galería solo las capturas y las grabaciones de pantalla más recientes. Las anteriores se borran automáticamente.",
+ "keep_all": "Nunca",
+ "keep_option": "Conservar las {0} más recientes",
"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 1f4cda4477..5dabbef2ca 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -6681,6 +6681,10 @@
"sound_label": "Auslöser-Geräusch abspielen",
"effect_label": "Animation zeigen",
"effect_hint": "Ein kurzer Blitz, dann fliegt das Vorschaubild in die Ecke.",
+ "keep_label": "Alte Aufnahmen löschen",
+ "keep_hint": "Behält nur die neuesten Screenshots und die neuesten Aufnahmen. Ältere werden automatisch aus dem Speicherordner gelöscht.",
+ "keep_all": "Nie",
+ "keep_option": "Die neuesten {0} behalten",
"recording_unavailable": "Bildschirmaufnahmen sind hier nicht verfügbar: {0}"
}
},
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 9be0b44836..6278dd0ea5 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -6714,6 +6714,10 @@
"sound_label": "Play the shutter sound",
"effect_label": "Show the animation",
"effect_hint": "A short flash, then the thumbnail flies into the corner.",
+ "keep_label": "Delete old captures",
+ "keep_hint": "Keeps only the newest screenshots and the newest recordings. Older ones are deleted from the save folder automatically.",
+ "keep_all": "Never",
+ "keep_option": "Keep the newest {0}",
"recording_unavailable": "Screen recording is not available here: {0}"
}
},
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 50642c6e65..c90933e327 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -6681,6 +6681,10 @@
"sound_label": "Reproducir el sonido del obturador",
"effect_label": "Mostrar la animación",
"effect_hint": "Un destello breve y la miniatura vuela a la esquina.",
+ "keep_label": "Borrar capturas antiguas",
+ "keep_hint": "Conserva solo las capturas y las grabaciones más recientes. Las anteriores se borran automáticamente de la carpeta de guardado.",
+ "keep_all": "Nunca",
+ "keep_option": "Conservar las {0} más recientes",
"recording_unavailable": "La grabación de pantalla no está disponible aquí: {0}"
}
},
diff --git a/jarvis/ui/web/frontend/src/lib/appshotApi.ts b/jarvis/ui/web/frontend/src/lib/appshotApi.ts
index 9219c309ca..28b0c5cfbc 100644
--- a/jarvis/ui/web/frontend/src/lib/appshotApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/appshotApi.ts
@@ -30,6 +30,8 @@ export interface AppshotSettings {
card_seconds: number;
/** Keep every appshot and edit in the gallery. Absent on an older backend. */
library?: boolean;
+ /** Keep only the newest N screenshots and N recordings; 0 = keep all. Absent on an older backend. */
+ keep_newest?: number;
/** Copy shortcut and button appshots to the clipboard. Absent on an older backend. */
copy_to_clipboard?: boolean;
sound_effects_master: boolean;
@@ -60,7 +62,7 @@ export type AppshotSettingsPatch = Partial<
Pick<
AppshotSettings,
"enabled" | "hotkey" | "region_hotkey" | "recording_hotkey" | "target" | "sound" | "effect" | "card_seconds" | "library"
- | "copy_to_clipboard"
+ | "copy_to_clipboard" | "keep_newest"
>
>;
@@ -177,6 +179,9 @@ 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;
+/** Choices for "Delete old captures"; 0 = never. */
+export const KEEP_NEWEST_CHOICES = [0, 10, 20, 50, 100] as const;
+
// -- library: the gallery of every kept appshot and edit ----------------------
export type AppshotLibraryVariant = "original" | "edited";
diff --git a/jarvis/ui/web/frontend/src/lib/jarvisxApi.ts b/jarvis/ui/web/frontend/src/lib/jarvisxApi.ts
index 86eca0a228..c9f6d46d0e 100644
--- a/jarvis/ui/web/frontend/src/lib/jarvisxApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/jarvisxApi.ts
@@ -38,6 +38,8 @@ export interface JarvisXSettings {
copy_to_clipboard: boolean;
sound: boolean;
effect: boolean;
+ /** Keep only the newest N screenshots and N recordings; 0 = keep all. Absent on an older backend. */
+ keep_newest?: number;
recording_available: boolean;
recording_detail: string;
shortcuts: Partial<Record<string, JarvisXShortcutStatus>>;
@@ -53,6 +55,7 @@ export type JarvisXSettingsPatch = Partial<
| "copy_to_clipboard"
| "sound"
| "effect"
+ | "keep_newest"
>
> & { hotkeys?: Partial<Record<JarvisXHotkeyAction, string>> };
diff --git a/jarvis/ui/web/frontend/src/views/AppshotLibrary.test.tsx b/jarvis/ui/web/frontend/src/views/AppshotLibrary.test.tsx
index 683638945d..9f5239278e 100644
--- a/jarvis/ui/web/frontend/src/views/AppshotLibrary.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/AppshotLibrary.test.tsx
@@ -83,6 +83,28 @@ describe("AppshotLibrary", () => {
vi.unstubAllGlobals();
});
+ it("shows three full rows first, then more and less on request", async () => {
+ // Four columns fit: three rows are twelve tiles.
+ const realStyle = window.getComputedStyle.bind(window);
+ vi.spyOn(window, "getComputedStyle").mockImplementation((element, pseudo) => {
+ const style = realStyle(element, pseudo);
+ if (element.tagName !== "UL") return style;
+ return Object.create(style, { gridTemplateColumns: { value: "100px 100px 100px 100px" } });
+ });
+ items = Array.from({ length: 30 }, (_, index) => ({ ...ORIGINAL, id: `p${index}`, has_edit: false }));
+ render(<AppshotLibrary enabled refreshKey="" />);
+ await waitFor(() => expect(screen.getAllByTestId("appshot-library-tile")).toHaveLength(12));
+ expect(screen.queryByTestId("appshot-library-less")).toBeNull();
+
+ fireEvent.click(screen.getByTestId("appshot-library-more"));
+ expect(screen.getAllByTestId("appshot-library-tile")).toHaveLength(30);
+ expect(screen.queryByTestId("appshot-library-more")).toBeNull();
+
+ fireEvent.click(screen.getByTestId("appshot-library-less"));
+ expect(screen.getAllByTestId("appshot-library-tile")).toHaveLength(12);
+ vi.restoreAllMocks();
+ });
+
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));
diff --git a/jarvis/ui/web/frontend/src/views/AppshotLibrary.tsx b/jarvis/ui/web/frontend/src/views/AppshotLibrary.tsx
index 16c0ba4645..aae5bedb88 100644
--- a/jarvis/ui/web/frontend/src/views/AppshotLibrary.tsx
+++ b/jarvis/ui/web/frontend/src/views/AppshotLibrary.tsx
@@ -37,8 +37,30 @@ import { useEventStore } from "@/store/events";
type Filter = "all" | "edited";
-/** Tiles rendered before "Show more"; the grid stays light with 500 kept. */
+/** Rows shown while the gallery is folded; "Show more" opens the rest. */
+const ROWS = 3;
+/** Tiles each further "Show more" adds; the grid stays light with 500 kept. */
const PAGE = 48;
+/** Columns assumed until the grid has been measured (and where it cannot be). */
+const FALLBACK_COLUMNS = 6;
+
+/** How many tiles fit in one row of the auto-filled grid right now. */
+function useGridColumns(grid: HTMLUListElement | null): number {
+ const [columns, setColumns] = useState(FALLBACK_COLUMNS);
+ useEffect(() => {
+ if (!grid) return;
+ const measure = () => {
+ const tracks = getComputedStyle(grid).gridTemplateColumns.split(" ").filter(Boolean).length;
+ if (tracks > 0) setColumns(tracks);
+ };
+ measure();
+ if (typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver(measure);
+ observer.observe(grid);
+ return () => observer.disconnect();
+ }, [grid]);
+ return columns;
+}
const tileKey = (item: AppshotLibraryItem) => `${item.id}:${item.variant}`;
@@ -207,7 +229,11 @@ export function AppshotLibrary({
const [items, setItems] = useState<AppshotLibraryItem[] | null>(null);
const [error, setError] = useState("");
const [filter, setFilter] = useState<Filter>("all");
+ // Folded: exactly ROWS full rows. Unfolded: `limit` tiles, PAGE more per click.
+ const [expanded, setExpanded] = useState(false);
const [limit, setLimit] = useState(PAGE);
+ const [grid, setGrid] = useState<HTMLUListElement | null>(null);
+ const columns = useGridColumns(grid);
const [busyKey, setBusyKey] = useState("");
const [confirmClear, setConfirmClear] = useState(false);
const [clearing, setClearing] = useState(false);
@@ -325,6 +351,8 @@ export function AppshotLibrary({
const total = items?.length ?? 0;
const empty = items !== null && shown.length === 0;
+ const folded = columns * ROWS;
+ const visible = expanded ? Math.max(limit, folded) : folded;
return (
<section
@@ -361,6 +389,7 @@ export function AppshotLibrary({
data-testid={`appshot-library-filter-${value}`}
onClick={() => {
setFilter(value);
+ setExpanded(false);
setLimit(PAGE);
}}
className={cn(
@@ -413,8 +442,8 @@ export function AppshotLibrary({
)
) : (
<>
- <ul className="mt-4 grid grid-cols-[repeat(auto-fill,minmax(min(100%,12rem),1fr))] gap-3">
- {shown.slice(0, limit).map((item) => (
+ <ul ref={setGrid} className="mt-4 grid grid-cols-[repeat(auto-fill,minmax(min(100%,12rem),1fr))] gap-3">
+ {shown.slice(0, visible).map((item) => (
<Tile
key={tileKey(item)}
item={item}
@@ -426,17 +455,40 @@ export function AppshotLibrary({
</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 className="flex shrink-0 items-center gap-2">
+ {expanded && shown.length > folded && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => {
+ setExpanded(false);
+ setLimit(PAGE);
+ grid?.scrollIntoView?.({ block: "nearest" });
+ }}
+ data-testid="appshot-library-less"
+ >
+ {t("appshot_editor.library_show_less")}
+ </Button>
+ )}
+ {shown.length > visible && (
+ <Button
+ type="button"
+ variant="secondary"
+ size="sm"
+ onClick={() => {
+ if (expanded) setLimit((value) => value + PAGE);
+ else {
+ setExpanded(true);
+ setLimit(Math.max(PAGE, folded));
+ }
+ }}
+ data-testid="appshot-library-more"
+ >
+ {t("appshot_editor.library_show_more")}
+ </Button>
+ )}
+ </div>
</div>
</>
)}
diff --git a/jarvis/ui/web/frontend/src/views/AppshotsView.tsx b/jarvis/ui/web/frontend/src/views/AppshotsView.tsx
index 556fdaa580..c7a97af404 100644
--- a/jarvis/ui/web/frontend/src/views/AppshotsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/AppshotsView.tsx
@@ -19,6 +19,7 @@ import {
type AppshotSettings,
type AppshotSettingsPatch,
CARD_SECONDS_CHOICES,
+ KEEP_NEWEST_CHOICES,
openAppshotEditorWindow,
} from "@/lib/appshotApi";
import { gestureFamily } from "@/lib/appshotChord";
@@ -352,6 +353,17 @@ export function AppshotsView() {
// `editorReady` re-labels the options once the chunk has arrived.
[t, editorReady],
);
+ const keepOptions = useMemo<BrandedSelectOption[]>(
+ () =>
+ KEEP_NEWEST_CHOICES.map((count) => ({
+ value: String(count),
+ label:
+ count === 0
+ ? t("appshot_editor.keep_all")
+ : t("appshot_editor.keep_option").replace("{0}", String(count)),
+ })),
+ [t, editorReady],
+ );
const targetOptions = useMemo<BrandedSelectOption[]>(
() => [
{ value: "auto", label: t("appshots.target_auto") },
@@ -563,6 +575,22 @@ export function AppshotsView() {
}
/>
)}
+ {typeof settings.keep_newest === "number" && (
+ <Row
+ label={editorReady ? t("appshot_editor.keep_label") : ""}
+ hint={editorReady ? t("appshot_editor.keep_hint") : ""}
+ control={
+ <BrandedSelect
+ value={String(settings.keep_newest)}
+ options={keepOptions}
+ ariaLabel={editorReady ? t("appshot_editor.keep_label") : ""}
+ disabled={saving}
+ testId="appshots-keep-newest"
+ onValueChange={(value) => void save({ keep_newest: Number(value) })}
+ />
+ }
+ />
+ )}
{typeof settings.copy_to_clipboard === "boolean" && (
<Row
label={editorReady ? t("appshot_editor.clipboard_label") : ""}
diff --git a/jarvis/ui/web/frontend/src/views/jarvisx/JarvisXSettingsPanel.tsx b/jarvis/ui/web/frontend/src/views/jarvisx/JarvisXSettingsPanel.tsx
index 9d43171a84..c8b9f08fb2 100644
--- a/jarvis/ui/web/frontend/src/views/jarvisx/JarvisXSettingsPanel.tsx
+++ b/jarvis/ui/web/frontend/src/views/jarvisx/JarvisXSettingsPanel.tsx
@@ -3,6 +3,7 @@ import { Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
+import { BrandedSelect, type BrandedSelectOption } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import type { KeybindAction, KeybindsConfig, KeybindSaveResult } from "@/hooks/useHotkey";
import { useT } from "@/i18n";
@@ -28,6 +29,9 @@ import { KeybindRow } from "@/views/settings/KeybindRow";
* answer replaces the local copy, so what is on screen is what is stored.
*/
+/** Choices for "Delete old captures"; 0 = never. */
+const KEEP_NEWEST_CHOICES = [0, 10, 20, 50, 100] as const;
+
const HOTKEY_LABEL_KEY: Record<JarvisXHotkeyAction, string> = {
region: "jarvisx.settings.hotkey_region",
window: "jarvisx.settings.hotkey_window",
@@ -109,6 +113,18 @@ export function JarvisXSettingsPanel({
[onSettings, pushToast, settings, t],
);
+ const keepOptions = useMemo<BrandedSelectOption[]>(
+ () =>
+ KEEP_NEWEST_CHOICES.map((count) => ({
+ value: String(count),
+ label:
+ count === 0
+ ? t("jarvisx.settings.keep_all")
+ : t("jarvisx.settings.keep_option").replace("{0}", String(count)),
+ })),
+ [t],
+ );
+
// The recorder's config shape, filled with this feature's shortcuts.
const keybindConfig = useMemo<KeybindsConfig | null>(
() =>
@@ -373,6 +389,22 @@ export function JarvisXSettingsPanel({
/>
}
/>
+ {typeof settings.keep_newest === "number" && (
+ <Row
+ label={t("jarvisx.settings.keep_label")}
+ hint={t("jarvisx.settings.keep_hint")}
+ control={
+ <BrandedSelect
+ value={String(settings.keep_newest)}
+ options={keepOptions}
+ ariaLabel={t("jarvisx.settings.keep_label")}
+ disabled={saving}
+ testId="jarvisx-keep-newest"
+ onValueChange={(value) => void save({ keep_newest: Number(value) })}
+ />
+ }
+ />
+ )}
</Section>
{!settings.recording_available && (
diff --git a/jarvis/ui/web/jarvisx_routes.py b/jarvis/ui/web/jarvisx_routes.py
index a6456ac17f..765b3dce14 100644
--- a/jarvis/ui/web/jarvisx_routes.py
+++ b/jarvis/ui/web/jarvisx_routes.py
@@ -67,6 +67,8 @@ class SettingsPatch(BaseModel):
copy_to_clipboard: bool | None = None
sound: bool | None = None
effect: bool | None = None
+ #: Keep only the newest N screenshots and N videos; ``0`` keeps all.
+ keep_newest: int | None = Field(default=None, ge=0, le=1000)
class CaptureRequest(BaseModel):
@@ -161,6 +163,7 @@ def _settings_payload() -> dict[str, Any]:
"copy_to_clipboard": bool(block.copy_to_clipboard),
"sound": bool(block.sound),
"effect": bool(block.effect),
+ "keep_newest": max(0, min(int(getattr(block, "keep_newest", 0) or 0), 1000)),
"sound_effects_master": bool(getattr(config.ui, "sound_effects", True)),
"recording_available": bool(encoder.available),
"recording_detail": encoder.detail,
@@ -223,6 +226,10 @@ async def put_settings(patch: SettingsPatch) -> dict[str, Any]:
shortcuts = get_shortcuts()
if shortcuts is not None and (hotkey_patch or "enabled" in changes):
await shortcuts.reload()
+ if changes.get("keep_newest"):
+ from jarvis.jarvisx.store import get_store # noqa: PLC0415
+
+ await asyncio.to_thread(get_store().prune, int(changes["keep_newest"]))
return await asyncio.to_thread(_settings_payload)
diff --git a/tests/unit/appshot/test_appshot_retention.py b/tests/unit/appshot/test_appshot_retention.py
new file mode 100644
index 0000000000..118edbb7ac
--- /dev/null
+++ b/tests/unit/appshot/test_appshot_retention.py
@@ -0,0 +1,96 @@
+"""``[appshot].keep_newest``: old screenshots and recordings are deleted automatically."""
+
+from __future__ import annotations
+
+import io
+import os
+from types import SimpleNamespace
+
+import pytest
+from PIL import Image
+
+from jarvis.appshot import library, recording, retention
+from jarvis.appshot.store import Appshot
+from jarvis.core.config import AppshotConfig, JarvisXConfig
+from jarvis.core.config_writer import APPSHOT_SETTING_KEYS, JARVISX_SETTING_KEYS
+
+
+def _png() -> bytes:
+ buffer = io.BytesIO()
+ Image.new("RGB", (8, 6), (20, 120, 200)).save(buffer, "PNG")
+ return buffer.getvalue()
+
+
+def _shot(shot_id: str, taken_at: float) -> Appshot:
+ return Appshot(
+ id=shot_id, image=_png(), mime="image/png", width=8, height=6, label="window",
+ app_name="Editor", note="", ui_text="", trigger="hotkey", taken_at=taken_at,
+ )
+
+
+def recordings(tmp_path, monkeypatch):
+ folder = tmp_path / "recordings"
+ folder.mkdir()
+ monkeypatch.setattr(recording, "recording_dir", lambda: folder)
+ return folder
+
+
+def _recording(folder, index: int) -> str:
+ recording_id = f"{index:032x}"
+ path = folder / f"{recording_id}.mp4"
+ path.write_bytes(b"mp4")
+ os.utime(path, (1000 + index, 1000 + index))
+ return recording_id
+
+
+def test_the_setting_is_off_by_default_and_writable() -> None:
+ assert AppshotConfig().keep_newest == 0
+ assert JarvisXConfig().keep_newest == 0
+ assert "keep_newest" in APPSHOT_SETTING_KEYS
+ assert "keep_newest" in JARVISX_SETTING_KEYS
+
+
+def test_keep_newest_reads_the_config_and_tolerates_junk() -> None:
+ assert retention.keep_newest(SimpleNamespace(appshot=SimpleNamespace(keep_newest=10))) == 10
+ assert retention.keep_newest(SimpleNamespace(appshot=SimpleNamespace(keep_newest="x"))) == 0
+ assert retention.keep_newest(SimpleNamespace()) == 0
+
+
+def test_only_the_newest_screenshots_stay(recordings) -> None:
+ for index in range(5):
+ library.save(_shot(f"s{index}", taken_at=float(index)))
+
+ assert library.prune(2) == 3
+ assert {item.id for item in library.list_items()} == {"s3", "s4"}
+
+
+def test_only_the_newest_recordings_stay_and_foreign_files_are_left(recordings) -> None:
+ ids = [_recording(recordings, index) for index in range(4)]
+ (recordings / "notes.mp4").write_bytes(b"not a recording")
+ (recordings / f"{'f' * 32}.partial").write_bytes(b"still being written")
+
+ assert retention.prune_recordings(1) == 3
+ assert sorted(path.name for path in recordings.iterdir()) == sorted(
+ [f"{ids[-1]}.mp4", "notes.mp4", f"{'f' * 32}.partial"]
+ )
+
+
+def test_zero_keeps_everything(recordings) -> None:
+ for index in range(3):
+ library.save(_shot(f"s{index}", taken_at=float(index)))
+ _recording(recordings, index)
+
+ assert retention.apply(0) == 0
+ assert len(library.list_items()) == 3
+ assert len(list(recordings.glob("*.mp4"))) == 3
+
+
+def test_apply_trims_both_kinds(recordings) -> None:
+ for index in range(3):
+ library.save(_shot(f"s{index}", taken_at=float(index)))
+ _recording(recordings, index)
+
+ assert retention.apply(2) == 2
+ assert len(library.list_items()) == 2
+ assert len(list(recordings.glob("*.mp4"))) == 2
diff --git a/tests/unit/jarvisx/test_service_and_routes.py b/tests/unit/jarvisx/test_service_and_routes.py
index 06c76c67e6..b14a2cd31f 100644
--- a/tests/unit/jarvisx/test_service_and_routes.py
+++ b/tests/unit/jarvisx/test_service_and_routes.py
@@ -303,6 +303,19 @@ def test_settings_contract_and_partial_update(client) -> None:
assert updated["thumbnail_persist"] is True
+def test_keep_newest_trims_the_library_at_once_and_after_each_capture(client) -> None:
+ for _ in range(3):
+ assert client.post("/api/jarvisx/capture", json={"mode": "fullscreen"}).json()["ok"]
+ assert client.get("/api/jarvisx/settings").json()["keep_newest"] == 0
+
+ assert client.put("/api/jarvisx/settings", json={"keep_newest": 2}).json()["keep_newest"] == 2
+ assert len(client.get("/api/jarvisx/items").json()["items"]) == 2
+
+ assert client.post("/api/jarvisx/capture", json={"mode": "fullscreen"}).json()["ok"]
+ assert len(client.get("/api/jarvisx/items").json()["items"]) == 2
+ assert client.put("/api/jarvisx/settings", json={"keep_newest": -1}).status_code == 422
+
+
def test_invalid_or_colliding_hotkeys_are_422(client) -> None:
clash = client.put("/api/jarvisx/settings", json={"hotkeys": {"window": "ctrl+shift+2"}})
assert clash.status_code == 422 and "same keys" in clash.json()["detail"]
diff --git a/tests/unit/jarvisx/test_store_and_recorder.py b/tests/unit/jarvisx/test_store_and_recorder.py
index e4bf902c3d..7007719c64 100644
--- a/tests/unit/jarvisx/test_store_and_recorder.py
+++ b/tests/unit/jarvisx/test_store_and_recorder.py
@@ -181,3 +181,14 @@ def test_an_encoder_failure_ends_the_recording_with_a_reason(tmp_path) -> None:
result = recorder.stop()
assert "disk full" in result.error
assert encoder.closed
+
+
+def test_prune_keeps_the_newest_of_each_kind_and_deletes_their_files(tmp_path) -> None:
+ store = ItemStore(tmp_path / "lib")
+ images = [store.add(_item(tmp_path, f"{index:032x}")) for index in range(3)]
+ videos = [store.add(_item(tmp_path, f"{index + 10:032x}", kind="video")) for index in range(2)]
+
+ assert store.prune(1) == 3
+ assert [item.id for item in store.recent()] == [videos[-1].id, images[-1].id]
+ assert not Path(images[0].path).exists(), "an old capture leaves the save folder too"
+ assert store.prune(0) == 0, "0 keeps everything"