Skip to content

Commit afeb878

Browse files
authored
After connecting an app from a Bot's card, the sign-in's tab closes and you're back with the Bot (#2071)
Connect on a Bot's card (or an app row on a Bot's page) opens the sign-in in a new tab, and the connect route brings a browser back to the app's page under Connections. So after connecting Gmail from a conversation the person was left on Gmail's page in that tab, while the Bot was already carrying on in the first one. The tab the card claims is now told, before it leaves OpenBot, where Connect was pressed: written into that tab's own session storage. The app's page reads and drops the note on arrival, and once the account is listed as connected it closes the tab, or, where the browser won't close it, goes back to where Connect was pressed. A sign-in that came back failed leaves the person where the failure is said. Two real-browser cases in consent-handoff.test.tsx (Chromium and WebKit): the tab closes once Gmail is connected, and goes back to the card where closing is refused. Both fail on main.
1 parent 2337a62 commit afeb878

5 files changed

Lines changed: 210 additions & 1 deletion

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,9 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged.
307307

308308
### Smaller changes
309309

310+
- After connecting an app from a Bot's card or a Bot's page, you're back where you pressed Connect.
311+
The sign-in's tab closes once the app is connected, or, where the browser won't close it, goes back
312+
to the conversation or the Bot's page. It used to stay on the app's page under Connections.
310313
- **A Bot's command is no longer refused as "not saved", and the Bot gets what it printed.** Every
311314
command a Bot runs is checked against the saved conversation first, and the saved copy can trail
312315
the conversation on screen by several seconds on a busy day. A command checked too soon was

