Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5ea9b608be | ||
|
|
7c92d0b4be | ||
|
|
319eb74a23 | ||
|
|
c745f58991 | ||
|
|
b046e90958 | ||
|
|
4a02035f33 | ||
|
|
f8a7b0f2e7 |
@@ -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`,
|
||||
|
||||
@@ -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
|
||||
*/
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.27.0",
|
||||
"version": "0.27.4",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -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 || [];
|
||||
|
||||
|
||||
@@ -182,7 +182,15 @@ def start(runner, env, log_max):
|
||||
"version": runner.get("version") or "",
|
||||
},
|
||||
)
|
||||
# A login shell can still be reading its profiles when the first look
|
||||
# happens, so give a process that exits soon a moment to be seen doing
|
||||
# it: another 1.2s costs nothing here and keeps a dead runner from
|
||||
# being reported as running.
|
||||
deadline = time.time() + 1.2
|
||||
code = child.poll()
|
||||
while code is None and time.time() < deadline:
|
||||
time.sleep(0.1)
|
||||
code = child.poll()
|
||||
if code is not None:
|
||||
tail = log_tail(runner_id, 400)
|
||||
try:
|
||||
|
||||
@@ -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,12 +42,14 @@ export default async function createConnectorRequest({
|
||||
session_id,
|
||||
connector,
|
||||
label,
|
||||
account_id,
|
||||
}: Params): Promise<ConnectorRequest> {
|
||||
const now = Date.now();
|
||||
const name = label || connector.name;
|
||||
const open = (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_REQUESTS>({
|
||||
sql: `SELECT * FROM connector_requests WHERE connector_id = ? AND user_id = ? AND status = 'pending' AND expires_at > ? ORDER BY id DESC LIMIT 1`,
|
||||
values: [connector.id, user_id, 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];
|
||||
|
||||
@@ -53,7 +59,7 @@ export default async function createConnectorRequest({
|
||||
const started = await provider.startConnect({
|
||||
app: connector.app,
|
||||
user_id,
|
||||
label: label || connector.name,
|
||||
label: name,
|
||||
auth_config_id: connector.auth_config_id,
|
||||
});
|
||||
|
||||
@@ -84,7 +90,8 @@ export default async function createConnectorRequest({
|
||||
user_id,
|
||||
bot_id: bot_id ?? undefined,
|
||||
bot_session_id: session_id ?? undefined,
|
||||
label: label || connector.name,
|
||||
label: name,
|
||||
account_id: Number(account_id || 0),
|
||||
url: started.url,
|
||||
provider_account_id: started.provider_account_id || undefined,
|
||||
status: "pending",
|
||||
|
||||
@@ -40,15 +40,23 @@ export default async function grabConnectorRequestView({ request_id, user_id }:
|
||||
});
|
||||
}
|
||||
|
||||
const request_account = String(row.provider_account_id || "");
|
||||
|
||||
// Only the account this request made counts: any connected one would
|
||||
// close a second sign-in with the first account's label, which is how a
|
||||
// second Gmail account looked already connected.
|
||||
const accountRows = (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS>({
|
||||
sql: `SELECT * FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND status = 'connected' ORDER BY id ASC`,
|
||||
values: [connector.id, Number(user_id)],
|
||||
sql: request_account
|
||||
? `SELECT * FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND status = 'connected' AND provider_account_id = ? LIMIT 1`
|
||||
: `SELECT * FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND status = 'connected' AND created_at >= ? ORDER BY id ASC LIMIT 1`,
|
||||
values: request_account
|
||||
? [connector.id, Number(user_id), request_account]
|
||||
: [connector.id, Number(user_id), Number(row.created_at || 0)],
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
const matching =
|
||||
accountRows.find((account) => account.provider_account_id == row.provider_account_id) || accountRows[0] || null;
|
||||
const matching = accountRows[0] || null;
|
||||
|
||||
if (status == "pending" && matching) {
|
||||
status = "connected";
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
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 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, free_slot: false })).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test("adopts a pending account that reconnects a row", () => {
|
||||
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, free_slot: true })).toBe(
|
||||
false,
|
||||
);
|
||||
expect(shouldAdoptConnectorAccount({ status: "expired", reconnect: false, claimed: false, free_slot: true })).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
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 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. 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, free_slot }: Params) {
|
||||
if (reconnect || claimed) return true;
|
||||
|
||||
return status == "connected" && free_slot;
|
||||
}
|
||||
@@ -12,29 +12,36 @@ 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;
|
||||
};
|
||||
|
||||
type Result = {
|
||||
/**
|
||||
* Null when the user already has a connected account: there is nothing
|
||||
* to sign in to.
|
||||
* The sign-in link. Always made: a person can keep several accounts on
|
||||
* one app (a work Gmail beside a personal one), so an account already
|
||||
* connected never stands in for the new one.
|
||||
*/
|
||||
request: ConnectorRequestPayload | null;
|
||||
accounts: ConnectorAccountRecord[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Starts (or finds) a sign-in for one connector, after reading what the
|
||||
* provider already has: a user who connected it before gets no second link.
|
||||
* The request outlives the page that made it, so the card under a reply and
|
||||
* Settings > Connectors both read it the same way.
|
||||
* Starts a sign-in for one connector. The request outlives the page that
|
||||
* made it, so the card under a reply and Settings > Connectors both read it
|
||||
* the same way.
|
||||
*/
|
||||
export default async function startConnectorConnection({
|
||||
user_id,
|
||||
connector_id,
|
||||
label,
|
||||
account_id,
|
||||
bot_id,
|
||||
session_id,
|
||||
}: Params): Promise<Result> {
|
||||
@@ -43,14 +50,12 @@ export default async function startConnectorConnection({
|
||||
if (!connector.enabled) throw new AppError(`${connector.name} is turned off, so it can't be connected right now.`);
|
||||
|
||||
const accounts = await syncConnectorAccounts({ user_id, connector_id: connector.id, label });
|
||||
const connected = accounts.filter((account) => account.status == "connected");
|
||||
|
||||
if (connected.length) return { request: null, accounts };
|
||||
|
||||
const request = await createConnectorRequest({
|
||||
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,
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
@@ -22,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 });
|
||||
@@ -36,9 +42,32 @@ 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");
|
||||
/**
|
||||
* 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;
|
||||
@@ -49,13 +78,34 @@ 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) {
|
||||
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),
|
||||
free_slot,
|
||||
})
|
||||
)
|
||||
continue;
|
||||
|
||||
await upsertAccount({
|
||||
connector_id: connector.id,
|
||||
user_id: Number(user_id),
|
||||
account,
|
||||
fallback_label: label,
|
||||
reconnect_id,
|
||||
});
|
||||
|
||||
if (account.status != "connected") continue;
|
||||
|
||||
if (free_slot) free_slot = false;
|
||||
|
||||
if (firstConnected === 0) {
|
||||
const created = (
|
||||
await BunSQLite.sql<{ id: number }>({
|
||||
@@ -72,8 +122,17 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab
|
||||
await BunSQLite.sql({ sql: `UPDATE connector_accounts SET is_default = 1 WHERE id = ?`, values: [firstConnected] });
|
||||
}
|
||||
|
||||
if (accounts.some((account) => account.status == "connected")) {
|
||||
await settleRequests({ connector_id: connector.id, user_id: Number(user_id) });
|
||||
const connected_ids = accounts
|
||||
.filter((account) => account.status == "connected")
|
||||
.map((account) => account.provider_account_id)
|
||||
.filter(Boolean);
|
||||
|
||||
if (connected_ids.length) {
|
||||
await settleRequests({
|
||||
connector_id: connector.id,
|
||||
user_id: Number(user_id),
|
||||
provider_account_ids: connected_ids,
|
||||
});
|
||||
}
|
||||
|
||||
return grabUserAccounts({ connector_id: connector.id, user_id: Number(user_id) });
|
||||
@@ -84,10 +143,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<BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS>({
|
||||
sql: `SELECT * FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND provider_account_id = ? LIMIT 1`,
|
||||
@@ -115,6 +199,49 @@ 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.
|
||||
* 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 named_dead = name
|
||||
? ((
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS>({
|
||||
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<BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS>({
|
||||
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]!;
|
||||
|
||||
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 = ?`,
|
||||
@@ -122,11 +249,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({
|
||||
@@ -138,7 +265,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,
|
||||
@@ -151,20 +278,35 @@ async function upsertAccount({ connector_id, user_id, account, fallback_label }:
|
||||
type SettleParams = {
|
||||
connector_id: number;
|
||||
user_id: number;
|
||||
provider_account_ids: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* A connect request is done the moment an account is connected: the card
|
||||
* under the reply says so instead of offering the link again.
|
||||
* A connect request is done only when the account it made is connected: a
|
||||
* second sign-in must not be closed by the first account that was already
|
||||
* there (`provider_account_id` is what the provider returned for this link).
|
||||
* A request the provider gave no id for falls back to an account created
|
||||
* after the request.
|
||||
*/
|
||||
async function settleRequests({ connector_id, user_id }: SettleParams) {
|
||||
async function settleRequests({ connector_id, user_id, provider_account_ids }: SettleParams) {
|
||||
const now = Date.now();
|
||||
const placeholders = provider_account_ids.map(() => "?").join(", ");
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE connector_requests SET status = 'connected', updated_at = ?
|
||||
WHERE connector_id = ? AND user_id = ? AND status = 'pending'
|
||||
AND expires_at > ?`,
|
||||
values: [now, connector_id, user_id, now],
|
||||
AND expires_at > ?
|
||||
AND (
|
||||
(provider_account_id != '' AND provider_account_id IN (${placeholders}))
|
||||
OR (provider_account_id == '' AND EXISTS (
|
||||
SELECT 1 FROM connector_accounts a
|
||||
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
|
||||
))
|
||||
)`,
|
||||
values: [now, connector_id, user_id, now, ...provider_account_ids],
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BotExtensionsPayload } from "@/src/types";
|
||||
import grabCrewRole from "../access/grab-crew-role";
|
||||
import countBotConnectors from "../connectors/count-bot-connectors";
|
||||
import grabBotConnectors from "../connectors/grab-bot-connectors";
|
||||
import grabExtensionsOverview from "./grab-extensions-overview";
|
||||
|
||||
type Params = {
|
||||
@@ -32,14 +33,27 @@ export default async function grabBotExtensionsOverview({
|
||||
BunSQLite.sql<{ kind: string }>({ sql: `SELECT kind FROM bots WHERE id = ?`, values: [bot_id] }),
|
||||
]);
|
||||
|
||||
const [overview, connector_count] = await Promise.all([
|
||||
const [overview, connector_count, connector_entries] = await Promise.all([
|
||||
grabExtensionsOverview({
|
||||
can_manage: role == "super_admin" || (role == "admin" && bot.payload?.[0]?.kind != "coordinator"),
|
||||
bot_id,
|
||||
workspace_id,
|
||||
}),
|
||||
countBotConnectors({ user_id, bot_id, workspace_id }),
|
||||
grabBotConnectors({ user_id, bot_id, workspace_id }),
|
||||
]);
|
||||
|
||||
return { ...overview, connector_count };
|
||||
/**
|
||||
* One icon per app, for the ones a connected account actually reaches
|
||||
* here: a pending sign-in has nothing to use yet.
|
||||
*/
|
||||
const connector_apps = connector_entries
|
||||
.filter((entry) => entry.accounts.some((account) => account.status == "connected"))
|
||||
.map((entry) => ({
|
||||
id: Number(entry.connector.id),
|
||||
name: entry.connector.name,
|
||||
logo: entry.connector.logo,
|
||||
}));
|
||||
|
||||
return { ...overview, connector_count, connector_apps };
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
@@ -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.`;
|
||||
}
|
||||
@@ -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<ReturnType<ConnectorProvider["accounts"]>>;
|
||||
|
||||
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));
|
||||
|
||||
@@ -132,16 +132,14 @@ describe("composioConnectorProvider", () => {
|
||||
|
||||
test("starts a sign-in with the app's sign-in setup and keeps what the provider returns", async () => {
|
||||
const { fetchImpl, calls } = stub({
|
||||
answer: ({ url, method }) =>
|
||||
url.pathname.endsWith("/auth_configs") && method == "GET"
|
||||
? { body: { items: [{ id: "ac_1", auth_scheme: "OAUTH2" }] } }
|
||||
: {
|
||||
body: {
|
||||
redirect_url: "https://connect/x",
|
||||
connected_account_id: "ca_9",
|
||||
expires_at: "2027-01-01T00:00:00Z",
|
||||
},
|
||||
},
|
||||
answer: ({ url, method }) => {
|
||||
if (url.pathname.endsWith("/tool_router/session")) return { status: 201, body: { session_id: "trs_1" } };
|
||||
if (url.pathname.endsWith("/tool_router/session/trs_1/link")) {
|
||||
return { status: 201, body: { redirect_url: "https://connect/x", connected_account_id: "ca_9", expires_at: "2027-01-01T00:00:00Z" } };
|
||||
}
|
||||
|
||||
return method == "GET" ? { body: { items: [{ id: "ac_1", auth_scheme: "OAUTH2" }] } } : { body: {} };
|
||||
},
|
||||
});
|
||||
|
||||
const started = await composioConnectorProvider({ key: "k", fetchImpl }).startConnect({
|
||||
@@ -155,20 +153,24 @@ describe("composioConnectorProvider", () => {
|
||||
expect(started.provider_account_id).toBe("ca_9");
|
||||
expect(started.expires_at).toBe(Date.parse("2027-01-01T00:00:00Z"));
|
||||
|
||||
const link = calls.find((call) => call.url.pathname.endsWith("/connected_accounts/link"))!;
|
||||
const session = calls.find((call) => call.url.pathname.endsWith("/tool_router/session"))!;
|
||||
|
||||
expect(link.body.toolkit_slug).toBe("gmail");
|
||||
expect(session.body.multi_account).toEqual({ enable: true, max_accounts_per_toolkit: 5 });
|
||||
|
||||
const link = calls.find((call) => call.url.pathname.endsWith("/tool_router/session/trs_1/link"))!;
|
||||
|
||||
expect(link.body.toolkit).toBe("gmail");
|
||||
expect(link.body.auth_config_id).toBe("ac_1");
|
||||
expect(link.body.account_label).toBe("Work");
|
||||
expect(link.body.callback_url).toBeUndefined();
|
||||
expect(calls.some((call) => call.url.pathname.endsWith("/connected_accounts/link"))).toBe(false);
|
||||
});
|
||||
|
||||
test("makes a managed sign-in setup when the app has none", async () => {
|
||||
const { fetchImpl, calls } = stub({
|
||||
answer: ({ url, method }) => {
|
||||
if (!url.pathname.endsWith("/auth_configs")) {
|
||||
return { body: { redirect_url: "https://connect/y" } };
|
||||
}
|
||||
if (url.pathname.endsWith("/tool_router/session")) return { status: 201, body: { session_id: "trs_1" } };
|
||||
if (url.pathname.endsWith("/link")) return { status: 201, body: { redirect_url: "https://connect/y" } };
|
||||
if (!url.pathname.endsWith("/auth_configs")) return { body: {} };
|
||||
|
||||
return method == "POST" ? { status: 201, body: { auth_config: { id: "ac_new" } } } : { body: { items: [] } };
|
||||
},
|
||||
|
||||
@@ -23,6 +23,8 @@ type Params = {
|
||||
|
||||
const DefaultBaseUrl = "https://backend.composio.dev/api/v3.1";
|
||||
const PageLimit = 100;
|
||||
/** Composio keeps one account per app unless a session allows more; 5 is its own ceiling in the docs. */
|
||||
const MaxAccountsPerToolkit = 5;
|
||||
const MaxPages = 20;
|
||||
|
||||
const Statuses: Record<string, ProviderAccountStatus> = {
|
||||
@@ -230,19 +232,36 @@ export default function composioConnectorProvider({ key, base_url, fetchImpl }:
|
||||
} satisfies ConnectorEndpoint;
|
||||
},
|
||||
|
||||
async startConnect({ app, user_id, label, auth_config_id, callback_url }: StartConnectParams) {
|
||||
async startConnect({ app, user_id, auth_config_id, callback_url }: StartConnectParams) {
|
||||
const config = await authConfigFor({ app, auth_config_id });
|
||||
|
||||
// A plain connected-accounts link replaces the app's account for
|
||||
// that user, so a second sign-in would take the first one away.
|
||||
// A multi-account session keeps both, which is what a connection
|
||||
// named "Work" beside one named "Personal" needs.
|
||||
const session = await request<any>({
|
||||
path: "/tool_router/session",
|
||||
method: "POST",
|
||||
what: `a sign-in session for ${app}`,
|
||||
body: {
|
||||
user_id: `cobble-user-${user_id}`,
|
||||
toolkits: { enable: [app] },
|
||||
multi_account: { enable: true, max_accounts_per_toolkit: MaxAccountsPerToolkit },
|
||||
},
|
||||
});
|
||||
|
||||
const session_id = session.session_id || session.id;
|
||||
|
||||
if (!session_id) throw new AppError(`Composio didn't open a sign-in session for ${app}.`);
|
||||
|
||||
const answer = await request<any>({
|
||||
path: "/connected_accounts/link",
|
||||
path: `/tool_router/session/${session_id}/link`,
|
||||
method: "POST",
|
||||
what: `a sign-in link for ${app}`,
|
||||
body: {
|
||||
toolkit_slug: app,
|
||||
user_id: `cobble-user-${user_id}`,
|
||||
toolkit: app,
|
||||
auth_config_id: config,
|
||||
callback_url,
|
||||
...(label ? { account_label: label } : {}),
|
||||
...(callback_url ? { callback_url } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import { Plus } from "lucide-react";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import type { BotConnectorEntry } from "@/src/types";
|
||||
import type { BotConnectorEntry, ConnectorAppIcon } from "@/src/types";
|
||||
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
|
||||
import ComposerConnectorPicker from "./composer-connector-picker";
|
||||
import ComposerConnectorRow from "./composer-connector-row";
|
||||
@@ -25,6 +25,11 @@ type Props = {
|
||||
* count follows an add or a remove without a reload.
|
||||
*/
|
||||
onCount?: (count: number) => void;
|
||||
/**
|
||||
* The apps a connected account reaches here, told to the composer for the
|
||||
* icons on its tools button.
|
||||
*/
|
||||
onApps?: (apps: ConnectorAppIcon[]) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -38,6 +43,7 @@ export default function ComposerConnectorsSection({
|
||||
workspace_id,
|
||||
open,
|
||||
onCount,
|
||||
onApps,
|
||||
}: Props) {
|
||||
const [items, setItems] = useState<BotConnectorEntry[]>();
|
||||
const [error, setError] = useState<string>();
|
||||
@@ -93,12 +99,23 @@ export default function ComposerConnectorsSection({
|
||||
|
||||
setItems(entries);
|
||||
onCount?.(entries.length);
|
||||
onApps?.(
|
||||
entries
|
||||
.filter((entry) =>
|
||||
entry.accounts.some((account) => account.status == "connected"),
|
||||
)
|
||||
.map((entry) => ({
|
||||
id: Number(entry.connector.id),
|
||||
name: entry.connector.name,
|
||||
logo: entry.connector.logo,
|
||||
})),
|
||||
);
|
||||
})();
|
||||
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [open, bot_id, workspace_id, tick, onCount]);
|
||||
}, [open, bot_id, workspace_id, tick, onCount, onApps]);
|
||||
|
||||
return (
|
||||
<Stack className="w-full mt-4 pt-4 items-stretch border-0 border-t border-solid border-hairline">
|
||||
|
||||
@@ -2,6 +2,8 @@ import { useState } from "react";
|
||||
import Modal from "@moduletrace/twui/elements/Modal";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import H2 from "@moduletrace/twui/layout/H2";
|
||||
import Img from "@moduletrace/twui/layout/Img";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { CircleAlert, type LucideIcon } from "lucide-react";
|
||||
@@ -10,9 +12,11 @@ import type {
|
||||
BotExtension,
|
||||
BotExtensionKind,
|
||||
BotExtensionsPayload,
|
||||
ConnectorAppIcon,
|
||||
} from "@/src/types";
|
||||
import ComposerConnectorsSection from "./composer-connectors-section";
|
||||
import ComposerToolRow from "./composer-tool-row";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
/**
|
||||
* What one of the composer's buttons is about, in copy: its tools, or its
|
||||
@@ -74,6 +78,13 @@ type Props = {
|
||||
* number follows an add or a remove without a reload.
|
||||
*/
|
||||
onConnectorCount?: (count: number) => void;
|
||||
/**
|
||||
* The apps a connector account reaches here, drawn as small circles
|
||||
* before the spanner (5 at most). Read with the count, so adding or
|
||||
* removing one shows without a reload.
|
||||
*/
|
||||
connector_apps?: ConnectorAppIcon[];
|
||||
onConnectorApps?: (apps: ConnectorAppIcon[]) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -94,6 +105,8 @@ export default function ComposerToolsModal({
|
||||
connectors,
|
||||
connector_count = 0,
|
||||
onConnectorCount,
|
||||
connector_apps = [],
|
||||
onConnectorApps,
|
||||
}: Props) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const count = attached.length;
|
||||
@@ -102,6 +115,7 @@ export default function ComposerToolsModal({
|
||||
(item) => !item.enabled || item.state == "error",
|
||||
);
|
||||
const TriggerIcon = has_problem ? CircleAlert : copy.Icon;
|
||||
const app_icons = connector_apps.filter((app) => app.logo).slice(0, 5);
|
||||
const label = total
|
||||
? `${total} ${total == 1 ? copy.one : copy.many}`
|
||||
: copy.empty_label;
|
||||
@@ -115,7 +129,26 @@ export default function ComposerToolsModal({
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
beforeIcon={<TriggerIcon size={12} aria-hidden />}
|
||||
beforeIcon={
|
||||
<Row className="items-center gap-1! flex-nowrap">
|
||||
{app_icons.map((app, index) => (
|
||||
<Img
|
||||
key={app.id}
|
||||
src={app.logo}
|
||||
alt={app.name}
|
||||
title={app.name}
|
||||
size={16}
|
||||
circle
|
||||
className={twMerge(
|
||||
"shrink-0 border border-hairline bg-white object-contain relative",
|
||||
index > 0 ? "-ml-1.5" : "",
|
||||
)}
|
||||
style={{ zIndex: index + 1 }}
|
||||
/>
|
||||
))}
|
||||
<TriggerIcon size={12} aria-hidden />
|
||||
</Row>
|
||||
}
|
||||
className="shrink-0 gap-1! px-2! py-0.5! text-[12px] leading-4 text-ink-secondary"
|
||||
>
|
||||
{label}
|
||||
@@ -181,6 +214,7 @@ export default function ComposerToolsModal({
|
||||
workspace_id={connectors.workspace_id}
|
||||
open={open}
|
||||
onCount={onConnectorCount}
|
||||
onApps={onConnectorApps}
|
||||
/>
|
||||
) : null}
|
||||
</Modal>
|
||||
|
||||
@@ -2,7 +2,11 @@ import { useContext, useEffect, useState } from "react";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import useExtensions from "@/src/hooks/use-extensions";
|
||||
import type { BotExtensionsPayload, BotWithLastMessage } from "@/src/types";
|
||||
import type {
|
||||
BotExtensionsPayload,
|
||||
BotWithLastMessage,
|
||||
ConnectorAppIcon,
|
||||
} from "@/src/types";
|
||||
import { BotComputersContext } from "../(data)/bot-computers-context";
|
||||
import { composerKnowledgebasesCopy, composerToolsCopy } from "../(data)/composer-extensions-copy";
|
||||
import ComposerBrowserButton from "./composer-browser-button";
|
||||
@@ -66,11 +70,18 @@ export default function ComposerTools({
|
||||
const [connector_count, set_connector_count] = useState(
|
||||
Number(initial?.connector_count || 0),
|
||||
);
|
||||
const [connector_apps, set_connector_apps] = useState<ConnectorAppIcon[]>(
|
||||
initial?.connector_apps || [],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
set_connector_count(Number(initial?.connector_count || 0));
|
||||
}, [initial?.connector_count]);
|
||||
|
||||
useEffect(() => {
|
||||
set_connector_apps(initial?.connector_apps || []);
|
||||
}, [initial?.connector_apps]);
|
||||
|
||||
const has_tools = Boolean(
|
||||
tools.attached.length || connector_count || (extensions.can_manage && tools.addable.length),
|
||||
);
|
||||
@@ -95,6 +106,8 @@ export default function ComposerTools({
|
||||
connectors={{ bot_id: bot.id || 0, workspace_id }}
|
||||
connector_count={connector_count}
|
||||
onConnectorCount={set_connector_count}
|
||||
connector_apps={connector_apps}
|
||||
onConnectorApps={set_connector_apps}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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" ? (
|
||||
<Stack className="w-full gap-2 rounded-default border border-hairline p-3">
|
||||
<Span className="text-sm">
|
||||
This sign-in is no longer connected. Reconnect puts a fresh one in its place, under the same name
|
||||
and tool names.
|
||||
</Span>
|
||||
<Row className="flex-wrap items-center gap-2!">
|
||||
<Button
|
||||
title={`Reconnect ${account.label}`}
|
||||
type="button"
|
||||
variant="outlined"
|
||||
size="small"
|
||||
className="gap-1!"
|
||||
loading={connect.busy}
|
||||
onClick={() => {
|
||||
setReconnectError("");
|
||||
connect.start({ connector_id: connector.id, label: account.label, account_id: account.id });
|
||||
}}
|
||||
>
|
||||
<RefreshCw size={14} aria-hidden />
|
||||
Reconnect
|
||||
</Button>
|
||||
{connect.sign_in ? (
|
||||
<Button
|
||||
title={`Open the ${connect.sign_in.label} sign-in page`}
|
||||
href={connect.sign_in.url}
|
||||
target="_blank"
|
||||
linkProps={{ rel: "noopener noreferrer" }}
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
className="gap-1!"
|
||||
>
|
||||
<ExternalLink size={14} aria-hidden />
|
||||
Open the sign-in page
|
||||
</Button>
|
||||
) : null}
|
||||
</Row>
|
||||
{reconnect_error ? <Span className="text-sm text-hue-red">{reconnect_error}</Span> : null}
|
||||
</Stack>
|
||||
) : null}
|
||||
|
||||
<Row className="w-full items-center justify-between gap-2!">
|
||||
<Button
|
||||
title={`Disconnect ${account.label}`}
|
||||
|
||||
@@ -3,13 +3,16 @@ import Button from "@moduletrace/twui/layout/Button";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { CircleAlert, CircleUser, Plus } from "lucide-react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { CircleSlash, CircleUser, Plus, RefreshCw } from "lucide-react";
|
||||
import { ConnectorAccountStatuses } from "@/src/dict/connector-dict";
|
||||
import type {
|
||||
ConnectorAccountRecord,
|
||||
ConnectorRecord,
|
||||
ExtensionTargets,
|
||||
} from "@/src/types";
|
||||
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
|
||||
import useConnectorConnect from "../(hooks)/use-connector-connect";
|
||||
import ConnectorAccountModal from "./connector-account-modal";
|
||||
import ConnectorConnectModal from "./connector-connect-modal";
|
||||
|
||||
@@ -22,43 +25,16 @@ type Props = {
|
||||
onError: (msg: string) => void;
|
||||
};
|
||||
|
||||
const isShared = ({ account }: { account: ConnectorAccountRecord }) =>
|
||||
account.all_bots ||
|
||||
Boolean(account.workspace_ids.length) ||
|
||||
Boolean(account.bot_ids.length);
|
||||
|
||||
/**
|
||||
* Where a sign-in is in force, in a few words.
|
||||
*/
|
||||
function accountReach({
|
||||
account,
|
||||
targets,
|
||||
bots,
|
||||
}: {
|
||||
account: ConnectorAccountRecord;
|
||||
targets: ExtensionTargets;
|
||||
bots: { id: number; name: string }[];
|
||||
}) {
|
||||
if (account.all_bots) return "Every bot, every user";
|
||||
|
||||
const names = [
|
||||
...account.workspace_ids.map(
|
||||
(id) =>
|
||||
targets.workspaces.find((workspace) => workspace.id == id)
|
||||
?.name || `workspace ${id}`,
|
||||
),
|
||||
...account.bot_ids.map(
|
||||
(id) => bots.find((bot) => bot.id == id)?.name || `bot ${id}`,
|
||||
),
|
||||
];
|
||||
|
||||
return names.length ? names.join(", ") : "Only your runs";
|
||||
}
|
||||
type Busy = {
|
||||
account_id: number;
|
||||
kind: "refresh" | "disconnect";
|
||||
};
|
||||
|
||||
/**
|
||||
* One app's sign-ins: the viewer's own, and any given out to a place they
|
||||
* reach. An account opens its own modal: its name, where it may be used,
|
||||
* and disconnecting it.
|
||||
* reach. A card carries its name, one status, and the two actions that keep
|
||||
* it alive (check again, or sign in again when it died, and disconnect).
|
||||
* Everything about where it may be used lives in its modal.
|
||||
*/
|
||||
export default function ConnectorAccounts({
|
||||
connector,
|
||||
@@ -70,6 +46,12 @@ export default function ConnectorAccounts({
|
||||
}: Props) {
|
||||
const [connecting, setConnecting] = useState(false);
|
||||
const [open_account, setOpenAccount] = useState<ConnectorAccountRecord>();
|
||||
const [busy, setBusy] = useState<Busy>();
|
||||
|
||||
const connect = useConnectorConnect({
|
||||
onConnected: (msg) => onChanged(msg),
|
||||
onError,
|
||||
});
|
||||
|
||||
/**
|
||||
* How many of this app's accounts are ready to use, whoever they belong
|
||||
@@ -83,55 +65,135 @@ export default function ConnectorAccounts({
|
||||
ConnectorAccountStatuses.find((entry) => entry.value == status)
|
||||
?.title || status;
|
||||
|
||||
const statusClass = (status: ConnectorAccountRecord["status"]) =>
|
||||
status == "connected"
|
||||
? "text-success dark:text-success-dark"
|
||||
: status == "pending"
|
||||
? "text-ink-secondary"
|
||||
: "text-hue-red";
|
||||
|
||||
const refresh = async ({ account }: { account: ConnectorAccountRecord }) => {
|
||||
if (busy) return;
|
||||
|
||||
if (account.status != "connected") {
|
||||
connect.start({
|
||||
connector_id: connector.id,
|
||||
label: account.label,
|
||||
account_id: account.id,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setBusy({ account_id: account.id, kind: "refresh" });
|
||||
|
||||
const res = await postAdminApi<{ connector_id: number; account: ConnectorAccountRecord }>({
|
||||
path: "connectors/refresh-account",
|
||||
body: { account_id: account.id },
|
||||
});
|
||||
|
||||
setBusy(undefined);
|
||||
|
||||
if (!res.success) {
|
||||
onError(res.msg || "Couldn't check it.");
|
||||
return;
|
||||
}
|
||||
|
||||
onChanged(res.msg || "Checked.");
|
||||
};
|
||||
|
||||
const disconnect = async ({ account }: { account: ConnectorAccountRecord }) => {
|
||||
if (busy) return;
|
||||
if (!window.confirm(`Disconnect ${account.label}? Runs using it lose it at once.`)) return;
|
||||
|
||||
setBusy({ account_id: account.id, kind: "disconnect" });
|
||||
|
||||
const res = await postAdminApi({
|
||||
path: "connectors/disconnect-account",
|
||||
body: { account_id: account.id },
|
||||
});
|
||||
|
||||
setBusy(undefined);
|
||||
|
||||
if (!res.success) {
|
||||
onError(res.msg || "Couldn't disconnect it.");
|
||||
return;
|
||||
}
|
||||
|
||||
onChanged(res.msg || "Disconnected.");
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack className="w-full gap-2! items-stretch pl-14 pr-4">
|
||||
{accounts.length ? (
|
||||
<Row className="flex-wrap items-center gap-2!">
|
||||
<Stack className="w-full gap-1!">
|
||||
{accounts.map((account) => (
|
||||
<Button
|
||||
<Row
|
||||
key={account.id}
|
||||
title={`${account.label}: ${accountReach({ account, targets, bots })}`}
|
||||
type="button"
|
||||
variant="outlined"
|
||||
color="gray"
|
||||
size="small"
|
||||
className="gap-2! w-full"
|
||||
onClick={() => setOpenAccount(account)}
|
||||
buttonContentProps={{ className: "w-full" }}
|
||||
className="w-full items-center gap-1! rounded-default border border-hairline py-0.5! pl-2 pr-1"
|
||||
>
|
||||
<Row className="w-full justify-between">
|
||||
<Row>
|
||||
<CircleUser size={14} aria-hidden />
|
||||
<Span className="text-sm text-ink">
|
||||
{account.label}
|
||||
</Span>
|
||||
</Row>
|
||||
<Button
|
||||
title={`Edit ${account.label}`}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
className="flex-1 min-w-0 justify-start gap-2! overflow-hidden px-1!"
|
||||
buttonContentProps={{ className: "w-full min-w-0" }}
|
||||
onClick={() => setOpenAccount(account)}
|
||||
>
|
||||
<CircleUser size={14} aria-hidden className="shrink-0" />
|
||||
<Span className="min-w-0 flex-1 truncate text-left text-sm text-ink">
|
||||
{account.label}
|
||||
</Span>
|
||||
</Button>
|
||||
|
||||
<Row>
|
||||
<Span className="text-xs text-ink-secondary">
|
||||
{isShared({ account })
|
||||
? accountReach({
|
||||
account,
|
||||
targets,
|
||||
bots,
|
||||
})
|
||||
: "Only your runs"}
|
||||
</Span>
|
||||
{account.status != "connected" ? (
|
||||
<Span className="text-xs text-hue-red">
|
||||
<CircleAlert
|
||||
size={12}
|
||||
aria-hidden
|
||||
className="mr-1 inline"
|
||||
/>
|
||||
{statusOf(account.status)}
|
||||
</Span>
|
||||
) : null}
|
||||
</Row>
|
||||
<Row className="shrink-0 items-center gap-1!">
|
||||
<Span
|
||||
className={twMerge(
|
||||
"text-xs",
|
||||
statusClass(account.status),
|
||||
)}
|
||||
>
|
||||
{statusOf(account.status)}
|
||||
</Span>
|
||||
<Button
|
||||
title={
|
||||
account.status == "connected"
|
||||
? `Check ${account.label} again`
|
||||
: `Reconnect ${account.label}`
|
||||
}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
className="px-1!"
|
||||
loading={
|
||||
busy?.account_id == account.id &&
|
||||
busy?.kind == "refresh"
|
||||
}
|
||||
onClick={() => refresh({ account })}
|
||||
>
|
||||
<RefreshCw size={14} aria-hidden />
|
||||
</Button>
|
||||
<Button
|
||||
title={`Disconnect ${account.label}`}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
className="px-1!"
|
||||
loading={
|
||||
busy?.account_id == account.id &&
|
||||
busy?.kind == "disconnect"
|
||||
}
|
||||
onClick={() => disconnect({ account })}
|
||||
>
|
||||
<CircleSlash size={14} aria-hidden />
|
||||
</Button>
|
||||
</Row>
|
||||
</Button>
|
||||
</Row>
|
||||
))}
|
||||
</Row>
|
||||
</Stack>
|
||||
) : (
|
||||
<Span className="text-xs text-ink-secondary">
|
||||
No account yet: add one, and your runs can use{" "}
|
||||
|
||||
@@ -37,9 +37,23 @@ export default function ConnectorConnectModal({ connector, onConnected, onCancel
|
||||
}}
|
||||
icon={<ConnectorLogo logo={connector.logo} name={connector.name} />}
|
||||
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."
|
||||
>
|
||||
<Form className="w-full flex-col gap-4! items-stretch" submitHandler={() => { setError(""); connect.start({ connector_id: connector.id, label }); }}>
|
||||
<Form
|
||||
className="w-full flex-col gap-4! items-stretch"
|
||||
submitHandler={() => {
|
||||
const name = label.trim();
|
||||
|
||||
if (!name) {
|
||||
setError("Name this connection, so you can tell it apart from another account of the same app.");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
setError("");
|
||||
connect.start({ connector_id: connector.id, label: name });
|
||||
}}
|
||||
>
|
||||
<Input
|
||||
id={`connector-${connector.id}-new-label`}
|
||||
title="Account name"
|
||||
@@ -49,7 +63,7 @@ export default function ConnectorConnectModal({ connector, onConnected, onCancel
|
||||
value={label}
|
||||
autoComplete="off"
|
||||
onChange={(e) => 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 ? (
|
||||
|
||||
@@ -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<APIResponseObject<Payload>> = 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 }) };
|
||||
}
|
||||
};
|
||||
@@ -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(""),
|
||||
});
|
||||
|
||||
|
||||
@@ -1756,6 +1756,22 @@ export type BotExtensionsPayload = {
|
||||
* composer's tools count includes them without reading them all.
|
||||
*/
|
||||
connector_count?: number;
|
||||
/**
|
||||
* The last few apps a connector account reaches here, for the composer's
|
||||
* tools button: their logo beside the spanner, so a glance says which
|
||||
* apps a message can use. Never repeats an app.
|
||||
*/
|
||||
connector_apps?: ConnectorAppIcon[];
|
||||
};
|
||||
|
||||
/**
|
||||
* One app a connector account reaches, as the composer's tools button shows
|
||||
* it.
|
||||
*/
|
||||
export type ConnectorAppIcon = {
|
||||
id: number;
|
||||
name: string;
|
||||
logo: string;
|
||||
};
|
||||
|
||||
export type McpServersOverviewPayload = ExtensionTargets & {
|
||||
|
||||
Reference in New Issue
Block a user