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
fix(pi): make runtime cloud-token refresh deterministic (#3615)
Ansh Groverc5e902abee48
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsxindex 82fec0f69..a8dfa6332 100644--- a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx+++ b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx@@ -937,6 +937,14 @@ export const SettingsProvider: React.FC<{ children: React.ReactNode }> = ({ chil() => settingsRef.current.user?.token ?? undefined,async () => {await updateSettings({ user: null as any });+ // Mirror the sign-out into the sidecar so the pi-agent and+ // cloud_proxy.rs stop sending the now-revoked token on the+ // next pipe run.+ try {+ await invoke("set_cloud_token", { token: null });+ } catch (e) {+ console.warn("failed to clear cloud token in sidecar:", e);+ }});}, []); // eslint-disable-line react-hooks/exhaustive-deps@@ -1152,6 +1160,19 @@ export const SettingsProvider: React.FC<{ children: React.ReactNode }> = ({ chil}await updateSettings({ user: userData });++ // Push the fresh token into the running sidecar so the+ // `Server.cloud_token` (used by /v1/chat/completions proxy) and+ // the `PiExecutor.user_token` (used by pi-agent's models.json+ // apiKey) both pick up the new value on the next pipe run.+ // Without this, sign-in only updates the webview's settings —+ // the engine keeps whatever token it captured at boot (often+ // `null`), and every Sonnet/Opus pipe 403s on tier=anonymous.+ try {+ await invoke("set_cloud_token", { token });+ } catch (e) {+ console.warn("failed to push cloud token to sidecar:", e);+ }} catch (err) {console.error("failed to load user:", err instanceof Error ? err.message : err);throw err;diff --git a/apps/screenpipe-app-tauri/src-tauri/src/commands.rs b/apps/screenpipe-app-tauri/src-tauri/src/commands.rsindex e4b6afcfd..2ed47a5e6 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/commands.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/commands.rs@@ -764,6 +764,35 @@ pub fn get_cloud_token() -> Option<String> {.map(String::from)}+/// Push a fresh cloud-auth token into the running sidecar.+///+/// The frontend invokes this on every sign-in (after `loadUser` writes+/// `settings.user`) and on sign-out (passing `None`). Without it, the+/// `Server.cloud_token` and `PiExecutor.user_token` captured at engine+/// boot would be permanent for the lifetime of the sidecar process —+/// users who signed in AFTER the engine started would stay on the+/// gateway's anonymous tier (allowed_models = haiku/gemini only) on+/// every pipe run, surfacing as `403 "model_not_allowed"` for any+/// Sonnet/Opus preset even with an active Pro subscription. Logout ++/// log-in from the webview alone does NOT restart the sidecar, which+/// is why the previous user-facing workaround was "fully quit the+/// 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>>>`,+/// so one write here updates both readers on the next pipe run.+#[tauri::command]+#[specta::specta]+pub async fn set_cloud_token(+ token: Option<String>,+ 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;+ Ok(())+}+/// Persist the user's enterprise admin status + team API token so the/// pi-agent's `screenpipe-team` skill knows whether to install itself.///diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rsindex 1b97a45a1..3e8856e88 100755--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs@@ -751,6 +751,7 @@ async fn main() {commands::save_enterprise_team_config,commands::get_enterprise_team_api_token,commands::get_cloud_token,+ commands::set_cloud_token,enterprise_policy::set_enterprise_policy,enterprise_policy::set_sync_streams,commands::get_disk_usage,@@ -924,6 +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)),};let pi_state = pi::PiState(Arc::new(tokio::sync::Mutex::new(pi::PiPool::new())));let suggestions_state = suggestions::SuggestionsState::new();@@ -1038,6 +1040,7 @@ async fn main() {commands::save_enterprise_team_config,commands::get_enterprise_team_api_token,commands::get_cloud_token,+ commands::set_cloud_token,spawn_screenpipe,stop_screenpipe,recording::start_capture,@@ -1694,6 +1697,7 @@ async fn main() {let server_arc = recording_state.server.clone();let capture_arc = recording_state.capture.clone();let is_starting_clone = recording_state.is_starting.clone();+ let cloud_token_arc = recording_state.cloud_token.clone();// Pipe output callback. Stage 5: legacy `pipe_event`// topic dropped — every pipe stdout line goes out on@@ -1828,6 +1832,7 @@ async fn main() {&config,on_pipe_output,Some(owned_browser),+ cloud_token_arc.clone(),).await{diff --git a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs b/apps/screenpipe-app-tauri/src-tauri/src/recording.rsindex 6d9765afa..d0efd951b 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/recording.rs@@ -149,6 +149,15 @@ pub struct RecordingState {pub last_spawn_epoch: Arc<AtomicU64>,/// Recently active meeting to revive when capture is immediately restarted.pub(crate) interrupted_meeting: Arc<Mutex<Option<InterruptedMeeting>>>,+ /// App-scoped cloud-auth token (Clerk JWT). Outlives the Server (which+ /// is recreated on every recording restart) so that writes from the+ /// `set_cloud_token` Tauri command — pushed by the frontend on every+ /// sign-in / sign-out — survive capture toggles. The Server's own+ /// `cloud_token` field is replaced with this same Arc at start, and+ /// `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>>>,}// ---------------------------------------------------------------------------@@ -790,6 +799,7 @@ pub async fn spawn_screenpipe(let server_arc = state.server.clone();let capture_arc = state.capture.clone();+ let cloud_token_arc = state.cloud_token.clone();// Pipe output callback. Stage 5: legacy `pipe_event` topic dropped.// Every pipe stdout line is emitted on the unified `agent_event`@@ -841,17 +851,21 @@ pub async fn spawn_screenpipe(server_runtime.block_on(async move {// Phase 1: Start server- let server =- match ServerCore::start(&recording_config, on_pipe_output, Some(owned_browser))- .await- {- Ok(s) => s,- Err(e) => {- error!("Failed to start server core: {}", e);- let _ = result_tx.send(Err(e));- return;- }- };+ let server = match ServerCore::start(+ &recording_config,+ on_pipe_output,+ Some(owned_browser),+ cloud_token_arc.clone(),+ )+ .await+ {+ Ok(s) => s,+ Err(e) => {+ error!("Failed to start server core: {}", e);+ let _ = result_tx.send(Err(e));+ return;+ }+ };// Phase 2: Start capturelet capture = match CaptureSession::start(&server, &recording_config, true).await {diff --git a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rsindex f499cabe5..057482310 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs@@ -63,6 +63,13 @@ impl ServerCore {owned_browser: Option<std::sync::Arc<screenpipe_connect::connections::browser::OwnedBrowser>,>,+ // App-scoped cloud-token handle. Outlives Server (which is recreated+ // on every recording restart) so a token pushed via `set_cloud_token`+ // survives capture toggles and is automatically picked up by the next+ // 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>>>,) -> Result<Self, String> {info!("Starting server core on port {}", config.port);crate::health::set_boot_phase("starting", Some("starting server"));@@ -313,9 +320,23 @@ impl ServerCore {// the Clerk JWT (despite the name — see line 96 where the same value// is used as the cloud transcription bearer). Pi's bash deliberately// can't see this token; the local proxy signs the upstream request.+ //+ // We replace the Server's per-instance cloud_token cell with the+ // app-scoped Arc so writes from `set_cloud_token` (Tauri command,+ // pushed on every sign-in/out from the webview) are visible to both+ // cloud_proxy.rs AND the PiExecutor that shares this same Arc.+ // Without this, a token captured at engine boot was permanent until+ // restart — paying users who signed in after the sidecar started got+ // anonymous-tier 403s on every Sonnet/Opus pipe.+ server.cloud_token = cloud_token_handle.clone();+ // Seed the shared cell from persisted settings, but ONLY when empty+ // — if `set_cloud_token` has already pushed a fresher value (e.g. the+ // user signed in between sidecar boots), don't clobber it with the+ // stale `config.user_id` snapshot.if let Some(ref t) = config.user_id {if !t.is_empty() {- if let Ok(mut g) = server.cloud_token.try_write() {+ let mut g = cloud_token_handle.write().await;+ if g.is_none() {*g = Some(t.clone());}}@@ -406,10 +427,17 @@ impl ServerCore {let pipes_dir = config.data_dir.join("pipes");std::fs::create_dir_all(&pipes_dir).ok();- let user_token = config.user_id.clone();+ // Share the cloud-token Arc between Server (for cloud_proxy.rs) and+ // PiExecutor (for pi-agent provider auth). With one shared Arc the+ // `set_cloud_token` Tauri command updates both readers in one shot,+ // so a fresh sign-in or sign-out takes effect on the very next pipe+ // run without restarting the engine.+ let cloud_token_handle = server.cloud_token.clone();let pi_executor = Arc::new(- screenpipe_core::agents::pi::PiExecutor::new(user_token)- .with_api_auth_key(config.api_auth_key.clone()),+ screenpipe_core::agents::pi::PiExecutor::with_shared_user_token(+ cloud_token_handle.clone(),+ )+ .with_api_auth_key(config.api_auth_key.clone()),);let mut agent_executors: std::collections::HashMap<String,diff --git a/crates/screenpipe-core/src/agents/mod.rs b/crates/screenpipe-core/src/agents/mod.rsindex bc3934cc3..816dbc36a 100644--- a/crates/screenpipe-core/src/agents/mod.rs+++ b/crates/screenpipe-core/src/agents/mod.rs@@ -115,7 +115,13 @@ pub trait AgentExecutor: Send + Sync {/// Optional cloud auth token for screenpipe provider proxy./// Defaults to `None`; override in agents that support cloud auth.- fn user_token(&self) -> Option<&str> {+ ///+ /// Returns an owned `Option<String>` (not `Option<&str>`) so+ /// implementations can read from interior-mutable storage (e.g. an+ /// `Arc<RwLock>`) without holding a lock across the caller's borrow.+ /// This lets the desktop app refresh the token at runtime without+ /// restarting the engine.+ fn user_token(&self) -> Option<String> {None}}diff --git a/crates/screenpipe-core/src/agents/pi.rs b/crates/screenpipe-core/src/agents/pi.rsindex a23378989..8f24ab1ec 100644--- a/crates/screenpipe-core/src/agents/pi.rs+++ b/crates/screenpipe-core/src/agents/pi.rs@@ -11,6 +11,8 @@ use super::{AgentExecutor, AgentOutput, ExecutionHandle};use anyhow::{anyhow, Result};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]";@@ -101,7 +103,15 @@ fn fallback_cloud_models() -> serde_json::Value {/// Pi agent executor.pub struct PiExecutor {/// Screenpipe cloud token (for LLM calls via screenpipe proxy).- pub user_token: Option<String>,+ ///+ /// Wrapped in `Arc<RwLock<…>>` 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>>>,/// Screenpipe API base URL (default: `https://api.screenpipe.com/v1`).pub api_url: String,/// Bearer token for the *local* screenpipe-server API (localhost:3030).@@ -114,6 +124,19 @@ pub struct PiExecutor {impl PiExecutor {pub fn new(user_token: Option<String>) -> Self {+ Self {+ user_token: Arc::new(RwLock::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+ /// `AppState.cloud_token`. A single update via `set_user_token` (or a+ /// write 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 {Self {user_token,api_url: SCREENPIPE_API_URL.to_string(),@@ -121,6 +144,35 @@ 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.+ pub fn current_user_token(&self) -> Option<String> {+ self.user_token+ .try_read()+ .ok()+ .and_then(|g| g.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());+ }++ /// 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>>> {+ self.user_token.clone()+ }+/// Attach the local server's api_auth_key so Pi's bash tool can include/// `Authorization: Bearer ...` on localhost:3030 calls.pub fn with_api_auth_key(mut self, key: Option<String>) -> Self {@@ -794,7 +846,8 @@ impl PiExecutor {}cmd.arg("-p").arg(prompt);- if let Some(ref token) = self.user_token {+ let cloud_token = self.current_user_token();+ if let Some(ref token) = cloud_token {cmd.env("SCREENPIPE_API_KEY", token);}@@ -819,7 +872,7 @@ impl PiExecutor {cmd.env("GOOGLE_API_KEY", key);}// Ensure screenpipe API key is set as env var fallback- "screenpipe" if self.user_token.is_none() => {+ "screenpipe" if cloud_token.is_none() => {cmd.env("SCREENPIPE_API_KEY", key);}_ => {}@@ -920,7 +973,8 @@ impl PiExecutor {}cmd.arg("-p").arg(prompt);- if let Some(ref token) = self.user_token {+ let cloud_token = self.current_user_token();+ if let Some(ref token) = cloud_token {cmd.env("SCREENPIPE_API_KEY", token);}@@ -943,7 +997,7 @@ impl PiExecutor {cmd.env("GOOGLE_API_KEY", key);}// Ensure screenpipe API key is set as env var fallback- "screenpipe" if self.user_token.is_none() => {+ "screenpipe" if cloud_token.is_none() => {cmd.env("SCREENPIPE_API_KEY", key);}_ => {}@@ -1091,8 +1145,9 @@ impl AgentExecutor for PiExecutor {shared_pid: Option<super::SharedPid>,continue_session: bool,) -> Result<AgentOutput> {+ let cloud_token = self.current_user_token();Self::ensure_pi_config(- self.user_token.as_deref(),+ cloud_token.as_deref(),&self.api_url,provider,Some(model),@@ -1147,8 +1202,13 @@ impl AgentExecutor for PiExecutor {"pi model not found, re-merging managed providers (stderr: {})",output.stderr.trim());+ // Re-read the cloud token — it may have been refreshed via+ // `set_user_token` since the run started (e.g. user signed in+ // mid-pipe). Picking up the fresh value avoids re-running with+ // the same stale token that triggered the not-found.+ let cloud_token = self.current_user_token();Self::ensure_pi_config(- self.user_token.as_deref(),+ cloud_token.as_deref(),&self.api_url,provider,Some(&resolved_model),@@ -1189,8 +1249,9 @@ impl AgentExecutor for PiExecutor {let resolved_provider = provider.unwrap_or("screenpipe").to_string();let resolved_model = Self::resolve_model(model, &resolved_provider);+ let cloud_token = self.current_user_token();Self::ensure_pi_config(- self.user_token.as_deref(),+ cloud_token.as_deref(),&self.api_url,provider,Some(&resolved_model),@@ -1237,8 +1298,10 @@ impl AgentExecutor for PiExecutor {"pi model not found, re-merging managed providers (stderr: {})",output.stderr.trim());+ // Re-read cloud token (see comment in `run` above).+ let cloud_token = self.current_user_token();Self::ensure_pi_config(- self.user_token.as_deref(),+ cloud_token.as_deref(),&self.api_url,provider,Some(&resolved_model),@@ -1323,8 +1386,8 @@ impl AgentExecutor for PiExecutor {"pi"}- fn user_token(&self) -> Option<&str> {- self.user_token.as_deref()+ fn user_token(&self) -> Option<String> {+ self.current_user_token()}}@@ -2125,4 +2188,63 @@ mod tests {assert_eq!(models.len(), 1);assert_eq!(models[0].get("id").unwrap().as_str().unwrap(), "qwen3:8b");}++ /// Regression: the engine used to capture the cloud user token once at+ /// boot via `PiExecutor::new(user_token)` and never refresh it. Users+ /// who signed in AFTER the sidecar started stayed on tier=anonymous+ /// until they fully quit + relaunched. The fix is `set_user_token` ++ /// `with_shared_user_token` — verify both work end-to-end.+ #[tokio::test]+ async fn set_user_token_updates_subsequent_reads() {+ let exec = PiExecutor::new(None);+ assert_eq!(exec.current_user_token(), None);++ exec.set_user_token(Some("token-v1".to_string())).await;+ assert_eq!(exec.current_user_token(), Some("token-v1".to_string()));++ exec.set_user_token(Some("token-v2".to_string())).await;+ 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;+ assert_eq!(exec.current_user_token(), None);++ exec.set_user_token(None).await;+ assert_eq!(exec.current_user_token(), None);+ }++ /// Confirms the design promise: a single shared `Arc<RwLock>` 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 exec_a = PiExecutor::with_shared_user_token(shared.clone());+ let exec_b = PiExecutor::with_shared_user_token(shared.clone());++ assert_eq!(exec_a.current_user_token(), None);+ 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;+ 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());+ }+ 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;+ assert_eq!(exec_a.current_user_token(), None);+ assert_eq!(exec_b.current_user_token(), None);+ }}diff --git a/crates/screenpipe-core/src/pipes/mod.rs b/crates/screenpipe-core/src/pipes/mod.rsindex 2c378b73f..35906bf56 100644--- a/crates/screenpipe-core/src/pipes/mod.rs+++ b/crates/screenpipe-core/src/pipes/mod.rs@@ -1974,8 +1974,9 @@ impl PipeManager {// Pre-configure pilet mut pipe_token: Option<String> = None;if config.agent == "pi" {+ let cloud_token = executor.user_token();if let Err(e) = PiExecutor::ensure_pi_config(- executor.user_token(),+ cloud_token.as_deref(),SCREENPIPE_API_URL,run_provider.as_deref(),Some(&run_model),@@ -3505,8 +3506,9 @@ impl PipeManager {// Pre-configure pi with the pipe's providerlet mut pipe_token: Option<String> = None;if config.agent == "pi" {+ let cloud_token = executor.user_token();if let Err(e) = PiExecutor::ensure_pi_config(- executor.user_token(),+ cloud_token.as_deref(),SCREENPIPE_API_URL,provider.as_deref(),Some(&model),