Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(apps): a turn never waits on a refresh of the connected-apps list (#3766)
Milind Soni4b9eb0ff00ec
diff --git a/server/host/team-connections-host.test.ts b/server/host/team-connections-host.test.tsindex e52fb3f4e4..1f60c824cd 100644--- a/server/host/team-connections-host.test.ts+++ b/server/host/team-connections-host.test.ts@@ -1,7 +1,7 @@import { mkdtempSync, readFileSync, statSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import { describe, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import type { Audience } from "../audience.ts";import type { AppConfig } from "../config.ts";@@ -10,6 +10,7 @@ import { McpOAuthManager } from "../mcp-oauth.ts";import { personKey } from "../person-key.ts";import { excludedWorkspaceAuthPath } from "../workspace-backup-policy.ts";import { appsFromCreator } from "../inherited-apps.ts";+import { APP_TOOLS_ENV } from "../connector-app-tools.ts";import { createTeamConnectionsHost } from "./team-connections-host.ts";const ADA = personKey({ id: "", email: "[email protected]" });@@ -226,3 +227,45 @@ describe("what the bot and the admins are told", () => {expect(await setup({ team: false }).host.adminExtras()).toEqual({});});});++describe("the connected apps a turn's app tools come from", () => {+ afterEach(() => { vi.useRealTimers(); });+ const bot = { id: "scout", name: "Scout" };+ const GMAIL = { gmail: { connected: true, pending: false, status: "ACTIVE", accounts: [] } };+ const appTools = (bridges: { composio?: { env: Record<string, string> } }): string[] => JSON.parse(bridges.composio?.env[APP_TOOLS_ENV] ?? "[]");++ it("uses what is known at once, and reads it again in the background once it is a minute old, never waiting on that", async () => {+ vi.useFakeTimers();+ const { host, composio } = setup({ team: false });+ composio.connectedServices.mockResolvedValue(GMAIL as never);+ host.primeApps();+ expect(composio.connectedServices, "read at start").toHaveBeenCalledTimes(1);+ expect(appTools(await host.appsIntegrations(bot, "main-chat", "g1"))).toContain("gmail.search_emails");+ expect(composio.connectedServices, "the read at start served the first turn").toHaveBeenCalledTimes(1);+ vi.setSystemTime(Date.now() + 61_000);+ let answer: (services: never) => void = () => {};+ composio.connectedServices.mockImplementation(() => new Promise((resolve) => { answer = resolve; }));+ expect(appTools(await host.appsIntegrations(bot, "main-chat", "g2")), "the known answer while the new read hangs").toContain("gmail.search_emails");+ expect(composio.connectedServices).toHaveBeenCalledTimes(2);+ answer({} as never);+ await vi.advanceTimersByTimeAsync(0);+ expect(appTools(await host.appsIntegrations(bot, "main-chat", "g3")), "Gmail was disconnected meanwhile").toEqual([]);+ });++ it("waits a few seconds at most for an installation's first answer, and reads again soon after a failed one", async () => {+ vi.useFakeTimers();+ const hanging = setup({ team: false });+ hanging.composio.connectedServices.mockImplementation(() => new Promise<never>(() => {}));+ const first = hanging.host.appsIntegrations(bot, "main-chat", "g1");+ await vi.advanceTimersByTimeAsync(3_000);+ expect(appTools(await first), "no answer yet: this turn goes without").toEqual([]);++ const { host, composio } = setup({ team: false });+ composio.connectedServices.mockRejectedValueOnce(new Error("broker down")).mockResolvedValue(GMAIL as never);+ expect(appTools(await host.appsIntegrations(bot, "main-chat", "g1"))).toEqual([]);+ expect(appTools(await host.appsIntegrations(bot, "main-chat", "g2"))).toEqual([]);+ expect(composio.connectedServices, "not read again at once").toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(10_000);+ expect(appTools(await host.appsIntegrations(bot, "main-chat", "g3"))).toContain("gmail.search_emails");+ });+});diff --git a/server/host/team-connections-host.ts b/server/host/team-connections-host.tsindex 836c75dfa5..3ec29ca5d5 100644--- a/server/host/team-connections-host.ts+++ b/server/host/team-connections-host.ts@@ -45,6 +45,10 @@ export interface TeamConnectionsHostDeps {const list = (names: readonly string[]) => names.length <= 1 ? names.join("") : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`;+/** How long a read of an installation's connected apps stands, how soon a failed first read is tried again, and how long a+ * turn waits for an installation's first answer. */+const APPS_FRESH_MS = 60_000, APPS_RETRY_MS = 10_000, FIRST_APPS_WAIT_MS = 3_000;+export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {const team = deps.team;const scopes = new ConnectionScopes(join(deps.dataDir, SCOPES_FILE));@@ -61,16 +65,23 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {isOwnerLive: deps.isSessionLive,});const personApps = () => (team ? scopes.person("app") : []);- /** The apps connected for an installation, the team's or a member's own, read at most once a minute. */- const connectedApps = new Map<string, { at: number; apps: Promise<string[]> }>();- const appsConnected = (as?: BrokerAccess): Promise<string[]> => {+ /** The apps connected for an installation, the team's or a member's own. A turn never waits on a refresh: what is known+ * is used at once, and read again in the background once it is a minute old. Only an installation's first answer is+ * waited for, at most a few seconds, and a failed first read is tried again soon; `primeApps` reads the team's at start. */+ const connectedApps = new Map<string, { at: number; apps: string[] | null; reading: Promise<void> | null }>();+ const appsConnected = async (as?: BrokerAccess): Promise<string[]> => {const key = as ? createHash("sha256").update(as.url).update("\u0000").update(as.token).digest("hex") : "";- const cached = connectedApps.get(key);- if (cached && Date.now() - cached.at < 60_000) return cached.apps;- const apps = deps.composio.connectedServices(deps.cfg(), as)- .then((services) => Object.entries(services).filter(([, state]) => state.connected).map(([slug]) => slug), () => [] as string[]);- connectedApps.set(key, { at: Date.now(), apps });- return apps;+ const entry = connectedApps.get(key) ?? { at: -Infinity, apps: null, reading: null };+ connectedApps.set(key, entry);+ if (!entry.reading && Date.now() - entry.at >= (entry.apps ? APPS_FRESH_MS : APPS_RETRY_MS)) {+ entry.reading = deps.composio.connectedServices(deps.cfg(), as).then((services) => {+ entry.apps = Object.entries(services).filter(([, state]) => state.connected).map(([slug]) => slug);+ }, () => {}).finally(() => { entry.at = Date.now(); entry.reading = null; });+ }+ if (!entry.apps && entry.reading) {+ await Promise.race([entry.reading, new Promise<void>((resolve) => { setTimeout(resolve, FIRST_APPS_WAIT_MS).unref?.(); })]);+ }+ return entry.apps ?? [];};const withAppTools = async (bridge: Integration, bot: Bot, names: "dotted" | "plain", as?: BrokerAccess): Promise<Integration> => {const tools = appToolsFor(bot, await appsConnected(as));@@ -128,6 +139,10 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {personMcp,link,turnPerson,+ /** At start: the team's installation's apps are read now, so the first turn need not wait for them. */+ primeApps(): void {+ if (deps.composio.configured(deps.cfg())) void appsConnected();+ },/** The connected-apps bridges of a turn: the team's, and in a member's own turn their own beside it. `names`: how the* engine spells the app tools' names. */diff --git a/server/index.test.ts b/server/index.test.tsindex c64e19bc3b..a577f6c53e 100644--- a/server/index.test.ts+++ b/server/index.test.ts@@ -1604,6 +1604,8 @@ describe("harness HTTP API", () => {expect(theirs.status).toBe(202);expect(theirs.body.message).toMatchObject({ role: "user", sender: { name: "Safari on Mac" } });+ // A message steers into a turn its engine is running; one sent while that turn is still being set up waits for it.+ await expect.poll(() => claudePrompts().some((line) => line.includes("from the paired person")), { timeout: 10_000 }).toBe(true);const steered = await person.call("POST", `/api/bots/${bot.id}/messages`, { text: "and one more" });expect(steered.status).toBe(202);expect(steered.body.message).toMatchObject({ steered: true, sender: { name: "Safari on Mac" } });diff --git a/server/index.ts b/server/index.tsindex a1412f5afb..71cd01b9d8 100644--- a/server/index.ts+++ b/server/index.ts@@ -1430,7 +1430,7 @@ const mcpOAuth = new McpOAuthManager({const teamConnections = createTeamConnectionsHost({ team: CLOUD_TEAM, dataDir: DATA_DIR, cfg: () => cfg, adminOrigin: CLOUD_HOME?.adminOrigin ?? null, harnessUrl: `http://127.0.0.1:${PORT}`, audienceOf: teamHost.audienceOf,requester: (threadId, generation) => { const owner = directRequestOwners.get(threadId); return provenRequestPerson(owner, generation ?? owner?.generation ?? "", (id) => linePersonKey(store.messagesFor(threadId).find((message) => message.id === id))); },mint: (capability) => mintInternalCapability({ ...capability, depth: 0, kind: "connectors", skillAuthoring: false, createdBots: 0, openedThreads: 0 }), mcpOAuth, isSessionLive: (id) => sessions.isLive(id),- botMcp: (bot) => managedPolicy.filterMcp(customMcpServers(cfg, bot.mcpServers)), brokerUrl: () => (CLOUD_TEAM ? cloudConnectedAppsBrokerUrl() || null : null), composio });+ botMcp: (bot) => managedPolicy.filterMcp(customMcpServers(cfg, bot.mcpServers)), brokerUrl: () => (CLOUD_TEAM ? cloudConnectedAppsBrokerUrl() || null : null), composio }); teamConnections.primeApps();// OpenCode reads provider keys (ANTHROPIC_API_KEY, OPENAI_API_KEY, …) from its environment. Wired before the first catalog probe below.let openCodeOrganisationManaged = (): boolean => false;const openCodeKeysAllowed = (): boolean => openCodeProviderKeysAllowed({