‎app/src/components/plugins/connect-in-new-tab.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
22
import { createElement, useCallback, useEffect, useRef, useState } from "react";
33
import { ConsentHandoffDialog } from "@/components/plugins/consent-handoff";
44
import { desktopShell } from "@/lib/desktop/shell";
5+
import { markConnectReturn } from "@/lib/plugins/connect-return";
56
import {
67
brokeredConsentFor,
78
type ConsentHandoff,
@@ -128,6 +129,14 @@ export function useConnectInNewTab() {
128129
return tab;
129130
};
130131

132+
/*
133+
* WHERE THE PRESS WAS MADE goes with the tab, so the page the sign-in comes back to can close it,
134+
* or send it back here, once the account is connected (lib/plugins/connect-return.ts). Written
135+
* before the tab leaves OpenBot, while it is still this site's blank page.
136+
*/
137+
const here = () =>
138+
`${window.location.pathname}${window.location.search}${window.location.hash}`;
139+
131140
/**
132141
* `first` runs between claiming the tab and asking for the consent, for a press that has to turn
133142
* the app on before it can be connected (the personal edition's chat card). The tab is claimed
@@ -141,6 +150,7 @@ export function useConnectInNewTab() {
141150
}
142151
const tab = claimTab();
143152
handle.current = tab;
153+
markConnectReturn(tab, serverId, here());
144154
void ask(serverId, tab);
145155
};
146156

@@ -151,8 +161,12 @@ export function useConnectInNewTab() {
151161
const openAfter = (first: () => Promise<string>) => {
152162
const tab = claimTab();
153163
handle.current = tab;
164+
const from = here();
154165
first().then(
155-
(serverId) => void ask(serverId, tab),
166+
(serverId) => {
167+
markConnectReturn(tab, serverId, from);
168+
void ask(serverId, tab);
169+
},
156170
() => {
157171
tab?.close();
158172
handle.current = null;
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
import { useQuery } from "@tanstack/react-query";
2+
import { useRouter } from "@tanstack/react-router";
3+
import { useEffect, useState } from "react";
4+
import { connectionsQueryOptions, personalConnections } from "./queries";
5+
6+
/**
7+
* BACK TO WHERE CONNECT WAS PRESSED, once the sign-in a new tab opened is done.
8+
*
9+
* A Bot's card in a conversation, and an app's row on a Bot's page, start a sign-in in a new tab
10+
* (`useConnectInNewTab`), so the person never leaves what they were in the middle of. The sign-in
11+
* comes back to the app's page under Connections, because that is where the connect route returns
12+
* a browser to. Reported: after connecting Gmail from a conversation, the person was left on
13+
* Gmail's page in the new tab, when what they expected was the Bot they had been talking to, which
14+
* by then was already carrying on in the first tab.
15+
*
16+
* So the tab is told, before it leaves, where the press was made: written into the new tab's own
17+
* session storage while it is still OpenBot's blank page, which the vendor's pages cannot touch and
18+
* which is still there when the tab comes back to OpenBot. On the app's page, once the account is
19+
* listed as connected, the tab closes, which puts the person back on the tab they pressed Connect
20+
* in. Where the browser will not let it close, it goes to that page instead.
21+
*
22+
* ONLY THE PAGE THE SIGN-IN LANDS ON acts on it, and only once: the note is read and dropped on
23+
* arrival, so somebody who stays in that tab and moves on is never taken anywhere later. A sign-in
24+
* that failed comes back saying so (`?status=failed`), and then the person stays where the failure
25+
* is said. Storage refused (a private window, a policy) means no note: the page works as before.
26+
*/
27+
28+
const KEY = "openbot:connect-return";
29+
30+
type Note = { app: string; path: string };
31+
32+
/**
33+
* Tell the tab a sign-in is about to open in where to come back to. `tab` is the blank tab claimed
34+
* on the click, still OpenBot's origin, so its session storage is this site's, in that tab.
35+
*/
36+
export function markConnectReturn(
37+
tab: Window | null,
38+
app: string,
39+
path: string,
40+
): void {
41+
if (!tab) return;
42+
try {
43+
tab.sessionStorage.setItem(KEY, JSON.stringify({ app, path }));
44+
} catch {
45+
// No storage: the tab stays where the sign-in lands, as it did before. See above.
46+
}
47+
}
48+
49+
/** The note this tab was given, dropped as it is read so it can be acted on once. */
50+
function takeNote(): Note | null {
51+
try {
52+
const text = sessionStorage.getItem(KEY);
53+
if (text === null) return null;
54+
sessionStorage.removeItem(KEY);
55+
const note = JSON.parse(text) as Partial<Note>;
56+
return typeof note.app === "string" &&
57+
typeof note.path === "string" &&
58+
// Only a path in OpenBot itself, never an address somewhere else.
59+
note.path.startsWith("/") &&
60+
!note.path.startsWith("//")
61+
? { app: note.app, path: note.path }
62+
: null;
63+
} catch {
64+
return null;
65+
}
66+
}
67+
68+
/** Whether the address the sign-in came back to says it failed. */
69+
function cameBackFailed(): boolean {
70+
const search = new URLSearchParams(window.location.search);
71+
return (
72+
search.get("status") === "failed" || search.get("connected") === "failed"
73+
);
74+
}
75+
76+
/**
77+
* On an app's page under Connections: when this tab was opened for this app's sign-in, close it
78+
* once the account is connected, or go back to where Connect was pressed. See above.
79+
*/
80+
export function useBackAfterConnect(app: string): void {
81+
const [note] = useState(() => {
82+
const taken = takeNote();
83+
return taken && !cameBackFailed() ? taken : null;
84+
});
85+
const waiting = note !== null && note.app === app;
86+
const connections = useQuery({
87+
...connectionsQueryOptions(),
88+
enabled: waiting,
89+
// The page confirms the account on arrival; until it is listed, ask again.
90+
refetchInterval: waiting ? 2_000 : false,
91+
});
92+
// A withdrawn credential leaves its row behind, so a row alone is not connected.
93+
const connected =
94+
waiting &&
95+
personalConnections(connections.data?.connections ?? []).some(
96+
(row) => row.serverId === app && row.revoked !== true,
97+
);
98+
const router = useRouter();
99+
const path = note?.path;
100+
useEffect(() => {
101+
if (!connected || !path) return;
102+
window.close();
103+
if (!window.closed) router.history.replace(path);
104+
}, [connected, path, router]);
105+
}

‎app/src/routes/_authed/_app/connections.$key.tsx‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ import { ALWAYS_ON_APP } from "@/lib/connections/rows";
5151
import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries";
5252
import { useManagePaths } from "@/lib/manage-paths";
5353
import { useReturnToReconnectList } from "@/lib/moves/use-moved-apps";
54+
import { useBackAfterConnect } from "@/lib/plugins/connect-return";
5455
import { useConnectionEnding } from "@/lib/plugins/connection-ending";
5556
import { connectAccountMutationOptions } from "@/lib/plugins/mutations";
5657
import {
@@ -168,6 +169,11 @@ function RouteComponent() {
168169
* too): back to the list once this app is connected, and a way back to it until then.
169170
*/
170171
const returningTo = useReturnToReconnectList();
172+
/*
173+
* Opened in a new tab for this app's sign-in, by a Bot's card or a Bot's page: closed, or sent
174+
* back to where Connect was pressed, once the account is connected.
175+
*/
176+
useBackAfterConnect(key);
171177
if (key === "github" || key === "slack") {
172178
return <IdentityConnectionPage linked={linked} provider={key} />;
173179
}

‎app/tests/consent-handoff.test.tsx‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
} from "./apps-api";
1414
import {
1515
confirmationResponse,
16+
connectionBody,
1617
connectionPage,
1718
connectionsCall,
1819
startResponse,
@@ -511,6 +512,86 @@ describe.skipIf(!asked)("a sign-in through Composio", () => {
511512
});
512513
}, 30_000);
513514

