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): support multiple Slack workspaces (#6693)
Louis Beaumont248e0ff417aa
diff --git a/apps/screenpipe-app-tauri/components/settings/__tests__/integration-icon-keys.test.ts b/apps/screenpipe-app-tauri/components/settings/__tests__/integration-icon-keys.test.tsindex 90483e961..7a5e9557d 100644--- a/apps/screenpipe-app-tauri/components/settings/__tests__/integration-icon-keys.test.ts+++ b/apps/screenpipe-app-tauri/components/settings/__tests__/integration-icon-keys.test.ts@@ -7,6 +7,7 @@ import {INTEGRATION_ICON_KEYS,TRY_IN_CHAT_PROMPTS,getOAuthFallbackMessage,+ getOAuthPanelCopy,isMcpOAuthProviderTileConnected,} from "../connections-section";import { connectionNameToId } from "../../../lib/utils/connection-chip";@@ -61,3 +62,19 @@ describe("getOAuthFallbackMessage", () => {expect(getOAuthFallbackMessage("slack", "pending")).toBeNull();});});++describe("getOAuthPanelCopy", () => {+ it("frames Slack multi-connect as workspaces", () => {+ expect(getOAuthPanelCopy("slack", "Slack")).toEqual({+ description: "Connect a Slack workspace. Add each workspace where Screenpipe should act on your behalf.",+ addAnotherLabel: "add another workspace",+ });+ });++ it("keeps account language for other OAuth providers", () => {+ expect(getOAuthPanelCopy("github", "GitHub")).toEqual({+ description: "Connect your GitHub account. AI can act on your behalf once connected.",+ addAnotherLabel: "add another account",+ });+ });+});diff --git a/apps/screenpipe-app-tauri/components/settings/connections-section.tsx b/apps/screenpipe-app-tauri/components/settings/connections-section.tsxindex b0209c10b..877d54434 100644--- a/apps/screenpipe-app-tauri/components/settings/connections-section.tsx+++ b/apps/screenpipe-app-tauri/components/settings/connections-section.tsx@@ -2227,6 +2227,20 @@ const OAUTH_SCOPE_VARIANTS: Record<],};+export function getOAuthPanelCopy(integrationId: string, integrationName: string) {+ if (integrationId === "slack") {+ return {+ description: "Connect a Slack workspace. Add each workspace where Screenpipe should act on your behalf.",+ addAnotherLabel: "add another workspace",+ };+ }++ return {+ description: `Connect your ${integrationName} account. AI can act on your behalf once connected.`,+ addAnotherLabel: "add another account",+ };+}+export function getOAuthFallbackMessage(integrationId: string,phase: "pending" | "failed",@@ -2283,6 +2297,7 @@ function OAuthPanel({? initialScopeVariant!: scopeVariants?.[0]?.id ?? null;const [scopeVariant, setScopeVariant] = useState(defaultScopeVariant);+ const panelCopy = getOAuthPanelCopy(integrationId, integrationName);const clearFallbackTimer = useCallback(() => {if (fallbackTimerRef.current) {@@ -2404,7 +2419,7 @@ function OAuthPanel({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.+ {panelCopy.description}</p>{connected && (<div className="space-y-2">@@ -2478,7 +2493,7 @@ function OAuthPanel({) : (<Button onClick={handleConnect} disabled={connectDisabled} size="sm" className="gap-1.5 h-7 text-xs normal-case font-sans tracking-normal whitespace-nowrap">{connected && supportsOAuthInstances- ? (<><Plus className="h-3 w-3" />add another account</>)+ ? (<><Plus className="h-3 w-3" />{panelCopy.addAnotherLabel}</>): connected? (<><LogIn className="h-3 w-3" />reconnect {integrationName}</>): (<><LogIn className="h-3 w-3" />connect with {integrationName}</>)}diff --git a/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs b/apps/screenpipe-app-tauri/src-tauri/src/oauth.rsindex e18c9a58a..6c545acfd 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs@@ -551,9 +551,10 @@ pub async fn oauth_connect(// provider coexist — connecting a second Google account must not clobber// the first.// We only fall back to the default slot (None) when the provider hands us- // no identity to key on (e.g. Notion/QuickBooks/Jira, which key on- // workspace metadata instead and stay single-account here).- let effective_instance = derive_effective_instance(instance, &token_data);+ // no stable identity to key on. Most multi-account providers use email;+ // Slack uses its stable team id so separate workspaces cannot overwrite+ // each other.+ let effective_instance = derive_effective_instance(&integration_id, instance, &token_data);let store_instance = effective_instance.as_deref();oauth::write_oauth_token_instance(store.as_ref(), &integration_id, store_instance, &token_data)@@ -749,10 +750,12 @@ fn extract_email_from_jwt(jwt: &str) -> Option<String> {}fn derive_effective_instance(+ integration_id: &str,explicit_instance: Option<String>,token_data: &serde_json::Value,) -> Option<String> {- explicit_instance.or_else(|| token_data["email"].as_str().map(String::from))+ explicit_instance+ .or_else(|| oauth::oauth_instance_identity(integration_id, token_data).map(String::from))}#[cfg(test)]@@ -769,11 +772,26 @@ mod tests {});assert_eq!(- derive_effective_instance(None, &token_data).as_deref(),+ derive_effective_instance("zoom", None, &token_data).as_deref(),Some("[email protected]"));}+ #[test]+ fn effective_instance_uses_slack_workspace_identity() {+ let token_data = json!({+ "authed_user": { "access_token": "xoxp-test" },+ "team": { "id": "T012345", "name": "Acme" },+ "team_id": "T012345",+ "workspace_name": "Acme",+ });++ assert_eq!(+ derive_effective_instance("slack", None, &token_data).as_deref(),+ Some("T012345")+ );+ }+#[test]fn effective_instance_does_not_use_workspace_metadata() {let token_data = json!({@@ -781,7 +799,7 @@ mod tests {"workspace_name": "Acme Workspace",});- assert_eq!(derive_effective_instance(None, &token_data), None);+ assert_eq!(derive_effective_instance("notion", None, &token_data), None);}/// Canceled flow (#5092): oauth_cancel drops the pending sender, whichdiff --git a/crates/screenpipe-connect/src/connections/slack.rs b/crates/screenpipe-connect/src/connections/slack.rsindex 80fe44950..40f5ae3f5 100644--- a/crates/screenpipe-connect/src/connections/slack.rs+++ b/crates/screenpipe-connect/src/connections/slack.rs@@ -57,6 +57,8 @@ static DEF: IntegrationDef = IntegrationDef {Send: POST /connections/slack/send with {\"text\":\"...\",\"channel\":\"...\"} \(defaults to your own direct message). With \"Send + read\" access also: \GET /connections/slack/search?q=..., /conversations, /history?channel=.... \+ Multiple workspaces: pass `instance=<team_id>` in the JSON body or query string; \+ omitting it works only when one workspace is connected. \The user token is stored in SecretStore and injected server-side.",fields: &[],};@@ -77,6 +79,10 @@ impl Integration for Slack {SCOPE_VARIANTS}+ fn supports_oauth_instances(&self) -> bool {+ true+ }+async fn test(&self,client: &reqwest::Client,@@ -140,3 +146,13 @@ impl Integration for Slack {})}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn advertises_multiple_oauth_workspaces() {+ assert!(Slack.supports_oauth_instances());+ }+}diff --git a/crates/screenpipe-connect/src/oauth.rs b/crates/screenpipe-connect/src/oauth.rsindex 3f6cd4d4d..c0628494b 100644--- a/crates/screenpipe-connect/src/oauth.rs+++ b/crates/screenpipe-connect/src/oauth.rs@@ -361,6 +361,21 @@ fn oauth_json_is_recoverable(v: &Value) -> bool {oauth_json_has_valid_access_token(v) || v["refresh_token"].as_str().is_some()}+/// Stable, non-secret identity used to key one OAuth connection instance.+/// Most providers expose an account email. Slack's OAuth response instead+/// identifies the connected workspace with a team id, so use that id only for+/// Slack rather than treating all workspace metadata as an instance key.+pub fn oauth_instance_identity<'a>(integration_id: &str, token_data: &'a Value) -> Option<&'a str> {+ if integration_id == "slack" {+ return token_data["team_id"]+ .as_str()+ .or_else(|| token_data["team"]["id"].as_str())+ .or_else(|| token_data["email"].as_str());+ }++ token_data["email"].as_str()+}+/// Exact-key variant with no instance fallback. Everything `load_oauth_json`/// does except the multi-instance resolution.async fn load_oauth_json_exact(@@ -539,6 +554,16 @@ pub async fn describe_oauth_error(display_name: &str,instance: Option<&str>,) -> String {+ let connection_kind = if integration_id == "slack" {+ "workspace"+ } else {+ "account"+ };+ let instance_placeholder = if integration_id == "slack" {+ "<team_id>"+ } else {+ "<email>"+ };let instances: Vec<String> =list_recoverable_named_oauth_instances(store, integration_id).await;let all_instances: Vec<String> = list_oauth_instances(store, integration_id)@@ -548,20 +573,20 @@ pub async fn describe_oauth_error(.collect();match (instance, instances.as_slice(), all_instances.as_slice()) {(Some(inst), _, _) => format!(- "{display_name} account '{inst}' is not connected or its token can't be refreshed — reconnect it from the Connections page in the desktop app"+ "{display_name} {connection_kind} '{inst}' is not connected or its token can't be refreshed — reconnect it from the Connections page in the desktop app"),(None, [], []) => format!("{display_name} not connected — use 'Connect {display_name}' from the Connections page in the desktop app"),(None, [], stale) => format!(- "{display_name} has saved account row(s) ({}) but none can be refreshed — reconnect it from the Connections page in the desktop app",+ "{display_name} has saved {connection_kind} row(s) ({}) but none can be refreshed — reconnect it from the Connections page in the desktop app",stale.join(", "),),(None, [only], _) => format!(- "{display_name} account '{only}' token can't be refreshed — reconnect it from the Connections page in the desktop app"+ "{display_name} {connection_kind} '{only}' token can't be refreshed — reconnect it from the Connections page in the desktop app"),(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=\"{}\")",+ "multiple {display_name} {connection_kind}s connected ({}) — specify which one with `instance`. On JSON-body endpoints add `\"instance\": \"{instance_placeholder}\"` to the request body; on proxy/query endpoints add `?instance={instance_placeholder}` (e.g. instance=\"{}\")",many.join(", "),many[0],),@@ -861,28 +886,28 @@ pub async fn sweep_shadowed_default_slots(store: &SecretStore) -> Result<usize>};let default_val = load_oauth_json_exact(Some(store), id, None).await;- let default_email = default_val+ let default_identity = default_val.as_ref()- .and_then(|v| v["email"].as_str().map(String::from));+ .and_then(|v| oauth_instance_identity(id, v).map(String::from));let is_distinct_recoverable = default_val.as_ref().is_some_and(oauth_json_is_recoverable)- && default_email+ && default_identity.as_ref()- .is_some_and(|e| !named_for_id.contains(e));+ .is_some_and(|identity| !named_for_id.contains(identity));let key = format!("oauth:{}", id);if is_distinct_recoverable {// A real, separate account sitting in the default slot — promote it// to its own named slot before clearing the default key.- let email = default_email.expect("distinct_recoverable implies Some email");+ let identity = default_identity.expect("distinct_recoverable implies Some identity");if let Err(e) =- write_oauth_token_instance(Some(store), id, Some(&email), &default_val.unwrap())+ write_oauth_token_instance(Some(store), id, Some(&identity), &default_val.unwrap()).await{// Promotion failed — leave the default slot intact rather than// risk losing the account; we'll retry on the next launch.tracing::warn!("oauth: failed to promote default-slot account {} for {} during sweep, leaving default slot intact: {e:#}",- email,+ identity,id,);continue;@@ -891,7 +916,7 @@ pub async fn sweep_shadowed_default_slots(store: &SecretStore) -> Result<usize>Ok(()) => {tracing::info!("oauth: promoted shadowed default-slot account {} to its own instance for {}",- email,+ identity,id,);deleted += 1;@@ -899,7 +924,7 @@ pub async fn sweep_shadowed_default_slots(store: &SecretStore) -> Result<usize>Err(e) => {tracing::warn!("oauth: promoted {} but failed to drop default slot for {}: {e:#}",- email,+ identity,id,);}@@ -936,7 +961,7 @@ pub async fn sweep_shadowed_default_slots(store: &SecretStore) -> Result<usize>/// intent — a stale default slot otherwise shadows every `instance=None`/// read)./// - default slot holds a *distinct, recoverable* account → promote it to its-/// own named slot (`oauth:{id}:{email}`) first, so it survives alongside the+/// own named slot (`oauth:{id}:{identity}`) first, so it survives alongside the/// account we just saved, then clear the default key.pub async fn reconcile_default_slot_after_instanced_save(store: Option<&SecretStore>,@@ -947,23 +972,23 @@ pub async fn reconcile_default_slot_after_instanced_save(return Ok(());};- let default_email = default_val["email"].as_str();- let is_distinct_recoverable =- oauth_json_is_recoverable(&default_val) && default_email.is_some_and(|e| e != new_instance);+ let default_identity = oauth_instance_identity(integration_id, &default_val);+ let is_distinct_recoverable = oauth_json_is_recoverable(&default_val)+ && default_identity.is_some_and(|identity| identity != new_instance);if is_distinct_recoverable {- let email = default_email.expect("distinct_recoverable implies Some email");+ let identity = default_identity.expect("distinct_recoverable implies Some identity");// Don't clobber an existing named slot for the same account (e.g. the// user just reconnected it under its own instance).let already_named = list_oauth_instances(store, integration_id).await.into_iter()- .any(|i| i.as_deref() == Some(email));+ .any(|i| i.as_deref() == Some(identity));if !already_named {- write_oauth_token_instance(store, integration_id, Some(email), &default_val).await?;+ write_oauth_token_instance(store, integration_id, Some(identity), &default_val).await?;tracing::info!("oauth: promoted default-slot account {} to its own instance for {} (multi-account)",- email,+ identity,integration_id,);}@@ -1224,6 +1249,50 @@ mod tests {SecretStore::new(pool, None).await.unwrap()}+ #[test]+ fn oauth_instance_identity_prefers_slack_team_id_and_keeps_email_elsewhere() {+ let token = json!({+ "team": { "id": "T012345", "name": "Acme" },+ "team_id": "T012345",+ "workspace_name": "Acme",+ "email": "[email protected]",+ });++ assert_eq!(oauth_instance_identity("slack", &token), Some("T012345"));+ assert_eq!(+ oauth_instance_identity("notion", &token),+ Some("[email protected]")+ );+ assert_eq!(+ oauth_instance_identity("slack", &json!({ "team": { "id": "T_LEGACY" } })),+ Some("T_LEGACY")+ );+ }++ #[tokio::test]+ async fn describe_slack_ambiguity_names_workspaces_and_instance_key() {+ let store = mem_store().await;+ for team_id in ["T_FIRST", "T_SECOND"] {+ store+ .set_json(+ &format!("oauth:slack:{team_id}"),+ &json!({+ "authed_user": { "access_token": format!("token-{team_id}") },+ "team_id": team_id,+ }),+ )+ .await+ .unwrap();+ }++ let error = describe_oauth_error(Some(&store), "slack", "Slack", None).await;+ assert!(error.contains("multiple Slack workspaces connected"));+ assert!(error.contains("T_FIRST"));+ assert!(error.contains("T_SECOND"));+ assert!(error.contains("<team_id>"));+ assert!(!error.contains("<email>"));+ }+#[test]fn refresh_gen_bumps_only_on_rotation() {// First token for a slot (no prior) → generation 1.@@ -1842,6 +1911,53 @@ mod tests {assert_eq!(sweep_shadowed_default_slots(&store).await.unwrap(), 0);}+ #[tokio::test]+ async fn sweep_promotes_distinct_slack_workspace_from_default() {+ let store = mem_store().await;+ store+ .set_json(+ "oauth:slack",+ &json!({+ "authed_user": { "access_token": "first" },+ "team": { "id": "T_FIRST", "name": "First" },+ "team_id": "T_FIRST",+ }),+ )+ .await+ .unwrap();+ store+ .set_json(+ "oauth:slack:T_SECOND",+ &json!({+ "authed_user": { "access_token": "second" },+ "team": { "id": "T_SECOND", "name": "Second" },+ "team_id": "T_SECOND",+ }),+ )+ .await+ .unwrap();++ assert_eq!(sweep_shadowed_default_slots(&store).await.unwrap(), 1);+ assert!(store+ .get_json::<Value>("oauth:slack")+ .await+ .unwrap()+ .is_none());+ assert_eq!(+ store+ .get_json::<Value>("oauth:slack:T_FIRST")+ .await+ .unwrap()+ .unwrap()["authed_user"]["access_token"],+ "first"+ );+ assert!(store+ .get_json::<Value>("oauth:slack:T_SECOND")+ .await+ .unwrap()+ .is_some());+ }+// ---- reconcile_default_slot_after_instanced_save ------------------//// The "connecting a 2nd Google account wiped the 1st" bug: the first account used to@@ -1911,6 +2027,56 @@ mod tests {);}+ #[tokio::test]+ async fn reconcile_promotes_distinct_default_slack_workspace() {+ let store = mem_store().await;+ store+ .set_json(+ "oauth:slack",+ &json!({+ "authed_user": { "access_token": "first" },+ "team_id": "T_FIRST",+ "workspace_name": "First",+ }),+ )+ .await+ .unwrap();+ store+ .set_json(+ "oauth:slack:T_SECOND",+ &json!({+ "authed_user": { "access_token": "second" },+ "team_id": "T_SECOND",+ "workspace_name": "Second",+ }),+ )+ .await+ .unwrap();++ reconcile_default_slot_after_instanced_save(Some(&store), "slack", "T_SECOND")+ .await+ .unwrap();++ assert!(store+ .get_json::<Value>("oauth:slack")+ .await+ .unwrap()+ .is_none());+ assert_eq!(+ store+ .get_json::<Value>("oauth:slack:T_FIRST")+ .await+ .unwrap()+ .unwrap()["authed_user"]["access_token"],+ "first"+ );+ assert!(store+ .get_json::<Value>("oauth:slack:T_SECOND")+ .await+ .unwrap()+ .is_some());+ }+#[tokio::test]async fn reconcile_drops_same_account_default() {// Reconnecting the same account: the fresh token was written under thediff --git a/crates/screenpipe-engine/src/connections_api.rs b/crates/screenpipe-engine/src/connections_api.rsindex 04ada5ed2..dbdf38a1a 100644--- a/crates/screenpipe-engine/src/connections_api.rs+++ b/crates/screenpipe-engine/src/connections_api.rs@@ -2387,12 +2387,14 @@ async fn slack_send({Some(value) => value,None => {- return (- StatusCode::UNAUTHORIZED,- Json(- json!({ "error": "Slack is not connected. Connect Slack from the Connections page in the desktop app." }),- ),- );+ let error = oauth_store::describe_oauth_error(+ state.secret_store.as_deref(),+ "slack",+ "Slack",+ body.instance.as_deref(),+ )+ .await;+ return (StatusCode::UNAUTHORIZED, Json(json!({ "error": error })));}};@@ -2610,12 +2612,25 @@ async fn slack_user_token(state: &ConnectionsState,instance: Option<&str>,) -> Result<String, (StatusCode, Json<Value>)> {- let token_json = oauth_store::load_oauth_json(state.secret_store.as_deref(), "slack", instance)- .await- .ok_or((- StatusCode::UNAUTHORIZED,- Json(json!({ "error": "Slack is not connected. Connect Slack from the Connections page in the desktop app." })),- ))?;+ let token_json = match oauth_store::load_oauth_json(+ state.secret_store.as_deref(),+ "slack",+ instance,+ )+ .await+ {+ Some(value) => value,+ None => {+ let error = oauth_store::describe_oauth_error(+ state.secret_store.as_deref(),+ "slack",+ "Slack",+ instance,+ )+ .await;+ return Err((StatusCode::UNAUTHORIZED, Json(json!({ "error": error }))));+ }+ };token_json["authed_user"]["access_token"].as_str().filter(|t| !t.is_empty())diff --git a/docs/pr-assets/slack-multiple-workspaces-before-after.png b/docs/pr-assets/slack-multiple-workspaces-before-after.pngnew file mode 100644index 000000000..b178db610Binary files /dev/null and b/docs/pr-assets/slack-multiple-workspaces-before-after.png differ