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
perf(auth): use ArcSwap for cloud token state (#3624)
Divanshu56ba136b8171
diff --git a/Cargo.lock b/Cargo.lockindex c6b999bdc..67ea2a35d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -8216,6 +8216,7 @@ dependencies = ["accessibility","accessibility-sys","anyhow",+ "arc-swap","argon2","async-trait","base64 0.22.1",diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lockindex 3bf9898c0..56cd7bcea 100644--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock@@ -10876,12 +10876,13 @@ dependencies = [[[package]]name = "screenpipe-app"-version = "2.4.272"+version = "2.4.281"dependencies = ["aes 0.8.4","aes-gcm 0.10.3","anyhow","arboard",+ "arc-swap","async-trait","axum 0.6.20","base64 0.22.1",@@ -10999,7 +11000,7 @@ dependencies = [[[package]]name = "screenpipe-audio"-version = "0.3.345"+version = "0.3.347"dependencies = ["anyhow","audiopipe",@@ -11074,7 +11075,7 @@ dependencies = [[[package]]name = "screenpipe-config"-version = "0.3.345"+version = "0.3.347"dependencies = ["dirs 6.0.0","serde",@@ -11086,7 +11087,7 @@ dependencies = [[[package]]name = "screenpipe-connect"-version = "0.3.345"+version = "0.3.347"dependencies = ["anyhow","async-trait",@@ -11119,11 +11120,12 @@ dependencies = [[[package]]name = "screenpipe-core"-version = "0.3.345"+version = "0.3.347"dependencies = ["accessibility","accessibility-sys","anyhow",+ "arc-swap","argon2","async-trait","base64 0.22.1",@@ -11169,7 +11171,7 @@ dependencies = [[[package]]name = "screenpipe-db"-version = "0.3.345"+version = "0.3.347"dependencies = ["anyhow","chrono",@@ -11194,7 +11196,7 @@ dependencies = [[[package]]name = "screenpipe-engine"-version = "0.3.345"+version = "0.3.347"dependencies = ["anyhow","arc-swap",@@ -11263,7 +11265,7 @@ dependencies = [[[package]]name = "screenpipe-events"-version = "0.3.345"+version = "0.3.347"dependencies = ["anyhow","chrono",@@ -11279,7 +11281,7 @@ dependencies = [[[package]]name = "screenpipe-redact"-version = "0.3.345"+version = "0.3.347"dependencies = ["anyhow","async-trait",@@ -11308,7 +11310,7 @@ dependencies = [[[package]]name = "screenpipe-rfdetr-mlx"-version = "0.3.345"+version = "0.3.347"dependencies = ["image 0.25.10","mlx-rs",@@ -11319,7 +11321,7 @@ dependencies = [[[package]]name = "screenpipe-screen"-version = "0.3.345"+version = "0.3.347"dependencies = ["accessibility-sys","anyhow",@@ -11372,7 +11374,7 @@ dependencies = [[[package]]name = "screenpipe-sync"-version = "0.3.345"+version = "0.3.347"dependencies = ["async-trait","base64 0.22.1",@@ -11392,7 +11394,7 @@ dependencies = [[[package]]name = "screenpipe-vault"-version = "0.3.345"+version = "0.3.347"dependencies = ["argon2","chacha20poly1305",diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.tomlindex 9f1493ea7..4509609d9 100644--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml@@ -50,6 +50,7 @@ tauri-plugin-http = "=2.5.7"serde = { version = "1.0", features = ["derive"] }serde_json = "1.0"base64 = "0.22"+arc-swap = "1"tower-http = { version = "0.4.0", features = ["cors", "trace"] }http = "0.2"diff --git a/apps/screenpipe-app-tauri/src-tauri/src/commands.rs b/apps/screenpipe-app-tauri/src-tauri/src/commands.rsindex 2ed47a5e6..94f846125 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/commands.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/commands.rs@@ -779,7 +779,7 @@ pub fn get_cloud_token() -> Option<String> {/// app from the tray."////// Both the local `/v1/chat/completions` proxy and the pi-agent's-/// `models.json` apiKey share the same `Arc<RwLock<Option<String>>>`,+/// `models.json` apiKey share the same `Arc<ArcSwap<Option<String>>>`,/// so one write here updates both readers on the next pipe run.#[tauri::command]#[specta::specta]@@ -788,8 +788,7 @@ pub async fn set_cloud_token(state: tauri::State<'_, crate::recording::RecordingState>,) -> Result<(), String> {let normalized = token.filter(|t| !t.is_empty());- let mut guard = state.cloud_token.write().await;- *guard = normalized;+ state.cloud_token.store(std::sync::Arc::new(normalized));Ok(())}diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rsindex 3e8856e88..335a8c138 100755--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs@@ -925,7 +925,7 @@ async fn main() {is_starting_capture: Arc::new(AtomicBool::new(false)),last_spawn_epoch: Arc::new(AtomicU64::new(0)),interrupted_meeting: Arc::new(tokio::sync::Mutex::new(None)),- cloud_token: Arc::new(tokio::sync::RwLock::new(None)),+ cloud_token: Arc::new(arc_swap::ArcSwap::new(Arc::new(None))),};let pi_state = pi::PiState(Arc::new(tokio::sync::Mutex::new(pi::PiPool::new())));let suggestions_state = suggestions::SuggestionsState::new();diff --git a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs b/apps/screenpipe-app-tauri/src-tauri/src/recording.rsindex d0efd951b..a85482b55 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/recording.rs@@ -157,7 +157,7 @@ pub struct RecordingState {/// `PiExecutor` is constructed with `with_shared_user_token(this)`, so/// one update propagates to all three readers (cloud_proxy.rs, the/// pi-agent's models.json apiKey, and any future Tauri-side consumer).- pub cloud_token: Arc<tokio::sync::RwLock<Option<String>>>,+ pub cloud_token: Arc<arc_swap::ArcSwap<Option<String>>>,}// ---------------------------------------------------------------------------diff --git a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rsindex 057482310..761cd5475 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs@@ -69,7 +69,7 @@ impl ServerCore {// Server + PiExecutor pair. Pre-existing per-Server cloud_token is// replaced with this Arc so all three observers (cloud_proxy.rs,// PiExecutor, the Tauri command writer) share one storage cell.- cloud_token_handle: std::sync::Arc<tokio::sync::RwLock<Option<String>>>,+ cloud_token_handle: std::sync::Arc<arc_swap::ArcSwap<Option<String>>>,) -> Result<Self, String> {info!("Starting server core on port {}", config.port);crate::health::set_boot_phase("starting", Some("starting server"));@@ -335,9 +335,9 @@ impl ServerCore {// stale `config.user_id` snapshot.if let Some(ref t) = config.user_id {if !t.is_empty() {- let mut g = cloud_token_handle.write().await;- if g.is_none() {- *g = Some(t.clone());+ let existing = cloud_token_handle.load();+ if existing.is_none() {+ cloud_token_handle.store(std::sync::Arc::new(Some(t.clone())));}}}diff --git a/crates/screenpipe-core/Cargo.toml b/crates/screenpipe-core/Cargo.tomlindex d98428a23..80dbf6f98 100644--- a/crates/screenpipe-core/Cargo.toml+++ b/crates/screenpipe-core/Cargo.toml@@ -16,6 +16,7 @@ which = "6.0.1"ffmpeg-sidecar = { git = "https://github.com/nathanbabcock/ffmpeg-sidecar", branch = "main" }log = "0.4.17"anyhow = "1.0.86"+arc-swap = "1"tokio = { workspace = true }@@ -104,4 +105,3 @@ windows-sys = { version = "0.59", features = ["Win32_System_Threading", "Win32_F# Used by sync::client wire-compat test (asserts the PUT request shape# stays byte-identical after the upload_to_s3 → HttpPutDirect migration).wiremock = "0.6"-diff --git a/crates/screenpipe-core/src/agents/pi.rs b/crates/screenpipe-core/src/agents/pi.rsindex 8f24ab1ec..1e2224b88 100644--- a/crates/screenpipe-core/src/agents/pi.rs+++ b/crates/screenpipe-core/src/agents/pi.rs@@ -9,10 +9,10 @@use super::{AgentExecutor, AgentOutput, ExecutionHandle};use anyhow::{anyhow, Result};+use arc_swap::ArcSwap;use serde_json::json;use std::path::{Path, PathBuf};use std::sync::Arc;-use tokio::sync::RwLock;use tracing::{debug, error, info, warn};const PI_PACKAGE: &str = "@earendil-works/[email protected]";@@ -104,14 +104,14 @@ fn fallback_cloud_models() -> serde_json::Value {pub struct PiExecutor {/// Screenpipe cloud token (for LLM calls via screenpipe proxy).///- /// Wrapped in `Arc<RwLock<…>>` so the desktop app can refresh it at+ /// Wrapped in `ArcSwap` so the desktop app can refresh it at/// runtime via the `set_cloud_token` Tauri command — without this the/// token captured at engine boot would be permanent for the lifetime of/// the process. Users who sign in AFTER the engine started would stay on/// the gateway's anonymous tier (allowed_models = haiku/gemini only)/// until they fully quit and restart, because logout/login from the/// webview doesn't restart the screenpipe sidecar.- pub user_token: Arc<RwLock<Option<String>>>,+ pub user_token: Arc<ArcSwap<Option<String>>>,/// Screenpipe API base URL (default: `https://api.screenpipe.com/v1`).pub api_url: String,/// Bearer token for the *local* screenpipe-server API (localhost:3030).@@ -125,18 +125,18 @@ pub struct PiExecutor {impl PiExecutor {pub fn new(user_token: Option<String>) -> Self {Self {- user_token: Arc::new(RwLock::new(user_token)),+ user_token: Arc::new(ArcSwap::new(Arc::new(user_token))),api_url: SCREENPIPE_API_URL.to_string(),api_auth_key: None,}}/// Construct a PiExecutor that shares its cloud-token storage with an- /// external `Arc<RwLock>` — typically the same Arc held by the server's+ /// external `Arc<ArcSwap>` — typically the same Arc held by the server's/// `AppState.cloud_token`. A single update via `set_user_token` (or a- /// write through the shared Arc) is then visible to both the cloud+ /// store through the shared Arc) is then visible to both the cloud/// proxy and pi-agent on the next pipe run.- pub fn with_shared_user_token(user_token: Arc<RwLock<Option<String>>>) -> Self {+ pub fn with_shared_user_token(user_token: Arc<ArcSwap<Option<String>>>) -> Self {Self {user_token,api_url: SCREENPIPE_API_URL.to_string(),@@ -144,32 +144,24 @@ impl PiExecutor {}}- /// Read the current cloud token. Returns an owned `Option<String>` so- /// callers don't hold the lock across later awaits.- ///- /// If the lock is briefly contended, return `None` instead of blocking;- /// the next pipe run falls back to the env-var path and a later run can- /// pick up the refreshed token.+ /// Read the current cloud token. Returns an owned `Option<String>`.pub fn current_user_token(&self) -> Option<String> {- self.user_token- .try_read()- .ok()- .and_then(|g| g.clone())- .filter(|s| !s.is_empty())+ let token = self.user_token.load();+ (**token).clone().filter(|s| !s.is_empty())}/// Push a new cloud token. Called by the desktop app on login/logout so/// the next pipe run picks up the fresh token instead of using whatever/// was present at engine boot.- pub async fn set_user_token(&self, token: Option<String>) {- let mut g = self.user_token.write().await;- *g = token.filter(|s| !s.is_empty());+ pub fn set_user_token(&self, token: Option<String>) {+ self.user_token+ .store(Arc::new(token.filter(|s| !s.is_empty())));}/// Expose the underlying `Arc` so it can be shared with other components/// (the cloud_proxy.rs reader, Tauri-managed state) — write through any/// of them is observed by all.- pub fn user_token_arc(&self) -> Arc<RwLock<Option<String>>> {+ pub fn user_token_arc(&self) -> Arc<ArcSwap<Option<String>>> {self.user_token.clone()}@@ -2199,29 +2191,29 @@ mod tests {let exec = PiExecutor::new(None);assert_eq!(exec.current_user_token(), None);- exec.set_user_token(Some("token-v1".to_string())).await;+ exec.set_user_token(Some("token-v1".to_string()));assert_eq!(exec.current_user_token(), Some("token-v1".to_string()));- exec.set_user_token(Some("token-v2".to_string())).await;+ exec.set_user_token(Some("token-v2".to_string()));assert_eq!(exec.current_user_token(), Some("token-v2".to_string()));// Empty strings normalize to None so downstream `is_some()` checks// can't be tricked into sending an empty Bearer token.- exec.set_user_token(Some("".to_string())).await;+ exec.set_user_token(Some("".to_string()));assert_eq!(exec.current_user_token(), None);- exec.set_user_token(None).await;+ exec.set_user_token(None);assert_eq!(exec.current_user_token(), None);}- /// Confirms the design promise: a single shared `Arc<RwLock>` written+ /// Confirms the design promise: a single shared `ArcSwap` written/// from one place is observed by every PiExecutor that was constructed/// with `with_shared_user_token` against that same Arc. This is what/// lets the Tauri `set_cloud_token` command update the running/// pi-agent's apiKey AND the cloud_proxy.rs forwarder in one write.#[tokio::test]async fn shared_arc_propagates_token_writes_across_executors() {- let shared = Arc::new(RwLock::new(None::<String>));+ let shared = Arc::new(ArcSwap::new(Arc::new(None::<String>)));let exec_a = PiExecutor::with_shared_user_token(shared.clone());let exec_b = PiExecutor::with_shared_user_token(shared.clone());@@ -2229,21 +2221,18 @@ mod tests {assert_eq!(exec_b.current_user_token(), None);// Write via executor A — both see it.- exec_a.set_user_token(Some("fresh-jwt".to_string())).await;+ exec_a.set_user_token(Some("fresh-jwt".to_string()));assert_eq!(exec_a.current_user_token(), Some("fresh-jwt".to_string()));assert_eq!(exec_b.current_user_token(), Some("fresh-jwt".to_string()));// Write directly through the Arc (simulates the Tauri command// path which holds only the Arc, not the executor) — both see it.- {- let mut g = shared.write().await;- *g = Some("from-tauri".to_string());- }+ shared.store(Arc::new(Some("from-tauri".to_string())));assert_eq!(exec_a.current_user_token(), Some("from-tauri".to_string()));assert_eq!(exec_b.current_user_token(), Some("from-tauri".to_string()));// Sign-out path.- exec_b.set_user_token(None).await;+ exec_b.set_user_token(None);assert_eq!(exec_a.current_user_token(), None);assert_eq!(exec_b.current_user_token(), None);}diff --git a/crates/screenpipe-engine/src/bin/screenpipe-engine.rs b/crates/screenpipe-engine/src/bin/screenpipe-engine.rsindex 054841dd8..afe50c837 100644--- a/crates/screenpipe-engine/src/bin/screenpipe-engine.rs+++ b/crates/screenpipe-engine/src/bin/screenpipe-engine.rs@@ -1061,7 +1061,7 @@ async fn main() -> anyhow::Result<()> {// SCServer::cloud_token_handle after spawn.if let Ok(t) = std::env::var("SCREENPIPE_API_KEY") {if !t.is_empty() {- let _ = server.cloud_token.try_write().map(|mut g| *g = Some(t));+ server.cloud_token.store(std::sync::Arc::new(Some(t)));}}diff --git a/crates/screenpipe-engine/src/routes/cloud_proxy.rs b/crates/screenpipe-engine/src/routes/cloud_proxy.rsindex 78a239cb9..ad4810300 100644--- a/crates/screenpipe-engine/src/routes/cloud_proxy.rs+++ b/crates/screenpipe-engine/src/routes/cloud_proxy.rs@@ -26,8 +26,8 @@ pub async fn chat_completions(State(state): State<Arc<AppState>>,body: axum::body::Bytes,) -> Response {- let token = { state.cloud_token.read().await.clone() };- let Some(token) = token.filter(|t| !t.is_empty()) else {+ let token = state.cloud_token.load();+ let Some(token) = (**token).clone().filter(|t| !t.is_empty()) else {return (StatusCode::SERVICE_UNAVAILABLE,r#"{"error":"cloud_token_missing","message":"sign in to screenpipe to use cloud media analysis"}"#,diff --git a/crates/screenpipe-engine/src/server.rs b/crates/screenpipe-engine/src/server.rsindex 2d7abffc7..5fa7fe108 100644--- a/crates/screenpipe-engine/src/server.rs+++ b/crates/screenpipe-engine/src/server.rs@@ -65,6 +65,7 @@ use crate::{sync_api::{self, SyncState},video_cache::FrameCache,};+use arc_swap::ArcSwap;use dashmap::DashMap;use lru::LruCache;use moka::future::Cache as MokaCache;@@ -191,11 +192,11 @@ pub struct AppState {/// The API key to validate against (from SCREENPIPE_API_KEY or auth.json)pub api_auth_key: Option<String>,/// Cloud JWT (Clerk) used to authenticate proxied requests to api.screenpipe.com.- /// Held in a RwLock so the desktop shell can refresh it after login/logout+ /// Held in ArcSwap so the desktop shell can refresh it after login/logout/// without rebuilding the server. The pi-agent's bash deliberately can't see/// this token — agent calls localhost/v1/chat/completions and the server/// signs the upstream request here. See routes/cloud_proxy.rs.- pub cloud_token: Arc<tokio::sync::RwLock<Option<String>>>,+ pub cloud_token: Arc<ArcSwap<Option<String>>>,/// Unified credential store for OAuth tokens, API keys, etc.pub secret_store: Option<Arc<screenpipe_secrets::SecretStore>>,}@@ -232,7 +233,7 @@ pub struct SCServer {/// API key for remote auth validationpub api_auth_key: Option<String>,/// Cloud JWT for proxied /v1/chat/completions calls. See AppState::cloud_token.- pub cloud_token: Arc<tokio::sync::RwLock<Option<String>>>,+ pub cloud_token: Arc<ArcSwap<Option<String>>>,/// Unified credential store for OAuth tokens, API keys, etc.pub secret_store: Option<Arc<screenpipe_secrets::SecretStore>>,/// Background OAuth refresh scheduler. Owned here so its JoinHandle@@ -280,7 +281,7 @@ impl SCServer {owned_browser: None,api_auth: false,api_auth_key: None,- cloud_token: Arc::new(tokio::sync::RwLock::new(None)),+ cloud_token: Arc::new(ArcSwap::new(Arc::new(None))),secret_store: None,oauth_refresher: None,external_memory_sync: None,@@ -292,15 +293,13 @@ impl SCServer {/// reads the inner Arc on each request. Callers can also clone the Arc/// directly (see `cloud_token_handle`) to update it from elsewhere.pub fn with_cloud_token(self, token: Option<String>) -> Self {- if let Ok(mut guard) = self.cloud_token.try_write() {- *guard = token;- }+ self.cloud_token.store(Arc::new(token));self}/// Clone the cloud-token handle so the desktop shell can refresh it/// after the server has started (e.g. when settings.user.token changes).- pub fn cloud_token_handle(&self) -> Arc<tokio::sync::RwLock<Option<String>>> {+ pub fn cloud_token_handle(&self) -> Arc<ArcSwap<Option<String>>> {self.cloud_token.clone()}