Skip to content

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

Suggest apps to connect, let bots search the catalog, list MCP servers under Connected

milind-soni5a4371ddc610
diff --git a/server/connector-advertisement.ts b/server/connector-advertisement.ts
index 789ac32646..9af9d19827 100644
--- a/server/connector-advertisement.ts
+++ b/server/connector-advertisement.ts
@@ -128,20 +128,29 @@ const AUTH_CONFIG_PARAMETER = {
+ "connect the one listed toolkit with. Leave it out to use their most recently created enabled config for it.",
};
-/** COMPOSIO_MANAGE_CONNECTIONS as OpenMausBot's connection cards read it: Composio's schema has no auth config id. */
-export function withAuthConfigParameter(frame: Record<string, unknown>): Record<string, unknown> {
+const FIND_PARAMETER = {
+ type: "string",
+ description: "Read by OpenMausBot, instead of toolkits: what the app is for, in plain words (\"something for spreadsheets\"). "
+ + "Searches every app that can be connected and lists their slugs. Use it when you are not sure of an app's exact slug.",
+};
+
+/** COMPOSIO_MANAGE_CONNECTIONS as OpenMausBot's connection cards read it: Composio's schema has no auth config id and no
+ * search, and a search names no toolkits. */
+export function withConnectionParameters(frame: Record<string, unknown>): Record<string, unknown> {
const result = frame.result;
if (!result || typeof result !== "object" || Array.isArray(result)) return frame;
const tools = (result as { tools?: unknown }).tools;
if (!Array.isArray(tools)) return frame;
- const withParameter = tools.map((tool) => {
+ const withParameters = tools.map((tool) => {
if (!tool || typeof tool !== "object" || Array.isArray(tool)) return tool;
const { name, inputSchema } = tool as { name?: unknown; inputSchema?: unknown };
if (typeof name !== "string" || !name.endsWith("_MANAGE_CONNECTIONS")) return tool;
if (!inputSchema || typeof inputSchema !== "object" || Array.isArray(inputSchema)) return tool;
- const properties = (inputSchema as { properties?: unknown }).properties;
+ const { properties, required } = inputSchema as { properties?: unknown; required?: unknown };
if (!properties || typeof properties !== "object" || Array.isArray(properties) || "auth_config_id" in properties) return tool;
- return { ...tool, inputSchema: { ...inputSchema, properties: { ...properties, auth_config_id: AUTH_CONFIG_PARAMETER } } };
+ const stillRequired = Array.isArray(required) ? required.filter((key) => key !== "toolkits") : undefined;
+ const { required: _required, ...rest } = inputSchema as Record<string, unknown>;
+ return { ...tool, inputSchema: { ...rest, properties: { ...properties, auth_config_id: AUTH_CONFIG_PARAMETER, find: FIND_PARAMETER }, ...(stillRequired?.length ? { required: stillRequired } : {}) } };
});
- return { ...frame, result: { ...(result as Record<string, unknown>), tools: withParameter } };
+ return { ...frame, result: { ...(result as Record<string, unknown>), tools: withParameters } };
}
diff --git a/server/connector-proxy.test.ts b/server/connector-proxy.test.ts
index e77fa40a56..58db28c131 100644
--- a/server/connector-proxy.test.ts
+++ b/server/connector-proxy.test.ts
@@ -200,12 +200,49 @@ describe("connector MCP bridge", () => {
const lines = start({ OMB_CONNECTOR_UPSTREAM_URL: upstream });
child!.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: 5, method: "tools/list", params: {} })}\n`);
const [listed, search] = (await nextJson(lines)).result.tools;
- expect(listed.inputSchema.required).toEqual(["toolkits"]);
- expect(Object.keys(listed.inputSchema.properties)).toEqual(["toolkits", "auth_config_id"]);
+ expect(listed.inputSchema.required).toBeUndefined();
+ expect(Object.keys(listed.inputSchema.properties)).toEqual(["toolkits", "auth_config_id", "find"]);
expect(listed.inputSchema.properties.auth_config_id).toMatchObject({ type: "string", description: expect.stringContaining("(ac_…)") });
+ expect(listed.inputSchema.properties.find).toMatchObject({ type: "string", description: expect.stringContaining("spreadsheets") });
expect(search).toEqual({ name: "COMPOSIO_SEARCH_TOOLS" });
});
+ it("answers a search of the catalog through the harness, and never sends it upstream", async () => {
+ const paths: string[] = [];
+ let body: any = null;
+ const harness = await listen((request, response) => {
+ let text = "";
+ request.on("data", (chunk) => { text += chunk; });
+ request.on("end", () => {
+ paths.push(request.url!);
+ body = JSON.parse(text);
+ response.writeHead(200, { "content-type": "application/json" });
+ response.end(JSON.stringify({ text: "- googlesheets: Google Sheets (not connected)." }));
+ });
+ });
+ const lines = start({ OMB_HARNESS_URL: harness, OMB_CONNECTOR_TOKEN: "token", OMB_BOT_ID: "b1", OMB_THREAD_ID: "t1" });
+ child!.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: 7, method: "tools/call", params: { name: "COMPOSIO_MANAGE_CONNECTIONS", arguments: { find: "something for spreadsheets" } } })}\n`);
+ expect((await nextJson(lines)).result.content[0].text).toContain("googlesheets");
+ expect(paths).toEqual(["/api/internal/connectors/find"]);
+ expect(body).toEqual({ botId: "b1", threadId: "t1", query: "something for spreadsheets" });
+ });
+
+ it("raises the card when a bot names toolkits, even with a search beside them", async () => {
+ const paths: string[] = [];
+ const harness = await listen((request, response) => {
+ request.resume();
+ request.on("end", () => {
+ paths.push(request.url!);
+ response.writeHead(200, { "content-type": "application/json" });
+ response.end("{}");
+ });
+ });
+ const lines = start({ OMB_HARNESS_URL: harness, OMB_CONNECTOR_TOKEN: "token", OMB_BOT_ID: "b1", OMB_THREAD_ID: "t1" });
+ child!.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: 8, method: "tools/call", params: { name: "COMPOSIO_MANAGE_CONNECTIONS", arguments: { toolkits: ["gmail"], find: "mail" } } })}\n`);
+ expect((await nextJson(lines)).result.content[0].text).toContain("secure connection card for gmail");
+ expect(paths).toEqual(["/api/internal/connectors/request"]);
+ });
+
it("answers initialize locally so a missing or failing upstream cannot fail the MCP handshake", async () => {
const lines = start({});
child!.stdin.write(`${JSON.stringify({
diff --git a/server/connector-proxy.ts b/server/connector-proxy.ts
index 103d23cbb0..e1246617c9 100644
--- a/server/connector-proxy.ts
+++ b/server/connector-proxy.ts
@@ -9,7 +9,7 @@ import {
filterToolsListFrame,
parseConnectorAllowedToolsEnv,
parseConnectorServiceSlugsEnv,
- withAuthConfigParameter,
+ withConnectionParameters,
} from "./connector-advertisement.ts";
import { APP_TOOL_NAMES_ENV, APP_TOOLS_ENV, appToolAnswer, appToolCall, appToolEntries, parseAppToolsEnv } from "./connector-app-tools.ts";
import { ARGUMENT_REFUSAL, argumentRefusalNote, fitArguments, fittedArgumentsNote } from "./connector-arguments.ts";
@@ -217,6 +217,19 @@ async function showConnectorCards(items: ConnectorRequest[]): Promise<string> {
return typeof body.authConfigNote === "string" && body.authConfigNote ? ` ${body.authConfigNote}` : "";
}
+/** The harness's answer to a bot's search of the catalog. */
+async function findApps(query: string): Promise<string> {
+ const response = await fetch(`${HARNESS}/api/internal/connectors/find`, {
+ method: "POST",
+ headers: { "content-type": "application/json", authorization: `Bearer ${TOKEN}` },
+ body: JSON.stringify({ botId: BOT_ID, threadId: THREAD_ID, query }),
+ signal: AbortSignal.timeout(30_000),
+ });
+ const body = (await response.json().catch(() => ({}))) as { error?: unknown; text?: unknown };
+ if (!response.ok || typeof body.text !== "string") throw new Error(String(body.error ?? `could not search the apps (HTTP ${response.status})`));
+ return body.text;
+}
+
/** The upstream list with the app tools after it, unless it already has one by that name. */
function withAppTools(frame: Json): Json {
const result = frame.result as { tools?: unknown } | undefined;
@@ -302,6 +315,11 @@ async function handle(received: Json): Promise<void> {
));
return;
}
+ const find = /MANAGE_CONNECTIONS$/i.test(name) ? (params.arguments as { find?: unknown } | undefined)?.find : undefined;
+ if (typeof find === "string" && find.trim()) {
+ send(textResult(id, await findApps(find)));
+ return;
+ }
if (/WAIT_FOR_CONNECTIONS$/i.test(name)) {
send(textResult(id, "OpenMausBot is handling connection completion and will continue the task automatically."));
return;
@@ -321,7 +339,7 @@ async function handle(received: Json): Promise<void> {
: await relay(message);
if (response && id !== undefined) {
const name = String((message.params as Json | undefined)?.name ?? "");
- send(method === "tools/list" ? fittedList(rememberSchemas(withAppTools(withAuthConfigParameter(ALLOWED_TOOLS ? filterToolsListFrame(response, ALLOWED_TOOLS, SERVICE_SLUGS) : response))))
+ send(method === "tools/list" ? fittedList(rememberSchemas(withAppTools(withConnectionParameters(ALLOWED_TOOLS ? filterToolsListFrame(response, ALLOWED_TOOLS, SERVICE_SLUGS) : response))))
: method === "tools/call" ? withArgumentNotes(name, withSignedOutHint(message, response, SERVICE_SLUGS), changed) : response);
}
} catch (error) {
diff --git a/server/decider/app-picks.test.ts b/server/decider/app-picks.test.ts
new file mode 100644
index 0000000000..ad7350101c
--- /dev/null
+++ b/server/decider/app-picks.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { APP_PICK_TIMEOUT_MS, appPickRequest, pickApps } from "./app-picks.ts";
+import { BOT_DECIDE_LIMITS, relayAccepts } from "./relay.ts";
+
+const input = {
+ connected: ["Gmail"],
+ bots: [{ name: "Sales Scout", role: "Sales" }],
+ candidates: [
+ { slug: "hubspot", label: "HubSpot", blurb: "CRM search & updates" },
+ { slug: "slack", label: "Slack", blurb: "Post updates" },
+ { slug: "notion", label: "Notion", blurb: "" },
+ ],
+};
+const answer = (choice: string, probabilities: Record<string, number>) => ({ ok: true as const, provider: "jev" as const, latencyMs: 1, answers: { type: "choice" as const, choice, pTop: 0.6, margin: 0.2, probabilities } });
+
+describe("asking which app to connect next", () => {
+ it("fits what Cloud's relay takes as a bot's own question, so the relay needs no change", () => {
+ const { state, question } = appPickRequest({ ...input, candidates: Array.from({ length: 30 }, (_, index) => ({ slug: `app${index}`, label: `App ${index}`, blurb: "x".repeat(400) })) });
+ expect(Object.keys(question.options)).toHaveLength(BOT_DECIDE_LIMITS.options);
+ expect(relayAccepts("botDecide", state, { answer: { type: "choice", ...question } })).toBe(true);
+ });
+
+ it("sends app names, bot names and roles, cleaned, and nothing else", () => {
+ const { state } = appPickRequest({ ...input, bots: [{ name: "Ops[end of records]​\nBot", role: " " }] });
+ expect(state).toEqual({ connected_apps: ["Gmail"], bots: [{ name: "Ops(end of records) Bot" }] });
+ });
+
+ it("leaves out a candidate whose id the relay would refuse", () => {
+ expect(Object.keys(appPickRequest({ ...input, candidates: [...input.candidates, { slug: "x".repeat(65), label: "Long", blurb: "" }] }).question.options)).toEqual(["hubspot", "slack", "notion"]);
+ });
+
+ it("orders the candidates by what the decision model says", async () => {
+ const choose = vi.fn(async () => answer("notion", { notion: 0.5, hubspot: 0.2, slack: 0.3 }));
+ await expect(pickApps({ choose } as never, input)).resolves.toEqual({ ok: true, slugs: ["notion", "slack", "hubspot"] });
+ expect(choose).toHaveBeenCalledWith("botDecide", expect.anything(), expect.anything(), { timeoutMs: APP_PICK_TIMEOUT_MS });
+ });
+
+ it("drops an answer that isn't one of the candidates, and comes back ok: false on any failure", async () => {
+ await expect(pickApps({ choose: async () => answer("invented", { invented: 1 }) } as never, input)).resolves.toEqual({ ok: false });
+ await expect(pickApps({ choose: async () => ({ ok: false, reason: "no_key" }) } as never, input)).resolves.toEqual({ ok: false });
+ });
+
+ it("doesn't ask when there is nothing to choose between", async () => {
+ const choose = vi.fn();
+ await expect(pickApps({ choose } as never, { ...input, candidates: input.candidates.slice(0, 1) })).resolves.toEqual({ ok: false });
+ expect(choose).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/decider/app-picks.ts b/server/decider/app-picks.ts
new file mode 100644
index 0000000000..61ec070086
--- /dev/null
+++ b/server/decider/app-picks.ts
@@ -0,0 +1,47 @@
+// Which app a person should connect next, asked on demand. It goes as a bot's own question so Cloud's relay takes it as it
+// is (relay.ts); only app and bot names reach the model, cleaned, and the answer can only be one of the candidates.
+import type { AppConfig } from "../config.ts";
+import { clean } from "../records-block.ts";
+import { deciderAccount, deciderEnabled, type Decider } from "./index.ts";
+import { BOT_DECIDE_LIMITS } from "./relay.ts";
+
+export const APP_PICK_INSTRUCTIONS = "Which one app should this person connect next, so their `bots` can do more for them? Go by the `connected_apps` they already use and what the bots are for.";
+export const APP_PICK_TIMEOUT_MS = 10_000;
+const MAX_CONNECTED = 40;
+const MAX_BOTS = 12;
+
+export interface AppPickInput {
+ connected: readonly string[];
+ bots: ReadonlyArray<{ name: string; role?: string }>;
+ candidates: ReadonlyArray<{ slug: string; label: string; blurb: string }>;
+}
+
+export function appPickAvailable(cfg: AppConfig): boolean {
+ return deciderEnabled(cfg) && Boolean(deciderAccount(cfg, "botDecide"));
+}
+
+export function appPickRequest(input: AppPickInput) {
+ const candidates = input.candidates.filter((app) => BOT_DECIDE_LIMITS.id.test(app.slug)).slice(0, BOT_DECIDE_LIMITS.options);
+ return {
+ state: {
+ connected_apps: input.connected.slice(0, MAX_CONNECTED).map((app) => clean(app, 80)),
+ bots: input.bots.slice(0, MAX_BOTS).map((bot) => ({ name: clean(bot.name, 80), ...(bot.role?.trim() ? { role: clean(bot.role, 120) } : {}) })),
+ },
+ question: {
+ instructions: APP_PICK_INSTRUCTIONS,
+ options: Object.fromEntries(candidates.map((app) => [app.slug, clean(app.blurb ? `${app.label}: ${app.blurb}` : app.label, 200)])),
+ },
+ };
+}
+
+/** The candidates, most useful first; `{ ok: false }` for every failure, and the caller keeps the order it had. */
+export async function pickApps(decider: Pick<Decider, "choose">, input: AppPickInput): Promise<{ ok: true; slugs: string[] } | { ok: false }> {
+ const { state, question } = appPickRequest(input);
+ const offered = Object.keys(question.options);
+ if (offered.length < 2) return { ok: false };
+ const result = await decider.choose("botDecide", state, question, { timeoutMs: APP_PICK_TIMEOUT_MS });
+ if (!result.ok || !offered.includes(result.answers.choice)) return { ok: false };
+ const { choice, probabilities } = result.answers;
+ const chance = (slug: string) => probabilities[slug] ?? 0;
+ return { ok: true, slugs: [choice, ...offered.filter((slug) => slug !== choice).sort((a, b) => chance(b) - chance(a))] };
+}
diff --git a/server/host/app-suggestions.test.ts b/server/host/app-suggestions.test.ts
new file mode 100644
index 0000000000..8267e8e5b8
--- /dev/null
+++ b/server/host/app-suggestions.test.ts
@@ -0,0 +1,223 @@
+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { requiredScope } from "../request-auth.ts";
+import { createAppFindRoute, createAppSuggestionRoutes } from "../routes/app-suggestions.ts";
+import { PASS } from "../routes/table.ts";
+import { createAppSuggestions, SUGGESTIONS_FILE, WANTED_TTL_MS } from "./app-suggestions.ts";
+
+const card = (slug: string, label = slug) => ({ slug, label, blurb: `${label} things`, logo: null, domain: null });
+const CARDS = ["gmail", "googlecalendar", "googledrive", "slack", "notion", "stripe", "linear", "github"].map((slug) => card(slug));
+
+let dataDir: string;
+let services: Record<string, { connected: boolean }>;
+let bots: Array<Record<string, unknown>>;
+let offerable: (slug: string) => boolean;
+let pickAvailable: boolean;
+let choose: ReturnType<typeof vi.fn>;
+let listener: ((change: unknown) => void) | undefined;
+let clock: number;
+
+const host = () => createAppSuggestions({
+ dataDir,
+ store: { get bots() { return bots; }, bot: (id: string) => bots.find((bot) => bot.id === id) ?? null, onChange: (next: (change: unknown) => void) => { listener = next; return () => {}; } } as never,
+ configured: () => true, catalog: async () => ({ cards: CARDS }), services: async () => services,
+ offerable: (slug) => offerable(slug), pickAvailable: () => pickAvailable, decider: { choose } as never, now: () => clock,
+});
+const slugs = (result: { cards: Array<{ slug: string }> }) => result.cards.map(({ slug }) => slug);
+const picked = (choice: string) => ({ ok: true, provider: "jev", latencyMs: 1, answers: { type: "choice", choice, pTop: 0.9, margin: 0.5, probabilities: { [choice]: 0.9 } } });
+const connectCard = (slug: string, status = "required", resumeKey = "resume-key") => listener!({ type: "message", threadId: "t", message: { connector: { slug, status, resumeKey, label: slug, description: "" } } });
+
+beforeEach(() => {
+ dataDir = mkdtempSync(join(tmpdir(), "omb-app-suggestions-"));
+ services = { gmail: { connected: true } };
+ bots = [{ id: "b1", name: "Sales", title: "Sales lead" }];
+ offerable = () => true;
+ pickAvailable = true;
+ choose = vi.fn(async () => picked("notion"));
+ listener = undefined;
+ clock = 1_000;
+});
+afterEach(() => {
+ if (dataDir.startsWith(tmpdir())) rmSync(dataDir, { recursive: true, force: true });
+});
+
+describe("the suggestions a person sees", () => {
+ it("shows the instant list without ever asking the decision model", async () => {
+ const result = await host().suggest({ limit: 3 });
+ expect(slugs(result)).toEqual(["googlecalendar", "googledrive", "slack"]);
+ expect(result.pick).toBe("available");
+ expect(choose).not.toHaveBeenCalled();
+ });
+
+ it("ranks an app a bot looked for first, and forgets it after a while", async () => {
+ const suggestions = host();
+ connectCard("stripe");
+ connectCard("gmail", "connected");
+ connectCard("notion", "required", "first-hour-offer:gmail");
+ expect(slugs(await suggestions.suggest({ limit: 2 }))).toEqual(["stripe", "googlecalendar"]);
+ clock += WANTED_TTL_MS + 1;
+ expect(slugs(await suggestions.suggest({ limit: 2 }))).toEqual(["googlecalendar", "googledrive"]);
+ });
+
+ it("keeps what bots looked for across a restart, as slugs only", async () => {
+ host();
+ connectCard("stripe");
+ expect(JSON.parse(readFileSync(join(dataDir, SUGGESTIONS_FILE), "utf8")).wanted).toEqual([{ slug: "stripe", at: 1_000 }]);
+ expect(slugs(await host().suggest({ limit: 1 }))).toEqual(["stripe"]);
+ });
+
+ it("asks the decision model only when told to, sends only names, and orders the list by its pick", async () => {
+ const suggestions = host();
+ const result = await suggestions.pick(3);
+ expect(choose).toHaveBeenCalledOnce();
+ const [seam, state, question] = choose.mock.calls[0]!;
+ expect(seam).toBe("botDecide");
+ expect(state).toEqual({ connected_apps: ["gmail"], bots: [{ name: "Sales", role: "Sales lead" }] });
+ expect(Object.keys(question.options)).toEqual(expect.arrayContaining(["googlecalendar", "notion", "stripe"]));
+ expect(result.pick).toBe("picked");
+ expect(slugs(result)[0]).toBe("notion");
+ });
+
+ it("keeps the pick until the connected apps or the bots change, and a connect card reads it without asking", async () => {
+ const suggestions = host();
+ await suggestions.pick(3);
+ await suggestions.pick(3);
+ expect(choose).toHaveBeenCalledOnce();
+ expect(slugs(await suggestions.suggest({ botId: "b1", about: "slack", limit: 3 }))[0]).toBe("notion");
+ expect(choose).toHaveBeenCalledOnce();
+
+ services = { gmail: { connected: true }, github: { connected: true } };
+ expect((await suggestions.suggest({ limit: 3 })).pick).toBe("available");
+ await suggestions.pick(3);
+ expect(choose).toHaveBeenCalledTimes(2);
+
+ bots = [{ id: "b1", name: "Support" }];
+ expect((await suggestions.suggest({ limit: 3 })).pick).toBe("available");
+ });
+
+ it("runs one call however many arrive together", async () => {
+ let finish!: (value: unknown) => void;
+ choose = vi.fn(() => new Promise((resolve) => { finish = resolve; }));
+ const suggestions = host();
+ const first = suggestions.pick(3), second = suggestions.pick(3);
+ await vi.waitFor(() => expect(choose).toHaveBeenCalledOnce());
+ finish(picked("notion"));
+ await Promise.all([first, second]);
+ expect(choose).toHaveBeenCalledOnce();
+ });
+
+ it("leaves the instant list in place, with no error, when the decision model fails", async () => {
+ choose = vi.fn(async () => ({ ok: false, reason: "timeout" }));
+ const suggestions = host();
+ const before = slugs(await suggestions.suggest({ limit: 3 }));
+ const after = await suggestions.pick(3);
+ expect(slugs(after)).toEqual(before);
+ expect(after.pick).toBe("available");
+ choose = vi.fn(async () => { throw new Error("boom"); });
+ await expect(suggestions.pick(3)).resolves.toMatchObject({ pick: "available" });
+ });
+
+ it("points to Settings without calling anyone when there is no decision model to ask", async () => {
+ pickAvailable = false;
+ const suggestions = host();
+ expect((await suggestions.suggest({ limit: 3 })).pick).toBe("needs-key");
+ await suggestions.pick(3);
+ expect(choose).not.toHaveBeenCalled();
+ });
+
+ it("never suggests an app the team or the bot isn't allowed", async () => {
+ offerable = (slug) => slug !== "googlecalendar";
+ bots = [{ id: "b1", name: "Scoped", connectorScopes: { apps: { googledrive: "read", slack: "read" } } }];
+ expect(slugs(await host().suggest({ botId: "b1", limit: 6 }))).toEqual(["googledrive", "slack"]);
+ expect(slugs(await host().suggest({ limit: 6 }))).toEqual(["googledrive", "slack"]);
+ bots.push({ id: "b2", name: "Open" });
+ expect(slugs(await host().suggest({ limit: 6 }))).not.toContain("googlecalendar");
+ expect(slugs(await host().suggest({ limit: 6 }))).toContain("notion");
+ });
+
+ it("leaves nothing to show, quietly, when the catalog or connections can't be read", async () => {
+ const suggestions = createAppSuggestions({
+ dataDir, store: { bots, bot: () => null, onChange: () => () => {} } as never, configured: () => true, catalog: async () => { throw new Error("down"); }, services: async () => services,
+ offerable: () => true, pickAvailable: () => true, decider: { choose } as never,
+ });
+ await expect(suggestions.suggest({ limit: 3 })).resolves.toEqual({ cards: [], pick: "available" });
+ });
+});
+
+describe("a bot searching the catalog", () => {
+ const bot = (extra = {}) => ({ id: "b1", name: "Sales", ...extra }) as never;
+ const cards = [{ ...card("googlesheets", "Google Sheets"), blurb: "Read and update spreadsheets" }, { ...card("excel", "Excel"), blurb: "A spreadsheet tool" }, { ...card("hiddenapp", "Hidden"), blurb: "spreadsheet" }];
+ const finder = () => createAppSuggestions({
+ dataDir, store: { bots, bot: () => null, onChange: () => () => {} } as never, configured: () => true, catalog: async () => ({ cards }), services: async () => ({ excel: { connected: true } }),
+ offerable: () => true, pickAvailable: () => true, decider: { choose } as never, now: () => clock,
+ });
+
+ it("lists what fits with slugs and connection state, and how to raise a card", async () => {
+ const text = await finder().find({ query: "something for spreadsheets", bot: bot(), refusal: () => null });
+ expect(text).toContain("- googlesheets: Google Sheets (not connected).");
+ expect(text).toContain("- excel: Excel (connected).");
+ expect(text).toContain('toolkits: ["<slug>"]');
+ });
+
+ 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 });
+ expect(JSON.parse(readFileSync(join(dataDir, SUGGESTIONS_FILE), "utf8")).wanted.map((entry: { slug: string }) => entry.slug)).toEqual(["googlesheets", "hiddenapp"]);
+ });
+
+ it("never lists an app the bot may not connect, and says so when none is left", async () => {
+ const scoped = await finder().find({ query: "spreadsheets", bot: bot({ connectorScopes: { apps: { excel: "read" } } }), refusal: () => null });
+ expect(scoped).toContain("excel");
+ expect(scoped).not.toContain("googlesheets");
+ await expect(finder().find({ query: "spreadsheets", bot: bot(), refusal: () => "Your organization does not allow this." })).resolves.toBe("Your organization does not allow this.");
+ expect(existsSync(join(dataDir, SUGGESTIONS_FILE))).toBe(false);
+ await expect(finder().find({ query: "weather", bot: bot(), refusal: () => null })).resolves.toContain('No app that can be connected here matches "weather"');
+ });
+});
+
+describe("the routes", () => {
+ const context = (method: string, path: string, query = "") => {
+ const json = vi.fn((_res: unknown, status: number, body: unknown) => ({ status, body }));
+ return { ctx: { req: {}, res: {}, url: new URL(`http://x${path}${query}`), path, method, auth: {}, json, readBody: async () => ({}) } as never, json };
+ };
+
+ it("are an admin's, like connecting an app", () => {
+ expect(requiredScope("GET", "/api/connectors/suggestions")).toBe("admin");
+ expect(requiredScope("POST", "/api/connectors/suggestions/pick")).toBe("admin");
+ });
+
+ it("passes on the card's bot and app, and bounds the limit", async () => {
+ const suggest = vi.fn(async () => ({ cards: [], pick: "available" as const }));
+ const route = createAppSuggestionRoutes({ suggest, pick: vi.fn() } as never);
+ await route(context("GET", "/api/connectors/suggestions", "?botId=b1&for=Gmail&limit=999").ctx);
+ expect(suggest).toHaveBeenCalledWith({ botId: "b1", about: "gmail", limit: 20 });
+ await expect(route(context("GET", "/api/connectors/catalog").ctx)).resolves.toBe(PASS);
+ });
+
+ it("asks for a pick only on the POST", async () => {
+ const pick = vi.fn(async () => ({ cards: [], pick: "picked" as const }));
+ const route = createAppSuggestionRoutes({ suggest: vi.fn(async () => ({ cards: [], pick: "available" as const })), pick } as never);
+ await route(context("GET", "/api/connectors/suggestions").ctx);
+ expect(pick).not.toHaveBeenCalled();
+ await route(context("POST", "/api/connectors/suggestions/pick").ctx);
+ expect(pick).toHaveBeenCalledOnce();
+ });
+
+ it("refuses a bot that can't use connected apps, and an empty search", async () => {
+ const find = vi.fn(async () => "found");
+ const route = (bot: unknown, query: unknown) => createAppFindRoute({ host: { find }, botId: "b1", bot: () => bot as never, refusal: () => null, readBody: async () => ({ query }) });
+ const a = context("POST", "/api/internal/connectors/find");
+ await route(null, "sheets")(a.ctx);
+ expect(a.json.mock.calls[0]![1]).toBe(409);
+ const b = context("POST", "/api/internal/connectors/find");
+ await route({ id: "b1" }, 7)(b.ctx);
+ expect(b.json.mock.calls[0]![1]).toBe(400);
+ const c = context("POST", "/api/internal/connectors/find");
+ await route({ id: "b1" }, " sheets ")(c.ctx);
+ expect(c.json.mock.calls[0]![2]).toEqual({ text: "found" });
+ expect(find.mock.calls[0]![0 as never]).toMatchObject({ query: "sheets" });
+ });
+});
diff --git a/server/host/app-suggestions.ts b/server/host/app-suggestions.ts
new file mode 100644
index 0000000000..eba2363e3c
--- /dev/null
+++ b/server/host/app-suggestions.ts
@@ -0,0 +1,161 @@
+// What to offer a person to connect next: apps their bots recently looked for and didn't have, the decision model's pick
+// when they asked for one, then the apps that go well with what they have. Works from the catalog and connections the
+// Apps page reads. The file holds app slugs only.
+import { createHash } from "node:crypto";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { z } from "zod";
+
+import { rankAppSuggestions, searchCatalog, type AppPickState } from "../../shared/app-suggestions.ts";
+import { FIRST_HOUR_OFFER_KEY } from "../../shared/person-wait.ts";
+import { writeFileAtomic } from "../atomic.ts";
+import type { ToolkitCard } from "../composio.ts";
+import { pickApps } from "../decider/app-picks.ts";
+import type { Decider } from "../decider/index.ts";
+import { BOT_DECIDE_LIMITS } from "../decider/relay.ts";
+import { clean } from "../records-block.ts";
+import type { BotRecord, Store } from "../store.ts";
+
+export const SUGGESTIONS_FILE = "app-suggestions.json";
+export const WANTED_TTL_MS = 30 * 24 * 60 * 60 * 1_000;
+const WANTED_MAX = 20;
+const FIND_LIMIT = 8;
+const FIND_NOTED = 2;
+
+const slug = z.string().min(1).max(100);
+const stateSchema = z.object({
+ version: z.literal(1),
+ wanted: z.array(z.object({ slug, at: z.number().finite().nonnegative() })).max(WANTED_MAX),
+ /** The decision model's order, for exactly these connected apps and bots. */
+ pick: z.object({ key: z.string().max(80), slugs: z.array(slug).max(BOT_DECIDE_LIMITS.options) }).optional(),
+});
+type SuggestionState = z.infer<typeof stateSchema>;
+
+export interface AppSuggestionDeps {
+ dataDir: string;
+ store: Pick<Store, "bots" | "bot" | "onChange">;
+ configured(): boolean;
+ catalog(): Promise<{ cards: ToolkitCard[] }>;
+ services(): 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;
+ decider: Pick<Decider, "choose">;
+ now?: () => number;
+}
+
+export interface Suggestions {
+ cards: ToolkitCard[];
+ pick: AppPickState;
+}
+
+export function createAppSuggestions(deps: AppSuggestionDeps) {
+ const now = deps.now ?? Date.now;
+ const file = join(deps.dataDir, SUGGESTIONS_FILE);
+ let state: SuggestionState = { version: 1, wanted: [] };
+ try {
+ const parsed = stateSchema.safeParse(JSON.parse(readFileSync(file, "utf8")));
+ if (parsed.success) state = parsed.data;
+ } catch {
+ // No file yet: nothing looked for, nothing picked.
+ }
+ const save = () => {
+ try {
+ writeFileAtomic(file, `${JSON.stringify(state)}\n`, { mode: 0o600 });
+ } catch (error) {
+ console.warn(`app suggestions: could not save: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ };
+
+ function noteWanted(app: string): void {
+ state = { ...state, wanted: [{ slug: app, at: now() }, ...state.wanted.filter((entry) => entry.slug !== app)].slice(0, WANTED_MAX) };
+ save();
+ }
+
+ deps.store.onChange((change) => {
+ if (change.type !== "message") return;
+ const card = change.message.connector;
+ if (card && card.source !== "mcp" && card.status !== "connected" && !card.resumeKey.startsWith(FIRST_HOUR_OFFER_KEY)) noteWanted(card.slug);
+ });
+
+ const everyoneBots = () => deps.store.bots.filter((bot) => !bot.hidden && !bot.movedTo);
+ const roles = () => everyoneBots().map((bot) => ({ name: bot.name, ...(bot.title?.trim() || bot.section?.trim() ? { role: bot.title?.trim() || bot.section!.trim() } : {}) }));
+ const wantedNow = () => state.wanted.filter((entry) => now() - entry.at <= WANTED_TTL_MS).map((entry) => entry.slug);
+ /** A bot's own limits, or with no bot in view, whether any bot could use it. */
+ const scopedTo = (botId: string | undefined) => {
+ const bot = botId ? deps.store.bot(botId) : null;
+ const bots: readonly BotRecord[] = bot ? [bot] : everyoneBots().filter((one) => one.composio !== false);
+ return (app: string) => deps.offerable(app) && (!bots.length || bots.some((one) => !one.connectorScopes || one.connectorScopes.apps[app]));
+ };
+
+ async function reading() {
+ if (!deps.configured()) return null;
+ try {
+ const [{ cards }, services] = await Promise.all([deps.catalog(), deps.services()]);
+ 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 {
+ return null;
+ }
+ }
+
+ async function suggest(input: { botId?: string; about?: string; limit: number }): Promise<Suggestions> {
+ const here = await reading();
+ if (!here) return { cards: [], pick: "available" };
+ const picked = state.pick?.key === here.key ? state.pick.slugs : undefined;
+ const cards = rankAppSuggestions({
+ catalog: here.cards, connected: here.connected, held: here.held, wanted: wantedNow(), allowed: scopedTo(input.botId), limit: input.limit,
+ ...(picked ? { picks: picked } : {}), ...(input.about ? { about: input.about } : {}),
+ });
+ return { cards, pick: picked ? "picked" : deps.pickAvailable() ? "available" : "needs-key" };
+ }
+
+ let picking: Promise<void> | null = null;
+
+ async function askDecisionModel(): Promise<void> {
+ const here = await reading();
+ if (!here || state.pick?.key === here.key || !deps.pickAvailable()) return;
+ const candidates = rankAppSuggestions({ catalog: here.cards, connected: here.connected, held: here.held, wanted: wantedNow(), allowed: scopedTo(undefined), limit: BOT_DECIDE_LIMITS.options });
+ const label = (app: string) => here.cards.find((card) => card.slug === app)?.label ?? app;
+ const picked = await pickApps(deps.decider, { connected: here.connected.map(label), bots: roles(), candidates });
+ if (!picked.ok) return;
+ state = { ...state, pick: { key: here.key, slugs: picked.slugs } };
+ save();
+ }
+
+ return {
+ suggest,
+ /** Runs the decision model at most once at a time, and not again for the same apps and bots. */
+ async pick(limit: number): Promise<Suggestions> {
+ picking ??= askDecisionModel().catch(() => {}).finally(() => { picking = null; });
+ await picking;
+ return suggest({ limit });
+ },
+
+ /** 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();
+ 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;
+ const usable = matches.filter((card) => (!scope || scope.apps[card.slug]) && !input.refusal(card.slug)).slice(0, FIND_LIMIT);
+ if (!usable.length) return (matches[0] ? input.refusal(matches[0].slug) : null) ?? `No app that can be connected here matches "${clean(input.query, 120)}". Try other words.`;
+ const connected = new Set(here.connected);
+ const missing = usable.filter((card) => !connected.has(card.slug) && !card.noAuth);
+ for (const card of missing.slice(0, FIND_NOTED).reverse()) noteWanted(card.slug);
+ const standing = (card: ToolkitCard) => (connected.has(card.slug) ? "connected" : card.noAuth ? "no sign-in needed" : "not connected");
+ return [
+ `Apps matching "${clean(input.query, 120)}":`,
+ ...usable.map((card) => `- ${card.slug}: ${clean(card.label, 80)} (${standing(card)}). ${clean(card.blurb, 120)}`),
+ 'To show the person a card that connects one, call this tool again with toolkits: ["<slug>"], using a slug listed here.',
+ ].join("\n");
+ },
+ };
+}
+
+export type AppSuggestions = ReturnType<typeof createAppSuggestions>;
+
+function pickKey(connected: readonly string[], bots: ReadonlyArray<{ name: string; role?: string }>): string {
+ const people = bots.map((bot) => [bot.name, bot.role ?? ""]).sort((a, b) => a.join().localeCompare(b.join()));
+ return createHash("sha256").update(JSON.stringify([connected, people])).digest("hex");
+}
diff --git a/server/index.test.ts b/server/index.test.ts
index 4a1e4e7c3e..7daee83036 100644
--- a/server/index.test.ts
+++ b/server/index.test.ts
@@ -12204,6 +12204,29 @@ describe("harness HTTP API", () => {
}
});
+ it("answers a bot's search of the catalog, and suggests what it looked for first, through the real routes", async () => {
+ expect((await api("PUT", "/api/config", { composio: { apiKey: "ak_good" } })).status).toBe(200);
+ const bot = (await api("POST", "/api/bots")).body.bot;
+ try {
+ const token = await mintTestCapability(BASE, bot.id, bot.threadId, { kind: "connectors" });
+ const found = await fetch(`${BASE}/api/internal/connectors/find`, {
+ method: "POST",
+ headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
+ body: JSON.stringify({ botId: bot.id, threadId: bot.threadId, query: "something for spreadsheets" }),
+ });
+ expect(found.status).toBe(200);
+ expect(((await found.json()) as { text: string }).text).toContain("- googlesheets: Google Sheets (not connected).");
+ const suggested = await api("GET", `/api/connectors/suggestions?botId=${bot.id}&for=notion&limit=3`);
+ expect(suggested.status).toBe(200);
+ expect(suggested.body.cards.map((card: { slug: string }) => card.slug)).toEqual(["googlesheets", "slack", "googledrive"]);
+ expect(suggested.body.pick).toBe("needs-key");
+ expect((await api("POST", "/api/connectors/suggestions/pick")).body.pick).toBe("needs-key");
+ } finally {
+ await api("PUT", "/api/config", { composio: { apiKey: "" } });
+ await api("DELETE", `/api/bots/${bot.id}`);
+ }
+ });
+
it("keeps connecting an app from its card an admin's, though members reach the card's authorize for MCP sign-ins", async () => {
expect((await api("PUT", "/api/config", { composio: { apiKey: "ak_good" } })).status).toBe(200);
const bot = (await api("POST", "/api/bots")).body.bot;
diff --git a/server/index.ts b/server/index.ts
index 2aee79bbd3..fe0322dfb7 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -593,7 +593,7 @@ import { createBotLifecycleRoutes } from "./routes/bot-lifecycle.ts";
import { createBotSkillsRoutes } from "./routes/bot-skills.ts";
import { createSkillShareRoutes } from "./routes/skill-share.ts";
import { createTeamContextRoutes } from "./routes/team-context.ts";
-import { createDeciderRoutes } from "./routes/decider.ts"; import { createCloudSendRoutes } from "./routes/cloud-send.ts"; import { claudeCodeSkillInputs } from "./setup-import.ts"; import { createCloudConnectionsHost } from "./cloud-connections-host.ts";
+import { createAppSuggestions } from "./host/app-suggestions.ts"; import { createAppFindRoute, createAppSuggestionRoutes } from "./routes/app-suggestions.ts"; import { appPickAvailable } from "./decider/app-picks.ts"; import { managedConnectorUnavailableReason } from "../shared/connector-availability.ts"; import { createDeciderRoutes } from "./routes/decider.ts"; import { createCloudSendRoutes } from "./routes/cloud-send.ts"; import { claudeCodeSkillInputs } from "./setup-import.ts"; import { createCloudConnectionsHost } from "./cloud-connections-host.ts";
import { createUpdateCheckRoutes, serverUpdateChecker } from "./routes/update-check.ts"; import { createTimeZoneRoutes } from "./routes/time-zone.ts";
import { createBrowserSiteRoutes } from "./routes/browser-sites.ts";
import { createInternalSignInRoutes } from "./routes/sign-in.ts";
@@ -12222,7 +12222,7 @@ 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 ? 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: CLOUD_PERSONAL })); 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({ check: serverUpdateChecker({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE) }) }), 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));
if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));
ROUTES.push(createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot }), createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (auth, threadId) => { if (ownerOrAdmin(auth) && 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), profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), 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) }));
+ 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) })); 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));
ROUTES.push(createRoomHoldRoutes({
group: (id) => store.group(id),
groupFor: personRooms.groupForAuth,
@@ -13151,7 +13151,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
return json(res, 200, { result });
}
// The turn's capability names its Boat; the Boat credential stays here.
- if (await dispatchRoutes([savedSteps.journalRoutes({ capability: internalCapability, readBody: readInternalBody })], { req, res, url, path, method, auth, json, readBody })) return; if (method === "POST" && path === "/api/internal/computer/mcp") {
+ if (await dispatchRoutes([savedSteps.journalRoutes({ capability: internalCapability, readBody: readInternalBody }), createAppFindRoute({ host: appSuggestions, botId: internalSender.id, readBody: readInternalBody, bot: (botId) => { const bot = connectorThread(botId, internalCapability.threadId)?.bot; return bot && bot.composio !== false && composio.configured(cfg) ? bot : null; }, refusal: (slug) => managedConnectorUnavailableReason(composio.connectionMode(cfg), slug) ?? managedPolicy.appRefusal(slug) ?? teamConnections.connectRefusal(internalCapability, [slug]) })], { req, res, url, path, method, auth, json, readBody })) return; if (method === "POST" && path === "/api/internal/computer/mcp") {
const body = await readInternalBody();
if (internalCapability.boxId === undefined) return json(res, 403, { error: "this turn has no cloud computer" });
const abort = new AbortController();
diff --git a/server/routes/app-suggestions.ts b/server/routes/app-suggestions.ts
new file mode 100644
index 0000000000..6438f0bd89
--- /dev/null
+++ b/server/routes/app-suggestions.ts
@@ -0,0 +1,43 @@
+// GET /api/connectors/suggestions[?botId=&for=&limit=] what to offer connecting next; never asks a model
+// POST /api/connectors/suggestions/pick the person asked: the decision model orders them, once per change
+// POST /api/internal/connectors/find { query } a bot's search of the catalog, for COMPOSIO_MANAGE_CONNECTIONS
+import { SUGGESTED_SECTION_SIZE } from "../../shared/app-suggestions.ts";
+import type { AppSuggestions } from "../host/app-suggestions.ts";
+import type { BotRecord } from "../store.ts";
+import { PASS, type RouteHandler } from "./table.ts";
+
+const MAX_LIMIT = 20;
+const MAX_QUERY = 200;
+
+export function createAppSuggestionRoutes(host: Pick<AppSuggestions, "suggest" | "pick">): RouteHandler {
+ return async ({ res, url, path, method, json }) => {
+ if (method === "GET" && path === "/api/connectors/suggestions") {
+ const limit = Number(url.searchParams.get("limit"));
+ const botId = url.searchParams.get("botId") ?? undefined, about = url.searchParams.get("for")?.trim().toLowerCase() || undefined;
+ return json(res, 200, await host.suggest({ limit: Number.isInteger(limit) && limit > 0 ? Math.min(limit, MAX_LIMIT) : SUGGESTED_SECTION_SIZE, ...(botId ? { botId } : {}), ...(about ? { about } : {}) }));
+ }
+ if (method === "POST" && path === "/api/connectors/suggestions/pick") return json(res, 200, await host.pick(SUGGESTED_SECTION_SIZE));
+ return PASS;
+ };
+}
+
+export interface AppFindDeps {
+ host: Pick<AppSuggestions, "find">;
+ /** Null when this bot can't use connected apps at all. */
+ bot(botId: string): BotRecord | null;
+ refusal(app: string): string | null | undefined;
+ readBody(): Promise<unknown>;
+ botId: string;
+}
+
+export function createAppFindRoute(deps: AppFindDeps): RouteHandler {
+ return async ({ res, path, method, json }) => {
+ if (method !== "POST" || path !== "/api/internal/connectors/find") return PASS;
+ const body = await deps.readBody() as { query?: unknown } | null;
+ const query = typeof body?.query === "string" ? body.query.trim().slice(0, MAX_QUERY) : "";
+ if (!query) return json(res, 400, { error: "find must say what the app is for." });
+ const bot = deps.bot(deps.botId);
+ if (!bot) return json(res, 409, { error: "connected apps are not enabled for this bot" });
+ return json(res, 200, { text: await deps.host.find({ query, bot, refusal: deps.refusal }) });
+ };
+}
diff --git a/shared/app-suggestions.test.ts b/shared/app-suggestions.test.ts
new file mode 100644
index 0000000000..b046f9b3fc
--- /dev/null
+++ b/shared/app-suggestions.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, it } from "vitest";
+
+import { GOES_WELL_WITH, matchesCatalogSearch, rankAppSuggestions, searchCatalog, searchWords, STARTER_APPS } from "./app-suggestions.ts";
+
+const card = (slug: string, extra: Partial<{ noAuth: boolean; label: string; blurb: string; categories: string[] }> = {}) => ({ slug, label: slug, blurb: "", ...extra });
+const catalog = [...new Set([...STARTER_APPS, ...Object.keys(GOES_WELL_WITH), ...Object.values(GOES_WELL_WITH).flat()])].map((slug) => card(slug));
+const rank = (input: Partial<Parameters<typeof rankAppSuggestions>[0]> = {}) => rankAppSuggestions({ catalog, connected: [], held: [], limit: 6, ...input }).map(({ slug }) => slug);
+
+describe("which apps to offer", () => {
+ it("offers a person with nothing connected the starter set", () => {
+ expect(rank()).toEqual(STARTER_APPS.slice(0, 6));
+ });
+
+ it("offers what goes well with what they have, never what they have", () => {
+ const offered = rank({ connected: ["gmail"], held: ["gmail"] });
+ expect(offered.slice(0, 3)).toEqual(["googlecalendar", "googledrive", "slack"]);
+ expect(offered).not.toContain("gmail");
+ expect(rank({ connected: ["github"], held: ["github"] }).slice(0, 3)).toEqual(["linear", "slack", "notion"]);
+ expect(rank({ connected: ["hubspot"], held: ["hubspot"] }).slice(0, 2)).toEqual(["gmail", "slack"]);
+ });
+
+ it("leaves out an app with any account, even one that isn't working", () => {
+ expect(rank({ connected: ["gmail"], held: ["gmail", "googlecalendar"] })).not.toContain("googlecalendar");
+ });
+
+ it("ranks what a bot looked for first, then the decision model's order, then the pairings", () => {
+ const offered = rank({ connected: ["gmail"], held: ["gmail"], wanted: ["stripe"], picks: ["zoom", "googledrive"] });
+ expect(offered.slice(0, 4)).toEqual(["stripe", "zoom", "googledrive", "googlecalendar"]);
+ });
+
+ it("keeps room for the rest however much was looked for", () => {
+ const offered = rank({ wanted: ["stripe", "zoom", "asana", "trello", "jira"], limit: 6 });
+ expect(offered.slice(0, 3)).toEqual(["stripe", "zoom", "asana"]);
+ expect(offered.slice(3)).toEqual(STARTER_APPS.filter((slug) => !["stripe", "zoom", "asana"].includes(slug)).slice(0, 3));
+ });
+
+ it("offers only catalog apps that may be connected and need a sign-in", () => {
+ const small = [card("gmail"), card("slack", { noAuth: true }), card("notion")];
+ expect(rankAppSuggestions({ catalog: small, connected: [], held: [], picks: ["invented"], limit: 6 }).map(({ slug }) => slug)).toEqual(["gmail", "notion"]);
+ expect(rankAppSuggestions({ catalog: small, connected: [], held: [], allowed: (slug) => slug !== "gmail", limit: 6 }).map(({ slug }) => slug)).toEqual(["notion"]);
+ });
+
+ it("puts a card's own app's pairings first and never offers that app", () => {
+ const offered = rank({ about: "gmail", connected: ["github"], held: ["github"] });
+ expect(offered).not.toContain("gmail");
+ expect(offered.slice(0, 3)).toEqual(["googlecalendar", "googledrive", "slack"]);
+ });
+
+ it("takes any name for the card's app without tripping on it", () => {
+ expect(rank({ about: "constructor" })).toEqual(STARTER_APPS.slice(0, 6));
+ });
+});
+
+describe("searching the catalog", () => {
+ it("reads what is being looked for out of plain words", () => {
+ expect(searchWords("something for spreadsheets")).toEqual(["spreadsheet"]);
+ expect(searchWords("The app")).toEqual(["the", "app"]);
+ });
+
+ it("matches every word, in any order, with spaces around them", () => {
+ expect(matchesCatalogSearch("Google Sheets Read and update spreadsheets", " sheets google ")).toBe(true);
+ expect(matchesCatalogSearch("Google Sheets", "sheets notion")).toBe(false);
+ expect(matchesCatalogSearch("anything", " ")).toBe(true);
+ });
+
+ it("finds apps by what they do, the closest and most used first", () => {
+ const cards = [
+ card("airtable", { label: "Airtable", blurb: "Bases and spreadsheets" }),
+ card("excel", { label: "Excel", blurb: "A spreadsheet tool" }),
+ card("spreadsheetly", { label: "Spreadsheetly", blurb: "" }),
+ card("notion", { label: "Notion", blurb: "Pages" }),
+ ];
+ expect(searchCatalog(cards, "something for spreadsheets", 8).map(({ slug }) => slug)).toEqual(["spreadsheetly", "airtable", "excel"]);
+ expect(searchCatalog(cards, "calendar", 8)).toEqual([]);
+ });
+});
diff --git a/shared/app-suggestions.ts b/shared/app-suggestions.ts
new file mode 100644
index 0000000000..3528c8cc44
--- /dev/null
+++ b/shared/app-suggestions.ts
@@ -0,0 +1,112 @@
+/** Common pairings, strongest first. A slug the catalog doesn't list is skipped. */
+export const GOES_WELL_WITH: Readonly<Record<string, readonly string[]>> = {
+ gmail: ["googlecalendar", "googledrive", "slack"],
+ googlecalendar: ["gmail", "googlemeet", "slack"],
+ googledrive: ["googledocs", "googlesheets", "gmail"],
+ googledocs: ["googledrive", "googlesheets", "notion"],
+ googlesheets: ["googledrive", "airtable", "gmail"],
+ outlook: ["one_drive", "microsoft_teams", "slack"],
+ slack: ["gmail", "notion", "linear"],
+ discord: ["github", "notion", "googlecalendar"],
+ github: ["linear", "slack", "notion"],
+ gitlab: ["linear", "slack", "jira"],
+ linear: ["github", "slack", "notion"],
+ jira: ["confluence", "github", "slack"],
+ sentry: ["github", "linear", "slack"],
+ posthog: ["github", "linear", "slack"],
+ notion: ["slack", "googledrive", "linear"],
+ airtable: ["slack", "googlesheets", "notion"],
+ asana: ["slack", "googlecalendar", "gmail"],
+ trello: ["slack", "googlecalendar", "gmail"],
+ hubspot: ["gmail", "slack", "googlecalendar"],
+ salesforce: ["gmail", "slack", "googlesheets"],
+ stripe: ["hubspot", "slack", "googlesheets"],
+ shopify: ["stripe", "mailchimp", "googlesheets"],
+ dropbox: ["gmail", "slack", "notion"],
+ figma: ["linear", "slack", "notion"],
+ zoom: ["googlecalendar", "slack", "gmail"],
+};
+
+/** What someone with nothing connected is offered, in this order. */
+export const STARTER_APPS: readonly string[] = [
+ "gmail", "googlecalendar", "slack", "notion", "googledrive", "github", "googlesheets", "linear", "hubspot", "airtable", "jira", "asana", "trello", "dropbox", "zoom", "stripe",
+];
+
+/** GET /api/connectors/suggestions: whether the Suggested section's button can ask the decision model. */
+export type AppPickState = "available" | "picked" | "needs-key";
+
+export const SUGGESTED_SECTION_SIZE = 6;
+export const SUGGESTED_CARD_SIZE = 3;
+/** Recently wanted apps lead, but never fill the list. */
+const WANTED_FIRST_MAX = 3;
+const NOISE_WORDS = new Set(["a", "an", "app", "apps", "and", "connect", "for", "i", "in", "my", "need", "of", "on", "or", "something", "that", "the", "to", "tool", "tools", "want", "with"]);
+
+export interface RankInput<Card> {
+ catalog: readonly Card[];
+ /** Apps with a working account: what the pairings go by. */
+ connected: readonly string[];
+ /** Every app with an account in any state: never offered. */
+ held: readonly string[];
+ /** Apps a bot looked for and didn't have, newest first. */
+ wanted?: readonly string[];
+ /** The decision model's order, when one was asked. */
+ picks?: readonly string[];
+ /** The app a connect card is for: its pairings lead, and it is never offered. */
+ about?: string;
+ allowed?: (slug: string) => boolean;
+ limit: number;
+}
+
+const partnersOf = (slug: string): readonly string[] => (Object.hasOwn(GOES_WELL_WITH, slug) ? GOES_WELL_WITH[slug]! : []);
+
+function pairings(connected: readonly string[]): string[] {
+ const votes = new Map<string, number>();
+ for (const app of connected) {
+ partnersOf(app).forEach((partner, position) => votes.set(partner, (votes.get(partner) ?? 0) + 3 - position));
+ }
+ return [...votes].sort((a, b) => b[1] - a[1]).map(([slug]) => slug);
+}
+
+export function rankAppSuggestions<Card extends { slug: string; noAuth?: boolean }>(input: RankInput<Card>): Card[] {
+ const bySlug = new Map(input.catalog.map((card) => [card.slug, card]));
+ const held = new Set([...input.held, ...input.connected, ...(input.about ? [input.about] : [])]);
+ const offerable = (slug: string) => {
+ const card = bySlug.get(slug);
+ return Boolean(card) && !card!.noAuth && !held.has(slug) && (input.allowed?.(slug) ?? true);
+ };
+ const ordered = [
+ ...(input.wanted ?? []).filter(offerable).slice(0, WANTED_FIRST_MAX),
+ ...(input.picks ?? []),
+ ...(input.about ? partnersOf(input.about) : []),
+ ...pairings(input.connected),
+ ...STARTER_APPS,
+ ];
+ return [...new Set(ordered.filter(offerable))].slice(0, input.limit).map((slug) => bySlug.get(slug)!);
+}
+
+/** What a search is looking for: lower case, plurals singular, filler words gone unless that leaves nothing. */
+export function searchWords(query: string): string[] {
+ const words = query.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean).map((word) => (word.length > 3 && word.endsWith("s") && !word.endsWith("ss") ? word.slice(0, -1) : word));
+ const meaningful = words.filter((word) => !NOISE_WORDS.has(word));
+ return meaningful.length ? meaningful : words;
+}
+
+/** The Apps search box: every word of `query` appears in `text`. */
+export function matchesCatalogSearch(text: string, query: string): boolean {
+ const haystack = text.toLowerCase();
+ return searchWords(query).every((word) => haystack.includes(word));
+}
+
+/** A bot's search: the apps matching any word, best first, and in catalog order (most used first) among equals. */
+export function searchCatalog<Card extends { slug: string; label: string; blurb: string; categories?: string[] }>(cards: readonly Card[], query: string, limit: number): Card[] {
+ const words = searchWords(query);
+ const score = (card: Card) => words.reduce((total, word) => {
+ const label = card.label.toLowerCase().split(/[^\p{L}\p{N}]+/u);
+ if (label.some((part) => part.startsWith(word))) return total + 4;
+ if (card.slug.includes(word)) return total + 3;
+ if (card.categories?.some((category) => category.toLowerCase().includes(word))) return total + 2;
+ return card.blurb.toLowerCase().includes(word) ? total + 1 : total;
+ }, 0);
+ return cards.map((card, index) => ({ card, index, points: score(card) })).filter(({ points }) => points > 0)
+ .sort((a, b) => b.points - a.points || a.index - b.index).slice(0, limit).map(({ card }) => card);
+}
diff --git a/src/components/ConnectorAlsoUseful.test.ts b/src/components/ConnectorAlsoUseful.test.ts
new file mode 100644
index 0000000000..d9fa50c901
--- /dev/null
+++ b/src/components/ConnectorAlsoUseful.test.ts
@@ -0,0 +1,89 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+
+import { setLocale } from "@/lib/i18n";
+
+const api = vi.hoisted(() => vi.fn());
+vi.mock("@/state/store", () => ({ api }));
+vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));
+const { ConnectorAlsoUseful } = await import("./ConnectorAlsoUseful");
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+let host: HTMLDivElement, root: Root, page: { location: { replace: ReturnType<typeof vi.fn> }; closed: boolean; close: ReturnType<typeof vi.fn>; opener: unknown };
+const app = (slug: string, label: string) => ({ slug, label, blurb: "", logo: null, domain: null });
+let cards: Array<ReturnType<typeof app>>;
+let authorize: () => unknown;
+
+const settle = () => act(async () => { for (let turn = 0; turn < 6; turn += 1) await Promise.resolve(); });
+const chip = (slug: string) => host.querySelector<HTMLButtonElement>(`[data-also-useful-app="${slug}"]`);
+async function render() {
+ await act(async () => root.render(createElement(ConnectorAlsoUseful, { botId: "atlas", slug: "gmail" })));
+ await settle();
+}
+
+beforeEach(() => {
+ setLocale("en");
+ vi.useFakeTimers();
+ cards = [app("googlecalendar", "Google Calendar"), app("slack", "Slack")];
+ authorize = () => ({ url: "https://connect.composio.dev/link/abc" });
+ api.mockReset();
+ api.mockImplementation(async (path: string) => {
+ if (path.startsWith("/api/connectors/suggestions")) return { cards, pick: "available" };
+ if (path.endsWith("/authorize")) return authorize();
+ if (path.startsWith("/api/connectors/connected")) return { services: {} };
+ return { services: { slack: { connected: true, pending: false, status: "ACTIVE" } } };
+ });
+ page = { location: { replace: vi.fn() }, closed: false, close: vi.fn(), opener: {} };
+ vi.stubGlobal("open", vi.fn(() => page));
+ host = document.createElement("div"); document.body.append(host); root = createRoot(host);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ host.remove();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+it("offers the suggested apps for this bot and this card", async () => {
+ await render();
+ expect(api.mock.calls[0]![0]).toBe("/api/connectors/suggestions?botId=atlas&for=gmail&limit=3");
+ expect(host.textContent).toContain("Also useful");
+ expect(chip("slack")?.textContent).toContain("Slack");
+ expect(chip("slack")?.getAttribute("aria-label")).toBe("Connect Slack");
+});
+
+it("shows nothing with fewer than two apps to offer, or when they can't be read", async () => {
+ cards = [app("slack", "Slack")];
+ await render();
+ expect(host.querySelector("[data-also-useful]")).toBeNull();
+ api.mockRejectedValue(Object.assign(new Error("forbidden: this session lacks the admin scope"), { status: 403 }));
+ await act(async () => root.render(createElement(ConnectorAlsoUseful, { botId: "atlas", slug: "notion" })));
+ await settle();
+ expect(host.querySelector("[data-also-useful]")).toBeNull();
+ expect(host.querySelector("[role=alert]")).toBeNull();
+});
+
+it("connects in one tap, on the sign-in page, and shows when it's done", async () => {
+ await render();
+ await act(async () => { chip("slack")!.click(); });
+ await settle();
+ expect(window.open).toHaveBeenCalledWith("", "_blank");
+ expect(api).toHaveBeenCalledWith("/api/connectors/slack/authorize", { method: "POST" });
+ expect(page.location.replace).toHaveBeenCalledWith("https://connect.composio.dev/link/abc");
+ expect(chip("slack")!.disabled).toBe(true);
+ await act(async () => { await vi.advanceTimersByTimeAsync(5_100); });
+ await settle();
+ expect(chip("slack")!.getAttribute("aria-label")).toBe("Slack · Connected");
+});
+
+it("says why when the sign-in can't start and lets the person try again", async () => {
+ authorize = () => { throw new Error("The app's sign-in couldn't start."); };
+ await render();
+ await act(async () => { chip("slack")!.click(); });
+ await settle();
+ expect(host.querySelector("[role=alert]")?.textContent).toBe("The app's sign-in couldn't start.");
+ expect(chip("slack")!.disabled).toBe(false);
+ expect(page.close).toHaveBeenCalled();
+});
diff --git a/src/components/ConnectorAlsoUseful.tsx b/src/components/ConnectorAlsoUseful.tsx
new file mode 100644
index 0000000000..0938997dfb
--- /dev/null
+++ b/src/components/ConnectorAlsoUseful.tsx
@@ -0,0 +1,90 @@
+import { useEffect, useRef, useState } from "react";
+import { Check, Loader2 } from "lucide-react";
+
+import { cardSuggestions } from "@/lib/app-suggestions";
+import { preloadConnectedApps } from "@/lib/connected-apps";
+import { reserveConnectionPage } from "@/lib/connector-oauth";
+import { pollConnector } from "@/lib/connector-poll";
+import { t } from "@/lib/i18n";
+import type { LocaleKey } from "@/locales";
+import { mcpSignInLink } from "@/lib/mcp-sign-in";
+import { connectorConnect } from "@/lib/product-events";
+import { api } from "@/state/store";
+import { ServiceIcon, type ToolkitCard } from "./ServiceIcon";
+
+const MIN_SHOWN = 2;
+
+/** A connect card's "Also useful" row: each app connects in one tap, on the same sign-in page the Apps page opens. */
+export function ConnectorAlsoUseful({ botId, slug }: { botId: string; slug: string }) {
+ const [cards, setCards] = useState<ToolkitCard[]>([]);
+ const [state, setState] = useState<Record<string, "busy" | "connected">>({});
+ const [error, setError] = useState<string | { key: LocaleKey } | null>(null);
+ const stops = useRef(new Set<() => void>());
+
+ useEffect(() => {
+ let alive = true;
+ void cardSuggestions(botId, slug).then((found) => { if (alive) setCards(found); });
+ return () => { alive = false; };
+ }, [botId, slug]);
+ useEffect(() => () => {
+ for (const stop of stops.current) stop();
+ stops.current.clear();
+ }, []);
+
+ if (cards.length < MIN_SHOWN) return null;
+
+ const connect = async (card: ToolkitCard) => {
+ if (state[card.slug]) return;
+ const launch = reserveConnectionPage();
+ setState((current) => ({ ...current, [card.slug]: "busy" }));
+ setError(null);
+ const settle = (connected: boolean) => setState((current) => {
+ const { [card.slug]: _, ...rest } = current;
+ return connected ? { ...current, [card.slug]: "connected" } : rest;
+ });
+ try {
+ const result = await api(`/api/connectors/${encodeURIComponent(card.slug)}/authorize`, { method: "POST" });
+ const url = mcpSignInLink(typeof result.url === "string" ? result.url : null);
+ if (!url) throw new Error(t("connectors.invalidAuthorizationUrl"));
+ if (!await launch.open(url)) setError({ key: "connectors.card.popupBlocked" });
+ const stop = pollConnector(undefined, () => api(`/api/connectors?services=${encodeURIComponent(card.slug)}`).then((answer) => answer.services?.[card.slug]), (end) => {
+ stops.current.delete(stop);
+ connectorConnect(card.slug, end);
+ settle(end === "connected");
+ if (end === "connected") void preloadConnectedApps(true).catch(() => {});
+ });
+ stops.current.add(stop);
+ } catch (cause) {
+ settle(false);
+ setError(cause instanceof Error ? cause.message : String(cause));
+ } finally {
+ launch.cancel();
+ }
+ };
+
+ return (
+ <div data-also-useful="" className="mt-2">
+ <div className="flex flex-wrap items-center gap-1.5">
+ <span className="me-0.5 text-[12px] text-ink-tertiary">{t("connectors.card.alsoUseful")}</span>
+ {cards.map((card) => {
+ const now = state[card.slug];
+ return (
+ <button
+ key={card.slug}
+ type="button"
+ data-also-useful-app={card.slug}
+ disabled={Boolean(now)}
+ onClick={() => void connect(card)}
+ aria-label={now === "connected" ? `${card.label} · ${t("connectors.card.connected")}` : t("hostedMcp.connect", { service: card.label })}
+ className="inline-flex h-7 items-center gap-1.5 rounded-full bg-control/70 ps-1.5 pe-2.5 text-[12px] font-medium text-ink transition-colors hover:bg-raised-hover disabled:opacity-70"
+ >
+ {now === "busy" ? <Loader2 size={14} className="animate-spin" /> : now === "connected" ? <Check size={14} className="text-success" /> : <ServiceIcon card={card} className="size-4 rounded" />}
+ {card.label}
+ </button>
+ );
+ })}
+ </div>
+ {error && <p role="alert" className="mt-1.5 text-[12px] text-danger">{typeof error === "string" ? error : t(error.key)}</p>}
+ </div>
+ );
+}
diff --git a/src/components/ConnectorCard.tsx b/src/components/ConnectorCard.tsx
index a618ae18fc..a2e930c65c 100644
--- a/src/components/ConnectorCard.tsx
+++ b/src/components/ConnectorCard.tsx
@@ -12,6 +12,7 @@ import { mcpSignInLink } from "@/lib/mcp-sign-in";
import { cn } from "@/lib/cn";
import { askPrimary, ASK_QUIET_BUTTON, AskCard, AskSettledLine } from "./AskCard";
import { CardHint } from "./CardHint";
+import { ConnectorAlsoUseful } from "./ConnectorAlsoUseful";
const STATUS_CHECK_MS = 4_000;
/** Composio marks an unfinished account EXPIRED shortly after its link lapses; the card keeps asking until it can say so. */
@@ -240,6 +241,7 @@ export function ConnectorCard({ botId, color, threadId, message }: { botId: stri
{t("connectors.openAuthorizationPage")}
</a>
)}
+ {!isMcp && <ConnectorAlsoUseful botId={botId} slug={connector.slug} />}
</AskCard>
);
}
diff --git a/src/components/McpServersPanel.hosted.test.ts b/src/components/McpServersPanel.hosted.test.ts
index 6bdf3696a2..67fc5018f2 100644
--- a/src/components/McpServersPanel.hosted.test.ts
+++ b/src/components/McpServersPanel.hosted.test.ts
@@ -36,6 +36,7 @@ let root: Root;
let servers: Listing[];
let testRequest: { resolve: (value: unknown) => void; signal?: AbortSignal } | null;
let shown: (id: string) => boolean;
+let own: { shown(server: unknown): boolean; manage(): void } | undefined;
const settle = () => act(async () => { for (let turn = 0; turn < 5; turn += 1) await Promise.resolve(); });
const card = (app: HostedApp) => host.querySelector<HTMLElement>(`[data-app-tile="${app.id}"]`)!;
@@ -49,7 +50,7 @@ async function mount() {
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
- const Cards = () => McpServersPanel({ hostedCards: { shown, onConnections: () => {} } });
+ const Cards = () => McpServersPanel({ hostedCards: { shown, onConnections: () => {}, ...(own ? { ownServers: own } : {}) } });
await act(async () => root.render(createElement(Cards)));
await settle();
}
@@ -60,6 +61,7 @@ beforeEach(() => {
testRequest = null;
servers = [];
shown = () => true;
+ own = undefined;
fixture.store = { config: null, bots: [{ id: "atlas", name: "Atlas", hidden: false }, { id: "ghost", name: "Ghost", hidden: true }] };
fixture.runMcpSignIn.mockResolvedValue({ phase: "succeeded", flowId: "00000000-0000-4000-8000-000000000000", authorizationUrl: null });
fixture.api.mockImplementation((path: string, init?: RequestInit) => {
@@ -333,3 +335,59 @@ describe("hiding a hosted card", () => {
expect(fixture.api.mock.calls.filter(([path]) => path === "/api/mcp/servers")).toHaveLength(1);
});
});
+
+describe("the person's own MCP servers in the Connected view", () => {
+ const remote = (name: string, extra: Record<string, unknown> = {}) => ({ name, type: "http" as const, url: `https://${name}.example/mcp`, headerKeys: [], enabled: true, ...extra }) as unknown as Listing;
+ const tile = (name: string) => host.querySelector<HTMLElement>(`[data-mcp-tile][data-app-tile="${name}"]`);
+
+ beforeEach(() => { own = { shown: () => true, manage: vi.fn() }; });
+
+ it("lists each switched-on server as a tile, and leaves out the ones that are off and every hosted app's", async () => {
+ servers = [remote("docs"), { ...remote("off"), enabled: false }, listing(HOSTED_MCP_APPS[0]!, { enabled: true, auth: "signed-in" }), remote("postiz")];
+ await mount();
+ expect(tile("docs")!.textContent).toContain("docs");
+ expect(tile("docs")!.querySelector('[aria-label="Connected"]')).not.toBeNull();
+ expect(tile("off")).toBeNull();
+ expect(tile(HOSTED_MCP_APPS[0]!.id)).toBeNull();
+ expect(host.querySelectorAll(`[data-app-tile="${HOSTED_MCP_APPS[0]!.id}"]`)).toHaveLength(1);
+ expect(tile("postiz")).toBeNull();
+ });
+
+ it("lists a command-line server too", async () => {
+ servers = [{ name: "local", command: "npx", args: ["pkg"], envKeys: [], enabled: true } as unknown as Listing];
+ await mount();
+ expect(tile("local")!.textContent).toContain("npx pkg");
+ });
+
+ it("lists one that needs a sign-in with its plain status and a way to sign in, but not as connected", async () => {
+ servers = [remote("docs", { auth: "needs-sign-in" })];
+ await mount();
+ expect(tile("docs")!.textContent).toContain("Needs sign-in");
+ expect(tile("docs")!.querySelector('[aria-label="Connected"]')).toBeNull();
+ await act(async () => { [...tile("docs")!.querySelectorAll("button")].find((element) => element.textContent?.trim() === "Sign in")!.click(); });
+ await settle();
+ expect(fixture.runMcpSignIn).toHaveBeenCalledOnce();
+ });
+
+ it("names the bots it is off for, and hands editing to the MCP servers view", async () => {
+ fixture.store.bots = [{ id: "atlas", name: "Atlas", hidden: false }];
+ servers = [remote("docs", { offFor: ["atlas"] })];
+ await mount();
+ expect(tile("docs")!.textContent).toContain("Atlas");
+ await act(async () => { [...tile("docs")!.querySelectorAll("button")].find((element) => element.textContent?.trim() === "Manage")!.click(); });
+ expect(own!.manage).toHaveBeenCalledOnce();
+ });
+
+ it("leaves out what a search doesn't match, and shows none outside the Connected view", async () => {
+ servers = [remote("docs"), remote("wiki")];
+ own = { shown: (server) => (server as Listing).name === "wiki", manage: vi.fn() };
+ await mount();
+ expect(tile("docs")).toBeNull();
+ expect(tile("wiki")).not.toBeNull();
+ act(() => root.unmount());
+ host.remove();
+ own = undefined;
+ await mount();
+ expect(host.querySelector("[data-mcp-tile]")).toBeNull();
+ });
+});
diff --git a/src/components/McpServersPanel.tsx b/src/components/McpServersPanel.tsx
index c2a76cf2eb..8b608abf2e 100644
--- a/src/components/McpServersPanel.tsx
+++ b/src/components/McpServersPanel.tsx
@@ -32,8 +32,7 @@ import { HostedMcpIcon } from "./HostedMcpIcon";
import type { McpMessage } from "./McpResultBudgetField";
import { McpServerEditor, type McpServerSubmission } from "./McpServerEditor";
import { isRemoteMcpListing, type McpServerListing } from "./mcp-draft";
-import { HOSTED_KEY_HEADER, HOSTED_MCP_APPS, hostedConnections, hostedMcpApp, hostedServerName, type HostedApp, type HostedConnections, type HostedMcpAppId } from "@/lib/hosted-mcp-apps";
-import { POSTIZ_SERVER } from "../../shared/postiz";
+import { HOSTED_KEY_HEADER, HOSTED_MCP_APPS, hostedConnections, hostedMcpApp, hostedServerName, mcpServerConnected, ownMcpServer, type HostedApp, type HostedConnections, type HostedMcpAppId } from "@/lib/hosted-mcp-apps";
import { CHAT_TOOL_LIMIT, chatToolBudgetFit } from "../../shared/tool-budget";
import { openBotSettings } from "./bot-panel/panel-link";
@@ -101,6 +100,10 @@ export interface HostedCardsProps {
/** Whether this app's card shows now (search, filter, category view). A hidden card stays mounted. */
shown(id: HostedMcpAppId): boolean;
onConnections(connected: HostedConnections): void;
+ /** Every server listed, for the Connected count. */
+ onServers?(servers: McpServerListing[]): void;
+ /** Set in the Connected view: which of the person's own switched-on servers show as tiles beside the apps. */
+ ownServers?: { shown(server: McpServerListing): boolean; manage(): void };
}
/** `hostedCards`: render the one-click card of each hosted MCP app (one instance, one server load, one sign-in at a time)
@@ -141,6 +144,8 @@ export function McpServersPanel({ embedded = false, hostedCards, hideHosted = fa
const connections = useMemo(() => servers && hostedConnections(servers), [servers]);
const onConnections = hostedCards?.onConnections;
useEffect(() => { if (connections) onConnections?.(connections); }, [connections, onConnections]);
+ const onServers = hostedCards?.onServers;
+ useEffect(() => { if (servers) onServers?.(servers); }, [servers, onServers]);
const listed = (next: McpServerListing[] | undefined) => {
setServers(next ?? []);
@@ -586,11 +591,44 @@ export function McpServersPanel({ embedded = false, hostedCards, hideHosted = fa
</div>;
}
+ function renderOwnServer(server: McpServerListing, manage: () => void) {
+ const needsSignIn = isRemoteMcpListing(server) && server.auth === "needs-sign-in";
+ const result = probe[server.name];
+ const failure = result && !result.ok && !result.auth ? t("mcp.check.failed", { reason: failureReason(server, result) }) : null;
+ const status = needsSignIn ? t("mcp.auth.needsSignIn") : server.offFor?.length ? t("mcp.offFor", { bots: server.offFor.map(botName).join(", ") }) : isRemoteMcpListing(server) ? server.url : [server.command, ...server.args].join(" ");
+ return <div key={server.name} data-app-tile={server.name} data-mcp-tile="" 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">
+ <div className="flex size-10 shrink-0 items-center justify-center rounded-[8px] bg-raised text-ink-secondary">{isRemoteMcpListing(server) ? <Globe size={19} /> : <ServerCog size={19} />}</div>
+ <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">{server.name}</span>
+ {mcpServerConnected(server) && <Check size={13} strokeWidth={2.5} className="shrink-0 text-success" aria-label={t("apps.connected")} />}
+ </div>
+ <p className={cn("truncate text-[13px] leading-[18px]", needsSignIn ? "text-warning" : "text-ink-secondary")} title={status}>{status}</p>
+ </div>
+ {signingIn === server.name
+ ? <button type="button" onClick={() => signInAbort.current?.abort()} className="inline-flex h-7 shrink-0 items-center rounded-full bg-control/80 px-3 text-[13px] font-medium leading-5 text-ink">{t("mcp.auth.cancel")}</button>
+ : <button type="button" disabled={needsSignIn && (busy !== null || signingIn !== null || Boolean(server.managedBy))} onClick={() => void (needsSignIn ? signIn(server) : manage())}
+ className="inline-flex h-7 min-w-[64px] shrink-0 items-center justify-center rounded-full bg-control/80 px-3 text-[13px] font-medium leading-5 text-ink hover:bg-raised-hover disabled:opacity-40">
+ {t(needsSignIn ? "mcp.auth.signIn" : "apps.mcp.manage")}
+ </button>}
+ </div>
+ <div className="ps-[52px]">
+ {failure && <p role="alert" className="mt-1.5 text-[12px] text-danger">{failure}</p>}
+ {renderSignIn(server)}
+ </div>
+ </div>;
+ }
+
if (hostedCards) {
- return <>{HOSTED_MCP_APPS.map((app) => <div key={app.id} className={hostedCards.shown(app.id) ? "contents" : "hidden"}>{renderHostedCard(app)}</div>)}</>;
+ const own = hostedCards.ownServers;
+ return <>
+ {HOSTED_MCP_APPS.map((app) => <div key={app.id} className={hostedCards.shown(app.id) ? "contents" : "hidden"}>{renderHostedCard(app)}</div>)}
+ {own && servers?.filter((server) => server.enabled && ownMcpServer(server) && own.shown(server)).map((server) => renderOwnServer(server, own.manage))}
+ </>;
}
- const visibleServers = servers?.filter((server) => !hideHosted || !isRemoteMcpListing(server) || !(hostedMcpApp(server) || server.name === POSTIZ_SERVER));
+ const visibleServers = servers?.filter((server) => !hideHosted || ownMcpServer(server));
return (
<section
diff --git a/src/components/PluginsPanel.navigation.test.ts b/src/components/PluginsPanel.navigation.test.ts
index c3566b34e4..dde3cd2074 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 { connectedInventoryCopy } from "@/lib/connector-status";
import { FACE_BOX } from "./cursor-face-data";
import { MASCOT_BODIES } from "../../shared/mascot-bodies";
@@ -571,6 +572,102 @@ describe("Apps pop-up", () => {
expect(fixture.overrides.get(20)).toBe("Productivity");
});
+ const MCP_SERVERS = 24, SUGGESTIONS = 25;
+ const headings = (html: string) => [...html.matchAll(/<h3 id="[^"]*"[^>]*>([^<]*)/g)].map((match) => match[1]);
+ const tiles = (html: string) => [...html.matchAll(/data-app-tile="([^"]*)"/g)].map((match) => match[1]).filter((slug) => !HOSTED_MCP_APPS.some((app) => app.id === slug));
+ const server = (name: string, extra: Record<string, unknown> = {}) => ({ name, type: "http", url: `https://${name}.example/mcp`, headerKeys: [], enabled: true, ...extra });
+ const suggestedAction = (tree: Node[]) => tree.find((node) => node.props.id === "apps-section-suggested")!.props.viewAll as { label: string; onClick: () => void } | undefined;
+
+ it("searches the whole catalog from the Connected view and from a category, not only what they show", () => {
+ fixture.overrides.set(TAB, "connected");
+ fixture.overrides.set(SEARCH, "notion");
+ let { html, nodes: tree } = render();
+ expect(tiles(html)).toEqual(["notion"]);
+ expect(headings(html)).toEqual(["Search results"]);
+ expect(chip(tree, "connected").props["aria-pressed"]).toBe(true);
+
+ fixture.overrides.set(TAB, "marketplace");
+ fixture.overrides.set(CATEGORY, "Design");
+ fixture.overrides.set(SEARCH, " Notion ");
+ ({ html } = render());
+ expect(tiles(html)).toEqual(["notion"]);
+ });
+
+ it("searches an app's category too, in any word order", () => {
+ fixture.overrides.set(CARDS, [{ ...card("sheets"), label: "Sheet Thing", categories: ["Spreadsheets"] }, card("gmail")]);
+ fixture.overrides.set(SEARCH, "spreadsheets thing");
+ expect(tiles(render().html)).toEqual(["sheets"]);
+ });
+
+ it("shows Suggested for you after Connected, the same tiles, with the on-demand button", () => {
+ fixture.overrides.set(SUGGESTIONS, { cards: [card("notion"), card("gmail")], pick: "available" });
+ const { html, nodes: tree } = render();
+ expect(headings(html).slice(0, 2)).toEqual(["Connected", "Suggested for you"]);
+ expect(html).toContain('data-apps-section="apps-section-suggested"');
+ expect(html.match(/data-app-tile="notion"/g)!.length).toBeGreaterThanOrEqual(2);
+ expect(suggestedAction(tree)!.label).toBe("Show suggested");
+ vi.mocked(api).mockClear();
+ suggestedAction(tree)!.onClick();
+ expect(vi.mocked(api).mock.calls).toEqual([["/api/connectors/suggestions/pick", { method: "POST" }]]);
+ });
+
+ it("drops an app from Suggested once it is connected, and leaves the section out when nothing is left", () => {
+ fixture.overrides.set(SUGGESTIONS, { cards: [card("slack")], pick: "available" });
+ expect(headings(render().html)).not.toContain("Suggested for you");
+ fixture.overrides.set(STATUS, {});
+ expect(headings(render().html)[0]).toBe("Suggested for you");
+ });
+
+ it("points to Settings for a key when no decision model is available, and hides the button after a pick", () => {
+ fixture.overrides.set(SUGGESTIONS, { cards: [card("notion")], pick: "needs-key" });
+ let { html, nodes: tree } = render();
+ expect(suggestedAction(tree)!.label).toBe("Add a Jev key in Settings");
+ suggestedAction(tree)!.onClick();
+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "togglePlugins", open: false });
+ expect(fixture.dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: "toggleAppSettings", open: true }));
+
+ fixture.overrides.set(SUGGESTIONS, { cards: [card("notion")], pick: "picked" });
+ ({ html, nodes: tree } = render());
+ expect(suggestedAction(tree)).toBeUndefined();
+ expect(html).toContain("Picked for what you&#x27;ve connected");
+ });
+
+ it("counts connected MCP servers, one rule, and never a hosted app's or one that is off or signed out", () => {
+ fixture.overrides.set(MCP_SERVERS, [
+ server("docs"),
+ server("signedin", { auth: "signed-in" }),
+ { name: "local", command: "npx", args: ["x"], envKeys: [], enabled: true },
+ server("needs", { auth: "needs-sign-in" }),
+ server("off", { enabled: false }),
+ server("hosted", { url: HOSTED_MCP_APPS[0]!.url, auth: "signed-in" }),
+ ]);
+ expect(render().html).toContain("4 connected");
+ });
+
+ it("hands the Connected view's search to the MCP tiles, and only there", () => {
+ fixture.overrides.set(MCP_SERVERS, [server("docs"), server("wiki")]);
+ const props = (tree: Node[]) => tree.find((node) => node.props.hostedCards)!.props.hostedCards as { ownServers?: { shown(one: unknown): boolean; manage(): void } };
+ expect(props(render().nodes).ownServers).toBeUndefined();
+ fixture.overrides.set(TAB, "connected");
+ fixture.overrides.set(SEARCH, "wiki");
+ const { ownServers } = props(render().nodes);
+ expect(ownServers!.shown(server("wiki"))).toBe(true);
+ expect(ownServers!.shown(server("docs"))).toBe(false);
+ ownServers!.manage();
+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "togglePlugins", open: true, surface: "mcp" });
+ });
+
+ it("doesn't call the Connected view empty while an MCP server is listed there", () => {
+ fixture.overrides.set(STATUS, {});
+ fixture.overrides.set(TAB, "connected");
+ fixture.overrides.set(21, false); fixture.overrides.set(22, false); fixture.overrides.set(23, false);
+ fixture.overrides.set(18, Object.fromEntries(HOSTED_MCP_APPS.map((app) => [app.id, false])));
+ const emptyTitle = connectedInventoryCopy("ready").title;
+ expect(render().html).toContain(emptyTitle);
+ fixture.overrides.set(MCP_SERVERS, [server("docs")]);
+ expect(render().html).not.toContain(emptyTitle);
+ });
+
it("pairs the search with an MCP servers pill and puts the connected count, with app icons, in the header", () => {
const { html, nodes: tree } = render();
expect(chip(tree, "mcp").props["aria-pressed"]).toBe(false);
diff --git a/src/components/PluginsPanel.tsx b/src/components/PluginsPanel.tsx
index ea8cb9c6e1..5ca766a693 100644
--- a/src/components/PluginsPanel.tsx
+++ b/src/components/PluginsPanel.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useRef, useState } from "react";
+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 { cn } from "@/lib/cn";
@@ -29,7 +29,10 @@ 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";
-import { HOSTED_MCP_APPS, type HostedApp, type HostedConnections } from "@/lib/hosted-mcp-apps";
+import { HOSTED_MCP_APPS, mcpServerConnected, ownMcpServer, type HostedApp, type HostedConnections } from "@/lib/hosted-mcp-apps";
+import { isRemoteMcpListing, type McpServerListing } from "./mcp-draft";
+import { useSuggestedApps } from "@/lib/app-suggestions";
+import { matchesCatalogSearch } from "../../shared/app-suggestions";
import { EmailCard } from "./EmailCard";
import { PostizCard } from "./PostizCard";
import { POSTIZ_CATALOG_CARD, POSTIZ_SEARCH } from "@/lib/postiz";
@@ -156,6 +159,7 @@ export function PluginsPanel() {
const [xConnected, setXConnected] = useState<boolean | null>(null);
const [postizConnected, setPostizConnected] = useState<boolean | null>(null);
const [emailConnected, setEmailConnected] = useState<boolean | null>(null);
+ const [mcpServers, setMcpServers] = useState<McpServerListing[]>([]);
const polls = useRef(new Map<string, () => void>());
const statusGenerations = useRef(new Map<string, number>());
@@ -314,6 +318,8 @@ export function PluginsPanel() {
};
}, [dispatch]);
+ const { suggestions, picking, pick } = useSuggestedApps(cards !== null && configured && inventoryPhase === "ready", `${cardsRefresh}:${Object.keys(status).filter((slug) => status[slug]?.connected).sort().join()}`);
+
const openConnectUrl = async (url: string) => {
if (opening.current) return;
const launch = reserveConnectionPage();
@@ -398,19 +404,24 @@ export function PluginsPanel() {
};
const matching = (cards ?? []).filter((c) => (!managedConnectorUnavailableReason(mode, c.slug) || hasActiveConnection(status[c.slug]))
- && (!search || `${c.label} ${c.slug} ${connectorDescription(c)}`.toLowerCase().includes(search.toLowerCase())));
+ && matchesCatalogSearch(`${c.label} ${c.slug} ${connectorDescription(c)} ${(c.categories ?? []).join(" ")}`, search));
const isConnected = (slug: string) => Boolean(status[slug]?.connected || status[slug]?.accounts?.length);
const filter: AppsFilter = surface === "mcp" ? "mcp" : tab === "connected" ? "connected" : "all";
- const shownHosted = new Set(HOSTED_MCP_APPS.filter((app) => hostedShown(app, search, filter, hostedConnected)).map((app) => app.id));
- const showEmail = (!search || `email mail imap smtp mailbox ${t("email.description")}`.toLowerCase().includes(search.toLowerCase().trim())) && (filter === "all" || (filter === "connected" && emailConnected !== false));
- const showX = (!search || `${X_CARD_SEARCH} ${t("apps.x.description")}`.toLowerCase().includes(search.toLowerCase().trim())) && (filter === "all" || (filter === "connected" && xConnected !== false));
- const showPostiz = (!search || `${POSTIZ_SEARCH} ${t("postiz.description")}`.toLowerCase().includes(search.toLowerCase().trim())) && (filter === "all" || (filter === "connected" && postizConnected !== false));
- const visible = (filter === "connected" ? matching.filter((card) => isConnected(card.slug)) : matching)
+ const searching = search.trim().length > 0;
+ /** A search covers the whole catalog, whichever view it was typed in. */
+ const listing: AppsFilter = searching && filter === "connected" ? "all" : filter;
+ const shownHosted = new Set(HOSTED_MCP_APPS.filter((app) => hostedShown(app, search, listing, hostedConnected)).map((app) => app.id));
+ 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)
.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);
const connectedHosted = HOSTED_MCP_APPS.filter((app) => hostedConnected?.[app.id]);
- const connectedCount = Object.values(status).filter(hasActiveConnection).length + connectedHosted.length + Number(emailConnected === true) + Number(xConnected === true) + Number(postizConnected === true);
+ const ownServers = mcpServers.filter((server) => ownMcpServer(server));
+ const ownServerShown = (server: McpServerListing) => matchesCatalogSearch(`${server.name} ${isRemoteMcpListing(server) ? server.url : [server.command, ...server.args].join(" ")}`, search);
+ const connectedCount = Object.values(status).filter(hasActiveConnection).length + connectedHosted.length + ownServers.filter(mcpServerConnected).length + Number(emailConnected === true) + Number(xConnected === true) + Number(postizConnected === true);
const connectedEmptyCopy = connectedInventoryCopy(inventoryPhase);
const close = () => dispatch({ type: "togglePlugins", open: false });
const setupNotice = connectorSetupNotice({ configured, stale, setup, remoteClient });
@@ -430,11 +441,11 @@ export function PluginsPanel() {
const ranked = rankCategories([...(cards ?? []), POSTIZ_CATALOG_CARD], undefined, POSTIZ_CATALOG_CARD.categories);
const moreCategories = ranked.more;
const categoryInMore = category !== null && moreCategories.includes(category);
- const inCategoryView = filter === "all" && category !== null;
+ 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;
+ 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 sectioned = filter === "all" && !search && category === null;
+ const sectioned = filter === "all" && !searching && category === null;
const sections = sectioned ? catalogSections(visible, isConnected, ranked.inline) : [];
const allSection = sections.find((section) => section.kind === "all");
const allCards = sectioned ? allSection?.cards ?? [] : categoryCards;
@@ -446,10 +457,10 @@ export function PluginsPanel() {
setTab("marketplace");
if (surface !== "apps") dispatch({ type: "togglePlugins", open: true, surface: "apps" });
};
- const listTitle = filter === "connected"
- ? t("connectors.section.yours")
- : search
- ? t("connectors.section.results")
+ const listTitle = searching
+ ? t("connectors.section.results")
+ : filter === "connected"
+ ? t("connectors.section.yours")
: category ? appCategoryLabel(category) : (sections.length > 1 ? t("apps.section.all") : t("connectors.section.available"));
const pill = "inline-flex h-7 shrink-0 items-center justify-center gap-2 rounded-full px-3 text-[13px] font-medium leading-5 transition-colors";
const pillTone = (selected: boolean) => selected
@@ -650,15 +661,18 @@ export function PluginsPanel() {
{filter !== "mcp" && (
<div data-apps-grid className="@container flex flex-col gap-7 pt-1">
+ {!sections.some((section) => section.kind === "connected") && renderSuggested()}
{sections.filter((section) => section.kind !== "all").map((section) => section.kind === "connected" ? (
- <AppsSection
- key="connected"
- id="apps-section-connected"
- title={t("apps.section.connected")}
- viewAll={section.cards.length > CATEGORY_SECTION_SIZE ? { label: t("apps.viewAll"), onClick: () => chooseFilter("connected") } : undefined}
- >
- {section.cards.slice(0, CATEGORY_SECTION_SIZE).map((card) => renderTile(card))}
- </AppsSection>
+ <Fragment key="connected">
+ <AppsSection
+ id="apps-section-connected"
+ title={t("apps.section.connected")}
+ viewAll={section.cards.length > CATEGORY_SECTION_SIZE ? { label: t("apps.viewAll"), onClick: () => chooseFilter("connected") } : undefined}
+ >
+ {section.cards.slice(0, CATEGORY_SECTION_SIZE).map((card) => renderTile(card))}
+ </AppsSection>
+ {renderSuggested()}
+ </Fragment>
) : (
<AppsSection
key={section.category}
@@ -705,10 +719,10 @@ export function PluginsPanel() {
{cards !== null && allShown.length === 0 && !nativeCardsShown && sections.length <= 1 && (
<div className="flex min-h-40 flex-col items-center justify-center text-center">
<div className="text-[14px] font-medium text-ink">
- {filter === "connected" ? connectedEmptyCopy.title : t("connectors.noAppsFound")}
+ {listing === "connected" ? connectedEmptyCopy.title : t("connectors.noAppsFound")}
</div>
<div className="mt-1 text-[13px] text-ink-secondary">
- {filter === "connected" ? connectedEmptyCopy.description : t("connectors.tryDifferentSearch")}
+ {listing === "connected" ? connectedEmptyCopy.description : t("connectors.tryDifferentSearch")}
</div>
{filter === "connected" && inventoryPhase === "error" && (
<button
@@ -726,7 +740,7 @@ export function PluginsPanel() {
</>
)}
>
- <McpServersPanel hostedCards={{ shown: (id) => !inCategoryView && shownHosted.has(id), onConnections: setHostedConnected }} refreshKey={cardsRefresh} />
+ <McpServersPanel hostedCards={{ shown: (id) => !inCategoryView && shownHosted.has(id), onConnections: setHostedConnected, onServers: setMcpServers, ...(filter === "connected" ? { ownServers: { shown: ownServerShown, manage: () => chooseFilter("mcp") } } : {}) }} refreshKey={cardsRefresh} />
<div data-native-card="x" className={showX && !inCategoryView ? "contents" : "hidden"}><XCard refreshKey={cardsRefresh} onConnection={setXConnected} /></div>
<div data-native-card="email" className={showEmail && !inCategoryView ? "contents" : "hidden"}><EmailCard refreshKey={cardsRefresh} onConnection={setEmailConnected} /></div>
<div data-native-card="postiz" className={postizHere ? "contents" : "hidden"}><PostizCard refreshKey={cardsRefresh} onConnection={setPostizConnected} /></div>
@@ -745,6 +759,21 @@ export function PluginsPanel() {
</div>
);
+ function renderSuggested() {
+ const shown = suggestions.cards.filter((card) => !isConnected(card.slug));
+ if (!sectioned || shown.length === 0) return null;
+ const action = suggestions.pick === "available"
+ ? { label: t(picking ? "apps.suggested.picking" : "apps.suggested.show"), onClick: pick }
+ : suggestions.pick === "needs-key" && !remoteClient
+ ? { label: t("apps.suggested.addKey"), onClick: () => { close(); dispatch(openKeySettings("jev")); } }
+ : undefined;
+ return (
+ <AppsSection id="apps-section-suggested" title={t("apps.section.suggested")} note={suggestions.pick === "picked" ? t("apps.suggested.picked") : undefined} viewAll={action}>
+ {shown.map((card) => renderTile(card))}
+ </AppsSection>
+ );
+ }
+
function renderTile(card: ToolkitCard) {
const serviceStatus = status[card.slug];
const failed = serviceStatus?.status && /^(expired|failed)$/i.test(serviceStatus.status);
diff --git a/src/lib/app-suggestions.ts b/src/lib/app-suggestions.ts
new file mode 100644
index 0000000000..0e2a8aa851
--- /dev/null
+++ b/src/lib/app-suggestions.ts
@@ -0,0 +1,47 @@
+import { useEffect, useRef, useState } from "react";
+
+import type { ToolkitCard } from "@/components/ServiceIcon";
+import { api } from "@/state/store";
+import { SUGGESTED_CARD_SIZE, type AppPickState } from "../../shared/app-suggestions";
+
+export interface AppSuggestions {
+ cards: ToolkitCard[];
+ pick: AppPickState;
+}
+
+const NONE: AppSuggestions = { cards: [], pick: "available" };
+
+const read = (answer: Partial<AppSuggestions> | null | undefined): AppSuggestions =>
+ Array.isArray(answer?.cards) ? { cards: answer.cards, pick: answer.pick ?? "available" } : NONE;
+
+/** The apps a connect card offers beside its own. Nothing, without a word, when they can't be read. */
+export async function cardSuggestions(botId: string, slug: string): Promise<ToolkitCard[]> {
+ const query = new URLSearchParams({ botId, for: slug, limit: String(SUGGESTED_CARD_SIZE) });
+ return api(`/api/connectors/suggestions?${query}`).then((answer) => read(answer).cards).catch(() => []);
+}
+
+/** The Apps page's Suggested section. `reload` changes when what is connected does. */
+export function useSuggestedApps(enabled: boolean, reload: string) {
+ const [suggestions, setSuggestions] = useState<AppSuggestions>(NONE);
+ const [picking, setPicking] = useState(false);
+ const latest = useRef(0);
+
+ useEffect(() => {
+ if (!enabled) return;
+ const request = ++latest.current;
+ void api("/api/connectors/suggestions").then((answer) => { if (request === latest.current) setSuggestions(read(answer)); }).catch(() => {});
+ }, [enabled, reload]);
+
+ /** Whatever goes wrong, the list on screen stays and nothing is said. */
+ const pick = () => {
+ if (picking) return;
+ setPicking(true);
+ const request = ++latest.current;
+ void api("/api/connectors/suggestions/pick", { method: "POST" })
+ .then((answer) => { if (request === latest.current && read(answer).cards.length) setSuggestions(read(answer)); })
+ .catch(() => {})
+ .finally(() => setPicking(false));
+ };
+
+ return { suggestions, picking, pick };
+}
diff --git a/src/lib/hosted-mcp-apps.ts b/src/lib/hosted-mcp-apps.ts
index 65b6fb638c..6ecc11ae61 100644
--- a/src/lib/hosted-mcp-apps.ts
+++ b/src/lib/hosted-mcp-apps.ts
@@ -2,6 +2,7 @@ import { CreditCard, Mail, PhoneCall, RadioTower, Smartphone, type LucideIcon }
import whopLogo from "@/assets/whop/logo.png";
import type { LocaleKey } from "@/locales";
+import { POSTIZ_SERVER } from "../../shared/postiz";
export interface HostedMcpApp {
/** The card's id (`data-app-tile`) and the name the server is added under (then `-2`, `-3`…): a valid server name. */
@@ -127,3 +128,13 @@ export function hostedConnections(
servers.some((server) => hostedMcpApp(server) === app && server.enabled && ("key" in app ? holdsKey(server) : server.auth === "signed-in")),
])) as HostedConnections;
}
+
+/** A server of the person's own: a hosted app's, and Postiz's, show as their own cards instead. */
+export function ownMcpServer(server: ServerAddress & { name: string }): boolean {
+ return server.url === undefined || !(hostedMcpApp(server) || server.name === POSTIZ_SERVER);
+}
+
+/** The one rule for "connected" for such a server: on, and signed in if it takes a sign-in. */
+export function mcpServerConnected(server: { enabled: boolean; auth?: "signed-in" | "needs-sign-in" }): boolean {
+ return server.enabled && server.auth !== "needs-sign-in";
+}
diff --git a/src/locales/en.json b/src/locales/en.json
index 1354da1a07..7d76b5b922 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -5592,6 +5592,7 @@
"computer.android.step2": "Enable Developer options by tapping {buildNumber} seven times in About phone, then turn on {usbDebugging}.",
"connectors.card.popupBlocked": "Your browser blocked the connection page. Allow pop-ups, then try again.",
"connectors.card.connected": "Connected",
+ "connectors.card.alsoUseful": "Also useful",
"connectors.card.resumed": "Connected securely. Your bot is continuing the task.",
"connectors.card.paused": "Connected securely. Continue the paused task when you're ready.",
"connectors.card.signInHint": "Sign in or enter the app key on the secure connection page, never in chat.",
@@ -6632,13 +6633,19 @@
"apps.usedBy": "Used by {names}",
"apps.showAll": "Show all {count} apps",
"apps.mcp.add": "Add MCP server",
+ "apps.mcp.manage": "Manage",
"apps.connectedCount": "{count} connected",
"apps.categoriesAria": "Categories",
"apps.more": "More",
"apps.moreCategories": "More categories",
"apps.section.connected": "Connected",
"apps.section.all": "All apps",
+ "apps.section.suggested": "Suggested for you",
"apps.viewAll": "View all",
+ "apps.suggested.show": "Show suggested",
+ "apps.suggested.picking": "Picking…",
+ "apps.suggested.picked": "Picked for what you've connected",
+ "apps.suggested.addKey": "Add a Jev key in Settings",
"apps.category.productivity": "Productivity",
"apps.category.developerTools": "Developer tools",
"apps.category.communication": "Communication",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 3cc07ce43b..ca1a9edfa9 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -5323,6 +5323,7 @@
"computer.android.step2": "Ative as opções do desenvolvedor tocando sete vezes em {buildNumber}, em Sobre o telefone, e depois ligue {usbDebugging}.",
"connectors.card.popupBlocked": "Seu navegador bloqueou a página de conexão. Permita pop-ups e tente novamente.",
"connectors.card.connected": "Conectado",
+ "connectors.card.alsoUseful": "Também úteis",
"connectors.card.resumed": "Conectado com segurança. Seu bot está continuando a tarefa.",
"connectors.card.paused": "Conectado com segurança. Continue a tarefa pausada quando quiser.",
"connectors.card.signInHint": "Entre ou informe a chave do app na página de conexão segura, nunca no chat.",
@@ -6363,13 +6364,19 @@
"apps.usedBy": "Usado por {names}",
"apps.showAll": "Mostrar todos os {count} apps",
"apps.mcp.add": "Adicionar servidor MCP",
+ "apps.mcp.manage": "Gerenciar",
"apps.connectedCount": "Conectados: {count}",
"apps.categoriesAria": "Categorias",
"apps.more": "Mais",
"apps.moreCategories": "Mais categorias",
"apps.section.connected": "Conectados",
"apps.section.all": "Todos os apps",
+ "apps.section.suggested": "Sugeridos para você",
"apps.viewAll": "Ver todos",
+ "apps.suggested.show": "Mostrar sugeridos",
+ "apps.suggested.picking": "Escolhendo…",
+ "apps.suggested.picked": "Escolhidos com base no que você conectou",
+ "apps.suggested.addKey": "Adicionar uma chave Jev em Configurações",
"apps.category.productivity": "Produtividade",
"apps.category.developerTools": "Ferramentas de desenvolvimento",
"apps.category.communication": "Comunicação",