diff --git a/AGENTS.md b/AGENTS.md index 0a238cbf..9de4ceb3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -214,7 +214,7 @@ A user's own running browser, reached over a browser MCP server they run beside ### Connectors (`connector_connections`, `connectors`, `bot_connectors`, `workspace_connectors`, `connector_accounts`, `connector_sessions`, `connector_requests`) -A user's access to an outside app (Gmail, Slack, ...) as themselves, reached through a provider that holds the OAuth app and the connected account (Settings > Connectors). Composio is the first provider: one file under `src/harness/connectors/providers/` and the preset in `src/dict/connector-dict.ts`. **A connection is one provider account, not an app**: `connector_connections` has one row per provider account (Composio Personal, Composio Work, ...), each with its own encrypted `api_key`, added in Settings > Connectors; the form's **paradigm** (`provider`, Composio the first) decides how that connection's apps are reached, and more paradigms can be added; that form names the key a paradigm wants and links where to make it (`key_help`, `key_url`, `key_url_title` in the preset: Composio wants a project API key `ak_...` from its Project Settings > API Keys, not a `ck_...` key made for `connect.composio.dev/mcp`, whose router signs everyone in as the key's owner); `connectorProviderFor` builds the provider from that key, so no install-wide key is read from Environment. `syncConnectorConnection({ connection_id })` reads every app the connection offers into `connectors` (`connectors.connection_id`; `planConnectorSync` derives each slug and names a second connection's app after it, `gmail-work`), so nothing is added or edited app by app; a stored app follows the provider's name, description and logo only, keeping its slug, reach and accounts. A thousand apps cost nothing until one is used: its tools are read when it is first given to a bot or workspace (`syncConnector` from `set-bot-connector`/`set-connector-access` when `tools` is empty) and by the cron for assigned apps alone. **An account is a person's own** (`connector_accounts.user_id`), several per app, and its owner's runs always reach it; its owner or a super admin can also give it out (`connector_accounts.all_bots`, `connector_account_workspaces`, `connector_account_bots`, written by `setConnectorAccountAccess`), so every run in a workspace or on a bot reaches it too, whoever signed in (and giving an account out brings its app along to that bot or workspace, since `botConnectorsSql` counts a connected account given there), and the session is built as the account's owner (`openBotConnectors` passes `account.user_id`, and a shared line names whose account it is). A sign-in the provider no longer lists reads revoked, and its modal offers **Reconnect**, which starts a fresh sign-in for that row (`connector_requests.account_id`), so the finished one replaces it in place and keeps its label and namespace. A reconnect reuses that row, never a second one: a pending account no request here started (an abandoned or replaced sign-in at the provider) never becomes a row, and a reconnect the provider gave no id for lands on the one dead row with that name (`shouldAdoptConnectorAccount`). Its owner or a super admin renames it (`saveConnectorAccount`, which regenerates the slug, so a namespace follows its label); a member can only give an account to places they reach, and only a super admin sets `all_bots`. **A second account is a new sign-in, never the first one reused:** `startConnectorConnection` always makes a link (an account already connected never stands in for the new one), and a request is settled only by the account it made (`connector_requests.provider_account_id`, matched in `settleRequests` and `grabConnectorRequestView`), so a request the user has not finished cannot show the label of an account that was already there. The sign-in itself must never replace the app's earlier account: Composio's plain `connected_accounts/link` does exactly that, so the adapter first opens a multi-account tool-router session and takes its link (`/tool_router/session//link`), which keeps the other sign-ins; tool sessions stay single-account, pinning one in `connected_accounts`, since a multi-account session exposes only the router's meta tools and refuses `preload`. Credentials never reach this app or a model, and a run gets tools from an endpoint the provider builds for one account. **Where a connector reaches:** `all_bots` (every bot, every user) and `workspace_connectors` are the install's and only a super admin sets them; `bot_connectors.user_id` is NOT NULL, so a bot row is always personal to whoever made it and shows only in their runs (`botConnectorsSql`). Runs get deferred tools through `openBotConnectors` (`__`, or `-__` when the user has more than one account) and `ConnectorsNote`, opened beside `openBotExtensions`/`openBotBrowsers` in replies and task runs. Tool names and the action cap (`connectors_actions_per_run`, an `app_settings` row, 50 by default) come from the app. Transport is the MCP lane; when a provider can't pin an account at a session endpoint (`endpoint` throws), `ensure-connector-endpoint` records `session_id = "rest"` and the tools call `provider.execute({tool, args, account})` with the account, so the model's surface never changes. Composio's tool router answers with a URL and no headers and rejects a keyless call (401 "API key is required"), so the adapter sends the connection's project key as `x-api-key` on every session call; a cached session whose stored headers can't be read is rebuilt, never used keyless. **Bots never make or change a connector:** a missing account in an attended reply makes the app create `connector_requests` and show `[connect:ID]` (`ConnectRefCard`, the sign-in opened from there, then read by asking the provider's accounts), and a note line says so; a task, routine, hook call or crew request never gets the card. **The settings page lists connections only** (super admin: add, edit, delete, sync; everyone: their own sign-in); each connection's apps live at `/admin/settings/connectors/`, `ConnectorAppsPageSize` (24) a page, searched on the server over name, app and description by `grabConnectorApps`, so a connection holding 1,842 apps never renders them all; that read puts apps with a connected account the viewer can see first and filters to `all` / `connected` / `unconnected` (`ConnectorAppFilters`), returning each tab's count with the page. A row's one assignment control is who gets the app; its account cards (`ConnectorAccounts`) carry the label, one status, a refresh action (re-check a live account, reconnect a dead one) and disconnect, never where the account reaches (that lives in its modal), "New connection" opens the sign-in modal (the app's logo beside its title, Connect the only primary button), an account chip opens its own modal: the name, `all_bots` and the bots and workspaces it reaches (reach-checked lists), and Disconnect; the row's New connection line leads with how many of the app's accounts are connected (`N accounts`, in the success colour, and nothing while none is). A conversation's composer tools modal ends with a **Connectors** section (`ComposerConnectorsSection`), read by `grabBotConnectors` when the modal opens (never by the page): each app the bot reaches there (its title tagged with the connection's name, and with the account's label when an account given here is what brings it), where it comes from (every bot, this workspace, only you, or an account given here) and the accounts that reach there (this user's own, whatever their status, and connected ones given here, with their owner), or that none is connected yet, with a Manage link to Settings > Connectors, and Add/remove: Add opens a modal that walks down from the connection, to the app (searched on the server through `grabAttachableConnectors` with its `connection_id`, 20 at a time, listing only apps with a connected account of the user's and never one they already attached to this bot), to that app's own accounts (`grabConnectorOwnAccounts`, which leaves out an account already given here) or All accounts for the app alone, and gives the app to this bot for this user (`connectors/set-bot`, so every account they have of it reaches the bot, ones connected later included), plus the picked account to this bot (`connectors/set-account-access`); Remove is the row's X (shown when `entry.removable`) and calls `connectors/detach`, taking away this user's own attachment there and their own account given to that bot alone, while a workspace's, the install's or an account given to every bot shows no X. The composer's Tools button draws that bot's connected apps as up to five small circles before the spanner (one per app, `connector_apps` from `grabBotExtensionsOverview`, kept live with the count when the modal reads them), so a conversation shows what it can reach at a glance. `sync-connectors` (`*/15`) refreshes every connection's apps, assigned apps' tools and the accounts a sign-in left waiting (pending requests and any account not yet `connected`, so an OAuth callback that lands after the poll is picked up); `prune-connector-requests` takes old requests. A request is only settled as connected once the provider reports an account connected, never on a sync that found none. Deleting a connection removes its apps, sessions, requests, accounts and grants explicitly. Connectors travel in no extension bundle. +A user's access to an outside app (Gmail, Slack, ...) as themselves, reached through a provider that holds the OAuth app and the connected account (Settings > Connectors). Composio is the first provider: one file under `src/harness/connectors/providers/` and the preset in `src/dict/connector-dict.ts`. **A connection is one provider account, not an app**: `connector_connections` has one row per provider account (Composio Personal, Composio Work, ...), each with its own encrypted `api_key`, added in Settings > Connectors; the form's **paradigm** (`provider`, Composio the first) decides how that connection's apps are reached, and more paradigms can be added; that form names the key a paradigm wants and links where to make it (`key_help`, `key_url`, `key_url_title` in the preset: Composio wants a project API key `ak_...` from its Project Settings > API Keys, not a `ck_...` key made for `connect.composio.dev/mcp`, whose router signs everyone in as the key's owner); `connectorProviderFor` builds the provider from that key, so no install-wide key is read from Environment. `syncConnectorConnection({ connection_id })` reads every app the connection offers into `connectors` (`connectors.connection_id`; `planConnectorSync` derives each slug and names a second connection's app after it, `gmail-work`), so nothing is added or edited app by app; a stored app follows the provider's name, description and logo only, keeping its slug, reach and accounts. A thousand apps cost nothing until one is used: its tools are read when it is first given to a bot or workspace (`syncConnector` from `set-bot-connector`/`set-connector-access` when `tools` is empty) and by the cron for assigned apps alone. **An account is a person's own** (`connector_accounts.user_id`), several per app, and its owner's runs always reach it; its owner or a super admin can also give it out (`connector_accounts.all_bots`, `connector_account_workspaces`, `connector_account_bots`, written by `setConnectorAccountAccess`), so every run in a workspace or on a bot reaches it too, whoever signed in (and giving an account out brings its app along to that bot or workspace, since `botConnectorsSql` counts a connected account given there), and the session is built as the account's owner (`openBotConnectors` passes `account.user_id`, and a shared line names whose account it is). A sign-in the provider no longer lists reads revoked, and its modal offers **Reconnect**, which starts a fresh sign-in for that row (`connector_requests.account_id`), so the finished one replaces it in place and keeps its label and namespace. A reconnect reuses that row, never a second one: a pending account no request here started (an abandoned or replaced sign-in at the provider) never becomes a row, and a reconnect the provider gave no id for lands on the one dead row with that name (`shouldAdoptConnectorAccount`). **One card per app unless the user signs in again:** a connected account the provider holds but no request here made fills the app's one free card and is left at the provider after that, so leftovers from earlier attempts cannot pile up as four rows of the same mailbox. The account name is only a label: the grant is whichever account was chosen on the provider's page, which the connect modal says. Its owner or a super admin renames it (`saveConnectorAccount`, which regenerates the slug, so a namespace follows its label); a member can only give an account to places they reach, and only a super admin sets `all_bots`. **A second account is a new sign-in, never the first one reused:** `startConnectorConnection` always makes a link (an account already connected never stands in for the new one), and a request is settled only by the account it made (`connector_requests.provider_account_id`, matched in `settleRequests` and `grabConnectorRequestView`), so a request the user has not finished cannot show the label of an account that was already there. The sign-in itself must never replace the app's earlier account: Composio's plain `connected_accounts/link` does exactly that, so the adapter first opens a multi-account tool-router session and takes its link (`/tool_router/session//link`), which keeps the other sign-ins; tool sessions stay single-account, pinning one in `connected_accounts`, since a multi-account session exposes only the router's meta tools and refuses `preload`. Credentials never reach this app or a model, and a run gets tools from an endpoint the provider builds for one account. **Where a connector reaches:** `all_bots` (every bot, every user) and `workspace_connectors` are the install's and only a super admin sets them; `bot_connectors.user_id` is NOT NULL, so a bot row is always personal to whoever made it and shows only in their runs (`botConnectorsSql`). Runs get deferred tools through `openBotConnectors` (`__`, or `-__` when the user has more than one account) and `ConnectorsNote`, opened beside `openBotExtensions`/`openBotBrowsers` in replies and task runs. Tool names and the action cap (`connectors_actions_per_run`, an `app_settings` row, 50 by default) come from the app. Transport is the MCP lane; when a provider can't pin an account at a session endpoint (`endpoint` throws), `ensure-connector-endpoint` records `session_id = "rest"` and the tools call `provider.execute({tool, args, account})` with the account, so the model's surface never changes. Composio's tool router answers with a URL and no headers and rejects a keyless call (401 "API key is required"), so the adapter sends the connection's project key as `x-api-key` on every session call; a cached session whose stored headers can't be read is rebuilt, never used keyless. An account the provider no longer has is refused, never guessed: a session pinned to a deleted id makes the provider answer from whichever account it still holds, so `ensure-connector-endpoint` checks the account is still listed, marks the row revoked and stops the call with `connectorAccountGoneMessage` (Reconnect is then on its card); the `*/15` cron re-checks connected accounts every hour for the same reason. **Bots never make or change a connector:** a missing account in an attended reply makes the app create `connector_requests` and show `[connect:ID]` (`ConnectRefCard`, the sign-in opened from there, then read by asking the provider's accounts), and a note line says so; a task, routine, hook call or crew request never gets the card. **The settings page lists connections only** (super admin: add, edit, delete, sync; everyone: their own sign-in); each connection's apps live at `/admin/settings/connectors/`, `ConnectorAppsPageSize` (24) a page, searched on the server over name, app and description by `grabConnectorApps`, so a connection holding 1,842 apps never renders them all; that read puts apps with a connected account the viewer can see first and filters to `all` / `connected` / `unconnected` (`ConnectorAppFilters`), returning each tab's count with the page. A row's one assignment control is who gets the app; its account cards (`ConnectorAccounts`) carry the label, one status, a refresh action (re-check a live account, reconnect a dead one) and disconnect, never where the account reaches (that lives in its modal), "New connection" opens the sign-in modal (the app's logo beside its title, Connect the only primary button), an account chip opens its own modal: the name, `all_bots` and the bots and workspaces it reaches (reach-checked lists), and Disconnect; the row's New connection line leads with how many of the app's accounts are connected (`N accounts`, in the success colour, and nothing while none is). A conversation's composer tools modal ends with a **Connectors** section (`ComposerConnectorsSection`), read by `grabBotConnectors` when the modal opens (never by the page): each app the bot reaches there (its title tagged with the connection's name, and with the account's label when an account given here is what brings it), where it comes from (every bot, this workspace, only you, or an account given here) and the accounts that reach there (this user's own, whatever their status, and connected ones given here, with their owner), or that none is connected yet, with a Manage link to Settings > Connectors, and Add/remove: Add opens a modal that walks down from the connection, to the app (searched on the server through `grabAttachableConnectors` with its `connection_id`, 20 at a time, listing only apps with a connected account of the user's and never one they already attached to this bot), to that app's own accounts (`grabConnectorOwnAccounts`, which leaves out an account already given here) or All accounts for the app alone, and gives the app to this bot for this user (`connectors/set-bot`, so every account they have of it reaches the bot, ones connected later included), plus the picked account to this bot (`connectors/set-account-access`); Remove is the row's X (shown when `entry.removable`) and calls `connectors/detach`, taking away this user's own attachment there and their own account given to that bot alone, while a workspace's, the install's or an account given to every bot shows no X. The composer's Tools button draws that bot's connected apps as up to five small circles before the spanner (one per app, `connector_apps` from `grabBotExtensionsOverview`, kept live with the count when the modal reads them), so a conversation shows what it can reach at a glance. `sync-connectors` (`*/15`) refreshes every connection's apps, assigned apps' tools and the accounts a sign-in left waiting (pending requests and any account not yet `connected`, so an OAuth callback that lands after the poll is picked up); `prune-connector-requests` takes old requests. A request is only settled as connected once the provider reports an account connected, never on a sync that found none. Deleting a connection removes its apps, sessions, requests, accounts and grants explicitly. Connectors travel in no extension bundle. ### Knowledgebases diff --git a/package.json b/package.json index cec5a219..36b49fe5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "cobble", - "version": "0.27.3", + "version": "0.27.4", "module": "index.ts", "type": "module", "private": true, diff --git a/src/cron/sync-connectors/index.ts b/src/cron/sync-connectors/index.ts index 5fe4ee71..45faabb8 100644 --- a/src/cron/sync-connectors/index.ts +++ b/src/cron/sync-connectors/index.ts @@ -6,7 +6,10 @@ import syncConnectorConnection from "@/src/functions/backend/db/connectors/sync- /** * Keeps every connection's app list current, reads the tools of the apps * someone actually gave to a bot or workspace (never all of them: a - * provider lists hundreds), and checks the accounts a sign-in left waiting. + * provider lists hundreds), and keeps accounts in line with the provider: + * the ones a sign-in left waiting, and connected ones an hour later, so an + * account deleted at the provider shows as revoked (and offers Reconnect) + * without waiting for a run to fail. * Each connection is synced with its own key, so a refused one only affects * the apps it read. */ @@ -37,13 +40,18 @@ export default async function syncConnectors() { await syncConnector({ connector_id: connector.id }); } + const now = Date.now(); + const stale_after = now - 60 * 60 * 1000; const waiting = ( await BunSQLite.sql<{ connector_id: number; user_id: number }>({ sql: `SELECT connector_id, user_id FROM connector_requests WHERE status = 'pending' AND expires_at > ? UNION - SELECT connector_id, user_id FROM connector_accounts WHERE status != 'connected'`, - values: [Date.now()], + SELECT connector_id, user_id FROM connector_accounts WHERE status != 'connected' + UNION + SELECT connector_id, user_id FROM connector_accounts + WHERE status = 'connected' AND (last_checked_at IS NULL OR last_checked_at < ?)`, + values: [now, stale_after], }) ).payload || []; diff --git a/src/functions/backend/db/connectors/should-adopt-connector-account.test.ts b/src/functions/backend/db/connectors/should-adopt-connector-account.test.ts index 39eca7de..6edd302c 100644 --- a/src/functions/backend/db/connectors/should-adopt-connector-account.test.ts +++ b/src/functions/backend/db/connectors/should-adopt-connector-account.test.ts @@ -2,21 +2,42 @@ import { describe, expect, test } from "bun:test"; import shouldAdoptConnectorAccount from "@/src/functions/backend/db/connectors/should-adopt-connector-account"; describe("shouldAdoptConnectorAccount", () => { - test("adopts a connected account whether or not a request claims it", () => { - expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: false, claimed: false })).toBe(true); - expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: false, claimed: true })).toBe(true); + test("adopts a connected account into the app's free card", () => { + expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: false, claimed: false, free_slot: true })).toBe( + true, + ); + }); + + test("leaves a second connected account at the provider once the card is taken", () => { + expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: false, claimed: false, free_slot: false })).toBe( + false, + ); + }); + + test("adopts a connected account a request here started, even with no free card", () => { + expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: false, claimed: true, free_slot: false })).toBe( + true, + ); }); test("adopts a pending account a request here started", () => { - expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: false, claimed: true })).toBe(true); + expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: false, claimed: true, free_slot: false })).toBe( + true, + ); }); test("adopts a pending account that reconnects a row", () => { - expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: true, claimed: false })).toBe(true); + expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: true, claimed: false, free_slot: false })).toBe( + true, + ); }); test("skips a pending account nothing here started", () => { - expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: false, claimed: false })).toBe(false); - expect(shouldAdoptConnectorAccount({ status: "expired", reconnect: false, claimed: false })).toBe(false); + expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: false, claimed: false, free_slot: true })).toBe( + false, + ); + expect(shouldAdoptConnectorAccount({ status: "expired", reconnect: false, claimed: false, free_slot: true })).toBe( + false, + ); }); }); \ No newline at end of file diff --git a/src/functions/backend/db/connectors/should-adopt-connector-account.ts b/src/functions/backend/db/connectors/should-adopt-connector-account.ts index d40628e0..c04051a0 100644 --- a/src/functions/backend/db/connectors/should-adopt-connector-account.ts +++ b/src/functions/backend/db/connectors/should-adopt-connector-account.ts @@ -6,15 +6,23 @@ type Params = { reconnect: boolean; /** A pending request here started this sign-in. */ claimed: boolean; + /** + * Whether the app has no live account here yet: one card per app is + * filled by the provider's account, and any other account arrives through + * its own sign-in (claimed). + */ + free_slot: boolean; }; /** - * Whether a provider account becomes a local row. A connected one always does. - * A pending one does only when a request here started it or reconnects it: an - * abandoned sign-in at the provider must not arrive as a second account, which - * is how a reconnect once left a never connected duplicate beside the account - * it replaced. + * Whether a provider account becomes a local row. One a request here started + * (or is reconnecting) always does. A connected one the app doesn't know + * gets the app's one free card, so leftovers from earlier sign-ins at the + * provider can't pile up as four rows of the same mailbox; a second account + * appears by signing in again, which claims its own row. */ -export default function shouldAdoptConnectorAccount({ status, reconnect, claimed }: Params) { - return reconnect || status == "connected" || claimed; +export default function shouldAdoptConnectorAccount({ status, reconnect, claimed, free_slot }: Params) { + if (reconnect || claimed) return true; + + return status == "connected" && free_slot; } \ No newline at end of file diff --git a/src/functions/backend/db/connectors/sync-connector-accounts.ts b/src/functions/backend/db/connectors/sync-connector-accounts.ts index eda31054..faf5c6b3 100644 --- a/src/functions/backend/db/connectors/sync-connector-accounts.ts +++ b/src/functions/backend/db/connectors/sync-connector-accounts.ts @@ -23,7 +23,12 @@ type Params = { * local rows in line: new sign-ins are added (the first connected one is the * default), ones the provider reports expired say so, and ones it no longer * lists are marked revoked without losing their label. Pending connect - * requests are closed as soon as an account is connected. + * requests are closed as soon as the account they made is connected. + * + * One card per app unless the user signed in again: an account the provider + * holds but no request here made fills the app's free card once and is left + * at the provider after that, so a pile of earlier sign-ins cannot arrive as + * four rows of the same mailbox. */ export default async function syncConnectorAccounts({ user_id, connector_id, label }: Params) { const connector = await grabConnector({ connector_id }); @@ -57,7 +62,12 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab const seen = new Set(accounts.map((account) => account.provider_account_id)); const now = Date.now(); - const hasConnected = local.some((row) => row.status == "connected"); + /** + * The app's one free card: a live row still listed by the provider holds + * it. An account arriving without a sign-in here (an older attempt at + * the provider) may fill it once, never pile up beside it. + */ + let free_slot = !local.some((row) => row.status == "connected" && seen.has(String(row.provider_account_id || ""))); for (const row of local) { if (seen.has(String(row.provider_account_id || ""))) continue; @@ -68,7 +78,7 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab }); } - let firstConnected: number | null = hasConnected ? null : 0; + let firstConnected: number | null = free_slot ? 0 : null; for (const account of accounts) { const provider_account_id = String(account.provider_account_id); @@ -79,6 +89,7 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab status: account.status, reconnect: Boolean(reconnect_id), claimed: claimed.has(provider_account_id), + free_slot, }) ) continue; @@ -93,6 +104,8 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab if (account.status != "connected") continue; + if (free_slot) free_slot = false; + if (firstConnected === 0) { const created = ( await BunSQLite.sql<{ id: number }>({ @@ -190,9 +203,11 @@ async function upsertAccount({ connector_id, user_id, account, fallback_label, r * A reconnect the provider gave no id for still lands on the row it * replaces: one dead row with this account's name is that row, and a * second one with the same name would be the duplicate this prevents. + * When the provider's name differs from the label the user chose, the one + * dead row for this app is still the row a new sign-in takes over. */ const name = account.label || fallback_label || ""; - const dead = name + const named_dead = name ? (( await BunSQLite.sql({ sql: `SELECT * FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND status IN ('revoked', 'expired') AND lower(label) = lower(?) ORDER BY id ASC`, @@ -200,6 +215,14 @@ async function upsertAccount({ connector_id, user_id, account, fallback_label, r }) ).payload || []) : []; + const dead = named_dead.length + ? named_dead + : (( + await BunSQLite.sql({ + sql: `SELECT * FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND status IN ('revoked', 'expired') ORDER BY id ASC`, + values: [connector_id, user_id], + }) + ).payload || []); if (dead.length == 1) { const row = dead[0]!; diff --git a/src/harness/connectors/connector-account-gone.test.ts b/src/harness/connectors/connector-account-gone.test.ts new file mode 100644 index 00000000..889289e0 --- /dev/null +++ b/src/harness/connectors/connector-account-gone.test.ts @@ -0,0 +1,14 @@ +import { expect, test } from "bun:test"; +import connectorAccountGoneMessage from "./connector-account-gone"; + +test("names the account, the provider and where to reconnect", () => { + const message = connectorAccountGoneMessage({ + connector_name: "Gmail", + label: "Benoti Sanchez Gmail", + provider_title: "Composio", + }); + + expect(message).toContain('The Gmail account "Benoti Sanchez Gmail"'); + expect(message).toContain("no longer exists at Composio"); + expect(message).toContain("Settings > Connectors"); +}); \ No newline at end of file diff --git a/src/harness/connectors/connector-account-gone.ts b/src/harness/connectors/connector-account-gone.ts new file mode 100644 index 00000000..f793bbe4 --- /dev/null +++ b/src/harness/connectors/connector-account-gone.ts @@ -0,0 +1,16 @@ +type Params = { + connector_name: string; + label: string; + provider_title: string; +}; + +/** + * A row can outlive the account it names: a sign-in is deleted at the + * provider (a second one replaced it, a connection was cleared there) while + * the local row still says connected. Pinning that id would make the provider + * fall back to whatever account it does have, so the run would answer from a + * mailbox nobody chose. The tool refuses instead, naming the fix. + */ +export default function connectorAccountGoneMessage({ connector_name, label, provider_title }: Params) { + return `The ${connector_name} account "${label}" no longer exists at ${provider_title}, so this didn't run. Reconnect it in Settings > Connectors.`; +} \ No newline at end of file diff --git a/src/harness/connectors/ensure-connector-endpoint.ts b/src/harness/connectors/ensure-connector-endpoint.ts index 7e8633a8..770db7b6 100644 --- a/src/harness/connectors/ensure-connector-endpoint.ts +++ b/src/harness/connectors/ensure-connector-endpoint.ts @@ -1,8 +1,11 @@ import BunSQLite from "@moduletrace/bun-sqlite"; import type { BUN_SQLITE_COBBLE_CONNECTOR_SESSIONS } from "@/db/types/db"; import { AppData } from "@/src/data/app-data"; +import { ConnectorProviders } from "@/src/dict/connector-dict"; +import AppError from "@/src/utils/app-error"; import { decrypt, encrypt } from "@/src/utils/crypt"; import type { ConnectorAccountRecord, ConnectorRecord } from "@/src/types"; +import connectorAccountGoneMessage from "./connector-account-gone"; import type { ConnectorProvider } from "./connector-provider"; /** @@ -45,6 +48,43 @@ async function readCachedHeaders({ headers }: { headers: string | null }): Promi } } +/** + * A row can name an account the provider no longer has (a second sign-in + * replaced it, a connection was cleared there). A session pinned to that id + * is not refused: the provider answers from whichever account it does have, + * so a bot read a mailbox the user never chose. The row is marked revoked + * (its card then offers Reconnect) and the call stops instead. + */ +async function assertAccountStillThere({ connector, provider, user_id, account, now }: Params & { now: number }) { + let accounts: Awaited>; + + try { + accounts = await provider.accounts({ app: connector.app, user_id }); + } catch { + // The provider is the one to say why the session failed; a list that + // can't be read is not proof the account is gone. + return; + } + + if (accounts.some((entry) => entry.provider_account_id == account.provider_account_id)) return; + + await BunSQLite.sql({ + sql: `UPDATE connector_accounts SET status = 'revoked', last_checked_at = ?, updated_at = ? WHERE id = ?`, + values: [now, now, Number(account.id)], + }); + + const provider_title = + ConnectorProviders.find((entry) => entry.value == connector.provider)?.title || connector.provider; + + throw new AppError( + connectorAccountGoneMessage({ + connector_name: connector.name, + label: account.label, + provider_title, + }), + ); +} + export default async function ensureConnectorEndpoint({ connector, provider, @@ -73,6 +113,8 @@ export default async function ensureConnectorEndpoint({ } } + await assertAccountStillThere({ connector, provider, user_id, account, now }); + const tools = connector.tools .map((tool) => tool.name) .filter((name) => !connector.excluded_tools.includes(name)); diff --git a/src/pages/admin/settings/connectors/(partials)/connector-connect-modal.tsx b/src/pages/admin/settings/connectors/(partials)/connector-connect-modal.tsx index c1e85e8c..95e19d75 100644 --- a/src/pages/admin/settings/connectors/(partials)/connector-connect-modal.tsx +++ b/src/pages/admin/settings/connectors/(partials)/connector-connect-modal.tsx @@ -37,7 +37,7 @@ export default function ConnectorConnectModal({ connector, onConnected, onCancel }} icon={} title={`New ${connector.name} connection`} - description="The sign-in happens at the provider, and it keeps the credentials. Your bots only ever reach the account it makes." + description="The sign-in happens at the provider, and it keeps the credentials. Sign in with the account you want your bots to act as: the name here is only a label for it." >
setLabel(e.target.value)} - info="What you'll call it, so you can tell two accounts of the same app apart." + info="What you'll call it, so you can tell two accounts of the same app apart. It doesn't choose the account: the one you sign in with at the provider is the one your bots use." /> {connect.sign_in ? (