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

fix: cloud archive auto-init on startup + UX feedback

Louis Beaumonta36b4de2d77e
diff --git a/apps/screenpipe-app-tauri/components/settings/archive-settings.tsx b/apps/screenpipe-app-tauri/components/settings/archive-settings.tsx
index f974cf94c..795504bf2 100644
--- a/apps/screenpipe-app-tauri/components/settings/archive-settings.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/archive-settings.tsx
@@ -4,7 +4,7 @@
"use client";
import React, { useEffect, useState, useCallback } from "react";
-import { useSettings } from "@/lib/hooks/use-settings";
+import { useSettings, getStore } from "@/lib/hooks/use-settings";
import { Card, CardContent } from "@/components/ui/card";
import { Switch } from "@/components/ui/switch";
import {
@@ -18,7 +18,7 @@ import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { useToast } from "@/components/ui/use-toast";
import { Skeleton } from "@/components/ui/skeleton";
-import { Lock, CloudUpload, AlertTriangle } from "lucide-react";
+import { Lock, CloudUpload, AlertTriangle, Loader2, Play } from "lucide-react";
import { open as openUrl } from "@tauri-apps/plugin-shell";
import { commands } from "@/lib/utils/tauri";
@@ -31,6 +31,8 @@ interface ArchiveStatus {
storage_used: number;
storage_limit: number;
pending_count: number;
+ is_uploading: boolean;
+ chunks_uploaded: number;
}
const RETENTION_OPTIONS = [
@@ -85,13 +87,26 @@ export function ArchiveSettings() {
}
}, []);
- // Poll status every 30s when enabled
+ // Poll status — faster when uploading, slower when idle
useEffect(() => {
fetchStatus();
if (!archiveEnabled) return;
- const interval = setInterval(fetchStatus, 30000);
+ const pollMs = status?.is_uploading ? 5000 : 30000;
+ const interval = setInterval(fetchStatus, pollMs);
return () => clearInterval(interval);
- }, [archiveEnabled, fetchStatus]);
+ }, [archiveEnabled, fetchStatus, status?.is_uploading]);
+
+ // Persist archive settings to the Rust-readable store key so the backend
+ // can auto-initialize on startup without needing the frontend.
+ const persistArchiveStore = async (enabled: boolean, days: number) => {
+ try {
+ const store = await getStore();
+ await store.set("cloud_archive", { enabled, retention_days: days });
+ await store.save();
+ } catch {
+ // best effort
+ }
+ };
const handleToggle = async (enabled: boolean) => {
if (!isProUser || !isLoggedIn) return;
@@ -115,6 +130,7 @@ export function ArchiveSettings() {
}
await updateSettings({ cloudArchiveEnabled: true });
+ await persistArchiveStore(true, retentionDays);
toast({ title: "cloud archive enabled" });
} else {
// Disable archive
@@ -130,6 +146,7 @@ export function ArchiveSettings() {
}
await updateSettings({ cloudArchiveEnabled: false });
+ await persistArchiveStore(false, retentionDays);
toast({ title: "cloud archive disabled" });
}
@@ -148,6 +165,7 @@ export function ArchiveSettings() {
const handleRetentionChange = async (value: string) => {
const days = parseInt(value, 10);
await updateSettings({ cloudArchiveRetentionDays: days });
+ await persistArchiveStore(archiveEnabled, days);
if (archiveEnabled) {
try {
@@ -277,7 +295,7 @@ export function ArchiveSettings() {
{/* Status card */}
{archiveEnabled && (
<Card>
- <CardContent className="px-4 py-3 space-y-2">
+ <CardContent className="px-4 py-3 space-y-3">
{!status ? (
<div className="space-y-2">
<Skeleton className="h-4 w-32" />
@@ -285,17 +303,40 @@ export function ArchiveSettings() {
</div>
) : (
<>
+ {/* Status row */}
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">status</span>
<span className="text-foreground">
- {status.enabled ? (
- <span className="text-green-600">active</span>
+ {status.is_uploading ? (
+ <span className="flex items-center gap-1.5 text-foreground">
+ <Loader2 className="h-3 w-3 animate-spin" />
+ uploading ({status.chunks_uploaded} chunks)
+ </span>
+ ) : status.enabled ? (
+ status.pending_count > 0 ? (
+ <span className="text-foreground">waiting (next run in ~5m)</span>
+ ) : (
+ <span className="text-foreground">up to date</span>
+ )
) : (
- "paused"
+ <span className="text-muted-foreground">paused</span>
)}
</span>
</div>
+ {/* Pending records */}
+ {status.pending_count > 0 && (
+ <div className="flex items-center justify-between text-sm">
+ <span className="text-muted-foreground">
+ pending records
+ </span>
+ <span className="text-foreground">
+ {status.pending_count.toLocaleString()}
+ </span>
+ </div>
+ )}
+
+ {/* Last archived */}
{status.last_cleanup && (
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">last archived</span>
@@ -305,6 +346,7 @@ export function ArchiveSettings() {
</div>
)}
+ {/* Cloud storage */}
{(status.storage_used > 0 || status.storage_limit > 0) && (
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">
@@ -319,23 +361,40 @@ export function ArchiveSettings() {
</div>
)}
- {status.pending_count > 0 && (
- <div className="flex items-center justify-between text-sm">
- <span className="text-muted-foreground">
- pending records
- </span>
- <span className="text-foreground">
- {status.pending_count.toLocaleString()}
- </span>
- </div>
- )}
-
+ {/* Error */}
{status.last_error && (
<div className="flex items-center gap-2 text-sm text-destructive">
<AlertTriangle className="h-3.5 w-3.5 flex-shrink-0" />
<span className="truncate">{status.last_error}</span>
</div>
)}
+
+ {/* Archive now button */}
+ {status.enabled && status.pending_count > 0 && !status.is_uploading && (
+ <Button
+ variant="outline"
+ size="sm"
+ className="w-full"
+ onClick={async () => {
+ try {
+ await fetch("http://localhost:3030/archive/run", {
+ method: "POST",
+ });
+ toast({ title: "archive run started" });
+ // Poll faster while uploading
+ setTimeout(fetchStatus, 2000);
+ } catch {
+ toast({
+ title: "failed to trigger archive",
+ variant: "destructive",
+ });
+ }
+ }}
+ >
+ <Play className="h-3 w-3 mr-1.5" />
+ archive now
+ </Button>
+ )}
</>
)}
</CardContent>
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
index 4d217a5bc..ba3fe81b4 100755
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -8097,7 +8097,7 @@ dependencies = [
[[package]]
name = "screenpipe-app"
-version = "2.0.567"
+version = "2.0.565"
dependencies = [
"anyhow",
"arboard",
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
index 0b71580d6..2d6678714 100755
--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -2129,6 +2129,13 @@ async fn main() {
sync::auto_start_sync(&app_handle_clone, &sync_state_clone).await;
});
+ // Auto-start cloud archive if it was enabled (after sync so it can reuse sync manager)
+ let app_handle_clone = app_handle.clone();
+ tauri::async_runtime::spawn(async move {
+ tokio::time::sleep(tokio::time::Duration::from_secs(15)).await;
+ sync::auto_start_archive(&app_handle_clone).await;
+ });
+
Ok(())
})
.build(tauri::generate_context!())
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/store.rs b/apps/screenpipe-app-tauri/src-tauri/src/store.rs
index 6cd094143..7efefda03 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/store.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/store.rs
@@ -734,6 +734,38 @@ impl CloudSyncSettingsStore {
}
}
+// ─── Cloud Archive Settings ──────────────────────────────────────────────────
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CloudArchiveSettingsStore {
+ pub enabled: bool,
+ #[serde(default = "default_archive_retention")]
+ pub retention_days: u32,
+}
+
+fn default_archive_retention() -> u32 { 7 }
+
+impl CloudArchiveSettingsStore {
+ pub fn get(app: &AppHandle) -> Result<Option<Self>, String> {
+ let store = get_store(app, None).map_err(|e| e.to_string())?;
+ if store.is_empty() {
+ return Ok(None);
+ }
+ let settings =
+ serde_json::from_value(store.get("cloud_archive").unwrap_or(Value::Null));
+ match settings {
+ Ok(settings) => Ok(settings),
+ Err(_) => Ok(None),
+ }
+ }
+
+ pub fn save(&self, app: &AppHandle) -> Result<(), String> {
+ let store = get_store(app, None).map_err(|e| e.to_string())?;
+ store.set("cloud_archive", json!(self));
+ store.save().map_err(|e| e.to_string())
+ }
+}
+
impl RemindersSettingsStore {
pub fn get(app: &AppHandle) -> Result<Option<Self>, String> {
let store = get_store(app, None).map_err(|e| e.to_string())?;
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/sync.rs b/apps/screenpipe-app-tauri/src-tauri/src/sync.rs
index 99ed54ee6..89a47b734 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/sync.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/sync.rs
@@ -1,6 +1,6 @@
//! Tauri commands for cloud sync operations.
-use crate::store::{CloudSyncSettingsStore, SettingsStore};
+use crate::store::{CloudArchiveSettingsStore, CloudSyncSettingsStore, SettingsStore};
use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
use chrono::Utc;
use screenpipe_core::sync::{SyncClientConfig, SyncManager};
@@ -534,6 +534,94 @@ pub async fn auto_start_sync(app: &AppHandle, state: &SyncState) {
}
}
+/// Auto-start cloud archive on app launch if previously enabled.
+/// Called from main.rs during startup (after sync auto-start so archive can
+/// reuse the sync manager if available).
+pub async fn auto_start_archive(app: &AppHandle) {
+ // Check dedicated cloud_archive store key first, then fall back to
+ // reading cloudArchiveEnabled from the main settings extra fields
+ // (for users who enabled archive before this auto-start was added).
+ let archive_settings = match CloudArchiveSettingsStore::get(app) {
+ Ok(Some(s)) if s.enabled => s,
+ _ => {
+ // Fallback: check main settings for cloudArchiveEnabled
+ match SettingsStore::get(app) {
+ Ok(Some(s)) => {
+ let enabled = s.extra
+ .get("cloudArchiveEnabled")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+ if !enabled { return; }
+ let days = s.extra
+ .get("cloudArchiveRetentionDays")
+ .and_then(|v| v.as_u64())
+ .unwrap_or(7) as u32;
+ // Migrate: persist to dedicated key for future startups
+ let migrated = CloudArchiveSettingsStore { enabled: true, retention_days: days };
+ let _ = migrated.save(app);
+ migrated
+ }
+ _ => return,
+ }
+ }
+ };
+
+ // Get auth token from settings
+ let fresh_settings = match SettingsStore::get(app) {
+ Ok(Some(s)) => s,
+ _ => {
+ warn!("cloud archive: no settings found, skipping auto-start");
+ return;
+ }
+ };
+
+ let token = match fresh_settings.user.token {
+ Some(t) if !t.is_empty() => t,
+ _ => {
+ info!("cloud archive: no auth token, skipping auto-start");
+ return;
+ }
+ };
+
+ let client = reqwest::Client::new();
+ let init_request = serde_json::json!({
+ "token": token,
+ "retention_days": archive_settings.retention_days,
+ });
+
+ match client
+ .post("http://localhost:3030/archive/init")
+ .json(&init_request)
+ .send()
+ .await
+ {
+ Ok(response) if response.status().is_success() => {
+ info!("cloud archive auto-started (retention={}d)", archive_settings.retention_days);
+ }
+ Ok(response) if response.status().as_u16() == 409 => {
+ info!("cloud archive: already initialized, re-enabling");
+ // Already initialized — make sure it's enabled
+ let enable_req = serde_json::json!({ "enabled": true });
+ if let Err(e) = client
+ .post("http://localhost:3030/archive/configure")
+ .json(&enable_req)
+ .send()
+ .await
+ {
+ warn!("cloud archive: failed to re-enable: {}", e);
+ }
+ }
+ Ok(response) => {
+ let status = response.status();
+ let body = response.text().await.unwrap_or_default();
+ warn!("cloud archive auto-start: init failed ({}): {}", status, body);
+ }
+ Err(e) => {
+ warn!("cloud archive auto-start: server not reachable: {}", e);
+ }
+ }
+}
+
/// Delete all cloud data.
#[tauri::command]
#[specta::specta]
diff --git a/crates/screenpipe-server/src/archive.rs b/crates/screenpipe-server/src/archive.rs
index 24f9b1d0b..b077cdb03 100644
--- a/crates/screenpipe-server/src/archive.rs
+++ b/crates/screenpipe-server/src/archive.rs
@@ -64,6 +64,12 @@ struct ArchiveRuntime {
storage_used: u64,
/// Storage limit bytes.
storage_limit: u64,
+ /// Whether the archive is currently uploading data.
+ is_uploading: bool,
+ /// Number of chunks uploaded in the current/last run.
+ chunks_uploaded: u64,
+ /// Notify channel to trigger an immediate run.
+ run_now: Arc<tokio::sync::Notify>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -113,6 +119,8 @@ pub struct ArchiveStatusResponse {
pub storage_used: u64,
pub storage_limit: u64,
pub pending_count: u64,
+ pub is_uploading: bool,
+ pub chunks_uploaded: u64,
}
// ============================================================================
@@ -201,6 +209,7 @@ pub async fn archive_init(
// Initial watermark: epoch (nothing uploaded yet)
let watermark = DateTime::<Utc>::MIN_UTC;
+ let run_now = Arc::new(tokio::sync::Notify::new());
// Spawn cleanup loop
let task_handle = spawn_archive_loop(
@@ -209,6 +218,7 @@ pub async fn archive_init(
machine_id.clone(),
archive_config.clone(),
state.archive_state.inner.clone(),
+ run_now.clone(),
);
let runtime = ArchiveRuntime {
@@ -221,6 +231,9 @@ pub async fn archive_init(
last_cleanup: None,
storage_used: 0,
storage_limit: 0,
+ is_uploading: false,
+ chunks_uploaded: 0,
+ run_now,
};
*state.archive_state.inner.write().await = Some(runtime);
@@ -259,12 +272,15 @@ pub async fn archive_configure(
} else if enabled && !runtime.config.enabled {
// Re-enable: spawn a new loop
runtime.config.enabled = true;
+ let run_now = Arc::new(tokio::sync::Notify::new());
+ runtime.run_now = run_now.clone();
runtime.task_handle = spawn_archive_loop(
state.db.clone(),
runtime.manager.clone(),
runtime.machine_id.clone(),
runtime.config.clone(),
state.archive_state.inner.clone(),
+ run_now,
);
info!("archive: re-enabled");
}
@@ -277,6 +293,31 @@ pub async fn archive_configure(
})))
}
+/// POST /archive/run — trigger an immediate archive run.
+pub async fn archive_run(
+ State(state): State<Arc<AppState>>,
+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
+ let guard = state.archive_state.inner.read().await;
+ let runtime = guard.as_ref().ok_or_else(|| {
+ (
+ StatusCode::BAD_REQUEST,
+ Json(json!({"error": "archive not initialized"})),
+ )
+ })?;
+
+ if !runtime.config.enabled {
+ return Err((
+ StatusCode::BAD_REQUEST,
+ Json(json!({"error": "archive is disabled"})),
+ ));
+ }
+
+ runtime.run_now.notify_one();
+ info!("archive: manual run triggered");
+
+ Ok(Json(json!({"success": true})))
+}
+
/// GET /archive/status — return current state.
pub async fn archive_status(
State(state): State<Arc<AppState>>,
@@ -293,6 +334,8 @@ pub async fn archive_status(
storage_used: 0,
storage_limit: 0,
pending_count: 0,
+ is_uploading: false,
+ chunks_uploaded: 0,
})),
Some(runtime) => {
// Count pending records between watermark and cutoff
@@ -319,6 +362,8 @@ pub async fn archive_status(
storage_used: runtime.storage_used,
storage_limit: runtime.storage_limit,
pending_count,
+ is_uploading: runtime.is_uploading,
+ chunks_uploaded: runtime.chunks_uploaded,
}))
}
}
@@ -334,16 +379,23 @@ fn spawn_archive_loop(
machine_id: String,
_config: ArchiveConfig,
state: Arc<RwLock<Option<ArchiveRuntime>>>,
+ run_now: Arc<tokio::sync::Notify>,
) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
- // Wait a bit before first run
- tokio::time::sleep(std::time::Duration::from_secs(60)).await;
+ // Short initial delay, then run immediately
+ tokio::time::sleep(std::time::Duration::from_secs(10)).await;
- let mut interval = tokio::time::interval(std::time::Duration::from_secs(3600));
+ let mut interval = tokio::time::interval(std::time::Duration::from_secs(300));
interval.tick().await; // consume immediate tick
loop {
- interval.tick().await;
+ // Wait for either the interval or a manual trigger
+ tokio::select! {
+ _ = interval.tick() => {}
+ _ = run_now.notified() => {
+ info!("archive: manual run triggered, starting now");
+ }
+ }
let retention_days = {
let guard = state.read().await;
@@ -389,6 +441,15 @@ fn spawn_archive_loop(
cutoff.to_rfc3339()
);
+ // Mark as uploading
+ {
+ let mut guard = state.write().await;
+ if let Some(rt) = guard.as_mut() {
+ rt.is_uploading = true;
+ rt.chunks_uploaded = 0;
+ }
+ }
+
let mut current_watermark = watermark;
let mut upload_error = false;
@@ -450,12 +511,13 @@ fn spawn_archive_loop(
current_watermark = ts.and_utc();
}
- // Update storage info
+ // Update storage info and progress
let mut guard = state.write().await;
if let Some(rt) = guard.as_mut() {
rt.watermark = current_watermark;
rt.storage_used = result.storage_used;
rt.storage_limit = result.storage_limit;
+ rt.chunks_uploaded += 1;
}
}
Err(e) => {
@@ -470,6 +532,14 @@ fn spawn_archive_loop(
}
}
+ // Mark upload complete
+ {
+ let mut guard = state.write().await;
+ if let Some(rt) = guard.as_mut() {
+ rt.is_uploading = false;
+ }
+ }
+
if !upload_error {
// Update watermark
{
diff --git a/crates/screenpipe-server/src/server.rs b/crates/screenpipe-server/src/server.rs
index d706981ef..0f136382f 100644
--- a/crates/screenpipe-server/src/server.rs
+++ b/crates/screenpipe-server/src/server.rs
@@ -435,6 +435,7 @@ impl SCServer {
.route("/archive/init", axum::routing::post(crate::archive::archive_init))
.route("/archive/configure", axum::routing::post(crate::archive::archive_configure))
.route("/archive/status", get(crate::archive::archive_status))
+ .route("/archive/run", axum::routing::post(crate::archive::archive_run))
// Vision status endpoint (not in OpenAPI spec to avoid oasgen registration issues)
.route("/vision/status", get(api_vision_status))
// Vision pipeline metrics (not in OpenAPI spec)