Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(composio): a fresh install reuses the project's earlier OpenMausBot user

Bugfixer 29ac4e8ab6a18
diff --git a/server/composio-project.ts b/server/composio-project.ts
index 69645e0834..bc6c88e19d 100644
--- a/server/composio-project.ts
+++ b/server/composio-project.ts
@@ -283,3 +283,57 @@ export async function keepAuthConfigPick(apiKey: string, toolkit: string, id: st
writeFileAtomic(picksFile(), `${JSON.stringify({ version: 1, projects: picks }, null, 2)}\n`, { mode: 0o600 });
forgetProjectAuthConfigs(apiKey);
}
+
+const connectedAccountResponseSchema = z.object({
+ id: z.string().optional(),
+ user_id: z.string().optional(),
+ alias: z.string().nullable().optional(),
+ status: z.string().optional(),
+ updated_at: z.string().optional(),
+ toolkit: z.object({ slug: z.string().optional() }).optional(),
+});
+export type ConnectedAccountResponse = z.infer<typeof connectedAccountResponseSchema>;
+
+const connectedAccountsPageSchema = z.object({
+ items: z.array(connectedAccountResponseSchema),
+ next_cursor: z.string().nullable().optional(),
+});
+
+export const MAX_CONNECTED_ACCOUNT_PAGES = 100;
+
+/** The project's connected accounts, newest first: one Composio user's, or every user's when `userId` is null. `stop`
+ * sees each page and ends the listing early by returning true. */
+export async function listConnectedAccounts(
+ apiKey: string,
+ userId: string | null,
+ slugs: string[],
+ stop?: (page: ConnectedAccountResponse[]) => boolean,
+): Promise<ConnectedAccountResponse[]> {
+ const accounts: ConnectedAccountResponse[] = [];
+ const seenCursors = new Set<string>();
+ let cursor: string | undefined;
+
+ for (let page = 0; page < MAX_CONNECTED_ACCOUNT_PAGES; page += 1) {
+ const params = new URLSearchParams({
+ limit: "50",
+ order_by: "updated_at",
+ order_direction: "desc",
+ });
+ if (userId !== null) params.set("user_ids", userId);
+ if (slugs.length) params.set("toolkit_slugs", slugs.join(","));
+ if (cursor) params.set("cursor", cursor);
+ const response = await fetch(`${apiBase()}/connected_accounts?${params}`, {
+ headers: projectHeaders(apiKey),
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (!response.ok) throw new Error(await responseError(response, `Composio accounts: HTTP ${response.status}`));
+ const body = connectedAccountsPageSchema.parse(await response.json());
+ accounts.push(...body.items);
+ if (stop?.(body.items)) return accounts;
+ const next = body.next_cursor || undefined;
+ if (!next || seenCursors.has(next)) return accounts;
+ seenCursors.add(next);
+ cursor = next;
+ }
+ throw new Error("Composio account inventory exceeded the pagination safety limit");
+}
diff --git a/server/composio-reuse.test.ts b/server/composio-reuse.test.ts
new file mode 100644
index 0000000000..41393f3707
--- /dev/null
+++ b/server/composio-reuse.test.ts
@@ -0,0 +1,116 @@
+// A fresh installation that connects a Composio project an earlier installation used picks up that installation's
+// Composio user, so the apps connected there come back without connecting each one again.
+import { createServer, type Server } from "node:http";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+
+import { prepareProjectSession } from "./composio.ts";
+import { forgetProjectAuthConfigs } from "./composio-project.ts";
+
+let api: Server;
+let accounts: Array<Record<string, unknown>> = [];
+let accountsDown = false;
+const accountQueries: URLSearchParams[] = [];
+const sessionUsers: string[] = [];
+
+beforeAll(async () => {
+ api = createServer(async (req, res) => {
+ const url = new URL(req.url ?? "/", "http://fake");
+ let raw = "";
+ for await (const chunk of req) raw += chunk;
+ const body = raw ? JSON.parse(raw) : null;
+ const json = (status: number, value: unknown) => {
+ res.writeHead(status, { "content-type": "application/json" });
+ res.end(JSON.stringify(value));
+ };
+ if (req.headers["x-api-key"] !== "ak_reuse") return json(401, { error: { message: "invalid project key" } });
+ if (req.method === "GET" && url.pathname === "/api/v3.1/auth_configs") return json(200, { items: [] });
+ if (req.method === "GET" && url.pathname === "/api/v3.1/connected_accounts") {
+ accountQueries.push(url.searchParams);
+ if (accountsDown) return json(503, { error: { message: "accounts unavailable" } });
+ const start = Number(url.searchParams.get("cursor") ?? 0);
+ const items = accounts.slice(start, start + 2);
+ return json(200, { items, next_cursor: start + 2 < accounts.length ? String(start + 2) : null });
+ }
+ if (req.method === "POST" && url.pathname === "/api/v3.1/tool_router/session") {
+ sessionUsers.push(body.user_id);
+ return json(201, {
+ session_id: `trs_${sessionUsers.length}`,
+ mcp: { type: "http", url: `https://app.composio.dev/tool_router/v3/trs_${sessionUsers.length}/mcp` },
+ config: { user_id: body.user_id, multi_account: body.multi_account, auth_configs: {} },
+ });
+ }
+ return json(404, { error: { message: "not found" } });
+ });
+ await new Promise<void>((resolve) => api.listen(0, "127.0.0.1", resolve));
+ process.env.OMB_COMPOSIO_API = `http://127.0.0.1:${(api.address() as { port: number }).port}/api/v3.1`;
+});
+
+afterAll(async () => {
+ delete process.env.OMB_COMPOSIO_API;
+ await new Promise<void>((resolve) => api.close(() => resolve()));
+});
+
+beforeEach(() => {
+ forgetProjectAuthConfigs();
+ accounts = [];
+ accountsDown = false;
+ accountQueries.length = 0;
+ sessionUsers.length = 0;
+});
+
+const account = (user_id: string, slug: string, status = "ACTIVE") => ({ id: `ca_${user_id}_${slug}`, user_id, status, toolkit: { slug } });
+const NEW_USER = /^openmausbot_[0-9a-f-]{36}$/u;
+
+describe("a fresh installation connecting a project an earlier installation used", () => {
+ it("keeps the earlier installation's Composio user, so its connected apps come back", async () => {
+ accounts = [
+ account("openmausbot_earlier", "gmail"),
+ account("openmausbot_earlier", "github"),
+ account("openmausbot_earlier", "slack"),
+ account("someone_elses_app", "notion"),
+ ];
+ const prepared = await prepareProjectSession("ak_reuse");
+ expect(prepared.userId).toBe("openmausbot_earlier");
+ expect(sessionUsers).toEqual(["openmausbot_earlier"]);
+ expect(accountQueries.length).toBe(2);
+ expect(accountQueries.every((query) => !query.has("user_ids"))).toBe(true);
+ });
+
+ it("starts a new user when the project has no earlier installation's live connections", async () => {
+ accounts = [account("someone_elses_app", "notion"), account("openmausbot_gone", "gmail", "EXPIRED")];
+ const prepared = await prepareProjectSession("ak_reuse");
+ expect(prepared.userId).toMatch(NEW_USER);
+ });
+
+ it("starts a new user when several earlier installations share the project, since it can't tell whose apps are whose", async () => {
+ accounts = [
+ account("openmausbot_one", "gmail"),
+ account("openmausbot_two", "github"),
+ account("someone_elses_app", "notion"),
+ account("someone_elses_app", "slack"),
+ ];
+ const prepared = await prepareProjectSession("ak_reuse");
+ expect(prepared.userId).toMatch(NEW_USER);
+ expect(accountQueries.length).toBe(1);
+ });
+
+ it("starts a new user when another installation's connections have only expired", async () => {
+ accounts = [account("openmausbot_earlier", "gmail"), account("openmausbot_other", "github", "EXPIRED")];
+ const prepared = await prepareProjectSession("ak_reuse");
+ expect(prepared.userId).toMatch(NEW_USER);
+ });
+
+ it("still connects, as a new user, when Composio can't list the project's connections", async () => {
+ accountsDown = true;
+ const prepared = await prepareProjectSession("ak_reuse");
+ expect(prepared.userId).toMatch(NEW_USER);
+ expect(sessionUsers).toEqual([prepared.userId]);
+ });
+
+ it("never looks for another user when this installation already has one", async () => {
+ accounts = [account("openmausbot_earlier", "gmail")];
+ const prepared = await prepareProjectSession("ak_reuse", { userId: "openmausbot_mine" });
+ expect(prepared.userId).toBe("openmausbot_mine");
+ expect(accountQueries).toEqual([]);
+ });
+});
diff --git a/server/composio-session.ts b/server/composio-session.ts
index 9d2fb4b950..4e3a6e506c 100644
--- a/server/composio-session.ts
+++ b/server/composio-session.ts
@@ -9,11 +9,13 @@ import {
apiBase,
canonicalToolkitSlug,
forgetProjectAuthConfigs,
+ listConnectedAccounts,
projectAuthConfigs,
projectHeaders,
responseError,
turnOnToolRouter,
type AuthConfigChoice,
+ type ConnectedAccountResponse,
type AuthConfigMap,
} from "./composio-project.ts";
@@ -155,6 +157,25 @@ async function createProjectSession(apiKey: string, userId: string, authConfigs:
return session.session_id;
}
+/** The one OpenMausBot Composio user in this project, when it still has a live connection, so a fresh installation (a
+ * reinstall, another computer) gets that installation's apps back; null when there is none, more than one (even with
+ * only expired connections, since it can't tell whose is whose), or Composio can't say. */
+async function earlierInstallationUser(apiKey: string): Promise<string | null> {
+ const users = new Set<string>();
+ const sawSeveralUsers = (page: ConnectedAccountResponse[]) => {
+ for (const { user_id } of page) if (user_id?.startsWith("openmausbot_")) users.add(user_id);
+ return users.size > 1;
+ };
+ try {
+ const accounts = await listConnectedAccounts(apiKey, null, [], sawSeveralUsers);
+ if (users.size !== 1) return null;
+ return accounts.find((account) => account.status === "ACTIVE" && users.has(account.user_id ?? ""))?.user_id ?? null;
+ } catch (error) {
+ console.warn(`[composio] Could not read the project's earlier connections: ${error instanceof Error ? error.message : String(error)}`);
+ return null;
+ }
+}
+
export async function prepareProjectSession(
apiKey: string,
current?: { apiKey?: string; userId?: string; sessionId?: string },
@@ -180,7 +201,8 @@ export async function prepareProjectSession(
priorUserId = existing?.config?.user_id ?? priorUserId;
}
- const userId = priorUserId ?? `openmausbot_${randomUUID()}`;
+ // A fresh installation keeps the Composio user an earlier one connected apps with in this project.
+ const userId = priorUserId ?? (await earlierInstallationUser(trimmed)) ?? `openmausbot_${randomUUID()}`;
const sessionId = await createProjectSession(trimmed, userId, authConfigs);
return { apiKey: trimmed, userId, sessionId };
}
diff --git a/server/composio.ts b/server/composio.ts
index 91e76034dc..406824a12a 100644
--- a/server/composio.ts
+++ b/server/composio.ts
@@ -9,10 +9,13 @@ import {
canonicalToolkitSlug,
inputError,
keepAuthConfigPick,
+ listConnectedAccounts,
+ MAX_CONNECTED_ACCOUNT_PAGES,
noAuthConfigReason,
projectHeaders,
refusedAuthConfigReason,
responseError,
+ type ConnectedAccountResponse,
} from "./composio-project.ts";
import { MULTI_ACCOUNT_CONFIG, authConfigRefusal, ensureProjectSession, projectApiKey, sessionForToolkit } from "./composio-session.ts";
import { authConfigUseLine, noManagedAuthToolkit, withNoManagedAuthNote } from "./connector-auth-config-hint.ts";
@@ -55,20 +58,6 @@ interface AccountLinkRequest {
alias?: string;
}
-const connectedAccountResponseSchema = z.object({
- id: z.string().optional(),
- alias: z.string().nullable().optional(),
- status: z.string().optional(),
- updated_at: z.string().optional(),
- toolkit: z.object({ slug: z.string().optional() }).optional(),
-});
-type ConnectedAccountResponse = z.infer<typeof connectedAccountResponseSchema>;
-
-const connectedAccountsPageSchema = z.object({
- items: z.array(connectedAccountResponseSchema),
- next_cursor: z.string().nullable().optional(),
-});
-
const toolkitItemSchema = z.object({
slug: z.string().optional(),
is_no_auth: z.boolean().optional(),
@@ -91,7 +80,6 @@ const removalResponseSchema = z.object({ removed: z.number() });
const authUrlResponseSchema = z.object({ url: z.string().optional() });
const linkResponseSchema = z.object({ redirect_url: z.string().optional() });
-const MAX_CONNECTED_ACCOUNT_PAGES = 100;
const ACCOUNT_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
const printableAliasSchema = z.string().min(1).max(64).refine((value) => {
for (const character of value) {
@@ -336,39 +324,6 @@ export async function relayMcp(
return { status: response.status, bytes, contentType, transportSessionId: nextTransportSessionId };
}
-async function listConnectedAccounts(
- apiKey: string,
- userId: string,
- slugs: string[],
-): Promise<ConnectedAccountResponse[]> {
- const accounts: ConnectedAccountResponse[] = [];
- const seenCursors = new Set<string>();
- let cursor: string | undefined;
-
- for (let page = 0; page < MAX_CONNECTED_ACCOUNT_PAGES; page += 1) {
- const params = new URLSearchParams({
- limit: "50",
- user_ids: userId,
- order_by: "updated_at",
- order_direction: "desc",
- });
- if (slugs.length) params.set("toolkit_slugs", slugs.join(","));
- if (cursor) params.set("cursor", cursor);
- const response = await fetch(`${apiBase()}/connected_accounts?${params}`, {
- headers: projectHeaders(apiKey),
- signal: AbortSignal.timeout(15_000),
- });
- if (!response.ok) throw new Error(await responseError(response, `Composio accounts: HTTP ${response.status}`));
- const body = connectedAccountsPageSchema.parse(await response.json());
- accounts.push(...body.items);
- const next = body.next_cursor || undefined;
- if (!next || seenCursors.has(next)) return accounts;
- seenCursors.add(next);
- cursor = next;
- }
- throw new Error("Composio account inventory exceeded the pagination safety limit");
-}
-
async function listSessionToolkits(
apiKey: string,
sessionId: string,