From dbfc84d4d7507af2b84fcd39fee5ea3ec34ecae7 Mon Sep 17 00:00:00 2001 From: David McKay Date: Wed, 25 Nov 2026 14:09:26 -0800 Subject: [PATCH 1/3] Connect another account at an app from the conversation 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 own card, which read "Gmail is ready now", and how-to steps. The job looked done, and the steps sent them to Connections. - A card for one more account at an app: the same card and the same press as Connections' Connect another account, in a new tab. Once the new account is listed it says which account Bots use and offers Make default. Drawn from show_app_access's answer behind a marker of its own (shared/connect-prompt.ts), so a front end that doesn't know it draws only the step's line, never "ready now". - An app card says "is ready now" only for an app that wasn't ready when the Bot asked, or that the card saw out of reach. A card about an app ready all along says what is true of it. --- .../channels/another-account-card.tsx | 247 ++++++++++++++ .../components/channels/app-access-card.tsx | 17 +- .../components/channels/chat-transcript.tsx | 8 + app/src/components/channels/tool-activity.tsx | 11 +- .../components/plugins/connect-in-new-tab.ts | 21 +- app/src/lib/copilot/carry-on.ts | 9 +- app/tests/another-account-card.test.tsx | 257 +++++++++++++++ app/tests/another-account-layout.fixture.tsx | 228 +++++++++++++ app/tests/another-account-layout.test.tsx | 309 ++++++++++++++++++ app/tests/app-access-card.test.tsx | 20 ++ shared/connect-prompt.ts | 74 +++++ 11 files changed, 1192 insertions(+), 9 deletions(-) create mode 100644 app/src/components/channels/another-account-card.tsx create mode 100644 app/tests/another-account-card.test.tsx create mode 100644 app/tests/another-account-layout.fixture.tsx create mode 100644 app/tests/another-account-layout.test.tsx diff --git a/app/src/components/channels/another-account-card.tsx b/app/src/components/channels/another-account-card.tsx new file mode 100644 index 0000000000..b0f087c809 --- /dev/null +++ b/app/src/components/channels/another-account-card.tsx @@ -0,0 +1,247 @@ +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 ( +
+
+
+ +
+
+

{name}

