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
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
chore: implement staggered polling and client-side caching to reduce backend load + remove dead code
Louis Beaumont2333a23d4f9c
diff --git a/screenpipe-app-tauri/app/page.tsx b/screenpipe-app-tauri/app/page.tsxindex 5629cf695..9c446ab5e 100644--- a/screenpipe-app-tauri/app/page.tsx+++ b/screenpipe-app-tauri/app/page.tsx@@ -33,11 +33,37 @@ export default function Home() {const { setIsOpen: setSettingsOpen } = useSettingsDialog();const isProcessingRef = React.useRef(false);+ // staggered polling with exponential backoff while maintaining responsiveness+ // while reducing backend loaduseEffect(() => {- const interval = setInterval(() => {- loadUser(settings.user?.token!);- }, 1000);- return () => clearInterval(interval);+ let retries = 0;+ const maxRetries = 5;+ const minDelay = 1000; // 1s minimum+ const maxDelay = 30000; // 30s maximum+ let timeoutId: NodeJS.Timeout;++ const loadUserWithBackoff = async () => {+ if (!settings.user?.token) return;++ try {+ await loadUser(settings.user.token, false);+ retries = 0;+ } catch (err) {+ console.error("failed to load user:", err);+ retries = Math.min(retries + 1, maxRetries);+ }++ // calculate next delay with exponential backoff+ const delay = Math.min(minDelay * Math.pow(2, retries), maxDelay);+ timeoutId = setTimeout(loadUserWithBackoff, delay);+ };++ loadUserWithBackoff();++ // cleanup+ return () => {+ if (timeoutId) clearTimeout(timeoutId);+ };}, [settings]);useEffect(() => {diff --git a/screenpipe-app-tauri/components/onboarding/login.tsx b/screenpipe-app-tauri/components/onboarding/login.tsxindex 0cb382ddf..1dedf6925 100644--- a/screenpipe-app-tauri/components/onboarding/login.tsx+++ b/screenpipe-app-tauri/components/onboarding/login.tsx@@ -32,7 +32,7 @@ const OnboardingLogin: React.FC<OnboardingLoginProps> = ({const apiKey = new URL(url).searchParams.get("api_key");if (apiKey) {updateSettings({ user: { token: apiKey } });- loadUser(apiKey);+ await loadUser(apiKey, true);toast({title: "logged in!",description: "your api key has been set",diff --git a/screenpipe-app-tauri/components/settings/account-section.tsx b/screenpipe-app-tauri/components/settings/account-section.tsxindex fba0dcdfb..b477965d9 100644--- a/screenpipe-app-tauri/components/settings/account-section.tsx+++ b/screenpipe-app-tauri/components/settings/account-section.tsx@@ -105,7 +105,7 @@ export function AccountSection() {const apiKey = new URL(url).searchParams.get("api_key");if (apiKey) {updateSettings({ user: { token: apiKey } });- await loadUser(apiKey);+ await loadUser(apiKey, true);toast({title: "logged in!",@@ -124,7 +124,7 @@ export function AccountSection() {stripe_connected: true,},});- loadUser(settings.user.token!);+ loadUser(settings.user.token!, true);}toast({title: "stripe connected!",diff --git a/screenpipe-app-tauri/components/store/credit-purchase-dialog.tsx b/screenpipe-app-tauri/components/store/credit-purchase-dialog.tsxindex e9a30789a..903d2e2f4 100644--- a/screenpipe-app-tauri/components/store/credit-purchase-dialog.tsx+++ b/screenpipe-app-tauri/components/store/credit-purchase-dialog.tsx@@ -36,7 +36,7 @@ export function CreditPurchaseDialog({`${url}?client_reference_id=${settings.user?.id}&metadata[user_id]=${settings.user?.id}`);setTimeout(async () => {- await loadUser(settings.user?.token!);+ await loadUser(settings.user?.token!, true);onCreditsUpdated?.();setShowRefreshHint(true);setIsLoading(false);diff --git a/screenpipe-app-tauri/lib/api/store/index.ts b/screenpipe-app-tauri/lib/api/store/index.tsindex 8c4298db6..90fa7229b 100644--- a/screenpipe-app-tauri/lib/api/store/index.ts+++ b/screenpipe-app-tauri/lib/api/store/index.ts@@ -1,4 +1,5 @@import { invoke } from "@tauri-apps/api/core";+import localforage from "localforage";export interface PipeStorePlugin {id: string;@@ -60,9 +61,15 @@ export interface CheckUpdateResponse {latest_file_size: number;}+interface CacheEntry<T> {+ data: T;+ timestamp: number;+}+export class PipeApi {private baseUrl: string;private authToken: string;+ private cacheTTL = 60000; // 60 seconds cacheprivate constructor(authToken: string) {this.baseUrl = "https://screenpi.pe";@@ -87,6 +94,34 @@ export class PipeApi {}}+ private async getCached<T>(key: string): Promise<T | null> {+ try {+ const entry = await localforage.getItem<CacheEntry<T>>(`pipe_api_${key}`);+ if (!entry) return null;++ if (Date.now() - entry.timestamp > this.cacheTTL) {+ await localforage.removeItem(`pipe_api_${key}`);+ return null;+ }++ return entry.data;+ } catch (error) {+ console.warn("cache read error:", error);+ return null;+ }+ }++ private async setCache<T>(key: string, data: T) {+ try {+ await localforage.setItem(`pipe_api_${key}`, {+ data,+ timestamp: Date.now(),+ });+ } catch (error) {+ console.warn("cache write error:", error);+ }+ }+async getUserPurchaseHistory(): Promise<PurchaseHistoryResponse> {try {const response = await fetch(@@ -102,8 +137,7 @@ export class PipeApi {throw new Error(`failed to fetch purchase history: ${error}`);}- const data = (await response.json()) as PurchaseHistoryResponse;- return data;+ return (await response.json()) as PurchaseHistoryResponse;} catch (error) {console.error("error getting purchase history:", error);throw error;@@ -111,6 +145,10 @@ export class PipeApi {}async listStorePlugins(): Promise<PipeStorePlugin[]> {+ const cacheKey = "store-plugins";+ const cached = await this.getCached<PipeStorePlugin[]>(cacheKey);+ if (cached) return cached;+try {const response = await fetch(`${this.baseUrl}/api/plugins/registry`, {headers: {@@ -122,6 +160,7 @@ export class PipeApi {throw new Error(`failed to fetch plugins: ${error}`);}const data: PipeStorePlugin[] = await response.json();+ await this.setCache(cacheKey, data);return data;} catch (error) {console.error("error listing pipes:", error);@@ -184,6 +223,10 @@ export class PipeApi {pipeId: string,version: string): Promise<CheckUpdateResponse> {+ const cacheKey = `update_${pipeId}_${version}`;+ const cached = await this.getCached<CheckUpdateResponse>(cacheKey);+ if (cached) return cached;+try {const response = await fetch(`${this.baseUrl}/api/plugins/check-update`, {method: "POST",@@ -200,10 +243,21 @@ export class PipeApi {}const data = await response.json();+ await this.setCache(cacheKey, data);return data;} catch (error) {console.error("error checking for updates:", error);throw error;}}++ // method to force refresh cache if needed+ async clearCache() {+ const keys = await localforage.keys();+ await Promise.all(+ keys+ .filter((key) => key.startsWith("pipe_api_"))+ .map((key) => localforage.removeItem(key))+ );+ }}diff --git a/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/screenpipe-app-tauri/lib/hooks/use-settings.tsxindex ad4d73386..059b9a29e 100644--- a/screenpipe-app-tauri/lib/hooks/use-settings.tsx+++ b/screenpipe-app-tauri/lib/hooks/use-settings.tsx@@ -12,9 +12,9 @@ import {import { LazyStore, LazyStore as TauriStore } from "@tauri-apps/plugin-store";import { localDataDir } from "@tauri-apps/api/path";import { flattenObject, unflattenObject } from "../utils";-import { invoke } from "@tauri-apps/api/core";import { useEffect } from "react";import posthog from "posthog-js";+import localforage from "localforage";export type VadSensitivity = "low" | "medium" | "high";@@ -214,8 +214,8 @@ export function createDefaultSettingsObject(): Settings {currentPlatform === "macos"? "apple-native": currentPlatform === "windows"- ? "windows-native"- : "tesseract";+ ? "windows-native"+ : "tesseract";defaultSettings.ocrEngine = ocrModel;defaultSettings.fps = currentPlatform === "macos" ? 0.5 : 1;@@ -327,15 +327,15 @@ export const store = createContextStore<StoreModel>({storage: tauriStorage,mergeStrategy: "mergeDeep",- },- ),+ }+ ));export function useSettings() {const settings = store.useStoreState((state) => state.settings);const setSettings = store.useStoreActions((actions) => actions.setSettings);const resetSettings = store.useStoreActions(- (actions) => actions.resetSettings,+ (actions) => actions.resetSettings);const resetSetting = store.useStoreActions((actions) => actions.resetSetting);@@ -371,8 +371,25 @@ export function useSettings() {: `${homeDirPath}\\.screenpipe`;};- const loadUser = async (token: string) => {+ const loadUser = async (token: string, forceReload = false) => {try {+ // try to get from cache first (unless force reload)+ const cacheKey = `user_data_${token}`;+ if (!forceReload) {+ const cached = await localforage.getItem<{+ data: User;+ timestamp: number;+ }>(cacheKey);++ // use cache if less than 30s old+ if (cached && Date.now() - cached.timestamp < 30000) {+ setSettings({+ user: cached.data,+ });+ return;+ }+ }+const response = await fetch(`https://screenpi.pe/api/user`, {method: "POST",headers: {@@ -397,11 +414,18 @@ export function useSettings() {});}+ // cache the result+ await localforage.setItem(cacheKey, {+ data: userData,+ timestamp: Date.now(),+ });+setSettings({user: userData,});} catch (err) {console.error("failed to load user:", err);+ throw err;}};diff --git a/screenpipe-app-tauri/src-tauri/Cargo.lock b/screenpipe-app-tauri/src-tauri/Cargo.lockindex 1dc3ef7ea..5e0f5a60d 100755--- a/screenpipe-app-tauri/src-tauri/Cargo.lock+++ b/screenpipe-app-tauri/src-tauri/Cargo.lock@@ -5289,7 +5289,7 @@ dependencies = [[[package]]name = "screenpipe-app"-version = "0.34.4"+version = "0.34.7"dependencies = ["anyhow","async-stream",diff --git a/screenpipe-app-tauri/src-tauri/src/sidecar.rs b/screenpipe-app-tauri/src-tauri/src/sidecar.rsindex 016bda4c1..b1c2b0303 100644--- a/screenpipe-app-tauri/src-tauri/src/sidecar.rs+++ b/screenpipe-app-tauri/src-tauri/src/sidecar.rs@@ -3,18 +3,13 @@ use crate::SidecarState;use serde::{Deserialize, Serialize};use serde_json::Value;use std::sync::Arc;-use std::time::{Duration, Instant};-use tauri::async_runtime::JoinHandle;use tauri::Emitter;use tauri::{Manager, State};use tauri_plugin_shell::process::{CommandChild, CommandEvent};use tauri_plugin_shell::ShellExt;use tauri_plugin_store::Store;use tokio::sync::Mutex;-use tokio::time::sleep;use tracing::{debug, error, info};-use crate::permissions::OSPermissionStatus;-use crate::permissions::do_permissions_check;#[derive(Debug, Serialize, Deserialize, Clone)]pub struct UserCredits {@@ -255,7 +250,7 @@ fn spawn_sidecar(app: &tauri::AppHandle) -> Result<CommandChild, String> {.and_then(|v| v.as_bool()).unwrap_or(false);- let use_all_monitors = store+ let _use_all_monitors = store.get("useAllMonitors").and_then(|v| v.as_bool()).unwrap_or(false);@@ -498,9 +493,6 @@ fn spawn_sidecar(app: &tauri::AppHandle) -> Result<CommandChild, String> {}pub struct SidecarManager {child: Option<CommandChild>,- last_restart: Instant,- restart_interval: Arc<Mutex<Duration>>,- restart_task: Option<JoinHandle<()>>,dev_mode: Arc<Mutex<bool>>,}@@ -508,40 +500,16 @@ impl SidecarManager {pub fn new() -> Self {Self {child: None,- last_restart: Instant::now(),- restart_interval: Arc::new(Mutex::new(Duration::from_secs(0))),- restart_task: None,dev_mode: Arc::new(Mutex::new(false)),}}- pub fn assert_permissions(&mut self) -> Result<(), String> {- // check for permissions before spawning- let permissions = do_permissions_check(true);-- if permissions.screen_recording != OSPermissionStatus::Granted {- return Err("Screen recording permission denied".to_string());- }- if permissions.microphone != OSPermissionStatus::Granted {- return Err("Microphone permission denied".to_string());- }- if permissions.accessibility != OSPermissionStatus::Granted {- return Err("Accessibility permission denied".to_string());- }-- Ok(())- }+pub async fn spawn(&mut self, app: &tauri::AppHandle) -> Result<(), String> {// Update settings from storeself.update_settings(app).await?;- // check for permissions before spawning- // #[cfg(target_os = "macos")]- // {- // self.assert_permissions()?;- // }-// Spawn the sidecarlet child = spawn_sidecar(app)?;self.child = Some(child);@@ -553,13 +521,6 @@ impl SidecarManager {async fn update_settings(&mut self, app: &tauri::AppHandle) -> Result<(), String> {let store = get_store(app, None).unwrap();- let restart_interval = store- .get("restartInterval")- .and_then(|v| v.as_u64())- .unwrap_or(0);-- debug!("restart_interval: {}", restart_interval);-let dev_mode = store.get("devMode").and_then(|v| v.as_bool())@@ -567,51 +528,9 @@ impl SidecarManager {debug!("dev_mode: {}", dev_mode);- *self.restart_interval.lock().await = Duration::from_secs(restart_interval * 60);*self.dev_mode.lock().await = dev_mode;Ok(())}- pub async fn check_and_restart(&mut self, app: &tauri::AppHandle) -> Result<(), String> {- let interval = *self.restart_interval.lock().await;- let dev_mode = *self.dev_mode.lock().await;- info!("interval: {}", interval.as_secs());- info!("last_restart: {:?}", self.last_restart);- info!("elapsed: {:?}", self.last_restart.elapsed());-- if interval.as_secs() > 0 && self.last_restart.elapsed() >= interval && !dev_mode {- info!("attempting to restart sidecar due to restart interval");-- // Safely kill the existing sidecar- if let Some(child) = self.child.take() {- match child.kill() {- Ok(_) => info!("successfully killed previous sidecar"),- Err(e) => {- error!("failed to kill previous sidecar: {}", e);- // Continue anyway as the process might have already died- }- }- }-- // Wait for process cleanup- sleep(Duration::from_secs(5)).await;-- // Try to spawn new sidecar- match spawn_sidecar(app) {- Ok(new_child) => {- info!("successfully spawned new sidecar");- self.child = Some(new_child);- self.last_restart = Instant::now();- }- Err(e) => {- error!("failed to spawn new sidecar: {}", e);- // Don't propagate error - let the app continue running- // The next check interval will try again- }- }- }-- Ok(())- }}