Compare commits
5
Commits
f8a7b0f2e7
...
7c92d0b4be
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c92d0b4be | ||
|
|
319eb74a23 | ||
|
|
c745f58991 | ||
|
|
b046e90958 | ||
|
|
4a02035f33 |
@@ -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.1",
|
||||
"version": "0.27.3",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -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,13 +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 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",
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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<Result> {
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
@@ -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<BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS>({
|
||||
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<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 || [])
|
||||
: [];
|
||||
|
||||
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,
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
|
||||
@@ -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{" "}
|
||||
|
||||
@@ -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