Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

feat(retention): media-only mode keeps search alive while reclaiming disk

Louis Beaumontec610658ab15
diff --git a/apps/screenpipe-app-tauri/components/settings/retention-settings.tsx b/apps/screenpipe-app-tauri/components/settings/retention-settings.tsx
index 7b679a146..81566d28d 100644
--- a/apps/screenpipe-app-tauri/components/settings/retention-settings.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/retention-settings.tsx
@@ -5,7 +5,6 @@
import React, { useEffect, useState, useCallback } from "react";
import { useSettings } from "@/lib/hooks/use-settings";
-import { Switch } from "@/components/ui/switch";
import {
Select,
SelectContent,
@@ -15,7 +14,14 @@ import {
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { useToast } from "@/components/ui/use-toast";
-import { Trash2, Loader2, Play, AlertTriangle, Clock } from "lucide-react";
+import {
+ Trash2,
+ Loader2,
+ Play,
+ AlertTriangle,
+ Clock,
+ Film,
+} from "lucide-react";
import {
AlertDialog,
AlertDialogAction,
@@ -28,9 +34,13 @@ import {
} from "@/components/ui/alert-dialog";
import { localFetch } from "@/lib/api";
+type RetentionMode = "media" | "all";
+type EffectiveMode = "off" | RetentionMode;
+
interface RetentionStatus {
enabled: boolean;
retention_days: number;
+ mode?: RetentionMode;
last_cleanup: string | null;
last_error: string | null;
total_deleted: number;
@@ -44,6 +54,12 @@ const RETENTION_OPTIONS = [
{ value: "90", label: "90 days" },
];
+const RECENT_DELETE_OPTIONS = [
+ { minutes: 15, label: "last 15 min" },
+ { minutes: 30, label: "last 30 min" },
+ { minutes: 60, label: "last hour" },
+];
+
function formatRelativeTime(isoString: string): string {
const date = new Date(isoString);
const now = new Date();
@@ -57,24 +73,33 @@ function formatRelativeTime(isoString: string): string {
return `${diffDays}d ago`;
}
-const RECENT_DELETE_OPTIONS = [
- { minutes: 15, label: "last 15 min" },
- { minutes: 30, label: "last 30 min" },
- { minutes: 60, label: "last hour" },
-];
+function formatBytes(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
+ if (bytes < 1024 * 1024 * 1024)
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
+}
export function RetentionSettings() {
const { settings, updateSettings } = useSettings();
const { toast } = useToast();
const [status, setStatus] = useState<RetentionStatus | null>(null);
- const [toggling, setToggling] = useState(false);
const [running, setRunning] = useState(false);
- const [showConfirm, setShowConfirm] = useState(false);
+ const [pendingMode, setPendingMode] = useState<RetentionMode | null>(null);
+ const [preview, setPreview] = useState<{
+ file_count: number;
+ bytes: number;
+ } | null>(null);
+ const [previewLoading, setPreviewLoading] = useState(false);
const [pendingRecent, setPendingRecent] = useState<number | null>(null);
const [deletingRecent, setDeletingRecent] = useState(false);
const enabled = settings.localRetentionEnabled ?? false;
const retentionDays = settings.localRetentionDays ?? 14;
+ const mode: RetentionMode =
+ (settings.localRetentionMode as RetentionMode | undefined) ?? "media";
+ const effective: EffectiveMode = enabled ? mode : "off";
const fetchStatus = useCallback(async () => {
try {
@@ -93,79 +118,111 @@ export function RetentionSettings() {
return () => clearInterval(interval);
}, [fetchStatus]);
- const handleToggle = async (wantEnabled: boolean) => {
- if (wantEnabled) {
- setShowConfirm(true);
+ // Pull a fresh disk-preview whenever a confirmation opens or retentionDays
+ // changes while pending. Cheap query, no debounce needed at human pace.
+ useEffect(() => {
+ if (pendingMode === null) {
+ setPreview(null);
return;
}
+ let cancelled = false;
+ setPreviewLoading(true);
+ (async () => {
+ try {
+ const res = await localFetch(
+ `/data/storage-preview?older_than_days=${retentionDays}`,
+ );
+ if (!res.ok) throw new Error(`status ${res.status}`);
+ const data = await res.json();
+ if (!cancelled) setPreview(data);
+ } catch {
+ if (!cancelled) setPreview(null);
+ } finally {
+ if (!cancelled) setPreviewLoading(false);
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [pendingMode, retentionDays]);
- setToggling(true);
- try {
- const res = await localFetch("/retention/configure", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ enabled: false }),
- });
+ const applyConfig = async (next: {
+ enabled: boolean;
+ mode?: RetentionMode;
+ retention_days?: number;
+ }) => {
+ const body: Record<string, unknown> = { enabled: next.enabled };
+ if (next.mode !== undefined) body.mode = next.mode;
+ if (next.retention_days !== undefined)
+ body.retention_days = next.retention_days;
+ const res = await localFetch("/retention/configure", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ if (!res.ok) {
+ const err = await res.json().catch(() => ({}));
+ throw new Error(err.error || `request failed (${res.status})`);
+ }
+ };
- if (!res.ok) {
- const err = await res.json();
- throw new Error(err.error || "failed to disable retention");
+ const handleSelectMode = async (next: EffectiveMode) => {
+ if (next === effective) return;
+ if (next === "off") {
+ try {
+ await applyConfig({ enabled: false });
+ await updateSettings({ localRetentionEnabled: false });
+ toast({ title: "auto-delete disabled" });
+ fetchStatus();
+ } catch (e: any) {
+ toast({
+ title: "failed to disable auto-delete",
+ description: e.message,
+ variant: "destructive",
+ });
}
-
- await updateSettings({ localRetentionEnabled: false });
- toast({ title: "auto-delete disabled" });
- fetchStatus();
- } catch (e: any) {
- toast({
- title: "failed to disable auto-delete",
- description: e.message,
- variant: "destructive",
- });
- } finally {
- setToggling(false);
+ return;
}
+ // Enabling or switching mode → confirm
+ setPendingMode(next);
};
const confirmEnable = async () => {
- setShowConfirm(false);
- setToggling(true);
+ if (pendingMode === null) return;
+ const nextMode = pendingMode;
+ setPendingMode(null);
try {
- const res = await localFetch("/retention/configure", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ enabled: true, retention_days: retentionDays }),
+ await applyConfig({
+ enabled: true,
+ mode: nextMode,
+ retention_days: retentionDays,
+ });
+ await updateSettings({
+ localRetentionEnabled: true,
+ localRetentionMode: nextMode,
+ });
+ toast({
+ title:
+ nextMode === "media"
+ ? `media eviction enabled (${retentionDays}d)`
+ : `auto-delete enabled (${retentionDays}d)`,
});
-
- if (!res.ok) {
- const err = await res.json();
- throw new Error(err.error || "failed to enable retention");
- }
-
- await updateSettings({ localRetentionEnabled: true });
- toast({ title: `auto-delete enabled (${retentionDays}d retention)` });
fetchStatus();
} catch (e: any) {
toast({
- title: "failed to enable auto-delete",
+ title: "failed to update retention",
description: e.message,
variant: "destructive",
});
- } finally {
- setToggling(false);
}
};
const handleRetentionChange = async (value: string) => {
const days = parseInt(value, 10);
await updateSettings({ localRetentionDays: days });
-
if (enabled) {
try {
- await localFetch("/retention/configure", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ retention_days: days }),
- });
+ await applyConfig({ enabled: true, retention_days: days });
} catch {
// non-critical
}
@@ -218,15 +275,12 @@ export function RetentionSettings() {
const handleRunNow = async () => {
setRunning(true);
try {
- const res = await localFetch("/retention/run", {
- method: "POST",
- });
+ const res = await localFetch("/retention/run", { method: "POST" });
if (!res.ok) {
const err = await res.json();
throw new Error(err.error || "failed to trigger cleanup");
}
toast({ title: "cleanup triggered" });
- // poll status after a short delay
setTimeout(fetchStatus, 3000);
} catch (e: any) {
toast({
@@ -242,6 +296,7 @@ export function RetentionSettings() {
return (
<>
<div className="space-y-4 pt-4 border-t border-border">
+ {/* Recent-window delete */}
<div className="space-y-2">
<div className="flex items-center gap-2">
<Clock className="h-4 w-4 text-muted-foreground" />
@@ -262,92 +317,108 @@ export function RetentionSettings() {
onClick={() => setPendingRecent(opt.minutes)}
disabled={deletingRecent}
>
- {deletingRecent && pendingRecent === null ? (
- <Loader2 className="h-3 w-3 mr-1.5 animate-spin" />
- ) : null}
{opt.label}
</Button>
))}
</div>
</div>
- <div className="flex items-center justify-between pt-2 border-t border-border/50">
+ {/* Auto-cleanup section */}
+ <div className="space-y-3 pt-3 border-t border-border/50">
<div className="flex items-center gap-2">
<Trash2 className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">auto-delete old data</p>
<p className="text-xs text-muted-foreground">
- permanently delete recordings older than the retention period
+ free disk space without losing your timeline
</p>
</div>
</div>
- <Switch
- checked={enabled}
- onCheckedChange={handleToggle}
- disabled={toggling}
- />
- </div>
- <div className="flex items-center gap-3">
- <span className="text-sm text-muted-foreground">keep data for</span>
- <Select
- value={retentionDays.toString()}
- onValueChange={handleRetentionChange}
- >
- <SelectTrigger className="w-[120px] h-8">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {RETENTION_OPTIONS.map((opt) => (
- <SelectItem key={opt.value} value={opt.value}>
- {opt.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
+ <div className="space-y-2 pl-6">
+ <ModeRow
+ checked={effective === "media"}
+ recommended
+ icon={<Film className="h-4 w-4" />}
+ title="video + audio only"
+ body="reclaims mp4/wav/jpeg files. transcripts, ocr, app history stay searchable. you won't be able to replay clips past the cutoff."
+ onClick={() => handleSelectMode("media")}
+ />
+ <ModeRow
+ checked={effective === "all"}
+ icon={<Trash2 className="h-4 w-4" />}
+ title="everything"
+ body="permanently deletes all data past the cutoff. search won't find anything from that period."
+ onClick={() => handleSelectMode("all")}
+ />
+ <ModeRow
+ checked={effective === "off"}
+ title="off"
+ body="keep everything forever. you'll need to monitor disk usage manually."
+ onClick={() => handleSelectMode("off")}
+ />
+ </div>
- {enabled && (
- <Button
- variant="outline"
- size="sm"
- className="h-8 text-xs"
- onClick={handleRunNow}
- disabled={running}
- >
- {running ? (
- <Loader2 className="h-3 w-3 mr-1.5 animate-spin" />
- ) : (
- <Play className="h-3 w-3 mr-1.5" />
+ {effective !== "off" && (
+ <div className="flex items-center gap-3 pl-6">
+ <span className="text-sm text-muted-foreground">
+ {effective === "media" ? "evict media older than" : "delete data older than"}
+ </span>
+ <Select
+ value={retentionDays.toString()}
+ onValueChange={handleRetentionChange}
+ >
+ <SelectTrigger className="w-[120px] h-8">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {RETENTION_OPTIONS.map((opt) => (
+ <SelectItem key={opt.value} value={opt.value}>
+ {opt.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-8 text-xs"
+ onClick={handleRunNow}
+ disabled={running}
+ >
+ {running ? (
+ <Loader2 className="h-3 w-3 mr-1.5 animate-spin" />
+ ) : (
+ <Play className="h-3 w-3 mr-1.5" />
+ )}
+ clean up now
+ </Button>
+ </div>
+ )}
+
+ {effective !== "off" && status && (
+ <div className="text-xs text-muted-foreground space-y-1 pl-6">
+ {status.last_cleanup && (
+ <p>last cleanup: {formatRelativeTime(status.last_cleanup)}</p>
+ )}
+ {status.total_deleted > 0 && (
+ <p>
+ total {effective === "media" ? "files evicted" : "records deleted"}:{" "}
+ {status.total_deleted.toLocaleString()}
+ </p>
+ )}
+ {status.last_error && (
+ <p className="text-destructive flex items-center gap-1">
+ <AlertTriangle className="h-3 w-3" />
+ {status.last_error}
+ </p>
)}
- clean up now
- </Button>
+ </div>
)}
</div>
-
- {/* Status */}
- {enabled && status && (
- <div className="text-xs text-muted-foreground space-y-1">
- {status.last_cleanup && (
- <p>last cleanup: {formatRelativeTime(status.last_cleanup)}</p>
- )}
- {status.total_deleted > 0 && (
- <p>total records deleted: {status.total_deleted.toLocaleString()}</p>
- )}
- {status.last_error && (
- <p className="text-destructive flex items-center gap-1">
- <AlertTriangle className="h-3 w-3" />
- {status.last_error}
- </p>
- )}
- </div>
- )}
-
- <p className="text-xs text-muted-foreground/70">
- this permanently deletes data from your device. use cloud archive if
- you want to keep a backup.
- </p>
</div>
+ {/* Recent-delete confirmation */}
<AlertDialog
open={pendingRecent !== null}
onOpenChange={(open) => {
@@ -377,20 +448,64 @@ export function RetentionSettings() {
</AlertDialogContent>
</AlertDialog>
- <AlertDialog open={showConfirm} onOpenChange={setShowConfirm}>
+ {/* Mode-change confirmation */}
+ <AlertDialog
+ open={pendingMode !== null}
+ onOpenChange={(open) => {
+ if (!open) setPendingMode(null);
+ }}
+ >
<AlertDialogContent>
<AlertDialogHeader>
- <AlertDialogTitle>enable auto-delete?</AlertDialogTitle>
+ <AlertDialogTitle>
+ {pendingMode === "media"
+ ? "enable media eviction?"
+ : "delete everything past the cutoff?"}
+ </AlertDialogTitle>
<AlertDialogDescription>
- data older than {retentionDays} days will be permanently deleted
- from your device. this includes screen recordings, audio, and
- transcriptions. this cannot be undone.
+ {pendingMode === "media" ? (
+ <>
+ every day, screenpipe will delete video and audio files older
+ than {retentionDays} days. transcripts, ocr text, and your
+ app/window timeline stay searchable.
+ </>
+ ) : (
+ <>
+ every day, screenpipe will permanently delete <em>all</em>{" "}
+ data older than {retentionDays} days — recordings,
+ transcripts, ocr, ui events. search won't find anything past
+ that. this cannot be undone.
+ </>
+ )}
+ <span className="block mt-3 text-xs">
+ {previewLoading ? (
+ <span className="inline-flex items-center gap-1">
+ <Loader2 className="h-3 w-3 animate-spin" />
+ estimating disk space...
+ </span>
+ ) : preview && preview.bytes > 0 ? (
+ <>
+ on your device this would currently free{" "}
+ <strong>{formatBytes(preview.bytes)}</strong> across{" "}
+ {preview.file_count.toLocaleString()} files.
+ </>
+ ) : preview ? (
+ <>nothing past the cutoff right now — first cleanup will run when data ages in.</>
+ ) : null}
+ </span>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>cancel</AlertDialogCancel>
- <AlertDialogAction onClick={confirmEnable}>
- enable auto-delete
+ <AlertDialogAction
+ onClick={confirmEnable}
+ className={
+ pendingMode === "all"
+ ? "bg-destructive text-destructive-foreground hover:bg-destructive/90"
+ : undefined
+ }
+ >
+ {pendingMode === "media" ? "enable eviction" : "enable deletion"}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
@@ -398,3 +513,51 @@ export function RetentionSettings() {
</>
);
}
+
+function ModeRow({
+ checked,
+ title,
+ body,
+ recommended,
+ icon,
+ onClick,
+}: {
+ checked: boolean;
+ title: string;
+ body: string;
+ recommended?: boolean;
+ icon?: React.ReactNode;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className={`w-full text-left flex gap-3 rounded border p-2.5 transition-colors ${
+ checked
+ ? "border-foreground/40 bg-muted/40"
+ : "border-border hover:border-foreground/20 hover:bg-muted/20"
+ }`}
+ >
+ <span
+ className={`mt-0.5 h-3.5 w-3.5 shrink-0 rounded-full border ${
+ checked
+ ? "border-foreground bg-foreground"
+ : "border-muted-foreground"
+ }`}
+ />
+ <div className="flex-1 space-y-0.5">
+ <div className="flex items-center gap-1.5 text-sm font-medium">
+ {icon}
+ <span>{title}</span>
+ {recommended && (
+ <span className="text-[10px] uppercase tracking-wider text-muted-foreground border border-border rounded px-1 py-px ml-1">
+ recommended
+ </span>
+ )}
+ </div>
+ <p className="text-xs text-muted-foreground">{body}</p>
+ </div>
+ </button>
+ );
+}
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
index bb5ff8d9c..508462e39 100644
--- a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
+++ b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
@@ -225,6 +225,9 @@ export type Settings = SettingsStore & {
localRetentionEnabled?: boolean;
/** Days to keep data locally before auto-deleting (default: 14) */
localRetentionDays?: number;
+ /** What gets deleted past the cutoff: "media" keeps DB rows (search/timeline still
+ * work), only reclaims mp4/wav/jpeg files. "all" wipes everything. Default: "media". */
+ localRetentionMode?: "media" | "all";
/** Apply macOS vibrancy effect to sidebar for a translucent glass look */
translucentSidebar?: boolean;
/** Notification preferences — which notification sources are enabled */
@@ -457,6 +460,7 @@ let DEFAULT_SETTINGS: Settings = {
appendTypedTextToMeetingNotes: true,
localRetentionEnabled: true,
localRetentionDays: 14,
+ localRetentionMode: "media",
};
export function createDefaultSettingsObject(): Settings {
diff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rs
index 3eda42a30..78a334989 100644
--- a/crates/screenpipe-db/src/db.rs
+++ b/crates/screenpipe-db/src/db.rs
@@ -59,6 +59,17 @@ pub struct DeleteTimeRangeResult {
pub snapshot_files: Vec<String>,
}
+/// Outcome of `evict_media_in_range`. DB rows stay alive (search/timeline
+/// keep working); only mp4/wav/jpeg files are reclaimed.
+pub struct EvictMediaResult {
+ pub video_chunks_evicted: u64,
+ pub audio_chunks_evicted: u64,
+ pub snapshots_evicted: u64,
+ pub video_files: Vec<String>,
+ pub audio_files: Vec<String>,
+ pub snapshot_files: Vec<String>,
+}
+
/// A transaction wrapper that uses `BEGIN IMMEDIATE` to acquire the write lock upfront,
/// preventing WAL deadlocks. Automatically rolls back on drop if not committed.
///
@@ -4983,6 +4994,189 @@ impl DatabaseManager {
})
}
+ /// Media-only eviction: keeps DB rows (frames, ocr_text, transcriptions,
+ /// ui_events) intact so search/timeline keep working, but reclaims the
+ /// heavy mp4/wav/jpeg files on disk. A chunk is only evicted if every
+ /// frame/transcription it owns falls inside [start, end] — straddling
+ /// chunks are left alone so unrelated playback isn't broken.
+ ///
+ /// Marks evicted chunks with `evicted_at = CURRENT_TIMESTAMP` and clears
+ /// `file_path` to '' so loaders can early-out without dereferencing a
+ /// stale path. Caller is responsible for unlinking the returned files.
+ pub async fn evict_media_in_range(
+ &self,
+ start: DateTime<Utc>,
+ end: DateTime<Utc>,
+ ) -> Result<EvictMediaResult, sqlx::Error> {
+ let mut tx = self.begin_immediate_with_retry().await?;
+
+ let start_str = start.to_rfc3339();
+ let end_str = end.to_rfc3339();
+
+ // Collect video chunks fully covered by the range and not already
+ // evicted. We only consider chunks whose ALL frames fall inside the
+ // window — straddling chunks are skipped so old playback still works.
+ let video_files: Vec<String> = sqlx::query_scalar(
+ r#"SELECT file_path FROM video_chunks
+ WHERE evicted_at IS NULL
+ AND file_path != ''
+ AND file_path NOT LIKE 'cloud://%'
+ AND id IN (SELECT DISTINCT video_chunk_id FROM frames WHERE timestamp BETWEEN ?1 AND ?2)
+ AND id NOT IN (SELECT DISTINCT video_chunk_id FROM frames WHERE timestamp NOT BETWEEN ?1 AND ?2)"#,
+ )
+ .bind(&start_str)
+ .bind(&end_str)
+ .fetch_all(&mut **tx.conn())
+ .await?;
+
+ let audio_files: Vec<String> = sqlx::query_scalar(
+ r#"SELECT file_path FROM audio_chunks
+ WHERE evicted_at IS NULL
+ AND file_path != ''
+ AND file_path NOT LIKE 'cloud://%'
+ AND id IN (SELECT DISTINCT audio_chunk_id FROM audio_transcriptions WHERE timestamp BETWEEN ?1 AND ?2)
+ AND id NOT IN (SELECT DISTINCT audio_chunk_id FROM audio_transcriptions WHERE timestamp NOT BETWEEN ?1 AND ?2)"#,
+ )
+ .bind(&start_str)
+ .bind(&end_str)
+ .fetch_all(&mut **tx.conn())
+ .await?;
+
+ // Snapshot JPEGs are per-frame, not chunked, so we can evict them
+ // unconditionally for any frame inside the range.
+ let snapshot_files: Vec<String> = sqlx::query_scalar(
+ r#"SELECT snapshot_path FROM frames
+ WHERE timestamp BETWEEN ?1 AND ?2
+ AND snapshot_path IS NOT NULL"#,
+ )
+ .bind(&start_str)
+ .bind(&end_str)
+ .fetch_all(&mut **tx.conn())
+ .await?;
+
+ // Mark video_chunks as evicted (file_path -> '', evicted_at -> now)
+ let video_evict = sqlx::query(
+ r#"UPDATE video_chunks
+ SET file_path = '', evicted_at = CURRENT_TIMESTAMP
+ WHERE evicted_at IS NULL
+ AND file_path != ''
+ AND file_path NOT LIKE 'cloud://%'
+ AND id IN (SELECT DISTINCT video_chunk_id FROM frames WHERE timestamp BETWEEN ?1 AND ?2)
+ AND id NOT IN (SELECT DISTINCT video_chunk_id FROM frames WHERE timestamp NOT BETWEEN ?1 AND ?2)"#,
+ )
+ .bind(&start_str)
+ .bind(&end_str)
+ .execute(&mut **tx.conn())
+ .await?;
+
+ let audio_evict = sqlx::query(
+ r#"UPDATE audio_chunks
+ SET file_path = '', evicted_at = CURRENT_TIMESTAMP
+ WHERE evicted_at IS NULL
+ AND file_path != ''
+ AND file_path NOT LIKE 'cloud://%'
+ AND id IN (SELECT DISTINCT audio_chunk_id FROM audio_transcriptions WHERE timestamp BETWEEN ?1 AND ?2)
+ AND id NOT IN (SELECT DISTINCT audio_chunk_id FROM audio_transcriptions WHERE timestamp NOT BETWEEN ?1 AND ?2)"#,
+ )
+ .bind(&start_str)
+ .bind(&end_str)
+ .execute(&mut **tx.conn())
+ .await?;
+
+ let snapshot_evict = sqlx::query(
+ r#"UPDATE frames
+ SET snapshot_path = NULL
+ WHERE timestamp BETWEEN ?1 AND ?2
+ AND snapshot_path IS NOT NULL"#,
+ )
+ .bind(&start_str)
+ .bind(&end_str)
+ .execute(&mut **tx.conn())
+ .await?;
+
+ tx.commit().await.map_err(|e| {
+ error!("failed to commit evict_media_in_range transaction: {}", e);
+ e
+ })?;
+
+ debug!(
+ "evict_media_in_range committed: video_chunks={}, audio_chunks={}, snapshots={}",
+ video_evict.rows_affected(),
+ audio_evict.rows_affected(),
+ snapshot_evict.rows_affected(),
+ );
+
+ Ok(EvictMediaResult {
+ video_chunks_evicted: video_evict.rows_affected(),
+ audio_chunks_evicted: audio_evict.rows_affected(),
+ snapshots_evicted: snapshot_evict.rows_affected(),
+ video_files,
+ audio_files,
+ snapshot_files,
+ })
+ }
+
+ /// Estimate disk reclaimable by `evict_media_in_range` for [start, end].
+ /// Returns (file count, total bytes). Reads file sizes from disk via
+ /// `tokio::fs::metadata`, so cost is O(N) syscalls — keep ranges
+ /// reasonable (the UI calls this for retention preview, not per-second).
+ pub async fn estimate_evictable_bytes(
+ &self,
+ start: DateTime<Utc>,
+ end: DateTime<Utc>,
+ ) -> Result<(u64, u64), sqlx::Error> {
+ let start_str = start.to_rfc3339();
+ let end_str = end.to_rfc3339();
+
+ let mut paths: Vec<String> = sqlx::query_scalar(
+ r#"SELECT file_path FROM video_chunks
+ WHERE evicted_at IS NULL
+ AND file_path != ''
+ AND file_path NOT LIKE 'cloud://%'
+ AND id IN (SELECT DISTINCT video_chunk_id FROM frames WHERE timestamp BETWEEN ?1 AND ?2)
+ AND id NOT IN (SELECT DISTINCT video_chunk_id FROM frames WHERE timestamp NOT BETWEEN ?1 AND ?2)"#,
+ )
+ .bind(&start_str)
+ .bind(&end_str)
+ .fetch_all(&self.pool)
+ .await?;
+
+ let audio: Vec<String> = sqlx::query_scalar(
+ r#"SELECT file_path FROM audio_chunks
+ WHERE evicted_at IS NULL
+ AND file_path != ''
+ AND file_path NOT LIKE 'cloud://%'
+ AND id IN (SELECT DISTINCT audio_chunk_id FROM audio_transcriptions WHERE timestamp BETWEEN ?1 AND ?2)
+ AND id NOT IN (SELECT DISTINCT audio_chunk_id FROM audio_transcriptions WHERE timestamp NOT BETWEEN ?1 AND ?2)"#,
+ )
+ .bind(&start_str)
+ .bind(&end_str)
+ .fetch_all(&self.pool)
+ .await?;
+ paths.extend(audio);
+
+ let snapshots: Vec<String> = sqlx::query_scalar(
+ r#"SELECT snapshot_path FROM frames
+ WHERE timestamp BETWEEN ?1 AND ?2
+ AND snapshot_path IS NOT NULL"#,
+ )
+ .bind(&start_str)
+ .bind(&end_str)
+ .fetch_all(&self.pool)
+ .await?;
+ paths.extend(snapshots);
+
+ let mut bytes: u64 = 0;
+ let mut count: u64 = 0;
+ for p in &paths {
+ if let Ok(meta) = tokio::fs::metadata(p).await {
+ bytes = bytes.saturating_add(meta.len());
+ count += 1;
+ }
+ }
+ Ok((count, bytes))
+ }
+
/// Fast batch delete: only deletes time-range-bounded rows (ocr_text,
/// elements, frames, audio_transcriptions, ui_events). Skips the expensive
/// orphan cleanup (video_chunks, audio_chunks) which requires full-table
diff --git a/crates/screenpipe-db/src/migrations/20260429000000_add_evicted_at_to_chunks.sql b/crates/screenpipe-db/src/migrations/20260429000000_add_evicted_at_to_chunks.sql
new file mode 100644
index 000000000..d830491cb
--- /dev/null
+++ b/crates/screenpipe-db/src/migrations/20260429000000_add_evicted_at_to_chunks.sql
@@ -0,0 +1,9 @@
+-- Media-only retention: track when a chunk's mp4/wav was evicted from disk
+-- while keeping its DB row (frames, ocr_text, transcriptions) intact for
+-- search and timeline. NULL means the file is still on disk.
+--
+-- file_path stays NOT NULL — eviction sets it to '' (empty string) so
+-- loaders can early-out without dereferencing a stale path.
+
+ALTER TABLE video_chunks ADD COLUMN evicted_at TIMESTAMP DEFAULT NULL;
+ALTER TABLE audio_chunks ADD COLUMN evicted_at TIMESTAMP DEFAULT NULL;
diff --git a/crates/screenpipe-engine/src/retention.rs b/crates/screenpipe-engine/src/retention.rs
index a246c71ac..6a2b0f29e 100644
--- a/crates/screenpipe-engine/src/retention.rs
+++ b/crates/screenpipe-engine/src/retention.rs
@@ -52,10 +52,28 @@ struct RetentionRuntime {
run_now: Arc<tokio::sync::Notify>,
}
+/// What old data gets cleaned up. `Media` (default) keeps DB rows (search,
+/// timeline, transcripts) and only reclaims mp4/wav/jpeg files; `All` is the
+/// legacy behavior that wipes everything past the cutoff.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, OaSchema)]
+#[serde(rename_all = "lowercase")]
+pub enum RetentionMode {
+ Media,
+ All,
+}
+
+impl Default for RetentionMode {
+ fn default() -> Self {
+ Self::Media
+ }
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetentionConfig {
pub enabled: bool,
pub retention_days: u32,
+ #[serde(default)]
+ pub mode: RetentionMode,
}
impl Default for RetentionConfig {
@@ -63,6 +81,7 @@ impl Default for RetentionConfig {
Self {
enabled: false,
retention_days: 14,
+ mode: RetentionMode::Media,
}
}
}
@@ -75,12 +94,15 @@ impl Default for RetentionConfig {
pub struct RetentionConfigureRequest {
pub enabled: Option<bool>,
pub retention_days: Option<u32>,
+ /// "media" (default) or "all". Omit to leave unchanged.
+ pub mode: Option<RetentionMode>,
}
#[derive(Debug, Serialize, OaSchema)]
pub struct RetentionStatusResponse {
pub enabled: bool,
pub retention_days: u32,
+ pub mode: RetentionMode,
pub last_cleanup: Option<String>,
pub last_error: Option<String>,
pub total_deleted: u64,
@@ -116,6 +138,9 @@ pub async fn retention_configure(
if let Some(days) = request.retention_days {
runtime.config.retention_days = days;
}
+ if let Some(mode) = request.mode {
+ runtime.config.mode = mode;
+ }
if !wants_enabled && runtime.config.enabled {
// Disable: abort background task
@@ -134,8 +159,8 @@ pub async fn retention_configure(
run_now,
);
info!(
- "retention: re-enabled with {}d",
- runtime.config.retention_days
+ "retention: re-enabled with {}d ({:?})",
+ runtime.config.retention_days, runtime.config.mode
);
}
@@ -143,6 +168,7 @@ pub async fn retention_configure(
"success": true,
"enabled": runtime.config.enabled,
"retention_days": runtime.config.retention_days,
+ "mode": runtime.config.mode,
})))
}
None => {
@@ -151,6 +177,7 @@ pub async fn retention_configure(
"success": true,
"enabled": false,
"retention_days": retention_days,
+ "mode": request.mode.unwrap_or_default(),
})));
}
@@ -158,6 +185,7 @@ pub async fn retention_configure(
let config = RetentionConfig {
enabled: true,
retention_days,
+ mode: request.mode.unwrap_or_default(),
};
let run_now = Arc::new(tokio::sync::Notify::new());
@@ -186,6 +214,7 @@ pub async fn retention_configure(
"success": true,
"enabled": true,
"retention_days": retention_days,
+ "mode": request.mode.unwrap_or_default(),
})))
}
}
@@ -202,6 +231,7 @@ pub async fn retention_status(
None => Ok(JsonResponse(RetentionStatusResponse {
enabled: false,
retention_days: 14,
+ mode: RetentionMode::Media,
last_cleanup: None,
last_error: None,
total_deleted: 0,
@@ -209,6 +239,7 @@ pub async fn retention_status(
Some(runtime) => Ok(JsonResponse(RetentionStatusResponse {
enabled: runtime.config.enabled,
retention_days: runtime.config.retention_days,
+ mode: runtime.config.mode,
last_cleanup: runtime.last_cleanup.map(|t| t.to_rfc3339()),
last_error: runtime.last_error.clone(),
total_deleted: runtime.total_deleted,
@@ -268,10 +299,10 @@ fn spawn_retention_loop(
}
}
- let retention_days = {
+ let (retention_days, mode) = {
let guard = state.read().await;
match guard.as_ref() {
- Some(rt) if rt.config.enabled => rt.config.retention_days,
+ Some(rt) if rt.config.enabled => (rt.config.retention_days, rt.config.mode),
_ => continue,
}
};
@@ -279,12 +310,13 @@ fn spawn_retention_loop(
let cutoff = Utc::now() - Duration::days(retention_days as i64);
info!(
- "retention: cleaning up data before {} ({}d retention)",
+ "retention: cleaning up data before {} ({}d retention, mode={:?})",
cutoff.to_rfc3339(),
- retention_days
+ retention_days,
+ mode
);
- match do_local_cleanup(&db, cutoff).await {
+ match do_local_cleanup(&db, cutoff, mode).await {
Ok(deleted) => {
if deleted > 0 {
info!("retention: deleted {} records", deleted);
@@ -308,10 +340,11 @@ fn spawn_retention_loop(
})
}
-async fn do_local_cleanup(db: &Arc<DatabaseManager>, cutoff: DateTime<Utc>) -> anyhow::Result<u64> {
- // Delete in 1-hour batches. Each batch only deletes time-bounded rows
- // (fast, uses indexed timestamp). The expensive orphan cleanup (full-table
- // NOT IN scans on video_chunks/audio_chunks) runs once at the end.
+async fn do_local_cleanup(
+ db: &Arc<DatabaseManager>,
+ cutoff: DateTime<Utc>,
+ mode: RetentionMode,
+) -> anyhow::Result<u64> {
let batch_size = Duration::hours(1);
let mut total: u64 = 0;
@@ -330,50 +363,94 @@ async fn do_local_cleanup(db: &Arc<DatabaseManager>, cutoff: DateTime<Utc>) -> a
while batch_start < cutoff {
let batch_end = (batch_start + batch_size).min(cutoff);
- match db
- .delete_time_range_batch(batch_start, batch_end, true)
- .await
- {
- Ok(result) => {
- let batch_total = result.frames_deleted
- + result.ocr_deleted
- + result.audio_transcriptions_deleted
- + result.ui_events_deleted;
-
- if batch_total > 0 {
- any_deleted = true;
- info!(
- "retention: batch deleted frames={} ocr={} audio={} ui_events={} \
- (video_files={} snapshot_files={} audio_files={})",
- result.frames_deleted,
- result.ocr_deleted,
- result.audio_transcriptions_deleted,
- result.ui_events_deleted,
- result.video_files.len(),
- result.snapshot_files.len(),
- result.audio_files.len(),
- );
- }
-
- total += batch_total;
-
- for path in result
- .video_files
- .iter()
- .chain(result.audio_files.iter())
- .chain(result.snapshot_files.iter())
+ match mode {
+ RetentionMode::All => {
+ match db
+ .delete_time_range_batch(batch_start, batch_end, true)
+ .await
{
- if let Err(e) = tokio::fs::remove_file(path).await {
- warn!("retention: failed to delete file {}: {}", path, e);
+ Ok(result) => {
+ let batch_total = result.frames_deleted
+ + result.ocr_deleted
+ + result.audio_transcriptions_deleted
+ + result.ui_events_deleted;
+
+ if batch_total > 0 {
+ any_deleted = true;
+ info!(
+ "retention: batch deleted frames={} ocr={} audio={} ui_events={} \
+ (video_files={} snapshot_files={} audio_files={})",
+ result.frames_deleted,
+ result.ocr_deleted,
+ result.audio_transcriptions_deleted,
+ result.ui_events_deleted,
+ result.video_files.len(),
+ result.snapshot_files.len(),
+ result.audio_files.len(),
+ );
+ }
+
+ total += batch_total;
+
+ for path in result
+ .video_files
+ .iter()
+ .chain(result.audio_files.iter())
+ .chain(result.snapshot_files.iter())
+ {
+ if let Err(e) = tokio::fs::remove_file(path).await {
+ warn!("retention: failed to delete file {}: {}", path, e);
+ }
+ }
+ }
+ Err(e) => {
+ warn!(
+ "retention: batch delete failed for range {} to {}: {}",
+ batch_start, batch_end, e
+ );
}
}
}
- Err(e) => {
- warn!(
- "retention: batch delete failed for range {} to {}: {}",
- batch_start, batch_end, e
- );
- }
+ RetentionMode::Media => match db.evict_media_in_range(batch_start, batch_end).await {
+ Ok(result) => {
+ let batch_total = result.video_chunks_evicted
+ + result.audio_chunks_evicted
+ + result.snapshots_evicted;
+
+ if batch_total > 0 {
+ any_deleted = true;
+ info!(
+ "retention: batch evicted video_chunks={} audio_chunks={} snapshots={} \
+ (files: video={} audio={} snapshots={})",
+ result.video_chunks_evicted,
+ result.audio_chunks_evicted,
+ result.snapshots_evicted,
+ result.video_files.len(),
+ result.audio_files.len(),
+ result.snapshot_files.len(),
+ );
+ }
+
+ total += batch_total;
+
+ for path in result
+ .video_files
+ .iter()
+ .chain(result.audio_files.iter())
+ .chain(result.snapshot_files.iter())
+ {
+ if let Err(e) = tokio::fs::remove_file(path).await {
+ warn!("retention: failed to evict file {}: {}", path, e);
+ }
+ }
+ }
+ Err(e) => {
+ warn!(
+ "retention: batch evict failed for range {} to {}: {}",
+ batch_start, batch_end, e
+ );
+ }
+ },
}
batch_start = batch_end;
@@ -382,12 +459,10 @@ async fn do_local_cleanup(db: &Arc<DatabaseManager>, cutoff: DateTime<Utc>) -> a
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
}
- // One-time orphan cleanup after all batches
- if any_deleted {
+ if any_deleted && matches!(mode, RetentionMode::All) {
if let Err(e) = db.cleanup_orphaned_chunks().await {
warn!("retention: orphan chunk cleanup failed: {}", e);
}
- // Reclaim disk space — without VACUUM, SQLite keeps deleted pages
info!("retention: running incremental vacuum to reclaim disk space");
if let Err(e) = db.execute_raw_sql("PRAGMA incremental_vacuum(1000)").await {
warn!("retention: incremental vacuum failed: {}", e);
diff --git a/crates/screenpipe-engine/src/routes/data.rs b/crates/screenpipe-engine/src/routes/data.rs
index b3097d6ce..e0b7771d2 100644
--- a/crates/screenpipe-engine/src/routes/data.rs
+++ b/crates/screenpipe-engine/src/routes/data.rs
@@ -106,6 +106,189 @@ pub(crate) async fn delete_time_range_handler(
}))
}
+#[derive(Deserialize, OaSchema)]
+pub struct EvictMediaRequest {
+ #[serde(deserialize_with = "super::time::deserialize_flexible_datetime")]
+ pub start: DateTime<Utc>,
+ #[serde(deserialize_with = "super::time::deserialize_flexible_datetime")]
+ pub end: DateTime<Utc>,
+}
+
+#[derive(Serialize, OaSchema)]
+pub struct EvictMediaResponse {
+ pub video_chunks_evicted: u64,
+ pub audio_chunks_evicted: u64,
+ pub snapshots_evicted: u64,
+ pub video_files_deleted: u64,
+ pub audio_files_deleted: u64,
+ pub snapshot_files_deleted: u64,
+ pub bytes_freed: u64,
+}
+
+/// POST /data/evict-media — reclaim mp4/wav/jpeg files in a time range
+/// while keeping DB rows intact. Search and timeline still work; playback
+/// for that period shows a "media evicted" placeholder.
+#[oasgen]
+pub(crate) async fn evict_media_handler(
+ State(state): State<Arc<AppState>>,
+ Json(payload): Json<EvictMediaRequest>,
+) -> Result<JsonResponse<EvictMediaResponse>, (StatusCode, JsonResponse<Value>)> {
+ if payload.start >= payload.end {
+ return Err((
+ StatusCode::BAD_REQUEST,
+ JsonResponse(json!({"error": "start must be before end"})),
+ ));
+ }
+
+ let result = state
+ .db
+ .evict_media_in_range(payload.start, payload.end)
+ .await
+ .map_err(|e| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({"error": format!("failed to evict media: {}", e)})),
+ )
+ })?;
+
+ let mut bytes_freed: u64 = 0;
+ let mut video_files_deleted: u64 = 0;
+ for path in &result.video_files {
+ match std::fs::metadata(path) {
+ Ok(meta) => {
+ let size = meta.len();
+ match std::fs::remove_file(path) {
+ Ok(_) => {
+ video_files_deleted += 1;
+ bytes_freed = bytes_freed.saturating_add(size);
+ }
+ Err(e) => warn!("failed to evict video file {}: {}", path, e),
+ }
+ }
+ Err(_) => {
+ let _ = std::fs::remove_file(path);
+ }
+ }
+ }
+
+ let mut audio_files_deleted: u64 = 0;
+ for path in &result.audio_files {
+ match std::fs::metadata(path) {
+ Ok(meta) => {
+ let size = meta.len();
+ match std::fs::remove_file(path) {
+ Ok(_) => {
+ audio_files_deleted += 1;
+ bytes_freed = bytes_freed.saturating_add(size);
+ }
+ Err(e) => warn!("failed to evict audio file {}: {}", path, e),
+ }
+ }
+ Err(_) => {
+ let _ = std::fs::remove_file(path);
+ }
+ }
+ }
+
+ let mut snapshot_files_deleted: u64 = 0;
+ for path in &result.snapshot_files {
+ match std::fs::metadata(path) {
+ Ok(meta) => {
+ let size = meta.len();
+ if std::fs::remove_file(path).is_ok() {
+ snapshot_files_deleted += 1;
+ bytes_freed = bytes_freed.saturating_add(size);
+ }
+ }
+ Err(_) => {
+ let _ = std::fs::remove_file(path);
+ }
+ }
+ }
+
+ Ok(JsonResponse(EvictMediaResponse {
+ video_chunks_evicted: result.video_chunks_evicted,
+ audio_chunks_evicted: result.audio_chunks_evicted,
+ snapshots_evicted: result.snapshots_evicted,
+ video_files_deleted,
+ audio_files_deleted,
+ snapshot_files_deleted,
+ bytes_freed,
+ }))
+}
+
+#[derive(Deserialize, OaSchema)]
+pub struct StoragePreviewQuery {
+ /// Either pass `older_than_days` (preview retention cleanup) or both
+ /// `start` and `end` (preview an arbitrary range).
+ pub older_than_days: Option<u32>,
+ #[serde(
+ default,
+ deserialize_with = "super::time::deserialize_flexible_datetime_option"
+ )]
+ pub start: Option<DateTime<Utc>>,
+ #[serde(
+ default,
+ deserialize_with = "super::time::deserialize_flexible_datetime_option"
+ )]
+ pub end: Option<DateTime<Utc>>,
+}
+
+#[derive(Serialize, OaSchema)]
+pub struct StoragePreviewResponse {
+ pub file_count: u64,
+ pub bytes: u64,
+}
+
+/// GET /data/storage-preview — estimate disk reclaimable by media eviction
+/// for the given window. Used by the retention confirmation dialog.
+#[oasgen]
+pub(crate) async fn storage_preview_handler(
+ State(state): State<Arc<AppState>>,
+ Query(query): Query<StoragePreviewQuery>,
+) -> Result<JsonResponse<StoragePreviewResponse>, (StatusCode, JsonResponse<Value>)> {
+ let (start, end) = if let Some(days) = query.older_than_days {
+ let end = Utc::now() - chrono::Duration::days(days as i64);
+ // Earliest representable timestamp; `evict_media_in_range` filters by
+ // actual data so the wide bound is fine.
+ let start = DateTime::<Utc>::from_timestamp(0, 0).unwrap_or_else(Utc::now);
+ (start, end)
+ } else {
+ match (query.start, query.end) {
+ (Some(s), Some(e)) => (s, e),
+ _ => {
+ return Err((
+ StatusCode::BAD_REQUEST,
+ JsonResponse(
+ json!({"error": "provide older_than_days or both start and end"}),
+ ),
+ ))
+ }
+ }
+ };
+
+ if start >= end {
+ return Err((
+ StatusCode::BAD_REQUEST,
+ JsonResponse(json!({"error": "start must be before end"})),
+ ));
+ }
+
+ let (file_count, bytes) =
+ state
+ .db
+ .estimate_evictable_bytes(start, end)
+ .await
+ .map_err(|e| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({"error": format!("failed to estimate: {}", e)})),
+ )
+ })?;
+
+ Ok(JsonResponse(StoragePreviewResponse { file_count, bytes }))
+}
+
#[derive(Serialize, OaSchema)]
pub struct DeviceStorageEntry {
pub machine_id: String,
diff --git a/crates/screenpipe-engine/src/server.rs b/crates/screenpipe-engine/src/server.rs
index f58039f7d..cbf4aa799 100644
--- a/crates/screenpipe-engine/src/server.rs
+++ b/crates/screenpipe-engine/src/server.rs
@@ -27,7 +27,8 @@ use crate::{
},
data::{
backup_handler, checkpoint_handler, delete_device_data_handler,
- delete_time_range_handler, device_storage_handler,
+ delete_time_range_handler, device_storage_handler, evict_media_handler,
+ storage_preview_handler,
},
elements::{get_frame_elements, search_elements},
frames::{
@@ -625,6 +626,8 @@ impl SCServer {
.post("/retention/run", crate::retention::retention_run)
// Data management
.post("/data/delete-range", delete_time_range_handler)
+ .post("/data/evict-media", evict_media_handler)
+ .get("/data/storage-preview", storage_preview_handler)
.post("/data/delete-device", delete_device_data_handler)
.get("/data/device-storage", device_storage_handler)
// Database backup & checkpoint