Reconnect an account in place, and keep its card readable
This commit is contained in:
@@ -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
|
||||
*/
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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(""),
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user