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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,9 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged.

### Smaller changes

- After connecting an app from a Bot's card or a Bot's page, you're back where you pressed Connect.
The sign-in's tab closes once the app is connected, or, where the browser won't close it, goes back
to the conversation or the Bot's page. It used to stay on the app's page under Connections.
- **A Bot's command is no longer refused as "not saved", and the Bot gets what it printed.** Every
command a Bot runs is checked against the saved conversation first, and the saved copy can trail
the conversation on screen by several seconds on a busy day. A command checked too soon was
Expand Down
16 changes: 15 additions & 1 deletion app/src/components/plugins/connect-in-new-tab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { createElement, useCallback, useEffect, useRef, useState } from "react";
import { ConsentHandoffDialog } from "@/components/plugins/consent-handoff";
import { desktopShell } from "@/lib/desktop/shell";
import { markConnectReturn } from "@/lib/plugins/connect-return";
import {
brokeredConsentFor,
type ConsentHandoff,
Expand Down Expand Up @@ -128,6 +129,14 @@ export function useConnectInNewTab() {
return tab;
};

/*
* WHERE THE PRESS WAS MADE goes with the tab, so the page the sign-in comes back to can close it,
* or send it back here, once the account is connected (lib/plugins/connect-return.ts). Written
* before the tab leaves OpenBot, while it is still this site's blank page.
*/
const here = () =>
`${window.location.pathname}${window.location.search}${window.location.hash}`;

/**
* `first` runs between claiming the tab and asking for the consent, for a press that has to turn
* the app on before it can be connected (the personal edition's chat card). The tab is claimed
Expand All @@ -141,6 +150,7 @@ export function useConnectInNewTab() {
}
const tab = claimTab();
handle.current = tab;
markConnectReturn(tab, serverId, here());
void ask(serverId, tab);
};

Expand All @@ -151,8 +161,12 @@ export function useConnectInNewTab() {
const openAfter = (first: () => Promise<string>) => {
const tab = claimTab();
handle.current = tab;
const from = here();
first().then(
(serverId) => void ask(serverId, tab),
(serverId) => {
markConnectReturn(tab, serverId, from);
void ask(serverId, tab);
},
() => {
tab?.close();
handle.current = null;
Expand Down
105 changes: 105 additions & 0 deletions app/src/lib/plugins/connect-return.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { useQuery } from "@tanstack/react-query";
import { useRouter } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { connectionsQueryOptions, personalConnections } from "./queries";

/**
* BACK TO WHERE CONNECT WAS PRESSED, once the sign-in a new tab opened is done.
*
* 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
* (`useConnectInNewTab`), so the person never leaves what they were in the middle of. The sign-in
* comes back to the app's page under Connections, because that is where the connect route returns
* a browser to. Reported: after connecting Gmail from a conversation, the person was left on
* Gmail's page in the new tab, when what they expected was the Bot they had been talking to, which
* by then was already carrying on in the first tab.
*
* So the tab is told, before it leaves, where the press was made: written into the new tab's own
* session storage while it is still OpenBot's blank page, which the vendor's pages cannot touch and
* which is still there when the tab comes back to OpenBot. On the app's page, once the account is
* listed as connected, the tab closes, which puts the person back on the tab they pressed Connect
* in. Where the browser will not let it close, it goes to that page instead.
*
* ONLY THE PAGE THE SIGN-IN LANDS ON acts on it, and only once: the note is read and dropped on
* arrival, so somebody who stays in that tab and moves on is never taken anywhere later. A sign-in
* that failed comes back saying so (`?status=failed`), and then the person stays where the failure
* is said. Storage refused (a private window, a policy) means no note: the page works as before.
*/

const KEY = "openbot:connect-return";

type Note = { app: string; path: string };

/**
* Tell the tab a sign-in is about to open in where to come back to. `tab` is the blank tab claimed
* on the click, still OpenBot's origin, so its session storage is this site's, in that tab.
*/
export function markConnectReturn(
tab: Window | null,
app: string,
path: string,
): void {
if (!tab) return;
try {
tab.sessionStorage.setItem(KEY, JSON.stringify({ app, path }));
} catch {
// No storage: the tab stays where the sign-in lands, as it did before. See above.
}
}

/** The note this tab was given, dropped as it is read so it can be acted on once. */
function takeNote(): Note | null {
try {
const text = sessionStorage.getItem(KEY);
if (text === null) return null;
sessionStorage.removeItem(KEY);
const note = JSON.parse(text) as Partial<Note>;
return typeof note.app === "string" &&
typeof note.path === "string" &&
// Only a path in OpenBot itself, never an address somewhere else.
note.path.startsWith("/") &&
!note.path.startsWith("//")
? { app: note.app, path: note.path }
: null;
} catch {
return null;
}
}

/** Whether the address the sign-in came back to says it failed. */
function cameBackFailed(): boolean {
const search = new URLSearchParams(window.location.search);
return (
search.get("status") === "failed" || search.get("connected") === "failed"
);
}

/**
* On an app's page under Connections: when this tab was opened for this app's sign-in, close it
* once the account is connected, or go back to where Connect was pressed. See above.
*/
export function useBackAfterConnect(app: string): void {
const [note] = useState(() => {
const taken = takeNote();
return taken && !cameBackFailed() ? taken : null;
});
const waiting = note !== null && note.app === app;
const connections = useQuery({
...connectionsQueryOptions(),
enabled: waiting,
// The page confirms the account on arrival; until it is listed, ask again.
refetchInterval: waiting ? 2_000 : false,
});
// A withdrawn credential leaves its row behind, so a row alone is not connected.
const connected =
waiting &&
personalConnections(connections.data?.connections ?? []).some(
(row) => row.serverId === app && row.revoked !== true,
);
const router = useRouter();
const path = note?.path;
useEffect(() => {
if (!connected || !path) return;
window.close();
if (!window.closed) router.history.replace(path);
}, [connected, path, router]);
}
6 changes: 6 additions & 0 deletions app/src/routes/_authed/_app/connections.$key.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import { ALWAYS_ON_APP } from "@/lib/connections/rows";
import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries";
import { useManagePaths } from "@/lib/manage-paths";
import { useReturnToReconnectList } from "@/lib/moves/use-moved-apps";
import { useBackAfterConnect } from "@/lib/plugins/connect-return";
import { useConnectionEnding } from "@/lib/plugins/connection-ending";
import { connectAccountMutationOptions } from "@/lib/plugins/mutations";
import {
Expand Down Expand Up @@ -168,6 +169,11 @@ function RouteComponent() {
* too): back to the list once this app is connected, and a way back to it until then.
*/
const returningTo = useReturnToReconnectList();
/*
* Opened in a new tab for this app's sign-in, by a Bot's card or a Bot's page: closed, or sent
* back to where Connect was pressed, once the account is connected.
*/
useBackAfterConnect(key);
if (key === "github" || key === "slack") {
return <IdentityConnectionPage linked={linked} provider={key} />;
}
Expand Down
81 changes: 81 additions & 0 deletions app/tests/consent-handoff.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
} from "./apps-api";
import {
confirmationResponse,
connectionBody,
connectionPage,
connectionsCall,
startResponse,
Expand Down Expand Up @@ -511,6 +512,86 @@ describe.skipIf(!asked)("a sign-in through Composio", () => {
});
}, 30_000);

