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
feat: multi-account OAuth support for Gmail and other OAuth integrations
Louis Beaumontc574c08ef78a
diff --git a/apps/screenpipe-app-tauri/components/settings/gmail-card.tsx b/apps/screenpipe-app-tauri/components/settings/gmail-card.tsxindex 01b67467f..109ccd17b 100644--- a/apps/screenpipe-app-tauri/components/settings/gmail-card.tsx+++ b/apps/screenpipe-app-tauri/components/settings/gmail-card.tsx@@ -6,43 +6,57 @@import React, { useState, useEffect, useCallback } from "react";import { Card, CardContent } from "@/components/ui/card";import { Button } from "@/components/ui/button";-import { Loader2, LogOut, Mail } from "lucide-react";+import { Loader2, LogOut, Mail, Plus } from "lucide-react";import { commands } from "@/lib/utils/tauri";import posthog from "posthog-js";+interface GmailAccount {+ instance: string | null;+ displayName: string | null;+}+export function GmailCard() {- const [connected, setConnected] = useState(false);- const [email, setEmail] = useState<string | null>(null);+ const [accounts, setAccounts] = useState<GmailAccount[]>([]);const [isConnecting, setIsConnecting] = useState(false);- const [isDisconnecting, setIsDisconnecting] = useState(false);+ const [disconnecting, setDisconnecting] = useState<string | null>(null);- const fetchStatus = useCallback(async () => {+ const fetchAccounts = useCallback(async () => {try {- const res = await commands.oauthStatus("gmail");- if (res.status === "ok" && res.data.connected) {- setConnected(true);- setEmail(res.data.display_name ?? null);- } else {- setConnected(false);- setEmail(null);+ const res = await commands.oauthListInstances("gmail");+ if (res.status === "ok") {+ setAccounts(+ res.data.map((a: any) => ({+ instance: a.instance ?? null,+ displayName: a.display_name ?? null,+ }))+ );}} catch (e) {- console.error("failed to fetch gmail status:", e);+ // fallback: check single default account+ try {+ const res = await commands.oauthStatus("gmail", null);+ if (res.status === "ok" && res.data.connected) {+ setAccounts([{ instance: null, displayName: res.data.display_name ?? null }]);+ } else {+ setAccounts([]);+ }+ } catch {+ setAccounts([]);+ }}}, []);useEffect(() => {- fetchStatus();- }, [fetchStatus]);+ fetchAccounts();+ }, [fetchAccounts]);const handleConnect = async () => {setIsConnecting(true);try {- const res = await commands.oauthConnect("gmail");+ const res = await commands.oauthConnect("gmail", null);if (res.status === "ok" && res.data.connected) {- setConnected(true);- setEmail(res.data.display_name ?? null);posthog.capture("gmail_connected");+ await fetchAccounts();}} catch (e) {console.error("gmail oauth failed:", e);@@ -50,19 +64,21 @@ export function GmailCard() {setIsConnecting(false);};- const handleDisconnect = async () => {- setIsDisconnecting(true);+ const handleDisconnect = async (instance: string | null) => {+ const key = instance ?? "__default__";+ setDisconnecting(key);try {- await commands.oauthDisconnect("gmail");- setConnected(false);- setEmail(null);- posthog.capture("gmail_disconnected");+ await commands.oauthDisconnect("gmail", instance);+ posthog.capture("gmail_disconnected", { instance });+ await fetchAccounts();} catch (e) {console.error("failed to disconnect gmail:", e);}- setIsDisconnecting(false);+ setDisconnecting(null);};+ const connected = accounts.length > 0;+return (<Card className="border-border bg-card overflow-hidden"><CardContent className="p-0">@@ -84,7 +100,7 @@ export function GmailCard() {<h3 className="text-sm font-semibold text-foreground">Gmail</h3>{connected && (<span className="px-2 py-0.5 text-xs font-medium bg-foreground text-background rounded-full">- connected+ {accounts.length} account{accounts.length > 1 ? "s" : ""}</span>)}</div>@@ -98,37 +114,57 @@ export function GmailCard() {.</p>- {!connected ? (- <Button- variant="outline"- size="sm"- onClick={handleConnect}- disabled={isConnecting}- className="text-xs"- >- {isConnecting ? (- <Loader2 className="h-3 w-3 mr-1.5 animate-spin" />- ) : (- <Mail className="h-3 w-3 mr-1.5" />- )}- {isConnecting ? "Waiting for Google..." : "Connect Gmail"}- </Button>- ) : (- <Button- variant="ghost"- size="sm"- onClick={handleDisconnect}- disabled={isDisconnecting}- className="text-xs text-muted-foreground hover:text-destructive h-7 px-2"- >- {isDisconnecting ? (- <Loader2 className="h-3 w-3 mr-1.5 animate-spin" />- ) : (- <LogOut className="h-3 w-3 mr-1.5" />- )}- Disconnect- </Button>+ {/* Connected accounts list */}+ {accounts.length > 0 && (+ <div className="space-y-2 mb-3">+ {accounts.map((account) => {+ const key = account.instance ?? "__default__";+ const isDisconnecting = disconnecting === key;+ return (+ <div key={key} className="flex items-center justify-between gap-2 text-xs">+ <span className="text-muted-foreground truncate">+ {account.displayName || account.instance || "default account"}+ </span>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => handleDisconnect(account.instance)}+ disabled={isDisconnecting}+ className="text-xs text-muted-foreground hover:text-destructive h-6 px-2 shrink-0"+ >+ {isDisconnecting ? (+ <Loader2 className="h-3 w-3 animate-spin" />+ ) : (+ <LogOut className="h-3 w-3" />+ )}+ </Button>+ </div>+ );+ })}+ </div>)}++ {/* Connect / Add account button */}+ <Button+ variant="outline"+ size="sm"+ onClick={handleConnect}+ disabled={isConnecting}+ className="text-xs"+ >+ {isConnecting ? (+ <Loader2 className="h-3 w-3 mr-1.5 animate-spin" />+ ) : connected ? (+ <Plus className="h-3 w-3 mr-1.5" />+ ) : (+ <Mail className="h-3 w-3 mr-1.5" />+ )}+ {isConnecting+ ? "Waiting for Google..."+ : connected+ ? "Add another account"+ : "Connect Gmail"}+ </Button></div></div>@@ -136,8 +172,8 @@ export function GmailCard() {<div className="px-4 py-2 bg-muted/50 border-t border-border"><div className="flex items-center gap-3 text-xs text-muted-foreground"><span>- {connected && email- ? `connected as ${email}`+ {connected+ ? accounts.map((a) => a.displayName || a.instance).filter(Boolean).join(", ") || "connected": "Lets pipes read and send Gmail via the local API"}</span><span className="ml-auto">diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rsindex 820fda44a..8ac494ad7 100755--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs@@ -637,6 +637,7 @@ async fn main() {oauth::oauth_connect,oauth::oauth_status,oauth::oauth_disconnect,+ oauth::oauth_list_instances,// Pipe suggestions scheduler commandspipe_suggestions_scheduler::pipe_suggestions_get_settings,pipe_suggestions_scheduler::pipe_suggestions_update_settings,@@ -901,6 +902,7 @@ async fn main() {oauth::oauth_connect,oauth::oauth_status,oauth::oauth_disconnect,+ oauth::oauth_list_instances,// Pipe suggestions scheduler commandspipe_suggestions_scheduler::pipe_suggestions_get_settings,pipe_suggestions_scheduler::pipe_suggestions_update_settings,diff --git a/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs b/apps/screenpipe-app-tauri/src-tauri/src/oauth.rsindex 39974fc87..941d81c6e 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs@@ -5,7 +5,7 @@//! Generic Tauri commands for OAuth 2.0 authorization_code flows.//!//! Any integration that implements `Integration::oauth_config()` in-//! screenpipe-connect is automatically handled by these three commands.+//! screenpipe-connect is automatically handled by these commands.//! Adding a new OAuth provider requires zero changes here.use screenpipe_connect::connections::all_integrations;@@ -22,17 +22,25 @@ pub struct OAuthStatus {pub display_name: Option<String>,}+#[derive(Serialize, Deserialize, specta::Type, Clone)]+pub struct OAuthInstanceInfo {+ pub instance: Option<String>,+ pub display_name: Option<String>,+}+// ---------------------------------------------------------------------------// Tauri commands// ---------------------------------------------------------------------------/// Start the OAuth flow for any integration that has `oauth_config()` set./// `integration_id` must match the integration's `def().id`.+/// `instance` is an optional name for multi-account support (e.g. email address).#[tauri::command]#[specta::specta]pub async fn oauth_connect(app_handle: AppHandle,integration_id: String,+ instance: Option<String>,) -> Result<OAuthStatus, String> {let integrations = all_integrations();let integration = integrations@@ -44,8 +52,6 @@ pub async fn oauth_connect(.oauth_config().ok_or_else(|| format!("{} does not use OAuth", integration_id))?;- // Register a oneshot channel in the global map so the HTTP callback handler- // can deliver the authorization code back to this waiting task.let state = uuid::Uuid::new_v4().simple().to_string();let (tx, rx) = oneshot::channel::<String>();{@@ -67,27 +73,31 @@ pub async fn oauth_connect(for (k, v) in config.extra_auth_params {pairs.append_pair(k, v);}+ // For Google OAuth, add login_hint to pre-select account+ if let Some(inst) = &instance {+ if config.auth_url.contains("google.com") {+ pairs.append_pair("login_hint", inst);+ }+ }}app_handle.opener().open_url(auth_url.as_str(), None::<&str>).map_err(|e| {- // Clean up the pending entry if we can't open the browserlet mut map = PENDING_OAUTH.lock().unwrap();map.remove(&state);format!("failed to open browser: {}", e)})?;info!(- "waiting for OAuth callback via /connections/oauth/callback ({})",- integration_id+ "waiting for OAuth callback via /connections/oauth/callback ({}, instance={:?})",+ integration_id, instance);let code = tokio::time::timeout(std::time::Duration::from_secs(120), rx).await.map_err(|_| {- // Timed out — remove the stale pending entrylet mut map = PENDING_OAUTH.lock().unwrap();map.remove(&state);format!("{} OAuth timed out (120s)", integration_id)@@ -106,16 +116,30 @@ pub async fn oauth_connect(format!("token exchange failed: {}", e)})?;- oauth::write_oauth_token(&integration_id, &token_data)+ // Auto-derive instance name from email in token response (for Google)+ let effective_instance = instance.or_else(|| {+ token_data["email"].as_str().map(String::from)+ });++ // If this is the first account (no existing instances), store as default (None).+ // Otherwise store with the instance name.+ let existing = oauth::list_oauth_instances(&integration_id);+ let store_instance = if existing.is_empty() {+ None+ } else {+ effective_instance.as_deref().or(Some("default"))+ };++ oauth::write_oauth_token_instance(&integration_id, store_instance, &token_data).map_err(|e| format!("failed to save token: {}", e))?;- // Extract a human-readable display name from the token response if available- let display_name = token_data["workspace_name"]+ let display_name = token_data["email"].as_str()+ .or_else(|| token_data["workspace_name"].as_str()).or_else(|| token_data["name"].as_str()).map(String::from);- info!("OAuth connected: {} ({:?})", integration_id, display_name);+ info!("OAuth connected: {} (instance={:?}, display={:?})", integration_id, store_instance, display_name);Ok(OAuthStatus {connected: true,@@ -126,19 +150,21 @@ pub async fn oauth_connect(/// Check whether a valid (non-expired) OAuth token exists for the given integration.#[tauri::command]#[specta::specta]-pub async fn oauth_status(integration_id: String) -> Result<OAuthStatus, String> {- // read_oauth_token checks expiry — returns None if token is missing or expired- let token = oauth::read_oauth_token(&integration_id);+pub async fn oauth_status(+ integration_id: String,+ instance: Option<String>,+) -> Result<OAuthStatus, String> {+ let token = oauth::read_oauth_token_instance(&integration_id, instance.as_deref());- // Try to read a display name from the stored token filelet display_name = if token.is_some() {- let path = oauth::oauth_token_path(&integration_id);+ let path = oauth::oauth_token_path_instance(&integration_id, instance.as_deref());std::fs::read_to_string(&path).ok().and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok()).and_then(|v| {- v["workspace_name"]+ v["email"].as_str()+ .or_else(|| v["workspace_name"].as_str()).or_else(|| v["name"].as_str()).map(String::from)})@@ -152,12 +178,44 @@ pub async fn oauth_status(integration_id: String) -> Result<OAuthStatus, String>})}-/// Remove the stored OAuth token for the given integration.+/// Remove the stored OAuth token for the given integration instance.#[tauri::command]#[specta::specta]-pub async fn oauth_disconnect(integration_id: String) -> Result<bool, String> {- oauth::delete_oauth_token(&integration_id)+pub async fn oauth_disconnect(+ integration_id: String,+ instance: Option<String>,+) -> Result<bool, String> {+ oauth::delete_oauth_token_instance(&integration_id, instance.as_deref()).map_err(|e| format!("failed to remove token: {}", e))?;- info!("OAuth disconnected: {}", integration_id);+ info!("OAuth disconnected: {} (instance={:?})", integration_id, instance);Ok(true)}++/// List all connected OAuth instances for a given integration.+#[tauri::command]+#[specta::specta]+pub async fn oauth_list_instances(integration_id: String) -> Result<Vec<OAuthInstanceInfo>, String> {+ let instances = oauth::list_oauth_instances(&integration_id);+ let mut result = Vec::new();++ for inst in instances {+ let path = oauth::oauth_token_path_instance(&integration_id, inst.as_deref());+ let display_name = std::fs::read_to_string(&path)+ .ok()+ .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())+ .and_then(|v| {+ v["email"]+ .as_str()+ .or_else(|| v["workspace_name"].as_str())+ .or_else(|| v["name"].as_str())+ .map(String::from)+ });++ result.push(OAuthInstanceInfo {+ instance: inst,+ display_name,+ });+ }++ Ok(result)+}diff --git a/crates/screenpipe-connect/src/connections/mod.rs b/crates/screenpipe-connect/src/connections/mod.rsindex 60bc2d6d9..867d997f6 100644--- a/crates/screenpipe-connect/src/connections/mod.rs+++ b/crates/screenpipe-connect/src/connections/mod.rs@@ -213,7 +213,7 @@ impl ConnectionManager {let def = i.def();let is_oauth = i.oauth_config().is_some();let connected = if is_oauth {- oauth::read_oauth_token(def.id).is_some()+ !oauth::list_oauth_instances(def.id).is_empty()} else {store.get(def.id)diff --git a/crates/screenpipe-connect/src/oauth.rs b/crates/screenpipe-connect/src/oauth.rsindex 520bb75c2..9fa3339db 100644--- a/crates/screenpipe-connect/src/oauth.rs+++ b/crates/screenpipe-connect/src/oauth.rs@@ -80,8 +80,15 @@ pub struct OAuthConfig {// ---------------------------------------------------------------------------pub fn oauth_token_path(integration_id: &str) -> PathBuf {- screenpipe_core::paths::default_screenpipe_data_dir()- .join(format!("{}-oauth.json", integration_id))+ oauth_token_path_instance(integration_id, None)+}++pub fn oauth_token_path_instance(integration_id: &str, instance: Option<&str>) -> PathBuf {+ let name = match instance {+ Some(inst) => format!("{}:{}-oauth.json", integration_id, inst),+ None => format!("{}-oauth.json", integration_id),+ };+ screenpipe_core::paths::default_screenpipe_data_dir().join(name)}fn unix_now() -> u64 {@@ -94,10 +101,13 @@ fn unix_now() -> u64 {/// Read the stored access token, returning `None` if the file is missing/// or the token has expired (with a 60-second safety buffer).pub fn read_oauth_token(integration_id: &str) -> Option<String> {- let content = std::fs::read_to_string(oauth_token_path(integration_id)).ok()?;+ read_oauth_token_instance(integration_id, None)+}++pub fn read_oauth_token_instance(integration_id: &str, instance: Option<&str>) -> Option<String> {+ let content = std::fs::read_to_string(oauth_token_path_instance(integration_id, instance)).ok()?;let v: Value = serde_json::from_str(&content).ok()?;- // If provider stores an expiry, treat the token as absent when expiredif let Some(expires_at) = v["expires_at"].as_u64() {if unix_now() >= expires_at.saturating_sub(60) {return None;@@ -110,7 +120,11 @@ pub fn read_oauth_token(integration_id: &str) -> Option<String> {/// Write the raw provider token response to disk, augmenting it with a/// computed `expires_at` unix timestamp if `expires_in` is present.pub fn write_oauth_token(integration_id: &str, data: &Value) -> Result<()> {- let path = oauth_token_path(integration_id);+ write_oauth_token_instance(integration_id, None, data)+}++pub fn write_oauth_token_instance(integration_id: &str, instance: Option<&str>, data: &Value) -> Result<()> {+ let path = oauth_token_path_instance(integration_id, instance);if let Some(parent) = path.parent() {std::fs::create_dir_all(parent)?;}@@ -123,13 +137,45 @@ pub fn write_oauth_token(integration_id: &str, data: &Value) -> Result<()> {}pub fn delete_oauth_token(integration_id: &str) -> Result<()> {- let path = oauth_token_path(integration_id);+ delete_oauth_token_instance(integration_id, None)+}++pub fn delete_oauth_token_instance(integration_id: &str, instance: Option<&str>) -> Result<()> {+ let path = oauth_token_path_instance(integration_id, instance);if path.exists() {std::fs::remove_file(path)?;}Ok(())}+/// List all OAuth instances for a given integration by scanning token files.+/// Returns a vec of instance names (None = default/unnamed instance).+pub fn list_oauth_instances(integration_id: &str) -> Vec<Option<String>> {+ let dir = screenpipe_core::paths::default_screenpipe_data_dir();+ let prefix = format!("{}", integration_id);+ let suffix = "-oauth.json";+ let mut instances = Vec::new();++ if let Ok(entries) = std::fs::read_dir(&dir) {+ for entry in entries.flatten() {+ let name = entry.file_name().to_string_lossy().to_string();+ if !name.ends_with(suffix) {+ continue;+ }+ let stem = &name[..name.len() - suffix.len()];+ if stem == prefix {+ // Default instance: gmail-oauth.json+ instances.push(None);+ } else if let Some(inst) = stem.strip_prefix(&format!("{}:", prefix)) {+ // Named instance: gmail:work-oauth.json+ instances.push(Some(inst.to_string()));+ }+ }+ }++ instances+}+// ---------------------------------------------------------------------------// Token refresh// ---------------------------------------------------------------------------@@ -137,7 +183,11 @@ pub fn delete_oauth_token(integration_id: &str) -> Result<()> {/// Attempt a token refresh via the backend proxy./// Writes the new token to disk on success, returns the new `access_token`.pub async fn refresh_token(client: &reqwest::Client, integration_id: &str) -> Result<String> {- let content = std::fs::read_to_string(oauth_token_path(integration_id))?;+ refresh_token_instance(client, integration_id, None).await+}++pub async fn refresh_token_instance(client: &reqwest::Client, integration_id: &str, instance: Option<&str>) -> Result<String> {+ let content = std::fs::read_to_string(oauth_token_path_instance(integration_id, instance))?;let stored: Value = serde_json::from_str(&content)?;let refresh_tok = stored["refresh_token"].as_str()@@ -156,7 +206,7 @@ pub async fn refresh_token(client: &reqwest::Client, integration_id: &str) -> Re.json().await?;- write_oauth_token(integration_id, &resp)?;+ write_oauth_token_instance(integration_id, instance, &resp)?;resp["access_token"].as_str()@@ -167,11 +217,14 @@ pub async fn refresh_token(client: &reqwest::Client, integration_id: &str) -> Re/// Read a valid token, refreshing automatically if expired./// Returns `None` only if disconnected with no way to recover.pub async fn get_valid_token(client: &reqwest::Client, integration_id: &str) -> Option<String> {- if let Some(token) = read_oauth_token(integration_id) {+ get_valid_token_instance(client, integration_id, None).await+}++pub async fn get_valid_token_instance(client: &reqwest::Client, integration_id: &str, instance: Option<&str>) -> Option<String> {+ if let Some(token) = read_oauth_token_instance(integration_id, instance) {return Some(token);}- // Token missing or expired — try refresh- refresh_token(client, integration_id).await.ok()+ refresh_token_instance(client, integration_id, instance).await.ok()}// ---------------------------------------------------------------------------diff --git a/crates/screenpipe-engine/src/connections_api.rs b/crates/screenpipe-engine/src/connections_api.rsindex 08e8ce478..d6e3c2232 100644--- a/crates/screenpipe-engine/src/connections_api.rs+++ b/crates/screenpipe-engine/src/connections_api.rs@@ -390,6 +390,12 @@ pub struct GmailMessagesQuery {pub max_results: Option<u32>,#[serde(rename = "pageToken")]pub page_token: Option<String>,+ pub instance: Option<String>,+}++#[derive(Deserialize)]+pub struct GmailInstanceQuery {+ pub instance: Option<String>,}#[derive(Deserialize)]@@ -398,6 +404,7 @@ pub struct GmailSendRequest {pub subject: String,pub body: String,pub from: Option<String>,+ pub instance: Option<String>,}/// GET /connections/gmail/messages — list or search Gmail messages.@@ -405,7 +412,8 @@ async fn gmail_list_messages(Query(params): Query<GmailMessagesQuery>,) -> (StatusCode, Json<Value>) {let client = reqwest::Client::new();- match gmail_list_messages_inner(&client, params).await {+ let instance = params.instance.clone();+ match gmail_list_messages_inner(&client, params, instance.as_deref()).await {Ok(data) => (StatusCode::OK, Json(json!({ "data": data }))),Err(e) => gmail_err(e),}@@ -414,8 +422,9 @@ async fn gmail_list_messages(async fn gmail_list_messages_inner(client: &reqwest::Client,params: GmailMessagesQuery,+ instance: Option<&str>,) -> anyhow::Result<Value> {- let token = gmail_token(client).await?;+ let token = gmail_token(client, instance).await?;let max_results = params.max_results.unwrap_or(20).min(500);let mut url =reqwest::Url::parse("https://gmail.googleapis.com/gmail/v1/users/me/messages").unwrap();@@ -441,16 +450,19 @@ async fn gmail_list_messages_inner(}/// GET /connections/gmail/messages/:id — read a full Gmail message.-async fn gmail_get_message(Path(id): Path<String>) -> (StatusCode, Json<Value>) {+async fn gmail_get_message(+ Path(id): Path<String>,+ Query(q): Query<GmailInstanceQuery>,+) -> (StatusCode, Json<Value>) {let client = reqwest::Client::new();- match gmail_get_message_inner(&client, &id).await {+ match gmail_get_message_inner(&client, &id, q.instance.as_deref()).await {Ok(data) => (StatusCode::OK, Json(json!({ "data": data }))),Err(e) => gmail_err(e),}}-async fn gmail_get_message_inner(client: &reqwest::Client, id: &str) -> anyhow::Result<Value> {- let token = gmail_token(client).await?;+async fn gmail_get_message_inner(client: &reqwest::Client, id: &str, instance: Option<&str>) -> anyhow::Result<Value> {+ let token = gmail_token(client, instance).await?;let url = format!("https://gmail.googleapis.com/gmail/v1/users/me/messages/{}?format=full",id@@ -469,7 +481,8 @@ async fn gmail_get_message_inner(client: &reqwest::Client, id: &str) -> anyhow::/// POST /connections/gmail/send — send an email via Gmail.async fn gmail_send(Json(body): Json<GmailSendRequest>) -> (StatusCode, Json<Value>) {let client = reqwest::Client::new();- match gmail_send_inner(&client, body).await {+ let instance = body.instance.clone();+ match gmail_send_inner(&client, body, instance.as_deref()).await {Ok(data) => (StatusCode::OK, Json(json!({ "data": data }))),Err(e) => gmail_err(e),}@@ -478,8 +491,9 @@ async fn gmail_send(Json(body): Json<GmailSendRequest>) -> (StatusCode, Json<Valasync fn gmail_send_inner(client: &reqwest::Client,body: GmailSendRequest,+ instance: Option<&str>,) -> anyhow::Result<Value> {- let token = gmail_token(client).await?;+ let token = gmail_token(client, instance).await?;let from = body.from.unwrap_or_default();let raw = build_rfc2822_message(&from, &body.to, &body.subject, &body.body);let encoded = URL_SAFE_NO_PAD.encode(raw.as_bytes());@@ -496,12 +510,30 @@ async fn gmail_send_inner(}/// Retrieve a valid Gmail OAuth token or return an error.-async fn gmail_token(client: &reqwest::Client) -> anyhow::Result<String> {- oauth_store::get_valid_token(client, "gmail")+async fn gmail_token(client: &reqwest::Client, instance: Option<&str>) -> anyhow::Result<String> {+ oauth_store::get_valid_token_instance(client, "gmail", instance).await.ok_or_else(|| anyhow::anyhow!("Gmail not connected — use 'Connect with Gmail' in Settings > Connections"))}+/// GET /connections/gmail/instances — list all connected Gmail accounts.+async fn gmail_list_instances() -> (StatusCode, Json<Value>) {+ let instances = oauth_store::list_oauth_instances("gmail");+ let mut accounts = Vec::new();+ for inst in instances {+ let path = oauth_store::oauth_token_path_instance("gmail", inst.as_deref());+ let email = std::fs::read_to_string(&path)+ .ok()+ .and_then(|s| serde_json::from_str::<Value>(&s).ok())+ .and_then(|v| v["email"].as_str().map(String::from));+ accounts.push(json!({+ "instance": inst,+ "email": email,+ }));+ }+ (StatusCode::OK, Json(json!({ "data": accounts })))+}+/// Convert an anyhow error into the standard `(StatusCode, Json)` handler return.fn gmail_err(e: anyhow::Error) -> (StatusCode, Json<Value>) {(@@ -670,6 +702,7 @@ where.route("/calendar/events", get(calendar_events)).route("/calendar/status", get(calendar_status))// Gmail-specific routes (must be before /:id to avoid conflict)+ .route("/gmail/instances", get(gmail_list_instances)).route("/gmail/messages", get(gmail_list_messages)).route("/gmail/messages/:id", get(gmail_get_message)).route("/gmail/send", post(gmail_send))