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: restore multi-instance connections
Louis Beaumont5746c4ea18a6
diff --git a/apps/screenpipe-app-tauri/components/settings/connections-section.tsx b/apps/screenpipe-app-tauri/components/settings/connections-section.tsxindex d5c1d4a8a..fc4d700e2 100644--- a/apps/screenpipe-app-tauri/components/settings/connections-section.tsx+++ b/apps/screenpipe-app-tauri/components/settings/connections-section.tsx@@ -11,7 +11,7 @@ import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";import { Dialog, DialogClose, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";-import { Download, ExternalLink, Check, Loader2, Copy, Terminal, Lock, LogIn, LogOut, Send, X, HelpCircle, Search, Calendar as CalendarIcon, Eye, EyeOff, FolderOpen } from "lucide-react";+import { Download, ExternalLink, Check, Loader2, Copy, Terminal, Lock, LogIn, LogOut, Send, X, HelpCircle, Search, Calendar as CalendarIcon, Eye, EyeOff, FolderOpen, Plus } from "lucide-react";import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";import { commands } from "@/lib/utils/tauri";import { useSettings, getStore } from "@/lib/hooks/use-settings";@@ -1191,6 +1191,11 @@ function ChatGptPanel() {// Generic OAuth panel — used for any integration with is_oauth: true// ---------------------------------------------------------------------------+interface OAuthAccount {+ instance: string | null;+ displayName: string | null;+}+function OAuthPanel({integrationId,integrationName,@@ -1204,8 +1209,9 @@ function OAuthPanel({}) {const { settings } = useSettings();const isPro = !!settings.user?.cloud_subscribed;- const [status, setStatus] = useState<"idle" | "loading" | "connected">("idle");- const [displayName, setDisplayName] = useState<string | null>(null);+ const [status, setStatus] = useState<"idle" | "loading">("idle");+ const [accounts, setAccounts] = useState<OAuthAccount[]>([]);+ const [disconnecting, setDisconnecting] = useState<string | null>(null);// Ref guard so a cancelled or timed-out connect attempt doesn't update state after cancel.const connectingRef = useRef(false);@@ -1214,18 +1220,25 @@ function OAuthPanel({// Try list instances first for richer infoconst listRes = await commands.oauthListInstances(integrationId);if (listRes.status === "ok" && listRes.data.length > 0) {- setStatus("connected");- setDisplayName(listRes.data.map(i => i.display_name || i.instance).filter(Boolean).join(", ") || null);+ setAccounts(+ listRes.data.map((i) => ({+ instance: i.instance ?? null,+ displayName: i.display_name ?? null,+ }))+ );return;}} catch { /* fallback below */ }try {const res = await commands.oauthStatus(integrationId, null);if (res.status === "ok" && res.data.connected) {- setStatus("connected");- setDisplayName(res.data.display_name ?? null);+ setAccounts([{ instance: null, displayName: res.data.display_name ?? null }]);+ } else {+ setAccounts([]);}- } catch { /* ignore */ }+ } catch {+ setAccounts([]);+ }}, [integrationId]);useEffect(() => { fetchStatus(); }, [fetchStatus]);@@ -1237,8 +1250,8 @@ function OAuthPanel({const res = await commands.oauthConnect(integrationId, null);if (!connectingRef.current) return; // cancelled — handleCancel owns the UIif (res.status === "ok" && res.data.connected) {- setStatus("connected");await fetchStatus();+ apiCache.invalidate("connections/list");onConnected?.();} else {setStatus("idle");@@ -1247,6 +1260,7 @@ function OAuthPanel({if (connectingRef.current) setStatus("idle");} finally {connectingRef.current = false;+ setStatus("idle");}};@@ -1261,24 +1275,58 @@ function OAuthPanel({setStatus("idle");};- const handleDisconnect = async () => {- await commands.oauthDisconnect(integrationId, null);- setStatus("idle");- setDisplayName(null);- onDisconnected?.();+ const handleDisconnect = async (instance: string | null) => {+ const key = instance ?? "__default__";+ setDisconnecting(key);+ const remainingAccounts = accounts.filter(account => (account.instance ?? "__default__") !== key);+ try {+ await commands.oauthDisconnect(integrationId, instance ?? null);+ setAccounts(remainingAccounts);+ await fetchStatus();+ apiCache.invalidate("connections/list");+ if (remainingAccounts.length === 0) {+ onDisconnected?.();+ } else {+ onConnected?.();+ }+ } finally {+ setDisconnecting(null);+ }};+ const connected = accounts.length > 0;+return (<div className="space-y-3"><p className="text-xs text-muted-foreground">Connect your {integrationName} account. AI can act on your behalf once connected.</p>+ {connected && (+ <div className="space-y-2">+ {accounts.map((account) => {+ const key = account.instance ?? "__default__";+ const isDisconnecting = disconnecting === key;+ return (+ <div key={key} className="flex items-center justify-between gap-2 rounded-md border border-border bg-muted/40 px-2.5 py-2 text-xs">+ <span className="text-muted-foreground truncate">+ {account.displayName || account.instance || "default account"}+ </span>+ <Button+ onClick={() => handleDisconnect(account.instance)}+ disabled={isDisconnecting}+ variant="ghost"+ size="sm"+ className="h-6 px-2 shrink-0 text-muted-foreground hover:text-destructive"+ >+ {isDisconnecting ? <Loader2 className="h-3 w-3 animate-spin" /> : <LogOut className="h-3 w-3" />}+ </Button>+ </div>+ );+ })}+ </div>+ )}<div className="flex flex-wrap gap-2">- {status === "connected" ? (- <Button onClick={handleDisconnect} variant="outline" size="sm" className="gap-1.5 h-7 text-xs normal-case font-sans tracking-normal">- <LogOut className="h-3 w-3" />disconnect{displayName ? ` (${displayName})` : ""}- </Button>- ) : !isPro ? (+ {!isPro && !connected ? (<div className="flex flex-col gap-1.5"><Button disabled size="sm" className="gap-1.5 h-7 text-xs normal-case font-sans tracking-normal whitespace-nowrap opacity-60"><Lock className="h-3 w-3" />pro required@@ -1301,16 +1349,12 @@ function OAuthPanel({</div>) : (<Button onClick={handleConnect} size="sm" className="gap-1.5 h-7 text-xs normal-case font-sans tracking-normal whitespace-nowrap">- <LogIn className="h-3 w-3" />connect with {integrationName}+ {connected+ ? (<><Plus className="h-3 w-3" />add another account</>)+ : (<><LogIn className="h-3 w-3" />connect with {integrationName}</>)}</Button>)}</div>- {status === "connected" && displayName && (- <div className="p-3 bg-muted border border-border rounded-lg">- <p className="text-xs font-medium text-foreground">connected</p>- <p className="text-xs text-muted-foreground">{displayName}</p>- </div>- )}</div>);}@@ -1687,10 +1731,9 @@ interface InstanceData {credentials: Record<string, string>;}-function ApiIntegrationPanel({ integration, onRefresh, onDisconnected }: {+function ApiIntegrationPanel({ integration, onRefresh }: {integration: IntegrationInfo;onRefresh: () => void;- onDisconnected?: () => void;}) {const [instances, setInstances] = useState<InstanceData[]>([]);const [instancesLoaded, setInstancesLoaded] = useState(false);@@ -1741,7 +1784,6 @@ function ApiIntegrationPanel({ integration, onRefresh, onDisconnected }: {const refreshAll = (disconnected = false) => {if (disconnected) {setDefaultCreds({});- onDisconnected?.();}onRefresh();// Re-fetch instances@@ -2055,7 +2097,6 @@ export function ConnectionsSection() {return <ApiIntegrationPanelintegration={selectedIntegration}onRefresh={fetchIntegrations}- onDisconnected={() => setIntegrations(prev => prev.map(i => i.id === selectedIntegration.id ? { ...i, connected: false } : i))}/>;}// Fall-through: hardcoded tile but the API hasn't returned (or returned withoutdiff --git a/apps/screenpipe-app-tauri/components/settings/google-calendar-card.tsx b/apps/screenpipe-app-tauri/components/settings/google-calendar-card.tsxindex 631cea545..e17607f50 100644--- a/apps/screenpipe-app-tauri/components/settings/google-calendar-card.tsx+++ b/apps/screenpipe-app-tauri/components/settings/google-calendar-card.tsx@@ -10,11 +10,11 @@ import { Label } from "@/components/ui/label";import { Button } from "@/components/ui/button";import {Loader2,+ Plus,RefreshCw,Users,LogOut,} from "lucide-react";-import { fetch as tauriFetch } from "@tauri-apps/plugin-http";import { commands } from "@/lib/utils/tauri";import posthog from "posthog-js";import { localFetch } from "@/lib/api";@@ -32,14 +32,18 @@ interface CalendarEventItem {isAllDay: boolean;}+interface CalendarAccount {+ instance: string | null;+ displayName: string | null;+}+export function GoogleCalendarCard({ onConnected, onDisconnected }: { onConnected?: () => void; onDisconnected?: () => void } = {}) {- const [connected, setConnected] = useState(false);- const [email, setEmail] = useState<string | null>(null);+ const [accounts, setAccounts] = useState<CalendarAccount[]>([]);const [isConnecting, setIsConnecting] = useState(false);const [enabled, setEnabled] = useState(false);const [upcomingEvents, setUpcomingEvents] = useState<CalendarEventItem[]>([]);const [isLoadingEvents, setIsLoadingEvents] = useState(false);- const [isDisconnecting, setIsDisconnecting] = useState(false);+ const [disconnecting, setDisconnecting] = useState<string | null>(null);// Load enabled state from localStorageuseEffect(() => {@@ -60,11 +64,30 @@ export function GoogleCalendarCard({ onConnected, onDisconnected }: { onConnecte// Fetch connection status via local OAuthconst fetchStatus = useCallback(async () => {try {+ const list = await commands.oauthListInstances("google-calendar");+ if (list.status === "ok" && list.data.length > 0) {+ setAccounts(+ list.data.map((i) => ({+ instance: i.instance ?? null,+ displayName: i.display_name ?? null,+ }))+ );+ if (!enabled) {+ const stored = localStorage?.getItem("google-calendar-enabled");+ if (stored === null) {+ setEnabled(true);+ try {+ localStorage?.setItem("google-calendar-enabled", "true");+ } catch {}+ }+ }+ return;+ }+const status = await commands.oauthStatus("google-calendar", null);- if (status.status === "ok") {- setConnected(status.data.connected);- setEmail(status.data.display_name ?? null);- if (status.data.connected && !enabled) {+ if (status.status === "ok" && status.data.connected) {+ setAccounts([{ instance: null, displayName: status.data.display_name ?? null }]);+ if (!enabled) {const stored = localStorage?.getItem("google-calendar-enabled");if (stored === null) {setEnabled(true);@@ -73,9 +96,12 @@ export function GoogleCalendarCard({ onConnected, onDisconnected }: { onConnecte} catch {}}}+ } else {+ setAccounts([]);}} catch (e) {console.error("failed to fetch google calendar status:", e);+ setAccounts([]);}}, [enabled]);@@ -83,42 +109,58 @@ export function GoogleCalendarCard({ onConnected, onDisconnected }: { onConnectefetchStatus();}, [fetchStatus]);+ const connected = accounts.length > 0;+// Fetch upcoming events via local APIconst fetchEvents = useCallback(async () => {setIsLoadingEvents(true);try {- const res = await localFetch(- `/connections/google-calendar/events?hours_back=0&hours_ahead=8`,- { method: "GET" }+ const connectedAccounts = accounts.length > 0 ? accounts : [{ instance: null, displayName: null }];+ const eventGroups = await Promise.all(+ connectedAccounts.map(async (account) => {+ const params = new URLSearchParams({ hours_back: "0", hours_ahead: "8" });+ if (account.instance) params.set("instance", account.instance);++ const res = await localFetch(+ `/connections/google-calendar/events?${params.toString()}`,+ { method: "GET" }+ );+ if (!res.ok) return [];++ const raw: CalendarEventItem[] = await res.json();+ const accountLabel = account.displayName || account.instance;+ return raw.map((e) => ({+ ...e,+ calendarName: connectedAccounts.length > 1 && accountLabel+ ? accountLabel+ : e.calendarName,+ startDisplay: e.start+ ? new Date(e.start).toLocaleTimeString("en-US", {+ hour: "numeric",+ minute: "2-digit",+ hour12: true,+ })+ : "",+ endDisplay: e.end+ ? new Date(e.end).toLocaleTimeString("en-US", {+ hour: "numeric",+ minute: "2-digit",+ hour12: true,+ })+ : "",+ }));+ }));- if (res.ok) {- const raw: CalendarEventItem[] = await res.json();- const events = raw.map((e) => ({- ...e,- startDisplay: e.start- ? new Date(e.start).toLocaleTimeString("en-US", {- hour: "numeric",- minute: "2-digit",- hour12: true,- })- : "",- endDisplay: e.end- ? new Date(e.end).toLocaleTimeString("en-US", {- hour: "numeric",- minute: "2-digit",- hour12: true,- })- : "",- }));- setUpcomingEvents(events.filter((e) => !e.isAllDay).slice(0, 5));- } else {- setUpcomingEvents([]);- }+ const events = eventGroups+ .flat()+ .filter((e) => !e.isAllDay)+ .sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime());+ setUpcomingEvents(events.slice(0, 5));} catch {setUpcomingEvents([]);}setIsLoadingEvents(false);- }, []);+ }, [accounts]);// Fetch events when connected + enableduseEffect(() => {@@ -148,21 +190,29 @@ export function GoogleCalendarCard({ onConnected, onDisconnected }: { onConnecte};// Disconnect flow- const handleDisconnect = async () => {- setIsDisconnecting(true);+ const handleDisconnect = async (instance: string | null) => {+ const key = instance ?? "__default__";+ setDisconnecting(key);+ const remainingAccounts = accounts.filter(account => (account.instance ?? "__default__") !== key);try {- await commands.oauthDisconnect("google-calendar", null);- setConnected(false);- setEmail(null);- setUpcomingEvents([]);+ await commands.oauthDisconnect("google-calendar", instance ?? null);+ setAccounts(remainingAccounts);+ await fetchStatus();posthog.capture("google_calendar_disconnected");- onDisconnected?.();+ if (remainingAccounts.length === 0) {+ onDisconnected?.();+ } else {+ onConnected?.();+ }} catch (e) {console.error("failed to disconnect google calendar:", e);}- setIsDisconnecting(false);+ setDisconnecting(null);};+ const primaryAccount = accounts[0];+ const accountLabel = primaryAccount?.displayName || primaryAccount?.instance || null;+const isHappeningNow = (start: string, end: string) => {const now = Date.now();return new Date(start).getTime() <= now && new Date(end).getTime() >= now;@@ -223,19 +273,48 @@ export function GoogleCalendarCard({ onConnected, onDisconnected }: { onConnecte</Label></div>+ {accounts.length > 0 && (+ <div className="space-y-2">+ {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>+ )}+<Buttonvariant="ghost"size="sm"- onClick={handleDisconnect}- disabled={isDisconnecting}- className="text-xs text-muted-foreground hover:text-destructive h-7 px-2"+ onClick={handleConnect}+ disabled={isConnecting}+ className="text-xs h-7 px-2">- {isDisconnecting ? (+ {isConnecting ? (<Loader2 className="h-3 w-3 mr-1.5 animate-spin" />) : (- <LogOut className="h-3 w-3 mr-1.5" />+ <Plus className="h-3 w-3 mr-1.5" />)}- Disconnect+ {isConnecting ? "Waiting for Google..." : "Add another account"}</Button></div>)}@@ -316,7 +395,7 @@ export function GoogleCalendarCard({ onConnected, onDisconnected }: { onConnecte</span>)}</div>- <span className="shrink-0 text-muted-foreground">+ <span className="shrink-0 max-w-[120px] truncate text-muted-foreground" title={event.calendarName}>{event.calendarName}</span></div>@@ -332,8 +411,10 @@ export function GoogleCalendarCard({ onConnected, onDisconnected }: { onConnecte<div className="flex items-center gap-3 text-xs text-muted-foreground"><span>{connected && enabled- ? `synced as ${email}`+ ? accounts.length > 1+ ? `${accounts.length} accounts synced`+ : accountLabel+ ? `synced as ${accountLabel}`: "calendar synced": "Enriches meeting detection with Google Calendar context"}</span>diff --git a/crates/screenpipe-connect/src/connections/gmail.rs b/crates/screenpipe-connect/src/connections/gmail.rsindex cc81a6d75..8ef075da1 100644--- a/crates/screenpipe-connect/src/connections/gmail.rs+++ b/crates/screenpipe-connect/src/connections/gmail.rs@@ -24,7 +24,7 @@ static OAUTH: OAuthConfig = OAuthConfig {https://www.googleapis.com/auth/userinfo.email",),("access_type", "offline"),- ("prompt", "consent"),+ ("prompt", "consent select_account"),],redirect_uri_override: None,};diff --git a/crates/screenpipe-connect/src/connections/google_calendar.rs b/crates/screenpipe-connect/src/connections/google_calendar.rsindex 6ec12fa8a..fb2cc26ef 100644--- a/crates/screenpipe-connect/src/connections/google_calendar.rs+++ b/crates/screenpipe-connect/src/connections/google_calendar.rs@@ -22,7 +22,7 @@ static OAUTH: OAuthConfig = OAuthConfig {https://www.googleapis.com/auth/userinfo.email",),("access_type", "offline"),- ("prompt", "consent"),+ ("prompt", "consent select_account"),],redirect_uri_override: None,};diff --git a/crates/screenpipe-connect/src/connections/mod.rs b/crates/screenpipe-connect/src/connections/mod.rsindex c949e64ce..d7df8fb39 100644--- a/crates/screenpipe-connect/src/connections/mod.rs+++ b/crates/screenpipe-connect/src/connections/mod.rs@@ -73,7 +73,7 @@ use async_trait::async_trait;use screenpipe_secrets::SecretStore;use serde::{Deserialize, Serialize};use serde_json::{Map, Value};-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};use std::path::{Path, PathBuf};use std::sync::Arc;@@ -402,9 +402,13 @@ impl ConnectionManager {}any_connected} else {- load_connection(ss, &self.screenpipe_dir, def.id)+ self.get_all_instances(def.id).await- .map(|c| c.enabled && !c.credentials.is_empty())+ .map(|instances| {+ instances+ .into_iter()+ .any(|(_, c)| c.enabled && !c.credentials.is_empty())+ }).unwrap_or(false)};result.push(ConnectionInfo {@@ -432,9 +436,18 @@ impl ConnectionManager {}pub async fn get_credentials(&self, id: &str) -> Result<Option<Map<String, Value>>> {+ self.get_credentials_instance(id, None).await+ }++ pub async fn get_credentials_instance(+ &self,+ id: &str,+ instance: Option<&str>,+ ) -> Result<Option<Map<String, Value>>> {self.find(id)?;+ let key = make_key(id, instance);Ok(- load_connection(self.secret_store.as_deref(), &self.screenpipe_dir, id)+ load_connection(self.secret_store.as_deref(), &self.screenpipe_dir, &key).await.map(|c| c.credentials),)@@ -509,47 +522,7 @@ impl ConnectionManager {id: &str,) -> Result<Vec<(Option<String>, SavedConnection)>> {self.find(id)?;- let mut results = Vec::new();- let mut seen = std::collections::HashSet::new();-- // Check SecretStore first- if let Some(ss) = self.secret_store.as_deref() {- let prefix = format!("cred:{}", id);- if let Ok(keys) = ss.list(&prefix).await {- for key in keys {- if key == prefix {- if let Ok(Some(conn)) = ss.get_json::<SavedConnection>(&key).await {- seen.insert(None::<String>);- results.push((None, conn));- }- } else if let Some(inst) = key.strip_prefix(&format!("{}:", prefix)) {- let inst = inst.to_string();- if let Ok(Some(conn)) = ss.get_json::<SavedConnection>(&key).await {- seen.insert(Some(inst.clone()));- results.push((Some(inst), conn));- }- }- }- }- }-- // Fall back to file for any not found in store- let file_store = load_store(&self.screenpipe_dir);- let prefix = format!("{}:", id);- for (key, conn) in &file_store {- if key == id {- if seen.insert(None::<String>) {- results.push((None, conn.clone()));- }- } else if let Some(inst) = key.strip_prefix(&prefix) {- let inst = inst.to_string();- if seen.insert(Some(inst.clone())) {- results.push((Some(inst), conn.clone()));- }- }- }-- Ok(results)+ Ok(load_all_instances(self.secret_store.as_deref(), &self.screenpipe_dir, id).await)}/// Remove a specific instance (or the default) for the given integration.@@ -591,26 +564,29 @@ pub async fn render_context(let mut cred_connected: Vec<(&dyn Integration,&'static IntegrationDef,+ Option<String>,Map<String, Value>,)> = Vec::new();- for i in integrations.iter().filter(|i| i.oauth_config().is_none()) {- let def = i.def();- if let Some(conn) = load_connection(secret_store, screenpipe_dir, def.id).await {+ for integration in integrations.iter().filter(|i| i.oauth_config().is_none()) {+ let def = integration.def();+ for (instance, conn) in load_all_instances(secret_store, screenpipe_dir, def.id).await {if conn.enabled && !conn.credentials.is_empty() {- cred_connected.push((i.as_ref(), def, conn.credentials));+ cred_connected.push((integration.as_ref(), def, instance, conn.credentials));}}}// OAuth integrations with a stored token- let mut oauth_connected: Vec<(&dyn Integration, &'static IntegrationDef)> = Vec::new();- for i in integrations.iter().filter(|i| i.oauth_config().is_some()) {- let def = i.def();- if oauth::read_oauth_token_instance(secret_store, def.id, None)- .await- .is_some()- {- oauth_connected.push((i.as_ref(), def));+ let mut oauth_connected: Vec<(&dyn Integration, &'static IntegrationDef, Option<String>)> =+ Vec::new();+ for integration in integrations.iter().filter(|i| i.oauth_config().is_some()) {+ let def = integration.def();+ let mut instances = oauth::list_oauth_instances(secret_store, def.id).await;+ instances.sort();+ for instance in instances {+ if oauth::is_oauth_instance_connected(secret_store, def.id, instance.as_deref()).await {+ oauth_connected.push((integration.as_ref(), def, instance));+ }}}@@ -625,18 +601,19 @@ pub async fn render_context(The proxy injects authentication automatically. NEVER fetch or use raw API keys.\n",);- for (integration, def, creds) in &cred_connected {- out.push_str(&format!("\n## {} ({})\n", def.name, def.id));+ for (integration, def, instance, creds) in &cred_connected {+ out.push_str(&connection_context_header(def, instance.as_deref()));out.push_str(&format!("{}\n", def.description));if integration.proxy_config().is_some() {+ let suffix = instance_query(instance.as_deref());out.push_str(&format!(- " proxy: {}/{}/proxy/ (append the API path, e.g. /v1/pages)\n",- base, def.id+ " proxy: {}/{}/proxy/<api-path>{} (append the API path, e.g. /v1/pages)\n",+ base, def.id, suffix));out.push_str(&format!(- " config: {}/{}/config (non-secret settings)\n",- base, def.id+ " config: {}/{}/config{} (non-secret settings)\n",+ base, def.id, suffix));} else {// No proxy config — fall back to raw credentials (webhook-style integrations)@@ -648,18 +625,19 @@ pub async fn render_context(}}- for (integration, def) in &oauth_connected {- out.push_str(&format!("\n## {} ({})\n", def.name, def.id));+ for (integration, def, instance) in &oauth_connected {+ out.push_str(&connection_context_header(def, instance.as_deref()));out.push_str(&format!("{}\n", def.description));if integration.proxy_config().is_some() {+ let suffix = instance_query(instance.as_deref());out.push_str(&format!(- " proxy: {}/{}/proxy/ (append the API path, e.g. /v1/pages)\n",- base, def.id+ " proxy: {}/{}/proxy/<api-path>{} (append the API path, e.g. /v1/pages)\n",+ base, def.id, suffix));out.push_str(&format!(- " config: {}/{}/config (non-secret settings)\n",- base, def.id+ " config: {}/{}/config{} (non-secret settings)\n",+ base, def.id, suffix));} else {// OAuth without proxy — still don't expose the token@@ -693,6 +671,82 @@ fn make_key(id: &str, instance: Option<&str>) -> String {}}+async fn load_all_instances(+ secret_store: Option<&SecretStore>,+ screenpipe_dir: &Path,+ id: &str,+) -> Vec<(Option<String>, SavedConnection)> {+ let mut instances = Vec::new();+ let mut seen = HashSet::new();++ if let Some(store) = secret_store {+ let prefix = format!("cred:{}", id);+ if let Ok(keys) = store.list(&prefix).await {+ for key in keys {+ if key == prefix {+ if let Ok(Some(conn)) = store.get_json::<SavedConnection>(&key).await {+ if seen.insert(None::<String>) {+ instances.push((None, conn));+ }+ }+ } else if let Some(inst) = key.strip_prefix(&format!("{}:", prefix)) {+ let inst = inst.to_string();+ if let Ok(Some(conn)) = store.get_json::<SavedConnection>(&key).await {+ if seen.insert(Some(inst.clone())) {+ instances.push((Some(inst), conn));+ }+ }+ }+ }+ }+ }++ let store = load_store(screenpipe_dir);+ let prefix = format!("{}:", id);+ for (key, conn) in store {+ if key == id {+ if seen.insert(None::<String>) {+ instances.push((None, conn));+ }+ } else if let Some(inst) = key.strip_prefix(&prefix) {+ let inst = inst.to_string();+ if seen.insert(Some(inst.clone())) {+ instances.push((Some(inst), conn));+ }+ }+ }++ instances.sort_by(|(a, _), (b, _)| a.cmp(b));+ instances+}++fn connection_context_header(def: &'static IntegrationDef, instance: Option<&str>) -> String {+ match instance {+ Some(instance) => format!("\n## {} ({}, instance: {})\n", def.name, def.id, instance),+ None => format!("\n## {} ({})\n", def.name, def.id),+ }+}++fn instance_query(instance: Option<&str>) -> String {+ match instance {+ Some(instance) => format!("?instance={}", percent_encode_query_value(instance)),+ None => String::new(),+ }+}++fn percent_encode_query_value(value: &str) -> String {+ let mut encoded = String::new();+ for byte in value.bytes() {+ match byte {+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {+ encoded.push(byte as char);+ }+ _ => encoded.push_str(&format!("%{:02X}", byte)),+ }+ }+ encoded+}+// ---------------------------------------------------------------------------// Helpers// ---------------------------------------------------------------------------@@ -702,3 +756,66 @@ pub fn require_str<'a>(map: &'a Map<String, Value>, key: &str) -> Result<&'a str.and_then(|v| v.as_str()).ok_or_else(|| anyhow::anyhow!("missing required field: {}", key))}++#[cfg(test)]+mod tests {+ use super::*;++ fn temp_screenpipe_dir() -> PathBuf {+ let dir = std::env::temp_dir().join(format!(+ "screenpipe-connect-test-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ std::fs::create_dir_all(&dir).unwrap();+ dir+ }++ fn creds() -> Map<String, Value> {+ let mut creds = Map::new();+ creds.insert(+ "api_key".to_string(),+ Value::String("test-token".to_string()),+ );+ creds+ }++ #[tokio::test]+ async fn named_manual_instances_count_as_connected() {+ let dir = temp_screenpipe_dir();+ let mgr = ConnectionManager::new(dir.clone(), None);++ mgr.connect_instance("slack", Some("work"), creds())+ .await+ .unwrap();++ let slack = mgr+ .list()+ .await+ .into_iter()+ .find(|connection| connection.def.id == "slack")+ .unwrap();+ assert!(slack.connected);++ let _ = std::fs::remove_dir_all(dir);+ }++ #[tokio::test]+ async fn render_context_includes_named_manual_instances() {+ let dir = temp_screenpipe_dir();+ let mgr = ConnectionManager::new(dir.clone(), None);++ mgr.connect_instance("slack", Some("work"), creds())+ .await+ .unwrap();++ let context = render_context(&dir, 3030, None).await;+ assert!(context.contains("## Slack (slack, instance: work)"));+ assert!(context.contains("api_key: test-token"));++ let _ = std::fs::remove_dir_all(dir);+ }+}diff --git a/crates/screenpipe-engine/src/connections_api.rs b/crates/screenpipe-engine/src/connections_api.rsindex 1e703ce48..d99ebb839 100644--- a/crates/screenpipe-engine/src/connections_api.rs+++ b/crates/screenpipe-engine/src/connections_api.rs@@ -1336,6 +1336,32 @@ fn resolve_auth(}}+fn split_instance_query(raw_query: Option<&str>) -> (Option<String>, Option<String>) {+ let Some(query) = raw_query.filter(|q| !q.is_empty()) else {+ return (None, None);+ };++ let mut instance = None;+ let mut has_forwarded_query = false;+ let mut forwarded = url::form_urlencoded::Serializer::new(String::new());++ for (key, value) in url::form_urlencoded::parse(query.as_bytes()) {+ let key = key.into_owned();+ let value = value.into_owned();+ if key == "instance" && instance.is_none() {+ if !value.is_empty() {+ instance = Some(value);+ }+ } else {+ forwarded.append_pair(&key, &value);+ has_forwarded_query = true;+ }+ }++ let forwarded_query = has_forwarded_query.then(|| forwarded.finish());+ (instance, forwarded_query)+}+/// Proxy handler: forward requests to third-party APIs with credentials injected./// Route: ANY /connections/:id/proxy/*path///@@ -1368,6 +1394,8 @@ async fn connection_proxy(.into_response();}+ let (instance, forwarded_query) = split_instance_query(raw_query.as_deref());+ let instance_ref = instance.as_deref();let mgr = state.cm.lock().await;// Find the integration and its proxy config@@ -1385,9 +1413,17 @@ async fn connection_proxy(// Load credentials (from connections.json) and the raw OAuth token JSON in parallel.// OAuth JSON is passed separately to resolve_base_url so callback-only fields like// QuickBooks' {realmId} can fill URL placeholders without polluting the credentials map.- let creds = mgr.get_credentials(&id).await.ok().flatten();- let oauth_json =- screenpipe_connect::oauth::load_oauth_json(state.secret_store.as_deref(), &id, None).await;+ let creds = mgr+ .get_credentials_instance(&id, instance_ref)+ .await+ .ok()+ .flatten();+ let oauth_json = screenpipe_connect::oauth::load_oauth_json(+ state.secret_store.as_deref(),+ &id,+ instance_ref,+ )+ .await;// Use get_valid_token_instance (not read_oauth_token_instance) so expired// access tokens are transparently refreshed via the stored refresh_token.// Before this fix the proxy would surface "no credentials found" and 401@@ -1398,7 +1434,7 @@ async fn connection_proxy(state.secret_store.as_deref(),&http_client,&id,- None,+ instance_ref,);// Resolve auth@@ -1417,8 +1453,9 @@ async fn connection_proxy(){tracing::warn!(- "proxy: no credentials found for connection '{}' — cannot authenticate",- id+ "proxy: no credentials found for connection '{}' instance {:?} — cannot authenticate",+ id,+ instance_ref);return (StatusCode::UNAUTHORIZED,@@ -1447,7 +1484,7 @@ async fn connection_proxy(// `?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`.- let target_url = match raw_query.as_deref() {+ let target_url = match forwarded_query.as_deref() {Some(q) if !q.is_empty() => {format!("{}/{}?{}", base_url, api_path.trim_start_matches('/'), q)}@@ -1456,11 +1493,12 @@ async fn connection_proxy(// Audit logtracing::info!(- "proxy: {} {} → {} (connection: {})",+ "proxy: {} {} → {} (connection: {}, instance: {:?})",method,api_path,target_url,- id+ id,+ instance_ref);// Forward the request — use a client that trusts any extra root CA the@@ -1573,9 +1611,11 @@ async fn connection_proxy(async fn connection_config(State(state): State<ConnectionsState>,Path(id): Path<String>,+ axum::extract::RawQuery(raw_query): axum::extract::RawQuery,) -> (StatusCode, Json<Value>) {+ let (instance, _) = split_instance_query(raw_query.as_deref());let mgr = state.cm.lock().await;- match mgr.get_credentials(&id).await {+ match mgr.get_credentials_instance(&id, instance.as_deref()).await {Ok(Some(creds)) => {// Filter out secret fieldslet def = mgr.find_def(&id);@@ -2415,6 +2455,21 @@ mod tests {));}+ #[test]+ fn split_instance_query_removes_instance_before_proxying() {+ let (instance, forwarded) =+ split_instance_query(Some("instance=work%20calendar&limit=10&q=hello%20world"));+ assert_eq!(instance.as_deref(), Some("work calendar"));+ assert_eq!(forwarded.as_deref(), Some("limit=10&q=hello+world"));+ }++ #[test]+ fn split_instance_query_preserves_non_instance_queries() {+ let (instance, forwarded) = split_instance_query(Some("page=1&limit=10"));+ assert_eq!(instance, None);+ assert_eq!(forwarded.as_deref(), Some("page=1&limit=10"));+ }+// -- proxy config validation --------------------------------------------#[test]