Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Find a tool: autocomplete, three groups, inline Composio key; one-key Composio tile (#552)

Oleksandr Ivanchenko85372ca0abae
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index e2ae941a..183a47bf 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -151,6 +151,7 @@ import { useEngines } from './useEngines';
import { canInstall, setupApi } from './setupInstall';
import { claudeNeedsSignIn } from './claudeLogin';
import { personFetch } from './auth';
+import { OPEN_ADD_TOOL_EVENT, type OpenAddTool } from './mcp';
import { teamChannelOf, teamOfChannel } from './teamChannel';
import { PromptContext, suggestedPrompts } from './suggestedPrompts';
import { isNotificationOpen, placeOfNotification, showDeviceNotification } from './push';
@@ -448,6 +449,17 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const [isMcpOpen, setIsMcpOpen] = useState(false);
// Connections' "+ Add connection" opens Tools straight on adding a server.
const [mcpStartAdding, setMcpStartAdding] = useState(false);
+ // Add a tool opened from Apps & accounts' Find a tool, straight on that tool's form.
+ const [mcpStartWith, setMcpStartWith] = useState<OpenAddTool | null>(null);
+ useEffect(() => {
+ const open = (e: Event) => {
+ setMcpStartWith((e as CustomEvent<OpenAddTool>).detail ?? null);
+ setMcpStartAdding(true);
+ setIsMcpOpen(true);
+ };
+ window.addEventListener(OPEN_ADD_TOOL_EVENT, open);
+ return () => window.removeEventListener(OPEN_ADD_TOOL_EVENT, open);
+ }, []);
const [isSearchOpen, setIsSearchOpen] = useState(false);
const [editingChannelInstructions, setEditingChannelInstructions] = useState<Channel | null>(null);
const [highlightMessageId, setHighlightMessageId] = useState<string | null>(null);
@@ -4541,11 +4553,13 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
<McpServersModal
isOpen={isMcpOpen}
startAdding={mcpStartAdding}
- onClose={() => { setIsMcpOpen(false); setMcpStartAdding(false); }}
+ startWith={mcpStartWith}
+ onClose={() => { setIsMcpOpen(false); setMcpStartAdding(false); setMcpStartWith(null); }}
kwants={kwants}
onOpenConnections={() => {
setIsMcpOpen(false);
setMcpStartAdding(false);
+ setMcpStartWith(null);
openConnections();
}}
/>
diff --git a/frontend/src/appsAccounts.ts b/frontend/src/appsAccounts.ts
index d92b42f0..db68f7d4 100644
--- a/frontend/src/appsAccounts.ts
+++ b/frontend/src/appsAccounts.ts
@@ -159,6 +159,23 @@ export async function giveServerTo(serverId: string, kwantIds: string[], chosen:
});
}
+/** Turns a tool server on or off, as Tools' switch does (the masks go back, so stored secrets stay). */
+export async function setServerEnabled(serverId: string, enabled: boolean, f: Fetch = (u, i) => personFetch(u, i)): Promise<void> {
+ const url = `/api/mcp/servers/${encodeURIComponent(serverId)}`;
+ const server = await json<McpServer>(f, url);
+ if (server.enabled === enabled) return;
+ await json(f, url, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ ...formToPayload(serverToForm(server)), enabled }),
+ });
+}
+
+/** Removes a tool server (Composio's included): every bot loses it. */
+export async function removeServer(serverId: string, f: Fetch = (u, i) => personFetch(u, i)): Promise<void> {
+ await json(f, `/api/mcp/servers/${encodeURIComponent(serverId)}`, { method: 'DELETE' });
+}
+
/** What the page's header says: things that need the person, and what's connected. */
export function pageCounts(connections: Connection[]): string {
const apps = connections.filter((c) => c.kind === 'mcp' && c.status === 'connected').length;
diff --git a/frontend/src/components/AppsAccounts.tsx b/frontend/src/components/AppsAccounts.tsx
index 8776db56..ef8a4ace 100644
--- a/frontend/src/components/AppsAccounts.tsx
+++ b/frontend/src/components/AppsAccounts.tsx
@@ -1,12 +1,12 @@
-// Settings › This space › Apps & accounts (0.9.5): app tiles first, then Composio search, the AI
+// Settings › This space › Apps & accounts (0.9.5): app tiles first, then Find a tool, the AI
// accounts the bots think with, and a closed Advanced (tool servers, Telegram, notes from bots).
// Connecting an app is one sheet with three steps; the bots picked in step 3 get it, turned on.
import React, { useCallback, useEffect, useId, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
-import { AlertTriangle, Check, ChevronRight, ExternalLink, Info, Loader2, RefreshCw, X } from 'lucide-react';
+import { AlertTriangle, Check, ChevronRight, ExternalLink, Eye, EyeOff, Info, Loader2, RefreshCw, X } from 'lucide-react';
import { PERSON_SIGNED_IN_EVENT, requestPersonToken } from '../auth';
-import { CatalogEntry, ComposioApp, Connection, ConnectionsError, ConnectionsList, composioBody, composioErrorText, connectionsApi } from '../connections';
+import { CatalogEntry, Connection, ConnectionsError, ConnectionsList, composioErrorText, connectionsApi } from '../connections';
import {
APP_TILES,
AppTile,
@@ -29,13 +29,16 @@ import { parsePick, type EngineInfo } from '../engines';
import { AccountPriority } from './AccountPriority';
import { Profile, cardOf } from '../profiles';
import type { Kwant } from './Sidebar';
-import { ComposioAppSearch } from './ConnectionsView';
+import { FindTool, FindToolApi } from './FindTool';
+import { OPEN_ADD_TOOL_EVENT, OpenAddTool } from '../mcp';
import { usePhoneLayout } from '../usePhoneLayout';
import { ModernAvatar } from './ModernAvatar';
/** The tile mark: plain initials on the overlay colour, never a brand logo. */
const TILE_BG = '#231d4b';
-export const COMPOSIO_HOME = 'https://platform.composio.dev';
+/** Where a Composio key is made, when the server doesn't say (#548 sends key_url). */
+export const COMPOSIO_HOME = 'https://dashboard.composio.dev';
+const keyUrlOf = (e: CatalogEntry | undefined) => (e?.key_url && /^https:\/\//.test(e.key_url) ? e.key_url : COMPOSIO_HOME);
const btn =
'inline-flex items-center justify-center gap-1.5 min-h-[44px] sm:min-h-[32px] px-3 py-1 rounded-lg text-xs font-medium transition-colors disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500';
@@ -63,7 +66,7 @@ export const AppMark: React.FC<{ name: string; size?: number; tint?: string }> =
// ── The Connect sheet ────────────────────────────────────────────────────────────────────────
export interface ConnectApi {
- addComposio: (body: { url: string; api_key?: string; enabled: boolean }) => Promise<{ connection_id: string }>;
+ addComposio: (body: { url?: string; api_key?: string; enabled: boolean }) => Promise<{ connection_id: string }>;
connect: (slug: string) => Promise<{ redirect_url: string }>;
give: (serverId: string, kwantIds: string[], chosen: string[]) => Promise<void>;
botsWith: (serverId: string, kwantIds: string[]) => Promise<string[]>;
@@ -90,7 +93,7 @@ export interface ConnectSheetProps {
api?: ConnectApi;
phone?: boolean;
/** Tests and screenshots: start with these filled in. */
- initial?: { url?: string; picked?: string[]; opened?: boolean; error?: string };
+ initial?: { key?: string; picked?: string[]; opened?: boolean; error?: string };
}
/** One numbered step of the sheet. Outside the sheet, so typing in a step keeps its focus.
@@ -144,13 +147,13 @@ export const ConnectSheet: React.FC<ConnectSheetProps> = ({ app, composio, kwant
// Composio set up already (or just now, if giving it to bots failed after): skip to the app.
const [serverId, setServerId] = useState<string | null>(composio.added ? serverIdOf(composio.connection_id) : null);
const ready = composio.added;
- const [opened, setOpened] = useState(!!initial.opened);
- const [url, setUrl] = useState(initial.url ?? '');
- const [key, setKey] = useState('');
+ const [key, setKey] = useState(initial.key ?? '');
+ const [addingKey, setAddingKey] = useState(false);
const [showKey, setShowKey] = useState(false);
const [picked, setPicked] = useState<string[]>(initial.picked ?? []);
const [pickedLoaded, setPickedLoaded] = useState(!ready || !!initial.picked);
- const [error, setError] = useState<{ step: 1 | 2 | 3; text: string } | null>(initial.error ? { step: 2, text: initial.error } : null);
+ const [error, setError] = useState<{ step: 1 | 2 | 3; text: string } | null>(initial.error ? { step: 1, text: initial.error } : null);
+ const keyUrl = keyUrlOf(composio);
const [saving, setSaving] = useState(false);
const [signingIn, setSigningIn] = useState(false);
const [signInOpened, setSignInOpened] = useState(false);
@@ -168,7 +171,9 @@ export const ConnectSheet: React.FC<ConnectSheetProps> = ({ app, composio, kwant
};
}, [ready, serverId]); // eslint-disable-line react-hooks/exhaustive-deps
- const title = app ? `Connect ${app.name}` : ready ? 'Choose bots for Composio' : 'Set up Composio';
+ const title = app ? `Connect ${app.name}` : ready ? 'Choose bots for Composio' : 'Add Composio';
+ // The sign-in step: before setup it waits for the key (step 2); once Composio is added it's step 1.
+ const signInStep: 1 | 2 = ready ? 1 : 2;
const chosenBots = kwants.filter((k) => picked.includes(k.id));
const approval = approvalLine(app?.acts ?? 'Send, post or change things', chosenBots, spaceMode);
const toggle = (kid: string) => (setPicked((p) => (p.includes(kid) ? p.filter((x) => x !== kid) : [...p, kid])), setError((x) => (x?.step === 3 ? null : x)));
@@ -190,9 +195,9 @@ export const ConnectSheet: React.FC<ConnectSheetProps> = ({ app, composio, kwant
// 409: Composio refused the saved key. Anything else (502, no answer) is Composio being down or slow.
const keyRefused = (e as { status?: number } | null)?.status === 409;
setError({
- step: 1,
+ step: signInStep,
text: keyRefused
- ? `Composio refused your API key, so the ${app.name} sign-in can’t start here. Fix the key under Advanced › Manage tools, or sign in to ${app.name} on composio.dev.`
+ ? `Composio didn’t accept your saved key, so the ${app.name} sign-in can’t start. Replace the key on the Composio tile under Advanced.`
: `Composio couldn’t be reached, so the ${app.name} sign-in didn’t open. Try again in a minute.`,
});
} finally {
@@ -200,28 +205,43 @@ export const ConnectSheet: React.FC<ConnectSheetProps> = ({ app, composio, kwant
}
};
+ /** Step 1 before setup: saves the key (off, for nobody yet); the server checks it with Composio. */
+ const addKey = async (): Promise<string | null> => {
+ if (serverId) return serverId;
+ if (!key.trim()) {
+ setError({ step: 1, text: 'Paste your Composio API key first.' });
+ return null;
+ }
+ setAddingKey(true);
+ setError(null);
+ try {
+ const r = await api.addComposio({ api_key: key.trim(), enabled: false });
+ const sid = serverIdOf(r.connection_id);
+ if (!sid) {
+ setError({ step: 1, text: 'Composio was added, but kwant bots didn’t say which server it is. Open Advanced to finish there.' });
+ return null;
+ }
+ setServerId(sid);
+ return sid;
+ } catch (err) {
+ setError({ step: 1, text: composioErrorText(err) });
+ return null;
+ } finally {
+ setAddingKey(false);
+ }
+ };
+
const submit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
let sid = serverId;
- if (!sid) {
- const body = composioBody(url, key, false);
- if ('error' in body) return setError({ step: 2, text: body.error });
- }
+ if (!sid && !key.trim()) return setError({ step: 1, text: 'Paste your Composio API key first.' });
if (picked.length === 0 && !ready) return setError({ step: 3, text: 'Tick at least one bot. Only the bots you tick can use it.' });
setSaving(true);
try {
if (!sid) {
- const body = composioBody(url, key, false) as { url: string; api_key?: string; enabled: boolean };
- try {
- const r = await api.addComposio(body);
- sid = serverIdOf(r.connection_id);
- setServerId(sid);
- } catch (err) {
- setError({ step: 2, text: composioErrorText(err) });
- return;
- }
- if (!sid) return setError({ step: 2, text: 'Composio was added, but kwant bots didn’t say which server it is. Open Advanced to finish there.' });
+ sid = await addKey();
+ if (!sid) return;
}
try {
await api.give(sid, kwants.map((k) => k.id), picked);
@@ -237,7 +257,7 @@ export const ConnectSheet: React.FC<ConnectSheetProps> = ({ app, composio, kwant
};
const stepDone = (n: 1 | 2 | 3) =>
- n === 3 ? picked.length > 0 : n === 1 ? (ready ? signInOpened : opened) : ready || !!serverId || !('error' in composioBody(url, key, false));
+ n === 3 ? picked.length > 0 : n === signInStep ? signInOpened : !!serverId;
const stepProps = (n: 1 | 2 | 3) => ({ n, done: stepDone(n), error: error?.step === n ? error.text : null });
const panel = isPhone
@@ -255,7 +275,7 @@ export const ConnectSheet: React.FC<ConnectSheetProps> = ({ app, composio, kwant
<h2 id={`${id}-t`} className="text-sm font-semibold text-zinc-100">
{title}
</h2>
- <p className="text-[11px] text-zinc-400">{!ready ? 'Takes about 2 minutes' : app ? 'Composio is set up, so this takes a minute' : 'Picked bots can use every app on your Composio'}</p>
+ <p className="text-[11px] text-zinc-400">{!ready ? 'Takes about a minute' : app ? 'Composio is set up, so this takes a minute' : 'Picked bots can use every app on your Composio'}</p>
</div>
<button type="button" onClick={onClose} aria-label="Close" className="inline-flex items-center justify-center w-11 h-11 sm:w-8 sm:h-8 -mr-2 sm:-mr-1 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500">
<X size={17} />
@@ -284,86 +304,92 @@ export const ConnectSheet: React.FC<ConnectSheetProps> = ({ app, composio, kwant
</div>
<ol className="space-y-4" aria-label="Steps">
- {ready ? (
- app && (
- <Step {...stepProps(1)} title={`Sign in to ${app.name}`}>
- {composio.can_connect ? (
+ {!ready && (
+ <Step {...stepProps(1)} errorInChildren title="Add your free Composio key">
+ <p className="text-[11px] text-zinc-400">Composio is a service with a free plan that signs your bots in to apps. Add your key once and your bots can use any app you connect.</p>
+ <div className="flex items-center justify-between gap-2">
+ <label htmlFor={`${id}-key`} className="text-[11px] font-medium text-zinc-300">
+ Composio API key
+ </label>
+ <a href={keyUrl} target="_blank" rel="noopener noreferrer" className={linkBtn} data-sheet-key-link>
+ Get a free key <ExternalLink size={12} aria-hidden="true" />
+ <span className="sr-only">(opens in a new tab)</span>
+ </a>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <div className="relative flex-1 min-w-[12rem]">
+ <input
+ id={`${id}-key`}
+ className={`${field} pr-11`}
+ type={showKey ? 'text' : 'password'}
+ autoComplete="off"
+ spellCheck={false}
+ placeholder="Paste your key"
+ value={key}
+ readOnly={!!serverId || addingKey}
+ onChange={(e) => (setKey(e.target.value), setError((x) => (x?.step === 1 ? null : x)))}
+ aria-describedby={error?.step === 1 ? `${id}-key-e ${id}-key-h` : `${id}-key-h`}
+ aria-invalid={error?.step === 1 ? true : undefined}
+ />
+ <button
+ type="button"
+ onClick={() => setShowKey((v) => !v)}
+ aria-label={showKey ? 'Hide key' : 'Show key'}
+ aria-pressed={showKey}
+ className="absolute right-0 top-0 h-full w-11 inline-flex items-center justify-center text-zinc-400 hover:text-zinc-200 rounded-r-lg focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ >
+ {showKey ? <EyeOff size={15} aria-hidden="true" /> : <Eye size={15} aria-hidden="true" />}
+ </button>
+ </div>
+ {serverId ? (
+ <span className="inline-flex items-center gap-1 text-xs text-emerald-300" data-sheet-key-added>
+ <Check size={13} aria-hidden="true" /> Key added
+ </span>
+ ) : (
+ <button type="button" className={quietBtn} onClick={() => void addKey()} disabled={addingKey || !key.trim()} data-sheet-add-key>
+ {addingKey && <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
+ {addingKey ? 'Checking your key…' : 'Add key'}
+ </button>
+ )}
+ </div>
+ {error?.step === 1 && (
+ <p id={`${id}-key-e`} role="alert" className="px-3 py-2 rounded-lg border border-rose-500/30 bg-rose-500/10 text-xs text-rose-200" data-sheet-error={1}>
+ {error.text}{' '}
+ <a href={keyUrl} target="_blank" rel="noopener noreferrer" className="text-sky-300 hover:underline">
+ Open your API keys ↗
+ </a>
+ </p>
+ )}
+ <p id={`${id}-key-h`} className="text-[11px] text-zinc-400">
+ Free plan: 10,000 tool calls a month. Kept on this computer and never shown again.
+ </p>
+ </Step>
+ )}
+ {app && (
+ <Step {...stepProps(signInStep)} title={`Sign in to ${app.name}`}>
+ {composio.can_connect || (!ready && serverId) ? (
<>
<p className="text-[11px] text-zinc-400">Opens {app.name}’s own sign-in on Composio {inDesktopApp() ? 'in your browser' : 'in a new tab'}. Come back here when it says you’re connected.</p>
- <button type="button" className={quietBtn} onClick={signIn} disabled={signingIn} data-sheet-signin>
+ <button type="button" className={quietBtn} onClick={signIn} disabled={signingIn || (!ready && !serverId)} data-sheet-signin>
{signingIn ? <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <ExternalLink size={12} aria-hidden="true" />}
{signInOpened ? `Open ${app.name} sign-in again` : `Sign in to ${app.name}`}
</button>
{signInOpened && <p className="text-[11px] text-emerald-200">Opened. Finish there, then choose the bots below.</p>}
</>
+ ) : !ready ? (
+ <p className="text-[11px] text-zinc-400">Add your key first, then sign in to {app.name} here.</p>
) : (
<p className="text-[11px] text-zinc-400">
- On{' '}
- <a href={COMPOSIO_HOME} target="_blank" rel="noopener noreferrer" className="text-sky-300 hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 rounded">
- composio.dev ↗
+ Sign in to {app.name} on{' '}
+ <a href={keyUrl} target="_blank" rel="noopener noreferrer" className="text-sky-300 hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 rounded">
+ your Composio dashboard ↗
</a>
- , add {app.name} to the same MCP server you gave kwant bots and sign in there.{' '}
- {composio.can_search
- ? 'kwant bots can’t open this sign-in for you with your Composio link, so sign in there.'
- : 'To sign in from here instead, add your Composio API key under Advanced › Manage tools.'}
+ . To sign in from here instead, add your Composio API key on the Composio tile under Advanced.
</p>
)}
- </Step>
- )
- ) : (
- <>
- <Step {...stepProps(1)} title="Make a free Composio account">
- <p className="text-[11px] text-zinc-400">
- Sign up, then {app ? `add ${app.name} and sign in to it there` : 'add the apps you want and sign in to them there'}. Composio keeps that sign-in for your bots.
- </p>
- <a href={COMPOSIO_HOME} target="_blank" rel="noopener noreferrer" className={quietBtn} onClick={() => setOpened(true)} data-sheet-open-composio>
- Open Composio <ExternalLink size={12} aria-hidden="true" />
- <span className="sr-only">(opens in a new tab)</span>
- </a>
- </Step>
- <Step {...stepProps(2)} errorInChildren title="Paste your Composio link">
- <label htmlFor={`${id}-url`} className="sr-only">
- Composio MCP link
- </label>
- <input
- id={`${id}-url`}
- className={field}
- type="url"
- inputMode="url"
- autoComplete="off"
- spellCheck={false}
- placeholder="https://backend.composio.dev/v3/mcp/…"
- value={url}
- onChange={(e) => (setUrl(e.target.value), setError((x) => (x?.step === 2 ? null : x)))}
- aria-describedby={error?.step === 2 ? `${id}-url-e ${id}-url-h` : `${id}-url-h`}
- aria-invalid={error?.step === 2 ? true : undefined}
- disabled={!!serverId}
- />
- {error?.step === 2 && (
- <p id={`${id}-url-e`} role="alert" className="px-3 py-2 rounded-lg border border-rose-500/30 bg-rose-500/10 text-xs text-rose-200" data-sheet-error={2}>
- {error.text}
- </p>
- )}
- <p id={`${id}-url-h`} className="text-[11px] text-zinc-400">
- In Composio, open <span className="text-zinc-200">MCP</span> in the left menu, pick your server (or create one with {app ? app.name : 'your apps'}), and copy its URL. It starts with https:// and is on composio.dev.
- </p>
- {showKey ? (
- <div className="space-y-1">
- <label htmlFor={`${id}-key`} className="block text-[11px] font-medium text-zinc-300">
- Composio API key <span className="font-normal text-zinc-500">(optional)</span>
- </label>
- <input id={`${id}-key`} className={field} type="password" autoComplete="off" value={key} onChange={(e) => setKey(e.target.value)} />
- <p className="text-[11px] text-zinc-500">Lets you find and sign in to apps from kwant bots. Kept on this computer and never shown again.</p>
- </div>
- ) : (
- <button type="button" className={linkBtn} onClick={() => setShowKey(true)}>
- Add your API key too (optional)
- </button>
- )}
- </Step>
- </>
+ </Step>
)}
- <Step {...stepProps(3)} label={ready ? (app ? 2 : null) : 3} title="Which bots get it?">
+ <Step {...stepProps(3)} label={ready ? (app ? 2 : null) : app ? 3 : 2} title="Which bots get it?">
{!pickedLoaded ? (
<p className="flex items-center gap-2 text-[11px] text-zinc-400">
<Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Checking which bots have it…
@@ -451,6 +477,10 @@ export interface AppsAccountsProps {
appStatus?: (slug: string) => Promise<{ connected: boolean }>;
initialSheet?: { slug: string | null; initial?: ConnectSheetProps['initial'] };
phone?: boolean;
+ /** Tests and shots: Find a tool's data and text already typed, and where Add a tool goes. */
+ findApi?: FindToolApi;
+ initialFindQuery?: string;
+ onAddTool?: (detail: OpenAddTool) => void;
}
// An older server (or an empty reply) may leave out a list; treat it as empty rather than crash.
@@ -588,9 +618,12 @@ export const AppsAccounts: React.FC<AppsAccountsProps> = (p) => {
setSheet({ app });
};
- const searchApi = {
- search: connectionsApi.searchComposioApps,
- connect: connectionsApi.connectComposioApp,
+ /** Add a tool, opened on a built-in tool's form, a directory listing's form or Add by address. */
+ const openAddTool = (detail: OpenAddTool) => (p.onAddTool ?? ((d: OpenAddTool) => window.dispatchEvent(new CustomEvent(OPEN_ADD_TOOL_EVENT, { detail: d }))))(detail);
+ /** A tool server's bots: its card under Advanced says who has it. */
+ const openServerBots = () => {
+ setAdvancedOpen(true);
+ window.setTimeout(() => advancedRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' }), 50);
};
return (
@@ -672,27 +705,25 @@ export const AppsAccounts: React.FC<AppsAccountsProps> = (p) => {
{data && !composio && <p className="text-[11px] text-zinc-400">This server can’t connect apps yet. Update kwant bots to connect them here.</p>}
</section>
- {/* Find any other app */}
- {composio && (
+ {/* Find a tool: built in, through Composio, and the public directory */}
+ {data && (
<section aria-labelledby="apps-find" className="space-y-2" data-apps-search>
<h3 id="apps-find" className={sectionTitle}>
- Another app
+ Find a tool
</h3>
- {composio.added ? (
- <ComposioAppSearch
- entry={composio}
- api={searchApi}
- onPick={(a: ComposioApp) => openApp(tileFor(a))}
- />
- ) : (
- <p className="text-[11px] text-zinc-400">
- Composio has hundreds more, like Figma, Linear or HubSpot.{' '}
- <button type="button" className={linkBtn} onClick={() => openApp(null)} data-apps-setup-composio>
- Set up Composio
- </button>{' '}
- and you can search them here.
- </p>
- )}
+ <FindTool
+ browseWhenEmpty={false}
+ data={data}
+ api={p.findApi}
+ phone={p.phone}
+ initialQuery={p.initialFindQuery}
+ onChanged={() => reload()}
+ onAddPreset={(preset) => openAddTool({ preset: preset.id })}
+ onAddDirectory={(entry) => openAddTool({ directory: entry })}
+ onAddByAddress={() => openAddTool({ address: true })}
+ onChooseBots={(t) => (t.kind === 'composio' ? openApp(tileFor({ slug: t.slug, name: t.name })) : openServerBots())}
+ onComposioElsewhere={(slug, name) => openApp(tileFor({ slug, name }))}
+ />
</section>
)}
diff --git a/frontend/src/components/ComposioTile.tsx b/frontend/src/components/ComposioTile.tsx
new file mode 100644
index 00000000..1e9490d7
--- /dev/null
+++ b/frontend/src/components/ComposioTile.tsx
@@ -0,0 +1,483 @@
+// The Composio tile (composio-simple/design.md §3): status and actions only; Find a tool does the
+// searching. One key field adds it, Replace key and Switch fix it in place, and Remove asks inline.
+// Every error sits next to the control that fixes it. The main path never says MCP, header or URL;
+// only "Use a Composio link instead (advanced)" does.
+
+import React, { useEffect, useId, useRef, useState } from 'react';
+import { ChevronDown, Info, KeyRound, Loader2, Lock, Plus } from 'lucide-react';
+import { CatalogEntry, ConnectionsError, connectionsApi } from '../connections';
+import { listNames, removeServer, serverIdOf, setServerEnabled } from '../appsAccounts';
+import { editorProps } from '../escape';
+import { KeyField, KeyPhase } from './FindTool';
+
+export interface ComposioTileApi {
+ addKey: (key: string) => Promise<unknown>;
+ replaceKey: (key: string) => Promise<unknown>;
+ switchTo: (key?: string) => Promise<unknown>;
+ setEnabled: (serverId: string, enabled: boolean) => Promise<void>;
+ remove: (serverId: string) => Promise<void>;
+}
+
+export const defaultComposioTileApi: ComposioTileApi = {
+ addKey: (k) => connectionsApi.addComposioKey(k),
+ replaceKey: (k) => connectionsApi.replaceComposioKey(k),
+ switchTo: (k) => connectionsApi.switchComposio(k),
+ setEnabled: (id, on) => setServerEnabled(id, on),
+ remove: (id) => removeServer(id),
+};
+
+type Open = 'none' | 'add' | 'replace' | 'remove' | 'switchKey';
+
+export interface ComposioTileProps {
+ entry: CatalogEntry;
+ /** Names of the bots that have Composio. */
+ usedBy: string[];
+ /** Apps & accounts: picking bots turns it on (the Connect sheet). */
+ onChooseBots?: () => void;
+ /** The old Connections page: on and off live in Tools. */
+ onOpenTools?: () => void;
+ /** The old link form ("Use a Composio link instead"): an error to show, or null. */
+ onAddLink: (url: string, apiKey: string, enabled: boolean) => Promise<string | null>;
+ /** Load the page again after a change. */
+ onChanged?: () => void;
+ api?: ComposioTileApi;
+ phone?: boolean;
+ /** Tests and shots: start with this open. */
+ initialOpen?: Open;
+ /** Goes up by one each time the page asks for Composio: scroll here (and open the key field if not added). */
+ openRequest?: number;
+}
+
+const KEY_DEFAULT = 'https://dashboard.composio.dev';
+
+const btn =
+ 'inline-flex items-center justify-center gap-1.5 min-h-[44px] sm:min-h-[30px] px-3 py-1 rounded-lg text-xs font-medium whitespace-nowrap transition-colors disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400 motion-reduce:transition-none';
+const quietBtn = `${btn} border border-zinc-700 bg-zinc-800/80 text-zinc-100 hover:bg-zinc-700 hover:border-zinc-600`;
+const primaryBtn = `${btn} border border-sky-600 bg-sky-600 text-white hover:bg-sky-500`;
+const roseBtn = `${btn} border border-zinc-700 bg-transparent text-rose-300 hover:bg-rose-500/10 hover:border-rose-500/40`;
+const roseFill = `${btn} border border-rose-500 bg-rose-600 text-white hover:bg-rose-500`;
+const field =
+ 'w-full min-h-[40px] px-3 py-1.5 bg-zinc-950 border border-zinc-700 rounded-[10px] text-sm text-zinc-100 placeholder:text-zinc-500 focus:outline-none focus:border-sky-400 focus:ring-[3px] focus:ring-sky-400/25';
+
+/** "Ann and Ben", or "Ann, Ben and 3 more" from three names on. */
+export function shortList(names: string[], joiner = 'and'): string {
+ if (names.length <= 2) return joiner === 'and' ? listNames(names) : names.join(` ${joiner} `);
+ return `${names[0]}, ${names[1]} and ${names.length - 2} more`;
+}
+
+/** The Remove question, with who and what it takes away. */
+export function removeQuestion(bots: string[], apps: string[]): string {
+ const lose = bots.length && apps.length ? ` ${shortList(bots)} ${bots.length === 1 ? 'loses' : 'lose'} ${shortList(apps)}.` : bots.length ? ` ${shortList(bots)} ${bots.length === 1 ? 'loses' : 'lose'} it.` : '';
+ return `Remove Composio?${lose} Your sign-ins stay on Composio, so you can add it back later.`;
+}
+
+export const ComposioTile: React.FC<ComposioTileProps> = (p) => {
+ const { entry, usedBy } = p;
+ const api = p.api ?? defaultComposioTileApi;
+ const id = useId().replace(/:/g, '');
+ const cardRef = useRef<HTMLLIElement>(null);
+ const keyRef = useRef<HTMLInputElement>(null);
+ const keepRef = useRef<HTMLButtonElement>(null);
+
+ const refused = entry.added && entry.problem?.action === 'replace_key';
+ const down = entry.added && entry.problem?.action === 'try_again';
+ const urlMode = entry.added && entry.mode === 'url';
+ const keyUrl = entry.key_url && /^https:\/\//.test(entry.key_url) ? entry.key_url : KEY_DEFAULT;
+ const apps = (entry.apps_connected ?? []).map((a) => a.name);
+ const serverId = serverIdOf(entry.connection_id);
+
+ const [open, setOpen] = useState<Open>(p.initialOpen ?? 'none');
+ const [phase, setPhase] = useState<KeyPhase>({ s: 'idle' });
+ const [busy, setBusy] = useState<null | 'off' | 'remove' | 'switch'>(null);
+ const [actionError, setActionError] = useState<{ at: 'off' | 'remove' | 'switch'; text: string } | null>(null);
+ const [notice, setNotice] = useState<string | null>(null);
+ const [linkOpen, setLinkOpen] = useState(false);
+ const [url, setUrl] = useState('');
+ const [linkKey, setLinkKey] = useState('');
+ const [linkError, setLinkError] = useState<string | null>(null);
+ const [linkSaving, setLinkSaving] = useState(false);
+
+ useEffect(() => {
+ if (!p.openRequest) return;
+ cardRef.current?.scrollIntoView?.({ behavior: 'smooth', block: 'start' });
+ if (!entry.added) openKey('add');
+ else cardRef.current?.querySelector<HTMLElement>('button')?.focus({ preventScroll: true });
+ }, [p.openRequest]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ useEffect(() => {
+ if (open === 'remove') keepRef.current?.focus();
+ }, [open]);
+
+ const openKey = (what: Open) => {
+ setOpen(what);
+ setPhase({ s: 'idle' });
+ setActionError(null);
+ window.setTimeout(() => keyRef.current?.focus(), 0);
+ };
+ const close = () => {
+ setOpen('none');
+ setPhase({ s: 'idle' });
+ };
+
+ const submitKey = async (key: string) => {
+ setPhase({ s: 'checking' });
+ try {
+ if (open === 'add') await api.addKey(key);
+ else if (open === 'switchKey') await api.switchTo(key);
+ else await api.replaceKey(key);
+ } catch (e) {
+ const text = e instanceof Error ? e.message : 'Something went wrong.';
+ const isRefused = e instanceof ConnectionsError && (e.status === 409 || e.status === 400);
+ setPhase(isRefused ? { s: 'refused', text } : { s: 'down', text });
+ window.setTimeout(() => keyRef.current?.focus(), 0);
+ return;
+ }
+ const was = open;
+ close();
+ setNotice(
+ was === 'add'
+ ? 'Composio is added. No bot has it until you choose bots.'
+ : was === 'switchKey'
+ ? switchedLine(apps)
+ : 'Key saved.',
+ );
+ p.onChanged?.();
+ };
+
+ const doSwitch = async () => {
+ setBusy('switch');
+ setActionError(null);
+ try {
+ await api.switchTo();
+ setNotice(switchedLine(apps));
+ p.onChanged?.();
+ } catch (e) {
+ // No saved key to switch with: ask for one, right here.
+ if (e instanceof ConnectionsError && (e.status === 400 || e.status === 409 || e.status === 422)) openKey('switchKey');
+ else setActionError({ at: 'switch', text: e instanceof Error ? e.message : 'Couldn’t switch. Try again in a minute.' });
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const turnOff = async () => {
+ if (!serverId) return;
+ setBusy('off');
+ setActionError(null);
+ try {
+ await api.setEnabled(serverId, false);
+ setNotice('Composio is off. No bot can use it until you turn it on again.');
+ p.onChanged?.();
+ } catch (e) {
+ setActionError({ at: 'off', text: e instanceof Error ? e.message : 'Couldn’t turn it off.' });
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const remove = async () => {
+ if (!serverId) return;
+ setBusy('remove');
+ setActionError(null);
+ try {
+ await api.remove(serverId);
+ setOpen('none');
+ setNotice(null);
+ p.onChanged?.();
+ } catch (e) {
+ setActionError({ at: 'remove', text: e instanceof Error ? e.message : 'Couldn’t remove it.' });
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const submitLink = async (e: React.FormEvent) => {
+ e.preventDefault();
+ setLinkSaving(true);
+ setLinkError(null);
+ const problem = await p.onAddLink(url.trim(), linkKey.trim(), false);
+ setLinkSaving(false);
+ if (problem) setLinkError(problem);
+ else (setLinkOpen(false), setUrl(''), setLinkKey(''), close());
+ };
+
+ // ── Pieces ──
+ const chip = refused ? (
+ <span className="px-1.5 py-px rounded-md border border-rose-500/40 bg-rose-500/10 text-[11px] text-rose-200" data-composio-chip="refused">
+ Key not accepted
+ </span>
+ ) : entry.added ? (
+ <span
+ className={`px-1.5 py-px rounded-md border text-[11px] ${entry.enabled ? 'border-emerald-500/30 bg-emerald-500/10 text-emerald-200' : 'border-zinc-700 text-zinc-300'}`}
+ data-composio-chip={entry.enabled ? 'on' : 'off'}
+ >
+ {entry.enabled ? 'Added · on' : 'Added · off'}
+ </span>
+ ) : null;
+
+ const fact = (k: string, v: React.ReactNode, attr: string) => (
+ <div className={p.phone ? 'space-y-0.5' : 'grid grid-cols-[120px_1fr] gap-3'} data-fact={attr}>
+ <dt className="text-xs text-zinc-400">{k}</dt>
+ <dd className="text-xs text-zinc-200 min-w-0">{v}</dd>
+ </div>
+ );
+
+ const keyField = (what: Open) => {
+ const replace = what === 'replace' || what === 'switchKey' || refused;
+ return (
+ <KeyField
+ id={`${id}-key`}
+ app={null}
+ replace={replace && what !== 'switchKey'}
+ keyUrl={keyUrl}
+ phone={!!p.phone}
+ phase={phase}
+ inputRef={keyRef}
+ onSubmit={submitKey}
+ onCancel={close}
+ noCancel={refused && what === 'replace'}
+ label={what === 'switchKey' ? 'Your Composio API key' : undefined}
+ action={what === 'switchKey' ? 'Switch' : undefined}
+ helper={
+ what === 'add'
+ ? undefined
+ : what === 'switchKey'
+ ? 'Free plan: 10,000 tool calls a month. Kept on this computer and never shown again.'
+ : refused
+ ? 'From your Composio dashboard.'
+ : apps.length
+ ? `A key from another Composio project starts fresh there, so you’d connect ${shortList(apps)} again.`
+ : undefined
+ }
+ />
+ );
+ };
+
+ const errorNext = (at: 'off' | 'remove' | 'switch') =>
+ actionError?.at === at ? (
+ <p role="alert" className="text-xs text-rose-300" data-tile-error={at}>
+ {actionError.text}
+ </p>
+ ) : null;
+
+ const actionsGrid = p.phone ? 'grid grid-cols-2 gap-2' : 'flex flex-wrap items-center gap-2';
+ const span2 = p.phone ? 'col-span-2' : '';
+ const spin = <Loader2 size={12} className="animate-spin motion-reduce:hidden" aria-hidden="true" />;
+
+ const chooseBots = (primary: boolean) =>
+ p.onChooseBots ? (
+ <button type="button" className={primary ? primaryBtn : quietBtn} onClick={p.onChooseBots} data-composio-choose-bots>
+ {entry.enabled ? 'Choose bots' : 'Choose bots to turn it on'}
+ </button>
+ ) : p.onOpenTools ? (
+ <button type="button" className={quietBtn} onClick={p.onOpenTools}>
+ {entry.enabled ? 'Manage in Tools' : 'Turn on in Tools'}
+ </button>
+ ) : null;
+ const replaceBtn = (
+ <button type="button" className={quietBtn} onClick={() => openKey('replace')} data-composio-replace>
+ <KeyRound size={12} aria-hidden="true" /> Replace key
+ </button>
+ );
+ const offBtn =
+ entry.enabled && serverId ? (
+ <button type="button" className={quietBtn} onClick={turnOff} disabled={busy === 'off'} data-composio-off>
+ {busy === 'off' && spin} Turn off
+ </button>
+ ) : null;
+ const removeBtn = serverId ? (
+ <button type="button" className={roseBtn} onClick={() => (setOpen('remove'), setActionError(null))} data-composio-remove>
+ Remove
+ </button>
+ ) : null;
+
+ let body: React.ReactNode;
+ if (!entry.added) {
+ body =
+ open === 'add' ? (
+ <div className="space-y-3">
+ {keyField('add')}
+ <div>
+ <button
+ type="button"
+ className="inline-flex items-center gap-1 min-h-[44px] sm:min-h-[28px] text-xs text-zinc-400 hover:text-zinc-200 rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400"
+ aria-expanded={linkOpen}
+ onClick={() => setLinkOpen((v) => !v)}
+ data-composio-link-toggle
+ >
+ <ChevronDown size={12} className={`transition-transform motion-reduce:transition-none ${linkOpen ? 'rotate-180' : ''}`} aria-hidden="true" />
+ Use a Composio link instead (advanced)
+ </button>
+ {linkOpen && (
+ <form onSubmit={submitLink} {...editorProps(!!(url.trim() || linkKey.trim()))} className="mt-2 space-y-3" aria-label="Add Composio with a link" noValidate data-composio-link-form>
+ <div className="space-y-1">
+ <label htmlFor={`${id}-url`} className="block text-xs font-medium text-zinc-200">
+ Composio MCP URL
+ </label>
+ <input
+ id={`${id}-url`}
+ className={field}
+ type="url"
+ inputMode="url"
+ autoComplete="off"
+ spellCheck={false}
+ placeholder="https://backend.composio.dev/v3/mcp/…"
+ value={url}
+ onChange={(e) => setUrl(e.target.value)}
+ aria-invalid={linkError ? true : undefined}
+ aria-describedby={`${id}-url-h${linkError ? ` ${id}-url-err` : ''}`}
+ />
+ <p id={`${id}-url-h`} className="text-[11px] text-zinc-400">
+ From your Composio dashboard. It has to be an https address on composio.dev.
+ </p>
+ </div>
+ <div className="space-y-1">
+ <label htmlFor={`${id}-lkey`} className="block text-xs font-medium text-zinc-200">
+ API key <span className="font-normal text-zinc-400">(optional)</span>
+ </label>
+ <input id={`${id}-lkey`} className={field} type="password" autoComplete="off" value={linkKey} onChange={(e) => setLinkKey(e.target.value)} />
+ </div>
+ {linkError && (
+ <p id={`${id}-url-err`} role="alert" className="px-3 py-2 rounded-lg border border-rose-500/40 bg-rose-500/10 text-xs text-rose-200">
+ {linkError}
+ </p>
+ )}
+ <button type="submit" className={quietBtn} disabled={linkSaving || !url.trim()}>
+ {linkSaving && spin} Add with this link
+ </button>
+ </form>
+ )}
+ </div>
+ </div>
+ ) : (
+ <div className={actionsGrid}>
+ <button type="button" className={`${primaryBtn} ${span2}`} onClick={() => openKey('add')} data-composio-add>
+ <Plus size={12} aria-hidden="true" /> Add Composio
+ </button>
+ </div>
+ );
+ } else if (open === 'remove') {
+ body = (
+ <div role="alert" className="px-3 py-2.5 rounded-xl border border-rose-500/40 bg-rose-500/10 space-y-2.5" data-composio-remove-ask>
+ <p className="text-xs text-rose-100">{removeQuestion(usedBy, apps)}</p>
+ <div className={actionsGrid}>
+ <button type="button" className={roseFill} onClick={remove} disabled={busy === 'remove'} data-composio-remove-yes>
+ {busy === 'remove' && spin} Remove Composio
+ </button>
+ <button ref={keepRef} type="button" className={quietBtn} onClick={() => setOpen('none')} data-composio-keep>
+ Keep it
+ </button>
+ </div>
+ {errorNext('remove')}
+ </div>
+ );
+ } else if (refused) {
+ const who = usedBy.length ? shortList(usedBy) : 'your bots';
+ const what = apps.length ? shortList(apps, 'or') : 'its apps';
+ body = (
+ <div className="space-y-3">
+ <p role="alert" className="px-3 py-2 rounded-lg border border-rose-500/40 bg-rose-500/10 text-xs text-rose-200" data-composio-refused>
+ Composio didn’t accept the saved key, so {who} can’t use {what} right now. Paste a new key to fix it.
+ </p>
+ {keyField('replace')}
+ <div className={actionsGrid}>
+ {offBtn}
+ {removeBtn}
+ </div>
+ {errorNext('off')}
+ </div>
+ );
+ } else if (open === 'replace' || open === 'switchKey') {
+ body = (
+ <div className="space-y-3">
+ {open === 'switchKey' && (
+ <p className="flex items-start gap-2 px-3 py-2 rounded-lg border border-violet-400/30 bg-violet-500/10 text-xs text-violet-100" data-composio-switch-needs-key>
+ <Info size={14} className="mt-px shrink-0" aria-hidden="true" />
+ The one-key setup needs your Composio API key. The apps you already connected stay connected.
+ </p>
+ )}
+ {keyField(open)}
+ </div>
+ );
+ } else {
+ body = (
+ <div className="space-y-2">
+ {urlMode && entry.can_switch && (
+ <div className="px-3 py-2.5 rounded-xl border border-violet-400/30 bg-violet-500/10 space-y-2" data-composio-switch>
+ <p className="flex items-start gap-2 text-xs text-violet-100">
+ <Info size={14} className="mt-px shrink-0" aria-hidden="true" />
+ Switch to the one-key setup to connect apps right here. Your bots then find any app by themselves, and the apps you already connected stay connected.
+ </p>
+ <div className={actionsGrid}>
+ <button type="button" className={`${primaryBtn} ${span2}`} onClick={doSwitch} disabled={busy === 'switch'} data-composio-switch-go>
+ {busy === 'switch' && spin} Switch to the one-key setup
+ </button>
+ </div>
+ {errorNext('switch')}
+ </div>
+ )}
+ <div className={actionsGrid}>
+ {chooseBots(!entry.enabled || !usedBy.length)}
+ {!urlMode && replaceBtn}
+ {offBtn}
+ {removeBtn}
+ </div>
+ {errorNext('off')}
+ </div>
+ );
+ }
+
+ return (
+ <li ref={cardRef} className="rounded-xl border border-zinc-800 bg-[#181335] p-4 space-y-3 scroll-mt-4" aria-labelledby={`${id}-n`} data-catalog={entry.id} data-composio-tile={open !== 'none' ? open : refused ? 'refused' : urlMode ? 'url' : entry.added ? (entry.enabled ? 'on' : 'off') : 'new'}>
+ <div className="space-y-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <h4 id={`${id}-n`} className="text-[15px] font-semibold text-zinc-100">
+ Composio
+ </h4>
+ {chip}
+ </div>
+ <p className="text-xs text-zinc-300">Gmail and hundreds more apps. Your bots find the app they need by themselves.</p>
+ </div>
+
+ {entry.added && (
+ <dl className="space-y-1.5">
+ {urlMode
+ ? fact('Set up with', 'a Composio link', 'setup')
+ : fact(
+ 'Apps connected',
+ down ? (
+ <span className="flex flex-wrap items-center gap-x-2">
+ Couldn’t reach Composio to list them.
+ <button type="button" className="inline-flex items-center min-h-[44px] sm:min-h-[20px] text-xs font-medium text-sky-300 hover:underline rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400" onClick={() => p.onChanged?.()} data-composio-retry>
+ Try again
+ </button>
+ </span>
+ ) : apps.length ? (
+ shortList(apps)
+ ) : (
+ <span className="text-zinc-300">None yet. Find one with Find a tool above.</span>
+ ),
+ 'apps',
+ )}
+ {fact('Used by', usedBy.length ? shortList(usedBy) : <span className="text-zinc-300">No bot yet</span>, 'used-by')}
+ </dl>
+ )}
+
+ {notice && (
+ <p role="status" className="px-3 py-2 rounded-lg border border-emerald-500/30 bg-emerald-500/10 text-xs text-emerald-100" data-composio-notice>
+ {notice}
+ </p>
+ )}
+
+ {body}
+
+ <p className="flex items-start gap-2 text-[11px] text-zinc-400" data-composio-footer>
+ <Lock size={12} className="mt-px shrink-0" aria-hidden="true" />
+ Your app sign-ins stay on Composio’s servers, not in this app’s vault.
+ </p>
+ </li>
+ );
+};
+
+const switchedLine = (apps: string[]) =>
+ apps.length ? `Switched to the one-key setup. ${shortList(apps)} ${apps.length === 1 ? 'is' : 'are'} still connected.` : 'Switched to the one-key setup.';
diff --git a/frontend/src/components/ConnectionsView.tsx b/frontend/src/components/ConnectionsView.tsx
index 24e6cb36..e5a3e121 100644
--- a/frontend/src/components/ConnectionsView.tsx
+++ b/frontend/src/components/ConnectionsView.tsx
@@ -31,6 +31,7 @@ import { TelegramConnection } from './TelegramCard';
import { ToolNotesSection, ToolNotesSectionProps } from './ToolNotesSection';
import { notesChipText } from '../toolNotes';
import { usePhoneLayout } from '../usePhoneLayout';
+import { ComposioTile, ComposioTileApi } from './ComposioTile';
const TONES: Record<Tone, string> = {
amber: 'border-amber-500/30 bg-amber-500/10 text-amber-200',
@@ -369,7 +370,7 @@ export const ComposioCard: React.FC<ComposioCardProps> = ({ entry, initialOpen =
if ('error' in body) return setError(body.error);
setSaving(true);
setError(null);
- const problem = await onAdd(body.url, body.api_key ?? '', body.enabled);
+ const problem = await onAdd(body.url ?? '', body.api_key ?? '', body.enabled);
setSaving(false);
if (problem) setError(problem);
else (setOpen(false), setUrl(''), setKey(''), setEnabled(false));
@@ -608,6 +609,8 @@ export interface ConnectionsViewProps extends ManageLinks {
hideAccounts?: boolean;
/** Apps & accounts' Advanced: Composio's "Choose bots" (instead of "Turn on in Tools"). */
onChooseComposioBots?: () => void;
+ /** Tests and screenshots: the Composio tile's api. */
+ composioTileApi?: ComposioTileApi;
}
export const ConnectionsView: React.FC<ConnectionsViewProps> = ({
@@ -636,6 +639,7 @@ export const ConnectionsView: React.FC<ConnectionsViewProps> = ({
phone,
hideAccounts = false,
onChooseComposioBots,
+ composioTileApi,
...links
}) => {
const phoneLayout = usePhoneLayout();
@@ -801,17 +805,25 @@ export const ConnectionsView: React.FC<ConnectionsViewProps> = ({
</h3>
<ul className="space-y-2">
<TelegramConnection />
- {data.catalog.map((entry) => (
- <ComposioCard
- key={entry.id}
- entry={entry}
- initialOpen={composioOpen}
- onAdd={onAddComposio}
- onOpenTools={links.onOpenTools}
- onChooseBots={entry.id === 'composio' ? onChooseComposioBots : undefined}
- openRequest={entry.id === 'composio' ? composioRequest : 0}
- />
- ))}
+ {data.catalog.map((entry) =>
+ entry.id === 'composio' ? (
+ <ComposioTile
+ key={entry.id}
+ entry={entry}
+ usedBy={data.connections.find((c) => c.id === entry.connection_id)?.used_by.map((b) => b.name) ?? []}
+ onAddLink={onAddComposio}
+ onOpenTools={onChooseComposioBots ? undefined : links.onOpenTools}
+ onChooseBots={onChooseComposioBots}
+ onChanged={onRefresh}
+ phone={phone ?? phoneLayout}
+ openRequest={composioRequest}
+ api={composioTileApi}
+ initialOpen={composioOpen && !entry.added ? 'add' : undefined}
+ />
+ ) : (
+ <ComposioCard key={entry.id} entry={entry} initialOpen={composioOpen} onAdd={onAddComposio} onOpenTools={links.onOpenTools} />
+ ),
+ )}
</ul>
</section>
)}
diff --git a/frontend/src/components/FindTool.tsx b/frontend/src/components/FindTool.tsx
new file mode 100644
index 00000000..13862266
--- /dev/null
+++ b/frontend/src/components/FindTool.tsx
@@ -0,0 +1,1189 @@
+// Find a tool (composio-simple/design.md §1, §2 and "Autocomplete"): one field that finds a tool
+// wherever it comes from (built in, through Composio, the public directory), from the first letter.
+// Used in Add a tool (browseWhenEmpty) and on Apps & accounts. ARIA 1.2 combobox: focus stays in the
+// field, ↑/↓ move a highlight across every group's rows, Enter runs the highlighted row's main button.
+//
+// Text from Composio and the directory is shown as plain text, never as HTML.
+
+import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
+import { AlertTriangle, Check, ExternalLink, Eye, EyeOff, KeyRound, Loader2, Lock, Plus, RefreshCw, Search, X } from 'lucide-react';
+import {
+ CatalogEntry,
+ ComposioAppList,
+ ComposioListedApp,
+ Connection,
+ ConnectionsError,
+ ConnectionsList,
+ DirectoryEntry,
+ connectionsApi,
+} from '../connections';
+import { APP_TILES, appInitials, listNames } from '../appsAccounts';
+import { COMPOSIO_ONLY_APPS, MCP_PRESETS, McpPreset } from '../mcp';
+import { ToolMatch, ghostRest, normalize, rankTools, suggestionsLine } from '../toolSearch';
+import { usePhoneLayout } from '../usePhoneLayout';
+
+// ── Data ─────────────────────────────────────────────────────────────────────────────────────
+
+export interface FindToolApi {
+ list: () => Promise<ConnectionsList>;
+ apps: () => Promise<ComposioAppList>;
+ addKey: (key: string) => Promise<unknown>;
+ replaceKey: (key: string) => Promise<unknown>;
+ connect: (slug: string) => Promise<{ redirect_url: string }>;
+ /** null: this server has no public directory yet, so the group hides. */
+ directory: (q: string, signal?: AbortSignal) => Promise<{ entries: DirectoryEntry[]; unavailable: boolean } | null>;
+}
+
+export const defaultFindToolApi: FindToolApi = {
+ list: () => connectionsApi.list(),
+ apps: () => connectionsApi.composioAppList(),
+ addKey: (k) => connectionsApi.addComposioKey(k),
+ replaceKey: (k) => connectionsApi.replaceComposioKey(k),
+ connect: (slug) => connectionsApi.connectComposioApp(slug),
+ directory: (q, signal) => connectionsApi.searchDirectory(q, signal),
+};
+
+/** What "Choose bots" is for: Composio (one connection, every app on it) or one tool server. */
+export type ChooseBotsTarget = { kind: 'composio'; slug: string; name: string } | { kind: 'server'; connectionId: string; name: string };
+
+export interface FindToolProps {
+ /** Add a tool: an empty field shows the browse grid (`children`) under "All built-in tools". */
+ browseWhenEmpty: boolean;
+ /** The page's connections, when it has loaded them; without it Find a tool loads them itself. */
+ data?: ConnectionsList | null;
+ /** Ask the page to load its connections again (after Composio is added or an app connects). */
+ onChanged?: () => void | Promise<unknown>;
+ onAddPreset: (preset: McpPreset) => void;
+ onAddDirectory?: (entry: DirectoryEntry) => void;
+ onAddByAddress?: () => void;
+ onChooseBots: (target: ChooseBotsTarget) => void;
+ /** Composio is added but can't start a sign-in here (an old link setup): the page's own way. */
+ onComposioElsewhere?: (slug: string, name: string) => void;
+ /** Esc on an empty field (Add a tool closes). */
+ onEscapeEmpty?: () => void;
+ autoFocus?: boolean;
+ phone?: boolean;
+ api?: FindToolApi;
+ /** Tests and shots: start with this text. */
+ initialQuery?: string;
+ /** The browse grid. */
+ children?: React.ReactNode;
+}
+
+type GroupKey = 'connected' | 'popular' | 'builtin' | 'composio' | 'directory';
+
+const GROUP_LABEL: Record<GroupKey, string> = {
+ connected: 'Connected',
+ popular: 'Popular',
+ builtin: 'Built in',
+ composio: 'Through Composio',
+ directory: 'From the public directory',
+};
+const MORE_LABEL: Partial<Record<GroupKey, string>> = {
+ builtin: 'built in',
+ composio: 'through Composio',
+ directory: 'in the public directory',
+};
+
+interface ComposioRowApp {
+ slug: string;
+ name: string;
+ description: string;
+ tools: number | null;
+ connected: boolean;
+}
+
+type Row =
+ | { key: string; group: GroupKey; kind: 'builtin'; name: string; match: ToolMatch | null; preset: McpPreset; added: Connection | null }
+ | { key: string; group: GroupKey; kind: 'composio'; name: string; match: ToolMatch | null; app: ComposioRowApp }
+ | { key: string; group: GroupKey; kind: 'directory'; name: string; match: ToolMatch | null; entry: DirectoryEntry }
+ | { key: string; group: GroupKey; kind: 'more'; name: string; match: null; count: number; of: GroupKey };
+
+interface Group {
+ key: GroupKey;
+ rows: Row[];
+ /** "{n} more. Type to find them." in Connected; not an option. */
+ rest?: number;
+}
+
+const POPULAR = ['gmail', 'googlecalendar', 'slack', 'notion', 'github', 'googledrive'];
+const PER_GROUP = 5;
+
+/** What an app does, for the Composio rows we know; Composio's lists carry no description. */
+const KNOWN_BLURBS: Record<string, string> = {};
+for (const a of COMPOSIO_ONLY_APPS) if (a.blurb) KNOWN_BLURBS[a.toolkit] = a.blurb;
+for (const t of APP_TILES) KNOWN_BLURBS[t.slug] = `${t.blurb}.`;
+const TINT: Record<string, string> = {};
+for (const t of APP_TILES) if (t.tint) TINT[t.slug] = t.tint;
+
+const FALLBACK_APPS: ComposioListedApp[] = COMPOSIO_ONLY_APPS.map((a) => ({ slug: a.toolkit, name: a.label }));
+
+const presetUrl = (p: McpPreset) => (p.form.transport === 'http' ? p.form.url.trim().replace(/\/+$/, '').toLowerCase() : '');
+const PRESET_URLS = new Set(MCP_PRESETS.map(presetUrl).filter(Boolean));
+
+/** "by notion.com" for a remote built-in tool: the last two labels of its address. */
+export function presetPublisher(p: McpPreset): string | null {
+ if (p.form.transport !== 'http') return null;
+ try {
+ const host = new URL(p.form.url).hostname.split('.');
+ return host.slice(-2).join('.');
+ } catch {
+ return null;
+ }
+}
+
+/** The directory clips a maker's description at 100 characters; when it stops mid-sentence, show that it was cut. */
+export function markCutDescription(description: string): string {
+ const t = description.trimEnd();
+ return description.length >= 100 && !/[.!?)\u2026]$/.test(t) ? `${t}\u2026` : description;
+}
+
+/** The directory's key chips: "API key", "2 keys" or "Sign-in". */
+export function directoryNeeds(e: DirectoryEntry): string | null {
+ const keys = (e.inputs ?? []).filter((i) => i.secret || /key|token|secret/i.test(i.name)).length;
+ if (keys === 1) return 'API key';
+ if (keys > 1) return `${keys} keys`;
+ return null;
+}
+
+/** A remote built-in tool's host, as the server shows an added tool's address (connections.rs: the host, or a local tool's command). */
+const presetHost = (p: McpPreset): string => {
+ if (p.form.transport !== 'http') return '';
+ try {
+ return new URL(p.form.url.trim()).hostname.toLowerCase();
+ } catch {
+ return '';
+ }
+};
+
+/** The added server that is this built-in tool: same name, and for a remote tool the same host. A server a person named
+ * "Stripe" at another address is not the built-in Stripe; only a server with no address falls back to the name alone. */
+const addedServer = (p: McpPreset, connections: Connection[]): Connection | null => {
+ const names = [p.form.name.toLowerCase(), p.label.toLowerCase()];
+ const host = presetHost(p);
+ return (
+ connections.find((c) => {
+ if (c.kind !== 'mcp' || !names.includes(c.name.toLowerCase())) return false;
+ const at = (c.detail ?? '').trim().toLowerCase();
+ return !host || !at || at === host;
+ }) ?? null
+ );
+};
+
+/** Every group for `query`, in order, before the Show more rows are cut. */
+export function buildGroups(opts: {
+ query: string;
+ composioApps: ComposioRowApp[];
+ composioAdded: boolean;
+ directory: DirectoryEntry[] | null;
+ connections: Connection[];
+ expanded: Set<GroupKey>;
+}): Group[] {
+ const { query, composioApps, directory, connections, expanded } = opts;
+ const q = normalize(query);
+ const cut = (key: GroupKey, rows: Row[]): Group => {
+ if (rows.length <= PER_GROUP || expanded.has(key)) return { key, rows };
+ const more: Row = { key: `more-${key}`, group: key, kind: 'more', name: `Show ${rows.length - PER_GROUP} more ${MORE_LABEL[key]}`, match: null, count: rows.length - PER_GROUP, of: key };
+ return { key, rows: [...rows.slice(0, PER_GROUP), more] };
+ };
+ const builtinRow = (group: GroupKey, preset: McpPreset, match: ToolMatch | null): Row => ({
+ key: `${group}-b-${preset.id}`,
+ group,
+ kind: 'builtin',
+ name: preset.label,
+ match,
+ preset,
+ added: addedServer(preset, connections),
+ });
+ const composioRow = (group: GroupKey, app: ComposioRowApp, match: ToolMatch | null): Row => ({ key: `${group}-c-${app.slug}`, group, kind: 'composio', name: app.name, match, app });
+
+ if (!q) {
+ const connected: Row[] = [];
+ MCP_PRESETS.forEach((p) => addedServer(p, connections) && connected.push(builtinRow('connected', p, null)));
+ composioApps.filter((a) => a.connected).forEach((a) => connected.push(composioRow('connected', a, null)));
+ const taken = new Set(connected.map((r) => (r.kind === 'builtin' ? r.preset.id : r.kind === 'composio' ? r.app.slug : '')));
+ const popular: Row[] = [];
+ POPULAR.forEach((slug) => {
+ if (taken.has(slug)) return;
+ const preset = MCP_PRESETS.find((p) => p.id === slug);
+ if (preset) return void popular.push(builtinRow('popular', preset, null));
+ const app = composioApps.find((a) => a.slug === slug);
+ if (app) popular.push(composioRow('popular', app, null));
+ });
+ const groups: Group[] = [];
+ if (connected.length) groups.push({ key: 'connected', rows: connected.slice(0, 4), rest: Math.max(0, connected.length - 4) || undefined });
+ if (popular.length) groups.push({ key: 'popular', rows: popular });
+ return groups;
+ }
+
+ const builtin = rankTools(query, MCP_PRESETS.map((p) => ({ name: p.label, slug: p.id, p })), (e) => (addedServer(e.p, connections) ? 1 : 0)).map((r) =>
+ builtinRow('builtin', r.entry.p, r.match),
+ );
+ const composio = rankTools(query, composioApps, (a) => (a.connected ? 1e6 : 0) + (a.tools ?? 0)).map((r) => composioRow('composio', r.entry, r.match));
+ const groups: Group[] = [];
+ if (builtin.length) groups.push(cut('builtin', builtin));
+ groups.push(cut('composio', composio));
+ if (directory) {
+ const seen = new Set<string>();
+ const rows: Row[] = directory
+ .filter((e) => !(e.url && PRESET_URLS.has(e.url.trim().replace(/\/+$/, '').toLowerCase())))
+ .filter((e) => (seen.has(e.registry_name) ? false : (seen.add(e.registry_name), true)))
+ .map((entry) => {
+ const name = entry.title?.trim() || entry.registry_name;
+ return { key: `directory-${entry.registry_name}`, group: 'directory' as GroupKey, kind: 'directory' as const, name, match: rankTools(query, [{ name }])[0]?.match ?? null, entry };
+ });
+ groups.push(cut('directory', rows));
+ }
+ return groups;
+}
+
+// ── Look ─────────────────────────────────────────────────────────────────────────────────────
+
+const btn =
+ 'inline-flex items-center justify-center gap-1.5 min-h-[44px] sm:min-h-[32px] px-3 py-1 rounded-lg text-xs font-medium whitespace-nowrap transition-colors disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400 motion-reduce:transition-none';
+const quietBtn = `${btn} border border-zinc-700 bg-zinc-800/80 text-zinc-100 hover:bg-zinc-700 hover:border-zinc-600`;
+const primaryBtn = `${btn} border border-sky-600 bg-sky-600 text-white hover:bg-sky-500`;
+const linkBtn =
+ 'inline-flex items-center gap-1 min-h-[44px] sm:min-h-[28px] text-xs font-medium text-sky-300 hover:text-sky-200 underline-offset-2 hover:underline rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400';
+const chip = 'inline-flex items-center px-1.5 py-px rounded-md border border-zinc-700 text-[11px] text-zinc-300';
+const amberChip = 'inline-flex items-center px-1.5 py-px rounded-md border border-amber-500/40 text-[11px] text-amber-300';
+const keycap = 'inline-flex items-center justify-center h-[18px] min-w-[18px] px-1 rounded border border-zinc-700 border-b-2 bg-zinc-900 text-[10.5px] font-medium text-zinc-400';
+const fade = 'motion-safe:animate-[findtool-in_160ms_ease-out]';
+
+const Mark: React.FC<{ name: string; slug?: string }> = ({ name, slug }) => (
+ <span
+ aria-hidden="true"
+ className={`shrink-0 inline-flex items-center justify-center w-8 h-8 rounded-lg border border-violet-400/20 text-[11px] font-semibold ${(slug && TINT[slug]) || 'text-violet-100'}`}
+ style={{ background: '#231d4b' }}
+ >
+ {appInitials(name)}
+ </span>
+);
+
+/** The name with the typed letters bold, in one span so the row's gap can't split it. */
+const Name: React.FC<{ name: string; bold: [number, number] | null }> = ({ name, bold }) => (
+ <span className="text-sm font-medium text-zinc-100" data-row-name>
+ {bold ? (
+ <>
+ {name.slice(0, bold[0])}
+ <b className="font-bold text-zinc-50">{name.slice(bold[0], bold[1])}</b>
+ {name.slice(bold[1])}
+ </>
+ ) : (
+ name
+ )}
+ </span>
+);
+
+const Spinner: React.FC = () => (
+ <>
+ <Loader2 size={14} className="shrink-0 animate-spin motion-reduce:hidden" style={{ animationDuration: '700ms' }} aria-hidden="true" />
+ <span className="hidden motion-reduce:inline-block w-1.5 h-1.5 rounded-full bg-zinc-400" aria-hidden="true" />
+ </>
+);
+
+const openKeyPage = (url: string) => window.open(url, '_blank', 'noopener,noreferrer');
+
+// ── The key field (§2, and Replace key for a refused saved key) ──────────────────────────────
+
+export type KeyPhase = { s: 'idle' } | { s: 'checking' } | { s: 'refused'; text: string } | { s: 'down'; text: string };
+
+export interface KeyFieldProps {
+ id: string;
+ /** Overrides for other places (the Composio tile): label, button, helper. */
+ label?: string;
+ action?: string;
+ helper?: string;
+ /** No Cancel button when the field is the only way forward (a refused saved key). */
+ noCancel?: boolean;
+ /** null: no app, "Add Composio". */
+ app: { slug: string; name: string } | null;
+ replace: boolean;
+ keyUrl: string;
+ phone: boolean;
+ phase: KeyPhase;
+ inputRef: React.RefObject<HTMLInputElement>;
+ onSubmit: (key: string) => void;
+ onCancel: () => void;
+}
+
+export const KeyField: React.FC<KeyFieldProps> = ({ id, app, replace, keyUrl, phone, phase, inputRef, onSubmit, onCancel, ...o }) => {
+ const [value, setValue] = useState('');
+ const [shown, setShown] = useState(false);
+ const checking = phase.s === 'checking';
+ const err = phase.s === 'refused' || phase.s === 'down' ? phase : null;
+ const label = o.label ?? (replace ? 'New Composio API key' : 'Your Composio API key');
+ const action = o.action ?? (replace ? 'Save key' : app ? `Connect ${app.name}` : 'Add Composio');
+ return (
+ <form
+ className={`space-y-2 ${fade}`}
+ data-composio-key-field={phase.s}
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (value.trim() && !checking) onSubmit(value);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ e.stopPropagation();
+ onCancel();
+ }
+ }}
+ >
+ <div className="flex items-center justify-between gap-2">
+ <label htmlFor={id} className="text-xs font-medium text-zinc-200">
+ {label}
+ </label>
+ <button type="button" className={linkBtn} onClick={() => openKeyPage(keyUrl)} data-key-link>
+ {replace ? 'Get a key' : 'Get a free key'} <ExternalLink size={12} aria-hidden="true" />
+ <span className="sr-only"> (opens a new tab)</span>
+ </button>
+ </div>
+ <div className={phone ? 'space-y-2' : 'flex items-stretch gap-2'}>
+ <div className="relative flex-1 min-w-0">
+ <input
+ ref={inputRef}
+ id={id}
+ type={shown ? 'text' : 'password'}
+ value={value}
+ readOnly={checking}
+ onChange={(e) => setValue(e.target.value)}
+ placeholder="Paste your key"
+ autoComplete="off"
+ spellCheck={false}
+ aria-invalid={phase.s === 'refused' || undefined}
+ aria-describedby={`${id}-help${err ? ` ${id}-err` : ''}`}
+ className={`w-full h-10 pl-3 pr-11 rounded-[10px] bg-zinc-950 border text-zinc-100 placeholder:text-zinc-500 focus:outline-none focus:border-sky-400 focus:ring-[3px] focus:ring-sky-400/25 ${
+ phone ? 'text-base h-11' : 'text-sm'
+ } ${phase.s === 'refused' ? 'border-rose-400' : checking ? 'border-sky-400' : 'border-zinc-700'}`}
+ />
+ <button
+ type="button"
+ onClick={() => setShown((v) => !v)}
+ aria-label={shown ? 'Hide key' : 'Show key'}
+ aria-pressed={shown}
+ className="absolute right-0 top-0 h-full w-11 inline-flex items-center justify-center text-zinc-400 hover:text-zinc-200 rounded-r-[10px] focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400"
+ >
+ {shown ? <EyeOff size={16} aria-hidden="true" /> : <Eye size={16} aria-hidden="true" />}
+ </button>
+ </div>
+ <button type="submit" className={`${primaryBtn} sm:min-h-[40px] ${phone ? 'w-full' : ''}`} disabled={!value.trim() || checking} data-key-submit>
+ {checking ? (
+ <>
+ <Spinner /> Checking your key…
+ </>
+ ) : (
+ action
+ )}
+ </button>
+ {replace && !checking && !o.noCancel && (
+ <button type="button" className={`${quietBtn} sm:min-h-[40px] ${phone ? 'w-full' : ''}`} onClick={onCancel}>
+ Cancel
+ </button>
+ )}
+ </div>
+ {err && (
+ <div id={`${id}-err`} role="alert" className="flex items-start gap-2 px-3 py-2 rounded-lg border border-rose-500/40 bg-rose-500/10 text-xs text-rose-200" data-key-error={err.s}>
+ <AlertTriangle size={14} className="mt-px shrink-0" aria-hidden="true" />
+ <span className="flex-1 min-w-0">
+ {err.text}{' '}
+ {err.s === 'refused' ? (
+ <button type="button" className={linkBtn} onClick={() => openKeyPage(keyUrl)}>
+ Open your API keys <ExternalLink size={12} aria-hidden="true" />
+ <span className="sr-only"> (opens a new tab)</span>
+ </button>
+ ) : (
+ <button type="button" className={linkBtn} onClick={() => value.trim() && onSubmit(value)}>
+ <RefreshCw size={12} aria-hidden="true" /> Try again
+ </button>
+ )}
+ </span>
+ </div>
+ )}
+ <p id={`${id}-help`} className="text-[11px] text-zinc-400">
+ {o.helper ?? (replace ? 'A key from another Composio project starts fresh there, so you’d connect your apps again.' : 'Free plan: 10,000 tool calls a month. Kept on this computer and never shown again.')}
+ </p>
+ </form>
+ );
+};
+
+// ── Find a tool ──────────────────────────────────────────────────────────────────────────────
+
+type AppsLoad = { s: 'loading' } | { s: 'ok'; list: ComposioAppList } | { s: 'down'; text: string } | { s: 'refused'; text: string } | { s: 'none' };
+type DirLoad = { q: string; entries: DirectoryEntry[]; unavailable: boolean; loading: boolean };
+type AppState = { s: 'waiting'; url: string | null; since: number } | { s: 'connected' };
+/** Where the key field is open: under a Composio row (setup before Composio is added) or Replace key. */
+type KeyOpen = { slug: string | null; name: string | null; replace: boolean } | null;
+
+const KEY_DEFAULT = 'https://dashboard.composio.dev';
+const POLL_MS = 3000;
+const POLL_FOR_MS = 5 * 60 * 1000;
+
+export const FindTool: React.FC<FindToolProps> = (p) => {
+ const api = p.api ?? defaultFindToolApi;
+ const phoneHook = usePhoneLayout();
+ const phone = p.phone ?? phoneHook;
+ const uid = useId().replace(/:/g, '');
+ const inputRef = useRef<HTMLInputElement>(null);
+ const keyRef = useRef<HTMLInputElement>(null);
+ const rootRef = useRef<HTMLDivElement>(null);
+ const alive = useRef(true);
+
+ const [query, setQuery] = useState(p.initialQuery ?? '');
+ const [hl, setHl] = useState<string | null>(null);
+ const [hlAuto, setHlAuto] = useState(true);
+ const [ghostOff, setGhostOff] = useState(false);
+ const [caretAtEnd, setCaretAtEnd] = useState(true);
+ const [focusIn, setFocusIn] = useState(false);
+ const [expanded, setExpanded] = useState<Set<GroupKey>>(new Set());
+ const [own, setOwn] = useState<ConnectionsList | null>(null);
+ const [apps, setApps] = useState<AppsLoad>({ s: 'loading' });
+ const [dir, setDir] = useState<DirLoad | null>(null);
+ const [dirMissing, setDirMissing] = useState(false);
+ const [dirTry, setDirTry] = useState(0);
+ const [appState, setAppState] = useState<Record<string, AppState>>({});
+ const [keyOpen, setKeyOpen] = useState<KeyOpen>(null);
+ const [keyPhase, setKeyPhase] = useState<KeyPhase>({ s: 'idle' });
+ const [live, setLive] = useState('');
+ const [notice, setNotice] = useState<string | null>(null);
+
+ useEffect(() => {
+ alive.current = true;
+ return () => {
+ alive.current = false;
+ };
+ }, []);
+
+ const data = p.data !== undefined ? p.data : own;
+ const composio: CatalogEntry | undefined = data?.catalog.find((e) => e.id === 'composio');
+ const connections = data?.connections ?? [];
+ const composioAdded = !!composio?.added;
+ const keyUrl = (composio?.key_url && /^https:\/\//.test(composio.key_url) ? composio.key_url : null) ?? KEY_DEFAULT;
+
+ const reloadOwn = useCallback(async () => {
+ if (p.data !== undefined) return void (await p.onChanged?.());
+ try {
+ const fresh = await api.list();
+ if (alive.current) setOwn(fresh);
+ } catch {
+ /* Composio rows fall back to the bundled apps; the setup row still works. */
+ }
+ }, [p.data !== undefined]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ useEffect(() => {
+ if (p.data === undefined) void reloadOwn();
+ }, []); // eslint-disable-line react-hooks/exhaustive-deps
+
+ const loadApps = useCallback(async () => {
+ try {
+ const list = await api.apps();
+ if (!alive.current) return null;
+ setApps({ s: 'ok', list });
+ return list;
+ } catch (e) {
+ if (!alive.current) return null;
+ if (e instanceof ConnectionsError && e.status === 409) setApps({ s: 'refused', text: e.message });
+ else if (e instanceof ConnectionsError && e.status === 404) setApps({ s: 'none' });
+ else setApps({ s: 'down', text: e instanceof Error ? e.message : '' });
+ return null;
+ }
+ }, [api]);
+
+ // Loaded once when Find a tool opens (ETag), and again when Composio's setup changes.
+ useEffect(() => {
+ void loadApps();
+ }, [loadApps, composio?.added, composio?.mode]);
+
+ // ── Composio's apps as rows ──
+ const composioApps: ComposioRowApp[] = useMemo(() => {
+ const listed = apps.s === 'ok' ? apps.list.apps : apps.s === 'loading' || apps.s === 'down' || apps.s === 'none' ? FALLBACK_APPS : [];
+ const fromCatalog = new Set((composio?.apps_connected ?? []).map((a) => a.slug));
+ return listed.map((a) => ({
+ slug: a.slug,
+ name: a.name,
+ description: KNOWN_BLURBS[a.slug] ?? '',
+ tools: typeof a.tools_count === 'number' ? a.tools_count : null,
+ connected: !!a.connected || fromCatalog.has(a.slug) || appState[a.slug]?.s === 'connected',
+ }));
+ }, [apps, composio?.apps_connected, appState]);
+
+ // ── The public directory: from 2 letters, 120 ms after the last key, newer cancels older ──
+ const q2 = normalize(query).length >= 2;
+ useEffect(() => {
+ if (dirMissing || !q2) return;
+ const ctl = new AbortController();
+ const t = window.setTimeout(async () => {
+ setDir((d) => (d ? { ...d, loading: true } : { q: query, entries: [], unavailable: false, loading: true }));
+ try {
+ const answer = await api.directory(query.trim(), ctl.signal);
+ if (ctl.signal.aborted || !alive.current) return;
+ if (answer === null) return setDirMissing(true);
+ setDir({ q: query, entries: answer.entries, unavailable: answer.unavailable, loading: false });
+ } catch (e) {
+ if ((e as Error)?.name === 'AbortError' || ctl.signal.aborted) return;
+ setDir({ q: query, entries: [], unavailable: true, loading: false });
+ }
+ }, 120);
+ return () => {
+ window.clearTimeout(t);
+ ctl.abort();
+ };
+ }, [query, q2, dirMissing, dirTry]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ const groups = useMemo(
+ () =>
+ buildGroups({
+ query,
+ composioApps,
+ composioAdded,
+ directory: dirMissing || !q2 ? null : dir?.entries ?? [],
+ connections,
+ expanded,
+ }),
+ [query, composioApps, composioAdded, dirMissing, q2, dir, connections, expanded],
+ );
+ const rows = useMemo(() => groups.flatMap((g) => g.rows), [groups]);
+ const typed = query.trim().length > 0;
+ const showEmptyGroups = !typed && (p.browseWhenEmpty || focusIn);
+ const visibleRows = typed || showEmptyGroups ? rows : [];
+ const active = visibleRows.find((r) => r.key === hl) ?? (typed && hlAuto ? visibleRows[0] : undefined) ?? null;
+ const ghost = active && typed && !ghostOff && caretAtEnd && active.kind !== 'more' && active.match?.kind === 'start' ? ghostRest(query, active.name) : '';
+ const optionId = (r: Row) => `${uid}-opt-${r.key}`;
+ const optionCount = visibleRows.filter((r) => r.kind !== 'more').length;
+
+ // The polite live line, 400 ms after typing stops.
+ useEffect(() => {
+ const t = window.setTimeout(() => setLive(typed || showEmptyGroups ? suggestionsLine(optionCount) : ''), 400);
+ return () => window.clearTimeout(t);
+ }, [optionCount, typed, showEmptyGroups]);
+
+ // The highlighted row scrolls into view.
+ useEffect(() => {
+ if (!active) return;
+ document.getElementById(optionId(active))?.scrollIntoView?.({ block: 'nearest' });
+ }, [active?.key]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ // ── Waiting rows: poll Composio's list every 3 s for 5 minutes, and when the window is back ──
+ const waiting = Object.entries(appState).filter(([, s]) => s.s === 'waiting').map(([slug]) => slug);
+ useEffect(() => {
+ if (!waiting.length) return;
+ const check = async () => {
+ const list = await loadApps();
+ if (!list || !alive.current) return;
+ const now = new Set(list.apps.filter((a) => a.connected).map((a) => a.slug));
+ const done = waiting.filter((slug) => now.has(slug));
+ if (!done.length) return;
+ setAppState((m) => ({ ...m, ...Object.fromEntries(done.map((s) => [s, { s: 'connected' } as AppState])) }));
+ void reloadOwn();
+ };
+ const started = Math.min(...waiting.map((s) => (appState[s] as { since: number }).since));
+ const iv = window.setInterval(() => {
+ if (Date.now() - started > POLL_FOR_MS) return window.clearInterval(iv);
+ void check();
+ }, POLL_MS);
+ const onFocus = () => void check();
+ window.addEventListener('focus', onFocus);
+ return () => {
+ window.clearInterval(iv);
+ window.removeEventListener('focus', onFocus);
+ };
+ }, [waiting.join(',')]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ // ── Actions ──
+ const composioUsers = (): string[] => {
+ const id = composio?.connection_id;
+ return id ? (connections.find((c) => c.id === id)?.used_by ?? []).map((u) => u.name) : [];
+ };
+
+ const openKey = (app: { slug: string; name: string } | null, replace = false) => {
+ setKeyOpen({ slug: app?.slug ?? null, name: app?.name ?? null, replace });
+ setKeyPhase({ s: 'idle' });
+ window.setTimeout(() => keyRef.current?.focus(), 0);
+ };
+
+ /** Starts an app's sign-in: the tab opens inside the click or key event, its address follows. */
+ const startSignIn = async (slug: string, tab: Window | null) => {
+ setAppState((m) => ({ ...m, [slug]: { s: 'waiting', url: null, since: Date.now() } }));
+ try {
+ const { redirect_url } = await api.connect(slug);
+ if (!/^https:\/\//.test(redirect_url)) throw new Error('Composio sent an address we can’t open.');
+ if (tab && !tab.closed) tab.location.href = redirect_url;
+ else window.open(redirect_url, '_blank', 'noopener,noreferrer');
+ if (alive.current) setAppState((m) => ({ ...m, [slug]: { s: 'waiting', url: redirect_url, since: Date.now() } }));
+ } catch (e) {
+ tab?.close();
+ if (!alive.current) return;
+ setAppState((m) => {
+ const next = { ...m };
+ delete next[slug];
+ return next;
+ });
+ setNotice(e instanceof Error ? e.message : 'Couldn’t start the sign-in.');
+ }
+ };
+
+ const connectApp = (app: ComposioRowApp) => {
+ setNotice(null);
+ if (!composioAdded) return openKey(app);
+ if (apps.s === 'refused' || composio?.problem?.action === 'replace_key') return openKey(app, true);
+ if (!composio?.can_connect) return p.onComposioElsewhere?.(app.slug, app.name);
+ const tab = window.open('about:blank', '_blank');
+ void startSignIn(app.slug, tab);
+ };
+
+ const submitKey = async (key: string) => {
+ if (!keyOpen) return;
+ const { slug, name, replace } = keyOpen;
+ // Open the sign-in tab now, inside the press, so a popup blocker lets it through.
+ const tab = !replace && slug ? window.open('about:blank', '_blank') : null;
+ setKeyPhase({ s: 'checking' });
+ try {
+ await (replace ? api.replaceKey(key) : api.addKey(key));
+ } catch (e) {
+ tab?.close();
+ if (!alive.current) return;
+ const text = e instanceof Error ? e.message : 'Something went wrong.';
+ const refused = e instanceof ConnectionsError && (e.status === 409 || e.status === 400);
+ setKeyPhase(refused ? { s: 'refused', text } : { s: 'down', text });
+ window.setTimeout(() => keyRef.current?.focus(), 0);
+ return;
+ }
+ if (!alive.current) return;
+ setKeyOpen(null);
+ setKeyPhase({ s: 'idle' });
+ await reloadOwn();
+ void loadApps();
+ if (slug && name && !replace) {
+ void startSignIn(slug, tab);
+ setNotice(`Composio is added. Finish signing in to ${name} in the new tab.`);
+ } else {
+ setNotice(replace ? 'Key saved.' : 'Composio is added. No bot has it until you choose bots.');
+ }
+ inputRef.current?.focus();
+ };
+
+ /** What Enter (and the row's main button) does. */
+ const run = (r: Row) => {
+ if (r.kind === 'more') {
+ setExpanded((s) => new Set(s).add(r.of));
+ setHl(null);
+ setHlAuto(true);
+ return;
+ }
+ if (r.kind === 'builtin') {
+ if (r.added) return p.onChooseBots({ kind: 'server', connectionId: r.added.id, name: r.preset.label });
+ return p.onAddPreset(r.preset);
+ }
+ if (r.kind === 'directory') {
+ if (!r.entry.already_added) p.onAddDirectory?.(r.entry);
+ return;
+ }
+ const st = appState[r.app.slug];
+ if (keyOpen && keyOpen.slug === r.app.slug) return keyRef.current?.focus();
+ if (r.app.connected) return p.onChooseBots({ kind: 'composio', slug: r.app.slug, name: r.app.name });
+ if (st?.s === 'waiting') {
+ if (st.url) window.open(st.url, '_blank', 'noopener,noreferrer');
+ return;
+ }
+ connectApp(r.app);
+ };
+
+ const move = (dir: 1 | -1) => {
+ if (!visibleRows.length) return;
+ const i = active ? visibleRows.indexOf(active) : -1;
+ const next = i + dir;
+ setGhostOff(false);
+ if (next < 0) {
+ setHl(null);
+ setHlAuto(false);
+ return;
+ }
+ if (next >= visibleRows.length) return;
+ setHl(visibleRows[next].key);
+ };
+
+ const accept = () => {
+ if (!ghost || !active) return false;
+ setQuery(active.name);
+ setHl(active.key.replace(/^(connected|popular)-/, active.kind === 'builtin' ? 'builtin-' : 'composio-'));
+ setHlAuto(true);
+ return true;
+ };
+
+ const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
+ if (e.nativeEvent.isComposing) return;
+ const atEnd = e.currentTarget.selectionStart === e.currentTarget.value.length && e.currentTarget.selectionEnd === e.currentTarget.value.length;
+ switch (e.key) {
+ case 'ArrowDown':
+ e.preventDefault();
+ if (!typed && !showEmptyGroups) setFocusIn(true);
+ move(1);
+ break;
+ case 'ArrowUp':
+ e.preventDefault();
+ move(-1);
+ break;
+ case 'Tab':
+ if (!e.shiftKey && ghost && accept()) {
+ e.preventDefault();
+ e.stopPropagation();
+ }
+ break;
+ case 'ArrowRight':
+ if (ghost && atEnd && accept()) e.preventDefault();
+ break;
+ case 'Enter':
+ if (active) {
+ e.preventDefault();
+ run(active);
+ }
+ break;
+ case 'Escape':
+ if (ghost) {
+ e.preventDefault();
+ e.stopPropagation();
+ setGhostOff(true);
+ } else if (query) {
+ e.preventDefault();
+ e.stopPropagation();
+ change('');
+ } else if (p.onEscapeEmpty) {
+ e.preventDefault();
+ e.stopPropagation();
+ p.onEscapeEmpty();
+ }
+ break;
+ }
+ };
+
+ const change = (v: string) => {
+ setQuery(v);
+ setHl(null);
+ setHlAuto(true);
+ setGhostOff(false);
+ setCaretAtEnd(true);
+ if (!v.trim()) setExpanded(new Set());
+ };
+
+ // ── Rows ──
+ const rowAction = (r: Row, isActive: boolean) => {
+ const enterCap = isActive && !phone && (
+ <span className={keycap} aria-hidden="true" data-enter-keycap>
+ ↵
+ </span>
+ );
+ const main = (label: React.ReactNode, onClick: () => void, extra?: { primary?: boolean; attr?: string }) => (
+ <span className={`flex items-center gap-2 ${phone ? 'w-full' : ''}`}>
+ {enterCap}
+ <button
+ type="button"
+ tabIndex={-1}
+ className={`${isActive || extra?.primary ? primaryBtn : quietBtn} ${phone ? 'w-full' : ''}`}
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={onClick}
+ data-row-action={extra?.attr ?? 'main'}
+ >
+ {label}
+ <span className="sr-only"> {r.name}</span>
+ </button>
+ </span>
+ );
+ if (r.kind === 'builtin') {
+ if (r.added)
+ return (
+ <span className={`flex items-center gap-3 ${phone ? 'w-full' : ''}`}>
+ <span className="inline-flex items-center gap-1 text-xs text-zinc-400 whitespace-nowrap">
+ <Check size={12} aria-hidden="true" /> Added
+ </span>
+ {main('Choose bots', () => run(r), { primary: !r.added.used_by.length })}
+ </span>
+ );
+ return main('Add', () => run(r));
+ }
+ if (r.kind === 'directory') {
+ if (r.entry.already_added)
+ return (
+ <span className="inline-flex items-center gap-1 text-xs text-zinc-400 whitespace-nowrap">
+ <Check size={12} aria-hidden="true" /> Added
+ </span>
+ );
+ return main('Add', () => run(r));
+ }
+ if (r.kind === 'composio') {
+ const st = appState[r.app.slug];
+ if (r.app.connected) {
+ const users = composioUsers();
+ return (
+ <span className={`flex items-center gap-3 ${phone ? 'w-full' : ''}`}>
+ <span className="inline-flex items-center gap-1 text-xs text-emerald-300 whitespace-nowrap">
+ <Check size={12} aria-hidden="true" /> Connected
+ </span>
+ {main('Choose bots', () => run(r), { primary: !users.length })}
+ </span>
+ );
+ }
+ if (st?.s === 'waiting')
+ return main(
+ <>
+ Open sign-in again <ExternalLink size={12} aria-hidden="true" />
+ </>,
+ () => run(r),
+ );
+ return main('Connect', () => run(r));
+ }
+ return null;
+ };
+
+ const rowSmall = (r: Row): string | null => {
+ if (r.group === 'connected' || r.group === 'popular') return r.kind === 'builtin' ? 'built in' : r.kind === 'composio' ? 'through Composio' : null;
+ if (r.kind === 'builtin') return presetPublisher(r.preset) ? `by ${presetPublisher(r.preset)}` : null;
+ if (r.kind === 'composio') return r.app.tools ? `${r.app.tools} tools` : null;
+ if (r.kind === 'directory') return r.entry.publisher?.label ? `by ${r.entry.publisher.label}` : null;
+ return null;
+ };
+
+ const rowMeta = (r: Row): React.ReactNode => {
+ if (r.kind === 'builtin') {
+ if (r.added) {
+ const who = r.added.used_by.map((u) => u.name);
+ return who.length ? <span className="text-xs text-zinc-400">{listNames(who)} can use it</span> : <span className="text-xs text-amber-300">No bot can use it yet.</span>;
+ }
+ if (r.group === 'connected') return null;
+ return (
+ <>
+ <span className={chip}>{r.preset.form.transport === 'http' ? 'Remote' : 'Runs on this computer'}</span>
+ {r.preset.needs.includes('Sign-in') && <span className={amberChip}>Sign in after adding</span>}
+ </>
+ );
+ }
+ if (r.kind === 'directory') {
+ const needs = directoryNeeds(r.entry);
+ return (
+ <>
+ <span className={chip}>{r.entry.kind === 'remote' ? 'Remote' : 'Runs on this computer'}</span>
+ {needs && <span className={chip}>{needs}</span>}
+ </>
+ );
+ }
+ if (r.kind === 'composio') {
+ const st = appState[r.app.slug];
+ if (r.app.connected) {
+ const who = composioUsers();
+ return who.length ? <span className="text-xs text-zinc-400">{listNames(who)} can use it</span> : <span className="text-xs text-amber-300">No bot can use it yet.</span>;
+ }
+ if (st?.s === 'waiting') return <span className="text-xs text-zinc-300">Waiting for you to finish signing in, in the new tab.</span>;
+ }
+ return null;
+ };
+
+ const renderRow = (r: Row) => {
+ const isActive = active?.key === r.key;
+ const activate = () => {
+ if (hl !== r.key) setHl(r.key);
+ };
+ if (r.kind === 'more')
+ return (
+ <li
+ key={r.key}
+ id={optionId(r)}
+ role="option"
+ aria-selected={isActive}
+ onMouseMove={activate}
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => run(r)}
+ className={`px-3.5 py-2.5 cursor-pointer ${phone ? 'pl-[56px]' : 'pl-[60px]'} ${isActive ? 'bg-[#272050] shadow-[inset_2px_0_0_#9d8fff]' : ''}`}
+ data-more={r.of}
+ >
+ <span className="text-xs font-medium text-sky-300">{r.name}</span>
+ </li>
+ );
+ const small = rowSmall(r);
+ const meta = rowMeta(r);
+ const description = r.kind === 'builtin' ? r.preset.blurb : r.kind === 'composio' ? r.app.description : r.entry.description;
+ const slug = r.kind === 'composio' ? r.app.slug : r.kind === 'builtin' ? r.preset.id : undefined;
+ const setupHere = r.kind === 'composio' && keyOpen && !keyOpen.replace && keyOpen.slug === r.app.slug;
+ return (
+ <li
+ key={r.key}
+ id={optionId(r)}
+ role="option"
+ aria-selected={isActive}
+ aria-label={small ? `${r.name}, ${small}` : r.name}
+ onMouseMove={activate}
+ className={`px-3.5 py-3 ${isActive ? 'bg-[#272050] shadow-[inset_2px_0_0_#9d8fff]' : ''}`}
+ data-row={r.kind}
+ data-row-key={r.key}
+ data-active={isActive || undefined}
+ >
+ <div className={phone ? 'space-y-2.5' : 'flex items-center gap-3'}>
+ <div className={`flex ${description || meta ? 'items-start' : 'items-center'} gap-2.5 flex-1 min-w-0`}>
+ <Mark name={r.name} slug={slug} />
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-baseline gap-x-1.5">
+ <Name name={r.name} bold={r.match?.bold ?? null} />
+ {small && <span className={`text-xs ${isActive ? 'text-zinc-400' : 'text-zinc-400'}`}>{small}</span>}
+ </div>
+ {description && (
+ <p className={`text-[13px] text-zinc-300 ${r.kind === 'directory' ? 'line-clamp-2' : 'truncate'}`} title={description}>
+ {r.kind === 'directory' ? markCutDescription(description) : description}
+ </p>
+ )}
+ {meta && <div className="mt-1 flex flex-wrap items-center gap-1.5">{meta}</div>}
+ </div>
+ </div>
+ {!setupHere && <div className={phone ? 'pl-[42px]' : 'shrink-0'}>{rowAction(r, isActive)}</div>}
+ </div>
+ {setupHere && (
+ <div className={`mt-3 ${phone ? '' : 'pl-[42px]'} space-y-2`} data-composio-setup={r.app.slug}>
+ <p className="text-sm font-medium text-zinc-100">{r.app.name} and hundreds more apps through Composio</p>
+ <p className="text-[13px] text-zinc-300">
+ Composio is a service with a free plan that signs your bots in to apps. Add your key once and your bots can use any app you connect.
+ </p>
+ <KeyField
+ id={`${uid}-key`}
+ app={{ slug: r.app.slug, name: r.app.name }}
+ replace={false}
+ keyUrl={keyUrl}
+ phone={phone}
+ phase={keyPhase}
+ inputRef={keyRef}
+ onSubmit={submitKey}
+ onCancel={() => (setKeyOpen(null), inputRef.current?.focus())}
+ />
+ </div>
+ )}
+ </li>
+ );
+ };
+
+ const groupHeader = (g: Group) => (
+ <div className={`flex ${phone ? 'flex-col gap-0.5' : 'items-baseline justify-between gap-2'} px-0.5 mb-1.5`}>
+ <h4 id={`${uid}-g-${g.key}`} className="text-[11px] font-semibold uppercase tracking-wider text-zinc-300">
+ {GROUP_LABEL[g.key]}
+ </h4>
+ {g.key === 'composio' && (
+ <span className="inline-flex items-center gap-1 text-xs text-zinc-400">
+ <Lock size={12} aria-hidden="true" /> Sign-ins stay on Composio’s servers
+ </span>
+ )}
+ {g.key === 'directory' && <span className="text-xs text-zinc-400">Listed by their makers, not checked by us</span>}
+ </div>
+ );
+
+ const composioState = (g: Group): React.ReactNode => {
+ if (apps.s === 'refused')
+ return (
+ <div role="alert" className="px-3 py-2.5 rounded-xl border border-rose-500/40 bg-rose-500/10 text-xs text-rose-200 space-y-2" data-composio-state="refused">
+ <p className="flex items-start gap-2">
+ <AlertTriangle size={14} className="mt-px shrink-0" aria-hidden="true" />
+ Composio didn’t accept your saved key, so its apps can’t be listed.
+ </p>
+ {keyOpen?.replace ? (
+ <div className="pl-[22px]">
+ <KeyField id={`${uid}-key`} app={null} replace keyUrl={keyUrl} phone={phone} phase={keyPhase} inputRef={keyRef} onSubmit={submitKey} onCancel={() => setKeyOpen(null)} />
+ </div>
+ ) : (
+ <button type="button" className={`${quietBtn} ml-[22px]`} onClick={() => openKey(null, true)} data-replace-key>
+ <KeyRound size={12} aria-hidden="true" /> Replace key
+ </button>
+ )}
+ </div>
+ );
+ if (apps.s === 'down' && composioAdded)
+ return (
+ <p className="flex flex-wrap items-center gap-x-2 text-xs text-zinc-300" data-composio-state="down">
+ Couldn’t reach Composio, so its apps aren’t listed.
+ <button type="button" className={linkBtn} onClick={() => (setApps({ s: 'loading' }), void loadApps())}>
+ <RefreshCw size={12} aria-hidden="true" /> Try again
+ </button>
+ </p>
+ );
+ const hasRows = g.rows.length > 0;
+ return (
+ <>
+ {apps.s === 'loading' && composioAdded && (
+ <p className="flex items-center gap-2 text-xs text-zinc-300 py-1" data-composio-state="loading">
+ <Spinner /> Loading Composio’s apps…
+ </p>
+ )}
+ {!hasRows && normalize(query).length >= 2 && (
+ <p className="text-xs text-zinc-300 py-1" data-not-listed>
+ Not listed? Bots with Composio find its other apps themselves.
+ </p>
+ )}
+ </>
+ );
+ };
+
+ const directoryState = (g: Group): React.ReactNode => {
+ if (dir?.unavailable && !g.rows.length)
+ return (
+ <p className="flex flex-wrap items-center gap-x-2 text-xs text-zinc-300" data-directory-state="down">
+ Couldn’t reach the public directory. The tools above still work.
+ <button type="button" className={linkBtn} onClick={() => setDirTry((n) => n + 1)}>
+ <RefreshCw size={12} aria-hidden="true" /> Try again
+ </button>
+ </p>
+ );
+ if ((!dir || dir.loading) && !g.rows.length)
+ return (
+ <p className="flex items-center gap-2 text-xs text-zinc-300 py-1" data-directory-state="loading">
+ <Spinner /> Searching the public directory…
+ </p>
+ );
+ return null;
+ };
+
+ // A group with no rows and nothing to say is hidden.
+ const shown = (g: Group): boolean => {
+ if (g.rows.length) return true;
+ if (g.key === 'composio') return apps.s === 'refused' || (apps.s === 'down' && composioAdded) || (apps.s === 'loading' && composioAdded) || normalize(query).length >= 2;
+ if (g.key === 'directory') return !!dir?.unavailable || !dir || dir.loading;
+ return false;
+ };
+ const visibleGroups = typed || showEmptyGroups ? groups.filter(shown) : [];
+ const nothing = typed && optionCount === 0 && !(apps.s === 'refused') && !(dir?.loading || (!dir && q2 && !dirMissing)) && !dir?.unavailable;
+
+ const expandedOpen = visibleGroups.length > 0;
+ return (
+ <div
+ ref={rootRef}
+ className="space-y-3"
+ data-find-tool
+ onFocus={() => setFocusIn(true)}
+ onBlur={(e) => {
+ if (!rootRef.current?.contains(e.relatedTarget as Node | null)) setFocusIn(false);
+ }}
+ >
+ <style>{'@keyframes findtool-in{from{opacity:0}to{opacity:1}}'}</style>
+ <div className="relative">
+ <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-400 pointer-events-none" aria-hidden="true" />
+ {/* The ghost sits under the typed text: the typed part is invisible, the rest is zinc-500. */}
+ {ghost && (
+ <div
+ aria-hidden="true"
+ className={`absolute inset-y-0 left-0 right-0 flex items-center pl-[38px] pr-20 whitespace-pre overflow-hidden ${phone ? 'text-base' : 'text-sm'}`}
+ onMouseDown={(e) => {
+ e.preventDefault();
+ accept();
+ inputRef.current?.focus();
+ }}
+ data-ghost
+ >
+ <span className="invisible">{query}</span>
+ <span className="text-zinc-500 pointer-events-auto cursor-text">{ghost}</span>
+ </div>
+ )}
+ <input
+ ref={inputRef}
+ type="text"
+ role="combobox"
+ aria-label="Find a tool"
+ aria-autocomplete="both"
+ aria-expanded={expandedOpen}
+ aria-controls={`${uid}-results`}
+ aria-activedescendant={active ? optionId(active) : undefined}
+ aria-describedby={`${uid}-live`}
+ enterKeyHint="go"
+ autoComplete="off"
+ autoCorrect="off"
+ autoCapitalize="off"
+ spellCheck={false}
+ autoFocus={p.autoFocus}
+ value={query}
+ placeholder="Find a tool, like gmail, stripe or a database"
+ onChange={(e) => change(e.target.value)}
+ onKeyDown={onKeyDown}
+ onSelect={(e) => {
+ const t = e.currentTarget;
+ setCaretAtEnd(t.selectionStart === t.value.length && t.selectionEnd === t.value.length);
+ }}
+ className={`relative w-full ${phone ? 'h-11 text-base' : 'h-11 sm:h-10 text-base sm:text-sm'} pl-[38px] pr-20 rounded-[10px] bg-transparent border border-zinc-700 text-zinc-100 placeholder:text-zinc-500 focus:outline-none focus:border-sky-400 focus:ring-[3px] focus:ring-sky-400/25`}
+ style={{ backgroundColor: ghost ? 'transparent' : undefined }}
+ data-find-input
+ />
+ <div className="absolute right-1.5 top-1/2 -translate-y-1/2 flex items-center gap-1.5">
+ {ghost && !phone && (
+ <span className={keycap} aria-hidden="true" data-tab-keycap>
+ Tab
+ </span>
+ )}
+ {query && (
+ <button
+ type="button"
+ aria-label="Clear"
+ onClick={() => (change(''), inputRef.current?.focus())}
+ className={`inline-flex items-center justify-center ${phone ? 'w-11 h-11' : 'w-11 h-11 sm:w-7 sm:h-7'} rounded-full focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400`}
+ data-find-clear
+ >
+ <span className="inline-flex items-center justify-center w-5 h-5 rounded-full bg-zinc-700 text-zinc-200">
+ <X size={12} aria-hidden="true" />
+ </span>
+ </button>
+ )}
+ </div>
+ </div>
+ <p id={`${uid}-live`} className="sr-only" aria-live="polite" data-find-live>
+ {live}
+ </p>
+ {notice && (
+ <p role="status" className="flex items-start gap-2 px-3 py-2 rounded-lg border border-zinc-700 bg-zinc-900/60 text-xs text-zinc-200" data-find-notice>
+ {notice}
+ </p>
+ )}
+
+ <div id={`${uid}-results`} className="space-y-4" data-find-results>
+ {visibleGroups.map((g) => (
+ <section key={g.key} className={showEmptyGroups ? 'motion-safe:animate-[findtool-in_120ms_ease-out]' : g.key === 'directory' ? fade : ''} data-group={g.key}>
+ {groupHeader(g)}
+ {g.key === 'composio' && composioState(g)}
+ {g.rows.length > 0 && (
+ <ul
+ role="listbox"
+ aria-labelledby={`${uid}-g-${g.key}`}
+ className="rounded-xl border border-zinc-800 bg-[#181335] divide-y divide-zinc-800 overflow-hidden"
+ >
+ {g.rows.map(renderRow)}
+ {g.rest ? (
+ <li role="presentation" className="px-3.5 py-2.5 pl-[60px] text-xs text-zinc-400" data-connected-rest>
+ {g.rest} more. Type to find them.
+ </li>
+ ) : null}
+ </ul>
+ )}
+ {g.key === 'directory' && directoryState(g)}
+ </section>
+ ))}
+ {nothing && (
+ <div className="flex flex-col items-center gap-1.5 px-4 py-5 rounded-xl border border-zinc-800 bg-[#181335] text-center" data-find-nothing>
+ <p className="text-sm text-zinc-100">Nothing found for “{query.trim()}”.</p>
+ <p className="text-xs text-zinc-300">Check the spelling, or add a tool by its address.</p>
+ {p.onAddByAddress && (
+ <button type="button" className={`${quietBtn} mt-1.5`} onClick={p.onAddByAddress} data-add-by-address-inline>
+ <Plus size={14} aria-hidden="true" /> Add by address
+ </button>
+ )}
+ </div>
+ )}
+ {typed && !phone && optionCount > 0 && (
+ <p className="flex flex-wrap items-center gap-1.5 text-[11px] text-zinc-500" aria-hidden="true" data-find-legend>
+ <span className={keycap}>↑</span>
+ <span className={keycap}>↓</span> move ·<span className={keycap}>↵</span> runs the button ·<span className={keycap}>Tab</span> fills in the name ·
+ <span className={keycap}>Esc</span> clears
+ </p>
+ )}
+ </div>
+
+ {p.browseWhenEmpty && !typed && p.children && (
+ <section aria-labelledby={`${uid}-all`} data-browse>
+ <div className="flex items-baseline justify-between gap-2 px-0.5 mb-1.5">
+ <h4 id={`${uid}-all`} className="text-[11px] font-semibold uppercase tracking-wider text-zinc-300">
+ All built-in tools
+ </h4>
+ </div>
+ {p.children}
+ </section>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/components/McpServersModal.tsx b/frontend/src/components/McpServersModal.tsx
index b8c7fcfb..d302bc3a 100644
--- a/frontend/src/components/McpServersModal.tsx
+++ b/frontend/src/components/McpServersModal.tsx
@@ -22,9 +22,7 @@ import {
ShieldCheck,
LogOut,
Users,
- Search,
ExternalLink,
- AlertTriangle,
} from 'lucide-react';
import { playSfx } from '../audio/chiptune';
import {
@@ -36,11 +34,8 @@ import {
SecretRow,
StoredStatus,
McpPreset,
- ComposioOnlyApp,
- searchComposioOnly,
- COMPOSIO_ONLY_APPS,
+ OpenAddTool,
MCP_PRESETS,
- searchPresets,
groupPresets,
emptyMcpForm,
formToPayload,
@@ -59,6 +54,8 @@ import {
} from '../mcp';
import { inDesktopApp, leaveForSignIn, pollUntil, signInChanged } from '../externalLinks';
import { useEscapeLayer } from '../escape';
+import { ChooseBotsTarget, FindTool, FindToolApi } from './FindTool';
+import { DirectoryEntry, connectionsApi } from '../connections';
interface McpServersModalProps {
isOpen: boolean;
@@ -69,6 +66,11 @@ interface McpServersModalProps {
onOpenConnections?: () => void;
/** Opens straight on "Add a tool server" instead of the list. */
startAdding?: boolean;
+ /** Tests and shots: Find a tool's data, and text already typed. */
+ findApi?: FindToolApi;
+ initialQuery?: string;
+ /** Opened from Apps & accounts' Find a tool: straight on this tool's form. */
+ startWith?: OpenAddTool | null;
}
const inputCls =
@@ -223,80 +225,24 @@ const ToolChips: React.FC<{ tools: Array<{ name: string; description?: string }>
};
/** A Composio-only app picked in the catalog: why it goes through Composio, and where to set it up. */
-const ComposioOnlyNote: React.FC<{ app: ComposioOnlyApp; onOpenConnections?: () => void; onClose: () => void }> = ({ app, onOpenConnections, onClose }) => (
- <div role="status" className="space-y-2 p-3 rounded-xl border border-amber-500/30 bg-amber-500/5 text-xs text-zinc-300" data-composio-note={app.id}>
- <p>
- <span className="font-medium text-zinc-100">{app.label}</span> goes through Composio. {app.why} This app doesn’t offer unofficial servers for it.
- </p>
- <p className="flex items-start gap-1.5 text-amber-100">
- <AlertTriangle size={12} className="mt-px shrink-0 text-amber-300" aria-hidden="true" />
- <span>Composio keeps your {app.label} sign-in on Composio’s servers, not in this app’s vault.</span>
- </p>
- <p className="text-zinc-400">
- Add Composio under Connections, then use “Find an app” there and search for “{app.toolkit}”.
- </p>
- <div className="flex flex-wrap gap-2">
- {onOpenConnections && (
- <button type="button" onClick={onOpenConnections} className="px-2.5 py-1 rounded-lg bg-sky-500 text-zinc-950 hover:bg-sky-400 text-xs font-medium">
- Open Connections
- </button>
- )}
- <a href={app.source} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-0.5 text-sky-300 hover:text-sky-200 hover:underline underline-offset-2">
- {app.label} on Composio
- <ExternalLink size={10} aria-hidden="true" />
- <span className="sr-only">(opens in a new tab)</span>
- </a>
- <button type="button" onClick={onClose} className="text-zinc-400 hover:text-zinc-200">
- Close
- </button>
- </div>
- </div>
-);
-
-export const PresetCatalog: React.FC<{
- query: string;
- onQuery: (q: string) => void;
- onPick: (preset: McpPreset) => void;
- onCustom: () => void;
- onOpenConnections?: () => void;
- autoFocus?: boolean;
- /** Tests open a Composio-only note. */
- initialComposioApp?: string;
-}> = ({ query, onQuery, onPick, onCustom, onOpenConnections, autoFocus, initialComposioApp }) => {
- const [composioApp, setComposioApp] = useState<string | null>(initialComposioApp ?? null);
- const groups = groupPresets(searchPresets(query), searchComposioOnly(query));
- const total = MCP_PRESETS.length + COMPOSIO_ONLY_APPS.length;
+/** The built-in tools by category, under "All built-in tools" while Find a tool is empty. */
+export const BuiltInGrid: React.FC<{ onPick: (preset: McpPreset) => void }> = ({ onPick }) => {
+ const groups = groupPresets(MCP_PRESETS, []);
return (
- <div className="space-y-4 text-left">
- <div className="relative">
- <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-500 pointer-events-none" aria-hidden="true" />
- <input
- type="search"
- aria-label="Search servers"
- value={query}
- autoFocus={autoFocus}
- onChange={(e) => onQuery(e.target.value)}
- placeholder={`Search ${total} apps and servers, like gmail or database`}
- className={`${inputCls} pl-8`}
- />
- </div>
- {groups.length === 0 && (
- <p className="py-4 text-center text-xs text-zinc-500">
- Nothing matches “{query.trim()}”. You can still add it as a custom server.
- </p>
- )}
+ <div className="space-y-4 text-left" data-builtin-grid>
{groups.map((g) => (
<section key={g.id} aria-labelledby={`mcp-cat-${g.id}`}>
- <h4 id={`mcp-cat-${g.id}`} className="mb-1.5 text-[11px] font-medium uppercase tracking-wide text-zinc-500">
+ <h5 id={`mcp-cat-${g.id}`} className="mb-1.5 text-[11px] font-medium text-zinc-400">
{g.label}
- </h4>
+ </h5>
<ul className="grid grid-cols-1 sm:grid-cols-2 gap-2">
{g.presets.map((p) => (
<li key={p.id}>
<button
type="button"
onClick={() => onPick(p)}
- className="group w-full h-full p-3 rounded-xl border border-zinc-800 bg-zinc-950/60 hover:border-sky-500/40 hover:bg-sky-500/5 focus-visible:border-sky-500/60 focus-visible:outline-none text-left transition-all"
+ data-preset={p.id}
+ className="group w-full h-full p-3 rounded-xl border border-zinc-800 bg-zinc-950/60 hover:border-sky-500/40 hover:bg-sky-500/5 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400 text-left transition-colors motion-reduce:transition-none"
>
<span className="flex items-center gap-1.5 text-xs font-medium text-zinc-200 group-hover:text-sky-200">
<span className="text-sky-400" aria-hidden="true">
@@ -304,66 +250,62 @@ export const PresetCatalog: React.FC<{
</span>
{p.label}
</span>
- <span className="mt-1 block text-[11px] text-zinc-500 leading-snug">{p.blurb}</span>
+ <span className="mt-1 block text-[11px] text-zinc-400 leading-snug">{p.blurb}</span>
<span className="mt-2 flex flex-wrap gap-1">
- {(p.needs.length ? p.needs : ['Nothing to install']).map((n) => (
- <span
- key={n}
- className={`px-1.5 py-px rounded border text-[10px] ${
- n === 'Sign-in' || n === 'Token' || n === 'API key'
- ? 'border-amber-500/25 text-amber-300/90'
- : 'border-zinc-700/70 text-zinc-400'
- }`}
- >
- {n}
- </span>
- ))}
+ <span className="px-1.5 py-px rounded border text-[10px] border-zinc-700/70 text-zinc-400">{p.form.transport === 'http' ? 'Remote' : 'Runs on this computer'}</span>
+ {p.needs.includes('Sign-in') && <span className="px-1.5 py-px rounded border text-[10px] border-amber-500/25 text-amber-300/90">Sign in after adding</span>}
</span>
</button>
</li>
))}
- {g.composio.map((a) => (
- <li key={a.id} className={composioApp === a.id ? 'sm:col-span-2 flex flex-col gap-2' : 'flex flex-col'}>
- {/* flex-1, not h-full: h-full made the card as tall as the whole item and pushed the note over the next section. */}
- <button
- type="button"
- onClick={() => setComposioApp(composioApp === a.id ? null : a.id)}
- aria-expanded={composioApp === a.id}
- className="group w-full flex-1 p-3 rounded-xl border border-zinc-800 bg-zinc-950/60 hover:border-sky-500/40 hover:bg-sky-500/5 focus-visible:border-sky-500/60 focus-visible:outline-none text-left transition-all"
- >
- <span className="flex items-center gap-1.5 text-xs font-medium text-zinc-200 group-hover:text-sky-200">
- <span className="text-sky-400" aria-hidden="true">
- <Plug size={13} />
- </span>
- {a.label}
- </span>
- <span className="mt-1 block text-[11px] text-zinc-500 leading-snug">{a.blurb}</span>
- <span className="mt-2 flex flex-wrap gap-1">
- <span className="px-1.5 py-px rounded border text-[10px] border-amber-500/25 text-amber-300/90">via Composio</span>
- </span>
- </button>
- {composioApp === a.id && <ComposioOnlyNote app={a} onOpenConnections={onOpenConnections} onClose={() => setComposioApp(null)} />}
- </li>
- ))}
</ul>
</section>
))}
- <button
- type="button"
- onClick={onCustom}
- className="w-full flex items-center gap-2.5 p-3 rounded-xl border border-dashed border-zinc-700 hover:border-sky-500/40 hover:bg-sky-500/5 focus-visible:border-sky-500/60 focus-visible:outline-none text-left transition-all"
- >
- <Plus size={16} className="flex-shrink-0 text-sky-400" />
- <span>
- <span className="block text-xs font-medium text-zinc-200">Custom server</span>
- <span className="block text-[11px] text-zinc-500">Paste a command or URL from any server’s README.</span>
- </span>
- </button>
</div>
);
};
-export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClose, kwants = [], onOpenConnections, startAdding = false }) => {
+/** Add a tool: Find a tool, the built-in grid while it's empty, and Add by address. */
+export const AddToolPicker: React.FC<{
+ onPick: (preset: McpPreset) => void;
+ onCustom: () => void;
+ onDirectory: (entry: DirectoryEntry) => void;
+ onChooseBots: (target: ChooseBotsTarget) => void;
+ onOpenConnections?: () => void;
+ autoFocus?: boolean;
+ findApi?: FindToolApi;
+ initialQuery?: string;
+}> = ({ onPick, onCustom, onDirectory, onChooseBots, onOpenConnections, autoFocus, findApi, initialQuery }) => (
+ <div className="space-y-4 text-left" data-add-tool>
+ <FindTool
+ browseWhenEmpty
+ autoFocus={autoFocus}
+ api={findApi}
+ initialQuery={initialQuery}
+ onAddPreset={onPick}
+ onAddDirectory={onDirectory}
+ onAddByAddress={onCustom}
+ onChooseBots={onChooseBots}
+ onComposioElsewhere={() => onOpenConnections?.()}
+ >
+ <BuiltInGrid onPick={onPick} />
+ </FindTool>
+ <button
+ type="button"
+ onClick={onCustom}
+ data-add-by-address
+ className="w-full flex items-center gap-2.5 p-3 rounded-xl border border-dashed border-zinc-700 hover:border-sky-500/40 hover:bg-sky-500/5 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400 text-left transition-colors motion-reduce:transition-none"
+ >
+ <Plus size={16} className="flex-shrink-0 text-sky-400" aria-hidden="true" />
+ <span>
+ <span className="block text-xs font-medium text-zinc-200">Add by address</span>
+ <span className="block text-[11px] text-zinc-400">Paste a command or web address from any tool’s instructions.</span>
+ </span>
+ </button>
+ </div>
+);
+
+export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClose, kwants = [], onOpenConnections, startAdding = false, findApi, initialQuery, startWith }) => {
const [servers, setServers] = useState<McpServer[] | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [statuses, setStatuses] = useState<Record<string, StoredStatus>>({});
@@ -376,10 +318,11 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
const [formStart, setFormStart] = useState<McpFormState | null>(null);
const [formError, setFormError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
- // Catalog step before the form when adding, its search, and the preset the form came from.
+ // Find a tool before the form when adding, and the preset the form came from.
const [picking, setPicking] = useState(false);
- const [query, setQuery] = useState('');
const [presetId, setPresetId] = useState<string | null>(null);
+ // Added from the public directory: Save installs it by its directory name.
+ const [fromDirectory, setFromDirectory] = useState<DirectoryEntry | null>(null);
// Sign-in: the server whose popup is open, sign-in errors per server, and a pending disconnect.
const [connecting, setConnecting] = useState<string | null>(null);
const [oauthErrors, setOauthErrors] = useState<Record<string, string>>({});
@@ -450,7 +393,6 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
if (!isOpen) return;
setEditing(null);
setPicking(startAdding);
- setQuery('');
setConfirmDelete(null);
setConfirmDisconnect(null);
setTestResults({});
@@ -460,6 +402,14 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
refresh().then(() => checkNewSignIns());
}, [isOpen, startAdding, refresh, checkNewSignIns]);
+ useEffect(() => {
+ if (!isOpen || !startWith) return;
+ const preset = startWith.preset ? MCP_PRESETS.find((p) => p.id === startWith.preset) : undefined;
+ if (preset) openForm('new', preset);
+ else if (startWith.directory) openDirectoryForm(startWith.directory);
+ else if (startWith.address) openForm('new');
+ }, [isOpen, startWith]); // eslint-disable-line react-hooks/exhaustive-deps
+
// If a provider cuts the popup's link back to this window, no message arrives: coming back to
// this window is the cue to look again.
useEffect(() => {
@@ -592,7 +542,6 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
const openCatalog = () => {
playSfx('click');
setEditing(null);
- setQuery('');
setPicking(true);
};
@@ -601,6 +550,7 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
setFormError(null);
setPicking(false);
setPresetId(preset?.id ?? null);
+ setFromDirectory(null);
const f = preset?.form;
const start = target !== 'new' ? serverToForm(target) : f ? { ...f, env: f.env.map((r) => ({ ...r })), headers: f.headers.map((r) => ({ ...r })) } : emptyMcpForm();
setEditing(target === 'new' ? 'new' : target.id);
@@ -608,6 +558,36 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
setFormStart(start);
};
+ /** A tool from the public directory: the form filled in from its listing, its keys still to add. */
+ const openDirectoryForm = (entry: DirectoryEntry) => {
+ playSfx('click');
+ setFormError(null);
+ setPicking(false);
+ setPresetId(null);
+ const remote = entry.kind === 'remote';
+ const rows: SecretRow[] = (entry.inputs ?? []).map((i) => ({ key: i.name, value: '', saved: false, hint: i.description, required: !!i.required }));
+ const start: McpFormState = {
+ ...emptyMcpForm(remote ? 'http' : 'stdio'),
+ name: (entry.title || entry.registry_name.split('/').pop() || entry.registry_name).trim(),
+ url: remote ? entry.url ?? '' : '',
+ commandLine: remote ? '' : entry.command ?? '',
+ env: remote ? [] : rows,
+ headers: remote ? rows : [],
+ };
+ setFromDirectory(entry);
+ setEditing('new');
+ setForm(start);
+ setFormStart(start);
+ };
+
+ /** "Choose bots" from Find a tool: a tool server's card shows who has it; Composio's bots are on Apps & accounts. */
+ const chooseBots = (target: ChooseBotsTarget) => {
+ if (target.kind === 'composio') return onOpenConnections?.();
+ setPicking(false);
+ setEditing(null);
+ window.setTimeout(() => document.querySelector<HTMLElement>(`[data-server-card="${CSS.escape(target.connectionId.replace(/^mcp:/, ''))}"]`)?.scrollIntoView({ block: 'nearest' }), 50);
+ };
+
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
const problem = validateMcpForm(form);
@@ -617,6 +597,24 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
}
setSaving(true);
setFormError(null);
+ if (editing === 'new' && fromDirectory) {
+ const pairs = (rows: SecretRow[]) => Object.fromEntries(rows.filter((r) => r.key.trim()).map((r) => [r.key.trim(), r.value]));
+ try {
+ const r = await connectionsApi.installFromDirectory(fromDirectory.registry_name, form.name.trim(), pairs(form.env), pairs(form.headers));
+ setEditing(null);
+ setFromDirectory(null);
+ await refresh();
+ if (r?.server?.id) {
+ setStatus(r.server.id, null);
+ runTest(r.server.id);
+ }
+ } catch (err) {
+ setFormError(err instanceof Error ? err.message : 'Could not reach the server.');
+ } finally {
+ setSaving(false);
+ }
+ return;
+ }
try {
const isNew = editing === 'new';
const res = await fetch(isNew ? '/api/mcp/servers' : `/api/mcp/servers/${editing}`, {
@@ -677,9 +675,19 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
const parsed = splitCommandLine(form.commandLine);
const preset = editing === 'new' && presetId ? MCP_PRESETS.find((p) => p.id === presetId) : undefined;
- const renderPicker = () => (
- <PresetCatalog query={query} onQuery={setQuery} onPick={(p) => openForm('new', p)} onCustom={() => openForm('new')} onOpenConnections={onOpenConnections} autoFocus />
+ const picker = (autoFocus: boolean) => (
+ <AddToolPicker
+ onPick={(p) => openForm('new', p)}
+ onCustom={() => openForm('new')}
+ onDirectory={openDirectoryForm}
+ onChooseBots={chooseBots}
+ onOpenConnections={onOpenConnections}
+ autoFocus={autoFocus}
+ findApi={findApi}
+ initialQuery={initialQuery}
+ />
);
+ const renderPicker = () => picker(true);
const renderEmpty = () => (
<div className="text-center py-6 px-2 space-y-5">
@@ -689,12 +697,11 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
<div className="space-y-1.5 max-w-md mx-auto">
<h3 className="text-sm font-semibold text-zinc-100">Give your bots new abilities</h3>
<p className="text-xs text-zinc-400 leading-relaxed">
- MCP servers are small add-ons that hand your bots tools, like reading files, browsing the web or working with GitHub.
+ Tools give your bots new abilities, like reading mail, browsing the web or working with GitHub.
Add one here and every bot in this space can use it; switch it off for a bot in that bot’s edit screen. They always ask you before using a tool.
- Pick a popular one below and just add your key or sign in.
</p>
</div>
- <PresetCatalog query={query} onQuery={setQuery} onPick={(p) => openForm('new', p)} onCustom={() => openForm('new')} onOpenConnections={onOpenConnections} />
+ {picker(false)}
</div>
);
@@ -712,6 +719,7 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
return (
<li
key={server.id}
+ data-server-card={server.id}
className={`p-3.5 rounded-xl border bg-zinc-950/50 transition-colors ${server.enabled ? 'border-zinc-800' : 'border-zinc-800/60 opacity-75'}`}
>
<div className="flex items-start gap-3">
@@ -970,7 +978,11 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
</div>
{editing === 'new' && (
<div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px]">
- {preset ? (
+ {fromDirectory ? (
+ <span className="text-zinc-400" data-from-directory>
+ Filled in from the public directory, listed by {fromDirectory.publisher?.label || 'its maker'}. Add any keys it needs below.
+ </span>
+ ) : preset ? (
<span className="text-zinc-400">
Filled in for <span className="text-zinc-200">{preset.label}</span>.{' '}
{preset.needs.includes('Sign-in')
@@ -993,7 +1005,7 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
</span>
) : null}
<button type="button" onClick={openCatalog} className="text-sky-300 hover:text-sky-200 hover:underline underline-offset-2">
- {preset ? 'Pick a different one' : 'Or pick a popular server'}
+ {preset || fromDirectory ? 'Pick a different one' : 'Or find a tool by name'}
</button>
</div>
)}
@@ -1177,11 +1189,11 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
)}
<div className="min-w-0">
<h2 id="mcp-title" className="text-sm font-semibold text-zinc-100 truncate">
- {editing === 'new' || picking ? 'Add a tool server' : editing ? `Edit ${form.name || 'server'}` : 'Tools for your kwant bots'}
+ {editing === 'new' || picking ? 'Add a tool' : editing ? `Edit ${form.name || 'server'}` : 'Tools for your kwant bots'}
</h2>
<p className="text-xs text-zinc-400 truncate">
{picking
- ? 'Pick a popular server or add your own'
+ ? 'Find one by name, or add one by its address'
: editing === 'new'
? 'Pick how it connects, then fill in the details'
: editing
diff --git a/frontend/src/connections.ts b/frontend/src/connections.ts
index b0afc8f4..3268b156 100644
--- a/frontend/src/connections.ts
+++ b/frontend/src/connections.ts
@@ -52,8 +52,22 @@ export interface CatalogEntry {
/** Composio only: the Composio URL names a user, so kwant can start an app's sign-in. */
can_connect?: boolean;
search?: string;
+ /** Composio only (#548): `session` (an ak_ key), `connect` (a ck_ key), `url` (a pasted link), null when not added. */
+ mode?: 'session' | 'connect' | 'url' | null;
+ user_id?: string | null;
+ apps_connected?: Array<{ slug: string; name: string }>;
+ /** What's wrong with the setup and the one action that fixes it. */
+ problem?: { message: string; action: ComposioAction } | null;
+ can_switch?: boolean;
+ /** Where a person copies a Composio key: open it, never a hard-coded address. */
+ key_url?: string;
+ switch?: string;
+ replace_key?: string;
}
+/** The one action that fixes a Composio error (#548). */
+export type ComposioAction = 'add_composio' | 'replace_key' | 'try_again' | 'switch' | 'turn_on' | string;
+
/** One app from Composio's catalogue (Composio calls it a toolkit). */
export interface ComposioApp {
slug: string;
@@ -64,6 +78,39 @@ export interface ComposioApp {
no_auth: boolean;
}
+/** One row of GET /composio/apps without `q`: the popular 120 (no tool count) or the whole catalogue. */
+export interface ComposioListedApp {
+ slug: string;
+ name: string;
+ logo?: string | null;
+ tools_count?: number | null;
+ connected?: boolean;
+}
+
+export interface ComposioAppList {
+ apps: ComposioListedApp[];
+ /** `popular`: kwant's bundled top apps (before setup, and with a ck_ key); `all`: Composio's whole catalogue. */
+ source: 'popular' | 'all' | string;
+ mode: 'session' | 'connect' | 'url' | null;
+ can_connect: boolean;
+ connected_checked?: boolean;
+}
+
+/** One entry of the public directory (mcp-finder/brief.md). Text is plain text, never HTML. */
+export interface DirectoryEntry {
+ registry_name: string;
+ version?: string;
+ title: string;
+ description: string;
+ publisher: { label: string; kind?: string };
+ kind: 'remote' | 'stdio' | string;
+ url?: string | null;
+ transport?: string | null;
+ command?: string | null;
+ inputs: Array<{ name: string; description?: string; required?: boolean; secret?: boolean }>;
+ already_added?: boolean;
+}
+
export interface VaultSummary {
status: 'ok' | 'locked' | 'unavailable' | string;
logins?: number;
@@ -78,7 +125,13 @@ export interface ConnectionsList {
}
export class ConnectionsError extends Error {
- constructor(message: string, public status: number) {
+ constructor(
+ message: string,
+ public status: number,
+ /** #548: the one action that fixes it, and where to copy a key. */
+ public action: ComposioAction | null = null,
+ public keyUrl: string | null = null,
+ ) {
super(message);
}
}
@@ -108,10 +161,66 @@ async function call<T>(url: string, method = 'GET', body?: unknown, missing = 'T
}
const answer = await res.json().catch(() => null);
if (res.ok) return answer as T;
- const err = answer && typeof answer === 'object' ? (answer as Record<string, unknown>).error : null;
- if (res.status === 403) throw new ConnectionsError('Only you can see and change connections.', 403);
- if (res.status === 404 && !err) throw new ConnectionsError(missing, 404);
- throw new ConnectionsError(typeof err === 'string' && err.trim() ? sentence(err) : `Something went wrong (HTTP ${res.status}).`, res.status);
+ throw errorOf(res.status, answer, missing);
+}
+
+function errorOf(status: number, answer: unknown, missing: string): ConnectionsError {
+ const o = answer && typeof answer === 'object' ? (answer as Record<string, unknown>) : {};
+ const err = o.error;
+ if (status === 403) return new ConnectionsError('Only you can see and change connections.', 403);
+ if (status === 404 && !err) return new ConnectionsError(missing, 404);
+ const action = typeof o.action === 'string' ? o.action : null;
+ const keyUrl = typeof o.key_url === 'string' && /^https:\/\//.test(o.key_url) ? o.key_url : null;
+ return new ConnectionsError(typeof err === 'string' && err.trim() ? sentence(err) : `Something went wrong (HTTP ${status}).`, status, action, keyUrl);
+}
+
+let appListCache: { etag: string; list: ComposioAppList } | null = null;
+
+/**
+ * GET /composio/apps without `q`, once per open, with the last answer's ETag: a 304 reuses it.
+ * Matched in the browser on every key (autocomplete.md), so there's no call per key.
+ */
+async function composioAppList(): Promise<ComposioAppList> {
+ let res: Response;
+ try {
+ res = await personFetch('/api/connections/composio/apps', {
+ cache: 'no-store',
+ headers: appListCache ? { 'If-None-Match': appListCache.etag } : undefined,
+ });
+ } catch (e) {
+ if (e instanceof PersonCancelledError) throw new ConnectionsError(e.message, 401);
+ throw new ConnectionsError('Couldn’t reach the server. Check your connection and try again.', 0, 'try_again');
+ }
+ if (res.status === 304 && appListCache) return appListCache.list;
+ const answer = await res.json().catch(() => null);
+ if (!res.ok) throw errorOf(res.status, answer, 'This server can’t list Composio’s apps yet.');
+ const o = (answer ?? {}) as Partial<ComposioAppList>;
+ const list: ComposioAppList = {
+ apps: Array.isArray(o.apps) ? o.apps.filter((a) => a && typeof a.slug === 'string' && typeof a.name === 'string') : [],
+ source: typeof o.source === 'string' ? o.source : 'all',
+ mode: (o.mode ?? null) as ComposioAppList['mode'],
+ can_connect: !!o.can_connect,
+ connected_checked: !!o.connected_checked,
+ };
+ const etag = res.headers.get('ETag');
+ appListCache = etag ? { etag, list } : null;
+ return list;
+}
+
+/** The public directory, from 2 letters. `null` when this server has no directory yet (404): the group hides. */
+async function searchDirectory(q: string, signal?: AbortSignal): Promise<{ entries: DirectoryEntry[]; unavailable: boolean } | null> {
+ let res: Response;
+ try {
+ res = await personFetch(`/api/mcp/registry/search?q=${encodeURIComponent(q)}`, { cache: 'no-store', signal });
+ } catch (e) {
+ if ((e as Error)?.name === 'AbortError') throw e;
+ return { entries: [], unavailable: true };
+ }
+ if (res.status === 404) return null;
+ const answer = (await res.json().catch(() => null)) as { entries?: unknown; unavailable?: unknown } | null;
+ if (!res.ok || !answer) return { entries: [], unavailable: true };
+ const entries = Array.isArray(answer.entries) ? (answer.entries as DirectoryEntry[]).filter((e) => e && typeof e.registry_name === 'string') : [];
+ return { entries: entries.slice(0, 12), unavailable: answer.unavailable === true };
}
const enc = encodeURIComponent;
@@ -121,6 +230,19 @@ export const connectionsApi = {
raw: <T>(url: string, method = 'GET', body?: unknown, missing?: string) => call<T>(url, method, body, missing),
list: () => call<ConnectionsList>('/api/connections'),
addComposio: (body: ComposioBody) => call<{ connection_id: string; warning: string }>('/api/connections/composio', 'POST', body),
+ /** #548: one Composio key (ck_ or ak_), Composio added off for every bot. */
+ addComposioKey: (apiKey: string) =>
+ call<{ connection_id: string; mode?: string; warning: string }>('/api/connections/composio', 'POST', { api_key: apiKey.trim(), enabled: false }),
+ /** #548: a new key for the saved setup. */
+ replaceComposioKey: (apiKey: string) => call<{ mode?: string }>('/api/connections/composio/key', 'PUT', { api_key: apiKey.trim() }),
+ /** #548: moves a pasted-link setup to the one-key setup; the key only when none is saved. */
+ switchComposio: (apiKey?: string) =>
+ call<{ mode?: string }>('/api/connections/composio/switch', 'POST', apiKey?.trim() ? { api_key: apiKey.trim() } : {}),
+ composioAppList,
+ searchDirectory,
+ /** Adds a public-directory entry with the values the person filled in. */
+ installFromDirectory: (registryName: string, name: string, env: Record<string, string>, headers: Record<string, string>) =>
+ call<{ server?: { id: string } }>('/api/mcp/registry/install', 'POST', { registry_name: registryName, name, env, headers }),
/** Searches Composio's apps with the person's own Composio key (only once Composio is added). */
searchComposioApps: (q: string) =>
call<{ apps: ComposioApp[]; can_connect: boolean; warning: string }>(`/api/connections/composio/apps?q=${enc(q)}`),
@@ -235,7 +357,7 @@ export const isComposioUrl = (raw: string): boolean => {
};
export interface ComposioBody {
- url: string;
+ url?: string;
api_key?: string;
enabled: boolean;
}
diff --git a/frontend/src/mcp.ts b/frontend/src/mcp.ts
index f456a187..d88d5e1b 100644
--- a/frontend/src/mcp.ts
+++ b/frontend/src/mcp.ts
@@ -829,3 +829,12 @@ export const kwantUsage = (
/** A new kwant starts with every server on, the same as the backend default. */
export const defaultKwantServerIds = (servers: Array<Pick<McpServer, 'id'>>): string[] => servers.map((s) => s.id);
+
+/** Opens Add a tool from elsewhere (Apps & accounts' Find a tool): on a built-in tool's form, a
+ * public-directory listing's form, or Add by address. App.tsx listens. */
+export const OPEN_ADD_TOOL_EVENT = 'kwant:open-add-tool';
+export interface OpenAddTool {
+ preset?: string;
+ directory?: import('./connections').DirectoryEntry;
+ address?: boolean;
+}
diff --git a/frontend/src/toolSearch.ts b/frontend/src/toolSearch.ts
new file mode 100644
index 00000000..a1c0827d
--- /dev/null
+++ b/frontend/src/toolSearch.ts
@@ -0,0 +1,165 @@
+// Find a tool's matching (composio-simple/autocomplete.md, design.md "Autocomplete"): one rule for
+// built-in tools, Composio's apps and the public directory, run in the browser on every key.
+//
+// Matching ignores case, spaces, dashes, dots and accents ("google sheets" = "googlesheets").
+// Rank: the name starts with the query > a word in it does > an alias > the slug > the name contains
+// it (2+ characters) > a typo (1 edit from 4 characters, 2 from 8). One character only matches the
+// start of the name or of a word in it.
+
+export type MatchKind = 'start' | 'word' | 'alias' | 'slug' | 'contains' | 'typo';
+
+export interface ToolEntry {
+ name: string;
+ slug?: string;
+}
+
+export interface ToolMatch {
+ kind: MatchKind;
+ /** Lower ranks first. */
+ rank: number;
+ /** The typed letters inside the name, [from, to) in the name as written; none for alias, slug and typo matches. */
+ bold: [number, number] | null;
+}
+
+const RANK: Record<MatchKind, number> = { start: 0, word: 1, alias: 2, slug: 3, contains: 4, typo: 5 };
+
+/** Other names people type for an app, by the app's normalized name or slug. */
+export const TOOL_ALIASES: Record<string, string[]> = {
+ gmail: ['google mail'],
+ googlecalendar: ['gcal', 'calendar'],
+ googlesheets: ['sheets'],
+ googledocs: ['docs'],
+ googledrive: ['drive'],
+ elevenlabs: ['11labs', 'eleven'],
+ microsoftteams: ['teams'],
+ x: ['twitter'],
+ twitter: ['twitter'],
+ postgresql: ['postgres', 'pg'],
+ postgres: ['postgres', 'pg'],
+};
+
+const SKIPPED = /[\s\-._/'’&,:()+]/;
+
+/** Lowercase, no accents, no spaces, dashes or dots. */
+export const normalize = (s: string): string => normalizeWithMap(s).text;
+
+/** The normalized text, and for each of its characters the index of the character it came from. */
+function normalizeWithMap(s: string): { text: string; from: number[] } {
+ let text = '';
+ const from: number[] = [];
+ for (let i = 0; i < s.length; i++) {
+ const ch = s[i];
+ if (SKIPPED.test(ch)) continue;
+ const plain = ch.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase();
+ for (const c of plain) {
+ text += c;
+ from.push(i);
+ }
+ }
+ return { text, from };
+}
+
+/** Where a normalized range [a, b) sits in the name as written. */
+function spanOf(from: number[], a: number, b: number): [number, number] {
+ return [from[a], from[b - 1] + 1];
+}
+
+/** Optimal string alignment distance (a swap of two letters is one edit), stopping early above `max`. */
+export function editDistance(a: string, b: string, max = 2): number {
+ if (Math.abs(a.length - b.length) > max) return max + 1;
+ const rows: number[][] = [];
+ for (let i = 0; i <= a.length; i++) {
+ rows.push(new Array(b.length + 1).fill(0));
+ rows[i][0] = i;
+ }
+ for (let j = 0; j <= b.length; j++) rows[0][j] = j;
+ for (let i = 1; i <= a.length; i++) {
+ let best = Infinity;
+ for (let j = 1; j <= b.length; j++) {
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
+ let v = Math.min(rows[i - 1][j] + 1, rows[i][j - 1] + 1, rows[i - 1][j - 1] + cost);
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) v = Math.min(v, rows[i - 2][j - 2] + 1);
+ rows[i][j] = v;
+ best = Math.min(best, v);
+ }
+ if (best > max) return max + 1;
+ }
+ return rows[a.length][b.length];
+}
+
+/** Indices (in the normalized name) where a word of the name starts, the first word excluded. */
+function wordStarts(name: string, from: number[]): number[] {
+ const starts: number[] = [];
+ for (let k = 1; k < from.length; k++) {
+ const i = from[k];
+ if (i === from[k - 1]) continue;
+ const prev = name[i - 1];
+ const cur = name[i];
+ const afterGap = i > 0 && SKIPPED.test(prev);
+ // "ElevenLabs", "PostHog": a capital after a small letter starts a word too.
+ const camel = /[a-z]/.test(prev ?? '') && /[A-Z]/.test(cur);
+ const digitEdge = /[0-9]/.test(prev ?? '') !== /[0-9]/.test(cur);
+ if (afterGap || camel || digitEdge) starts.push(k);
+ }
+ return starts;
+}
+
+const aliasesOf = (entry: ToolEntry): string[] => {
+ const keys = new Set([normalize(entry.name), entry.slug ? normalize(entry.slug) : '']);
+ const out: string[] = [];
+ keys.forEach((k) => k && TOOL_ALIASES[k]?.forEach((a) => out.push(normalize(a))));
+ return out;
+};
+
+/** How `query` matches `entry`, or null. */
+export function matchTool(query: string, entry: ToolEntry): ToolMatch | null {
+ const q = normalize(query);
+ if (!q) return null;
+ const { text: name, from } = normalizeWithMap(entry.name);
+ const hit = (kind: MatchKind, at?: number): ToolMatch => ({
+ kind,
+ rank: RANK[kind],
+ bold: at === undefined ? null : spanOf(from, at, at + q.length),
+ });
+ if (name.startsWith(q)) return hit('start', 0);
+ const word = wordStarts(entry.name, from).find((k) => name.startsWith(q, k));
+ if (word !== undefined) return hit('word', word);
+ if (q.length < 2) return null;
+ if (aliasesOf(entry).some((a) => a.startsWith(q))) return hit('alias');
+ const slug = entry.slug ? normalize(entry.slug) : '';
+ if (slug && slug !== name && slug.startsWith(q)) return hit('slug');
+ const inside = name.indexOf(q);
+ if (inside >= 0) return hit('contains', inside);
+ if (q.length < 4) return null;
+ const max = q.length >= 8 ? 2 : 1;
+ // A typo in a whole name, or in the part typed so far ("gmial" → Gmail, "notoin" → Notion, "slak" → Slack).
+ const candidates = [name, ...[-1, 0, 1].map((d) => name.slice(0, q.length + d)).filter((p) => p.length >= 3)];
+ if (candidates.some((c) => editDistance(q, c, max) <= max)) return hit('typo');
+ return null;
+}
+
+/**
+ * The rest of `name` after what was typed, for the ghost completion, or '' when the name doesn't
+ * start with it. "gm" + "Gmail" → "ail"; "google s" + "Google Sheets" → "heets".
+ */
+export function ghostRest(query: string, name: string): string {
+ const q = normalize(query);
+ const { text, from } = normalizeWithMap(name);
+ if (!q || !text.startsWith(q)) return '';
+ const lastTyped = from[q.length - 1];
+ return name.slice(lastTyped + 1);
+}
+
+/** The rows of a group that match, best first. `tie` breaks equal ranks: higher first. */
+export function rankTools<T extends ToolEntry>(query: string, entries: T[], tie: (e: T) => number = () => 0): Array<{ entry: T; match: ToolMatch }> {
+ const out: Array<{ entry: T; match: ToolMatch; i: number }> = [];
+ entries.forEach((entry, i) => {
+ const match = matchTool(query, entry);
+ if (match) out.push({ entry, match, i });
+ });
+ out.sort((a, b) => a.match.rank - b.match.rank || tie(b.entry) - tie(a.entry) || a.i - b.i);
+ return out.map(({ entry, match }) => ({ entry, match }));
+}
+
+/** "{n} suggestions" for the live line. */
+export const suggestionsLine = (n: number): string => (n === 0 ? 'No suggestions' : n === 1 ? '1 suggestion' : `${n} suggestions`);
diff --git a/frontend/tests/appsAccounts.test.mjs b/frontend/tests/appsAccounts.test.mjs
index 7577d635..d6aa2317 100644
--- a/frontend/tests/appsAccounts.test.mjs
+++ b/frontend/tests/appsAccounts.test.mjs
@@ -14,6 +14,7 @@ for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLInputEle
}
g.window.matchMedia ??= () => ({ matches: false, addEventListener() {}, removeEventListener() {} });
g.window.HTMLElement.prototype.scrollIntoView ??= () => {};
+g.CSS ??= { escape: (x) => String(x).replace(/[^\w-]/g, (c) => '\\' + c) };
const m = await loadBundled(`
export * from './src/appsAccounts';
@@ -106,61 +107,61 @@ const sheetProps = (over = {}) => ({
test('the sheet says what bots can do and that it goes through Composio, then shows three steps with no bot ticked', () => {
const html = m.renderToStaticMarkup(h(m.ConnectSheet, sheetProps()));
- for (const t of ['Connect Gmail', 'Your bots will be able to', 'Read and search your mail', 'Through Composio, a service with a free plan', 'Open Composio', 'Paste your Composio link', 'Which bots get it?', 'None until you tick one.']) {
+ for (const t of ['Connect Gmail', 'Your bots will be able to', 'Read and search your mail', 'Through Composio, a service with a free plan', 'Add your free Composio key', 'Composio API key', 'Get a free key', 'Sign in to Gmail', 'Which bots get it?', 'None until you tick one.', 'Free plan: 10,000 tool calls a month.']) {
assert.ok(html.includes(t), `sheet shows "${t}"`);
}
assert.equal((html.match(/data-sheet-step="/g) ?? []).length, 3);
assert.ok(!/type="checkbox"[^>]*checked/.test(html), 'no bot is preselected');
assert.match(html, /role="dialog"/);
assert.match(html, /aria-modal="true"/);
- assert.ok(html.includes('MCP</span> in the left menu'), 'step 2 says where the link is');
+ for (const t of ['MCP', 'Composio link', 'user_id', 'toolkit', 'server URL', 'connector']) assert.ok(!html.includes(t), `no "${t}" on the main path`);
+ assert.ok(html.includes('href="https://dashboard.composio.dev"'), 'the key link goes to the Composio dashboard');
assert.ok(!html.includes('Turn on in Tools'));
});
-test('a bad link stops at step 2 with words, and no bot stops at step 3', async () => {
+test('no key stops at step 1 with words, and no bot stops at step 3', async () => {
const api = fakeApi();
const host = await mount(m.ConnectSheet, sheetProps({ api }));
await submit(host);
- assert.match(text(host.querySelector('[data-sheet-error="2"]')), /^Paste your Composio link first\. It’s under MCP in Composio\.$/);
- await type(host.querySelector('input[type="url"]'), 'https://example.com/mcp');
- await submit(host);
- assert.match(text(host.querySelector('[data-sheet-error="2"]')), /^That isn’t a Composio link\. Copy the one under MCP in Composio; it starts with https:\/\/ and is on composio\.dev\.$/);
- await type(host.querySelector('input[type="url"]'), 'https://backend.composio.dev/v3/mcp/abc');
+ assert.match(text(host.querySelector('[data-sheet-error="1"]')), /^Paste your Composio API key first\./);
+ await type(host.querySelector('[data-sheet-step="1"] input'), 'ck_abc');
+ assert.equal(host.querySelector('[data-sheet-error="1"]'), null, 'typing clears the key error');
await submit(host);
assert.match(text(host.querySelector('[data-sheet-error="3"]')), /Tick at least one bot/);
+ await click(host.querySelector('[data-sheet-bot] input'));
+ assert.equal(host.querySelector('[data-sheet-error="3"]'), null, 'ticking a bot clears the bot error');
assert.deepEqual(api.calls, [], 'nothing is sent until the form is whole');
});
-test('fixing the link or ticking a bot clears that step’s error at once', async () => {
- const host = await mount(m.ConnectSheet, sheetProps({ api: fakeApi() }));
- await type(host.querySelector('input[type="url"]'), 'https://example.com/mcp');
- await submit(host);
- assert.ok(host.querySelector('[data-sheet-error="2"]'));
- await type(host.querySelector('input[type="url"]'), 'https://backend.composio.dev/v3/mcp/abc');
- assert.equal(host.querySelector('[data-sheet-error="2"]'), null, 'the old link error goes as soon as the link changes');
- await submit(host);
- assert.ok(host.querySelector('[data-sheet-error="3"]'));
- await click(host.querySelector('[data-sheet-bot] input'));
- assert.equal(host.querySelector('[data-sheet-error="3"]'), null, 'ticking a bot clears the bot error');
+test('Add key saves the key on its own, then the sign-in step opens', async () => {
+ const api = fakeApi();
+ const host = await mount(m.ConnectSheet, sheetProps({ api }));
+ assert.ok(host.querySelector('[data-sheet-signin]') === null, 'no sign-in before the key');
+ await type(host.querySelector('[data-sheet-step="1"] input'), ' ck_abc ');
+ await click(host.querySelector('[data-sheet-add-key]'));
+ assert.deepEqual(api.calls[0], ['add', { api_key: 'ck_abc', enabled: false }], 'added off, for no bot yet');
+ assert.ok(host.querySelector('[data-sheet-key-added]'));
+ assert.ok(host.querySelector('[data-sheet-signin]'), 'Sign in to Gmail is there now');
});
-test('Composio refusing the link shows its reason at step 2', async () => {
+test('Composio refusing the key shows its reason at step 1, next to the key', async () => {
const { ConnectionsError } = await loadBundled(`export { ConnectionsError } from './src/connections';`);
- const api = fakeApi({ addComposio: async () => { throw new ConnectionsError('Composio didn’t answer.', 400); } });
- const host = await mount(m.ConnectSheet, sheetProps({ api, initial: { url: 'https://backend.composio.dev/v3/mcp/abc', picked: ['k1'] } }));
+ const api = fakeApi({ addComposio: async () => { throw new ConnectionsError('Composio didn’t accept this key. Copy your key again from your Composio dashboard.', 400); } });
+ const host = await mount(m.ConnectSheet, sheetProps({ api, initial: { key: 'ck_bad', picked: ['k1'] } }));
await submit(host);
- assert.match(text(host.querySelector('[data-sheet-error="2"]')), /Composio didn’t answer/);
+ assert.match(text(host.querySelector('[data-sheet-error="1"]')), /Composio didn’t accept this key\. .*Open your API keys/);
+ assert.equal(host.querySelector('[data-sheet-step="1"] input').getAttribute('aria-invalid'), 'true');
});
test('picking one bot adds Composio and gives it to just that bot, then says so', async () => {
const api = fakeApi();
let done = null;
const host = await mount(m.ConnectSheet, sheetProps({ api, onDone: (r) => (done = r) }));
- await type(host.querySelector('input[type="url"]'), 'https://backend.composio.dev/v3/mcp/abc');
+ await type(host.querySelector('[data-sheet-step="1"] input'), 'ck_abc');
await click(host.querySelector('[data-sheet-bot="k1"] input'));
assert.match(text(host), /Ann gets it, turned on/);
await submit(host);
- assert.deepEqual(api.calls[0], ['add', { url: 'https://backend.composio.dev/v3/mcp/abc', enabled: false }], 'added off: only the picks turn it on');
+ assert.deepEqual(api.calls[0], ['add', { api_key: 'ck_abc', enabled: false }], 'added off: only the picks turn it on');
assert.deepEqual(api.calls[1], ['give', 'cmp1', ['k1', 'k2', 'k3'], ['k1']]);
assert.deepEqual({ app: done.app.slug, who: done.who }, { app: 'gmail', who: ['Ann'] }, 'the page words the result once it knows the sign-in');
});
@@ -168,7 +169,7 @@ test('picking one bot adds Composio and gives it to just that bot, then says so'
test('with Composio set up the sheet starts at the app’s own sign-in and the bots that have it now', async () => {
const api = fakeApi();
const host = await mount(m.ConnectSheet, sheetProps({ api, composio: composio({ added: true, enabled: true, connection_id: 'mcp:cmp1', can_connect: true }) }));
- assert.ok(!host.querySelector('input[type="url"]'), 'no link to paste again');
+ assert.ok(!host.querySelector('[data-sheet-add-key]'), 'no key to add again');
assert.equal(host.querySelectorAll('[data-sheet-step]').length, 2);
assert.ok(host.querySelector('[data-sheet-bot="k2"] input').checked, 'Ben has it already');
assert.ok(!host.querySelector('[data-sheet-bot="k1"] input').checked);
@@ -196,7 +197,7 @@ test('a refused Composio key says so and doesn’t blame an outage', async () =>
g.window.open = () => null;
await click(host.querySelector('[data-sheet-signin]'));
const t = text(host.querySelector('[data-sheet-error="1"]'));
- assert.match(t, /refused your API key.*Advanced › Manage tools/);
+ assert.match(t, /Composio didn’t accept your saved key, so the Gmail sign-in can’t start\. Replace the key on the Composio tile under Advanced\./);
assert.doesNotMatch(t, /may be down/);
});
@@ -296,7 +297,7 @@ const pageProps = (over = {}) => ({
manageAccounts: () => h('p', null, 'MANAGE'), advanced: () => h('p', null, 'ADVANCED'), phone: false, ...over,
});
-test('the page puts app tiles first, then another app, AI accounts, and a closed Advanced', () => {
+test('the page puts app tiles first, then Find a tool, AI accounts, and a closed Advanced', () => {
const html = m.renderToStaticMarkup(h(m.AppsAccounts, pageProps()));
const order = ['data-apps-tiles', 'data-apps-search', 'data-ai-accounts', 'data-apps-advanced'].map((k) => html.indexOf(k));
assert.ok(order.every((i, n) => i > 0 && (n === 0 || i > order[n - 1])), `order ${order}`);
@@ -320,8 +321,10 @@ test('the page puts app tiles first, then another app, AI accounts, and a closed
const tints = [...html.matchAll(/data-app-mark-tint="([^"]+)"/g)].map((x) => x[1]);
assert.equal(new Set(tints).size, 6, `six tints: ${tints}`);
assert.equal((html.match(/line-clamp-2/g) ?? []).length, 6);
- // F8: phone-sized targets on the page's buttons.
- assert.match(html, /min-h-\[44px\] sm:min-h-\[32px\]/);
+ // F8: phone-sized targets on the page's buttons, and Find a tool's field is 44 px on a phone (40 px from sm, design §1).
+ assert.match(html, /min-h-\[44px\]/);
+ const search = html.slice(html.indexOf('data-apps-search'), html.indexOf('data-ai-accounts'));
+ assert.match(search, /<input[^>]*class="[^"]*h-11 sm:h-10[^"]*"[^>]*data-find-input/);
});
test('a tile opens the Connect sheet and Escape closes it', async () => {
@@ -414,18 +417,19 @@ test('F4: bot chips show the bot’s face and step 3 says Composio is one connec
assert.match(html, /data-sheet-one-connection="true">Composio is one connection: the bots you tick can use every app on it, not only Gmail\./);
});
-test('F5: the link error sits right under the field and is read with it; a good link ticks step 2', async () => {
+test('F5: the key error sits right under the field and is read with it; an added key ticks step 1', async () => {
const host = await mount(m.ConnectSheet, sheetProps({ api: fakeApi() }));
- const input = host.querySelector('input[type="url"]');
+ const input = host.querySelector('[data-sheet-step="1"] input');
await submit(host);
- const err = host.querySelector('[data-sheet-error="2"]');
+ const err = host.querySelector('[data-sheet-error="1"]');
assert.equal(err.getAttribute('role'), 'alert');
assert.ok(input.getAttribute('aria-describedby').split(' ').includes(err.id));
assert.equal(input.getAttribute('aria-invalid'), 'true');
const after = [...input.closest('[data-sheet-step]').querySelectorAll('*')];
assert.ok(after.indexOf(err) > after.indexOf(input), 'error after the input');
- await type(input, 'https://backend.composio.dev/v3/mcp/abc');
- assert.equal(host.querySelector('[data-sheet-step="2"]').getAttribute('data-done'), 'true');
+ await type(input, 'ck_abc');
+ await click(host.querySelector('[data-sheet-add-key]'));
+ assert.equal(host.querySelector('[data-sheet-step="1"]').getAttribute('data-done'), 'true');
});
test('Sign-ins and settings has no account list of its own: no "What runs your kwant bots" there', () => {
diff --git a/frontend/tests/composioTile.test.mjs b/frontend/tests/composioTile.test.mjs
new file mode 100644
index 00000000..a95b68dd
--- /dev/null
+++ b/frontend/tests/composioTile.test.mjs
@@ -0,0 +1,231 @@
+// The Composio tile (composio-simple/design.md §3): one key adds it, status chip and facts, Replace
+// key, Turn off, Remove asks inline with Keep it focused, the old link mode offers the switch, a
+// refused key opens the field with the fix, and the main path never says MCP or header.
+import assert from 'node:assert/strict';
+import test, { afterEach } from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLInputElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'FocusEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+g.window.matchMedia ??= () => ({ matches: false, addEventListener() {}, removeEventListener() {} });
+g.window.HTMLElement.prototype.scrollIntoView ??= () => {};
+
+const m = await loadBundled(`
+ export { ComposioTile, shortList, removeQuestion } from './src/components/ComposioTile';
+ export { ConnectionsError } from './src/connections';
+ export { createRoot } from 'react-dom/client';
+ export { createElement } from 'react';
+`);
+const h = m.createElement;
+const PLUMBING = /\b(MCP|header|user_id|toolkit|server URL|connector)\b/i;
+
+const entry = (over = {}) => ({
+ id: 'composio', kind: 'mcp', name: 'Composio', description: '', optional: true, added: false, connection_id: null, enabled: false,
+ logins_stored: 'composio', warning: '', add: '/api/connections/composio', key_url: 'https://dashboard.composio.dev', ...over,
+});
+const added = (over = {}) =>
+ entry({ added: true, enabled: true, connection_id: 'mcp:cmp1', mode: 'connect', apps_connected: [{ slug: 'gmail', name: 'Gmail' }, { slug: 'slack', name: 'Slack' }], ...over });
+
+const stubApi = (over = {}) => {
+ const calls = [];
+ const api = {
+ addKey: async (k) => void calls.push(['addKey', k]),
+ replaceKey: async (k) => void calls.push(['replaceKey', k]),
+ switchTo: async (k) => void calls.push(['switchTo', k ?? null]),
+ setEnabled: async (id, on) => void calls.push(['setEnabled', id, on]),
+ remove: async (id) => void calls.push(['remove', id]),
+ ...over,
+ };
+ return { api, calls };
+};
+
+const mounted = new Set();
+afterEach(() => {
+ for (const u of mounted) u();
+ document.body.replaceChildren();
+});
+const settle = async () => {
+ for (let i = 0; i < 20; i++) await new Promise((r) => setTimeout(r, 0));
+};
+const mount = async (props) => {
+ const host = document.createElement('ul');
+ document.body.appendChild(host);
+ const root = m.createRoot(host);
+ root.render(h(m.ComposioTile, { usedBy: [], onAddLink: async () => null, ...props }));
+ await settle();
+ const u = () => {
+ if (!mounted.delete(u)) return;
+ root.unmount();
+ host.remove();
+ };
+ mounted.add(u);
+ return host;
+};
+const text = (el) => el.textContent.replace(/\s+/g, ' ').trim();
+const click = async (el) => {
+ el.dispatchEvent(new window.MouseEvent('click', { bubbles: true, cancelable: true }));
+ await settle();
+};
+const fill = async (el, value) => {
+ Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set.call(el, value);
+ el.dispatchEvent(new window.Event('input', { bubbles: true }));
+ await settle();
+};
+const submit = async (form) => {
+ form.dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));
+ await settle();
+};
+
+test('names and lists stay short', () => {
+ assert.equal(m.shortList(['Ann']), 'Ann');
+ assert.equal(m.shortList(['Ann', 'Ben']), 'Ann and Ben');
+ assert.equal(m.shortList(['Ann', 'Ben', 'Cy', 'Di']), 'Ann, Ben and 2 more');
+ assert.equal(m.shortList(['Gmail', 'Slack'], 'or'), 'Gmail or Slack');
+ assert.equal(m.removeQuestion(['Ada'], ['Gmail', 'Slack']), 'Remove Composio? Ada loses Gmail and Slack. Your sign-ins stay on Composio, so you can add it back later.');
+ assert.equal(m.removeQuestion([], []), 'Remove Composio? Your sign-ins stay on Composio, so you can add it back later.');
+});
+
+test('not added: one key field adds it, and the link form hides under advanced', async () => {
+ const { api, calls } = stubApi();
+ let changed = 0;
+ const host = await mount({ entry: entry(), api, onChanged: () => changed++ });
+ assert.equal(host.querySelector('[data-composio-tile]').dataset.composioTile, 'new');
+ assert.ok(!PLUMBING.test(text(host)), 'no plumbing words');
+ await click(host.querySelector('[data-composio-add]'));
+ const field = host.querySelector('input[type="password"]');
+ assert.ok(field, 'the key field opens');
+ assert.ok(!PLUMBING.test(text(host)), 'no plumbing words with the field open');
+ assert.ok(!host.querySelector('[data-composio-link-form]'));
+ await fill(field, 'ck_test');
+ await submit(field.form);
+ assert.deepEqual(calls, [['addKey', 'ck_test']]);
+ assert.equal(changed, 1);
+ assert.match(text(host.querySelector('[data-composio-notice]')), /Composio is added\. No bot has it until you choose bots\./);
+});
+
+test('the advanced link form is the only place that says MCP', async () => {
+ const links = [];
+ const host = await mount({ entry: entry(), initialOpen: 'add', onAddLink: async (u, k, on) => (links.push([u, k, on]), 'Composio already added.') });
+ const toggle = host.querySelector('[data-composio-link-toggle]');
+ assert.equal(text(toggle), 'Use a Composio link instead (advanced)');
+ assert.equal(toggle.getAttribute('aria-expanded'), 'false');
+ await click(toggle);
+ const form = host.querySelector('[data-composio-link-form]');
+ assert.ok(form && text(form).includes('Composio MCP URL'));
+ await fill(form.querySelector('input[type="url"]'), ' https://backend.composio.dev/v3/mcp/x ');
+ await submit(form);
+ assert.deepEqual(links, [['https://backend.composio.dev/v3/mcp/x', '', false]]);
+ assert.equal(text(form.querySelector('[role="alert"]')), 'Composio already added.');
+});
+
+test('on: chip, facts, and Choose bots · Replace key · Turn off · Remove', async () => {
+ const host = await mount({ entry: added(), usedBy: ['Ada', 'Lin'], onChooseBots() {}, api: stubApi().api });
+ assert.equal(text(host.querySelector('[data-composio-chip]')), 'Added · on');
+ assert.equal(text(host.querySelector('[data-fact="apps"] dd')), 'Gmail and Slack');
+ assert.equal(text(host.querySelector('[data-fact="used-by"] dd')), 'Ada and Lin');
+ const buttons = [...host.querySelectorAll('button')].map(text);
+ assert.deepEqual(buttons, ['Choose bots', 'Replace key', 'Turn off', 'Remove']);
+ assert.ok(text(host).includes('Gmail and hundreds more apps. Your bots find the app they need by themselves.'));
+ assert.ok(!PLUMBING.test(text(host)));
+});
+
+test('off: the primary action is Choose bots to turn it on, and no Turn off', async () => {
+ const host = await mount({ entry: added({ enabled: false, apps_connected: [] }), onChooseBots() {}, api: stubApi().api });
+ assert.equal(text(host.querySelector('[data-composio-chip]')), 'Added · off');
+ assert.deepEqual([...host.querySelectorAll('button')].map(text), ['Choose bots to turn it on', 'Replace key', 'Remove']);
+ assert.equal(text(host.querySelector('[data-fact="apps"] dd')), 'None yet. Find one with Find a tool above.');
+ assert.equal(text(host.querySelector('[data-fact="used-by"] dd')), 'No bot yet');
+});
+
+test('Turn off and Replace key call the server with the right thing', async () => {
+ const { api, calls } = stubApi();
+ const host = await mount({ entry: added(), api });
+ await click(host.querySelector('[data-composio-off]'));
+ assert.deepEqual(calls.at(-1), ['setEnabled', 'cmp1', false]);
+ await click(host.querySelector('[data-composio-replace]'));
+ const field = host.querySelector('input[type="password"]');
+ assert.ok(text(host).includes('New Composio API key'));
+ assert.ok(text(host).includes('A key from another Composio project starts fresh there, so you’d connect Gmail and Slack again.'));
+ await fill(field, 'ck_new');
+ await submit(field.form);
+ assert.deepEqual(calls.at(-1), ['replaceKey', 'ck_new']);
+});
+
+test('Remove asks inline, focuses Keep it, and only removes on Remove Composio', async () => {
+ const { api, calls } = stubApi();
+ const host = await mount({ entry: added(), usedBy: ['Ada'], api });
+ await click(host.querySelector('[data-composio-remove]'));
+ const ask = host.querySelector('[data-composio-remove-ask]');
+ assert.ok(text(ask).startsWith('Remove Composio? Ada loses Gmail and Slack. Your sign-ins stay on Composio, so you can add it back later.'));
+ assert.equal(document.activeElement, host.querySelector('[data-composio-keep]'));
+ await click(host.querySelector('[data-composio-keep]'));
+ assert.ok(!host.querySelector('[data-composio-remove-ask]'));
+ assert.equal(calls.length, 0);
+ await click(host.querySelector('[data-composio-remove]'));
+ await click(host.querySelector('[data-composio-remove-yes]'));
+ assert.deepEqual(calls, [['remove', 'cmp1']]);
+});
+
+test('a failed Remove says so next to the Remove button', async () => {
+ const { api } = stubApi({ remove: async () => { throw new Error('Couldn’t remove it. Try again.'); } });
+ const host = await mount({ entry: added(), api });
+ await click(host.querySelector('[data-composio-remove]'));
+ await click(host.querySelector('[data-composio-remove-yes]'));
+ const err = host.querySelector('[data-composio-remove-ask] [data-tile-error="remove"]');
+ assert.ok(err && err.getAttribute('role') === 'alert');
+});
+
+test('a refused saved key: rose line, the key field already open with no Cancel, then Turn off · Remove', async () => {
+ const host = await mount({
+ entry: added({ problem: { message: 'Composio refused the key.', action: 'replace_key' } }),
+ usedBy: ['Ada'],
+ api: stubApi().api,
+ });
+ assert.equal(text(host.querySelector('[data-composio-chip]')), 'Key not accepted');
+ assert.equal(text(host.querySelector('[data-composio-refused]')), 'Composio didn’t accept the saved key, so Ada can’t use Gmail or Slack right now. Paste a new key to fix it.');
+ assert.ok(host.querySelector('input[type="password"]'));
+ const buttons = [...host.querySelectorAll('button')].map(text);
+ assert.ok(!buttons.includes('Cancel'));
+ assert.ok(buttons.includes('Save key') && buttons.includes('Turn off') && buttons.includes('Remove'));
+ assert.ok(text(host).includes('your Composio dashboard') || text(host).includes('From your Composio dashboard'));
+});
+
+test('Composio down while listing apps: says so with Try again in the facts', async () => {
+ let changed = 0;
+ const host = await mount({ entry: added({ problem: { message: 'down', action: 'try_again' }, apps_connected: [] }), api: stubApi().api, onChanged: () => changed++ });
+ assert.ok(text(host.querySelector('[data-fact="apps"]')).includes('Couldn’t reach Composio to list them.'));
+ await click(host.querySelector('[data-composio-retry]'));
+ assert.equal(changed, 1);
+});
+
+test('the old link setup offers the switch; with no saved key it asks for one right there', async () => {
+ const { api, calls } = stubApi({
+ switchTo: async (k) => {
+ calls.push(['switchTo', k ?? null]);
+ if (!k) throw new m.ConnectionsError('needs a key', 400);
+ },
+ });
+ const host = await mount({ entry: added({ mode: 'url', can_switch: true }), api });
+ assert.equal(text(host.querySelector('[data-fact="setup"] dd')), 'a Composio link');
+ assert.ok(text(host.querySelector('[data-composio-switch]')).startsWith('Switch to the one-key setup to connect apps right here.'));
+ assert.ok(!host.querySelector('[data-composio-replace]'), 'no Replace key in link mode');
+ await click(host.querySelector('[data-composio-switch-go]'));
+ assert.ok(host.querySelector('[data-composio-switch-needs-key]'));
+ const field = host.querySelector('input[type="password"]');
+ await fill(field, 'ck_k');
+ await submit(field.form);
+ assert.deepEqual(calls, [['switchTo', null], ['switchTo', 'ck_k']]);
+ assert.equal(text(host.querySelector('[data-composio-notice]')), 'Switched to the one-key setup. Gmail and Slack are still connected.');
+});
+
+test('the footer always says where sign-ins live', async () => {
+ for (const e of [entry(), added(), added({ enabled: false })]) {
+ const host = await mount({ entry: e, api: stubApi().api });
+ assert.equal(text(host.querySelector('[data-composio-footer]')), 'Your app sign-ins stay on Composio’s servers, not in this app’s vault.');
+ }
+});
diff --git a/frontend/tests/connections.test.mjs b/frontend/tests/connections.test.mjs
index 7dc271f0..b7faab5b 100644
--- a/frontend/tests/connections.test.mjs
+++ b/frontend/tests/connections.test.mjs
@@ -98,12 +98,13 @@ test('a Composio connection is marked as storing its login on Composio’s serve
assert.ok(html.includes('text-amber-200'));
});
-test('the page groups rows, counts them, and offers Composio as optional with its warning', () => {
+test('the page groups rows, counts them, and offers Composio with where it keeps sign-ins', () => {
const html = ui.view(viewProps({ onOpenTools: noop, onOpenAccounts: noop, onOpenLooseEnds: noop }));
- for (const t of ['Connections', '2 connected · 2 need you', 'Tool servers (MCP)', 'Engine accounts', 'Saved website logins', 'Mail and GitHub (Loose ends)', 'Out of quota until 14:00', 'Open Loose ends', 'Optional connectors', 'Composio', 'Optional', 'Add Composio']) {
+ for (const t of ['Connections', '2 connected · 2 need you', 'Tool servers (MCP)', 'Engine accounts', 'Saved website logins', 'Mail and GitHub (Loose ends)', 'Out of quota until 14:00', 'Open Loose ends', 'Optional connectors', 'Composio', 'Add Composio']) {
assert.ok(html.includes(t), `page shows "${t}"`);
}
- assert.ok(html.includes('Composio keeps your app sign-ins on Composio&#x27;s servers'), 'the warning is next to the add button');
+ assert.ok(html.includes('data-composio-tile="new"'), 'Composio is the one-key tile (design.md §3)');
+ assert.ok(html.includes('Your app sign-ins stay on Composio’s servers, not in this app’s vault.'), 'the footer says where sign-ins live');
});
test('the add form is off by default and repeats nothing secret', () => {
@@ -194,22 +195,19 @@ test('the search and connect calls go to kwnt, never straight to Composio', asyn
]);
});
-test('the server catalog lists Gmail as "via Composio" and explains why, with the warning', async () => {
+test('Add a tool is Find a tool over the built-in grid, with Add by address, and never says MCP', async () => {
const cat = await loadBundled(`
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server.browser';
- import { PresetCatalog } from './src/components/McpServersModal';
- export const render = (props) => renderToStaticMarkup(React.createElement(PresetCatalog, props));
+ import { AddToolPicker } from './src/components/McpServersModal';
+ export const render = (props) => renderToStaticMarkup(React.createElement(AddToolPicker, props));
`);
- const base = { query: 'gmail', onQuery: noop, onPick: noop, onCustom: noop, onOpenConnections: noop };
- const list = cat.render(base);
- assert.ok(list.includes('Gmail') && list.includes('via Composio'));
- const open = cat.render({ ...base, initialComposioApp: 'gmail' });
- assert.ok(open.includes('data-composio-note="gmail"') && open.includes('Open Connections'));
- assert.ok(open.includes('not in this app’s vault'));
- // The open card must not stretch to the item's full height, or the note spills over the next section.
- const card = open.slice(open.lastIndexOf('<button', open.indexOf('aria-expanded="true"')), open.indexOf('data-composio-note="gmail"'));
- assert.ok(!/class="[^"]*\bh-full\b/.test(card.slice(0, card.indexOf('>'))), 'open Composio card is not h-full');
+ const api = { list: async () => ({ connections: [], catalog: [] }), apps: async () => ({ apps: [] }), addKey: noop, replaceKey: noop, connect: noop, directory: async () => null };
+ const html = cat.render({ onPick: noop, onCustom: noop, onDirectory: noop, onChooseBots: noop, findApi: api });
+ assert.ok(html.includes('placeholder="Find a tool, like gmail, stripe or a database"'));
+ assert.ok(html.includes('All built-in tools') && html.includes('data-builtin-grid'));
+ assert.ok(html.includes('Add by address') && html.includes('Paste a command or web address from any tool’s instructions.'));
+ assert.ok(!/MCP|Custom server|server URL|connector/.test(html.replace(/<[^>]+>/g, ' ')), 'no MCP words on the main path');
});
// Oleks (2026-10-28): "why is there no way to connect new tools here?" The header gets "+ Add
diff --git a/frontend/tests/findTool.test.mjs b/frontend/tests/findTool.test.mjs
new file mode 100644
index 00000000..a30328ed
--- /dev/null
+++ b/frontend/tests/findTool.test.mjs
@@ -0,0 +1,435 @@
+// Find a tool (composio-simple/design.md §1, §2, "Autocomplete"): suggestions from the first letter,
+// three groups, the ghost and the keys, Connect before Composio is set up opening the key field under
+// the row, the not-listed line, the public directory hiding on 404, and no plumbing words.
+import assert from 'node:assert/strict';
+import test, { afterEach } from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLInputElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'FocusEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+g.window.matchMedia ??= () => ({ matches: false, addEventListener() {}, removeEventListener() {} });
+g.window.HTMLElement.prototype.scrollIntoView ??= () => {};
+
+const m = await loadBundled(`
+ export { FindTool, buildGroups, directoryNeeds, presetPublisher, markCutDescription } from './src/components/FindTool';
+ export { ConnectionsError, connectionsApi } from './src/connections';
+ export { MCP_PRESETS } from './src/mcp';
+ export { createRoot } from 'react-dom/client';
+ export { createElement } from 'react';
+`);
+const h = m.createElement;
+
+const PLUMBING = /\b(MCP|header|user_id|toolkit|server URL|connector)\b/i;
+
+const composio = (over = {}) => ({
+ id: 'composio', kind: 'mcp', name: 'Composio', description: '', optional: true, added: false, connection_id: null, enabled: false,
+ logins_stored: 'composio', warning: '', add: '/api/connections/composio', ...over,
+});
+const listOf = (entry = composio(), connections = []) => ({ catalog: [entry], connections });
+const APPS = [
+ { slug: 'gmail', name: 'Gmail', tools_count: 61 },
+ { slug: 'googlecalendar', name: 'Google Calendar', tools_count: 46 },
+ { slug: 'googlesheets', name: 'Google Sheets', tools_count: 40 },
+ { slug: 'slack', name: 'Slack', tools_count: 130 },
+ { slug: 'notion', name: 'Notion', tools_count: 44 },
+];
+const DIR = [
+ { registry_name: 'io.example/gmail-tools', title: 'Gmail tools', description: 'Mail from a maker.', publisher: { label: 'example.io' }, kind: 'local', inputs: [{ name: 'API_KEY', secret: true }] },
+];
+
+/** A stub api that records calls. `over` replaces any of its functions. */
+const stubApi = (over = {}) => {
+ const calls = [];
+ const api = {
+ list: async () => (calls.push(['list']), listOf()),
+ apps: async () => (calls.push(['apps']), { apps: APPS, source: 'popular' }),
+ addKey: async (k) => (calls.push(['addKey', k]), {}),
+ replaceKey: async (k) => (calls.push(['replaceKey', k]), {}),
+ connect: async (slug) => (calls.push(['connect', slug]), { redirect_url: `https://connect.example/${slug}` }),
+ directory: async (q) => (calls.push(['directory', q]), null),
+ ...over,
+ };
+ return { api, calls };
+};
+
+// ── DOM helpers ──
+const mounted = new Set();
+afterEach(() => {
+ for (const u of mounted) u();
+ document.body.replaceChildren();
+});
+const settle = async (ms = 0) => {
+ if (ms) await new Promise((r) => setTimeout(r, ms));
+ for (let i = 0; i < 20; i++) await new Promise((r) => setTimeout(r, 0));
+};
+const mount = async (props) => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = m.createRoot(host);
+ root.render(h(m.FindTool, { browseWhenEmpty: false, onAddPreset() {}, onChooseBots() {}, ...props }));
+ await settle();
+ const u = () => {
+ if (!mounted.delete(u)) return;
+ root.unmount();
+ host.remove();
+ };
+ mounted.add(u);
+ return host;
+};
+const text = (el) => el.textContent.replace(/\s+/g, ' ').trim();
+const input = (host) => host.querySelector('[data-find-input]');
+const type = async (host, value, ms = 0) => {
+ const el = input(host);
+ el.focus();
+ Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set.call(el, value);
+ el.setSelectionRange?.(value.length, value.length);
+ el.dispatchEvent(new window.Event('input', { bubbles: true }));
+ await settle(ms);
+};
+const key = async (el, k, opts = {}) => {
+ const ev = new window.KeyboardEvent('keydown', { key: k, bubbles: true, cancelable: true, ...opts });
+ el.dispatchEvent(ev);
+ await settle();
+ return ev;
+};
+const rowNames = (host, group) => [...host.querySelectorAll(`[data-group="${group}"] [data-row-name]`)].map(text);
+const activeRow = (host) => host.querySelector('[data-active]');
+
+test('one letter already suggests, best match first, with the typed letter bold', async () => {
+ const { api } = stubApi();
+ const host = await mount({ api });
+ await type(host, 'g');
+ assert.deepEqual(rowNames(host, 'composio').slice(0, 3), ['Gmail', 'Google Calendar', 'Google Sheets']);
+ assert.ok(host.querySelector('[data-group="builtin"]'), 'built-in tools starting with g (GitHub, Git) are listed too');
+ const first = host.querySelector('[data-group="builtin"] [data-row-name] b');
+ assert.equal(text(first).toLowerCase(), 'g');
+ assert.equal(host.querySelector('[data-group="directory"]'), null, 'the directory waits for two letters');
+});
+
+test('the three groups come in order and say where the tool comes from', async () => {
+ const { api } = stubApi({ directory: async () => ({ entries: DIR, unavailable: false }) });
+ const host = await mount({ api });
+ await type(host, 'gm', 200);
+ const groups = [...host.querySelectorAll('[data-group]')].map((s) => s.dataset.group);
+ assert.deepEqual(groups, ['composio', 'directory']);
+ assert.match(text(host.querySelector('[data-group="composio"]')), /Through Composio.*Sign-ins stay on Composio’s servers/);
+ assert.match(text(host.querySelector('[data-group="directory"]')), /From the public directory.*Listed by their makers, not checked by us/);
+ assert.match(text(host.querySelector('[data-group="directory"] [data-row]')), /by example\.io.*Runs on this computer.*API key/);
+ assert.doesNotMatch(text(host), PLUMBING);
+});
+
+test('typos and other names find the app', async () => {
+ const { api } = stubApi();
+ const host = await mount({ api });
+ for (const [q, name] of [['gmial', 'Gmail'], ['slak', 'Slack'], ['notoin', 'Notion'], ['sheets', 'Google Sheets']]) {
+ await type(host, q);
+ assert.ok(rowNames(host, 'composio').includes(name), `${q} → ${name}`);
+ }
+});
+
+test('"eleven" is not in the list: the not-listed line says bots find other apps themselves', async () => {
+ const { api } = stubApi();
+ const host = await mount({ api });
+ await type(host, 'eleven');
+ const line = host.querySelector('[data-not-listed]');
+ assert.ok(line, 'the not-listed line shows');
+ assert.equal(text(line), 'Not listed? Bots with Composio find its other apps themselves.');
+ assert.equal(host.querySelectorAll('[data-group="composio"] [data-row]').length, 0);
+ assert.equal(host.querySelector('[data-find-nothing]'), null, 'not "nothing found": the line is the answer');
+});
+
+test('Connect before Composio is set up opens the key field under that row, focused', async () => {
+ const { api, calls } = stubApi();
+ const opened = [];
+ window.open = (url) => (opened.push(url), { closed: false, location: {}, close() {} });
+ const host = await mount({ api });
+ await type(host, 'gm');
+ const row = host.querySelector('[data-row-key="composio-c-gmail"]');
+ row.querySelector('[data-row-action]').dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
+ await settle();
+ const setup = host.querySelector('[data-composio-setup="gmail"]');
+ assert.ok(setup, 'the key field opens under Gmail');
+ assert.ok(row.contains(setup), 'inside the row, not somewhere else');
+ assert.equal(row.querySelector('[data-row-action]'), null, 'the row’s Connect button gives way to the field');
+ const field = setup.querySelector('input[type="password"]');
+ assert.equal(document.activeElement, field, 'the key field has focus');
+ assert.equal(text(setup.querySelector(`label[for="${field.id}"]`)), 'Your Composio API key');
+ assert.equal(text(setup.querySelector('[data-key-submit]')), 'Connect Gmail');
+ assert.match(text(setup), /Free plan: 10,000 tool calls a month/);
+ assert.doesNotMatch(text(setup), PLUMBING);
+ assert.equal(opened.length, 0, 'nothing opens before the key is in');
+ assert.equal(calls.filter((c) => c[0] === 'connect').length, 0);
+});
+
+test('Enter on Gmail before setup opens the same field; Esc in it closes it and goes back to the search', async () => {
+ const { api } = stubApi();
+ const host = await mount({ api });
+ await type(host, 'gm');
+ assert.equal(activeRow(host)?.dataset.rowKey, 'composio-c-gmail');
+ await key(input(host), 'Enter');
+ const field = host.querySelector('[data-composio-setup="gmail"] input');
+ assert.equal(document.activeElement, field);
+ await key(field, 'Escape');
+ assert.equal(host.querySelector('[data-composio-setup]'), null);
+ assert.equal(document.activeElement, input(host));
+});
+
+test('a good key adds Composio, then the sign-in opens in the tab opened by the press', async () => {
+ let added = false;
+ const { api, calls } = stubApi({ list: async () => listOf(composio({ added, can_connect: added })) });
+ api.addKey = async (k) => ((added = true), calls.push(['addKey', k]), {});
+ const tab = { closed: false, location: {}, close() {} };
+ const opened = [];
+ window.open = (url) => (opened.push(url), tab);
+ const host = await mount({ api });
+ await type(host, 'gm');
+ await key(input(host), 'Enter');
+ const field = host.querySelector('[data-composio-setup] input');
+ Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set.call(field, 'ck_test');
+ field.dispatchEvent(new window.Event('input', { bubbles: true }));
+ await settle();
+ host.querySelector('[data-key-submit]').closest('form').dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));
+ await settle();
+ assert.deepEqual(calls.find((c) => c[0] === 'addKey'), ['addKey', 'ck_test']);
+ assert.deepEqual(opened, ['about:blank'], 'the tab opens synchronously in the press');
+ assert.equal(tab.location.href, 'https://connect.example/gmail');
+ assert.match(text(host.querySelector('[data-find-notice]')), /Composio is added\. Finish signing in to Gmail in the new tab\./);
+ assert.match(text(host.querySelector('[data-row-key="composio-c-gmail"]')), /Waiting for you to finish signing in/);
+});
+
+test('a refused key stays in the field with the error and its fix next to it', async () => {
+ const { api } = stubApi({ addKey: async () => { throw new m.ConnectionsError('Composio didn’t accept this key.', 409, 'replace_key'); } });
+ window.open = () => ({ closed: false, location: {}, close() {} });
+ const host = await mount({ api });
+ await type(host, 'gm');
+ await key(input(host), 'Enter');
+ const field = host.querySelector('[data-composio-setup] input');
+ Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set.call(field, 'nope');
+ field.dispatchEvent(new window.Event('input', { bubbles: true }));
+ await settle();
+ field.closest('form').dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));
+ await settle();
+ const err = host.querySelector('[data-key-error="refused"]');
+ assert.ok(err);
+ assert.equal(err.getAttribute('role'), 'alert');
+ assert.match(text(err), /Composio didn’t accept this key\. Open your API keys/);
+ assert.equal(host.querySelector('[data-composio-setup] input').getAttribute('aria-invalid'), 'true');
+ assert.ok(host.querySelector('[data-composio-setup] [data-key-error]'), 'the error sits in the field, under the row');
+});
+
+test('the ghost fills in the rest of the name; Tab and → accept it, Esc drops it, then clears', async () => {
+ const { api } = stubApi();
+ const host = await mount({ api });
+ await type(host, 'gm');
+ const ghost = host.querySelector('[data-ghost]');
+ assert.ok(ghost);
+ assert.equal(ghost.getAttribute('aria-hidden'), 'true');
+ assert.equal(text(ghost.lastElementChild), 'ail');
+ assert.ok(host.querySelector('[data-tab-keycap]'));
+ const tab = await key(input(host), 'Tab');
+ assert.equal(tab.defaultPrevented, true);
+ assert.equal(input(host).value, 'Gmail');
+ await type(host, 'gm');
+ await key(input(host), 'Escape');
+ assert.equal(host.querySelector('[data-ghost]'), null, 'first Esc drops the ghost');
+ assert.equal(input(host).value, 'gm');
+ await key(input(host), 'Escape');
+ assert.equal(input(host).value, '', 'second Esc clears the field');
+ const third = await key(input(host), 'Escape');
+ assert.equal(third.defaultPrevented, false, 'with nothing to clear, Esc goes on to the dialog');
+});
+
+test('no ghost for a word or typo match', async () => {
+ const { api } = stubApi();
+ const host = await mount({ api });
+ await type(host, 'sheets');
+ assert.equal(host.querySelector('[data-ghost]'), null);
+ await type(host, 'gmial');
+ assert.equal(host.querySelector('[data-ghost]'), null);
+});
+
+test('arrows move one highlight across groups with no wrap; ↑ from the first row clears it', async () => {
+ const { api } = stubApi({ directory: async () => ({ entries: DIR, unavailable: false }) });
+ const host = await mount({ api });
+ await type(host, 'gm', 200);
+ const el = input(host);
+ assert.equal(el.getAttribute('role'), 'combobox');
+ assert.equal(el.getAttribute('aria-autocomplete'), 'both');
+ assert.equal(el.getAttribute('aria-expanded'), 'true');
+ const first = activeRow(host);
+ assert.equal(el.getAttribute('aria-activedescendant'), first.id);
+ assert.equal(first.getAttribute('aria-selected'), 'true');
+ assert.ok(first.querySelector('[data-enter-keycap]'));
+ await key(el, 'ArrowDown');
+ assert.equal(activeRow(host).dataset.rowKey, 'directory-io.example/gmail-tools', 'down crosses into the next group');
+ await key(el, 'ArrowDown');
+ assert.equal(activeRow(host).dataset.rowKey, 'directory-io.example/gmail-tools', 'no wrap at the end');
+ await key(el, 'ArrowUp');
+ await key(el, 'ArrowUp');
+ assert.equal(activeRow(host), null);
+ assert.equal(el.getAttribute('aria-activedescendant'), null);
+ for (const lb of host.querySelectorAll('[role="listbox"]')) assert.ok(document.getElementById(lb.getAttribute('aria-labelledby')));
+});
+
+test('Enter on a built-in tool adds it; on a directory row opens its form', async () => {
+ const picked = [];
+ const { api } = stubApi({ directory: async () => ({ entries: DIR, unavailable: false }) });
+ const host = await mount({ api, onAddPreset: (p) => picked.push(['preset', p.id]), onAddDirectory: (e) => picked.push(['dir', e.registry_name]) });
+ await type(host, 'githu');
+ assert.equal(activeRow(host).dataset.row, 'builtin');
+ await key(input(host), 'Enter');
+ await type(host, 'gmail tools', 200);
+ const dirRow = host.querySelector('[data-row-key="directory-io.example/gmail-tools"]');
+ dirRow.querySelector('[data-row-action]').dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
+ await settle();
+ assert.deepEqual(picked, [['preset', 'github'], ['dir', 'io.example/gmail-tools']]);
+});
+
+test('the public directory hides on 404 and says so when it can’t be reached', async () => {
+ const missing = stubApi();
+ let host = await mount({ api: missing.api });
+ await type(host, 'gm', 200);
+ assert.equal(host.querySelector('[data-group="directory"]'), null, 'a server without the directory shows no group');
+ assert.ok(missing.calls.some((c) => c[0] === 'directory'));
+ for (const u of mounted) u();
+
+ const down = stubApi({ directory: async () => ({ entries: [], unavailable: true }) });
+ host = await mount({ api: down.api });
+ await type(host, 'gm', 200);
+ const line = host.querySelector('[data-directory-state="down"]');
+ assert.ok(line);
+ assert.match(text(line), /Couldn’t reach the public directory\. The tools above still work\. Try again/);
+});
+
+test('a directory entry that is a built-in tool is listed once, as built in', () => {
+ const notion = m.MCP_PRESETS.find((p) => p.id === 'notion');
+ const groups = m.buildGroups({
+ query: 'notion',
+ composioApps: [],
+ composioAdded: false,
+ directory: [{ registry_name: 'com.notion/mcp', title: 'Notion', description: '', publisher: { label: 'notion.com' }, kind: 'remote', url: notion.form.url + '/', inputs: [] }],
+ connections: [],
+ expanded: new Set(),
+ });
+ assert.deepEqual(groups.map((g) => [g.key, g.rows.length]), [['builtin', 1], ['composio', 0], ['directory', 0]]);
+});
+
+test('a server named like a built-in tool at another address is not that tool', () => {
+ // QA (mcp-finder/qa.md): a directory "Stripe" at https://api.mcp.ai/p_stripe made the built-in Stripe read "Added".
+ const groupsWith = (query, detail) =>
+ m.buildGroups({
+ query,
+ composioApps: [],
+ composioAdded: false,
+ directory: null,
+ connections: [{ id: 'mcp:s1', kind: 'mcp', name: 'Stripe', detail, status: 'ok', used_by: [] }],
+ expanded: new Set(),
+ });
+ const stripeRow = (detail) => groupsWith('stripe', detail).find((g) => g.key === 'builtin').rows.find((r) => r.preset?.id === 'stripe');
+ assert.equal(stripeRow('api.mcp.ai').added, null, 'another host is not the built-in Stripe');
+ assert.equal(stripeRow('npx').added, null, 'a local server named Stripe is not the hosted one');
+ assert.equal(stripeRow('mcp.stripe.com').added?.id, 'mcp:s1', 'the same host is');
+ assert.equal(stripeRow('MCP.Stripe.com ').added?.id, 'mcp:s1', 'host case and spaces do not matter');
+ assert.equal(stripeRow(null).added?.id, 'mcp:s1', 'no address: the name alone decides, as before');
+ const connected = (detail) => groupsWith('', detail).find((g) => g.key === 'connected');
+ assert.equal(connected('api.mcp.ai'), undefined, 'not listed under Connected as the built-in Stripe');
+ assert.deepEqual(connected('mcp.stripe.com').rows.map((r) => r.preset?.id), ['stripe']);
+});
+
+test('more than five in a group: a Show more row that is itself an option', () => {
+ const composioApps = Array.from({ length: 8 }, (_, i) => ({ slug: `g${i}`, name: `Gapp ${i}`, description: '', tools: null, connected: false }));
+ // No built-in tool matches "gapp", so Built in is left out and the group is found by its key.
+ const c = m.buildGroups({ query: 'gapp', composioApps, composioAdded: true, directory: null, connections: [], expanded: new Set() }).find((g) => g.key === 'composio');
+ assert.ok(c, 'a Through Composio group');
+ assert.equal(c.rows.length, 6);
+ assert.equal(c.rows[5].name, 'Show 3 more through Composio');
+ const all = m.buildGroups({ query: 'gapp', composioApps, composioAdded: true, directory: null, connections: [], expanded: new Set(['composio']) }).find((g) => g.key === 'composio');
+ assert.equal(all.rows.length, 8);
+});
+
+test('nothing anywhere: the empty state offers Add by address', async () => {
+ const { api } = stubApi();
+ let asked = 0;
+ const host = await mount({ api, onAddByAddress: () => asked++ });
+ await type(host, 'q');
+ const none = host.querySelector('[data-find-nothing]');
+ assert.ok(none);
+ assert.match(text(none), /Nothing found for “q”\./);
+ none.querySelector('[data-add-by-address-inline]').dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
+ assert.equal(asked, 1);
+});
+
+test('empty field: Add a tool shows Popular and the browse grid; Apps & accounts shows nothing until focus', async () => {
+ const { api } = stubApi();
+ const browse = await mount({ api, browseWhenEmpty: true, children: h('div', { 'data-grid': '' }, 'grid') });
+ assert.ok(browse.querySelector('[data-group="popular"]'));
+ assert.ok(browse.querySelector('[data-browse] [data-grid]'));
+ assert.match(text(browse.querySelector('[data-browse]')), /All built-in tools/);
+ for (const u of mounted) u();
+ const page = await mount({ api });
+ assert.equal(page.querySelector('[data-group]'), null);
+ assert.equal(input(page).getAttribute('aria-expanded'), 'false');
+ assert.equal(input(page).getAttribute('placeholder'), 'Find a tool, like gmail, stripe or a database');
+});
+
+test('a connected app offers Choose bots, and the live line counts suggestions', async () => {
+ const chosen = [];
+ const { api } = stubApi({
+ list: async () => listOf(composio({ added: true, can_connect: true, connection_id: 'c1', apps_connected: [{ slug: 'gmail', name: 'Gmail' }] }), [{ id: 'c1', kind: 'mcp', name: 'Composio', used_by: [] }]),
+ });
+ const host = await mount({ api, onChooseBots: (t) => chosen.push(t) });
+ await type(host, 'gmail', 450);
+ const row = host.querySelector('[data-row-key="composio-c-gmail"]');
+ assert.match(text(row), /Connected.*Choose bots/);
+ assert.match(text(row), /No bot can use it yet\./);
+ await key(input(host), 'Enter');
+ assert.deepEqual(chosen, [{ kind: 'composio', slug: 'gmail', name: 'Gmail' }]);
+ assert.match(text(host.querySelector('[data-find-live]')), /^\d+ suggestions?$/);
+});
+
+// Mira's design check FIX 1-3 (composio-simple/design-check.md, "Fixes, ranked").
+const CUT = 'The official Stripe server lets bots call the Stripe API (api.stripe.com), covers the entire d';
+test('a maker description cut at 100 characters ends in an ellipsis; a whole one is left alone', () => {
+ const cut = CUT.padEnd(100, 'x');
+ assert.equal(m.markCutDescription(cut), `${cut}\u2026`);
+ assert.equal(m.markCutDescription(`${cut} `), `${cut}\u2026`);
+ for (const whole of [`${cut.slice(0, 99)}.`, `${cut.slice(0, 99)})`, `${cut.slice(0, 99)}\u2026`, 'Short and cut mid-wor']) assert.equal(m.markCutDescription(whole), whole);
+});
+
+test('directory rows show the cut, keep the full text in title; a one-line row centres its name on the mark', async () => {
+ const description = CUT.padEnd(100, 'x');
+ const entries = [{ registry_name: 'com.stripe/mcp', title: 'Stripe tools', description, publisher: { label: 'stripe.com' }, kind: 'remote', inputs: [] }];
+ const { api } = stubApi({
+ apps: async () => ({ apps: [...APPS, { slug: 'zebratool', name: 'Stripe Zebra' }], source: 'popular' }),
+ directory: async () => ({ entries, unavailable: false }),
+ });
+ const host = await mount({ api });
+ await type(host, 'stripe', 200);
+ const dir = host.querySelector('[data-row-key="directory-com.stripe/mcp"]');
+ const p = dir.querySelector('p[title]');
+ assert.equal(p.getAttribute('title'), description);
+ assert.equal(p.textContent, `${description}\u2026`);
+ assert.ok(dir.querySelector('.items-start'), 'a two-line row stays top-aligned');
+ const bare = host.querySelector('[data-row-key="composio-c-zebratool"]');
+ assert.ok(bare, 'the bare Composio row is listed');
+ assert.equal(bare.querySelector('p'), null);
+ assert.ok(bare.querySelector('.items-center > [data-row-name], .items-center [data-row-name]'));
+ assert.equal(bare.querySelector('.items-start'), null);
+});
+
+test('installing from the directory sends the Name from the form', async () => {
+ const sent = [];
+ const prev = globalThis.fetch;
+ globalThis.fetch = async (url, init) => (sent.push([String(url), init?.method, JSON.parse(init?.body ?? 'null')]), new Response('{"server":{"id":"s1"}}', { status: 200, headers: { 'content-type': 'application/json' } }));
+ try {
+ await m.connectionsApi.installFromDirectory('com.stripe/mcp', 'Stripe', { A: '1' }, {});
+ } finally {
+ globalThis.fetch = prev;
+ }
+ assert.deepEqual(sent, [['/api/mcp/registry/install', 'POST', { registry_name: 'com.stripe/mcp', name: 'Stripe', env: { A: '1' }, headers: {} }]]);
+});
diff --git a/frontend/tests/toolSearch.test.mjs b/frontend/tests/toolSearch.test.mjs
new file mode 100644
index 00000000..43b623bb
--- /dev/null
+++ b/frontend/tests/toolSearch.test.mjs
@@ -0,0 +1,72 @@
+// Find a tool's matching (composio-simple/design.md "Autocomplete"): from the first letter, typos and
+// other names, the typed letters bold, and the ghost completion.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+const m = await loadBundled(`export * from './src/toolSearch';`);
+const apps = ['Gmail', 'Google Calendar', 'Google Sheets', 'GitHub', 'Slack', 'Notion', 'ElevenLabs', 'Microsoft Teams', 'PostgreSQL', 'Figma'].map((name) => ({
+ name,
+ slug: name.toLowerCase().replace(/\s+/g, ''),
+}));
+const names = (q) => m.rankTools(q, apps).map((r) => r.entry.name);
+const kind = (q, name) => m.matchTool(q, apps.find((a) => a.name === name) ?? { name })?.kind ?? null;
+
+test('one letter matches only the start of a name or of a word in it', () => {
+ assert.deepEqual(names('g'), ['Gmail', 'Google Calendar', 'Google Sheets', 'GitHub']);
+ assert.deepEqual(names('s'), ['Slack', 'Google Sheets', 'PostgreSQL'], 'start first, then a word start');
+ assert.deepEqual(names('q'), [], 'no letter-in-the-middle matches at one character');
+});
+
+test('case, spaces, dashes and dots are ignored', () => {
+ assert.equal(kind('GOOGLE-sheets', 'Google Sheets'), 'start');
+ assert.equal(kind('googlesheets', 'Google Sheets'), 'start');
+ assert.equal(kind('g.mail', 'Gmail'), 'start');
+});
+
+test('typos find the app: gmial, slak, notoin', () => {
+ assert.equal(kind('gmial', 'Gmail'), 'typo');
+ assert.equal(kind('slak', 'Slack'), 'typo');
+ assert.equal(kind('notoin', 'Notion'), 'typo');
+ assert.equal(kind('zzqx', 'Gmail'), null);
+ assert.equal(kind('gmi', 'Gmail'), null, 'no typo below 4 characters');
+});
+
+test('other names: sheets, 11labs, eleven, pg, twitter', () => {
+ assert.equal(kind('sheets', 'Google Sheets'), 'word');
+ assert.equal(kind('11labs', 'ElevenLabs'), 'alias');
+ assert.equal(kind('eleven', 'ElevenLabs'), 'start');
+ assert.equal(kind('labs', 'ElevenLabs'), 'word', 'a capital starts a word');
+ assert.equal(kind('pg', 'PostgreSQL'), 'alias');
+ assert.equal(kind('teams', 'Microsoft Teams'), 'word');
+ assert.equal(kind('twitter', 'X'), 'alias');
+});
+
+test('rank: start > word > alias > slug > contains > typo; ties go to the tie breaker', () => {
+ const r = m.rankTools('cal', [{ name: 'Localize' }, { name: 'Google Calendar' }, { name: 'Calendly' }]);
+ assert.deepEqual(r.map((x) => [x.entry.name, x.match.kind]), [['Calendly', 'start'], ['Google Calendar', 'word'], ['Localize', 'contains']]);
+ const tie = m.rankTools('g', [{ name: 'Gong', n: 1 }, { name: 'Gmail', n: 9 }], (e) => e.n);
+ assert.deepEqual(tie.map((x) => x.entry.name), ['Gmail', 'Gong']);
+});
+
+test('the typed letters are bold where they sit in the name as written; none for alias or typo', () => {
+ assert.deepEqual(m.matchTool('gm', { name: 'Gmail' }).bold, [0, 2]);
+ assert.deepEqual(m.matchTool('google s', { name: 'Google Sheets' }).bold, [0, 8]);
+ assert.deepEqual(m.matchTool('sheets', { name: 'Google Sheets' }).bold, [7, 13]);
+ assert.equal(m.matchTool('11labs', { name: 'ElevenLabs', slug: 'elevenlabs' }).bold, null);
+ assert.equal(m.matchTool('gmial', { name: 'Gmail' }).bold, null);
+});
+
+test('the ghost is the rest of the name after what was typed', () => {
+ assert.equal(m.ghostRest('gm', 'Gmail'), 'ail');
+ assert.equal(m.ghostRest('google s', 'Google Sheets'), 'heets');
+ assert.equal(m.ghostRest('googles', 'Google Sheets'), 'heets');
+ assert.equal(m.ghostRest('sheets', 'Google Sheets'), '', 'no ghost for a word match');
+ assert.equal(m.ghostRest('Gmail', 'Gmail'), '');
+});
+
+test('the live line counts suggestions', () => {
+ assert.equal(m.suggestionsLine(0), 'No suggestions');
+ assert.equal(m.suggestionsLine(1), '1 suggestion');
+ assert.equal(m.suggestionsLine(7), '7 suggestions');
+});