/*
* Reported on OpenBot Cloud: Connect on a Bot's Gmail card, sign in, and the new tab was left on
* Gmail's page under Connections. The person expected to be back with the Bot, which was already
* carrying on in the first tab. Now the tab the card opened closes once Gmail is connected, and
* where the browser will not let it close, it goes back to where Connect was pressed.
*/
async function signInFromCard(
name: "chromium" | "webkit",
options: { closeRefused?: boolean } = {},
) {
const { page, context } = await launch(name);
if (options.closeRefused)
await context.addInitScript({ content: "window.close = () => {};" });
let connected = false;
/*
* The provider's consent, done: back to the app's page, as the connect route returns a
* browser. Sent on by the page rather than a 302, whose follow-up request Playwright's routes
* don't always see.
*/
const back = `${ORIGIN}/connections/composio-gmail?status=success&connected_account_id=ca_test`;
await context.route(`${CONSENT}/**`, (route) => {
connected = true;
return route.fulfill({
contentType: "text/html",
body: `<!doctype html><title>Consent</title><script>location.replace(${JSON.stringify(back)})</script>`,
});
});
// Once it is done, the person's connections list Gmail.
await context.route(`${ORIGIN}/api/**`, (route) => {
const call = connectionsCall(new URL(route.request().url()).pathname, {
method: route.request().method(),
});
if (call?.operation !== "list" || !connected) return route.fallback();
return route.fulfill({
json: {
connections: [
connectionBody({
serverId: "composio-gmail",
verified: true,
checkable: false,
}),
],
nextCursor: null,
},
});
});
await page.goto(`${ORIGIN}/card/composio-gmail`, {
waitUntil: "domcontentloaded",
});
const connect = page.getByRole("button", { name: "Connect" });
await connect.waitFor();
const [tab] = await Promise.all([
context.waitForEvent("page", { timeout: 5_000 }),
connect.click(),
]);
return { page, tab };
}

test(`in ${name}: once Gmail is connected, the tab a Bot's card opened for the sign-in closes`, async () => {
const { page, tab } = await signInFromCard(name);
// Through OpenBot's step and the consent, back on Gmail's page, then gone.
await tab.waitForEvent("close", { timeout: MS(SECONDS + 10) });
// The person is where they pressed Connect, and the card says Gmail is connected.
expect(page.url()).toBe(`${ORIGIN}/card/composio-gmail`);
await page
.getByText("Waiting for Gmail…")
.waitFor({ state: "hidden", timeout: 10_000 });
}, 40_000);

test(`in ${name}: where the browser won't close that tab, it goes back to where Connect was pressed`, async () => {
const { tab } = await signInFromCard(name, { closeRefused: true });
await tab.waitForURL(`${ORIGIN}/connections/composio-gmail**`, {
timeout: MS(SECONDS + 5),
});
await tab.waitForURL(`${ORIGIN}/card/composio-gmail`, {
timeout: 10_000,
});
expect(tab.isClosed()).toBe(false);
}, 40_000);

test(`in ${name}: the page Desktop's sign-in comes back to says Gmail is connected and counts down before it hands back`, async () => {
const { page } = await launch(name);
await page.goto(
Expand Down