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(connections): google-docs proxy routing and single-account instance lookup (#3649)
Ansh Grover2e430713009b
diff --git a/apps/screenpipe-app-tauri/components/settings/connections-section.tsx b/apps/screenpipe-app-tauri/components/settings/connections-section.tsxindex c4b7728f6..044c6dd79 100644--- a/apps/screenpipe-app-tauri/components/settings/connections-section.tsx+++ b/apps/screenpipe-app-tauri/components/settings/connections-section.tsx@@ -2281,6 +2281,9 @@ export function ConnectionsSection({ focusConnectionId, focusRequestId = 0 }: Coconst [chatgptConnected, setChatgptConnected] = useState(false);const [browserUrlConnected, setBrowserUrlConnected] = useState(false);const [googleCalendarConnected, setGoogleCalendarConnected] = useState(false);+ const [googleDocsConnected, setGoogleDocsConnected] = useState(false);+ const [googleSheetsConnected, setGoogleSheetsConnected] = useState(false);+ const [gmailConnected, setGmailConnected] = useState(false);const [customMcpConnected, setCustomMcpConnected] = useState(false);const [inputMonitoringGranted, setInputMonitoringGranted] = useState(false);@@ -2299,6 +2302,15 @@ export function ConnectionsSection({ focusConnectionId, focusRequestId = 0 }: Cocommands.oauthStatus("google-calendar", null).then(res => {setGoogleCalendarConnected(res.status === "ok" && res.data.connected);}).catch(() => {});+ commands.oauthStatus("google-docs", null).then(res => {+ setGoogleDocsConnected(res.status === "ok" && res.data.connected);+ }).catch(() => {});+ commands.oauthStatus("google-sheets", null).then(res => {+ setGoogleSheetsConnected(res.status === "ok" && res.data.connected);+ }).catch(() => {});+ commands.oauthStatus("gmail", null).then(res => {+ setGmailConnected(res.status === "ok" && res.data.connected);+ }).catch(() => {});localFetch("/mcp-servers").then(async r => {if (!r.ok) { setCustomMcpConnected(false); return; }const body = await r.json();@@ -2412,10 +2424,16 @@ export function ConnectionsSection({ focusConnectionId, focusRequestId = 0 }: Coconst api = integrations.find(i => i.id === h.id);if (api) h.connected = api.connected;}- // Google Calendar dot is driven by direct oauthStatus (not the cached API), so it stays+ // Google OAuth dots are driven by direct oauthStatus (not the cached API), so they stay// in sync immediately after connect/disconnect without waiting for cache expiry.const googleCalTile = hardcoded.find(h => h.id === "google-calendar");if (googleCalTile) googleCalTile.connected = googleCalendarConnected;+ const googleDocsTile = hardcoded.find(h => h.id === "google-docs");+ if (googleDocsTile) googleDocsTile.connected = googleDocsConnected;+ const googleSheetsTile = hardcoded.find(h => h.id === "google-sheets");+ if (googleSheetsTile) googleSheetsTile.connected = googleSheetsConnected;+ const gmailTile = hardcoded.find(h => h.id === "gmail");+ if (gmailTile) gmailTile.connected = gmailConnected;// Custom MCP tile shows the dot when any user-registered MCP server is enabled.const customMcpTile = hardcoded.find(h => h.id === "custom-mcp");if (customMcpTile) customMcpTile.connected = customMcpConnected;@@ -2423,7 +2441,7 @@ export function ConnectionsSection({ focusConnectionId, focusRequestId = 0 }: Co...tile,category: tile.category ?? CONNECTION_CATEGORY_BY_ID[tile.id] ?? "Other",}));- }, [os, claudeInstalled, cursorInstalled, codexInstalled, chatgptConnected, browserUrlConnected, integrations, googleCalendarConnected, customMcpConnected, inputMonitoringGranted]);+ }, [os, claudeInstalled, cursorInstalled, codexInstalled, chatgptConnected, browserUrlConnected, integrations, googleCalendarConnected, googleDocsConnected, googleSheetsConnected, gmailConnected, customMcpConnected, inputMonitoringGranted]);const categoryOptions = useMemo(() => {const categories = Array.from(diff --git a/crates/screenpipe-connect/src/connections/google_docs.rs b/crates/screenpipe-connect/src/connections/google_docs.rsindex e875ed818..ca08e0e4e 100644--- a/crates/screenpipe-connect/src/connections/google_docs.rs+++ b/crates/screenpipe-connect/src/connections/google_docs.rs@@ -69,9 +69,9 @@ impl Integration for GoogleDocs {fn proxy_config(&self) -> Option<&'static ProxyConfig> {static CFG: ProxyConfig = ProxyConfig {- // Using googleapis.com root so the proxy covers both the Docs API- // (docs.googleapis.com paths rewrite to /docs/v1/...) and the Drive- // API (/drive/v3/...) with a single token injection point.+ // Drive API lives on www.googleapis.com (/drive/v3/...).+ // Docs API paths (/docs/v1/...) are rerouted to docs.googleapis.com+ // by path_routes below — they would 404 on www.googleapis.com.base_url: "https://www.googleapis.com",auth: ProxyAuth::Bearer {credential_key: "api_key",@@ -81,6 +81,13 @@ impl Integration for GoogleDocs {Some(&CFG)}+ fn path_routes(&self) -> &'static [(&'static str, &'static str)] {+ // Google Docs API is at docs.googleapis.com, not www.googleapis.com.+ // Strip the "docs/" prefix from the proxy path and use the correct host.+ // Drive paths (drive/v3/...) fall through to the default base_url.+ &[("docs/", "https://docs.googleapis.com/")]+ }+async fn test(&self,client: &reqwest::Client,@@ -106,3 +113,70 @@ impl Integration for GoogleDocs {Ok(format!("connected as {}", email))}}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::connections::Integration;++ fn resolve(path: &str) -> String {+ let routes = GoogleDocs.path_routes();+ let base = "https://www.googleapis.com";+ let api_path_clean = path.trim_start_matches('/');+ routes+ .iter()+ .find(|(prefix, _)| api_path_clean.starts_with(prefix))+ .map(|(prefix, new_base)| {+ let rest = api_path_clean+ .strip_prefix(prefix)+ .unwrap_or(api_path_clean);+ format!("{}/{}", new_base.trim_end_matches('/'), rest)+ })+ .unwrap_or_else(|| format!("{}/{}", base, api_path_clean))+ }++ #[test]+ fn docs_create_routes_to_docs_subdomain() {+ assert_eq!(+ resolve("docs/v1/documents"),+ "https://docs.googleapis.com/v1/documents"+ );+ }++ #[test]+ fn docs_get_routes_to_docs_subdomain() {+ let doc_id = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgVE2upms";+ assert_eq!(+ resolve(&format!("docs/v1/documents/{}", doc_id)),+ format!("https://docs.googleapis.com/v1/documents/{}", doc_id)+ );+ }++ #[test]+ fn docs_batch_update_routes_to_docs_subdomain() {+ let doc_id = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgVE2upms";+ assert_eq!(+ resolve(&format!("docs/v1/documents/{}:batchUpdate", doc_id)),+ format!(+ "https://docs.googleapis.com/v1/documents/{}:batchUpdate",+ doc_id+ )+ );+ }++ #[test]+ fn drive_paths_stay_on_www_googleapis() {+ assert_eq!(+ resolve("drive/v3/files"),+ "https://www.googleapis.com/drive/v3/files"+ );+ }++ #[test]+ fn drive_export_stays_on_www_googleapis() {+ assert_eq!(+ resolve("drive/v3/files/FILE_ID/export"),+ "https://www.googleapis.com/drive/v3/files/FILE_ID/export"+ );+ }+}diff --git a/crates/screenpipe-connect/src/connections/mod.rs b/crates/screenpipe-connect/src/connections/mod.rsindex daa964f5b..78f02baa1 100644--- a/crates/screenpipe-connect/src/connections/mod.rs+++ b/crates/screenpipe-connect/src/connections/mod.rs@@ -201,6 +201,18 @@ pub trait Integration: Send + Sync {None}+ /// Path-prefix routing overrides for the credential proxy.+ ///+ /// Each entry is `(path_prefix, replacement_base_url)`. When the incoming+ /// proxy path starts with `path_prefix`, the proxy strips that prefix and+ /// forwards to `replacement_base_url/<rest>` instead of the `ProxyConfig`+ /// base_url. Useful when a single OAuth credential covers APIs on multiple+ /// subdomains (e.g. Google Docs at docs.googleapis.com vs Drive at+ /// www.googleapis.com). Default: no overrides (everything goes to base_url).+ fn path_routes(&self) -> &'static [(&'static str, &'static str)] {+ &[]+ }+/// Extra PEM-encoded root certificate to trust when calling this/// integration's API. Required for providers that run on a private/// CA (e.g. Bee uses `CN=BeeCertificateAuthority`, not WebPKI).@@ -497,6 +509,15 @@ impl ConnectionManager {.and_then(|i| i.proxy_config())}+ /// Look up path-prefix routing overrides for a connection by ID.+ pub fn find_path_routes(&self, id: &str) -> &'static [(&'static str, &'static str)] {+ self.integrations+ .iter()+ .find(|i| i.def().id == id)+ .map(|i| i.path_routes())+ .unwrap_or(&[])+ }+/// Look up the integration definition by ID.pub fn find_def(&self, id: &str) -> Option<&'static IntegrationDef> {self.integrationsdiff --git a/crates/screenpipe-connect/src/oauth.rs b/crates/screenpipe-connect/src/oauth.rsindex 57d6adeaf..efb7e6690 100644--- a/crates/screenpipe-connect/src/oauth.rs+++ b/crates/screenpipe-connect/src/oauth.rs@@ -218,13 +218,27 @@ pub(crate) async fn load_oauth_json_with_instance();}- // Fallback: callers that don't know about instances (instance=None)- // should still find the token when the user has a single named- // instance. Skip when instance is explicitly set — the caller wants- // that exact one.+ // Fallback A: explicit instance that has no keyed entry but exactly one+ // default-slot token exists. Happens when the user connected once before+ // multi-account support (token stored under None), then passes+ // [email protected]. We know there is only one account so it is+ // safe to serve it — we are not guessing between multiple accounts.if instance.is_some() {+ let instances = list_oauth_instances(store, integration_id).await;+ if matches!(instances.as_slice(), [None]) {+ tracing::debug!(+ "oauth: {} explicit instance {:?} not found, falling back to sole default-slot token",+ integration_id,+ instance,+ );+ let v = load_oauth_json_exact(store, integration_id, None).await?;+ return Some((v, None));+ }return None;}++ // Fallback B: callers that don't know about instances (instance=None)+ // should still find the token when the user has a single named instance.let instances = list_oauth_instances(store, integration_id).await;let named: Vec<String> = instances.into_iter().flatten().collect();match named.len() {@@ -983,6 +997,54 @@ mod tests {assert!(got.is_none());}+ #[tokio::test]+ async fn explicit_instance_falls_back_to_sole_default_slot() {+ // Bug: user connected once (token in default slot), then passes+ // [email protected]. The exact key doesn't exist but there's+ // only one account — we should serve it rather than 401.+ let store = mem_store().await;+ let id = "_t_default_fallback";+ store+ .set_json(+ &format!("oauth:{}", id),+ &json!({"access_token": "default-tok", "refresh_token": "rt"}),+ )+ .await+ .unwrap();++ let got = load_oauth_json(Some(&store), id, Some("[email protected]")).await;+ assert!(got.is_some(), "expected fallback to default slot");+ assert_eq!(got.unwrap()["access_token"], "default-tok");+ }++ #[tokio::test]+ async fn explicit_instance_does_not_fall_back_when_multiple_exist() {+ // Two named accounts — passing a non-matching explicit instance must+ // still return None; we cannot guess which account was meant.+ let store = mem_store().await;+ let id = "_t_no_fallback_multi";+ store+ .set_json(+ &format!("oauth:{}:[email protected]", id),+ &json!({"access_token": "A", "refresh_token": "ra"}),+ )+ .await+ .unwrap();+ store+ .set_json(+ &format!("oauth:{}:[email protected]", id),+ &json!({"access_token": "B", "refresh_token": "rb"}),+ )+ .await+ .unwrap();++ let got = load_oauth_json(Some(&store), id, Some("[email protected]")).await;+ assert!(+ got.is_none(),+ "must not fall back when multiple accounts exist"+ );+ }+#[tokio::test]async fn load_with_none_returns_none_when_store_empty() {let store = mem_store().await;diff --git a/crates/screenpipe-engine/src/connections_api.rs b/crates/screenpipe-engine/src/connections_api.rsindex 3c348e232..62d80fbd3 100644--- a/crates/screenpipe-engine/src/connections_api.rs+++ b/crates/screenpipe-engine/src/connections_api.rs@@ -1608,22 +1608,32 @@ async fn connection_proxy(}};- // Capture the extra-root-CA PEM (if any) BEFORE releasing the lock, so- // we can build the right reqwest client without keeping the manager- // borrow alive across the network call.+ // Capture the extra-root-CA PEM (if any) and path-prefix routing rules+ // BEFORE releasing the lock, so we can build the right reqwest client and+ // target URL without keeping the manager borrow alive across the network call.let extra_root_pem = mgr.find_extra_root_pem(&id);+ let path_routes = mgr.find_path_routes(&id);drop(mgr); // release lock before making external request- // Build the target URL. Query params from the caller (e.g.- // `?valueInputOption=USER_ENTERED` for Google Sheets appends) must be- // forwarded verbatim — without this, callers silently hit defaults and- // bad requests like 400s on `values:append`.+ // Build the target URL. Path-prefix routes (e.g. Google Docs "docs/" →+ // docs.googleapis.com) override base_url for specific path prefixes.+ // Query params from the caller must be forwarded verbatim — without this,+ // callers silently hit defaults and get 400s on endpoints like `values:append`.+ let api_path_clean = api_path.trim_start_matches('/');+ let (effective_base, effective_path) = path_routes+ .iter()+ .find(|(prefix, _)| api_path_clean.starts_with(prefix))+ .map(|(prefix, new_base)| {+ let rest = api_path_clean+ .strip_prefix(prefix)+ .unwrap_or(api_path_clean);+ (new_base.trim_end_matches('/').to_string(), rest.to_string())+ })+ .unwrap_or_else(|| (base_url.clone(), api_path_clean.to_string()));let target_url = match forwarded_query.as_deref() {- Some(q) if !q.is_empty() => {- format!("{}/{}?{}", base_url, api_path.trim_start_matches('/'), q)- }- _ => format!("{}/{}", base_url, api_path.trim_start_matches('/')),+ Some(q) if !q.is_empty() => format!("{}/{}?{}", effective_base, effective_path, q),+ _ => format!("{}/{}", effective_base, effective_path),};// Audit log