diff --git a/AGENTS.md b/AGENTS.md index d45cf5a6..ba43957e 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`). **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. +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 row it replaces, which its request names (`connector_requests.account_id`, read in `syncConnectorAccounts`). **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, and a listing that names no account revokes no card: the provider failing to answer is not every account deleted there. Deleting a connection removes its apps, sessions, requests, accounts and grants explicitly. Connectors travel in no extension bundle. ### Knowledgebases diff --git a/src/functions/backend/db/connectors/sync-connector-accounts.test.ts b/src/functions/backend/db/connectors/sync-connector-accounts.test.ts new file mode 100644 index 00000000..eb20b83d --- /dev/null +++ b/src/functions/backend/db/connectors/sync-connector-accounts.test.ts @@ -0,0 +1,21 @@ +/** + * The row an id-less reconnect replaces. The production fault this pins: + * 0.27.6 fell back to the one dead row with the requested name, so a new + * mailbox that arrived while a dead row existed took that row's label and + * namespace. Only a pending request that names a row may hand it over. + */ +import { expect, test } from "bun:test"; +import { pendingReconnectRow } from "./sync-connector-accounts"; + +test("an id-less reconnect names the row its request does", () => { + expect(pendingReconnectRow([{ account_id: 5, provider_account_id: "" }])).toBe(5); +}); + +test("a reconnect the provider gave an id for is not an id-less one", () => { + expect(pendingReconnectRow([{ account_id: 5, provider_account_id: "ca_new" }])).toBeNull(); +}); + +test("a plain sign-in (no row) and no request name nothing", () => { + expect(pendingReconnectRow([])).toBeNull(); + expect(pendingReconnectRow([{ account_id: 0, provider_account_id: "" }])).toBeNull(); +}); \ 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 faf5c6b3..2e108695 100644 --- a/src/functions/backend/db/connectors/sync-connector-accounts.ts +++ b/src/functions/backend/db/connectors/sync-connector-accounts.ts @@ -44,13 +44,18 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab const requests = ( await BunSQLite.sql<{ account_id: number; provider_account_id: string }>({ - sql: `SELECT account_id, provider_account_id FROM connector_requests WHERE connector_id = ? AND user_id = ? AND status = 'pending' AND provider_account_id != ''`, + sql: `SELECT account_id, provider_account_id FROM connector_requests WHERE connector_id = ? AND user_id = ? AND status = 'pending'`, values: [connector.id, Number(user_id)], }) ).payload || []; const reconnect_for = new Map( - requests.filter((row) => Number(row.account_id) != 0).map((row) => [String(row.provider_account_id), Number(row.account_id)]), + requests + .filter((row) => Number(row.account_id) != 0 && row.provider_account_id) + .map((row) => [String(row.provider_account_id), Number(row.account_id)]), ); + let reconnect_row = pendingReconnectRow(requests); + // A row disconnected since is no target: that sign-in arrives as a new one. + if (reconnect_row && !local.some((row) => Number(row.id) == reconnect_row)) reconnect_row = null; /** * A sign-in only becomes a row once it is connected, or while the request * that started it is still open. A pending account nothing here asked for @@ -58,7 +63,7 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab * `INITIALIZING` per abandoned link), and adopting it would put a second, * never connected account beside the one a reconnect replaced. */ - const claimed = new Set(requests.map((row) => String(row.provider_account_id))); + const claimed = new Set(requests.map((row) => String(row.provider_account_id || "")).filter(Boolean)); const seen = new Set(accounts.map((account) => account.provider_account_id)); const now = Date.now(); @@ -69,13 +74,20 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab */ 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; + /** + * A listing that names no account is the provider unable to answer, not + * every account deleted there: revoking them all would put Reconnect on + * cards that are fine. + */ + if (accounts.length) { + for (const row of local) { + if (seen.has(String(row.provider_account_id || ""))) continue; - await BunSQLite.sql({ - sql: `UPDATE connector_accounts SET status = 'revoked', last_checked_at = ?, updated_at = ? WHERE id = ?`, - values: [now, now, Number(row.id)], - }); + await BunSQLite.sql({ + sql: `UPDATE connector_accounts SET status = 'revoked', last_checked_at = ?, updated_at = ? WHERE id = ?`, + values: [now, now, Number(row.id)], + }); + } } let firstConnected: number | null = free_slot ? 0 : null; @@ -87,7 +99,7 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab if ( !shouldAdoptConnectorAccount({ status: account.status, - reconnect: Boolean(reconnect_id), + reconnect: Boolean(reconnect_id) || (account.status == "connected" && Boolean(reconnect_row)), claimed: claimed.has(provider_account_id), free_slot, }) @@ -100,8 +112,11 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab account, fallback_label: label, reconnect_id, + reconnect_row: account.status == "connected" ? reconnect_row : null, }); + if (account.status == "connected" && reconnect_row) reconnect_row = null; + if (account.status != "connected") continue; if (free_slot) free_slot = false; @@ -138,6 +153,12 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab return grabUserAccounts({ connector_id: connector.id, user_id: Number(user_id) }); } +export function pendingReconnectRow(requests: Array<{ account_id: number; provider_account_id: string }>) { + const named = requests.find((row) => Number(row.account_id) != 0 && !row.provider_account_id); + + return Number(named?.account_id || 0) || null; +} + type UpsertParams = { connector_id: number; user_id: number; @@ -148,9 +169,15 @@ type UpsertParams = { * sign-in takes its place instead of arriving as a second account. */ reconnect_id?: number; + /** + * That row when the provider gave the sign-in no id at all: the request + * names it, so it's never guessed from a name or a sole dead row, which + * would hand a new mailbox the dead one's label and namespace. + */ + reconnect_row?: number | null; }; -async function upsertAccount({ connector_id, user_id, account, fallback_label, reconnect_id }: UpsertParams) { +async function upsertAccount({ connector_id, user_id, account, fallback_label, reconnect_id, reconnect_row }: UpsertParams) { const now = Date.now(); if (reconnect_id) { @@ -200,42 +227,25 @@ 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. + * An id-less reconnect lands on the row it replaces, named by its request. + * A row that is merely dead is not it: a new mailbox that arrives while + * one dead row exists would otherwise take that row's name and namespace. + * Only a connected account takes it, since an abandoned link at the + * provider stays pending, and only once. */ - const name = account.label || fallback_label || ""; - 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`, - values: [connector_id, user_id, name], - }) - ).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]!; - + if (reconnect_row) { await BunSQLite.sql({ - sql: `UPDATE connector_accounts SET provider_account_id = ?, status = ?, connected_at = ?, last_checked_at = ?, last_error = '', updated_at = ? WHERE id = ?`, + sql: `UPDATE connector_accounts SET provider_account_id = ?, status = ?, connected_at = ?, last_checked_at = ?, last_error = '', updated_at = ? + WHERE id = ? AND connector_id = ? AND user_id = ?`, values: [ account.provider_account_id, account.status, account.status == "connected" ? now : null, now, now, - Number(row.id), + reconnect_row, + connector_id, + user_id, ], }); @@ -249,7 +259,7 @@ async function upsertAccount({ connector_id, user_id, account, fallback_label, r }) ).payload?.map((row) => row.slug) || []; - const display_name = name || "Account"; + const display_name = account.label || fallback_label || "Account"; let slug = connectorSlug({ name: display_name, max: 12, fallback: "account" }); for (let index = 2; taken.includes(slug); index++) { @@ -303,7 +313,7 @@ async function settleRequests({ connector_id, user_id, provider_account_ids }: S WHERE a.connector_id = connector_requests.connector_id AND a.user_id = connector_requests.user_id AND a.status = 'connected' - AND a.created_at >= connector_requests.created_at + AND (a.created_at >= connector_requests.created_at OR a.id = connector_requests.account_id) )) )`, values: [now, connector_id, user_id, now, ...provider_account_ids], diff --git a/src/harness/connectors/ensure-connector-endpoint.ts b/src/harness/connectors/ensure-connector-endpoint.ts index 770db7b6..ea7e6343 100644 --- a/src/harness/connectors/ensure-connector-endpoint.ts +++ b/src/harness/connectors/ensure-connector-endpoint.ts @@ -8,6 +8,14 @@ import type { ConnectorAccountRecord, ConnectorRecord } from "@/src/types"; import connectorAccountGoneMessage from "./connector-account-gone"; import type { ConnectorProvider } from "./connector-provider"; +/** + * When each account was last checked against the provider, per process: the + * check is a listing of every account the user has, and a cached session is + * used many times a minute. + */ +const accountChecks = new Map(); +const AccountCheckEveryMs = 5 * 60 * 1000; + /** * The endpoint one account's tools live at, cached in `connector_sessions` * because asking the provider costs a call and the session expires. @@ -54,8 +62,20 @@ async function readCachedHeaders({ headers }: { headers: string | null }): Promi * 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. + * + * The check lists every account the user has, so it is remembered per account + * for `AccountCheckEveryMs`: a cached session is checked too, at that pace + * rather than on every tool call. */ async function assertAccountStillThere({ connector, provider, user_id, account, now }: Params & { now: number }) { + const key = `${connector.id}:${account.provider_account_id}`; + + if (now - (accountChecks.get(key) || 0) < AccountCheckEveryMs) return; + + if (accountChecks.size > 1000) accountChecks.clear(); + + accountChecks.set(key, now); + let accounts: Awaited>; try { @@ -92,6 +112,9 @@ export default async function ensureConnectorEndpoint({ account, }: Params): Promise { const now = Date.now(); + + await assertAccountStillThere({ connector, provider, user_id, account, now }); + const cached = ( await BunSQLite.sql({ sql: `SELECT * FROM connector_sessions WHERE connector_id = ? AND user_id = ? AND provider_account_id = ? LIMIT 1`, @@ -113,8 +136,6 @@ 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));