Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Apps: the connected-apps list opens at once from a kept copy, and tiles stop re-rendering (#6688)
Milind Soniecabd15caa08
diff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.tsindex 66f4a3e1c4..f078efb7c7 100644--- a/packages/phone-protocol/src/wire.ts+++ b/packages/phone-protocol/src/wire.ts@@ -990,7 +990,7 @@ export type ServerFrame =| DataBroadcast| { kind: "bot.deleted"; botId: string }/** The whole fleet (PUT /api/bots/order) or every room (PUT /api/groups/order) in its new order; a member is sent only the ones they see. */- | { kind: "bots.order"; botIds: string[] } | { kind: "groups.order"; groupIds: string[] } | WindowPrefFrame | { kind: "theme"; skin?: string }+ | { kind: "bots.order"; botIds: string[] } | { kind: "groups.order"; groupIds: string[] } | WindowPrefFrame | { kind: "theme"; skin?: string } | /** The Apps page's catalog changed; the list is read again. */ { kind: "apps-catalog" }| { kind: "live.call"; botId: string; threadId: string; call: LiveCallState | null }/** A job is waiting for the phone whose registry key this is; it polls now. */| { kind: "device.job"; phone: string; id: string }diff --git a/server/cloud-connected-apps.e2e.test.ts b/server/cloud-connected-apps.e2e.test.tsindex 79adc3bbe6..018672d9da 100644--- a/server/cloud-connected-apps.e2e.test.ts+++ b/server/cloud-connected-apps.e2e.test.ts@@ -5,13 +5,14 @@ import { randomBytes } from "node:crypto";import { spawn, type ChildProcess } from "node:child_process";import { createServer, type Server } from "node:http";import type { AddressInfo } from "node:net";-import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join } from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";import { afterAll, beforeAll, describe, expect, it } from "vitest";import { cloudPairingSignature } from "./cloud-home.ts";import { CLOUD_CONNECTED_APPS_FILE } from "./cloud-connected-apps.ts";+import { CATALOG_FILE } from "./composio-catalog.ts";import { removeTempDir, waitForExit } from "./testing/cleanup.ts";import { freePortBlock } from "./testing/ports.ts";@@ -20,6 +21,7 @@ const HOST = "omb-t-0123456789ab.fly.dev";const secret = randomBytes(32).toString("base64url");const brokerToken = randomBytes(32).toString("hex");const CATALOG = ["outlook", "linkedin", "calendly", "gmail", "slack"];+let serviceCatalog = CATALOG;let broker: Server;let brokerUrl = "";@@ -115,8 +117,8 @@ beforeAll(async () => {if (req.method === "GET" && url.pathname === "/v1/me") return send(200, { installationId: "install-cloud" });if (req.method === "GET" && url.pathname === "/v1/catalog") {return send(200, {- items: CATALOG.map((slug) => ({ slug, name: slug, meta: { description: `${slug} tools`, logo: "" } })),- total_items: CATALOG.length, current_page: 1, total_pages: 1,+ items: serviceCatalog.map((slug) => ({ slug, name: slug, meta: { description: `${slug} tools`, logo: "" } })),+ total_items: serviceCatalog.length, current_page: 1, total_pages: 1,});}send(404, { error: "not found" });@@ -188,6 +190,49 @@ describe("connected apps on a Cloud home", { timeout: 90_000 }, () => {expect(brokerCalls.filter((call) => call.path === "/v1/installations")).toHaveLength(1);});+ it("after a restart answers the catalog from the data folder, reads an old one again behind the answer, and tells the open window", async () => {+ const file = join(dataDir, CATALOG_FILE);+ const slugs = (body: { cards: Array<{ slug: string }> }) => body.cards.map((card) => card.slug);+ const catalogReads = (since: number) => brokerCalls.slice(since).filter((call) => call.path === "/v1/catalog").length;+ expect(existsSync(file)).toBe(true);+ if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600);+ expect(readFileSync(file, "utf8")).not.toContain(brokerToken);++ await waitForExit(child!, { signal: "SIGTERM" });+ child = null;+ let before = brokerCalls.length;+ await boot();+ expect(slugs(await catalog())).toEqual(CATALOG);+ expect(catalogReads(before)).toBe(0);++ await waitForExit(child!, { signal: "SIGTERM" });+ child = null;+ writeFileSync(file, JSON.stringify({ ...JSON.parse(readFileSync(file, "utf8")), at: 0 }), { mode: 0o600 });+ serviceCatalog = [...CATALOG, "notion"];+ before = brokerCalls.length;+ await boot();+ const closed = new AbortController();+ let heard = "";+ try {+ const events = await fetch(`${base}/api/events`, {+ headers: { host: HOST, "x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https", authorization: `Bearer ${ownerToken}` },+ signal: closed.signal,+ });+ expect(events.status).toBe(200);+ void (async () => {+ const decoder = new TextDecoder();+ for await (const chunk of events.body!) heard += decoder.decode(chunk as Uint8Array, { stream: true });+ })().catch(() => {});+ expect(slugs(await catalog())).toEqual(CATALOG);+ await expect.poll(() => heard.includes('"kind":"apps-catalog"'), { timeout: 15_000, interval: 100 }).toBe(true);+ expect(slugs((await api("GET", "/api/connectors/catalog")).body)).toEqual([...CATALOG, "notion"]);+ expect(catalogReads(before)).toBe(1);+ } finally {+ closed.abort();+ serviceCatalog = CATALOG;+ }+ });+it("while the service will not register it, still starts, and says the included service is unavailable instead of asking for a key", async () => {await waitForExit(child!, { signal: "SIGTERM" });child = null;diff --git a/server/composio-catalog.test.ts b/server/composio-catalog.test.tsnew file mode 100644index 0000000000..852a58b9c0--- /dev/null+++ b/server/composio-catalog.test.ts@@ -0,0 +1,302 @@+import { chmodSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";++import { CATALOG_FILE, catalogWalksSettled, forgetCatalogs, onCatalogChange, rememberCatalogIn } from "./composio-catalog.ts";+import { removeTempDir } from "./testing/cleanup.ts";+import { listToolkits, setManagedBrokerAccess } from "./composio.ts";+import { startFakeCatalogService, waitedOnService, type FakeCatalogService } from "./testing/fake-catalog-service.ts";++let fake: FakeCatalogService;+let installation = 0;+let clock = 0;+const ELEVEN_MINUTES = 11 * 60_000;+const later = (ms: number) => { clock += ms; };+const labels = async () => (await listToolkits({})).cards.map((card) => card.label);++beforeAll(async () => {+ fake = await startFakeCatalogService();+});+afterAll(async () => {+ await fake.close();+});+beforeEach(() => {+ const start = Date.now();+ clock = 0;+ vi.spyOn(Date, "now").mockImplementation(() => start + clock);+ vi.spyOn(console, "warn").mockImplementation(() => {});+ Object.assign(fake, { pages: [3, 3, 2], edition: 0, failPage: 0, dropPage: 0, garblePage: 0, totals: true, down: false });+ installation += 1;+ setManagedBrokerAccess({ url: fake.url, token: installation.toString(16).padStart(64, "0") });+ fake.requests.catalog = 0;+});+afterEach(async () => {+ await catalogWalksSettled();+ setManagedBrokerAccess(null);+ rememberCatalogIn(null);+ forgetCatalogs();+ vi.restoreAllMocks();+});++describe("the catalog answers from the copy it holds", () => {+ it("makes its first read wait for the walk, one walk for every reader asking at once", async () => {+ const first = await waitedOnService(fake, () => Promise.all([listToolkits({}), listToolkits({}), listToolkits({})]));+ expect(first.waited).toBe(true);+ expect(first.value.map((catalog) => catalog.cards.length)).toEqual([8, 8, 8]);+ expect(first.value[0]).toMatchObject({ source: "api", fresh: true, pagination: { items: 8, complete: true } });+ expect(fake.requests.catalog).toBe(3);+ });++ it("answers an old copy at once and reads again behind it, once", async () => {+ await listToolkits({});+ fake.requests.catalog = 0;+ await listToolkits({});+ expect(fake.requests.catalog).toBe(0);++ later(ELEVEN_MINUTES);+ fake.edition = 1;+ const changed = vi.fn();+ const stop = onCatalogChange(changed);+ try {+ const stale = await waitedOnService(fake, () => Promise.all([listToolkits({}), listToolkits({}), listToolkits({})]));+ expect(stale.waited).toBe(false);+ expect(stale.value.map((catalog) => catalog.fresh)).toEqual([false, false, false]);+ expect(stale.value[0]!.cards[0]!.label).toBe("App 0 v0");+ await catalogWalksSettled();+ expect(fake.requests.catalog).toBe(3);+ expect(changed).toHaveBeenCalledTimes(1);+ expect((await labels())[0]).toBe("App 0 v1");+ expect((await listToolkits({})).fresh).toBe(true);+ expect(fake.requests.catalog).toBe(3);++ later(ELEVEN_MINUTES);+ await listToolkits({});+ await catalogWalksSettled();+ expect(fake.requests.catalog).toBe(6);+ expect(changed).toHaveBeenCalledTimes(1);+ } finally {+ stop();+ }+ });++ it("keeps one installation's catalog from another's", async () => {+ await listToolkits({});+ setManagedBrokerAccess({ url: fake.url, token: "f".repeat(64) });+ fake.requests.catalog = 0;+ await listToolkits({});+ expect(fake.requests.catalog).toBe(3);+ });+});++describe("the catalog kept in the data folder", () => {+ let dataDir: string;+ beforeEach(() => {+ dataDir = mkdtempSync(join(tmpdir(), "omb-catalog-"));+ rememberCatalogIn(dataDir);+ });+ afterEach(async () => {+ await catalogWalksSettled();+ await removeTempDir(dataDir);+ });++ it("answers the first read after a restart from the file, without waiting", async () => {+ await listToolkits({});+ const file = join(dataDir, CATALOG_FILE);+ if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600);+ expect(readFileSync(file, "utf8")).not.toContain(installation.toString(16).padStart(64, "0"));++ forgetCatalogs();+ fake.requests.catalog = 0;+ const afterRestart = await listToolkits({});+ expect(afterRestart).toMatchObject({ source: "api", fresh: true, pagination: { items: 8, complete: true } });+ expect(afterRestart.cards).toHaveLength(8);+ expect(fake.requests.catalog).toBe(0);++ forgetCatalogs();+ later(ELEVEN_MINUTES);+ fake.edition = 1;+ const old = await waitedOnService(fake, () => listToolkits({}));+ expect(old.waited).toBe(false);+ expect(old.value).toMatchObject({ fresh: false });+ expect(old.value.cards[0]!.label).toBe("App 0 v0");+ await catalogWalksSettled();+ expect(fake.requests.catalog).toBe(3);++ forgetCatalogs();+ expect((await labels())[0]).toBe("App 0 v1");+ expect(fake.requests.catalog).toBe(3);+ });++ it("starts from nothing when the file is another installation's, or is not a catalog", async () => {+ await listToolkits({});+ forgetCatalogs();+ setManagedBrokerAccess({ url: fake.url, token: "e".repeat(64) });+ fake.requests.catalog = 0;+ expect((await waitedOnService(fake, () => listToolkits({}))).waited).toBe(true);+ expect(fake.requests.catalog).toBe(3);++ await catalogWalksSettled();+ forgetCatalogs();+ writeFileSync(join(dataDir, CATALOG_FILE), "{ not json");+ fake.requests.catalog = 0;+ expect((await listToolkits({})).cards).toHaveLength(8);+ expect(fake.requests.catalog).toBe(3);+ expect(vi.mocked(console.warn)).toHaveBeenCalledWith(expect.stringContaining("saved catalog could not be read"));+ });++ it("starts from a saved catalog whose labels, blurbs and logo links are as long as the service sends them", async () => {+ await listToolkits({});+ const file = join(dataDir, CATALOG_FILE);+ const saved = JSON.parse(readFileSync(file, "utf8")) as { cards: Array<Record<string, unknown>> };+ saved.cards[0] = { ...saved.cards[0], label: "L".repeat(5_000), logo: `https://logos.example/${"x".repeat(20_000)}`, categories: Array.from({ length: 30 }, (_, index) => `Category ${index}`) };+ writeFileSync(file, JSON.stringify(saved));+ forgetCatalogs();+ fake.requests.catalog = 0;+ expect((await listToolkits({})).cards[0]!.label).toHaveLength(5_000);+ expect(fake.requests.catalog).toBe(0);+ });++ it("still answers when the file can't be written", async () => {+ if (process.platform === "win32" || process.getuid?.() === 0) return;+ chmodSync(dataDir, 0o500);+ try {+ expect((await listToolkits({})).cards).toHaveLength(8);+ } finally {+ chmodSync(dataDir, 0o700);+ }+ });+});++describe("a walk that fails or comes up short", () => {+ const SHORT = { stalled: true, complete: false, reason: "http-error" };++ it.each([+ ["an error on page 2", { failPage: 2 }],+ ["a connection dropped on page 2", { dropPage: 2 }],+ ["a page 2 that is not JSON", { garblePage: 2 }],+ ["a page 2 that is not JSON, in a catalog that reports no totals", { garblePage: 2, totals: false }],+ ["an outage", { down: true }],+ ])("keeps the whole list after %s, and tries again later, less often each time", async (_name, failure) => {+ await listToolkits({});+ later(ELEVEN_MINUTES);+ Object.assign(fake, failure);+ const changed = vi.fn();+ const stop = onCatalogChange(changed);+ try {+ fake.requests.catalog = 0;+ expect(await listToolkits({})).toMatchObject({ source: "api", fresh: false, pagination: { items: 8, complete: true } });+ await catalogWalksSettled();+ const oneWalk = fake.requests.catalog;+ expect(oneWalk).toBeGreaterThan(0);+ expect(await listToolkits({})).toMatchObject({ source: "api", fresh: false, pagination: { items: 8, complete: true } });+ await catalogWalksSettled();+ expect(fake.requests.catalog).toBe(oneWalk);++ later(31_000);+ await listToolkits({});+ await catalogWalksSettled();+ expect(fake.requests.catalog).toBe(2 * oneWalk);+ later(31_000);+ await listToolkits({});+ await catalogWalksSettled();+ expect(fake.requests.catalog).toBe(2 * oneWalk);+ later(31_000);+ await listToolkits({});+ await catalogWalksSettled();+ expect(fake.requests.catalog).toBe(3 * oneWalk);+ expect(changed).not.toHaveBeenCalled();++ Object.assign(fake, { failPage: 0, dropPage: 0, garblePage: 0, down: false, edition: 1 });+ later(2 * 60_000 + 1_000);+ expect((await labels())[0]).toBe("App 0 v0");+ await catalogWalksSettled();+ expect(await listToolkits({})).toMatchObject({ fresh: true, pagination: { items: 8, complete: true } });+ expect((await labels())[0]).toBe("App 0 v1");+ expect(changed).toHaveBeenCalledTimes(1);+ } finally {+ stop();+ }+ });++ it.each([+ ["an error", { failPage: 3 }, 3],+ ["a dropped connection", { dropPage: 3 }, 3],+ ])("keeps the pages read before %s on a first read, and reads again behind the next reader", async (_name, failure, walkRequests) => {+ Object.assign(fake, failure);+ expect(await listToolkits({})).toMatchObject({ source: "api", pagination: { items: 6, totalItems: 8, ...SHORT } });+ expect(fake.requests.catalog).toBe(walkRequests);+ expect((await listToolkits({})).cards).toHaveLength(6);+ await catalogWalksSettled();+ expect(fake.requests.catalog).toBe(walkRequests);++ Object.assign(fake, { failPage: 0, dropPage: 0 });+ later(31_000);+ const short = await waitedOnService(fake, () => listToolkits({}));+ expect(short.waited).toBe(false);+ expect(short.value.cards).toHaveLength(6);+ await catalogWalksSettled();+ expect(await listToolkits({})).toMatchObject({ fresh: true, pagination: { items: 8, complete: true } });+ });++ it("reads a page that is not JSON as a walk cut short, with or without totals to show it", async () => {+ fake.garblePage = 2;+ expect((await listToolkits({})).pagination).toMatchObject({ items: 3, complete: false, reason: "bad-page" });+ forgetCatalogs();+ fake.totals = false;+ expect((await listToolkits({})).pagination).toEqual({ items: 3, stalled: false, complete: false });+ });++ it("goes on when a listener of the change throws", async () => {+ await listToolkits({});+ later(ELEVEN_MINUTES);+ fake.edition = 1;+ const heard = vi.fn();+ const stops = [onCatalogChange(() => { throw new Error("listener down"); }), onCatalogChange(heard)];+ try {+ await listToolkits({});+ await catalogWalksSettled();+ expect(heard).toHaveBeenCalledTimes(1);+ expect((await labels())[0]).toBe("App 0 v1");+ } finally {+ for (const stop of stops) stop();+ }+ });++ it("never puts a shorter partial list in place of a longer one", async () => {+ fake.failPage = 3;+ await listToolkits({});+ fake.failPage = 2;+ later(31_000);+ await listToolkits({});+ await catalogWalksSettled();+ expect((await listToolkits({})).cards).toHaveLength(6);+ });++ it("answers the curated list when nothing was ever read, and waits for the walk on the next read", async () => {+ fake.down = true;+ expect(await listToolkits({})).toMatchObject({ source: "curated" });+ fake.down = false;+ const next = await waitedOnService(fake, () => listToolkits({}));+ expect(next.waited).toBe(true);+ expect(next.value).toMatchObject({ source: "api", pagination: { items: 8, complete: true } });+ });++ it("does not let a partial list on disk stand in for long after a restart", async () => {+ const dataDir = mkdtempSync(join(tmpdir(), "omb-catalog-"));+ rememberCatalogIn(dataDir);+ try {+ fake.failPage = 3;+ await listToolkits({});+ fake.failPage = 0;+ forgetCatalogs();+ fake.requests.catalog = 0;+ expect((await listToolkits({})).cards).toHaveLength(6);+ await catalogWalksSettled();+ expect(fake.requests.catalog).toBe(3);+ expect((await listToolkits({})).cards).toHaveLength(8);+ } finally {+ await removeTempDir(dataDir);+ }+ });+});diff --git a/server/composio-catalog.ts b/server/composio-catalog.tsnew file mode 100644index 0000000000..2426f3e31e--- /dev/null+++ b/server/composio-catalog.ts@@ -0,0 +1,330 @@+// The marketplace catalog: one walk of its pages, and the copy the Apps page is answered from. A reader gets the copy held+// for its backend at once, whatever its age; an old copy is read again behind it, by one walk however many readers ask.+// The newest copy is also kept in the data folder, so a restart starts from it. A walk that failed or came up short never+// takes the place of a whole list: the list held stays, and the walk is tried again later, less often each time.+import { createHash } from "node:crypto";+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { z } from "zod";++import { writeFileAtomic } from "./atomic.ts";+import { canonicalToolkitSlug, MAX_CONNECTED_ACCOUNT_PAGES } from "./composio-project.ts";++export interface ToolkitCard {+ slug: string;+ label: string;+ blurb: string;+ logo: string | null;+ /** Toolkits such as public search need no user authorization. */+ noAuth?: boolean;+ domain: string | null;+ categories?: string[];+}++export type CatalogStopReason =+ | "end"+ | "total-reached"+ | "page-stuck"+ | "cursor-repeated"+ | "http-error"+ | "bad-page"+ | "limit";++export interface CatalogPagination {+ items: number;+ /** Upstream's own count of the full marketplace, when it reports one. */+ totalItems?: number;+ /** True when paging stopped before the reported total. */+ stalled: boolean;+ reason?: CatalogStopReason;+ /** True only when the walk reached its natural end without stalling. */+ complete: boolean;+}++export interface Catalog {+ cards: ToolkitCard[];+ pagination: CatalogPagination;+ /** False once the copy is older than CATALOG_FRESH_MS: still served, but no proof of what the marketplace lists now. */+ fresh: boolean;+}++/** One page of the catalog; the walk gives the cursor the page before it named. */+export type CatalogPageReader = (cursor: string | undefined) => Promise<Response>;++/** Composio lists meta.categories as `{ id, name }` objects (older payloads: plain strings). */+export function toolkitCategories(raw: unknown): string[] | undefined {+ if (!Array.isArray(raw)) return undefined;+ const names = raw+ .map((entry) => typeof entry === "string" ? entry : entry && typeof entry === "object" ? (entry as { name?: unknown }).name : undefined)+ .filter((name): name is string => typeof name === "string")+ .map((name) => name.trim().slice(0, 40))+ .filter(Boolean);+ const unique = [...new Set(names)].slice(0, 4);+ return unique.length ? unique : undefined;+}++export const CATALOG_FRESH_MS = 10 * 60_000;+const MAX_HELD_CATALOGS = 4;++/** How long after each walk in a row that failed or came up short the next one waits. */+const RETRY_AFTER_MS = [30_000, 60_000, 2 * 60_000, 5 * 60_000, CATALOG_FRESH_MS];+const retryAfter = (failures: number) => RETRY_AFTER_MS[Math.min(failures, RETRY_AFTER_MS.length) - 1]!;++interface HeldCatalog {+ at: number;+ cards: ToolkitCard[];+ pagination: CatalogPagination;+ digest: string;+ /** When the next reader starts a walk behind its answer. */+ walkAgainAt: number;+ failures: number;+}++export const CATALOG_FILE = "connector-catalog.json";+const savedCatalogSchema = z.object({+ version: z.literal(1),+ /** Names the backend without holding its credential. */+ key: z.string().length(64),+ at: z.number().finite().nonnegative(),+ cards: z.array(z.object({+ slug: z.string().min(1),+ label: z.string(),+ blurb: z.string(),+ logo: z.string().nullable(),+ noAuth: z.boolean().optional(),+ domain: z.string().nullable(),+ categories: z.array(z.string()).optional(),+ })).min(1),+ pagination: z.object({+ items: z.number(),+ totalItems: z.number().optional(),+ stalled: z.boolean(),+ reason: z.enum(["end", "total-reached", "page-stuck", "cursor-repeated", "http-error", "bad-page", "limit"]).optional(),+ complete: z.boolean(),+ }),+});++const held = new Map<string, HeldCatalog>();+let savedFile: string | null = null;+let savedFileRead = false;++/** Keeps the newest catalog in `dataDir` and starts from the one found there; null stops both. */+export function rememberCatalogIn(dataDir: string | null): void {+ savedFile = dataDir ? join(dataDir, CATALOG_FILE) : null;+ savedFileRead = false;+}++const savedKey = (identity: string) => createHash("sha256").update("catalog-file\0").update(identity).digest("hex");++function loadSaved(identity: string): HeldCatalog | null {+ if (!savedFile || savedFileRead) return null;+ savedFileRead = true;+ let text: string;+ try {+ text = readFileSync(savedFile, "utf8");+ } catch {+ return null;+ }+ let parsed;+ try {+ parsed = savedCatalogSchema.safeParse(JSON.parse(text));+ } catch {+ parsed = null;+ }+ if (!parsed?.success) {+ console.warn("[composio] the saved catalog could not be read; the catalog is read from the service instead");+ return null;+ }+ if (parsed.data.key !== savedKey(identity)) return null;+ const { cards, pagination, at } = parsed.data;+ const readAt = Math.min(at, Date.now());+ const catalog: HeldCatalog = { at: readAt, cards, pagination, digest: digestOf(cards), walkAgainAt: pagination.complete ? readAt + CATALOG_FRESH_MS : 0, failures: 0 };+ keep(identity, catalog);+ return catalog;+}++function save(identity: string, catalog: HeldCatalog): void {+ if (!savedFile) return;+ try {+ const { at, cards, pagination } = catalog;+ writeFileAtomic(savedFile, `${JSON.stringify({ version: 1, key: savedKey(identity), at, cards, pagination })}\n`, { mode: 0o600, durable: false });+ } catch (error) {+ console.warn(`[composio] could not save the catalog: ${error instanceof Error ? error.message : String(error)}`);+ }+}+const walks = new Map<string, Promise<HeldCatalog | null>>();+const listeners = new Set<() => void>();++/** Called when a walk behind a reader brought a list that differs from the one readers were given. */+export function onCatalogChange(listener: () => void): () => void {+ listeners.add(listener);+ return () => listeners.delete(listener);+}++function announceChange(): void {+ for (const listener of listeners) {+ try {+ listener();+ } catch (error) {+ console.warn(`[composio] a catalog listener failed: ${error instanceof Error ? error.message : String(error)}`);+ }+ }+}++const digestOf = (cards: readonly ToolkitCard[]) => createHash("sha256").update(JSON.stringify(cards)).digest("hex");++async function walkCatalog(readPage: CatalogPageReader): Promise<{ cards: ToolkitCard[]; pagination: CatalogPagination } | null> {+ const items: any[] = [];+ const seenCursors = new Set<string>();+ let cursor: string | undefined;+ let lastReportedPage: number | undefined;+ let reportedTotalItems: number | undefined;+ let reportedTotalPages: number | undefined;+ let stop: CatalogStopReason = "limit";+ for (let page = 0; page < MAX_CONNECTED_ACCOUNT_PAGES; page += 1) {+ const res = await readPage(cursor).catch(() => null);+ if (!res?.ok) {+ stop = "http-error";+ break;+ }+ const json: any = await res.json().catch(() => null);+ const pageItems = json && typeof json === "object" ? json.items ?? json.data ?? [] : null;+ if (!Array.isArray(pageItems)) {+ stop = "bad-page";+ break;+ }+ items.push(...pageItems);+ const pageTotalItems = Number(json.total_items);+ if (Number.isFinite(pageTotalItems) && pageTotalItems > 0) reportedTotalItems = pageTotalItems;+ // A broker that drops the cursor can replay a page while minting fresh cursors, so trust Composio's current_page movement.+ const reportedPage = Number(json.current_page);+ if (Number.isFinite(reportedPage)) {+ if (lastReportedPage !== undefined && reportedPage <= lastReportedPage) {+ stop = "page-stuck";+ break;+ }+ lastReportedPage = reportedPage;+ }+ const pageTotalPages = Number(json.total_pages);+ if (Number.isFinite(pageTotalPages) && pageTotalPages > 0) reportedTotalPages = pageTotalPages;+ if (+ lastReportedPage !== undefined &&+ Number.isFinite(pageTotalPages) &&+ pageTotalPages > 0 &&+ lastReportedPage >= pageTotalPages+ ) {+ stop = "total-reached";+ break;+ }+ const next = typeof json.next_cursor === "string" ? json.next_cursor.trim() : "";+ if (!next) {+ stop = "end";+ break;+ }+ if (seenCursors.has(next)) {+ stop = "cursor-repeated";+ break;+ }+ seenCursors.add(next);+ cursor = next;+ }+ if (!items.length) return null;+ const cards: ToolkitCard[] = items.map((t: any) => ({+ slug: canonicalToolkitSlug(String(t.slug ?? t.key ?? t.name ?? "")),+ label: t.name ?? t.slug ?? "",+ blurb: (t.meta?.description ?? t.description ?? "").slice(0, 90),+ logo: t.meta?.logo ?? t.logo ?? null,+ noAuth: t.no_auth === true,+ domain: null,+ ...(toolkitCategories(t.meta?.categories) ? { categories: toolkitCategories(t.meta?.categories) } : {}),+ }));+ const uniqueCards = cards.filter(+ (card, index) => card.slug && cards.findIndex((candidate) => candidate.slug === card.slug) === index,+ );+ const shortOfReportedTotal = reportedTotalItems !== undefined && uniqueCards.length < reportedTotalItems;+ const pagingStoppedEarly = lastReportedPage !== undefined+ && reportedTotalPages !== undefined+ && lastReportedPage < reportedTotalPages;+ const stalled = shortOfReportedTotal || pagingStoppedEarly;+ const complete = (stop === "end" || stop === "total-reached") && !stalled;+ const pagination: CatalogPagination = { items: uniqueCards.length, stalled, complete };+ if (reportedTotalItems !== undefined) pagination.totalItems = reportedTotalItems;+ if (pagination.stalled) pagination.reason = stop;+ if (pagination.stalled) {+ console.warn(+ `[composio] marketplace catalog paging stopped early (${stop}) after ${uniqueCards.length} toolkits`+ + (reportedTotalItems !== undefined ? ` of ~${reportedTotalItems}` : "")+ + "; serving a partial marketplace",+ );+ }+ return { cards: uniqueCards, pagination };+}++function keep(identity: string, catalog: HeldCatalog): void {+ held.delete(identity);+ held.set(identity, catalog);+ while (held.size > MAX_HELD_CATALOGS) {+ const oldest = held.keys().next().value;+ if (oldest === undefined) break;+ held.delete(oldest);+ }+}++function refresh(identity: string, readPage: CatalogPageReader): Promise<HeldCatalog | null> {+ const running = walks.get(identity);+ if (running) return running;+ const walk = walkCatalog(readPage).catch(() => null).then((found) => {+ const previous = held.get(identity) ?? null;+ const now = Date.now();+ const whole = found?.pagination.complete === true;+ if (!found || (previous && !whole && (previous.pagination.complete || found.cards.length < previous.cards.length))) {+ if (previous) {+ previous.failures += 1;+ previous.walkAgainAt = now + retryAfter(previous.failures);+ }+ return previous;+ }+ const failures = whole ? 0 : (previous?.failures ?? 0) + 1;+ const next: HeldCatalog = {+ at: now, cards: found.cards, pagination: found.pagination, digest: digestOf(found.cards),+ walkAgainAt: now + (whole ? CATALOG_FRESH_MS : retryAfter(failures)), failures,+ };+ keep(identity, next);+ save(identity, next);+ if (previous && previous.digest !== next.digest) announceChange();+ return next;+ }).finally(() => {+ if (walks.get(identity) === walk) walks.delete(identity);+ });+ walks.set(identity, walk);+ return walk;+}++const answer = (catalog: HeldCatalog): Catalog => ({+ cards: catalog.cards,+ pagination: catalog.pagination,+ fresh: Date.now() - catalog.at < CATALOG_FRESH_MS,+});++/** The catalog of the backend `identity` names; null when it has never been read and can't be now. Only a backend's first+ * read waits for the walk. */+export async function catalogFor(identity: string, readPage: CatalogPageReader): Promise<Catalog | null> {+ const known = held.get(identity) ?? loadSaved(identity);+ if (known) {+ if (Date.now() >= known.walkAgainAt) void refresh(identity, readPage);+ return answer(known);+ }+ const first = await refresh(identity, readPage);+ return first ? answer(first) : null;+}++/** Resolves once no walk is running: for tests, so none outlives the stand-in it reads. */+export async function catalogWalksSettled(): Promise<void> {+ while (walks.size) await Promise.all(walks.values());+}++/** What a restart leaves: nothing in memory, the saved file still there to start from. */+export function forgetCatalogs(): void {+ held.clear();+ savedFileRead = false;+}diff --git a/server/composio-inventory-cache.ts b/server/composio-inventory-cache.tsnew file mode 100644index 0000000000..5c24fc6aea--- /dev/null+++ b/server/composio-inventory-cache.ts@@ -0,0 +1,70 @@+// One read of an installation's connected apps for everyone asking together or soon after: the Apps page's list and its+// suggestions ask within moments of each other. It is for what a person is shown; a bot's tool call never reads it.++export interface KeptInventory<Service> {+ services: Record<string, Service>;+ complete: boolean;+}++interface ComparedService {+ connected?: boolean;+ pending?: boolean;+ accounts?: ReadonlyArray<{ id: string; status?: string }>;+}++export const INVENTORY_KEEP_MS = 20_000;++const kept = new Map<string, { at: number; inventory: KeptInventory<ComparedService> }>();+const reads = new Map<string, Promise<KeptInventory<ComparedService>>>();++/** The inventory kept for `identity` if under INVENTORY_KEEP_MS old, else the read already running, else `read`. `fresh`+ * always reads. Only a complete inventory is kept, and never one whose read began before forgetInventory. */+export function sharedInventory<Service extends ComparedService>(+ identity: string,+ read: () => Promise<KeptInventory<Service>>,+ fresh = false,+): Promise<KeptInventory<Service>> {+ if (!fresh) {+ const known = kept.get(identity);+ if (known && Date.now() - known.at < INVENTORY_KEEP_MS) return Promise.resolve(known.inventory as KeptInventory<Service>);+ const running = reads.get(identity);+ if (running) return running as Promise<KeptInventory<Service>>;+ }+ const reading: Promise<KeptInventory<Service>> = read().then((inventory) => {+ if (reads.get(identity) === reading) {+ if (inventory.complete) kept.set(identity, { at: Date.now(), inventory });+ else kept.delete(identity);+ }+ return inventory;+ }).finally(() => {+ if (reads.get(identity) === reading) reads.delete(identity);+ });+ reads.set(identity, reading);+ return reading;+}++/** A connection was started or removed: the next reader reads, and a read already running is not kept. */+export function forgetInventory(identity: string): void {+ kept.delete(identity);+ reads.delete(identity);+}++const accountsOf = (service: ComparedService | undefined) =>+ (service?.accounts ?? []).map((account) => `${account.id}:${account.status ?? ""}`).sort().join();++/** Whether a status check of some apps says other than the inventory kept for `identity`. Nothing kept: nothing differs. */+export function inventoryDiffers(identity: string, checked: Record<string, ComparedService>, canonical: (slug: string) => string): boolean {+ const known = kept.get(identity);+ if (!known) return false;+ return Object.entries(checked).some(([slug, now]) => {+ const before = known.inventory.services[canonical(slug)];+ return Boolean(before?.connected) !== Boolean(now.connected)+ || Boolean(before?.pending) !== Boolean(now.pending)+ || accountsOf(before) !== accountsOf(now);+ });+}++export function forgetInventories(): void {+ kept.clear();+ reads.clear();+}diff --git a/server/composio-inventory-shared.test.ts b/server/composio-inventory-shared.test.tsnew file mode 100644index 0000000000..0cf6809426--- /dev/null+++ b/server/composio-inventory-shared.test.ts@@ -0,0 +1,122 @@+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";++import { forgetInventories } from "./composio-inventory-cache.ts";+import { authorizeService, connectedServicesInventory, connectionStatus, removeAccount, removeService, setManagedBrokerAccess, sharedConnectedInventory } from "./composio.ts";+import { startFakeCatalogService, waitedOnService, type FakeCatalogService } from "./testing/fake-catalog-service.ts";++let fake: FakeCatalogService;+let installation = 0;+let clock = 0;+const later = (ms: number) => { clock += ms; };+const reads = () => fake.requests.connected;++beforeAll(async () => {+ fake = await startFakeCatalogService();+});+afterAll(async () => {+ await fake.close();+});+beforeEach(() => {+ const start = Date.now();+ clock = 0;+ vi.spyOn(Date, "now").mockImplementation(() => start + clock);+ Object.assign(fake, { down: false, connected: { gmail: { connected: true, status: "ACTIVE" } }, inventoryComplete: undefined });+ installation += 1;+ setManagedBrokerAccess({ url: fake.url, token: installation.toString(16).padStart(64, "a") });+ fake.requests.connected = 0;+});+afterEach(() => {+ setManagedBrokerAccess(null);+ forgetInventories();+ vi.restoreAllMocks();+});++describe("the connected-apps inventory the Apps page reads", () => {+ it("is read once for readers one after another, and once for readers asking together", async () => {+ for (let read = 0; read < 5; read += 1) {+ expect(await sharedConnectedInventory({})).toMatchObject({ complete: true, services: { gmail: { connected: true } } });+ }+ expect(reads()).toBe(1);++ later(21_000);+ const together = await waitedOnService(fake, () => Promise.all(Array.from({ length: 5 }, () => sharedConnectedInventory({}))));+ expect(together.waited).toBe(true);+ expect(reads()).toBe(2);+ });++ it("reads again for Refresh, and leaves the plain read uncached for a bot's own checks", async () => {+ await sharedConnectedInventory({});+ await sharedConnectedInventory({}, { fresh: true });+ expect(reads()).toBe(2);+ await sharedConnectedInventory({});+ expect(reads()).toBe(2);+ await connectedServicesInventory({});+ await connectedServicesInventory({});+ expect(reads()).toBe(4);+ });++ it.each([+ ["a connection is started", () => authorizeService({}, "slack")],+ ["an app is removed", () => removeService({}, "gmail")],+ ["an account is removed", () => removeAccount({}, "gmail", "ca_fixture")],+ ])("reads again once %s", async (_name, change) => {+ await sharedConnectedInventory({});+ await change();+ fake.connected = { gmail: { connected: true, status: "ACTIVE" }, slack: { connected: false, status: "INITIATED" } };+ expect((await sharedConnectedInventory({})).services).toHaveProperty("slack");+ expect(reads()).toBe(2);+ });++ it("reads again when a status check says other than it holds, and not when it says the same", async () => {+ await sharedConnectedInventory({});+ await connectionStatus({}, ["gmail", "slack"]);+ await sharedConnectedInventory({});+ expect(reads()).toBe(1);++ fake.connected = { gmail: { connected: true, status: "ACTIVE" }, slack: { connected: true, status: "ACTIVE" } };+ expect((await sharedConnectedInventory({})).services).not.toHaveProperty("slack");+ await connectionStatus({}, ["slack"]);+ expect((await sharedConnectedInventory({})).services).toMatchObject({ slack: { connected: true } });+ expect(reads()).toBe(2);++ fake.connected = { slack: { connected: true, status: "ACTIVE" } };+ await connectionStatus({}, ["gmail"]);+ expect((await sharedConnectedInventory({})).services).not.toHaveProperty("gmail");+ expect(reads()).toBe(3);+ });++ it("does not keep a read that was running when a connection changed", async () => {+ const open = fake.hold();+ const arrival = fake.arrival();+ const running = sharedConnectedInventory({});+ await arrival;+ open();+ await removeService({}, "gmail");+ await running;+ fake.connected = {};+ expect((await sharedConnectedInventory({})).services).toEqual({});+ expect(reads()).toBe(2);+ });++ it("keeps neither an incomplete inventory nor a failed read", async () => {+ fake.inventoryComplete = false;+ expect(await sharedConnectedInventory({})).toMatchObject({ complete: false });+ fake.inventoryComplete = true;+ expect(await sharedConnectedInventory({})).toMatchObject({ complete: true });+ expect(reads()).toBe(2);++ later(21_000);+ fake.down = true;+ await expect(sharedConnectedInventory({})).rejects.toThrow();+ fake.down = false;+ expect(await sharedConnectedInventory({})).toMatchObject({ complete: true });+ expect(reads()).toBe(4);+ });++ it("keeps one installation's inventory from another's", async () => {+ await sharedConnectedInventory({});+ setManagedBrokerAccess({ url: fake.url, token: "b".repeat(64) });+ await sharedConnectedInventory({});+ expect(reads()).toBe(2);+ });+});diff --git a/server/composio-inventory.test.ts b/server/composio-inventory.test.tsindex 14546f7367..90bf73628b 100644--- a/server/composio-inventory.test.ts+++ b/server/composio-inventory.test.ts@@ -26,7 +26,8 @@ function guard(cfg: AppConfig = {}) {return host;}-afterEach(() => {+afterEach(async () => {+ await composio.serviceSlugsReadSettled();composio.setManagedBrokerAccess(null);vi.unstubAllGlobals();vi.unstubAllEnvs();diff --git a/server/composio-service-slugs.test.ts b/server/composio-service-slugs.test.tsnew file mode 100644index 0000000000..4ba7e5d60d--- /dev/null+++ b/server/composio-service-slugs.test.ts@@ -0,0 +1,157 @@+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";++import { CONNECTOR_SERVICE_SLUGS_ENV } from "./connector-advertisement.ts";+import {+ CONNECTOR_SERVICE_SLUGS_STALE_MS,+ authorizeService,+ connectedServiceSlugs,+ connectionStatus,+ mcpIntegration,+ removeService,+ serviceSlugsReadSettled,+ setManagedBrokerAccess,+ sharedConnectedInventory,+} from "./composio.ts";+import { forgetInventories } from "./composio-inventory-cache.ts";+import { startFakeCatalogService, waitedOnService, type FakeCatalogService } from "./testing/fake-catalog-service.ts";++let fake: FakeCatalogService;+let installation = 0;+let clock = 0;+const later = (ms: number) => { clock += ms; };+const reads = () => fake.requests.connected;+const ACTIVE = { connected: true, status: "ACTIVE" };+const turn = { harnessUrl: "http://127.0.0.1:1", commsToken: "fixture", botId: "bot", threadId: "thread", connectorTools: { bland: { tools: "*" as const } } };+const advertised = async () => (await mcpIntegration({}, turn))!.env[CONNECTOR_SERVICE_SLUGS_ENV];++beforeAll(async () => {+ fake = await startFakeCatalogService();+});+afterAll(async () => {+ await fake.close();+});+beforeEach(() => {+ const start = Date.now();+ clock = 0;+ vi.spyOn(Date, "now").mockImplementation(() => start + clock);+ Object.assign(fake, { down: false, connected: { bland: ACTIVE }, inventoryComplete: undefined });+ installation += 1;+ setManagedBrokerAccess({ url: fake.url, token: installation.toString(16).padStart(64, "c") });+ fake.requests.connected = 0;+});+afterEach(async () => {+ await serviceSlugsReadSettled();+ setManagedBrokerAccess(null);+ forgetInventories();+ vi.useRealTimers();+ vi.restoreAllMocks();+});++describe("the connected services a tool's name is read against", () => {+ it("waits for the first read, then uses it for a minute", async () => {+ const first = await waitedOnService(fake, () => connectedServiceSlugs({}));+ expect(first).toEqual({ waited: true, value: ["bland"] });+ later(59_000);+ expect(await connectedServiceSlugs({})).toEqual(["bland"]);+ expect(reads()).toBe(1);+ });++ it("uses the list it has while one read brings the new one, from a minute old to five", async () => {+ await connectedServiceSlugs({});+ later(61_000);+ fake.connected = { bland: ACTIVE, bland_ai: ACTIVE };+ const old = await waitedOnService(fake, () => Promise.all([connectedServiceSlugs({}), connectedServiceSlugs({}), connectedServiceSlugs({})]));+ expect(old).toEqual({ waited: false, value: [["bland"], ["bland"], ["bland"]] });+ await serviceSlugsReadSettled();+ expect(reads()).toBe(2);+ expect(await connectedServiceSlugs({})).toEqual(["bland", "bland_ai"]);+ expect(reads()).toBe(2);+ });++ it("never judges by a list older than five minutes: it waits for the read", async () => {+ await connectedServiceSlugs({});+ later(CONNECTOR_SERVICE_SLUGS_STALE_MS);+ fake.connected = { bland: ACTIVE, bland_ai: ACTIVE };+ const read = await waitedOnService(fake, () => connectedServiceSlugs({}));+ expect(read).toEqual({ waited: true, value: ["bland", "bland_ai"] });+ });++ it.each([+ ["a connection is started here", () => authorizeService({}, "bland_ai")],+ ["an app is removed here", () => removeService({}, "bland")],+ ["a status check says other than the Apps page holds", async () => {+ await sharedConnectedInventory({});+ fake.connected = { bland: ACTIVE, bland_ai: ACTIVE };+ await connectionStatus({}, ["bland_ai"]);+ }],+ ])("waits for a new read once %s, however new its list", async (_name, change) => {+ await connectedServiceSlugs({});+ await change();+ fake.connected = { bland_ai: ACTIVE };+ fake.requests.connected = 0;+ const read = await waitedOnService(fake, () => connectedServiceSlugs({}));+ expect(read).toEqual({ waited: true, value: ["bland_ai"] });+ expect(reads()).toBe(1);+ });++ it("does not keep a read that was running when a connection changed", async () => {+ const open = fake.hold();+ const arrival = fake.arrival();+ const overtaken = connectedServiceSlugs({});+ await arrival;+ open();+ await removeService({}, "bland");+ expect(await overtaken).toEqual(["bland"]);+ fake.connected = { bland_ai: ACTIVE };+ fake.requests.connected = 0;+ expect(await waitedOnService(fake, () => connectedServiceSlugs({}))).toEqual({ waited: true, value: ["bland_ai"] });+ expect(reads()).toBe(1);+ });++ it("answers the last good list when the read it waited for fails", async () => {+ await connectedServiceSlugs({});+ await removeService({}, "bland");+ fake.down = true;+ expect(await connectedServiceSlugs({})).toEqual(["bland"]);+ later(CONNECTOR_SERVICE_SLUGS_STALE_MS);+ expect(await connectedServiceSlugs({})).toEqual(["bland"]);+ });+});++describe("a turn's start, for a bot with tool grants", () => {+ it("does not wait on the service when it has a list under five minutes old", async () => {+ expect((await waitedOnService(fake, advertised)).waited).toBe(true);+ later(2 * 60_000);+ fake.connected = { bland: ACTIVE, bland_ai: ACTIVE };+ const next = await waitedOnService(fake, advertised);+ expect(next).toEqual({ waited: false, value: JSON.stringify(["bland"]) });+ await serviceSlugsReadSettled();+ expect(await advertised()).toBe(JSON.stringify(["bland", "bland_ai"]));+ expect(reads()).toBe(2);+ });++ it("waits a bounded time for its first list, then starts without one", async () => {+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });+ const open = fake.hold();+ const arrival = fake.arrival();+ let started = false;+ const starting = advertised().finally(() => { started = true; });+ try {+ await arrival;+ await vi.advanceTimersByTimeAsync(4_000);+ expect(started).toBe(false);+ await vi.advanceTimersByTimeAsync(1_000);+ expect(await starting).toBeUndefined();+ } finally {+ open();+ }+ await serviceSlugsReadSettled();+ expect(await advertised()).toBe(JSON.stringify(["bland"]));+ });++ it("reads nothing for a bot with no tool grants", async () => {+ const { connectorTools: _none, ...plain } = turn;+ expect((await mcpIntegration({}, plain))!.env).not.toHaveProperty(CONNECTOR_SERVICE_SLUGS_ENV);+ expect(reads()).toBe(0);+ });+});diff --git a/server/composio.test.ts b/server/composio.test.tsindex e1df3e0bf6..ebbc747977 100644--- a/server/composio.test.ts+++ b/server/composio.test.ts@@ -7,6 +7,7 @@ import {applyManagedBrokerMessage,authorizeService,connectedServiceSlugs,+ serviceSlugsReadSettled,verifiedConnectedServiceSlugs,connectedServices,connectedServicesInventory,@@ -416,6 +417,7 @@ beforeAll(async () => {});afterAll(async () => {+ await serviceSlugsReadSettled();setManagedBrokerAccess(null);delete process.env.OMB_COMPOSIO_API;delete process.env.OMB_COMPOSIO_TOOLKITS_API;diff --git a/server/composio.ts b/server/composio.tsindex 56c5beb294..4b4310f50f 100644--- a/server/composio.ts+++ b/server/composio.ts@@ -37,6 +37,9 @@ import { parseMcpResponse, withToolsListFallback } from "./connector-tools-list.import { brokerAccess, managedComposioBrokerOff, type BrokerAccess } from "./composio-broker-access.ts";export { applyManagedBrokerMessage, brokerAccess, setManagedBrokerAccess, type BrokerAccess } from "./composio-broker-access.ts";export { prepareProjectSession, trustedSessionMcpUrl } from "./composio-session.ts";+import { catalogFor, type CatalogPagination, type ToolkitCard } from "./composio-catalog.ts";+import { forgetInventory, inventoryDiffers, sharedInventory } from "./composio-inventory-cache.ts";+export { onCatalogChange, rememberCatalogIn, toolkitCategories, type CatalogPagination, type CatalogStopReason, type ToolkitCard } from "./composio-catalog.ts";function toolkitBase() {return (process.env.OMB_COMPOSIO_TOOLKITS_API ?? `${DEFAULT_BACKEND_ORIGIN}/api/v3`).replace(/\/$/, "");@@ -229,7 +232,7 @@ export async function mcpIntegration(}const serviceSlugs = context.connectorTools === undefined? undefined- : serializeConnectorServiceSlugs(await connectedServiceSlugs(cfg, context.as));+ : serializeConnectorServiceSlugs(await connectedServiceSlugs(cfg, context.as, { waitMs: TURN_START_SLUGS_WAIT_MS }));if (serviceSlugs?.oversized) {console.warn(`[composio] connector service slugs for bot ${context.botId} exceed ${CONNECTOR_SERVICE_SLUGS_MAX_BYTES} bytes;`@@ -454,6 +457,19 @@ export async function connectedServicesInventory(cfg: AppConfig, as?: BrokerAcce};}+/** The inventory as the Apps page shows it: one read for readers together or within 20 s, read anew after a connection is+ * started or removed here, or a status check differs from it. `fresh` always reads. */+export function sharedConnectedInventory(cfg: AppConfig, options: { fresh?: boolean } = {}): Promise<ConnectedServicesInventory> {+ return sharedInventory(connectorToolsIdentity(cfg), () => connectedServicesInventory(cfg), options.fresh);+}++function connectionsChanged(cfg: AppConfig, as?: BrokerAccess): void {+ const identity = connectorToolsIdentity(cfg, as);+ forgetInventory(identity);+ if (connectorServiceSlugsCache?.identity === identity) connectorServiceSlugsCache = { ...connectorServiceSlugsCache, at: -Infinity };+ if (connectorServiceSlugsRequest?.identity === identity) connectorServiceSlugsRequest = null;+}+export async function verifiedConnectedServiceSlugs(cfg: AppConfig, as?: BrokerAccess): Promise<readonly string[]> {const { services, complete } = await connectedServicesInventory(cfg, as);if (!complete) throw new Error("Connected-app inventory is incomplete; account discovery did not finish.");@@ -487,7 +503,7 @@ export async function validateConnectorGrants(return `connectorTools names services that are not connected: ${unconnected.join(", ")}`;}const catalog = await listToolkits(cfg);- if (catalog.source !== "api" || !catalog.pagination?.complete) return null;+ if (catalog.source !== "api" || !catalog.pagination?.complete || !catalog.fresh) return null;const known = new Set(catalog.cards.map((card) => card.slug.toLowerCase()));const unknown = connectedAppGrantSlugs(grants).filter((slug) => !known.has(slug));if (unknown.length) {@@ -536,33 +552,58 @@ function connectorToolsIdentity(cfg: AppConfig, as?: BrokerAccess): string {let connectorToolsRequest: { identity: string; services: Promise<Record<string, ConnectorToolListing[]>> } | null = null;-/** Real backend slugs, so an underscored service (bland_ai) is never captured by a plain-prefix grant (bland); a failed read answers the last good one. */-export async function connectedServiceSlugs(cfg: AppConfig, as?: BrokerAccess): Promise<readonly string[]> {+/** Real backend slugs, so an underscored service (bland_ai) is never captured by a plain-prefix grant (bland); a failed read+ * answers the last good one. An answer under a minute old is used as it is. An older one is used while it is read again+ * behind, until it is CONNECTOR_SERVICE_SLUGS_STALE_MS old or a connection was started or removed here: from then the read+ * is waited for, for at most `waitMs` when a caller gives one.+ *+ * Security: this list only decides which service a tool's name belongs to. It never makes a connection usable: the vendor+ * refuses a removed one, and a call that names no tool is checked against verifiedConnectedServiceSlugs, which is never+ * cached. The risk in an old list is a service connected elsewhere since (bland_ai) being read as another's (bland), so the+ * list a call is judged by is never more than CONNECTOR_SERVICE_SLUGS_STALE_MS old. */+export async function connectedServiceSlugs(cfg: AppConfig, as?: BrokerAccess, options: { waitMs?: number } = {}): Promise<readonly string[]> {const identity = connectorToolsIdentity(cfg, as);- if (connectorServiceSlugsCache?.identity === identity- && Date.now() - connectorServiceSlugsCache.at < CONNECTOR_SERVICE_SLUGS_CACHE_MS) {- return connectorServiceSlugsCache.slugs;- }- if (connectorServiceSlugsRequest?.identity === identity) return connectorServiceSlugsRequest.slugs;- const walk = connectedServices(cfg, as).then(+ const known = connectorServiceSlugsCache?.identity === identity ? connectorServiceSlugsCache : null;+ const age = known ? Date.now() - known.at : Infinity;+ if (known && age < CONNECTOR_SERVICE_SLUGS_CACHE_MS) return known.slugs;+ const read = connectorServiceSlugsRequest?.identity === identity ? connectorServiceSlugsRequest.slugs : readServiceSlugs(cfg, as, identity);+ if (known && age < CONNECTOR_SERVICE_SLUGS_STALE_MS) return known.slugs;+ if (options.waitMs === undefined) return read;+ let timer: ReturnType<typeof setTimeout> | undefined;+ const lastKnown = new Promise<readonly string[]>((resolve) => { timer = setTimeout(() => resolve(known?.slugs ?? []), options.waitMs); });+ return Promise.race([read, lastKnown]).finally(() => clearTimeout(timer));+}++function readServiceSlugs(cfg: AppConfig, as: BrokerAccess | undefined, identity: string): Promise<readonly string[]> {+ const read = connectedServices(cfg, as).then((services) => {const slugs = Object.keys(services);- connectorServiceSlugsCache = { at: Date.now(), identity, slugs };+ // A read that a connection change overtook answers its own caller and is not kept.+ if (connectorServiceSlugsRequest?.slugs === read) connectorServiceSlugsCache = { at: Date.now(), identity, slugs };return slugs;},() => connectorServiceSlugsCache?.identity === identity ? connectorServiceSlugsCache.slugs : [] as readonly string[],- );- connectorServiceSlugsRequest = { identity, slugs: walk };- try {- return await walk;- } finally {- if (connectorServiceSlugsRequest?.slugs === walk) connectorServiceSlugsRequest = null;- }+ ).finally(() => {+ if (connectorServiceSlugsRequest?.slugs === read) connectorServiceSlugsRequest = null;+ });+ connectorServiceSlugsRequest = { identity, slugs: read };+ serviceSlugReads.add(read);+ void read.finally(() => serviceSlugReads.delete(read));+ return read;+}++/** Resolves once no read of the service slugs is running. */+export async function serviceSlugsReadSettled(): Promise<void> {+ while (serviceSlugReads.size) await Promise.all(serviceSlugReads);}const CONNECTOR_SERVICE_SLUGS_CACHE_MS = 60_000;+export const CONNECTOR_SERVICE_SLUGS_STALE_MS = 5 * 60_000;+/** How long a turn's start waits for the slugs when none it may use are held. */+const TURN_START_SLUGS_WAIT_MS = 5_000;let connectorServiceSlugsCache: { at: number; identity: string; slugs: readonly string[] } | null = null;let connectorServiceSlugsRequest: { identity: string; slugs: Promise<readonly string[]> } | null = null;+const serviceSlugReads = new Set<Promise<readonly string[]>>();const TOOL_DESCRIPTION_MAX = 240;const TOOLS_LIST_PAGES_MAX = 10;@@ -657,6 +698,12 @@ async function responseErrorFromBytes(status: number, bytes: Uint8Array): Promis}export async function connectionStatus(cfg: AppConfig, slugs: string[]) {+ const status = await readConnectionStatus(cfg, slugs);+ if (inventoryDiffers(connectorToolsIdentity(cfg), status, canonicalToolkitSlug)) connectionsChanged(cfg);+ return status;+}++async function readConnectionStatus(cfg: AppConfig, slugs: string[]) {const canonicalSlugs = [...new Set(slugs.map(canonicalToolkitSlug))];const apiKey = projectApiKey(cfg);if (!apiKey) {@@ -713,6 +760,7 @@ export async function removeService(cfg: AppConfig, slug: string, as?: BrokerAccconst apiKey = as ? null : projectApiKey(cfg);if (!apiKey) {const response = await brokerRequest(`/v1/connectors/${encodeURIComponent(toolkit)}`, { method: "DELETE" }, as);+ connectionsChanged(cfg, as);if (!response.ok) await throwBrokerError(response, `Connected apps: HTTP ${response.status}`);return removalResponseSchema.parse(await response.json());}@@ -726,6 +774,7 @@ export async function removeService(cfg: AppConfig, slug: string, as?: BrokerAccconst body = toolkitPageSchema.parse(await list.json());const id = body.items?.find((item) => item.slug && canonicalToolkitSlug(item.slug) === toolkit)?.connected_account?.id;if (!id) return { removed: 0 };+ connectionsChanged(cfg);await deleteConnectedAccount(apiKey, id);return { removed: 1 };}@@ -740,6 +789,7 @@ export async function removeAccount(cfg: AppConfig, slug: string, accountId: str`/v1/connectors/${encodeURIComponent(toolkit)}/accounts/${encodeURIComponent(accountId)}`,{ method: "DELETE" },);+ connectionsChanged(cfg);if (!response.ok) await throwBrokerError(response, `Connected apps: HTTP ${response.status}`);return removalResponseSchema.parse(await response.json());}@@ -753,6 +803,7 @@ export async function removeAccount(cfg: AppConfig, slug: string, accountId: str&& canonicalToolkitSlug(account.toolkit.slug) === toolkit);if (!owned) return { removed: 0 };+ connectionsChanged(cfg);await deleteConnectedAccount(apiKey, accountId);return { removed: 1 };}@@ -786,6 +837,7 @@ export async function authorizeService(cfg: AppConfig, slug: string, requestedAlconst unavailable = managedConnectorUnavailableReason(as ? "managed" : connectionMode(cfg), toolkit);if (unavailable) throw inputError(unavailable, 409);const apiKey = as ? null : projectApiKey(cfg);+ connectionsChanged(cfg, as);if (!apiKey) {const request: RequestInit = { method: "POST" };if (alias) request.body = JSON.stringify({ alias });@@ -836,29 +888,6 @@ export async function authorizeService(cfg: AppConfig, slug: string, requestedAlreturn { url: trustedAuthUrl(body.redirect_url, toolkit) };}-export interface ToolkitCard {- slug: string;- label: string;- blurb: string;- logo: string | null;- /** Toolkits such as public search need no user authorization. */- noAuth?: boolean;- domain: string | null;- categories?: string[];-}--/** Composio lists meta.categories as `{ id, name }` objects (older payloads: plain strings). */-export function toolkitCategories(raw: unknown): string[] | undefined {- if (!Array.isArray(raw)) return undefined;- const names = raw- .map((entry) => typeof entry === "string" ? entry : entry && typeof entry === "object" ? (entry as { name?: unknown }).name : undefined)- .filter((name): name is string => typeof name === "string")- .map((name) => name.trim().slice(0, 40))- .filter(Boolean);- const unique = [...new Set(names)].slice(0, 4);- return unique.length ? unique : undefined;-}-const CURATED: Array<ToolkitCard & { slug: CuratedConnectorSlug }> = [{ slug: "slack", label: "Slack", blurb: "Post updates and read channels", domain: "slack.com", logo: null, categories: ["Communication"] },{ slug: "github", label: "GitHub", blurb: "Issues, pull requests, and code", domain: "github.com", logo: null, categories: ["Developer tools"] },@@ -886,139 +915,25 @@ const CURATED: Array<ToolkitCard & { slug: CuratedConnectorSlug }> = [{ slug: "stripe", label: "Stripe", blurb: "Payments and customers", domain: "stripe.com", logo: null, categories: ["Finance"] },];-let toolkitCache: { at: number; cards: ToolkitCard[]; identity: string; pagination: CatalogPagination } | null = null;--export type CatalogStopReason =- | "end"- | "total-reached"- | "page-stuck"- | "cursor-repeated"- | "http-error"- | "bad-page"- | "limit";--export interface CatalogPagination {- items: number;- /** Upstream's own count of the full marketplace, when it reports one. */- totalItems?: number;- /** True when paging stopped before the reported total. */- stalled: boolean;- reason?: CatalogStopReason;- /** True only when the walk reached its natural end without stalling. */- complete: boolean;-}--export async function listToolkits(cfg: AppConfig): Promise<{ cards: ToolkitCard[]; source: "api" | "curated"; pagination?: CatalogPagination }> {+export async function listToolkits(cfg: AppConfig): Promise<{ cards: ToolkitCard[]; source: "api" | "curated"; pagination?: CatalogPagination; fresh?: boolean }> {const backendKey = projectApiKey(cfg);const broker = backendKey ? null : brokerAccess();+ const base = toolkitBase();const identity = backendKey- ? backendFingerprint("project-catalog", toolkitBase(), backendKey)+ ? backendFingerprint("project-catalog", base, backendKey): broker? backendFingerprint("managed-catalog", broker.url, broker.token): null;- if (identity && toolkitCache?.identity === identity && Date.now() - toolkitCache.at < 10 * 60_000) {- return { cards: toolkitCache.cards, source: "api", pagination: toolkitCache.pagination };- }- if (backendKey || broker) {- try {- const items: any[] = [];- const seenCursors = new Set<string>();- let cursor: string | undefined;- let lastReportedPage: number | undefined;- let reportedTotalItems: number | undefined;- let reportedTotalPages: number | undefined;- let stop: CatalogStopReason = "limit";- for (let page = 0; page < MAX_CONNECTED_ACCOUNT_PAGES; page += 1) {- const params = new URLSearchParams({ limit: "500", sort_by: "usage" });- if (cursor) params.set("cursor", cursor);- const res = backendKey- ? await fetch(`${toolkitBase()}/toolkits?${params}`, {- headers: { "x-api-key": backendKey },- signal: AbortSignal.timeout(15_000),- })- : await brokerRequest(cursor ? `/v1/catalog?cursor=${encodeURIComponent(cursor)}` : "/v1/catalog", {- signal: AbortSignal.timeout(15_000),- });- if (!res.ok) {- stop = "http-error";- break;- }- const json: any = await res.json();- const pageItems = json.items ?? json.data ?? [];- if (!Array.isArray(pageItems)) {- stop = "bad-page";- break;- }- items.push(...pageItems);- const pageTotalItems = Number(json.total_items);- if (Number.isFinite(pageTotalItems) && pageTotalItems > 0) reportedTotalItems = pageTotalItems;- // A broker that drops the cursor can replay a page while minting fresh cursors, so trust Composio's current_page movement.- const reportedPage = Number(json.current_page);- if (Number.isFinite(reportedPage)) {- if (lastReportedPage !== undefined && reportedPage <= lastReportedPage) {- stop = "page-stuck";- break;- }- lastReportedPage = reportedPage;- }- const pageTotalPages = Number(json.total_pages);- if (Number.isFinite(pageTotalPages) && pageTotalPages > 0) reportedTotalPages = pageTotalPages;- if (- lastReportedPage !== undefined &&- Number.isFinite(pageTotalPages) &&- pageTotalPages > 0 &&- lastReportedPage >= pageTotalPages- ) {- stop = "total-reached";- break;- }- const next = typeof json.next_cursor === "string" ? json.next_cursor.trim() : "";- if (!next) {- stop = "end";- break;- }- if (seenCursors.has(next)) {- stop = "cursor-repeated";- break;- }- seenCursors.add(next);- cursor = next;- }- if (items.length) {- const cards: ToolkitCard[] = items.map((t: any) => ({- slug: canonicalToolkitSlug(String(t.slug ?? t.key ?? t.name ?? "")),- label: t.name ?? t.slug ?? "",- blurb: (t.meta?.description ?? t.description ?? "").slice(0, 90),- logo: t.meta?.logo ?? t.logo ?? null,- noAuth: t.no_auth === true,- domain: null,- ...(toolkitCategories(t.meta?.categories) ? { categories: toolkitCategories(t.meta?.categories) } : {}),- }));- const uniqueCards = cards.filter(- (card, index) => card.slug && cards.findIndex((candidate) => candidate.slug === card.slug) === index,- );- const shortOfReportedTotal = reportedTotalItems !== undefined && uniqueCards.length < reportedTotalItems;- const pagingStoppedEarly = lastReportedPage !== undefined- && reportedTotalPages !== undefined- && lastReportedPage < reportedTotalPages;- const stalled = shortOfReportedTotal || pagingStoppedEarly;- const complete = (stop === "end" || stop === "total-reached") && !stalled;- const pagination: CatalogPagination = { items: uniqueCards.length, stalled, complete };- if (reportedTotalItems !== undefined) pagination.totalItems = reportedTotalItems;- if (pagination.stalled) pagination.reason = stop;- if (pagination.stalled) {- console.warn(- `[composio] marketplace catalog paging stopped early (${stop}) after ${uniqueCards.length} toolkits`- + (reportedTotalItems !== undefined ? ` of ~${reportedTotalItems}` : "")- + "; serving a partial marketplace",- );- }- toolkitCache = { at: Date.now(), cards: uniqueCards, identity: identity!, pagination };- return { cards: uniqueCards, source: "api", pagination };- }- } catch {}- }- return { cards: CURATED, source: "curated" };+ if (!identity) return { cards: CURATED, source: "curated" };+ const catalog = await catalogFor(identity, (cursor) => {+ if (!backendKey) {+ return brokerRequest(cursor ? `/v1/catalog?cursor=${encodeURIComponent(cursor)}` : "/v1/catalog", { signal: AbortSignal.timeout(15_000) }, broker);+ }+ const params = new URLSearchParams({ limit: "500", sort_by: "usage" });+ if (cursor) params.set("cursor", cursor);+ return fetch(`${base}/toolkits?${params}`, { headers: { "x-api-key": backendKey }, signal: AbortSignal.timeout(15_000) });+ });+ return catalog ? { ...catalog, source: "api" } : { cards: CURATED, source: "curated" };}export async function toolkitCard(cfg: AppConfig, slug: string): Promise<ToolkitCard> {diff --git a/server/host/app-suggestions.test.ts b/server/host/app-suggestions.test.tsindex 8267e8e5b8..58e7b97334 100644--- a/server/host/app-suggestions.test.ts+++ b/server/host/app-suggestions.test.ts@@ -162,6 +162,18 @@ describe("a bot searching the catalog", () => {expect(text).toContain('toolkits: ["<slug>"]');});+ it("reads the connections now for what a bot is told, and lets the Apps page's suggestions share a read", async () => {+ const asked: boolean[] = [];+ const suggestions = createAppSuggestions({+ dataDir, store: { bots, bot: () => null, onChange: () => () => {} } as never, configured: () => true, catalog: async () => ({ cards: CARDS }),+ services: async (live) => { asked.push(live === true); return services; },+ offerable: () => true, pickAvailable: () => false, decider: { choose } as never,+ });+ await suggestions.suggest({ limit: 3 });+ await suggestions.find({ query: "mail", bot: { id: "b1" } as never, refusal: () => null });+ expect(asked).toEqual([false, true]);+ });+it("remembers the top apps it didn't have, so they lead the suggestions", async () => {const suggestions = finder();await suggestions.find({ query: "spreadsheets", bot: bot(), refusal: () => null });diff --git a/server/host/app-suggestions.ts b/server/host/app-suggestions.tsindex eba2363e3c..dc956da313 100644--- a/server/host/app-suggestions.ts+++ b/server/host/app-suggestions.ts@@ -36,7 +36,8 @@ export interface AppSuggestionDeps {store: Pick<Store, "bots" | "bot" | "onChange">;configured(): boolean;catalog(): Promise<{ cards: ToolkitCard[] }>;- services(): Promise<Record<string, { connected: boolean }>>;+ /** `live` reads the service now, for what a bot is told; otherwise the read the Apps page shares will do. */+ services(live?: boolean): Promise<Record<string, { connected: boolean }>>;/** False for an app the organization, the team or this kind of connection doesn't let anyone connect here. */offerable(slug: string): boolean;pickAvailable(): boolean;@@ -88,10 +89,10 @@ export function createAppSuggestions(deps: AppSuggestionDeps) {return (app: string) => deps.offerable(app) && (!bots.length || bots.some((one) => !one.connectorScopes || one.connectorScopes.apps[app]));};- async function reading() {+ async function reading(live = false) {if (!deps.configured()) return null;try {- const [{ cards }, services] = await Promise.all([deps.catalog(), deps.services()]);+ const [{ cards }, services] = await Promise.all([deps.catalog(), deps.services(live)]);const connected = Object.entries(services).filter(([, service]) => service.connected).map(([app]) => app).sort();return { cards, connected, held: Object.keys(services), key: pickKey(connected, roles()) };} catch {@@ -134,7 +135,7 @@ export function createAppSuggestions(deps: AppSuggestionDeps) {/** A bot's catalog search, as the lines it reads. `refusal`: why this conversation can't connect an app, if it can't. */async find(input: { query: string; bot: BotRecord; refusal(app: string): string | null | undefined }): Promise<string> {- const here = await reading();+ const here = await reading(true);if (!here) return "The list of apps can't be read right now. Try again in a minute.";const matches = searchCatalog(here.cards, input.query, FIND_LIMIT * 3);const scope = input.bot.connectorScopes;diff --git a/server/index.ts b/server/index.tsindex 5e24dada1d..df7cd87924 100644--- a/server/index.ts+++ b/server/index.ts@@ -114,7 +114,7 @@ import { boatCreateRecoverySnapshot } from "./boat-create-idempotency.ts";import { boatDeletionSnapshot } from "./boat-delete-journal.ts";import { liveDecisionRefusal } from "../shared/live-approval.ts"; import type { PersonWaitKind } from "../shared/person-wait.ts";import { vpsLeftBehindNotice, vpsNotChosenReason } from "./cloud-backend.ts";-import * as composio from "./composio.ts";+import * as composio from "./composio.ts"; import { createConnectorListingRoutes } from "./routes/connectors-listing.ts";import { appSandboxRule, connectorCallFromFrame, connectorRefusalText, connectorScopeRefusalText, connectorUnrecognizedText, evaluateConnectorTools } from "./connector-verdict.ts";import { signInCardText } from "./connector-card-text.ts";import { BOT_HELD_CODE, BOT_PAUSED_CODE } from "../shared/bot-limit.ts"; import { createBotHolds } from "./host/bot-holds.ts"; import { createBotHoldRoutes } from "./routes/bot-holds.ts"; import { createCliLogin } from "./routes/cli-login.ts"; import { createStarterAwake } from "./host/starter-awake.ts"; import { createStarterCaps } from "./host/starter-caps.ts"; import { createStarterAwakeRoutes } from "./routes/starter-awake.ts"; import { chiefOfStaffPrompt, chiefOfStaffSystemPrompt } from "./chief-of-staff.ts"; import { coordinateMessageMax, coordinateTooLong } from "./too-long.ts"; import { chiefAbsentFrom, createChiefRooms } from "./host/chief-rooms.ts"; import { chiefLevel, readTeamRolesWith } from "./chief-level.ts"; import { defaultBotRefusal, ensureDefaultBot } from "./default-bot.ts";@@ -12090,7 +12090,8 @@ ROUTES.push(createBotMemoryRoutes({const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : (CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin")) || ownHome.owner(auth) ? { person: actorKey(auth as RequestAuth & { kind: "session" }), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL || DESKTOP_MANAGED ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: Boolean(botMoves) })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createImageSettingsRoutes({ config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, notificationListed), createUpdateCheckRoutes(updateRouteDeps({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE), dataDir: DATA_DIR, activeTurns: () => liveTurnByThread.size, actor: adminActorFor })), createSeatsRoutes({ signInList: signInAllowList, sessions: () => sessions.list() }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, lineLanguage: personLanguages.forLine, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), ownHome: ownHome.owner, automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }, connectionsMoved: (language) => cloudConnections.moved(language), connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages)); const conversationSharing = createConversationSharing({ team: CLOUD_TEAM, store: () => store, shares: conversationShares, saves: createTeamMemorySaves({ dataDir: DATA_DIR }), starter: (threadId) => threadStarters.get(threadId), audienceOf: teamHost.audienceOf, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), levelOf, levelFor: (person, botId) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }).level(botId), people: () => teamOwners.people?.list() ?? [], nameOf: (email) => teamHost.personName(personKey({ id: "", email })) ?? email, language: (person) => personLanguages.forLine(person), busy: threadBusy, routinesIn: (threadId) => (routines?.listRoutines() ?? []).filter((routine) => routine.sourceThreadId === threadId || routine.resultsThreadId === threadId).length, outside: cloudGuestDriven, audienceChanged: (botId, threadId) => { store.patchTask(botId, threadId, { rewound: true, resumeCursors: {} }); }, changed: (botId) => { const bot = store.bot(botId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, inbox: () => teamMessages.inbox, looking: (email, threadId) => teamPresence.looking(email, threadId), notify, botOf: (threadId) => store.botByThread(threadId)?.id, handTo: (threadId, person) => threadStarters.handTo(threadId, person) }); ROUTES.push(conversationSharing.routes);if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));const sidebarRoutes = createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot, renamed: (from, to) => (to ? botHolds.rename(from, to) : botHolds.forget("department", from)) }); ROUTES.push(teamPresence.routes, sidebarRoutes, createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (_auth, threadId) => { if (store.botByThread(threadId)) sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: (auth) => { noAiNotice.flush(); return teamMessages.arrived(auth); } } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), welcome: teamWelcome, profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }), names: SELF_HOSTED ? { store: personNames, shownAs: sessionPersonName } : null }), teamAway.routes, createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(publicUrl(), auth.kind === "session" ? requestOrigin(req) : null) }),- createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, policy: managedPolicy, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: memberLoginRefusal(CLOUD_TEAM) }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), vault: createSignInVaultChoices({ logins, cardBots: (id) => botLogins.cardBots(id), settle: signInSettle.settle, openCard: (botId, threadId, messageId) => { const card = signInMessage(botId, threadId, messageId)?.signIn; return card && card.place === "browser" && !card.superseded && !card.answeredInChat && !card.stopped && !signInOutcome(card) ? card : null; } }) })); const appSuggestions = createAppSuggestions({ dataDir: DATA_DIR, store, configured: () => composio.configured(cfg), catalog: () => composio.listToolkits(cfg), services: () => composio.connectedServices(cfg), offerable: (slug) => !managedPolicy.appRefusal(slug) && !managedConnectorUnavailableReason(composio.connectionMode(cfg), slug) && !teamConnections.personApps().includes(slug), pickAvailable: () => appPickAvailable(cfg), decider }); ROUTES.push(createAppSuggestionRoutes(appSuggestions));+ createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, policy: managedPolicy, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: memberLoginRefusal(CLOUD_TEAM) }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), vault: createSignInVaultChoices({ logins, cardBots: (id) => botLogins.cardBots(id), settle: signInSettle.settle, openCard: (botId, threadId, messageId) => { const card = signInMessage(botId, threadId, messageId)?.signIn; return card && card.place === "browser" && !card.superseded && !card.answeredInChat && !card.stopped && !signInOutcome(card) ? card : null; } }) })); const appSuggestions = createAppSuggestions({ dataDir: DATA_DIR, store, configured: () => composio.configured(cfg), catalog: () => composio.listToolkits(cfg), services: async (live) => live ? composio.connectedServices(cfg) : (await composio.sharedConnectedInventory(cfg)).services, offerable: (slug) => !managedPolicy.appRefusal(slug) && !managedConnectorUnavailableReason(composio.connectionMode(cfg), slug) && !teamConnections.personApps().includes(slug), pickAvailable: () => appPickAvailable(cfg), decider }); ROUTES.push(createAppSuggestionRoutes(appSuggestions));+ROUTES.push(createConnectorListingRoutes({ cfg: () => cfg, composio, managedHost: DESKTOP_MANAGED || CLOUD_HOME !== null })); composio.rememberCatalogIn(DATA_DIR); composio.onCatalogChange(() => broadcast({ kind: "apps-catalog" }, { adminOnly: true }));ROUTES.push(createRoomHoldRoutes({group: (id) => store.group(id),groupFor: personRooms.groupForAuth,@@ -14786,34 +14787,6 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {return json(res, 200, { ok: true, outcome: "stopped" });}- if (method === "GET" && path === "/api/connectors/catalog") {- const { cards, source, pagination } = await composio.listToolkits(cfg);- return json(res, 200, {- configured: composio.configured(cfg),- mode: composio.connectionMode(cfg),- setup: composio.connectorSetup(cfg, DESKTOP_MANAGED || CLOUD_HOME !== null),- source,- cards,- ...(pagination ? { pagination } : {}),- });- }- if (method === "GET" && path === "/api/connectors/connected") {- const availability = composio.connectorAvailability(cfg);- if (availability !== "configured") {- return json(res, 200, {- configured: false,- credentialStore: availability === "unreadable" ? "unavailable" : "ok",- services: {},- });- }- const inventory = await composio.connectedServicesInventory(cfg);- return json(res, 200, {- configured: true,- credentialStore: "ok",- inventoryComplete: inventory.complete,- services: inventory.services,- });- }if (method === "GET" && path === "/api/connectors/tools") {const availability = composio.connectorAvailability(cfg);const nativeTools = { ...emailHost.toolListing(), ...phones.toolListing() };diff --git a/server/routes/connectors-listing.test.ts b/server/routes/connectors-listing.test.tsnew file mode 100644index 0000000000..8d5a2eddce--- /dev/null+++ b/server/routes/connectors-listing.test.ts@@ -0,0 +1,59 @@+import type { IncomingMessage, ServerResponse } from "node:http";+import { describe, expect, it, vi } from "vitest";++import { createConnectorListingRoutes, type ConnectorListingDeps } from "./connectors-listing.ts";+import { PASS, type RouteContext } from "./table.ts";++function setup(overrides: Partial<ConnectorListingDeps["composio"]> = {}) {+ const composio = {+ listToolkits: vi.fn(async () => ({ cards: [{ slug: "gmail", label: "Gmail", blurb: "", logo: null, domain: null }], source: "api" as const, pagination: { items: 1, stalled: false, complete: true }, fresh: false })),+ configured: () => true,+ connectionMode: () => "managed" as const,+ connectorSetup: vi.fn(() => "ready" as const),+ connectorAvailability: vi.fn(() => "configured" as const),+ sharedConnectedInventory: vi.fn(async () => ({ complete: true, services: { gmail: { connected: true, pending: false, status: "ACTIVE", accounts: [] } } })),+ ...overrides,+ };+ const route = createConnectorListingRoutes({ cfg: () => ({}), composio, managedHost: true });+ const call = async (method: string, path: string, headers: Record<string, string> = {}) => {+ const json = vi.fn();+ const out = await route({ req: { headers } as IncomingMessage, res: {} as ServerResponse, path, method, json } as unknown as RouteContext);+ return { out, answer: json.mock.calls[0] as [unknown, number, Record<string, unknown>] | undefined };+ };+ return { composio, call };+}++describe("the Apps page's listing routes", () => {+ it("answers the catalog with how connected apps are set up here", async () => {+ const { composio, call } = setup();+ const { answer } = await call("GET", "/api/connectors/catalog");+ expect(answer![1]).toBe(200);+ expect(answer![2]).toEqual({+ configured: true, mode: "managed", setup: "ready", source: "api",+ cards: [expect.objectContaining({ slug: "gmail" })], pagination: { items: 1, stalled: false, complete: true },+ });+ expect(composio.connectorSetup).toHaveBeenCalledWith({}, true);+ });++ it("answers the connected apps from the shared read, and reads anew only for Refresh", async () => {+ const { composio, call } = setup();+ const { answer } = await call("GET", "/api/connectors/connected");+ expect(answer![2]).toEqual({ configured: true, credentialStore: "ok", inventoryComplete: true, services: { gmail: expect.objectContaining({ connected: true }) } });+ expect(composio.sharedConnectedInventory).toHaveBeenLastCalledWith({}, { fresh: false });+ await call("GET", "/api/connectors/connected", { "cache-control": "no-cache" });+ expect(composio.sharedConnectedInventory).toHaveBeenLastCalledWith({}, { fresh: true });+ });++ it.each([["unconfigured", "ok"], ["unreadable", "unavailable"]] as const)("reads nothing when connected apps are %s", async (availability, credentialStore) => {+ const { composio, call } = setup({ connectorAvailability: () => availability });+ expect((await call("GET", "/api/connectors/connected")).answer![2]).toEqual({ configured: false, credentialStore, services: {} });+ expect(composio.sharedConnectedInventory).not.toHaveBeenCalled();+ });++ it("leaves every other connector route to its own handler", async () => {+ const { call } = setup();+ for (const [method, path] of [["POST", "/api/connectors/catalog"], ["GET", "/api/connectors"], ["GET", "/api/connectors/tools"], ["GET", "/api/connectors/suggestions"], ["DELETE", "/api/connectors/connected"]] as const) {+ expect((await call(method, path)).out).toBe(PASS);+ }+ });+});diff --git a/server/routes/connectors-listing.ts b/server/routes/connectors-listing.tsnew file mode 100644index 0000000000..58275a3e6e--- /dev/null+++ b/server/routes/connectors-listing.ts@@ -0,0 +1,51 @@+// GET /api/connectors/catalog the apps the Apps page lists+// GET /api/connectors/connected which of them are connected+import type { AppConfig } from "../config.ts";+import type * as Composio from "../composio.ts";+import { PASS, type RouteHandler } from "./table.ts";++export interface ConnectorListingDeps {+ cfg(): AppConfig;+ composio: Pick<typeof Composio, "listToolkits" | "configured" | "connectionMode" | "connectorSetup" | "connectorAvailability" | "sharedConnectedInventory">;+ /** The desktop app or a Cloud home: a host the managed service comes with. */+ managedHost: boolean;+}++export function createConnectorListingRoutes(deps: ConnectorListingDeps): RouteHandler {+ const { composio } = deps;+ return async ({ req, res, path, method, json }) => {+ if (method !== "GET") return PASS;+ if (path === "/api/connectors/catalog") {+ const cfg = deps.cfg();+ const { cards, source, pagination } = await composio.listToolkits(cfg);+ return json(res, 200, {+ configured: composio.configured(cfg),+ mode: composio.connectionMode(cfg),+ setup: composio.connectorSetup(cfg, deps.managedHost),+ source,+ cards,+ ...(pagination ? { pagination } : {}),+ });+ }+ if (path === "/api/connectors/connected") {+ const cfg = deps.cfg();+ const availability = composio.connectorAvailability(cfg);+ if (availability !== "configured") {+ return json(res, 200, {+ configured: false,+ credentialStore: availability === "unreadable" ? "unavailable" : "ok",+ services: {},+ });+ }+ // The page's Refresh asks with no-cache; every other reader shares one read.+ const inventory = await composio.sharedConnectedInventory(cfg, { fresh: req.headers["cache-control"] === "no-cache" });+ return json(res, 200, {+ configured: true,+ credentialStore: "ok",+ inventoryComplete: inventory.complete,+ services: inventory.services,+ });+ }+ return PASS;+ };+}diff --git a/server/testing/fake-catalog-service.ts b/server/testing/fake-catalog-service.tsnew file mode 100644index 0000000000..44ced5a6a7--- /dev/null+++ b/server/testing/fake-catalog-service.ts@@ -0,0 +1,109 @@+// A loopback stand-in for the connected-apps service's catalog and connected list. It counts what reaches it and can hold,+// fail or drop a catalog page, so a test asserts on requests made and on whether a read waited, never on time.+import { createServer } from "node:http";+import type { AddressInfo } from "node:net";++export interface FakeCatalogService {+ url: string;+ /** Toolkits per page, in order. */+ pages: number[];+ /** Renames every toolkit, so the next walk brings a different list. */+ edition: number;+ requests: { catalog: number; connected: number; status: number };+ /** The catalog page (from 1) answered with HTTP 500, or whose connection is dropped. */+ failPage: number;+ dropPage: number;+ /** The catalog page (from 1) answered HTTP 200 with a body that is not JSON. */+ garblePage: number;+ /** Whether pages report the catalog's totals; without them a walk can only end on a page with no cursor. */+ totals: boolean;+ /** Every request answers HTTP 503. */+ down: boolean;+ connected: Record<string, { connected: boolean; status: string }>;+ /** What the connected list says of itself; unset, it says nothing, as an older service does. */+ inventoryComplete?: boolean;+ /** Holds every answer until the returned function is called. */+ hold(): () => void;+ /** Resolves when the next request arrives. */+ arrival(): Promise<void>;+ close(): Promise<void>;+}++export async function startFakeCatalogService(): Promise<FakeCatalogService> {+ let gate: Promise<void> | null = null;+ let arrived = () => {};+ const fake: Omit<FakeCatalogService, "url" | "close"> = {+ pages: [3, 3, 2], edition: 0, requests: { catalog: 0, connected: 0, status: 0 }, failPage: 0, dropPage: 0, garblePage: 0, totals: true, down: false,+ connected: { gmail: { connected: true, status: "ACTIVE" } },+ hold() {+ let open = () => {};+ gate = new Promise<void>((resolve) => { open = () => { gate = null; resolve(); }; });+ return open;+ },+ arrival: () => new Promise<void>((resolve) => { arrived = resolve; }),+ };+ const server = createServer(async (req, res) => {+ const url = new URL(req.url ?? "/", "http://fake");+ if (url.pathname === "/v1/catalog") fake.requests.catalog += 1;+ if (url.pathname === "/v1/connectors/connected") fake.requests.connected += 1;+ if (url.pathname === "/v1/connectors") fake.requests.status += 1;+ arrived();+ if (gate) await gate;+ res.setHeader("content-type", "application/json");+ if (fake.down) {+ res.statusCode = 503;+ return res.end(JSON.stringify({ error: "down" }));+ }+ if (url.pathname === "/v1/catalog") {+ const page = Number((url.searchParams.get("cursor") ?? "p1").slice(1));+ if (fake.failPage === page) {+ res.statusCode = 500;+ return res.end(JSON.stringify({ error: "page unavailable" }));+ }+ if (fake.dropPage === page) return void req.socket.destroy();+ if (fake.garblePage === page) return res.end("<html>bad gateway</html>");+ const start = fake.pages.slice(0, page - 1).reduce((sum, size) => sum + size, 0);+ const items = Array.from({ length: fake.pages[page - 1] ?? 0 }, (_, index) => ({ slug: `app${start + index}`, name: `App ${start + index} v${fake.edition}` }));+ return res.end(JSON.stringify({+ items,+ ...(fake.totals ? { total_items: fake.pages.reduce((sum, size) => sum + size, 0), current_page: page, total_pages: fake.pages.length } : {}),+ ...(page < fake.pages.length ? { next_cursor: `p${page + 1}` } : {}),+ }));+ }+ if (url.pathname === "/v1/connectors/connected") {+ return res.end(JSON.stringify({ services: fake.connected, ...(fake.inventoryComplete === undefined ? {} : { complete: fake.inventoryComplete }) }));+ }+ if (url.pathname === "/v1/connectors") {+ const asked = (url.searchParams.get("services") ?? "").split(",").filter(Boolean);+ return res.end(JSON.stringify({ services: Object.fromEntries(asked.map((slug) => [slug, fake.connected[slug] ?? { connected: false, status: "not_connected" }])) }));+ }+ if (req.method === "POST" && url.pathname.endsWith("/authorize")) return res.end(JSON.stringify({ url: "https://connect.composio.dev/fake" }));+ if (req.method === "DELETE") return res.end(JSON.stringify({ removed: 1 }));+ res.statusCode = 404;+ return res.end(JSON.stringify({ error: "not found" }));+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ return Object.assign(fake, {+ url: `http://127.0.0.1:${(server.address() as AddressInfo).port}`,+ close: () => new Promise<void>((resolve) => {+ server.close(() => resolve());+ server.closeAllConnections();+ }),+ });+}++/** Whether `read` was still waiting once the stand-in held a request of its; the stand-in answers before this returns. */+export async function waitedOnService<T>(fake: FakeCatalogService, read: () => Promise<T>): Promise<{ waited: boolean; value: T }> {+ const open = fake.hold();+ const arrival = fake.arrival();+ let settled = false;+ const pending = read().then((value) => {+ settled = true;+ return value;+ });+ await Promise.race([pending, arrival]);+ for (let turn = 0; turn < 20; turn += 1) await new Promise((resolve) => setImmediate(resolve));+ const waited = !settled;+ open();+ return { waited, value: await pending };+}diff --git a/src/components/AppGrantPrompt.tsx b/src/components/AppGrantPrompt.tsxindex 20403fe7c4..cf961ce414 100644--- a/src/components/AppGrantPrompt.tsx+++ b/src/components/AppGrantPrompt.tsx@@ -6,6 +6,7 @@ import type { ConnectorStatus } from "@/lib/connector-status";import { t } from "@/lib/i18n";import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";import { useStore, type Action, type Bot, type InstanceInfo } from "@/state/store";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";import { EMAIL_SLUG } from "../../shared/email";import { BotAvatar } from "./Avatar";import { UndoToast } from "./bot-access/ShareBotButton";@@ -81,14 +82,16 @@ function connectedAppSlugs(status: Record<string, ConnectorStatus>, emailConnect/** Security: only an owner or admin's connection gives an app to bots, and only they can change which bots use it. A bot* whose apps are off stays off, unless the connection was started from that bot. */export function useAppGrants({ status, emailConnected, inventoryReady }: { status: Record<string, ConnectorStatus>; emailConnected: boolean | null; inventoryReady: boolean }) {- const { state, dispatch } = useStore();+ const dispatch = useStoreDispatch();+ const everyBot = useStoreSelector((state) => state.bots);+ const instances = useStoreSelector((state) => state.instances);+ const allowed = useStoreSelector((state) => state.config?.managedPolicy?.apps);const admin = useOwnerOrAdmin();const [startingBot] = useState(takeConnectingBot);const [changing, setChanging] = useState<string | null>(null);const requested = useSyncExternalStore(subscribe, () => changeRequested, () => null);- const bots = botsForApps(state.bots, state.instances);+ const bots = botsForApps(everyBot, instances);const canChange = admin === true && inventoryReady && bots.length > 0;- const allowed = state.config?.managedPolicy?.apps;useEffect(() => {if (!requested) return;diff --git a/src/components/AppTile.tsx b/src/components/AppTile.tsxnew file mode 100644index 0000000000..c141c2c08d--- /dev/null+++ b/src/components/AppTile.tsx@@ -0,0 +1,301 @@+import { memo, useMemo, useRef } from "react";+import { Check, Loader2 } from "lucide-react";+import { cn } from "@/lib/cn";+import { t } from "@/lib/i18n";+import { connectorDescription } from "@/lib/app-catalog";+import { reusableConnectionUrl, type PendingAuthorization } from "@/lib/connector-oauth";+import {+ accountToReconnect,+ connectorActionLabel,+ hasActiveConnection,+ needsReconnect,+ type ConnectorAccount,+ type ConnectorInventoryPhase,+ type ConnectorStatus,+} from "@/lib/connector-status";+import type { AppState, Bot } from "@/state/store";+import { managedConnectorUnavailableReason } from "../../shared/connector-availability";+import { BotAvatar } from "./Avatar";+import { ServiceIcon, type ToolkitCard } from "./ServiceIcon";++export const USED_BY_AVATAR_SIZE = 16;++export interface AppTileActions {+ connect(slug: string, alias?: string, replacing?: ConnectorAccount): void;+ openUrl(url: string): void;+ /** Opens the app's account-name form, or closes it when it is the one open. */+ toggleAlias(slug: string): void;+ setAliasDraft(value: string): void;+ aliasRequired(): void;+ changeBots(slug: string): void;+ disconnect(target: { slug: string; label: string; account: ConnectorAccount }): void;+ openBotApps(botId: string): void;+}++export interface AppTileProps {+ card: ToolkitCard;+ serviceStatus: ConnectorStatus | undefined;+ pendingUrl: PendingAuthorization | undefined;+ /** The account name being typed for this app; null while its form is closed. */+ aliasDraft: string | null;+ busy: boolean;+ configured: boolean;+ inventoryPhase: ConnectorInventoryPhase;+ mode: "managed" | "self-hosted" | "unavailable";+ policy: NonNullable<AppState["config"]>["managedPolicy"] | undefined;+ usedBy: readonly Bot[];+ /** The bots that may use only some of this app's tools. */+ limited: readonly Bot[];+ canChangeBots: boolean;+ actions: AppTileActions;+}++export function tileStanding(card: ToolkitCard, serviceStatus: ConnectorStatus | undefined) {+ const failed = Boolean(serviceStatus?.status && /^(expired|failed)$/i.test(serviceStatus.status));+ const pending = Boolean(serviceStatus?.pending && !failed);+ const accounts = serviceStatus?.accounts ?? [];+ const included = card.noAuth === true+ || (serviceStatus?.connected === true && !accounts.length && !pending && !failed);+ return { failed, pending, accounts, included, connected: hasActiveConnection(serviceStatus) };+}++/** Actions that stay the same objects from render to render, each calling the newest one given, so a tile is not rendered+ * again for a handler that was only made anew. */+export function useTileActions(actions: AppTileActions): AppTileActions {+ const latest = useRef(actions);+ latest.current = actions;+ return useMemo<AppTileActions>(() => ({+ connect: (slug, alias, replacing) => latest.current.connect(slug, alias, replacing),+ openUrl: (url) => latest.current.openUrl(url),+ toggleAlias: (slug) => latest.current.toggleAlias(slug),+ setAliasDraft: (value) => latest.current.setAliasDraft(value),+ aliasRequired: () => latest.current.aliasRequired(),+ changeBots: (slug) => latest.current.changeBots(slug),+ disconnect: (target) => latest.current.disconnect(target),+ openBotApps: (botId) => latest.current.openBotApps(botId),+ }), []);+}++/** One app in the Apps panel. Props only and no hooks: it is rendered again only when something it shows changed. */+export function AppTileView({ card, serviceStatus, pendingUrl, aliasDraft, busy, configured, inventoryPhase, mode, policy, usedBy, limited, canChangeBots, actions }: AppTileProps) {+ const { failed, pending, accounts, included, connected } = tileStanding(card, serviceStatus);+ const pendingAuthorization = pending && !failed ? pendingUrl : undefined;+ const authorizationUrl = reusableConnectionUrl(pendingAuthorization);+ const reconnect = pending ? undefined : accountToReconnect(serviceStatus);+ const addingAccount = aliasDraft !== null && !included;+ const unavailableReason = policy?.apps && !policy.apps.allowAll && !policy.apps.allowlist.includes(card.slug) ? t("policy.managedBy", { organization: policy.organizationName })+ : managedConnectorUnavailableReason(mode, card.slug) ? t("connectors.selfHostOnlyReason") : null;+ const usedByLabel = t("apps.usedBy", { names: usedBy.map((candidate) => candidate.name).join(", ") });+ const description = unavailableReason ?? (+ pending+ ? authorizationUrl+ ? t("connectors.finishSetup")+ : t("connectors.finishSetupOrDisconnect")+ : reconnect+ ? t("connectors.signedOut")+ : failed && !accounts.length+ ? t("connectors.authExpired")+ : connectorDescription(card)+ );+ return (+ <div+ data-app-tile={card.slug}+ className="flex min-w-0 flex-col rounded-xl px-2 py-2 transition-colors hover:bg-raised/40"+ >+ <div className="flex items-center gap-3">+ <ServiceIcon card={card} className="size-10 shrink-0 rounded-[8px]" />+ <div className="min-w-0 flex-1">+ <div className="flex min-w-0 items-center gap-1.5">+ <span className="truncate text-[14px] font-semibold leading-5 text-ink">{card.label}</span>+ {connected && !pending && (+ <Check size={13} strokeWidth={2.5} className="shrink-0 text-success" aria-label={t("apps.connected")} />+ )}+ {usedBy.length > 0 && (+ <span+ className="ms-1 flex shrink-0 -space-x-1.5 rtl:space-x-reverse"+ title={usedByLabel}+ aria-label={usedByLabel}+ role="img"+ >+ {usedBy.slice(0, 3).map((candidate) => (+ <span+ key={candidate.id}+ data-used-by-avatar={candidate.id}+ className="flex size-5 shrink-0 items-center justify-center overflow-hidden rounded-full bg-menu ring-2 ring-menu"+ >+ <BotAvatar bot={candidate} size={USED_BY_AVATAR_SIZE} animated={false} />+ </span>+ ))}+ </span>+ )}+ </div>+ <div className="truncate text-[13px] leading-[18px] text-ink-secondary" title={description}>+ {description}+ </div>+ </div>+ <button+ type="button"+ disabled={!configured || inventoryPhase !== "ready" || busy || included || Boolean(unavailableReason)}+ title={unavailableReason ?? undefined}+ onClick={() => {+ if (pending && !failed) {+ const url = reusableConnectionUrl(pendingAuthorization);+ if (url) {+ actions.openUrl(url);+ } else {+ actions.connect(card.slug);+ }+ } else if (reconnect) {+ actions.connect(card.slug, reconnect.alias, reconnect);+ } else {+ actions.toggleAlias(card.slug);+ }+ }}+ className="inline-flex h-7 min-w-[64px] shrink-0 items-center justify-center gap-2 rounded-full bg-control/80 px-3 text-[13px] font-medium leading-5 text-ink transition-colors hover:bg-raised-hover disabled:opacity-40"+ >+ {unavailableReason ? (+ t("connectors.selfHostOnly")+ ) : busy ? (+ <Loader2 size={14} className="animate-spin" />+ ) : (+ connectorActionLabel(inventoryPhase, {+ busy,+ included,+ canContinue: Boolean(pendingAuthorization),+ pending,+ reconnect: Boolean(reconnect),+ hasAccounts: accounts.length > 0,+ failed: Boolean(failed),+ })+ )}+ </button>+ </div>+ <div className="ps-[52px]">+ {authorizationUrl && (+ <a href={authorizationUrl} target="_blank" rel="noopener noreferrer" onClick={(event) => {+ if (!reusableConnectionUrl(pendingAuthorization)) {+ event.preventDefault();+ actions.connect(card.slug);+ }+ }} className="mt-1.5 inline-block text-[12px] text-accent-text underline underline-offset-2">+ {t("connectors.openAuthorizationPage")}+ </a>+ )}+ {connected && !pending && (+ <div data-app-bots={card.slug} className="mt-1.5 flex min-w-0 items-center gap-2 text-[12px] leading-5 text-ink-secondary">+ <span className="min-w-0 truncate" title={usedBy.length ? usedByLabel : undefined}>+ {usedBy.length ? usedByLabel : t("apps.usedByNone")}+ </span>+ {canChangeBots && (+ <button+ type="button"+ onClick={() => actions.changeBots(card.slug)}+ aria-label={t("apps.whichBots", { app: card.label })}+ className="ms-auto shrink-0 rounded-full px-2 text-[12px] font-medium leading-5 text-accent-text transition-colors hover:bg-raised-hover"+ >+ {t("apps.usedByChange")}+ </button>+ )}+ </div>+ )}+ {accounts.length > 0 && (+ <div className="mt-1.5 space-y-0.5">+ {accounts.map((account) => {+ const active = /^active$/i.test(account.status);+ const reconnectable = needsReconnect(account) && account.id !== reconnect?.id;+ return (+ <div key={account.id} className="flex min-w-0 items-center gap-2 text-[12px] leading-5">+ {active ? <Check size={12} className="shrink-0 text-success" /> : <span className="size-3 shrink-0" />}+ <span className="min-w-0 truncate text-ink" title={`${account.alias ? `${account.id} · ` : ""}${account.status.toLowerCase()}`}>+ {account.alias || account.id}+ <span className="text-ink-secondary"> · {account.status.toLowerCase()}</span>+ </span>+ {reconnectable && (+ <button+ type="button"+ disabled={busy}+ onClick={() => actions.connect(card.slug, account.alias, account)}+ className="ms-auto shrink-0 rounded-full px-2 text-[12px] font-medium leading-5 text-accent-text transition-colors hover:bg-raised-hover disabled:opacity-40"+ aria-label={t("connectors.reconnectAria", { account: account.alias || account.id, service: card.label })}+ >+ {t("connectors.action.reconnect")}+ </button>+ )}+ <button+ type="button"+ disabled={busy}+ onClick={() => actions.disconnect({ slug: card.slug, label: card.label, account })}+ className={cn("shrink-0 rounded-full px-2 text-[12px] font-medium leading-5 text-ink-secondary transition-colors hover:bg-danger/10 hover:text-danger disabled:opacity-40", !reconnectable && "ms-auto")}+ aria-label={t("connectors.disconnectAria", {+ account: account.alias || account.id,+ service: card.label,+ })}+ >+ {t("connectors.disconnect")}+ </button>+ </div>+ );+ })}+ </div>+ )}+ {(serviceStatus?.connected || included) && (() => {+ if (!limited.length) return null;+ const names = limited.slice(0, 4).map((candidate, index) => (+ <span key={candidate.id}>+ {index > 0 && ", "}+ <button+ type="button"+ onClick={() => actions.openBotApps(candidate.id)}+ className="font-medium text-ink underline underline-offset-2 hover:text-accent-text"+ >+ {candidate.name}+ </button>+ </span>+ ));+ return (+ <div className="mt-1.5 text-[12px] leading-relaxed text-ink-secondary">+ <span>{t("connectors.grants.limited", { count: limited.length })}</span>{" "}+ {names}+ {limited.length > 4 && <span>{t("connectors.grants.more", { count: limited.length - 4 })}</span>}+ </div>+ );+ })()}+ {addingAccount && (+ <form+ className="mt-2 flex items-center gap-2"+ onSubmit={(event) => {+ event.preventDefault();+ const alias = (aliasDraft ?? "").trim();+ if (!alias) {+ actions.aliasRequired();+ return;+ }+ actions.connect(card.slug, alias);+ }}+ >+ <input+ autoFocus+ value={aliasDraft ?? ""}+ maxLength={64}+ onChange={(event) => actions.setAliasDraft(event.target.value)}+ placeholder={t("connectors.aliasPlaceholder")}+ aria-label={accounts.length > 0+ ? t("connectors.aliasAriaAnother", { service: card.label })+ : t("connectors.aliasAriaNew", { service: card.label })}+ className="h-8 min-w-0 flex-1 rounded-full bg-inset px-3 text-[13px] text-ink placeholder:text-ink-secondary focus:outline-none focus:ring-1 focus:ring-accent"+ />+ <button+ type="submit"+ disabled={busy || !(aliasDraft ?? "").trim()}+ className="inline-flex h-7 shrink-0 items-center rounded-full bg-accent px-3 text-[13px] font-medium leading-5 text-accent-ink disabled:opacity-40"+ >+ {t("connectors.action.continue")}+ </button>+ </form>+ )}+ </div>+ </div>+ );+}++export const AppTile = memo(AppTileView);diff --git a/src/components/PluginsPanel.listing.test.ts b/src/components/PluginsPanel.listing.test.tsnew file mode 100644index 0000000000..1920355462--- /dev/null+++ b/src/components/PluginsPanel.listing.test.ts@@ -0,0 +1,194 @@+// @vitest-environment happy-dom+// What the Apps panel paints and how often, counted: catalog requests, whether the loading line shows, tile renders.+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const fixture = vi.hoisted(() => ({+ cards: [] as Array<{ slug: string; label: string; blurb: string; logo: null; domain: null; categories: string[] }>,+ catalogRequests: 0,+ held: [] as Array<() => void>,+ hold: false,+ tileRenders: 0,+ state: { pluginsSurface: "apps", bots: [], instances: [], config: null, tick: 0 } as Record<string, unknown>,+ watchers: new Set<() => void>(),+}));++vi.mock("@/state/store", async () => {+ const { useSyncExternalStore } = await import("react");+ const subscribe = (watch: () => void) => {+ fixture.watchers.add(watch);+ return () => fixture.watchers.delete(watch);+ };+ return {+ api: vi.fn(async (path: string) => {+ if (path === "/api/connectors/catalog") {+ fixture.catalogRequests += 1;+ const cards = fixture.cards;+ if (fixture.hold) await new Promise<void>((resolve) => fixture.held.push(resolve));+ return { cards, source: "api", configured: true, mode: "managed", setup: "ready" };+ }+ if (path.startsWith("/api/connectors/suggestions")) return { cards: [], pick: "available" };+ throw new Error(`unexpected ${path}`);+ }),+ // As the real one: a reader of the whole store, rendered again by every change to it.+ useStore: () => ({ state: useSyncExternalStore(subscribe, () => fixture.state), dispatch: () => {} }),+ };+});+vi.mock("./ServiceIcon", () => ({+ ServiceIcon: ({ className }: { className?: string }) => {+ if (className?.includes("size-10")) fixture.tileRenders += 1;+ return null;+ },+}));+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => true }));+vi.mock("@/lib/connected-apps", () => ({+ preloadConnectedApps: vi.fn(async () => ({ services: {}, authoritative: true })),+ connectorStatusMemory: () => null,+ rememberConnectorStatus: () => {},+}));+vi.mock("@/lib/connected-apps-cache", () => ({ readCachedInventory: () => null, writeCachedInventory: () => {} }));+vi.mock("@/lib/product-events", () => ({ connectorConnect: vi.fn() }));+vi.mock("./McpServersPanel", () => ({ McpServersPanel: () => null }));+vi.mock("./XCard", () => ({ X_CARD_SEARCH: "x", XCard: () => null }));+vi.mock("./PostizCard", () => ({ PostizCard: () => null }));+vi.mock("./EmailCard", () => ({ EmailCard: () => null }));+vi.mock("./Avatar", () => ({ BotAvatar: () => null }));++const { PluginsPanel } = await import("./PluginsPanel");+const { StoreSourceContext } = await import("@/state/store-context");+const { t } = await import("@/lib/i18n");++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const source = {+ getState: () => fixture.state,+ subscribe: (watch: () => void) => {+ fixture.watchers.add(watch);+ return () => fixture.watchers.delete(watch);+ },+ dispatch: () => {},+} as never;+const KINDS = ["Mail", "Sheet", "Chat", "Code", "Pay", "Docs", "Cal", "Crm", "Ads", "Map"];+const catalog = (count: number, edition = 0) => Array.from({ length: count }, (_, index) => ({+ slug: `app${index}`, label: `${KINDS[index % KINDS.length]} ${index}${edition ? ` v${edition}` : ""}`, blurb: `does thing ${index}`, logo: null, domain: null, categories: [`Kind ${index % 9}`],+}));++let host: HTMLDivElement;+let root: Root | null = null;+const flush = () => act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });+const open = async () => {+ root = createRoot(host);+ await act(async () => root!.render(createElement(StoreSourceContext, { value: source }, createElement(PluginsPanel))));+ await flush();+};+const close = async () => {+ await act(async () => root?.unmount());+ root = null;+};+const answerCatalog = async () => {+ for (const answer of fixture.held.splice(0)) answer();+ await flush();+};+const tiles = () => host.querySelectorAll("[data-app-tile]").length;+/** The tiles rendered, first time or again, while `step` ran. */+const tileRenders = async (step: () => void) => {+ const before = fixture.tileRenders;+ await act(async () => step());+ await flush();+ return fixture.tileRenders - before;+};+const storeChange = () => {+ fixture.state = { ...fixture.state, tick: Number(fixture.state.tick) + 1 };+ for (const watch of Array.from(fixture.watchers)) watch();+};+const type = (text: string) => {+ const input = host.querySelector("input")!;+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, text);+ input.dispatchEvent(new Event("input", { bubbles: true }));+};+const loadingShown = () => host.textContent!.includes(t("connectors.loadingCatalog"));++beforeEach(() => {+ host = document.createElement("div");+ document.body.append(host);+ Object.assign(fixture, { cards: catalog(40), catalogRequests: 0, held: [], hold: false, tileRenders: 0 });+ fixture.state = { pluginsSurface: "apps", bots: [], instances: [], config: null, tick: 0 };+});+afterEach(async () => {+ await close();+ host.remove();+});++describe("opening the Apps panel again", () => {+ it("paints the apps it already has at once, reads the catalog again behind them, and shows what changed", async () => {+ fixture.hold = true;+ await open();+ const firstOpen = { tiles: tiles(), loadingShown: loadingShown() };+ await answerCatalog();+ const loaded = tiles();+ await close();++ fixture.cards = catalog(40, 2);+ fixture.catalogRequests = 0;+ await open();+ const reopened = { tiles: tiles(), loadingShown: loadingShown(), catalogRequests: fixture.catalogRequests };+ await answerCatalog();+ const refreshed = host.querySelector('[data-app-tile="app0"]')!.textContent;++ expect(firstOpen).toEqual({ tiles: 0, loadingShown: true });+ expect(loaded).toBeGreaterThan(0);+ expect(reopened).toEqual({ tiles: loaded, loadingShown: false, catalogRequests: 1 });+ expect(refreshed).toContain("Mail 0 v2");+ });+});++describe("how often the Apps panel renders its tiles", () => {+ const APPS = 300;+ beforeEach(async () => {+ fixture.cards = catalog(APPS);+ await open();+ });++ it("renders no tile again for a store change that is not about apps, however many show", async () => {+ expect(tiles()).toBeGreaterThan(0);+ expect(await tileRenders(storeChange)).toBe(0);++ const showAll = Array.from(host.querySelectorAll("button")).find((button) => button.textContent === t("apps.showAll", { count: String(APPS) }))!;+ expect(await tileRenders(() => showAll.click())).toBeGreaterThan(0);+ expect(tiles()).toBeGreaterThanOrEqual(APPS);+ expect(await tileRenders(storeChange)).toBe(0);+ });++ it("renders no tile again for a config frame that brings the same policy, and every tile for one that changes it", async () => {+ const policy = () => ({ organizationName: "Acme", apps: { allowAll: false, allowlist: ["app0"] } });+ const withConfig = (managedPolicy: unknown) => () => {+ fixture.state = { ...fixture.state, config: { managedPolicy } };+ for (const watch of Array.from(fixture.watchers)) watch();+ };+ await tileRenders(withConfig(policy()));+ expect(await tileRenders(withConfig(policy()))).toBe(0);+ expect(await tileRenders(withConfig({ ...policy(), organizationName: "Other" }))).toBe(tiles());+ });++ it("renders only the tiles a search brings in, and none of those it keeps as the search narrows", async () => {+ const all = APPS / KINDS.length;+ expect(await tileRenders(() => type("m"))).toBeGreaterThan(0);+ expect(tiles()).toBe(3 * all);+ expect(await tileRenders(() => type("ma"))).toBe(0);+ expect(tiles()).toBe(2 * all);+ expect(await tileRenders(() => type("mai"))).toBe(0);+ expect(tiles()).toBe(all);+ expect(host.querySelector("input")!.value).toBe("mai");+ expect(await tileRenders(storeChange)).toBe(0);+ });++ it("renders a tile again when its own app changes", async () => {+ fixture.cards = catalog(APPS).map((card) => card.slug === "app0" ? { ...card, blurb: "now does more" } : card);+ const { appCatalogAnnounced } = await import("@/lib/app-catalog-signal");+ const shownIn = host.querySelectorAll('[data-app-tile="app0"]').length;+ expect(shownIn).toBeGreaterThan(0);+ expect(await tileRenders(appCatalogAnnounced)).toBe(shownIn);+ expect(host.querySelector('[data-app-tile="app0"]')!.textContent).toContain("now does more");+ });+});diff --git a/src/components/PluginsPanel.navigation.test.ts b/src/components/PluginsPanel.navigation.test.tsindex 06f3cebd44..fa00786d3c 100644--- a/src/components/PluginsPanel.navigation.test.ts+++ b/src/components/PluginsPanel.navigation.test.ts@@ -62,6 +62,7 @@ vi.mock("./PostizCard", () => ({}));import { HOSTED_MCP_APPS } from "@/lib/hosted-mcp-apps";import { APPS_PREVIEW_COUNT, PluginsPanel, USED_BY_AVATAR_SIZE, botsUsingService } from "./PluginsPanel";+import { AppTile, AppTileView, type AppTileProps } from "./AppTile";import { connectedInventoryCopy } from "@/lib/connector-status";import { FACE_BOX } from "./cursor-face-data";import { MASCOT_BODIES } from "../../shared/mascot-bodies";@@ -84,7 +85,9 @@ function nodes(value: ReactNode): Node[] {return Children.toArray(value).flatMap((child) => {if (!isValidElement(child)) return [];const node = child as Node;- return [node, ...nodes(node.props.children)];+ // A tile is its own component, of props alone: what it renders is walked as part of the panel's tree.+ const inside = node.type === AppTile ? AppTileView(node.props as unknown as AppTileProps) : node.props.children;+ return [node, ...nodes(inside)];});}function render() {diff --git a/src/components/PluginsPanel.tsx b/src/components/PluginsPanel.tsxindex 08db1068e4..93c8a146d9 100644--- a/src/components/PluginsPanel.tsx+++ b/src/components/PluginsPanel.tsx@@ -1,13 +1,14 @@-import { Fragment, useCallback, useEffect, useRef, useState } from "react";-import { Check, ChevronDown, ChevronRight, Loader2, RefreshCw, Search, Server, TriangleAlert, X } from "lucide-react";-import { api, useStore, type Bot, type InstanceInfo } from "@/state/store";+import { Fragment, useCallback, useDeferredValue, useEffect, useMemo, useRef, useState } from "react";+import { ChevronDown, ChevronRight, Loader2, RefreshCw, Search, Server, TriangleAlert, X } from "lucide-react";+import { api, type Bot, type InstanceInfo } from "@/state/store";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";import { cn } from "@/lib/cn";import { glassPopupFrameStyle } from "@/lib/glass-popup";import { activeLocale, intlLocale, t } from "@/lib/i18n";import type { LocaleKey } from "@/locales";import { readCachedInventory } from "@/lib/connected-apps-cache";import { connectorStatusMemory, preloadConnectedApps, rememberConnectorStatus } from "@/lib/connected-apps";-import { reserveConnectionPage, reusableConnectionUrl, type PendingAuthorization } from "@/lib/connector-oauth";+import { reserveConnectionPage, type PendingAuthorization } from "@/lib/connector-oauth";import { mcpSignInLink } from "@/lib/mcp-sign-in";import { pollConnector } from "@/lib/connector-poll";import { connectorConnect } from "@/lib/product-events";@@ -15,17 +16,13 @@ import { managedConnectorUnavailableReason } from "../../shared/connector-availaimport { isConnectorToolGrantShape } from "@/lib/connector-grants";import {accountAliasTaken,- accountToReconnect,connectedInventoryCopy,- connectorActionLabel,hasActiveConnection,- needsReconnect,requiresAccountAlias,type ConnectorAccount,type ConnectorInventoryPhase,type ConnectorStatus,} from "@/lib/connector-status";-import { BotAvatar } from "./Avatar";import { SidebarPopoverMenu } from "./SidebarPopoverMenu";import { appCategoryLabel, CATEGORY_SECTION_SIZE, catalogSections, connectorDescription, inCategory, rankCategories } from "@/lib/app-catalog";import { McpServersPanel } from "./McpServersPanel";@@ -46,6 +43,8 @@ import { botAppScope } from "@/lib/bot-app-access";import { AppGrantPrompt, botsForApps, useAppGrants } from "./AppGrantPrompt";import { ConfirmDialog } from "./ConfirmDialog";import { ServiceIcon, type ToolkitCard } from "./ServiceIcon"; import { AppsSection } from "./AppsSection";+import { AppTile, tileStanding, useTileActions } from "./AppTile";+import { appCatalogMemory, loadAppCatalog, onAppCatalog, type AppCatalog, type CatalogPagination, type ConnectorSetup } from "@/lib/app-catalog-cache";export { ServiceIcon, type ToolkitCard } from "./ServiceIcon";export { preloadConnectedApps, type ConnectorInventory } from "@/lib/connected-apps";@@ -78,7 +77,7 @@ export function hostedShown(app: HostedApp, search: string, filter: AppsFilter,return matches && (filter === "all" || (filter === "connected" && connected?.[app.id] !== false));}-export type ConnectorSetup = "ready" | "needs-setup" | "service-unavailable";+export type { CatalogPagination, ConnectorSetup } from "@/lib/app-catalog-cache";export function connectorSetupNotice(state: {configured: boolean;@@ -93,34 +92,34 @@ export function connectorSetupNotice(state: {return { key: "connectors.notConfigured", tone: "warning" };}-export interface CatalogPagination {- items: number;- totalItems?: number;- stalled: boolean;- reason?: string;-}-export type AppsFilter = "all" | "connected" | "mcp";export const APPS_PREVIEW_COUNT = 48;-export const USED_BY_AVATAR_SIZE = 16;+export { USED_BY_AVATAR_SIZE } from "./AppTile";++const NO_BOTS: readonly Bot[] = [];+/** A config frame brings the policy as a new object each time; the tiles get the one they have while it says the same. */+const sameJson = (a: unknown, b: unknown) => a === b || JSON.stringify(a) === JSON.stringify(b);export function botsUsingService(bots: Bot[], instances: InstanceInfo[], slug: string): Bot[] {return botsForApps(bots, instances).filter((bot) => botAppScope(bot, slug) !== null);}export function PluginsPanel() {- const { state, dispatch } = useStore();+ const surface = useStoreSelector((state) => state.pluginsSurface);+ const bots = useStoreSelector((state) => state.bots);+ const instances = useStoreSelector((state) => state.instances);+ const policy = useStoreSelector((state) => state.config?.managedPolicy, sameJson);+ const dispatch = useStoreDispatch();const remoteClient = window.ogb?.remoteClient?.active === true;const dialogRef = useRef<HTMLDivElement>(null);- const surface = state.pluginsSurface;- const [cards, setCards] = useState<ToolkitCard[] | null>(null);- const [source, setSource] = useState<"api" | "curated">("curated");- const [pagination, setPagination] = useState<CatalogPagination | null>(null);- const [configured, setConfigured] = useState(false);- const [mode, setMode] = useState<"managed" | "self-hosted" | "unavailable">("unavailable");- const [setup, setSetup] = useState<ConnectorSetup | undefined>(undefined);+ const [cards, setCards] = useState<ToolkitCard[] | null>(() => appCatalogMemory()?.cards ?? null);+ const [source, setSource] = useState<"api" | "curated">(() => appCatalogMemory()?.source ?? "curated");+ const [pagination, setPagination] = useState<CatalogPagination | null>(() => appCatalogMemory()?.pagination ?? null);+ const [configured, setConfigured] = useState(() => appCatalogMemory()?.configured ?? false);+ const [mode, setMode] = useState<AppCatalog["mode"]>(() => appCatalogMemory()?.mode ?? "unavailable");+ const [setup, setSetup] = useState<ConnectorSetup | undefined>(() => appCatalogMemory()?.setup);const [status, setStatus] = useState<Record<string, ConnectorStatus>>(() => connectorStatusMemory()?.services ?? readCachedInventory()?.services ?? {},);@@ -136,7 +135,7 @@ export function PluginsPanel() {connectorStatusMemory() === null ? "loading" : "ready",);const [error, setError] = useState<string | { key: LocaleKey } | null>(null);- const [search, setSearch] = useState("");+ const [typed, setSearch] = useState("");const [tab, setTab] = useState<"marketplace" | "connected">("marketplace");const [showAllApps, setShowAllApps] = useState(false);const [hostedConnected, setHostedConnected] = useState<HostedConnections | null>(null);@@ -242,23 +241,22 @@ export function PluginsPanel() {useEffect(() => {let alive = true;void loadConnectionInventory();- api("/api/connectors/catalog")- .then((r) => {- if (!alive) return;- setCards(r.cards ?? []);- setSource(r.source ?? "curated");- setPagination(r.pagination ?? null);- setConfigured(Boolean(r.configured));- setMode(r.mode ?? "unavailable");- setSetup(r.setup);- })- .catch((e) => {- if (!alive) return;- setCards((current) => current ?? []);- setError(lacksAdminScope(e) ? { key: "connectors.adminOnly" } : e.message);- });+ const stop = onAppCatalog((r) => {+ setCards(r.cards);+ setSource(r.source);+ setPagination(r.pagination);+ setConfigured(r.configured);+ setMode(r.mode);+ setSetup(r.setup);+ });+ loadAppCatalog().catch((e) => {+ if (!alive) return;+ setCards((current) => current ?? []);+ setError(lacksAdminScope(e) ? { key: "connectors.adminOnly" } : e.message);+ });return () => {alive = false;+ stop();};}, [loadConnectionInventory]);@@ -398,9 +396,10 @@ export function PluginsPanel() {.finally(() => setBusySlug(null));};- const matching = (cards ?? []).filter((c) => (!managedConnectorUnavailableReason(mode, c.slug) || hasActiveConnection(status[c.slug]))- && matchesCatalogSearch(`${c.label} ${c.slug} ${connectorDescription(c)} ${(c.categories ?? []).join(" ")}`, search));- const isConnected = (slug: string) => Boolean(status[slug]?.connected || status[slug]?.accounts?.length);+ const search = useDeferredValue(typed);+ const matching = useMemo(() => (cards ?? []).filter((c) => (!managedConnectorUnavailableReason(mode, c.slug) || hasActiveConnection(status[c.slug]))+ && matchesCatalogSearch(`${c.label} ${c.slug} ${connectorDescription(c)} ${(c.categories ?? []).join(" ")}`, search)), [cards, mode, status, search]);+ const isConnected = useCallback((slug: string) => Boolean(status[slug]?.connected || status[slug]?.accounts?.length), [status]);const filter: AppsFilter = surface === "mcp" ? "mcp" : tab === "connected" ? "connected" : "all";const searching = search.trim().length > 0;/** A search covers the whole catalog, whichever view it was typed in. */@@ -409,10 +408,10 @@ export function PluginsPanel() {const showEmail = (!search || `email mail imap smtp mailbox ${t("email.description")}`.toLowerCase().includes(search.toLowerCase().trim())) && (listing === "all" || (listing === "connected" && emailConnected !== false));const showX = (!search || `${X_CARD_SEARCH} ${t("apps.x.description")}`.toLowerCase().includes(search.toLowerCase().trim())) && (listing === "all" || (listing === "connected" && xConnected !== false));const showPostiz = (!search || `${POSTIZ_SEARCH} ${t("postiz.description")}`.toLowerCase().includes(search.toLowerCase().trim())) && (listing === "all" || (listing === "connected" && postizConnected !== false));- const visible = (listing === "connected" ? matching.filter((card) => isConnected(card.slug)) : matching)+ const visible = useMemo(() => (listing === "connected" ? matching.filter((card) => isConnected(card.slug)) : matching).map((card, index) => ({ card, index })).sort((a, b) => Number(isConnected(b.card.slug)) - Number(isConnected(a.card.slug)) || a.index - b.index)- .map(({ card }) => card);+ .map(({ card }) => card), [listing, matching, isConnected]);const connectedHosted = HOSTED_MCP_APPS.filter((app) => hostedConnected?.[app.id]);const ownServers = mcpServers.filter((server) => ownMcpServer(server));const ownServerShown = (server: McpServerListing) => matchesCatalogSearch(`${server.name} ${isRemoteMcpListing(server) ? server.url : [server.command, ...server.args].join(" ")}`, search);@@ -430,20 +429,37 @@ export function PluginsPanel() {if (surface !== "apps") dispatch({ type: "togglePlugins", open: true, surface: "apps" });};- const ranked = rankCategories([...(cards ?? []), POSTIZ_CATALOG_CARD], undefined, POSTIZ_CATALOG_CARD.categories);+ const ranked = useMemo(() => rankCategories([...(cards ?? []), POSTIZ_CATALOG_CARD], undefined, POSTIZ_CATALOG_CARD.categories), [cards]);const moreCategories = ranked.more;const categoryInMore = category !== null && moreCategories.includes(category);const inCategoryView = filter === "all" && category !== null && !searching;const postizHere = showPostiz && (!inCategoryView || inCategory(POSTIZ_CATALOG_CARD, category));const nativeCardsShown = (!inCategoryView && (shownHosted.size > 0 || showEmail || showX)) || postizHere || (filter === "connected" && ownServers.some((server) => server.enabled && ownServerShown(server)));- const categoryCards = inCategoryView ? visible.filter((card) => inCategory(card, category)) : visible;+ const categoryCards = useMemo(() => inCategoryView ? visible.filter((card) => inCategory(card, category)) : visible, [inCategoryView, visible, category]);const sectioned = filter === "all" && !searching && category === null;- const sections = sectioned ? catalogSections(visible, isConnected, ranked.inline) : [];+ const sections = useMemo(() => sectioned ? catalogSections(visible, isConnected, ranked.inline) : [], [sectioned, visible, isConnected, ranked]);const allSection = sections.find((section) => section.kind === "all");const allCards = sectioned ? allSection?.cards ?? [] : categoryCards;const allCapped = sectioned && !showAllApps && allCards.length > APPS_PREVIEW_COUNT;const allShown = allCapped ? allCards.slice(0, APPS_PREVIEW_COUNT) : allCards;- const connectedCards = (cards ?? []).filter((card) => hasActiveConnection(status[card.slug]));+ const connectedCards = useMemo(() => (cards ?? []).filter((card) => hasActiveConnection(status[card.slug])), [cards, status]);+ const botLists = useMemo(() => {+ const cached = (find: (slug: string) => Bot[]) => {+ const found = new Map<string, Bot[]>();+ return (slug: string) => found.get(slug) ?? found.set(slug, find(slug)).get(slug)!;+ };+ return { usedBy: cached((slug) => botsUsingService(bots, instances, slug)), limited: cached((slug) => botsWithLimitedServiceTools(bots, instances, slug)) };+ }, [bots, instances]);+ const tileActions = useTileActions({+ connect: (slug, alias, replacing) => void connect(slug, alias, replacing),+ openUrl: (url) => { setError(null); void openConnectUrl(url).catch((e) => setError(e.message)); },+ toggleAlias: (slug) => { setAliasSlug((current) => current === slug ? null : slug); setAliasDraft(""); },+ setAliasDraft,+ aliasRequired: () => setError({ key: "connectors.aliasRequired" }),+ changeBots: appGrants.change,+ disconnect: setDisconnecting,+ openBotApps: (botId) => { close(); openBotSettings(dispatch, "access", { botId, page: "apps" }); },+ });const pickCategory = (next: string | null) => {setCategory(next);setTab("marketplace");@@ -529,7 +545,7 @@ export function PluginsPanel() {<label className="flex h-9 min-w-0 flex-1 items-center gap-2.5 rounded-full bg-control/70 px-3.5 focus-within:ring-1 focus-within:ring-accent"><Search size={15} className="shrink-0 text-ink-secondary" /><input- value={search}+ value={typed}onChange={(event) => setSearch(event.target.value)}placeholder={t("connectors.searchPlaceholder")}aria-label={t("connectors.searchPlaceholder")}@@ -766,234 +782,24 @@ export function PluginsPanel() {function renderTile(card: ToolkitCard) {const serviceStatus = status[card.slug];- const failed = serviceStatus?.status && /^(expired|failed)$/i.test(serviceStatus.status);- const pending = serviceStatus?.pending && !failed;- const pendingAuthorization = pending && !failed ? pendingUrls[card.slug] : undefined;- const authorizationUrl = reusableConnectionUrl(pendingAuthorization);- const accounts = serviceStatus?.accounts ?? [];- const included = card.noAuth === true- || (serviceStatus?.connected === true && !accounts.length && !pending && !failed);- const connected = hasActiveConnection(serviceStatus);- const reconnect = pending ? undefined : accountToReconnect(serviceStatus);- const addingAccount = aliasSlug === card.slug && !included;- const busy = busySlug === card.slug;- const policy = state.config?.managedPolicy, unavailableReason = policy?.apps && !policy.apps.allowAll && !policy.apps.allowlist.includes(card.slug) ? t("policy.managedBy", { organization: policy.organizationName })- : managedConnectorUnavailableReason(mode, card.slug) ? t("connectors.selfHostOnlyReason") : null;- const usedBy = connected || included ? botsUsingService(state.bots, state.instances, card.slug) : [];- const usedByLabel = t("apps.usedBy", { names: usedBy.map((candidate) => candidate.name).join(", ") });- const description = unavailableReason ?? (- pending- ? authorizationUrl- ? t("connectors.finishSetup")- : t("connectors.finishSetupOrDisconnect")- : reconnect- ? t("connectors.signedOut")- : failed && !accounts.length- ? t("connectors.authExpired")- : connectorDescription(card)- );+ const standing = tileStanding(card, serviceStatus);return (- <div+ <AppTilekey={card.slug}- data-app-tile={card.slug}- className="flex min-w-0 flex-col rounded-xl px-2 py-2 transition-colors hover:bg-raised/40"- >- <div className="flex items-center gap-3">- <ServiceIcon card={card} className="size-10 shrink-0 rounded-[8px]" />- <div className="min-w-0 flex-1">- <div className="flex min-w-0 items-center gap-1.5">- <span className="truncate text-[14px] font-semibold leading-5 text-ink">{card.label}</span>- {connected && !pending && (- <Check size={13} strokeWidth={2.5} className="shrink-0 text-success" aria-label={t("apps.connected")} />- )}- {usedBy.length > 0 && (- <span- className="ms-1 flex shrink-0 -space-x-1.5 rtl:space-x-reverse"- title={usedByLabel}- aria-label={usedByLabel}- role="img"- >- {usedBy.slice(0, 3).map((candidate) => (- <span- key={candidate.id}- data-used-by-avatar={candidate.id}- className="flex size-5 shrink-0 items-center justify-center overflow-hidden rounded-full bg-menu ring-2 ring-menu"- >- <BotAvatar bot={candidate} size={USED_BY_AVATAR_SIZE} animated={false} />- </span>- ))}- </span>- )}- </div>- <div className="truncate text-[13px] leading-[18px] text-ink-secondary" title={description}>- {description}- </div>- </div>- <button- type="button"- disabled={!configured || inventoryPhase !== "ready" || busy || included || Boolean(unavailableReason)}- title={unavailableReason ?? undefined}- onClick={() => {- if (pending && !failed) {- const url = reusableConnectionUrl(pendingAuthorization);- if (url) {- setError(null);- void openConnectUrl(url).catch((e) => setError(e.message));- } else {- void connect(card.slug);- }- } else if (reconnect) {- void connect(card.slug, reconnect.alias, reconnect);- } else {- setAliasSlug((current) => current === card.slug ? null : card.slug);- setAliasDraft("");- }- }}- className="inline-flex h-7 min-w-[64px] shrink-0 items-center justify-center gap-2 rounded-full bg-control/80 px-3 text-[13px] font-medium leading-5 text-ink transition-colors hover:bg-raised-hover disabled:opacity-40"- >- {unavailableReason ? (- t("connectors.selfHostOnly")- ) : busy ? (- <Loader2 size={14} className="animate-spin" />- ) : (- connectorActionLabel(inventoryPhase, {- busy,- included,- canContinue: Boolean(pendingAuthorization),- pending,- reconnect: Boolean(reconnect),- hasAccounts: accounts.length > 0,- failed: Boolean(failed),- })- )}- </button>- </div>- <div className="ps-[52px]">- {authorizationUrl && (- <a href={authorizationUrl} target="_blank" rel="noopener noreferrer" onClick={(event) => {- if (!reusableConnectionUrl(pendingAuthorization)) {- event.preventDefault();- void connect(card.slug);- }- }} className="mt-1.5 inline-block text-[12px] text-accent-text underline underline-offset-2">- {t("connectors.openAuthorizationPage")}- </a>- )}- {connected && !pending && (- <div data-app-bots={card.slug} className="mt-1.5 flex min-w-0 items-center gap-2 text-[12px] leading-5 text-ink-secondary">- <span className="min-w-0 truncate" title={usedBy.length ? usedByLabel : undefined}>- {usedBy.length ? usedByLabel : t("apps.usedByNone")}- </span>- {appGrants.canChange && (- <button- type="button"- onClick={() => appGrants.change(card.slug)}- aria-label={t("apps.whichBots", { app: card.label })}- className="ms-auto shrink-0 rounded-full px-2 text-[12px] font-medium leading-5 text-accent-text transition-colors hover:bg-raised-hover"- >- {t("apps.usedByChange")}- </button>- )}- </div>- )}- {accounts.length > 0 && (- <div className="mt-1.5 space-y-0.5">- {accounts.map((account) => {- const active = /^active$/i.test(account.status);- const reconnectable = needsReconnect(account) && account.id !== reconnect?.id;- return (- <div key={account.id} className="flex min-w-0 items-center gap-2 text-[12px] leading-5">- {active ? <Check size={12} className="shrink-0 text-success" /> : <span className="size-3 shrink-0" />}- <span className="min-w-0 truncate text-ink" title={`${account.alias ? `${account.id} · ` : ""}${account.status.toLowerCase()}`}>- {account.alias || account.id}- <span className="text-ink-secondary"> · {account.status.toLowerCase()}</span>- </span>- {reconnectable && (- <button- type="button"- disabled={busy}- onClick={() => void connect(card.slug, account.alias, account)}- className="ms-auto shrink-0 rounded-full px-2 text-[12px] font-medium leading-5 text-accent-text transition-colors hover:bg-raised-hover disabled:opacity-40"- aria-label={t("connectors.reconnectAria", { account: account.alias || account.id, service: card.label })}- >- {t("connectors.action.reconnect")}- </button>- )}- <button- type="button"- disabled={busy}- onClick={() => setDisconnecting({ slug: card.slug, label: card.label, account })}- className={cn("shrink-0 rounded-full px-2 text-[12px] font-medium leading-5 text-ink-secondary transition-colors hover:bg-danger/10 hover:text-danger disabled:opacity-40", !reconnectable && "ms-auto")}- aria-label={t("connectors.disconnectAria", {- account: account.alias || account.id,- service: card.label,- })}- >- {t("connectors.disconnect")}- </button>- </div>- );- })}- </div>- )}- {(serviceStatus?.connected || included) && (() => {- const limited = botsWithLimitedServiceTools(state.bots, state.instances, card.slug);- if (!limited.length) return null;- const names = limited.slice(0, 4).map((candidate, index) => (- <span key={candidate.id}>- {index > 0 && ", "}- <button- type="button"- onClick={() => { close(); openBotSettings(dispatch, "access", { botId: candidate.id, page: "apps" }); }}- className="font-medium text-ink underline underline-offset-2 hover:text-accent-text"- >- {candidate.name}- </button>- </span>- ));- return (- <div className="mt-1.5 text-[12px] leading-relaxed text-ink-secondary">- <span>{t("connectors.grants.limited", { count: limited.length })}</span>{" "}- {names}- {limited.length > 4 && <span>{t("connectors.grants.more", { count: limited.length - 4 })}</span>}- </div>- );- })()}- {addingAccount && (- <form- className="mt-2 flex items-center gap-2"- onSubmit={(event) => {- event.preventDefault();- const alias = aliasDraft.trim();- if (!alias) {- setError({ key: "connectors.aliasRequired" });- return;- }- void connect(card.slug, alias);- }}- >- <input- autoFocus- value={aliasDraft}- maxLength={64}- onChange={(event) => setAliasDraft(event.target.value)}- placeholder={t("connectors.aliasPlaceholder")}- aria-label={accounts.length > 0- ? t("connectors.aliasAriaAnother", { service: card.label })- : t("connectors.aliasAriaNew", { service: card.label })}- className="h-8 min-w-0 flex-1 rounded-full bg-inset px-3 text-[13px] text-ink placeholder:text-ink-secondary focus:outline-none focus:ring-1 focus:ring-accent"- />- <button- type="submit"- disabled={busy || !aliasDraft.trim()}- className="inline-flex h-7 shrink-0 items-center rounded-full bg-accent px-3 text-[13px] font-medium leading-5 text-accent-ink disabled:opacity-40"- >- {t("connectors.action.continue")}- </button>- </form>- )}- </div>- </div>+ card={card}+ serviceStatus={serviceStatus}+ pendingUrl={pendingUrls[card.slug]}+ aliasDraft={aliasSlug === card.slug ? aliasDraft : null}+ busy={busySlug === card.slug}+ configured={configured}+ inventoryPhase={inventoryPhase}+ mode={mode}+ policy={policy}+ usedBy={standing.connected || standing.included ? botLists.usedBy(card.slug) : NO_BOTS}+ limited={serviceStatus?.connected || standing.included ? botLists.limited(card.slug) : NO_BOTS}+ canChangeBots={appGrants.canChange}+ actions={tileActions}+ />);}}diff --git a/src/components/bot-settings/useBotApps.ts b/src/components/bot-settings/useBotApps.tsindex dc8e2522c6..c14a8a95db 100644--- a/src/components/bot-settings/useBotApps.ts+++ b/src/components/bot-settings/useBotApps.ts@@ -8,6 +8,9 @@ import { EMAIL_SLUG, type EmailStatus } from "../../../shared/email";import { preloadConnectedApps, type ConnectorInventory } from "@/lib/connected-apps";import type { ConnectorAccount } from "@/lib/connector-status";import type { ToolkitCard } from "../ServiceIcon";+import { cardsBySlug, loadAppCards, onAppCatalog } from "@/lib/app-catalog-cache";++export { loadAppCards };export interface BotApp {slug: string;@@ -25,17 +28,6 @@ export interface BotApps {connectedSlugs: string[];}-let cardsRequest: Promise<Map<string, ToolkitCard>> | null = null;-export function loadAppCards(): Promise<Map<string, ToolkitCard>> {- cardsRequest ??= api("/api/connectors/catalog")- .then((response: { cards?: ToolkitCard[] }) => new Map((response.cards ?? []).map((card) => [card.slug, card])))- .catch(() => {- cardsRequest = null;- return new Map<string, ToolkitCard>();- });- return cardsRequest;-}-function slugLabel(slug: string): string {return slug.charAt(0).toUpperCase() + slug.slice(1).replace(/[_-]+/g, " ");}@@ -110,12 +102,14 @@ export function useBotApps(bot: Bot, load = true): BotAppsState {setCards(result);setCardsSettled(true);});+ const stopCatalog = onAppCatalog((catalog) => setCards(cardsBySlug(catalog)));void api("/api/email").then((result: EmailStatus) => { if (!cancelled) setEmail(result); }).catch(() => {}).finally(() => { if (!cancelled) setEmailSettled(true); });return () => {cancelled = true;+ stopCatalog();};}, [load]);diff --git a/src/lib/app-catalog-cache.test.ts b/src/lib/app-catalog-cache.test.tsnew file mode 100644index 0000000000..94378c5520--- /dev/null+++ b/src/lib/app-catalog-cache.test.ts@@ -0,0 +1,85 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const fixture = vi.hoisted(() => ({ label: "Gmail", fail: false, requests: 0, answers: [] as Array<() => void>, hold: false }));+vi.mock("@/state/store", () => ({+ api: vi.fn(async (path: string) => {+ if (path !== "/api/connectors/catalog") throw new Error(`unexpected ${path}`);+ fixture.requests += 1;+ if (fixture.hold) await new Promise<void>((resolve) => fixture.answers.push(resolve));+ if (fixture.fail) throw new Error("down");+ return { cards: [{ slug: "gmail", label: fixture.label, blurb: "mail", logo: null, domain: null }], source: "api", configured: true, mode: "managed", setup: "ready", pagination: { items: 1, stalled: false } };+ }),+}));++let cache: typeof import("./app-catalog-cache");+let signal: typeof import("./app-catalog-signal");+const settle = async () => { for (let turn = 0; turn < 5; turn += 1) await Promise.resolve(); };++beforeEach(async () => {+ vi.resetModules();+ Object.assign(fixture, { label: "Gmail", fail: false, requests: 0, answers: [], hold: false });+ cache = await import("./app-catalog-cache");+ signal = await import("./app-catalog-signal");+});++describe("the Apps catalog this page holds", () => {+ it("is read once however many ask at once, and then answers a bot's apps from memory", async () => {+ fixture.hold = true;+ const readers = [cache.loadAppCatalog(), cache.loadAppCards(), cache.loadAppCards()];+ await settle();+ expect(fixture.requests).toBe(1);+ expect(cache.appCatalogMemory()).toBeNull();+ fixture.answers.shift()!();+ const [catalog, cards] = await Promise.all(readers) as [Awaited<ReturnType<typeof cache.loadAppCatalog>>, Map<string, unknown>, Map<string, unknown>];+ expect(catalog).toMatchObject({ source: "api", configured: true, mode: "managed", setup: "ready", pagination: { items: 1 } });+ expect(cards.get("gmail")).toBe(catalog.cards[0]);++ fixture.hold = false;+ expect(await cache.loadAppCards()).toBe(cards);+ expect(fixture.requests).toBe(1);+ });++ it("keeps the same cards when a later read brings the same list, and tells listeners of every read", async () => {+ const first = await cache.loadAppCatalog();+ const heard = vi.fn();+ const stop = cache.onAppCatalog(heard);+ const same = await cache.loadAppCatalog();+ expect(same.cards).toBe(first.cards);+ expect(cache.cardsBySlug(same)).toBe(cache.cardsBySlug(first));+ fixture.label = "Google Mail";+ const changed = await cache.loadAppCatalog();+ expect(changed.cards).not.toBe(first.cards);+ expect(changed.cards[0]!.label).toBe("Google Mail");+ expect(heard).toHaveBeenCalledTimes(2);+ stop();+ await cache.loadAppCatalog();+ expect(heard).toHaveBeenCalledTimes(2);+ });++ it("reads again when the server says its catalog changed, only where a copy is held or shown", async () => {+ signal.appCatalogAnnounced();+ await settle();+ expect(fixture.requests).toBe(0);++ await cache.loadAppCatalog();+ fixture.label = "Google Mail";+ signal.appCatalogAnnounced();+ await settle();+ expect(fixture.requests).toBe(2);+ expect(cache.appCatalogMemory()!.cards[0]!.label).toBe("Google Mail");+ expect((await cache.loadAppCards()).get("gmail")!.label).toBe("Google Mail");+ expect(fixture.requests).toBe(2);+ });++ it("answers no cards when the first read fails, keeps what it held when a later one does, and asks again", async () => {+ fixture.fail = true;+ expect((await cache.loadAppCards()).size).toBe(0);+ await expect(cache.loadAppCatalog()).rejects.toThrow("down");+ fixture.fail = false;+ expect((await cache.loadAppCards()).size).toBe(1);+ expect(fixture.requests).toBe(3);+ fixture.fail = true;+ await expect(cache.loadAppCatalog()).rejects.toThrow("down");+ expect((await cache.loadAppCards()).size).toBe(1);+ });+});diff --git a/src/lib/app-catalog-cache.ts b/src/lib/app-catalog-cache.tsnew file mode 100644index 0000000000..5026b40d7c--- /dev/null+++ b/src/lib/app-catalog-cache.ts@@ -0,0 +1,88 @@+import type { ToolkitCard } from "@/components/ServiceIcon";+import { onAppCatalogAnnounced } from "@/lib/app-catalog-signal";+import { api } from "@/state/store";++// The Apps catalog as this page last read it. The Apps panel and a bot's apps share the one copy and the one request, so a+// re-opened panel paints from it at once and reads again behind.++export type ConnectorSetup = "ready" | "needs-setup" | "service-unavailable";++export interface CatalogPagination {+ items: number;+ totalItems?: number;+ stalled: boolean;+ reason?: string;+}++export interface AppCatalog {+ cards: ToolkitCard[];+ source: "api" | "curated";+ pagination: CatalogPagination | null;+ configured: boolean;+ mode: "managed" | "self-hosted" | "unavailable";+ setup: ConnectorSetup | undefined;+}++let catalog: AppCatalog | null = null;+let cardsText = "";+let request: Promise<AppCatalog> | null = null;+let bySlug: { of: ToolkitCard[]; map: Map<string, ToolkitCard> } | null = null;+const listeners = new Set<(catalog: AppCatalog) => void>();++export function appCatalogMemory(): AppCatalog | null {+ return catalog;+}++/** The new list, with each card that is as it was kept as the same object, so only what changed is painted again. */+function keepingKnownCards(next: ToolkitCard[], known: ToolkitCard[]): ToolkitCard[] {+ const before = new Map(known.map((card) => [card.slug, card]));+ return next.map((card) => {+ const same = before.get(card.slug);+ return same && JSON.stringify(same) === JSON.stringify(card) ? same : card;+ });+}++/** Reads the catalog, one request however many ask at once. Cards that came back unchanged stay the same array. */+export function loadAppCatalog(): Promise<AppCatalog> {+ request ??= api("/api/connectors/catalog")+ .then((r: Partial<AppCatalog>) => {+ const cards = r.cards ?? [];+ const text = JSON.stringify(cards);+ const next: AppCatalog = {+ cards: !catalog ? cards : text === cardsText ? catalog.cards : keepingKnownCards(cards, catalog.cards),+ source: r.source ?? "curated",+ pagination: r.pagination ?? null,+ configured: Boolean(r.configured),+ mode: r.mode ?? "unavailable",+ setup: r.setup,+ };+ cardsText = text;+ catalog = next;+ for (const listener of listeners) listener(next);+ return next;+ })+ .finally(() => {+ request = null;+ });+ return request;+}++/** Called with each catalog read from now on. */+export function onAppCatalog(listener: (catalog: AppCatalog) => void): () => void {+ listeners.add(listener);+ return () => listeners.delete(listener);+}++onAppCatalogAnnounced(() => {+ if (catalog || listeners.size) void loadAppCatalog().catch(() => {});+});++/** The held cards by slug, read first when nothing is held; empty when that read fails. */+export function loadAppCards(): Promise<Map<string, ToolkitCard>> {+ return (catalog ? Promise.resolve(catalog) : loadAppCatalog()).then(cardsBySlug, () => new Map<string, ToolkitCard>());+}++export function cardsBySlug({ cards }: Pick<AppCatalog, "cards">): Map<string, ToolkitCard> {+ if (bySlug?.of !== cards) bySlug = { of: cards, map: new Map(cards.map((card) => [card.slug, card])) };+ return bySlug.map;+}diff --git a/src/lib/app-catalog-signal.ts b/src/lib/app-catalog-signal.tsnew file mode 100644index 0000000000..a5786af103--- /dev/null+++ b/src/lib/app-catalog-signal.ts@@ -0,0 +1,12 @@+// The server's word that its Apps catalog changed, passed on to whoever holds a copy. It imports nothing, so the store+// can send it without loading the catalog.+const hearers = new Set<() => void>();++export function appCatalogAnnounced(): void {+ for (const hear of hearers) hear();+}++export function onAppCatalogAnnounced(hear: () => void): () => void {+ hearers.add(hear);+ return () => hearers.delete(hear);+}diff --git a/src/lib/connected-apps-outages.test.ts b/src/lib/connected-apps-outages.test.tsindex 3641ecd16a..d45622ee4c 100644--- a/src/lib/connected-apps-outages.test.ts+++ b/src/lib/connected-apps-outages.test.ts@@ -46,4 +46,17 @@ describe("connected app refresh failures", () => {expect(connectorStatusMemory()).toEqual({ services: old, authoritative: true });expect(fixture.write).toHaveBeenCalledExactlyOnceWith(old, expect.any(Number));});++ it("asks the server to read anew only for a forced refresh", async () => {+ const { preloadConnectedApps } = await import("./connected-apps");+ fixture.api.mockResolvedValue({ services: current });+ await preloadConnectedApps();+ await preloadConnectedApps(true);+ await preloadConnectedApps(true, true);+ expect(fixture.api.mock.calls).toEqual([+ ["/api/connectors/connected", undefined],+ ["/api/connectors/connected", { headers: { "cache-control": "no-cache" } }],+ ["/api/connectors/connected", { headers: { "cache-control": "no-cache" }, background: true }],+ ]);+ });});diff --git a/src/lib/connected-apps.ts b/src/lib/connected-apps.tsindex f9f2179fa8..d26ea3abf2 100644--- a/src/lib/connected-apps.ts+++ b/src/lib/connected-apps.ts@@ -36,7 +36,7 @@ export function preloadConnectedApps(force = false, background = false): Promise}if (connectorStatusRequest) return connectorStatusRequest;type ConnectedAnswer = { services?: Record<string, ConnectorStatus>; credentialStore?: string; inventoryComplete?: boolean };- connectorStatusRequest = unlessRefused<ConnectedAnswer | null>("/api/connectors/connected", () => api("/api/connectors/connected", background ? { background: true } : undefined), null)+ connectorStatusRequest = unlessRefused<ConnectedAnswer | null>("/api/connectors/connected", () => api("/api/connectors/connected", force || background ? { ...(force ? { headers: { "cache-control": "no-cache" } } : {}), ...(background ? { background: true } : {}) } : undefined), null).then((response): ConnectorInventory => {if (!response) return REFUSED_INVENTORY;const services: Record<string, ConnectorStatus> = response.services ?? {};diff --git a/src/state/store.tsx b/src/state/store.tsxindex 038d698fc2..82b9c90d56 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -49,7 +49,7 @@ import type { Routine, RoutineInput, RoutineRun, RoutineRunStatusFilter } from "import type { WebhookAttempt, WebhookIngressStatus, WebhookTrigger } from "@/lib/webhooks";import { duplicateBotProfile, restrictedCopyRequest } from "@/lib/bot-duplicate";import { markVisibleBotThreadsRead, markVisibleGroupThreadsRead } from "./read-visible";-import { applyWindowPref } from "@/lib/window-prefs"; import { applyThemeFrame } from "@/lib/theme/runtime";+import { applyWindowPref } from "@/lib/window-prefs"; import { applyThemeFrame } from "@/lib/theme/runtime"; import { appCatalogAnnounced } from "@/lib/app-catalog-signal";import { placeUnreadDivider, threadOpensUnread, threadReadCursor, unreadDividerFor, type UnreadDivider } from "@/lib/unread-divider";import type { ComputerStart } from "@/lib/computer-start";import { parseComputerHelp } from "@/lib/computer-control";@@ -3184,7 +3184,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {break;}case "window-pref": applyWindowPref(frame); break;- case "theme": applyThemeFrame(frame); break;+ case "theme": applyThemeFrame(frame); break; case "apps-catalog": appCatalogAnnounced(); break;case "config":rawDispatch({type: "configStatus",