Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
255 changes: 255 additions & 0 deletions app/src/components/channels/another-account-card.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,255 @@
import type { AnotherAccountPrompt } from "@openbot/shared/connect-prompt";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Link } from "@tanstack/react-router";
import { useEffect } from "react";
import { useConnectInNewTab } from "@/components/plugins/connect-in-new-tab";
import { PluginLogo } from "@/components/plugins/plugin-logo";
import { Button } from "@/components/ui/button";
import { botAppQueryOptions } from "@/lib/app-access/queries";
import { useDeclaredBotId } from "@/lib/copilot/active-bot";
import { failureSaid } from "@/lib/load-failure";
import { setDefaultBrokeredAccountMutationOptions } from "@/lib/plugins/mutations";
import {
type BrokeredAccountRecord,
brokeredAccountsQueryOptions,
pluginKeys,
} from "@/lib/plugins/queries";

/**
* One more account at an app the person already connected, started where they asked for it.
*
* FOUND IN DOGFOODING. Asked "Can I connect you to my personal email as well?" by somebody whose
* work Gmail was connected, a Bot could only show Gmail's card, which read "Gmail is ready now", and
* three how-to guides, two of them about something else. Connections had Connect another account
* all along; this card is that press, in the conversation.
*
* THE SAME CARD AND THE SAME PRESS. Drawn as the app-access card is drawn, and the button starts the
* sign-in in a new tab with `useConnectInNewTab`, asking for another account the way Connections'
* Connect another account asks (`connectAnotherAccountMutationOptions`). The person's accounts at
* the app are read live, as the app's page reads them.
*
* AND THEN WHICH ACCOUNT BOTS USE. Once the app lists more accounts than the person held when the
* Bot asked (`held`), the newest is the one just connected (the server lists oldest first). The card
* says which account Bots use and, where that isn't the new one, offers Make default, the same press
* as on the app's page. A card scrolled back to, or drawn after a reload, says the same.
*/
export function AnotherAccountCard({
prompt,
}: {
prompt: AnotherAccountPrompt;
}) {
const declared = useDeclaredBotId();
const agentId = prompt.agentId ?? declared ?? "";
const queryClient = useQueryClient();
const app = useQuery({
...botAppQueryOptions(agentId, prompt.serverId),
enabled: agentId !== "",
});
const listing = useQuery({
...brokeredAccountsQueryOptions(prompt.serverId),
refetchOnWindowFocus: true,
});
const tab = useConnectInNewTab({ another: true });
const makeDefault = useMutation(
setDefaultBrokeredAccountMutationOptions(queryClient),
);

const name = app.data?.displayName ?? prompt.title;
const accounts = listing.data?.accounts ?? [];
const connectedSince = accounts.length > Math.max(prompt.held ?? 1, 1);
const newest = connectedSince ? accounts.at(-1) : undefined;
const usedByDefault = accounts.find((account) => account.isDefault);

/*
* WATCHING THE SERVER WHILE THE SIGN-IN IS OPEN in the other tab, as `ConnectAction` does: the
* accounts are read every two seconds until the new one is listed, and then the wait ends.
*/
const { waiting, stopWaiting } = tab;
useEffect(() => {
if (!waiting) return;
const timer = setInterval(() => {
void queryClient.invalidateQueries({
queryKey: pluginKeys.accounts(prompt.serverId),
});
}, 2_000);
return () => clearInterval(timer);
}, [waiting, queryClient, prompt.serverId]);
useEffect(() => {
if (connectedSince && waiting) stopWaiting();
}, [connectedSince, waiting, stopWaiting]);

return (
<div
className="my-2 flex w-full max-w-2xl flex-col gap-3 rounded-xl border border-border p-4"
data-another-account={prompt.serverId}
data-state={
listing.isPending
? undefined
: newest
? "connected"
: listing.data?.canAddAnother
? "ready-to-connect"
: "only-one"
}
>
<div className="flex items-start gap-3">
<div className="flex size-8 shrink-0 items-center justify-center rounded-md border border-border">
<PluginLogo logo={app.data?.logo} />
</div>
<div className="flex min-w-0 flex-1 flex-col gap-1">
<p className="font-medium text-sm">{name}</p>
{listing.isPending ? null : listing.error ? (
<p className="text-muted-foreground text-sm" role="alert">
{name}'s accounts couldn't be loaded. Try again in a moment.
</p>
) : (
<p className="text-muted-foreground text-sm">
{sentence(
name,
newest,
usedByDefault,
listing.data.canAddAnother,
)}
</p>
)}
</div>
</div>
{listing.data && !listing.error ? (
<div className="flex flex-wrap items-center justify-end gap-2">
{newest ? (
newest.isDefault ? null : (
<>
{makeDefault.error ? (
<p className="text-destructive text-xs" role="alert">
{failureSaid(makeDefault.error)}
</p>
) : null}
<Button
aria-label={`Make ${newest.label} the default`}
disabled={makeDefault.isPending}
onClick={() =>
makeDefault.mutate({
serverId: prompt.serverId,
accountId: newest.id,
})
}
size="sm"
variant="outline"
>
Make default
</Button>
</>
)
) : listing.data.canAddAnother ? (
<ConnectAnother
keyApp={app.data?.connect === "key"}
name={name}
serverId={prompt.serverId}
tab={tab}
/>
) : null}
</div>
) : null}
{tab.consentStep}
</div>
);
}