+ {listing.isPending ? null : listing.error ? ( +

+ {name}'s accounts couldn't be loaded. Try again in a moment. +

+ ) : ( +

+ {sentence( + name, + newest, + usedByDefault, + listing.data.canAddAnother, + )} +

+ )} +
+
+ {listing.data && !listing.error ? ( +
+ {newest ? ( + newest.isDefault ? null : ( + <> + {makeDefault.error ? ( +

+ {failureSaid(makeDefault.error)} +

+ ) : null} + + + ) + ) : listing.data.canAddAnother ? ( + + ) : null} +
+ ) : null} + {tab.consentStep} +
+ ); +} + +/** Which account Bots use, in the person's words. */ +function sentence( + name: string, + newest: BrokeredAccountRecord | undefined, + usedByDefault: BrokeredAccountRecord | undefined, + canAddAnother: boolean, +): string { + if (newest) + return newest.isDefault || !usedByDefault + ? `${newest.label} is connected. Bots use it by default.` + : `${newest.label} 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; +}) { + 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 ( + + ); + return ( + <> + {tab.error ? ( +

+ {failureSaid(tab.error)} +

+ ) : null} + {tab.blockedUrl ? ( +

+ This browser blocked the tab.{" "} + + Open {name}'s sign-in + + . +

+ ) : tab.waiting ? ( +

+ Finish in the tab that opened. +

+ ) : null} + + + ); +} diff --git a/app/src/components/channels/app-access-card.tsx b/app/src/components/channels/app-access-card.tsx index 15bb3d82b1..193fcd4ebd 100644 --- a/app/src/components/channels/app-access-card.tsx +++ b/app/src/components/channels/app-access-card.tsx @@ -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 ; return (
; + // 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 ; /* * 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 diff --git a/app/src/components/channels/tool-activity.tsx b/app/src/components/channels/tool-activity.tsx index 0ce9c7aea0..ee4af524c8 100644 --- a/app/src/components/channels/tool-activity.tsx +++ b/app/src/components/channels/tool-activity.tsx @@ -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"; @@ -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; } /** diff --git a/app/src/components/plugins/connect-in-new-tab.ts b/app/src/components/plugins/connect-in-new-tab.ts index f3d0a90f1b..dd0b98e921 100644 --- a/app/src/components/plugins/connect-in-new-tab.ts +++ b/app/src/components/plugins/connect-in-new-tab.ts @@ -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"; /** @@ -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 @@ -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(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. */ diff --git a/app/src/lib/copilot/carry-on.ts b/app/src/lib/copilot/carry-on.ts index 885a1eb2e4..918b982a5c 100644 --- a/app/src/lib/copilot/carry-on.ts +++ b/app/src/lib/copilot/carry-on.ts @@ -73,7 +73,13 @@ export function useCarryOn({ ready: boolean | null; blockedWhenAsked: boolean; app: string; -}): { carried: boolean; inHand: boolean; offer: (() => void) | null } { +}): { + carried: boolean; + inHand: boolean; + offer: (() => void) | null; + /** This card saw its app out of reach, here, so ready now is a change. */ + sawBlocked: boolean; +} { const conversation = useConversation(); const ask = conversation?.ask ?? null; const group = conversation?.carryOn ?? ALONE; @@ -118,6 +124,7 @@ export function useCarryOn({ const carried = toolCallId ? hasCarriedOn(toolCallId) : false; return { carried, + sawBlocked, inHand: joins, offer: joins && ready === true && !carried && group.view(key).offer diff --git a/app/tests/another-account-card.test.tsx b/app/tests/another-account-card.test.tsx new file mode 100644 index 0000000000..78a34f5418 --- /dev/null +++ b/app/tests/another-account-card.test.tsx @@ -0,0 +1,257 @@ +import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { + anotherAccountAnswer, + connectAppRefusal, + readAnotherAccountPrompt, + readConnectPrompt, + SHOW_APP_ACCESS_TOOL, +} from "@openbot/shared/connect-prompt"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + Outlet, + RouterProvider, +} from "@tanstack/react-router"; +import { + act, + cleanup, + fireEvent, + render, + waitFor, +} from "@testing-library/react"; +import type { ReactNode } from "react"; +import { ServerToolLine } from "@/components/channels/chat-transcript"; +import { setCurrentOrganization } from "@/lib/organizations/current"; +import { appAccess } from "./app-access-fixture"; +import { botAppResponse } from "./bot-grants-api"; +import { + accountsPage, + connectionResponse, + myAccountPath, + myConnectionPath, + startResponse, +} from "./connections-api"; +import { settleReactWork } from "./settle-react-work"; + +/** + * Asked to connect one more account at an app the person already connected ("Can I connect you to + * my personal email as well?"), a Bot puts up one card that starts that account's sign-in, as + * Connections' Connect another account does, and then says which account Bots use, with Make + * default where that isn't the new one. Reported in dogfooding: the Bot could only show Gmail's + * card, reading "Gmail is ready now", and three how-to guides. + */ + +beforeAll(() => GlobalRegistrator.register()); +afterEach(cleanup); +afterAll(async () => { + await settleReactWork(); + GlobalRegistrator.unregister(); +}); + +const originalFetch = global.fetch; +let originalOpen: typeof window.open | undefined; +beforeAll(() => { + originalOpen = window.open; +}); +afterEach(() => { + global.fetch = originalFetch; + if (originalOpen) window.open = originalOpen; +}); + +const APP = "composio-gmail"; +const WORK = { + id: "00000000-0000-4000-8000-000000000001", + identity: "sam@work.example", + label: "sam@work.example", + isDefault: true, + connectedAt: "2026-11-01T09:00:00.000Z", +}; +const PERSONAL = { + id: "00000000-0000-4000-8000-000000000002", + identity: "sam@home.example", + label: "sam@home.example", + isDefault: false, + connectedAt: "2026-11-25T09:00:00.000Z", +}; + +const answer = anotherAccountAnswer({ + serverId: APP, + title: "Gmail", + agentId: "assistant", + held: 1, + message: + "The card in front of the person offers Connect another account. Say so in one sentence.", +}); + +/** The server: Gmail's accounts as `state.accounts` says now, and every write the card sends. */ +function serving(state: { accounts: (typeof WORK)[] }) { + const writes: { path: string; body: unknown }[] = []; + global.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const path = new URL(String(input), "http://openbot.test").pathname; + const method = (init?.method ?? "GET").toUpperCase(); + if (method !== "GET") { + writes.push({ + path, + body: init?.body ? JSON.parse(String(init.body)) : null, + }); + if (path === myConnectionPath(APP, "connect")) + return startResponse({ + authorizationUrl: "https://gmail.test/consent", + }); + if (path === myAccountPath(APP, PERSONAL.id, "make-default")) { + state.accounts = state.accounts.map((account) => ({ + ...account, + isDefault: account.id === PERSONAL.id, + })); + return new Response(null, { status: 204 }); + } + return Response.json({}); + } + if (path.includes("/apps/")) + return botAppResponse( + appAccess({ key: APP, displayName: "Gmail", connect: "oauth" }), + ); + if (path === myConnectionPath(APP, "accounts")) + return accountsPage(state.accounts); + if (path === myConnectionPath(APP)) + return connectionResponse({ serverId: APP, canAddAccount: true }); + return Response.json({}); + }) as unknown as typeof fetch; + return writes; +} + +/** Where the sign-in tab was sent, recorded rather than opened. */ +function claimingTabs() { + const sent: string[] = []; + window.open = (() => ({ + opener: null, + closed: false, + location: { replace: (to: string) => sent.push(to) }, + close: () => {}, + focus: () => {}, + })) as unknown as typeof window.open; + return sent; +} + +function mount(children: ReactNode) { + setCurrentOrganization("default"); + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + const root = createRootRoute({ component: Outlet }); + const page = createRoute({ + getParentRoute: () => root, + path: "/", + component: () => <>{children}, + }); + const router = createRouter({ + routeTree: root.addChildren([page]), + history: createMemoryHistory({ initialEntries: ["/"] }), + }); + const view = render( + + + , + ); + return Object.assign(view, { client }); +} + +const card = (view: ReturnType) => + waitFor(() => { + const found = view.container.querySelector("[data-another-account]"); + if (!found?.getAttribute("data-state")) throw new Error("not drawn yet"); + return found as HTMLElement; + }); + +test("the answer is a card of its own, which an older reader leaves as a line", () => { + expect(readAnotherAccountPrompt(answer)).toEqual({ + serverId: APP, + title: "Gmail", + agentId: "assistant", + held: 1, + message: + "The card in front of the person offers Connect another account. Say so in one sentence.", + }); + // Never the app's own card, which would say Gmail is ready now. + expect(readConnectPrompt(answer)).toBeNull(); + expect( + readAnotherAccountPrompt( + connectAppRefusal({ serverId: APP, title: "Gmail", message: "" }), + ), + ).toBeNull(); +}); + +test("one card starts the second account's sign-in, then offers Make default for it", async () => { + const state = { accounts: [WORK] }; + const writes = serving(state); + const sent = claimingTabs(); + const view = mount( + , + ); + + const drawn = await card(view); + expect(drawn.getAttribute("data-state")).toBe("ready-to-connect"); + expect(drawn.textContent).toContain( + "Connect another Gmail account. Bots keep using sam@work.example until you make another the default.", + ); + expect(drawn.textContent).not.toContain("ready now"); + expect( + view.container.querySelectorAll("[data-another-account]"), + ).toHaveLength(1); + expect(view.container.querySelector("[data-app-access]")).toBeNull(); + + fireEvent.click( + await view.findByRole("button", { name: "Connect another Gmail account" }), + ); + await waitFor(() => expect(sent).toEqual(["https://gmail.test/consent"])); + // The same press as Connections' Connect another account. + expect(writes[0]).toEqual({ + path: myConnectionPath(APP, "connect"), + body: { returnTo: "connections", anotherAccount: true }, + }); + expect(await view.findByText("Finish in the tab that opened.")).toBeTruthy(); + + // Signed in with the second account in the other tab. + state.accounts = [WORK, PERSONAL]; + await act(() => view.client.invalidateQueries()); + await waitFor(async () => + expect((await card(view)).getAttribute("data-state")).toBe("connected"), + ); + expect((await card(view)).textContent).toContain( + "sam@home.example is connected. Bots use sam@work.example unless you ask for sam@home.example.", + ); + expect(view.queryByText("Finish in the tab that opened.")).toBeNull(); + + fireEvent.click( + await view.findByRole("button", { + name: "Make sam@home.example the default", + }), + ); + await waitFor(async () => + expect((await card(view)).textContent).toContain( + "sam@home.example is connected. Bots use it by default.", + ), + ); + expect(writes.at(-1)?.path).toBe( + myAccountPath(APP, PERSONAL.id, "make-default"), + ); + expect( + view.queryByRole("button", { name: /Make .* the default/ }), + ).toBeNull(); +}); + +test("drawn again after the account was connected, it says so and offers no second sign-in", async () => { + serving({ accounts: [WORK, PERSONAL] }); + const view = mount( + , + ); + const drawn = await card(view); + expect(drawn.getAttribute("data-state")).toBe("connected"); + expect( + view.queryByRole("button", { name: "Connect another Gmail account" }), + ).toBeNull(); +}); diff --git a/app/tests/another-account-layout.fixture.tsx b/app/tests/another-account-layout.fixture.tsx new file mode 100644 index 0000000000..0017e6d44e --- /dev/null +++ b/app/tests/another-account-layout.fixture.tsx @@ -0,0 +1,228 @@ +import type { Message } from "@ag-ui/core"; +import { CopilotKitProvider } from "@copilotkit/react-core/v2"; +import { + anotherAccountAnswer, + SHOW_APP_ACCESS_TOOL, +} from "@openbot/shared/connect-prompt"; +import { QueryClientProvider } from "@tanstack/react-query"; +import { + createBrowserHistory, + createRootRoute, + createRoute, + createRouter, + Outlet, + RouterProvider, +} from "@tanstack/react-router"; +import { createRoot } from "react-dom/client"; +import { ConversationView } from "@/components/channels/conversation-view"; +import { TooltipProvider } from "@/components/ui/tooltip"; +import { setCurrentOrganization } from "@/lib/organizations/current"; +import { queryClient } from "@/query-client"; +import { ME_PATH, meResponse } from "./accounts-api"; +import { DEPLOYMENT_PATH } from "./admin-settings-api"; +import { appAccess } from "./app-access-fixture"; +import { answerAppsApi } from "./apps-api"; +import { + APP_ACCESS_REQUESTS_PATH, + appAccessRequestsResponse, + botAppPath, + botAppResponse, +} from "./bot-grants-api"; +import { botPath } from "./bots-api"; +import { + accountsPage, + connectionResponse, + myAccountPath, + myConnectionPath, + startResponse, +} from "./connections-api"; + +/** + * A conversation in which the person, whose work Gmail is connected, asks to connect their personal + * email as well, and the Bot answered with the card for one more account. A page of its own for + * another-account-layout.test.tsx to bundle and load in a browser: the real conversation view draws + * the real card from the `show_app_access` answer, with this page playing the server and the app's + * sign-in. + * + * Connect's press claims a tab (recorded, not opened); the sign-in in that tab is taken to finish at + * once, so the next read of the person's accounts lists the second one. What the page sends is kept + * in order on `window.__events`: each write, each tab claimed and where it was sent. + */ +type Page = Window & { __events: string[] }; +const page = window as unknown as Page; +page.__events = []; +setCurrentOrganization("default"); + +const params = new URLSearchParams(location.search); +if (params.get("theme") === "dark") + document.documentElement.classList.add("dark"); + +const APP = "composio-gmail"; +const BOT = "assistant"; +const WORK = { + id: "00000000-0000-4000-8000-000000000001", + identity: "sam.rivera@work.example", + label: "sam.rivera@work.example", + isDefault: true, + connectedAt: "2026-11-01T09:00:00.000Z", +}; +const PERSONAL = { + id: "00000000-0000-4000-8000-000000000002", + identity: "sam.rivera@home.example", + label: "sam.rivera@home.example", + isDefault: false, + connectedAt: "2026-11-25T09:00:00.000Z", +}; +let accounts = [WORK]; +let signedIn = false; + +const original = window.fetch.bind(window); +window.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(String(input), location.origin); + const path = url.pathname; + const method = (init?.method ?? "GET").toUpperCase(); + if (!path.startsWith("/api/")) return original(input, init); + if (method !== "GET") + page.__events.push( + `${method} ${path}${init?.body ? ` ${String(init.body)}` : ""}`, + ); + if (path === DEPLOYMENT_PATH) + return Response.json({ + generativeUi: true, + selfHostBanner: false, + localEvaluation: true, + edition: "personal", + }); + if (path === ME_PATH) + return meResponse({ user: { id: "usr_me", role: "admin", name: "Me" } }); + if (path === botPath(BOT)) + return Response.json({ bot: { id: BOT, name: "Personal Assistant" } }); + if (path === botAppPath(BOT, APP)) + return botAppResponse( + appAccess({ key: APP, displayName: "Gmail", connect: "oauth" }), + ); + if (path === myConnectionPath(APP, "connect")) { + signedIn = true; + return startResponse({ authorizationUrl: "https://gmail.test/consent" }); + } + if (path === myConnectionPath(APP, "accounts")) { + if (signedIn && accounts.length === 1) accounts = [WORK, PERSONAL]; + return accountsPage(accounts); + } + if (path === myAccountPath(APP, PERSONAL.id, "make-default")) { + accounts = accounts.map((account) => ({ + ...account, + isDefault: account.id === PERSONAL.id, + })); + return new Response(null, { status: 204 }); + } + if (path === myConnectionPath(APP)) + return connectionResponse({ serverId: APP, canAddAccount: true }); + if (path === APP_ACCESS_REQUESTS_PATH) return appAccessRequestsResponse([]); + const apps = answerAppsApi(input, init, { + servers: [], + catalogue: [], + composioConfigured: true, + provider: "composio", + }); + if (apps) return apps; + return Response.json({ error: "Not found." }, { status: 404 }); +}) as typeof fetch; + +/** The tab a sign-in claims, recorded rather than opened. */ +window.open = (() => { + page.__events.push("tab claimed"); + const tab = { + opener: null as unknown, + closed: false, + location: { + replace: (to: string) => page.__events.push(`tab to ${to}`), + }, + close: () => { + tab.closed = true; + page.__events.push("tab closed"); + }, + focus: () => {}, + }; + return tab as unknown as Window; +}) as typeof window.open; + +const SO_FAR: Message[] = [ + { + id: "asked", + role: "user", + content: "Can I connect you to my personal email as well?", + }, + { + id: "called", + role: "assistant", + content: "", + toolCalls: [ + { + id: "call-1", + type: "function", + function: { + name: SHOW_APP_ACCESS_TOOL, + arguments: JSON.stringify({ app: "Gmail", anotherAccount: true }), + }, + }, + ], + }, + { + id: "answered", + role: "tool", + toolCallId: "call-1", + content: anotherAccountAnswer({ + serverId: APP, + title: "Gmail", + agentId: BOT, + held: 1, + message: + "The card in front of the person offers Connect another account. Say so in one sentence.", + }), + }, + { + id: "said", + role: "assistant", + content: + "Yes. Press Connect another account and sign in with your personal Gmail.", + }, +]; + +queryClient.setDefaultOptions({ queries: { retry: false } }); + +const root = createRootRoute({ component: Outlet }); +const conversation = createRoute({ + getParentRoute: () => root, + path: "/", + component: () => ( +
+ {}} + onSubmit={async () => {}} + pending={false} + stoppable={false} + /> +
+ ), +}); +const router = createRouter({ + routeTree: root.addChildren([conversation]), + history: createBrowserHistory(), +}); + +const mount = document.getElementById("root"); +if (mount) { + createRoot(mount).render( + + + + + + + , + ); +} diff --git a/app/tests/another-account-layout.test.tsx b/app/tests/another-account-layout.test.tsx new file mode 100644 index 0000000000..8e6649a0d7 --- /dev/null +++ b/app/tests/another-account-layout.test.tsx @@ -0,0 +1,309 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import type { Browser, BrowserType, Page } from "playwright-core"; +import { compile } from "tailwindcss"; +import { myAccountPath, myConnectionPath } from "./connections-api"; + +/** + * The card for one more account at an app, in a real browser, in the app's stylesheet. + * + * Reported in dogfooding: asked "Can I connect you to my personal email as well?" by somebody whose + * work Gmail was connected, a Bot showed Gmail's card reading "Gmail is ready now" and three how-to + * guides. Now it puts up one card, whose Connect another account starts the second account's sign-in + * in a tab claimed on the click, as Connections does, and once that account is listed says which one + * Bots use and offers Make default. another-account-card.test.tsx holds the behaviour; this drives it + * with a real mouse, light and dark. + * + * OPENBOT_APP_BROWSER=1 bun test app/tests/another-account-layout.test.tsx + * + * Chromium by default, as CI has it. OPENBOT_APP_ENGINES=chromium,webkit adds WebKit. With + * OPENBOT_APP_SHOTS= each step is saved as another-account---.png. + */ +const asked = process.env.OPENBOT_APP_BROWSER === "1"; +const shots = process.env.OPENBOT_APP_SHOTS; +const engines = (process.env.OPENBOT_APP_ENGINES ?? "chromium") + .split(",") + .map((engine) => engine.trim()) + .filter((engine) => engine === "chromium" || engine === "webkit") as ( + | "chromium" + | "webkit" +)[]; + +const APP_DIR = join(import.meta.dir, ".."); +const ORIGIN = "http://openbot.test"; +const GMAIL = "composio-gmail"; +const PERSONAL = "00000000-0000-4000-8000-000000000002"; + +/** The fixture bundled for the browser. `@/lib/marks` is Vite's `import.meta.glob`, so no marks. */ +async function bundle(): Promise { + const built = await Bun.build({ + entrypoints: [join(import.meta.dir, "another-account-layout.fixture.tsx")], + target: "browser", + define: { "process.env.NODE_ENV": JSON.stringify("production") }, + plugins: [ + { + name: "no-marks", + setup(build) { + build.onResolve({ filter: /^@\/lib\/marks$/ }, () => ({ + path: "marks", + namespace: "no-marks", + })); + build.onLoad({ filter: /.*/, namespace: "no-marks" }, () => ({ + contents: "export const markFor = () => null;", + loader: "js", + })); + }, + }, + ], + }); + if (!built.success) throw new AggregateError(built.logs, "bundle failed"); + const script = built.outputs.find((output) => output.kind === "entry-point"); + if (!script) throw new Error("bundle has no entry point"); + return script.text(); +} + +/** The directory of an installed package, from the app or the repository root. */ +function packageDir(name: string): string { + const dir = [ + join(APP_DIR, "node_modules", name), + join(APP_DIR, "..", "node_modules", name), + ].find(existsSync); + if (!dir) throw new Error(`no package ${name}`); + return dir; +} + +/** Where `@import "[/]"` lands, by the package's `style` export as Vite reads it. */ +function packageStylesheet(id: string): string { + const parts = id.split("/"); + const name = id.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]; + const dir = packageDir(name); + const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); + const subpath = `.${id.slice(name.length)}`; + const entry = pkg.exports?.[subpath]; + const file = + typeof entry === "string" + ? entry + : (entry?.style ?? entry?.default ?? pkg.main ?? "index.css"); + return join(dir, file); +} + +/** The app's stylesheet, built by Tailwind for these classes, as the app's build does. */ +async function stylesheet(classes: string[]): Promise { + const tailwind = dirname( + Bun.resolveSync("tailwindcss/package.json", APP_DIR), + ); + const entry = join(APP_DIR, "src", "styles.css"); + const compiler = await compile(readFileSync(entry, "utf8"), { + base: dirname(entry), + loadStylesheet: async (id, base) => { + const path = + id === "tailwindcss" + ? join(tailwind, "index.css") + : id.startsWith(".") + ? join(base, id) + : packageStylesheet(id); + return { path, base: dirname(path), content: readFileSync(path, "utf8") }; + }, + }); + return compiler.build(classes); +} + +const browsers = new Map(); +let script: string; + +beforeAll(async () => { + if (!asked) return; + script = await bundle(); + const playwright = await import("playwright-core"); + for (const engine of engines) { + const type: BrowserType = playwright[engine]; + browsers.set( + engine, + // The CI job installs full Chromium without the headless shell. + await type.launch(engine === "chromium" ? { channel: "chromium" } : {}), + ); + } +}, 120_000); + +afterAll(async () => { + for (const browser of browsers.values()) await browser.close(); +}); + +/** Styled for everything now on the page. */ +async function style(page: Page) { + const classes = await page.evaluate(() => + [...document.querySelectorAll("[class]")].flatMap((element) => [ + ...element.classList, + ]), + ); + await page.addStyleTag({ content: await stylesheet([...new Set(classes)]) }); + await page.evaluate(() => document.fonts.ready); + await page.evaluate(() => + Promise.race([ + Promise.all(document.getAnimations().map((motion) => motion.finished)), + new Promise((done) => setTimeout(done, 1_500)), + ]), + ); +} + +/** The fixture, in a window the width of a desktop app, or of a phone. */ +async function open( + engine: string, + theme: "light" | "dark", + width = 1000, +): Promise { + const browser = browsers.get(engine); + if (!browser) throw new Error(`no ${engine}`); + const page = await browser.newPage({ + viewport: { width, height: 760 }, + colorScheme: theme, + reducedMotion: "reduce", + }); + page.on("pageerror", (error) => console.error(error)); + const inter = join(packageDir("@fontsource-variable/inter"), "files"); + await page.route(`${ORIGIN}/**`, (route) => { + const path = new URL(route.request().url()).pathname; + if (path === "/another-account.js") + return route.fulfill({ contentType: "text/javascript", body: script }); + const font = join(inter, path.split("/").pop() ?? ""); + if (path.startsWith("/files/") && existsSync(font)) + return route.fulfill({ path: font }); + if (path.startsWith("/api/")) return route.fulfill({ status: 404 }); + return route.fulfill({ + contentType: "text/html", + body: `
`, + }); + }); + await page.goto(`${ORIGIN}/?theme=${theme}`); + return page; +} + +async function shoot(page: Page, step: string, name: string) { + if (!shots) return; + mkdirSync(shots, { recursive: true }); + await page.screenshot({ + path: join(shots, `another-account-${step}-${name}.png`), + }); +} + +/** How the card's control sits: inside the card, on one line, nothing running off the side. */ +function fits(page: Page) { + return page.locator("[data-another-account]").evaluate((element) => { + const box = element.getBoundingClientRect(); + const control = element.querySelector("button, a") as HTMLElement; + const inner = control.getBoundingClientRect(); + return { + inside: inner.left >= box.left && inner.right <= box.right, + oneLine: inner.height < 40, + sideways: document.documentElement.scrollWidth > innerWidth, + }; + }); +} + +/** What the page did about Gmail and its tab, leaving out the conversation's own requests. */ +const events = async (page: Page) => + ( + await page.evaluate( + () => (window as unknown as { __events: string[] }).__events, + ) + ).filter((event) => event.includes(GMAIL) || event.startsWith("tab ")); + +describe.skipIf(!asked)("the card for one more account", () => { + for (const engine of engines) + for (const theme of ["light", "dark"] as const) { + const name = `${engine}-${theme}`; + + test(`one card starts the second account's sign-in, then offers Make default, in ${engine}, ${theme}`, async () => { + const page = await open(engine, theme); + try { + const card = page.locator("[data-another-account]"); + const connect = card.getByRole("button", { + name: "Connect another Gmail account", + }); + await connect.waitFor({ timeout: 15_000 }); + await style(page); + await shoot(page, "card", name); + // One card, never the app's own "ready now" card beside it. + expect(await card.count()).toBe(1); + expect(await page.locator("[data-app-access]").count()).toBe(0); + expect(await page.getByText(/ready now/).count()).toBe(0); + expect(await card.textContent()).toContain( + "Connect another Gmail account. Bots keep using sam.rivera@work.example until you make another the default.", + ); + expect(await connect.textContent()).toBe("Connect another account"); + expect(await fits(page)).toEqual({ + inside: true, + oneLine: true, + sideways: false, + }); + + await connect.click(); + await page + .getByText("Finish in the tab that opened.") + .waitFor({ timeout: 15_000 }); + await style(page); + await shoot(page, "signing-in", name); + // Claimed on the click, then the same press Connections' Connect another account makes. + const seen = await events(page); + expect(seen.slice(0, 2)).toEqual([ + "tab claimed", + `POST ${myConnectionPath(GMAIL, "connect")} {"returnTo":"connections","anotherAccount":true}`, + ]); + expect(seen[2]?.startsWith("tab to ")).toBe(true); + + // The second account is listed on the card's next read. + await card + .getByRole("button", { + name: "Make sam.rivera@home.example the default", + }) + .waitFor({ timeout: 15_000 }); + await style(page); + await shoot(page, "connected", name); + expect(await card.textContent()).toContain( + "sam.rivera@home.example is connected. Bots use sam.rivera@work.example unless you ask for sam.rivera@home.example.", + ); + expect(await fits(page)).toEqual({ + inside: true, + oneLine: true, + sideways: false, + }); + + await card + .getByRole("button", { name: /Make .* the default/ }) + .click(); + await page + .getByText( + "sam.rivera@home.example is connected. Bots use it by default.", + ) + .waitFor({ timeout: 15_000 }); + await style(page); + await shoot(page, "made-default", name); + expect(await events(page)).toContain( + `POST ${myAccountPath(GMAIL, PERSONAL, "make-default")}`, + ); + } finally { + await page.close(); + } + }, 90_000); + + test(`the card in a narrow window, in ${engine}, ${theme}`, async () => { + const page = await open(engine, theme, 390); + try { + const card = page.locator("[data-another-account]"); + await card + .getByRole("button", { name: "Connect another Gmail account" }) + .waitFor({ timeout: 15_000 }); + await style(page); + await shoot(page, "narrow", name); + expect(await fits(page)).toEqual({ + inside: true, + oneLine: true, + sideways: false, + }); + } finally { + await page.close(); + } + }, 90_000); + } +}); diff --git a/app/tests/app-access-card.test.tsx b/app/tests/app-access-card.test.tsx index 0090353d4f..4e471ef353 100644 --- a/app/tests/app-access-card.test.tsx +++ b/app/tests/app-access-card.test.tsx @@ -714,6 +714,26 @@ describe("carrying the task on once the app is ready", () => { }, ); + /* + * FOUND IN DOGFOODING. Asked to connect a personal mailbox beside a connected work one, a Bot + * showed Gmail's card, the latest thing in the conversation, and it read "Gmail is ready now": the + * job looked done. Gmail had been ready all along, and the card says only what is true of it. + */ + test("show_app_access about an app ready all along never says it is ready now", async () => { + servingNow({ live: appAccess({ state: "ready" }) }); + const view = inConversation( + , + ); + const drawn = await card(view); + await settleReactWork(); + expect(drawn.textContent).toContain("Ready to use."); + expect(drawn.textContent).not.toContain("ready now"); + expect(view.asked).toEqual([]); + }); + test("with no conversation around it, the card only says the app is ready", async () => { servingNow({ live: appAccess({ state: "ready" }) }); const view = mount( diff --git a/shared/connect-prompt.ts b/shared/connect-prompt.ts index eeedd3526e..87f31aca02 100644 --- a/shared/connect-prompt.ts +++ b/shared/connect-prompt.ts @@ -232,3 +232,77 @@ export function readConnectPrompt( return null; } } + +/** + * The first characters of `show_app_access`'s answer when the person asked to connect one more + * account at an app they already connected (a personal mailbox beside a work one), immediately + * followed by its JSON. + * + * A MARKER OF ITS OWN, NOT A NEW `ConnectReason`. A front end released before this card reads an + * unknown reason as `connect`, and the app's live state is `ready`, so it drew "Gmail is ready now" + * over a question about a second Gmail: the job read as done (reported in dogfooding). A marker it + * doesn't know draws only the step's line, and the Bot's reply says what to do. + */ +export const ANOTHER_ACCOUNT_MARKER = "[connect-another-account]"; + +/** The card that starts the sign-in for one more account at an app, as the transcript reads it. */ +export type AnotherAccountPrompt = { + /** The app, as `ConnectPrompt.serverId` names it: what the card connects and lists accounts of. */ + serverId: string; + /** The app's own name. */ + title: string; + /** What the Bot was told, kept for a reader with no card to draw. */ + message: string; + /** The Bot that asked. */ + agentId?: string; + /** + * How many accounts the person held at the app when the Bot asked. More than this listed now is + * the account connected from the card, so a card scrolled back to (or drawn after a reload) says + * it is connected and never offers the sign-in again. Absent reads as one. + */ + held?: number; +}; + +/** `show_app_access`'s answer for one more account at an app: the marker, then what the model reads. */ +export function anotherAccountAnswer(prompt: AnotherAccountPrompt): string { + const { serverId, title, message, agentId, held } = prompt; + return `${ANOTHER_ACCOUNT_MARKER}${JSON.stringify({ + serverId, + title, + ...(agentId ? { agentId } : {}), + ...(held !== undefined ? { held } : {}), + })} ${message}`; +} + +/** The prompt inside that answer, or null for any other text. Fails to null, as `readConnectPrompt` does. */ +export function readAnotherAccountPrompt( + text: string | undefined | null, +): AnotherAccountPrompt | null { + if (!text?.startsWith(ANOTHER_ACCOUNT_MARKER)) return null; + const rest = text.slice(ANOTHER_ACCOUNT_MARKER.length); + const end = rest.indexOf("}"); + if (end < 0) return null; + try { + const parsed: unknown = JSON.parse(rest.slice(0, end + 1)); + if (!parsed || typeof parsed !== "object") return null; + const { serverId, title, agentId, held } = parsed as { + serverId?: unknown; + title?: unknown; + agentId?: unknown; + held?: unknown; + }; + if (typeof serverId !== "string" || typeof title !== "string") return null; + if (!serverId || !title) return null; + return { + serverId, + title, + message: rest.slice(end + 1).trim(), + ...(typeof agentId === "string" && agentId ? { agentId } : {}), + ...(typeof held === "number" && Number.isInteger(held) && held >= 0 + ? { held } + : {}), + }; + } catch { + return null; + } +} From 1f0bc26753c7d13ad9bba85bc115d8c582c2d105 Mon Sep 17 00:00:00 2001 From: David McKay Date: Wed, 25 Nov 2026 14:22:16 -0800 Subject: [PATCH 2/3] Start the another-account card's sentence with a capital for an account with no address --- .../components/channels/another-account-card.tsx | 12 ++++++++++-- app/tests/another-account-card.test.tsx | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/app/src/components/channels/another-account-card.tsx b/app/src/components/channels/another-account-card.tsx index b0f087c809..43591ba276 100644 --- a/app/src/components/channels/another-account-card.tsx +++ b/app/src/components/channels/another-account-card.tsx @@ -162,10 +162,18 @@ function sentence( 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 - ? `${newest.label} is connected. Bots use it by default.` - : `${newest.label} is connected. Bots use ${usedByDefault.label} unless you ask for ${newest.label}.`; + ? `${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.` diff --git a/app/tests/another-account-card.test.tsx b/app/tests/another-account-card.test.tsx index 78a34f5418..695884ab0b 100644 --- a/app/tests/another-account-card.test.tsx +++ b/app/tests/another-account-card.test.tsx @@ -255,3 +255,19 @@ test("drawn again after the account was connected, it says so and offers no seco view.queryByRole("button", { name: "Connect another Gmail account" }), ).toBeNull(); }); + +// Found in the live journey: an account the app names by no address started the sentence lower case. +test("an account with no address starts its sentence with a capital", async () => { + serving({ + accounts: [ + { ...WORK, identity: null, label: "account 1" }, + { ...PERSONAL, identity: null, label: "account 2" }, + ], + }); + const view = mount( + , + ); + expect((await card(view)).textContent).toContain( + "Account 2 is connected. Bots use account 1 unless you ask for account 2.", + ); +}); From 053efc8e7bb71676603aa3999428b3ed4242294e Mon Sep 17 00:00:00 2001 From: David McKay Date: Wed, 25 Nov 2026 14:26:33 -0800 Subject: [PATCH 3/3] Type the card test's accounts as the app reads them --- app/tests/another-account-card.test.tsx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/app/tests/another-account-card.test.tsx b/app/tests/another-account-card.test.tsx index 695884ab0b..ec45b2eab3 100644 --- a/app/tests/another-account-card.test.tsx +++ b/app/tests/another-account-card.test.tsx @@ -26,6 +26,7 @@ import { import type { ReactNode } from "react"; import { ServerToolLine } from "@/components/channels/chat-transcript"; import { setCurrentOrganization } from "@/lib/organizations/current"; +import type { BrokeredAccountRecord } from "@/lib/plugins/queries"; import { appAccess } from "./app-access-fixture"; import { botAppResponse } from "./bot-grants-api"; import { @@ -63,14 +64,14 @@ afterEach(() => { }); const APP = "composio-gmail"; -const WORK = { +const WORK: BrokeredAccountRecord = { id: "00000000-0000-4000-8000-000000000001", identity: "sam@work.example", label: "sam@work.example", isDefault: true, connectedAt: "2026-11-01T09:00:00.000Z", }; -const PERSONAL = { +const PERSONAL: BrokeredAccountRecord = { id: "00000000-0000-4000-8000-000000000002", identity: "sam@home.example", label: "sam@home.example", @@ -88,7 +89,7 @@ const answer = anotherAccountAnswer({ }); /** The server: Gmail's accounts as `state.accounts` says now, and every write the card sends. */ -function serving(state: { accounts: (typeof WORK)[] }) { +function serving(state: { accounts: BrokeredAccountRecord[] }) { const writes: { path: string; body: unknown }[] = []; global.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { const path = new URL(String(input), "http://openbot.test").pathname;