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 google calendar oauth reconnects
Louis Beaumont1b2c199a204e
diff --git a/apps/screenpipe-app-tauri/lib/utils/calendar.test.ts b/apps/screenpipe-app-tauri/lib/utils/calendar.test.tsindex ecb4d83e2..7568e739a 100644--- a/apps/screenpipe-app-tauri/lib/utils/calendar.test.ts+++ b/apps/screenpipe-app-tauri/lib/utils/calendar.test.ts@@ -48,10 +48,10 @@ describe("fetchUpcomingCalendarSnapshot", () => {});});- it("uses Google events even when OAuth status says disconnected", async () => {+ it("uses Google events when OAuth status is connected", async () => {mocks.commands.oauthStatus.mockResolvedValue({status: "ok",- data: { connected: false },+ data: { connected: true },});mocks.localFetch.mockImplementation((url: string) => {if (url.startsWith("/connections/google-calendar/events")) {@@ -92,4 +92,68 @@ describe("fetchUpcomingCalendarSnapshot", () => {meeting_url: "https://meet.google.com/zqn-ahtt-iib",});});++ it("does not repeatedly probe Google events when OAuth status is disconnected", async () => {+ mocks.commands.oauthStatus.mockResolvedValue({+ status: "ok",+ data: { connected: false },+ });+ mocks.localFetch.mockImplementation((url: string) => {+ if (url.startsWith("/connections/calendar/events")) {+ return Promise.resolve(+ jsonResponse(false, { error: "AuthorizationDenied" }),+ );+ }++ return Promise.reject(new Error(`unexpected url: ${url}`));+ });++ const snapshot = await fetchUpcomingCalendarSnapshot({ hoursAhead: 8 });++ expect(snapshot.connectedSources).toEqual([]);+ expect(snapshot.failedSources).toEqual([]);+ expect(+ mocks.localFetch.mock.calls.some(([url]) =>+ String(url).startsWith("/connections/google-calendar/events"),+ ),+ ).toBe(false);+ });++ it("falls back to Google events when OAuth status cannot be read", async () => {+ mocks.commands.oauthStatus.mockRejectedValue(+ new Error("tauri unavailable"),+ );+ mocks.localFetch.mockImplementation((url: string) => {+ if (url.startsWith("/connections/google-calendar/events")) {+ return Promise.resolve(+ jsonResponse(true, [+ {+ id: "gcal-2",+ title: "Fallback calendar fetch",+ start: "2026-05-15T15:00:00-07:00",+ end: "2026-05-15T15:30:00-07:00",+ hangoutLink: "meet.google.com/abc-defg-hij",+ },+ ]),+ );+ }++ if (url.startsWith("/connections/calendar/events")) {+ return Promise.resolve(+ jsonResponse(false, { error: "AuthorizationDenied" }),+ );+ }++ return Promise.reject(new Error(`unexpected url: ${url}`));+ });++ const snapshot = await fetchUpcomingCalendarSnapshot({ hoursAhead: 8 });++ expect(snapshot.connectedSources).toEqual(["google"]);+ expect(snapshot.events[0]).toMatchObject({+ title: "Fallback calendar fetch",+ source: "google",+ meeting_url: "https://meet.google.com/abc-defg-hij",+ });+ });});diff --git a/apps/screenpipe-app-tauri/lib/utils/calendar.ts b/apps/screenpipe-app-tauri/lib/utils/calendar.tsindex d44e5e80e..aca834de9 100644--- a/apps/screenpipe-app-tauri/lib/utils/calendar.ts+++ b/apps/screenpipe-app-tauri/lib/utils/calendar.ts@@ -264,17 +264,25 @@ async function fetchGoogleProvider(hoursBack: number,hoursAhead: number,): Promise<ProviderCalendarResult> {+ let statusKnown = false;let statusConnected = false;try {const status = await commands.oauthStatus("google-calendar", null);- statusConnected = status.status === "ok" && status.data.connected;+ if (status.status === "ok") {+ statusKnown = true;+ statusConnected = status.data.connected;+ }} catch {// Fall back to probing the events endpoint below.}- // The status command can report disconnected when the access token is- // expired, even though a refresh token is present. The events endpoint is- // the source of truth because it refreshes before reading the calendar.+ // Once OAuth status is available, disconnected means there is no recoverable+ // token. Avoid repeatedly probing an endpoint that can only fail until the+ // user reconnects.+ if (statusKnown && !statusConnected) {+ return { source: "google", connected: false, ok: true, events: [] };+ }+const events = await fetchGoogleCalendar(hoursBack, hoursAhead);return {source: "google",diff --git a/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs b/apps/screenpipe-app-tauri/src-tauri/src/oauth.rsindex f699899a0..2fad73537 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs@@ -437,11 +437,11 @@ pub async fn oauth_status(instance: Option<String>,) -> Result<OAuthStatus, String> {let store = open_secret_store().await;- let token =- oauth::read_oauth_token_instance(store.as_ref(), &integration_id, instance.as_deref())+ let connected =+ oauth::is_oauth_instance_connected(store.as_ref(), &integration_id, instance.as_deref()).await;- let display_name = if token.is_some() {+ let display_name = if connected {oauth::load_oauth_json(store.as_ref(), &integration_id, instance.as_deref()).await.and_then(|v| {@@ -456,7 +456,7 @@ pub async fn oauth_status(};Ok(OAuthStatus {- connected: token.is_some(),+ connected,display_name,})}@@ -504,7 +504,7 @@ pub async fn oauth_list_instances(integration_id: String,) -> Result<Vec<OAuthInstanceInfo>, String> {let store = open_secret_store().await;- let instances = oauth::list_oauth_instances(store.as_ref(), &integration_id).await;+ let instances = oauth::list_connected_oauth_instances(store.as_ref(), &integration_id).await;let mut result = Vec::new();for inst in instances {diff --git a/crates/screenpipe-connect/src/oauth.rs b/crates/screenpipe-connect/src/oauth.rsindex 5e0019a67..c1dae6d18 100644--- a/crates/screenpipe-connect/src/oauth.rs+++ b/crates/screenpipe-connect/src/oauth.rs@@ -187,7 +187,14 @@ pub async fn load_oauth_json(instance: Option<&str>,) -> Option<Value> {if let Some(v) = load_oauth_json_exact(store, integration_id, instance).await {- return Some(v);+ if instance.is_some() || oauth_json_is_recoverable(&v) {+ return Some(v);+ }++ tracing::warn!(+ "oauth: {} default token is not recoverable, checking for a single healthy named instance",+ integration_id,+ );}// Fallback: callers that don't know about instances (instance=None)@@ -211,6 +218,21 @@ pub async fn load_oauth_json(None}+fn oauth_json_has_valid_access_token(v: &Value) -> bool {+ if v["access_token"].as_str().is_none() {+ return false;+ }++ match v["expires_at"].as_u64() {+ Some(expires_at) => unix_now() < expires_at.saturating_sub(60),+ None => true,+ }+}++fn oauth_json_is_recoverable(v: &Value) -> bool {+ oauth_json_has_valid_access_token(v) || v["refresh_token"].as_str().is_some()+}+/// Exact-key variant with no instance fallback. Everything `load_oauth_json`/// does except the multi-instance resolution.async fn load_oauth_json_exact(@@ -296,20 +318,30 @@ pub async fn is_oauth_instance_connected(integration_id: &str,instance: Option<&str>,) -> bool {- let v = match load_oauth_json(store, integration_id, instance).await {- Some(v) => v,- None => return false,- };+ load_oauth_json(store, integration_id, instance)+ .await+ .as_ref()+ .is_some_and(oauth_json_is_recoverable)+}- // Valid (non-expired) access token → connected- if let Some(expires_at) = v["expires_at"].as_u64() {- if unix_now() < expires_at.saturating_sub(60) {- return v["access_token"].as_str().is_some();+/// List only instances that are recoverable: either the access token is still+/// valid, or a refresh token exists and can keep the connection alive.+pub async fn list_connected_oauth_instances(+ store: Option<&SecretStore>,+ integration_id: &str,+) -> Vec<Option<String>> {+ let instances = list_oauth_instances(store, integration_id).await;+ let mut connected = Vec::new();+ for inst in instances {+ if load_oauth_json_exact(store, integration_id, inst.as_deref())+ .await+ .as_ref()+ .is_some_and(oauth_json_is_recoverable)+ {+ connected.push(inst);}}-- // Expired but has refresh token → recoverable (still "connected")- v["refresh_token"].as_str().is_some()+ connected}// ---------------------------------------------------------------------------@@ -665,13 +697,14 @@ mod tests {#[tokio::test]async fn load_with_none_prefers_exact_match_over_fallback() {// When BOTH a no-instance entry and a named one exist, the exact- // match wins — don't accidentally prefer a random named instance.+ // recoverable match wins — don't accidentally prefer a random named+ // instance.let store = mem_store().await;let id = "_t_prefer";store.set_json(&format!("oauth:{}", id),- &json!({"access_token": "default"}),+ &json!({"access_token": "default", "refresh_token": "default-rt"}),).await.unwrap();@@ -687,6 +720,39 @@ mod tests {assert_eq!(got["access_token"], "default");}+ #[tokio::test]+ async fn load_with_none_falls_back_when_default_is_unrecoverable() {+ // A stale default slot must not shadow a healthy named Google account.+ // This is the calendar "reconnect every hour" failure mode: status+ // checked the default key, found an expired non-refreshable token, and+ // ignored the refreshable token saved under the user's email.+ let store = mem_store().await;+ let id = "_t_shadowed_unrecoverable";+ let expired = unix_now().saturating_sub(3600);+ store+ .set_json(+ &format!("oauth:{}", id),+ &json!({"access_token": "stale-default", "expires_at": expired}),+ )+ .await+ .unwrap();+ store+ .set_json(+ &format!("oauth:{}:[email protected]", id),+ &json!({+ "access_token": "fresh-named",+ "refresh_token": "named-rt",+ "expires_at": expired,+ }),+ )+ .await+ .unwrap();++ let got = load_oauth_json(Some(&store), id, None).await.unwrap();+ assert_eq!(got["access_token"], "fresh-named");+ assert_eq!(got["refresh_token"], "named-rt");+ }+#[tokio::test]async fn load_with_none_is_ambiguous_when_multiple_instances() {// Two named instances, no default — we must NOT pick one arbitrarily.@@ -761,6 +827,78 @@ mod tests {assert!(is_oauth_instance_connected(Some(&store), id, None).await);}+ #[tokio::test]+ async fn is_oauth_instance_connected_treats_expired_refresh_token_as_connected() {+ let store = mem_store().await;+ let id = "_t_expired_refreshable";+ let expired = unix_now().saturating_sub(3600);+ store+ .set_json(+ &format!("oauth:{}", id),+ &json!({+ "access_token": "expired",+ "refresh_token": "rt",+ "expires_at": expired,+ }),+ )+ .await+ .unwrap();++ assert!(is_oauth_instance_connected(Some(&store), id, None).await);+ }++ #[tokio::test]+ async fn is_oauth_instance_connected_accepts_legacy_token_without_expiry() {+ let store = mem_store().await;+ let id = "_t_legacy_no_expiry";+ store+ .set_json(&format!("oauth:{}", id), &json!({"access_token": "legacy"}))+ .await+ .unwrap();++ assert!(is_oauth_instance_connected(Some(&store), id, None).await);+ }++ #[tokio::test]+ async fn is_oauth_instance_connected_rejects_expired_token_without_refresh() {+ let store = mem_store().await;+ let id = "_t_expired_unrecoverable";+ let expired = unix_now().saturating_sub(3600);+ store+ .set_json(+ &format!("oauth:{}", id),+ &json!({"access_token": "expired", "expires_at": expired}),+ )+ .await+ .unwrap();++ assert!(!is_oauth_instance_connected(Some(&store), id, None).await);+ }++ #[tokio::test]+ async fn list_connected_oauth_instances_filters_unrecoverable_slots() {+ let store = mem_store().await;+ let id = "_t_list_connected";+ let expired = unix_now().saturating_sub(3600);+ store+ .set_json(+ &format!("oauth:{}", id),+ &json!({"access_token": "stale-default", "expires_at": expired}),+ )+ .await+ .unwrap();+ store+ .set_json(+ &format!("oauth:{}:[email protected]", id),+ &json!({"access_token": "expired", "refresh_token": "rt", "expires_at": expired}),+ )+ .await+ .unwrap();++ let got = list_connected_oauth_instances(Some(&store), id).await;+ assert_eq!(got, vec![Some("[email protected]".to_string())]);+ }+// ---- sweep_shadowed_default_slots --------------------------------#[tokio::test]diff --git a/crates/screenpipe-engine/src/connections_api.rs b/crates/screenpipe-engine/src/connections_api.rsindex b80b3d511..26500dc35 100644--- a/crates/screenpipe-engine/src/connections_api.rs+++ b/crates/screenpipe-engine/src/connections_api.rs@@ -1027,10 +1027,15 @@ async fn gcal_events(let client = reqwest::Client::new();match gcal_events_inner(&client, params, &state.secret_store).await {Ok(events) => (StatusCode::OK, Json(json!(events))),- Err(e) => (- StatusCode::INTERNAL_SERVER_ERROR,- Json(json!({ "error": e.to_string() })),- ),+ Err(e) => {+ let message = e.to_string();+ let status = if message.contains("Google Calendar not connected") {+ StatusCode::UNAUTHORIZED+ } else {+ StatusCode::INTERNAL_SERVER_ERROR+ };+ (status, Json(json!({ "error": message })))+ }}}