/** Which account Bots use, in the person's words. */
function sentence(
name: string,
newest: BrokeredAccountRecord | undefined,
usedByDefault: BrokeredAccountRecord | undefined,
canAddAnother: boolean,
): string {
/*
* An account the app names by no address is "account 2", which starts the sentence with a capital.
* FOUND IN THE LIVE JOURNEY: "account 2 is connected." An address is left as the app writes it.
*/
const first =
newest && newest.identity === null
? newest.label.charAt(0).toUpperCase() + newest.label.slice(1)
: newest?.label;
if (newest)
return newest.isDefault || !usedByDefault
? `${first} is connected. Bots use it by default.`
: `${first} is connected. Bots use ${usedByDefault.label} unless you ask for ${newest.label}.`;
if (!canAddAnother) return `You can't connect a second ${name} account.`;
return usedByDefault
? `Connect another ${name} account. Bots keep using ${usedByDefault.label} until you make another the default.`
: `Connect another ${name} account.`;
}

/** The press itself, and what it says while the sign-in is open in the other tab. */
function ConnectAnother({
keyApp,
name,
serverId,
tab,
}: {
keyApp: boolean;
name: string;
serverId: string;
tab: ReturnType<typeof useConnectInNewTab>;
}) {
const label = "Connect another account";
// A key is typed on the app's own page, where Connect another account opens its form.
if (keyApp || tab.needsKey)
return (
<Button
aria-label={`Connect another ${name} account`}
render={<Link params={{ key: serverId }} to="/connections/$key" />}
size="sm"
variant="outline"
>
{label}
</Button>
);
return (
<>
{tab.error ? (
<p className="text-destructive text-xs" role="alert">
{failureSaid(tab.error)}
</p>
) : null}
{tab.blockedUrl ? (
<p className="text-xs" role="status">
This browser blocked the tab.{" "}
<a
className="underline underline-offset-2"
href={tab.blockedUrl}
rel="noreferrer"
target="_blank"
>
Open {name}'s sign-in
</a>
.
</p>
) : tab.waiting ? (
<p className="text-muted-foreground text-xs" role="status">
Finish in the tab that opened.
</p>
) : null}
<Button
aria-label={
tab.waiting || tab.pending
? undefined
: `Connect another ${name} account`
}
disabled={tab.pending}
onClick={() => {
tab.stopWaiting();
tab.open(serverId);
}}
size="sm"
variant="outline"
>
{tab.waiting
? `Waiting for ${name}…`
: tab.pending
? "Opening sign-in…"
: label}
</Button>
</>
);
}
17 changes: 13 additions & 4 deletions app/src/components/channels/app-access-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -123,14 +123,23 @@ function LiveAppAccessCard({
*/
const fallsBack =
Boolean(live.error) && (prompt.reason ?? "connect") === "connect";
const { carried, inHand, offer } = useCarryOn({
// A refusal was blocked by definition; `show_app_access` says what it found.
const blockedWhenAsked =
prompt.reason !== "access" || prompt.blocked === true;
const { carried, inHand, offer, sawBlocked } = useCarryOn({
// The Connect card drawn instead carries on for this call; this one, never ready, must not wait.
place: fallsBack ? undefined : place,
ready: access ? access.state === "ready" : null,
// A refusal was blocked by definition; `show_app_access` says what it found.
blockedWhenAsked: prompt.reason !== "access" || prompt.blocked === true,
blockedWhenAsked,
app: name,
});
/*
* "IS READY NOW" ONLY FOR AN APP THAT WAS NOT. FOUND IN DOGFOODING: asked to connect a personal
* mailbox beside a connected work one, a Bot showed Gmail's card, and because the card was the
* latest thing in the conversation it read "Gmail is ready now", as if the job were done. Gmail had
* been ready all along. A card whose app was ready when the Bot asked says what is true of it.
*/
const becameReady = blockedWhenAsked || sawBlocked;
if (fallsBack) return <ConnectAppCard {...prompt} place={place} />;
return (
<div
Expand Down Expand Up @@ -162,7 +171,7 @@ function LiveAppAccessCard({
admins,
open,
)
: carried || inHand || offer
: becameReady && (carried || inHand || offer)
? `${name} is ready now.`
: prompt.reason !== "access"
? `${name} is ready now. Ask again and the Bot can use it.`
Expand Down
8 changes: 8 additions & 0 deletions app/src/components/channels/chat-transcript.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
} from "@copilotkit/react-core/v2";
import { outcomeForPerson } from "@openbot/shared/approval-outcomes";
import {
readAnotherAccountPrompt,
readConnectPrompt,
SHOW_APP_ACCESS_TOOL,
} from "@openbot/shared/connect-prompt";
Expand Down Expand Up @@ -149,6 +150,7 @@ import {
import { readTeamBotConsent } from "@/lib/team-bots";
import { cn } from "@/lib/utils";
import { VOICE_CHAT_ACTIVITY, type VoiceChatEntry } from "@/lib/voice/archive";
import { AnotherAccountCard } from "./another-account-card";
import { AppAccessCard } from "./app-access-card";
import {
AttachmentLightbox,
Expand Down Expand Up @@ -1933,6 +1935,12 @@ export function ServerToolLine({
? readConnectPrompt(answer)
: null;
if (card) return <AppAccessCard place={place} prompt={card} />;
// Asked to connect one more account at an app: its sign-in, started from the card.
const another =
!refused && name === SHOW_APP_ACCESS_TOOL
? readAnotherAccountPrompt(answer)
: null;
if (another) return <AnotherAccountCard prompt={another} />;
/*
* THAT TOOL'S OTHER ANSWERS ARE FOR THE MODEL. An app nobody can name comes back as plain text
* telling the Bot to say so plainly and not to browse to it — an instruction, which read by the
Expand Down
11 changes: 10 additions & 1 deletion app/src/components/channels/tool-activity.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { CopilotKitContext } from "@copilotkit/react-core/v2/context";
import { outcomeForPerson } from "@openbot/shared/approval-outcomes";
import {
readAnotherAccountPrompt,
readConnectPrompt,
SHOW_APP_ACCESS_TOOL,
} from "@openbot/shared/connect-prompt";
Expand Down Expand Up @@ -256,7 +257,15 @@ function cardApp(item: ToolItem): string | null {
: item.toolCall.function.name === SHOW_APP_ACCESS_TOOL
? readConnectPrompt(answer)
: null;
return prompt ? `${prompt.agentId ?? ""}\u0000${prompt.serverId}` : null;
if (prompt) return `${prompt.agentId ?? ""}\u0000${prompt.serverId}`;
// The card for one more account is a question of its own, kept apart from the app's own card.
const another =
item.toolCall.function.name === SHOW_APP_ACCESS_TOOL
? readAnotherAccountPrompt(answer)
: null;
return another
? `another\u0000${another.agentId ?? ""}\u0000${another.serverId}`
: null;
}

/**
Expand Down
21 changes: 18 additions & 3 deletions app/src/components/plugins/connect-in-new-tab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ import {
storeConsentHandoff,
} from "@/lib/plugins/consent-handoff";
import { finishInBackground } from "@/lib/plugins/finish-on-return";
import { connectAccountMutationOptions } from "@/lib/plugins/mutations";
import {
connectAccountMutationOptions,
connectAnotherAccountMutationOptions,
} from "@/lib/plugins/mutations";
import { pluginKeys } from "@/lib/plugins/queries";

/**
Expand All @@ -35,7 +38,15 @@ import { pluginKeys } from "@/lib/plugins/queries";
* button that pressed it is swapped for another between the two.
*/

export function useConnectInNewTab() {
export function useConnectInNewTab(
options: {
/**
* One more account at an app the person already connected: the press Connections' Connect
* another account makes (`connectAnotherAccountMutationOptions`), from a card in a conversation.
*/
another?: boolean;
} = {},
) {
/*
* The provider's client, which is the one whoever drew the button reads from. In the app it is
* the module's own singleton; a screen mounted under another provider is refetched through its
Expand All @@ -47,7 +58,11 @@ export function useConnectInNewTab() {
const [needsKey, setNeedsKey] = useState(false);
/** The authorization url, when the browser refused to open the tab holding it. */
const [blockedUrl, setBlockedUrl] = useState<string | null>(null);
const connect = useMutation(connectAccountMutationOptions());
const connect = useMutation(
options.another
? connectAnotherAccountMutationOptions()
: connectAccountMutationOptions(),
);
// Stable, so a caller can list it in an effect's dependencies without re-running it every render.
const stopWaiting = useCallback(() => setWaiting(false), []);
/** The tab the consent is open in, while there is one to watch. */
Expand Down
Loading