Skip to content

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

fix(connections): distinguish "not connected" from multi-account ambiguity

Louis Beaumont59282010ff9a
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
index 409e9633f..4ac91167d 100644
--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx
+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
@@ -1169,14 +1169,108 @@ function classifyCurl(cmd: string): CurlPresentation | null {
return { label: "Listed connections", connectionIconName: "connections" };
}
if (path.startsWith("/connections/")) {
- const name = path.split("/")[2];
+ const segments = path.split("/").slice(2); // [name, ...sub]
+ const name = segments[0];
+ const sub = segments.slice(1).join("/");
+ const icon = name;
+
+ // --- Gmail-specific labels (the connection has custom endpoints, not a proxy) ---
+ if (name === "gmail") {
+ if (sub === "send" && method === "POST") {
+ const body = curlBodyJson(cmd);
+ const to = typeof body?.to === "string" ? body.to : null;
+ return {
+ label: to ? `Sent email to ${trunc(to, 40)}` : "Sent email via Gmail",
+ connectionIconName: icon,
+ };
+ }
+ if (sub === "messages") {
+ const q = url.searchParams.get("q");
+ return {
+ label: q ? `Searched Gmail "${trunc(q, 30)}"` : "Listed Gmail messages",
+ connectionIconName: icon,
+ };
+ }
+ if (sub.startsWith("messages/")) {
+ return { label: "Read Gmail message", connectionIconName: icon };
+ }
+ if (sub === "instances") {
+ return { label: "Listed Gmail accounts", connectionIconName: icon };
+ }
+ }
+
+ // --- Google Calendar ---
+ if (name === "google-calendar") {
+ if (sub === "events") {
+ return { label: "Listed calendar events", connectionIconName: icon };
+ }
+ if (sub === "status") {
+ return { label: "Checked calendar connection", connectionIconName: icon };
+ }
+ }
+
+ // --- Proxy endpoints (Google Docs/Sheets, Notion, etc.) ---
+ if (sub.startsWith("proxy/")) {
+ const proxyPath = sub.slice("proxy/".length);
+ // Google Docs API
+ if (proxyPath.startsWith("docs/v1/documents")) {
+ if (method === "POST" && proxyPath.endsWith(":batchUpdate")) {
+ return { label: "Edited Google Doc", connectionIconName: icon };
+ }
+ if (method === "POST") {
+ return { label: "Created Google Doc", connectionIconName: icon };
+ }
+ return { label: "Read Google Doc", connectionIconName: icon };
+ }
+ // Drive API (used by google-docs for file listing + creation)
+ if (proxyPath.startsWith("drive/v3/files")) {
+ if (proxyPath.includes("/export")) {
+ return { label: "Exported Drive file", connectionIconName: icon };
+ }
+ if (method === "POST") {
+ return { label: "Created Drive file", connectionIconName: icon };
+ }
+ return { label: "Listed Drive files", connectionIconName: icon };
+ }
+ // Drive resumable/multipart upload
+ if (proxyPath.startsWith("upload/")) {
+ return { label: "Uploaded file to Drive", connectionIconName: icon };
+ }
+ // Google Sheets API
+ if (name === "google-sheets") {
+ if (proxyPath.endsWith(":append")) {
+ return { label: "Appended to sheet", connectionIconName: icon };
+ }
+ if (proxyPath.includes("/values/")) {
+ return {
+ label: method === "GET" ? "Read sheet values" : "Updated sheet values",
+ connectionIconName: icon,
+ };
+ }
+ return { label: "Sheets request", connectionIconName: icon };
+ }
+ // Generic proxy fallback — name the action by verb, not "Configured"
+ if (method === "POST") return { label: `Posted to ${name}`, connectionIconName: icon };
+ if (method === "PATCH" || method === "PUT") {
+ return { label: `Updated via ${name}`, connectionIconName: icon };
+ }
+ return { label: `Read from ${name}`, connectionIconName: icon };
+ }
+
+ // --- Catch-all for connection root + unrecognized subpaths ---
if (method === "DELETE") {
- return { label: `Removed ${name} connection`, connectionIconName: name };
+ return { label: `Removed ${name} connection`, connectionIconName: icon };
+ }
+ // Root POST/PATCH/PUT on /connections/<id> is the actual "configure" action.
+ if (!sub && (method === "POST" || method === "PATCH" || method === "PUT")) {
+ return { label: `Configured ${name} connection`, connectionIconName: icon };
}
- if (method === "POST" || method === "PATCH" || method === "PUT") {
- return { label: `Configured ${name} connection`, connectionIconName: name };
+ // Sub-path POST/PATCH/PUT is an action, not a configuration change.
+ if (method === "POST") return { label: `Posted to ${name}`, connectionIconName: icon };
+ if (method === "PATCH" || method === "PUT") {
+ return { label: `Updated via ${name}`, connectionIconName: icon };
}
- return { label: `${name} connection`, connectionIconName: name };
+ return { label: `${name} connection`, connectionIconName: icon };
}
if (path === "/pipes") {
@@ -1342,7 +1436,23 @@ function endpointFamily(path: string): string {
if (path === "/search") return "Screen search";
if (path === "/activity-summary") return "Activity";
if (path === "/raw_sql") return "Database";
- if (path.startsWith("/connections/")) return "Connection";
+ if (path.startsWith("/connections/")) {
+ // Narrow the chip to the action surface, not just "Connection", so the AI's
+ // user-visible card matches the verb in the title (Sent email → EMAIL).
+ const segments = path.split("/").slice(2);
+ const name = segments[0];
+ const sub = segments.slice(1).join("/");
+ if (name === "gmail" && sub === "send") return "Email";
+ if (name === "gmail") return "Gmail";
+ if (name === "google-calendar") return "Calendar";
+ if (name === "google-docs") return "Doc";
+ if (name === "google-sheets") return "Sheet";
+ if (name === "slack") return "Slack";
+ if (name === "notion") return "Notion";
+ if (name === "telegram") return "Telegram";
+ if (name === "discord") return "Discord";
+ return "Connection";
+ }
if (path.startsWith("/meetings")) return "Meetings";
if (path.startsWith("/speakers")) return "Speakers";
if (path.startsWith("/pipes")) return "Pipes";
@@ -1362,6 +1472,29 @@ function summarizeToolResult(result: string | undefined, family: string): string
const json = parseToolResultJson(result);
if (!json) return result?.trim() ? trunc(result.trim().replace(/\s+/g, " "), 120) : undefined;
+ // Connection-specific successes: read the actual response shape so the
+ // summary reflects what just happened ("Email sent", "Doc created") instead
+ // of the generic "JSON response returned" fallback.
+ if (family.startsWith("/connections/")) {
+ if (family === "/connections/gmail/send" && (json?.data?.id || json?.id || json?.threadId)) {
+ return "Email sent";
+ }
+ if (family.startsWith("/connections/google-docs/proxy/docs/v1/documents")) {
+ if (family.endsWith(":batchUpdate")) return "Document updated";
+ if (json?.documentId) return "Document created";
+ }
+ if (family.startsWith("/connections/google-docs/proxy/drive/v3/files") && json?.id) {
+ return json?.mimeType?.includes("spreadsheet") ? "Spreadsheet created" : "Drive file created";
+ }
+ if (family.startsWith("/connections/google-docs/proxy/upload/drive/v3/files") && json?.id) {
+ return "File uploaded";
+ }
+ if (family.endsWith(":append") && json?.updates?.updatedCells) {
+ return `Appended ${json.updates.updatedCells} cell${json.updates.updatedCells === 1 ? "" : "s"}`;
+ }
+ if (typeof json?.error === "string") return trunc(json.error, 120);
+ }
+
const noun = family === "/memories" ? "memories"
: family === "/search" ? "results"
: family.startsWith("/meetings") ? "meetings"
diff --git a/crates/screenpipe-connect/src/connections/gmail.rs b/crates/screenpipe-connect/src/connections/gmail.rs
index 8ef075da1..bf90425e7 100644
--- a/crates/screenpipe-connect/src/connections/gmail.rs
+++ b/crates/screenpipe-connect/src/connections/gmail.rs
@@ -38,7 +38,10 @@ static DEF: IntegrationDef = IntegrationDef {
Endpoints (all require a connected Gmail account): \
GET /connections/gmail/messages?q=<search>&maxResults=<n>&pageToken=<token> — list/search messages. \
GET /connections/gmail/messages/{id} — read a full message (headers + body). \
- POST /connections/gmail/send {\"to\":\"addr\",\"subject\":\"…\",\"body\":\"…\"} — send an email.",
+ POST /connections/gmail/send {\"to\":\"addr\",\"subject\":\"…\",\"body\":\"…\"} — send an email. \
+ Multi-account: when more than one Gmail account is connected you must pick which one. \
+ Pass `instance=<email>` as a query param on GET endpoints, or include `\"instance\": \"<email>\"` \
+ in the JSON body on POST /send. List connected accounts at GET /connections/gmail/instances.",
fields: &[],
};
diff --git a/crates/screenpipe-connect/src/connections/google_calendar.rs b/crates/screenpipe-connect/src/connections/google_calendar.rs
index fb2cc26ef..bc2d7c799 100644
--- a/crates/screenpipe-connect/src/connections/google_calendar.rs
+++ b/crates/screenpipe-connect/src/connections/google_calendar.rs
@@ -35,7 +35,10 @@ static DEF: IntegrationDef = IntegrationDef {
description: "Read-only access to Google Calendar events via OAuth. \
Endpoints: \
GET /connections/google-calendar/events?hours_back=1&hours_ahead=8 — list upcoming events. \
- GET /connections/google-calendar/status — check connection status and email.",
+ GET /connections/google-calendar/status — check connection status and email. \
+ Multi-account: when more than one Google account is connected you must pick which one — \
+ pass `instance=<email>` as a query param (e.g. /[email protected]&hours_ahead=24). \
+ Without it, the request fails with an ambiguous-account error.",
fields: &[],
};
diff --git a/crates/screenpipe-connect/src/connections/google_docs.rs b/crates/screenpipe-connect/src/connections/google_docs.rs
index d44511023..e875ed818 100644
--- a/crates/screenpipe-connect/src/connections/google_docs.rs
+++ b/crates/screenpipe-connect/src/connections/google_docs.rs
@@ -50,7 +50,8 @@ static DEF: IntegrationDef = IntegrationDef {
POST /connections/google-docs/proxy/docs/v1/documents/{documentId}:batchUpdate — edit an existing doc (requests: insertText, updateTextStyle, etc.). \
GET /connections/google-docs/proxy/drive/v3/files?q=mimeType='application/vnd.google-apps.document' — list Docs the app created or the user opened with screenpipe. \
GET /connections/google-docs/proxy/drive/v3/files/{fileId}/export?mimeType=text/plain — export a Doc as plain text. \
- Uses drive.file scope — only files the user explicitly opens with screenpipe (e.g. by pasting a Doc URL) or that screenpipe creates are visible; this is intentional privacy design.",
+ Uses drive.file scope — only files the user explicitly opens with screenpipe (e.g. by pasting a Doc URL) or that screenpipe creates are visible; this is intentional privacy design. \
+ Multi-account: when more than one Google account is connected, append `?instance=<email>` to any proxy URL to pick which one (the `?` becomes `&` if the path already has a query string).",
fields: &[],
};
diff --git a/crates/screenpipe-connect/src/connections/google_sheets.rs b/crates/screenpipe-connect/src/connections/google_sheets.rs
index 2cb0018ba..f54bc89e3 100644
--- a/crates/screenpipe-connect/src/connections/google_sheets.rs
+++ b/crates/screenpipe-connect/src/connections/google_sheets.rs
@@ -19,7 +19,9 @@ static DEF: IntegrationDef = IntegrationDef {
Useful endpoints: \
GET {spreadsheetId} — get spreadsheet metadata and sheet names. \
GET {spreadsheetId}/values/{range} — read cell values (e.g. Sheet1!A1:Z100). \
- POST {spreadsheetId}/values/{range}:append — append rows to a sheet.",
+ POST {spreadsheetId}/values/{range}:append — append rows to a sheet. \
+ Multi-account: when more than one Google account is connected, append `?instance=<email>` \
+ to any proxy URL to pick which one (the `?` becomes `&` if the path already has a query string).",
fields: &[],
};
diff --git a/crates/screenpipe-connect/src/oauth.rs b/crates/screenpipe-connect/src/oauth.rs
index e1e158715..57d6adeaf 100644
--- a/crates/screenpipe-connect/src/oauth.rs
+++ b/crates/screenpipe-connect/src/oauth.rs
@@ -411,6 +411,46 @@ pub async fn list_connected_oauth_instances(
connected
}
+/// Build a human/AI-readable explanation of why an OAuth lookup failed for
+/// `(integration_id, instance)`. Without this, every miss collapses to the
+/// same "not connected" string — which is wrong (and infuriating) when the
+/// user *is* connected and the real problem is multi-account ambiguity, the
+/// shape that hit Gmail when two accounts were authorized.
+///
+/// Four cases the caller cares about:
+/// - no instances at all → "not connected, please connect"
+/// - one instance, default lookup unhealthy → "instance X token can't refresh, reconnect"
+/// - multiple instances, none specified → "ambiguous: pick one of [X, Y]"
+/// - explicit instance specified but unhealthy → "instance X token can't refresh, reconnect"
+pub async fn describe_oauth_error(
+ store: Option<&SecretStore>,
+ integration_id: &str,
+ display_name: &str,
+ instance: Option<&str>,
+) -> String {
+ let instances: Vec<String> = list_oauth_instances(store, integration_id)
+ .await
+ .into_iter()
+ .flatten()
+ .collect();
+ match (instance, instances.as_slice()) {
+ (Some(inst), _) => format!(
+ "{display_name} account '{inst}' is not connected or its token can't be refreshed — reconnect it in Settings > Connections"
+ ),
+ (None, []) => format!(
+ "{display_name} not connected — use 'Connect {display_name}' in Settings > Connections"
+ ),
+ (None, [only]) => format!(
+ "{display_name} account '{only}' token can't be refreshed — reconnect it in Settings > Connections"
+ ),
+ (None, many) => format!(
+ "multiple {display_name} accounts connected ({}) — specify which one with `instance`. On JSON-body endpoints add `\"instance\": \"<email>\"` to the request body; on proxy/query endpoints add `?instance=<email>` (e.g. instance=\"{}\")",
+ many.join(", "),
+ many[0],
+ ),
+ }
+}
+
// ---------------------------------------------------------------------------
// Write / delete
// ---------------------------------------------------------------------------
diff --git a/crates/screenpipe-engine/src/connections_api.rs b/crates/screenpipe-engine/src/connections_api.rs
index 1ba7161e8..e774edc8a 100644
--- a/crates/screenpipe-engine/src/connections_api.rs
+++ b/crates/screenpipe-engine/src/connections_api.rs
@@ -786,19 +786,24 @@ async fn gmail_send_inner(
gmail_json_or_upstream(resp).await
}
-/// Retrieve a valid Gmail OAuth token or return an error.
+/// Retrieve a valid Gmail OAuth token or return an error. Distinguishes
+/// "not connected" from "ambiguous, multiple accounts connected" so the
+/// caller (AI tool, pipe, user) gets actionable context instead of an
+/// always-wrong "reconnect Gmail" string.
async fn gmail_token(
client: &reqwest::Client,
instance: Option<&str>,
secret_store: &Option<Arc<SecretStore>>,
) -> anyhow::Result<String> {
- oauth_store::get_valid_token_instance(secret_store.as_deref(), client, "gmail", instance)
- .await
- .ok_or_else(|| {
- anyhow::anyhow!(
- "Gmail not connected — use 'Connect with Gmail' in Settings > Connections"
- )
- })
+ let store = secret_store.as_deref();
+ if let Some(token) =
+ oauth_store::get_valid_token_instance(store, client, "gmail", instance).await
+ {
+ return Ok(token);
+ }
+ Err(anyhow::anyhow!(
+ oauth_store::describe_oauth_error(store, "gmail", "Gmail", instance).await
+ ))
}
/// GET /connections/gmail/instances — list all connected Gmail accounts.
@@ -979,24 +984,23 @@ pub struct GoogleCalendarInstanceQuery {
pub instance: Option<String>,
}
-/// Retrieve a valid Google Calendar OAuth token or return an error.
+/// Retrieve a valid Google Calendar OAuth token or return an error. See
+/// [`gmail_token`] for why "not connected" is split into distinct cases.
async fn gcal_token(
client: &reqwest::Client,
instance: Option<&str>,
secret_store: &Option<Arc<SecretStore>>,
) -> anyhow::Result<String> {
- oauth_store::get_valid_token_instance(
- secret_store.as_deref(),
- client,
- "google-calendar",
- instance,
- )
- .await
- .ok_or_else(|| {
- anyhow::anyhow!(
- "Google Calendar not connected — use 'Connect Google Calendar' in Settings > Connections"
- )
- })
+ let store = secret_store.as_deref();
+ if let Some(token) =
+ oauth_store::get_valid_token_instance(store, client, "google-calendar", instance).await
+ {
+ return Ok(token);
+ }
+ Err(anyhow::anyhow!(
+ oauth_store::describe_oauth_error(store, "google-calendar", "Google Calendar", instance)
+ .await
+ ))
}
/// GET /connections/google-calendar/status — check connection + email.
@@ -1055,7 +1059,14 @@ async fn gcal_events(
Ok(events) => (StatusCode::OK, Json(json!(events))),
Err(e) => {
let message = e.to_string();
- let status = if message.contains("Google Calendar not connected") {
+ // Recognize every variant of the OAuth-failure message from
+ // `describe_oauth_error` (not-connected, single-instance broken,
+ // multi-instance ambiguous, explicit-instance broken) and surface
+ // them as 401 so callers can distinguish auth from upstream 5xx.
+ let is_oauth_failure = message.contains("Google Calendar not connected")
+ || message.contains("Google Calendar account")
+ || message.contains("multiple Google Calendar accounts connected");
+ let status = if is_oauth_failure {
StatusCode::UNAUTHORIZED
} else {
StatusCode::INTERNAL_SERVER_ERROR
@@ -1561,11 +1572,33 @@ async fn connection_proxy(
id,
instance_ref
);
- return (
- StatusCode::UNAUTHORIZED,
- Json(json!({ "error": format!("connection '{}' has no stored credentials — connect it first in Settings", id) })),
+ // For OAuth-style integrations (Google Docs/Sheets, etc.) the
+ // generic "no stored credentials" message is wrong when the real
+ // problem is multi-account ambiguity — the user *is* connected,
+ // they just need to pick which account. `describe_oauth_error`
+ // produces the actionable string from the actual instance list.
+ let has_oauth_state = !screenpipe_connect::oauth::list_oauth_instances(
+ state.secret_store.as_deref(),
+ &id,
)
- .into_response();
+ .await
+ .is_empty();
+ let error = if has_oauth_state {
+ let display_name = mgr.find_def(&id).map(|d| d.name).unwrap_or(id.as_str());
+ screenpipe_connect::oauth::describe_oauth_error(
+ state.secret_store.as_deref(),
+ &id,
+ display_name,
+ instance_ref,
+ )
+ .await
+ } else {
+ format!(
+ "connection '{}' has no stored credentials — connect it first in Settings",
+ id
+ )
+ };
+ return (StatusCode::UNAUTHORIZED, Json(json!({ "error": error }))).into_response();
}
// Resolve dynamic base_url