515+
/*
516+
* Reported on OpenBot Cloud: Connect on a Bot's Gmail card, sign in, and the new tab was left on
517+
* Gmail's page under Connections. The person expected to be back with the Bot, which was already
518+
* carrying on in the first tab. Now the tab the card opened closes once Gmail is connected, and
519+
* where the browser will not let it close, it goes back to where Connect was pressed.
520+
*/
521+
async function signInFromCard(
522+
name: "chromium" | "webkit",
523+
options: { closeRefused?: boolean } = {},
524+
) {
525+
const { page, context } = await launch(name);
526+
if (options.closeRefused)
527+
await context.addInitScript({ content: "window.close = () => {};" });
528+
let connected = false;
529+
/*
530+
* The provider's consent, done: back to the app's page, as the connect route returns a
531+
* browser. Sent on by the page rather than a 302, whose follow-up request Playwright's routes
532+
* don't always see.
533+
*/
534+
const back = `${ORIGIN}/connections/composio-gmail?status=success&connected_account_id=ca_test`;
535+
await context.route(`${CONSENT}/**`, (route) => {
536+
connected = true;
537+
return route.fulfill({
538+
contentType: "text/html",
539+
body: `<!doctype html><title>Consent</title><script>location.replace(${JSON.stringify(back)})</script>`,
540+
});
541+
});
542+
// Once it is done, the person's connections list Gmail.
543+
await context.route(`${ORIGIN}/api/**`, (route) => {
544+
const call = connectionsCall(new URL(route.request().url()).pathname, {
545+
method: route.request().method(),
546+
});
547+
if (call?.operation !== "list" || !connected) return route.fallback();
548+
return route.fulfill({
549+
json: {
550+
connections: [
551+
connectionBody({
552+
serverId: "composio-gmail",
553+
verified: true,
554+
checkable: false,
555+
}),
556+
],
557+
nextCursor: null,
558+
},
559+
});
560+
});
561+
await page.goto(`${ORIGIN}/card/composio-gmail`, {
562+
waitUntil: "domcontentloaded",
563+
});
564+
const connect = page.getByRole("button", { name: "Connect" });
565+
await connect.waitFor();
566+
const [tab] = await Promise.all([
567+
context.waitForEvent("page", { timeout: 5_000 }),
568+
connect.click(),
569+
]);
570+
return { page, tab };
571+
}
572+
573+
test(`in ${name}: once Gmail is connected, the tab a Bot's card opened for the sign-in closes`, async () => {
574+
const { page, tab } = await signInFromCard(name);
575+
// Through OpenBot's step and the consent, back on Gmail's page, then gone.
576+
await tab.waitForEvent("close", { timeout: MS(SECONDS + 10) });
577+
// The person is where they pressed Connect, and the card says Gmail is connected.
578+
expect(page.url()).toBe(`${ORIGIN}/card/composio-gmail`);
579+
await page
580+
.getByText("Waiting for Gmail…")
581+
.waitFor({ state: "hidden", timeout: 10_000 });
582+
}, 40_000);
583+
584+
test(`in ${name}: where the browser won't close that tab, it goes back to where Connect was pressed`, async () => {
585+
const { tab } = await signInFromCard(name, { closeRefused: true });
586+
await tab.waitForURL(`${ORIGIN}/connections/composio-gmail**`, {
587+
timeout: MS(SECONDS + 5),
588+
});
589+
await tab.waitForURL(`${ORIGIN}/card/composio-gmail`, {
590+
timeout: 10_000,
591+
});
592+
expect(tab.isClosed()).toBe(false);
593+
}, 40_000);
594+
514595
test(`in ${name}: the page Desktop's sign-in comes back to says Gmail is connected and counts down before it hands back`, async () => {
515596
const { page } = await launch(name);
516597
await page.goto(

0 commit comments

Comments
 (0)