diff --git a/AGENTS.md b/AGENTS.md index b3f72d65..69dfa0e6 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). 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 chips (`ConnectorAccounts`) show the label and where each is in force, "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. `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`). 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. `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/db/schema.ts b/db/schema.ts index 257a4372..200cc378 100644 --- a/db/schema.ts +++ b/db/schema.ts @@ -4223,6 +4223,12 @@ const schema: BUN_SQLITE_DatabaseSchemaType = { fieldDescription: `The conversation the card sits in, which the wake message goes to. Not a foreign key`, dataType: "INTEGER", }, + { + fieldName: "account_id", + fieldDescription: `The account this link reconnects, 0 for a new one. A finished sign-in updates that row in place, so a dead account keeps its label and namespace`, + dataType: "INTEGER", + defaultValue: 0, + }, { fieldName: "label", fieldDescription: `The account label the user typed, or the one the card suggested`, diff --git a/db/types/db.ts b/db/types/db.ts index 408b9da3..0a9be27b 100644 --- a/db/types/db.ts +++ b/db/types/db.ts @@ -2622,6 +2622,10 @@ export type BUN_SQLITE_COBBLE_CONNECTOR_REQUESTS = { * The conversation the card sits in, which the wake message goes to. Not a foreign key */ bot_session_id?: number | ""; + /** + * The account this link reconnects, 0 for a new one. A finished sign-in updates that row in place, so a dead account keeps its label and namespace + */ + account_id?: number | ""; /** * The account label the user typed, or the one the card suggested */ diff --git a/src/functions/backend/db/connectors/create-connector-request.ts b/src/functions/backend/db/connectors/create-connector-request.ts index 1583a3d5..7dae4fd5 100644 --- a/src/functions/backend/db/connectors/create-connector-request.ts +++ b/src/functions/backend/db/connectors/create-connector-request.ts @@ -18,6 +18,10 @@ type Params = { session_id?: number | null; connector: ConnectorRecord; label?: string; + /** + * The account being reconnected, 0 or absent for a new one. + */ + account_id?: number; }; export type ConnectorRequest = { @@ -38,13 +42,14 @@ export default async function createConnectorRequest({ session_id, connector, label, + account_id, }: Params): Promise { const now = Date.now(); const name = label || connector.name; const open = ( await BunSQLite.sql({ - sql: `SELECT * FROM connector_requests WHERE connector_id = ? AND user_id = ? AND label = ? AND status = 'pending' AND expires_at > ? ORDER BY id DESC LIMIT 1`, - values: [connector.id, user_id, name, now], + sql: `SELECT * FROM connector_requests WHERE connector_id = ? AND user_id = ? AND label = ? AND account_id = ? AND status = 'pending' AND expires_at > ? ORDER BY id DESC LIMIT 1`, + values: [connector.id, user_id, name, Number(account_id || 0), now], }) ).payload?.[0]; @@ -86,6 +91,7 @@ export default async function createConnectorRequest({ bot_id: bot_id ?? undefined, bot_session_id: session_id ?? undefined, label: name, + account_id: Number(account_id || 0), url: started.url, provider_account_id: started.provider_account_id || undefined, status: "pending", 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 new file mode 100644 index 00000000..39eca7de --- /dev/null +++ b/src/functions/backend/db/connectors/should-adopt-connector-account.test.ts @@ -0,0 +1,22 @@ +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 pending account a request here started", () => { + expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: false, claimed: true })).toBe(true); + }); + + test("adopts a pending account that reconnects a row", () => { + expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: true, claimed: 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); + }); +}); \ 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 new file mode 100644 index 00000000..d40628e0 --- /dev/null +++ b/src/functions/backend/db/connectors/should-adopt-connector-account.ts @@ -0,0 +1,20 @@ +import type { ProviderAccountStatus } from "@/src/harness/connectors/connector-provider"; + +type Params = { + status: ProviderAccountStatus; + /** A pending request is reconnecting this very account. */ + reconnect: boolean; + /** A pending request here started this sign-in. */ + claimed: 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. + */ +export default function shouldAdoptConnectorAccount({ status, reconnect, claimed }: Params) { + return reconnect || status == "connected" || claimed; +} \ No newline at end of file diff --git a/src/functions/backend/db/connectors/start-connector-connection.ts b/src/functions/backend/db/connectors/start-connector-connection.ts index ee6c8987..1a887d50 100644 --- a/src/functions/backend/db/connectors/start-connector-connection.ts +++ b/src/functions/backend/db/connectors/start-connector-connection.ts @@ -12,6 +12,12 @@ type Params = { * What the user calls the account they're connecting, e.g. Work Gmail. */ label?: string; + /** + * The account this sign-in reconnects, when one went dead. Its row is + * updated in place once the provider lists the new sign-in, so it keeps + * its label and its tool namespace. + */ + account_id?: number | string; bot_id?: number | string; session_id?: number | string; }; @@ -35,6 +41,7 @@ export default async function startConnectorConnection({ user_id, connector_id, label, + account_id, bot_id, session_id, }: Params): Promise { @@ -48,6 +55,7 @@ export default async function startConnectorConnection({ user_id: Number(user_id), connector, label, + account_id: account_id ? Number(account_id) : undefined, bot_id: bot_id ? Number(bot_id) : undefined, session_id: session_id ? Number(session_id) : undefined, }); diff --git a/src/functions/backend/db/connectors/sync-connector-accounts.ts b/src/functions/backend/db/connectors/sync-connector-accounts.ts index 149bc552..eda31054 100644 --- a/src/functions/backend/db/connectors/sync-connector-accounts.ts +++ b/src/functions/backend/db/connectors/sync-connector-accounts.ts @@ -6,6 +6,7 @@ import type { ConnectorAccountRecord } from "@/src/types"; import connectorSlug from "@/src/utils/connector-slug"; import grabConnector from "./grab-connector"; import parseConnectorAccountRow from "./parse-connector-account-row"; +import shouldAdoptConnectorAccount from "./should-adopt-connector-account"; type Params = { user_id: number | string; @@ -36,6 +37,24 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab }) ).payload || []; + 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 != ''`, + 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)]), + ); + /** + * 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 + * is an abandoned or replaced sign-in at the provider (Composio keeps one + * `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 seen = new Set(accounts.map((account) => account.provider_account_id)); const now = Date.now(); const hasConnected = local.some((row) => row.status == "connected"); @@ -52,7 +71,25 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab let firstConnected: number | null = hasConnected ? null : 0; for (const account of accounts) { - await upsertAccount({ connector_id: connector.id, user_id: Number(user_id), account, fallback_label: label }); + const provider_account_id = String(account.provider_account_id); + const reconnect_id = reconnect_for.get(provider_account_id); + + if ( + !shouldAdoptConnectorAccount({ + status: account.status, + reconnect: Boolean(reconnect_id), + claimed: claimed.has(provider_account_id), + }) + ) + continue; + + await upsertAccount({ + connector_id: connector.id, + user_id: Number(user_id), + account, + fallback_label: label, + reconnect_id, + }); if (account.status != "connected") continue; @@ -93,10 +130,35 @@ type UpsertParams = { user_id: number; account: ProviderAccount; fallback_label?: string; + /** + * The row a reconnect replaces: its provider id is gone, so the new + * sign-in takes its place instead of arriving as a second account. + */ + reconnect_id?: number; }; -async function upsertAccount({ connector_id, user_id, account, fallback_label }: UpsertParams) { +async function upsertAccount({ connector_id, user_id, account, fallback_label, reconnect_id }: UpsertParams) { const now = Date.now(); + + if (reconnect_id) { + await BunSQLite.sql({ + 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, + reconnect_id, + connector_id, + user_id, + ], + }); + + return; + } + const existing = ( await BunSQLite.sql({ sql: `SELECT * FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND provider_account_id = ? LIMIT 1`, @@ -124,6 +186,39 @@ async function upsertAccount({ connector_id, user_id, account, fallback_label }: return; } + /** + * 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. + */ + const name = account.label || fallback_label || ""; + const 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 || []) + : []; + + if (dead.length == 1) { + const row = dead[0]!; + + await BunSQLite.sql({ + sql: `UPDATE connector_accounts SET provider_account_id = ?, status = ?, connected_at = ?, last_checked_at = ?, last_error = '', updated_at = ? WHERE id = ?`, + values: [ + account.provider_account_id, + account.status, + account.status == "connected" ? now : null, + now, + now, + Number(row.id), + ], + }); + + return; + } + const taken = ( await BunSQLite.sql<{ slug: string }>({ sql: `SELECT slug FROM connector_accounts WHERE connector_id = ? AND user_id = ?`, @@ -131,11 +226,11 @@ async function upsertAccount({ connector_id, user_id, account, fallback_label }: }) ).payload?.map((row) => row.slug) || []; - const name = account.label || fallback_label || "Account"; - let slug = connectorSlug({ name, max: 12, fallback: "account" }); + const display_name = name || "Account"; + let slug = connectorSlug({ name: display_name, max: 12, fallback: "account" }); for (let index = 2; taken.includes(slug); index++) { - slug = `${connectorSlug({ name, max: 8, fallback: "account" })}-${index}`; + slug = `${connectorSlug({ name: display_name, max: 8, fallback: "account" })}-${index}`; } await BunSQLite.sql({ @@ -147,7 +242,7 @@ async function upsertAccount({ connector_id, user_id, account, fallback_label }: now, connector_id, user_id, - name, + display_name, slug, account.provider_account_id, account.status, diff --git a/src/pages/admin/settings/connectors/(hooks)/use-connector-connect.ts b/src/pages/admin/settings/connectors/(hooks)/use-connector-connect.ts index 265dcd47..a116b1a7 100644 --- a/src/pages/admin/settings/connectors/(hooks)/use-connector-connect.ts +++ b/src/pages/admin/settings/connectors/(hooks)/use-connector-connect.ts @@ -13,6 +13,11 @@ type Params = { type StartParams = { connector_id: number; label: string; + /** + * The account being reconnected; its row is updated instead of a new + * one being added. + */ + account_id?: number; }; /** @@ -39,7 +44,7 @@ export default function useConnectorConnect({ onConnected, onError }: Params) { onConnected(msg); }; - const start = async ({ connector_id, label }: StartParams) => { + const start = async ({ connector_id, label, account_id }: StartParams) => { if (busy) return; setBusy(true); @@ -51,7 +56,7 @@ export default function useConnectorConnect({ onConnected, onError }: Params) { const res = await postAdminApi<{ request: ConnectorRequestPayload | null; accounts: ConnectorAccountRecord[] }>({ path: "connectors/start-connection", - body: { connector_id, label }, + body: { connector_id, label, account_id }, }); if (!res.success || !res.singleRes) { diff --git a/src/pages/admin/settings/connectors/(partials)/connector-account-modal.tsx b/src/pages/admin/settings/connectors/(partials)/connector-account-modal.tsx index d5b100c2..591c9baf 100644 --- a/src/pages/admin/settings/connectors/(partials)/connector-account-modal.tsx +++ b/src/pages/admin/settings/connectors/(partials)/connector-account-modal.tsx @@ -7,11 +7,12 @@ import Input from "@moduletrace/twui/form/Input"; import Form from "@moduletrace/twui/form/Form"; import Checkbox from "@moduletrace/twui/form/Checkbox"; import SearchSelect from "@moduletrace/twui/form/SearchSelect"; -import { CircleSlash } from "lucide-react"; +import { CircleSlash, ExternalLink, RefreshCw } from "lucide-react"; import AddModalShell from "@/src/layouts/bots/(partials)/add-modal-shell"; import AddFormActions from "@/src/layouts/bots/(partials)/add-form-actions"; import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api"; import type { ConnectorAccountRecord, ConnectorRecord, ExtensionTargets } from "@/src/types"; +import useConnectorConnect from "../(hooks)/use-connector-connect"; type Props = { connector: ConnectorRecord; @@ -34,6 +35,12 @@ export default function ConnectorAccountModal({ connector, account, targets, bot const [all_bots, setAllBots] = useState(account.all_bots); const [busy, setBusy] = useState<"save" | "disconnect">(); const [error, setError] = useState(""); + const [reconnect_error, setReconnectError] = useState(""); + const connect = useConnectorConnect({ + onConnected: onSaved, + onError: (msg) => setReconnectError(msg), + }); + const save = async () => { if (busy) return; @@ -153,6 +160,48 @@ export default function ConnectorAccountModal({ connector, account, targets, bot info="Every bot working in these workspaces may use the account." /> + {account.status != "connected" ? ( + + + This sign-in is no longer connected. Reconnect puts a fresh one in its place, under the same name + and tool names. + + + + {connect.sign_in ? ( + + ) : null} + + {reconnect_error ? {reconnect_error} : null} + + ) : null} + - - - {isShared({ account }) - ? accountReach({ - account, - targets, - bots, - }) - : "Only your runs"} - - {account.status != "connected" ? ( - - - {statusOf(account.status)} - - ) : null} - + + + {statusOf(account.status)} + + + - + ))} - + ) : ( No account yet: add one, and your runs can use{" "} diff --git a/src/pages/api/admin/connectors/refresh-account.ts b/src/pages/api/admin/connectors/refresh-account.ts new file mode 100644 index 00000000..8142709c --- /dev/null +++ b/src/pages/api/admin/connectors/refresh-account.ts @@ -0,0 +1,51 @@ +import userAuth from "@/src/functions/backend/auth/user-auth"; +import grabConnectorAccount from "@/src/functions/backend/db/connectors/grab-connector-account"; +import syncConnectorAccounts from "@/src/functions/backend/db/connectors/sync-connector-accounts"; +import { DisconnectConnectorAccountSchema } from "@/src/schemas/connector-schema"; +import { ConnectorAccountStatuses } from "@/src/dict/connector-dict"; +import type { ConnectorAccountRecord } from "@/src/types"; +import AppError from "@/src/utils/app-error"; +import parseWithSchema from "@/src/utils/parse-with-schema"; +import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user"; +import safeErrorMessage from "@/src/utils/safe-error-message"; +import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types"; + +type Payload = { + connector_id: number; + account: ConnectorAccountRecord; +}; + +/** + * Re-reads one of the signed-in user's accounts at its provider, so a + * sign-in finished on another device shows here without a reload. + */ +export const handler: BunextAPIRouteHandler> = async ({ req, body }) => { + try { + if (req.method != "POST") throw new AppError(`Method not allowed`); + + const { user, user_types } = await userAuth({ req }); + + if (!user?.logged_in_status || !user.id) { + return { success: false, msg: `Unauthorized`, logoutUser: true }; + } + + if (isReadOnlyUser({ user_types: user_types || [] })) { + throw new AppError(`This user can only read records.`); + } + + const { account_id } = parseWithSchema({ schema: DisconnectConnectorAccountSchema, data: body }); + const own = await grabConnectorAccount({ user_id: user.id, account_id }); + + await syncConnectorAccounts({ user_id: user.id, connector_id: own.connector_id }); + const account = await grabConnectorAccount({ user_id: user.id, account_id }); + const title = ConnectorAccountStatuses.find((entry) => entry.value == account.status)?.title || account.status; + + return { + success: true, + msg: account.status == "connected" ? `${account.label} is connected.` : `${account.label} is still ${title.toLowerCase()}.`, + singleRes: { connector_id: own.connector_id, account }, + }; + } catch (error: unknown) { + return { success: false, msg: safeErrorMessage({ error }) }; + } +}; diff --git a/src/schemas/connector-schema.ts b/src/schemas/connector-schema.ts index 3b34ef66..b8c1a131 100644 --- a/src/schemas/connector-schema.ts +++ b/src/schemas/connector-schema.ts @@ -29,6 +29,7 @@ export const SetBotConnectorRequestSchema = z.object({ export const StartConnectorConnectionRequestSchema = z.object({ connector_id: Id, + account_id: Id.optional(), label: z.string().trim().max(80).default(""), });