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.

Chat: one-tap Connect on a bot's connection card

Pixel (kwant bot)9cff73e50372
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1cbb4711..8c4f6113 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
as Google Search Console, it offers you a connection card instead of stopping, and carries on with the
rest. Bots are told to try the fallback first, such as the PageSpeed website when the API is
rate-limited.
+- **Connect an app from a bot's card.** When a bot offers a connection (such as Google Search Console),
+ its card has a Connect button. It opens the app's sign-in in your browser (in the Mac app too), shows
+ "Connected" once the sign-in finishes, and offers to open the sign-in again. Without a usable Composio
+ connector, the card says what's missing and opens Connections instead.
- **Mission board: AutoFix, change approvals and restore.** A failed task shows why it failed in plain
words, what AutoFix plans, its tries and what retries cost, with Retry now and Don't retry. Proposed
changes to a check, the acceptance or a routine appear in Needs you with before and after, and only
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 53538b60..d785b628 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -22,6 +22,8 @@ import {
turnsAwaitingStep,
} from './humanSteps';
import { McpSuggestionCard } from './components/McpSuggestionCard';
+import { ConnectionSuggestionCard } from './components/ConnectionSuggestionCard';
+import type { ConnectionSuggestionMeta } from './connectionSuggestions';
import { Suggestion, SuggestionMeta, applySuggestion, suggestionsApi } from './mcpSuggestions';
import { ApiError, BotActionMeta, HireMeta, applyBotAction, applyHire, botActionsApi, changesBots, decisionError, hiresApi } from './botActions';
import { BotActionCard, type BotActionDecision } from './components/BotActionCard';
@@ -269,6 +271,15 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
playSfx('click');
};
const openSettings = () => openSpaceSettings('accounts');
+ const openConnections = () => {
+ setShowConnections(true);
+ setShowLoose(false);
+ setShowParallel(false);
+ setShowMissions(false);
+ setShowAway(false);
+ setPhoneView('chat');
+ playSfx('click');
+ };
const openClaudeSignIn = () => {
setClaudeSignInFocus(Date.now());
setSpaceSettingsTab('accounts');
@@ -1784,6 +1795,20 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
);
};
+ const renderConnectionSuggestion = (msg: ChatMessage, meta: ConnectionSuggestionMeta, flash: boolean) => {
+ const name = kwantName(meta.kwant_id ?? undefined);
+ return (
+ <ConnectionSuggestionCard
+ meta={meta}
+ messageId={msg.id}
+ kwantName={name ?? (msg.sender_id && msg.sender_id.length <= 20 ? msg.sender_id : chatTitle)}
+ kwantId={meta.kwant_id ?? undefined}
+ onOpenConnections={openConnections}
+ flash={flash}
+ />
+ );
+ };
+
// A routine card's Edit or Pause: open Space settings → Routines at that routine.
const handleOpenRoutine = (id: string, mode: 'edit' | 'pause') => {
setRoutineFocus({ id, mode, nonce: Date.now() });
@@ -2780,15 +2805,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
playSfx('click');
}}
connectionsActive={showConnections}
- onOpenConnections={() => {
- setShowConnections(true);
- setShowLoose(false);
- setShowParallel(false);
- setShowMissions(false);
- setShowAway(false);
- setPhoneView('chat');
- playSfx('click');
- }}
+ onOpenConnections={openConnections}
missionBoard={missionBoard}
missionsActive={showMissions}
onOpenMissions={() => {
@@ -2943,6 +2960,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
renderDelegation={renderDelegation}
renderQuestion={renderQuestion}
renderMcpSuggestion={renderMcpSuggestion}
+ renderConnectionSuggestion={renderConnectionSuggestion}
renderBotAction={renderBotAction}
renderHire={renderHire}
awaitingAnswer={awaitingHere}
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 50a09c88..389c5023 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -36,6 +36,7 @@ import { ranOnLabel } from '../engines';
import { replyTokens } from '../modelUsage';
import { parseRoutingMeta, ranOnAccount, routingLine } from '../spaces';
import { SetupNeededCard, parseSetupMeta } from './SetupNeededCard';
+import { ConnectionSuggestionMeta, parseConnectionMeta } from '../connectionSuggestions';
import { routeReasonText } from '../routeReason';
import { BudgetPausedNotice, InterruptedNotice, SystemNotice } from './SystemNotice';
import { chainBudgetApi, parseBudgetPaused } from '../chainBudget';
@@ -204,6 +205,8 @@ export interface ChatViewProps {
renderQuestion?: (msg: ChatMessage, meta: QuestionMeta, flash: boolean) => React.ReactNode;
/** Draws a bot's tool suggestion card (messages with `mcp_suggestion` meta). */
renderMcpSuggestion?: (msg: ChatMessage, meta: SuggestionMeta, flash: boolean) => React.ReactNode;
+ /** Draws a bot's offer to connect an app (message meta kind "connection_suggestion"). */
+ renderConnectionSuggestion?: (msg: ChatMessage, meta: ConnectionSuggestionMeta, flash: boolean) => React.ReactNode;
/** A change a bot made in the app (message meta kind "bot_action"). */
renderBotAction?: (msg: ChatMessage, meta: BotActionMeta, flash: boolean) => React.ReactNode;
/** A bot's proposal to hire a new bot (message meta kind "hire_proposal"). */
@@ -414,6 +417,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
renderDelegation,
renderQuestion,
renderMcpSuggestion,
+ renderConnectionSuggestion,
renderBotAction,
renderHire,
onOpenAccounts,
@@ -782,6 +786,9 @@ export const ChatView: React.FC<ChatViewProps> = ({
if (humanStep && renderHumanStep) return <React.Fragment key={msg.id}>{renderHumanStep(msg, humanStep, flashId === msg.id)}</React.Fragment>;
const suggestion = msg.meta && renderMcpSuggestion ? parseSuggestionMeta(msg.meta) : null;
if (suggestion && renderMcpSuggestion) return <React.Fragment key={msg.id}>{renderMcpSuggestion(msg, suggestion, flashId === msg.id)}</React.Fragment>;
+ const connection = msg.meta && renderConnectionSuggestion ? parseConnectionMeta(msg.meta) : null;
+ if (connection && renderConnectionSuggestion)
+ return <React.Fragment key={msg.id}>{renderConnectionSuggestion(msg, connection, flashId === msg.id)}</React.Fragment>;
const botAction = msg.meta && renderBotAction ? parseBotActionMeta(msg.meta) : null;
if (botAction && renderBotAction) return <React.Fragment key={msg.id}>{renderBotAction(msg, botAction, flashId === msg.id)}</React.Fragment>;
const hire = msg.meta && renderHire ? parseHireMeta(msg.meta) : null;
diff --git a/frontend/src/components/ConnectionSuggestionCard.tsx b/frontend/src/components/ConnectionSuggestionCard.tsx
new file mode 100644
index 00000000..b186e8d6
--- /dev/null
+++ b/frontend/src/components/ConnectionSuggestionCard.tsx
@@ -0,0 +1,198 @@
+import React, { useEffect, useRef, useState } from 'react';
+import { AlertTriangle, CheckCircle2, ExternalLink, Link2, Loader2, Plug } from 'lucide-react';
+import { ModernAvatar } from './ModernAvatar';
+import { inMacApp } from '../externalLinks';
+import {
+ CardState,
+ ConnectApi,
+ ConnectionSuggestionMeta,
+ connectedNow,
+ defaultConnectApi,
+ initialState,
+ startConnect,
+} from '../connectionSuggestions';
+
+const focusRing = 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2';
+const mainBtn = `inline-flex items-center gap-1.5 min-h-[40px] sm:min-h-[34px] px-3.5 rounded-xl text-sm font-medium bg-sky-600 text-white hover:bg-sky-500 disabled:opacity-60 ${focusRing} focus-visible:outline-sky-300`;
+const quietBtn = `inline-flex items-center gap-1.5 min-h-[40px] sm:min-h-[34px] px-3 rounded-xl text-sm text-zinc-300 border border-zinc-700 hover:bg-zinc-800 ${focusRing} focus-visible:outline-sky-400`;
+
+export interface ConnectionSuggestionViewProps {
+ meta: ConnectionSuggestionMeta;
+ messageId: string;
+ kwantName: string;
+ kwantId?: string;
+ state: CardState;
+ /** The Mac app: sign-ins open in the default browser, not a new tab. */
+ mac?: boolean;
+ onConnect: () => void;
+ onOpenConnections?: () => void;
+ flash?: boolean;
+}
+
+/** The card itself, drawn from its state; [`ConnectionSuggestionCard`] holds the state. */
+export const ConnectionSuggestionView: React.FC<ConnectionSuggestionViewProps> = ({
+ meta,
+ messageId,
+ kwantName,
+ kwantId,
+ state,
+ mac = false,
+ onConnect,
+ onOpenConnections,
+ flash,
+}) => {
+ const headingId = `conn-s-${messageId}`;
+ const { phase } = state;
+ const where = mac ? 'your browser' : 'the new tab';
+ const border =
+ phase === 'connected' ? 'border-emerald-500/30' : phase === 'error' ? 'border-rose-500/40' : phase === 'missing' ? 'border-amber-500/30' : 'border-sky-500/35';
+ const again = (
+ <button type="button" onClick={onConnect} className={quietBtn} data-connect-again>
+ <Link2 size={13} aria-hidden="true" /> Open the sign-in again
+ </button>
+ );
+
+ return (
+ <section
+ data-message-id={messageId}
+ data-connection-card={phase}
+ aria-labelledby={headingId}
+ className={`flex items-start gap-3.5 w-full max-w-5xl rounded-xl ${flash ? 'kw-flash' : ''}`}
+ >
+ <ModernAvatar role={kwantName} name={kwantName} size={34} kwantId={kwantId} />
+ <div className={`flex-1 min-w-0 max-w-2xl rounded-2xl rounded-tl-sm border bg-zinc-900/60 shadow-sm ${border}`}>
+ <div className="px-4 pt-3 pb-2 space-y-1.5">
+ <span className="flex items-center gap-1.5 text-[11px] font-medium text-zinc-400">
+ <Plug size={12} className="text-sky-300" aria-hidden="true" />
+ <span className="text-zinc-200">{kwantName}</span> suggests a connection
+ </span>
+ <h3 id={headingId} className="text-sm font-semibold text-zinc-100 break-words leading-snug">
+ {meta.name}
+ </h3>
+ {meta.reason && (
+ <p className="text-sm text-zinc-300 break-words leading-relaxed">
+ <span className="text-zinc-500">Why: </span>
+ {meta.reason}
+ </p>
+ )}
+ </div>
+
+ <div className="px-4 pb-3 space-y-2 text-sm" aria-live="polite">
+ {phase === 'connected' ? (
+ <p className="flex items-start gap-1.5 text-emerald-200" data-connected>
+ <CheckCircle2 size={15} className="mt-0.5 shrink-0" aria-hidden="true" />
+ <span>
+ <span className="font-medium">Connected.</span> {kwantName} can use {meta.name} from its next turn.
+ </span>
+ </p>
+ ) : phase === 'missing' ? (
+ <>
+ <p className="flex items-start gap-1.5 text-amber-200 break-words">
+ <AlertTriangle size={14} className="mt-0.5 shrink-0" aria-hidden="true" />
+ <span>{state.message}</span>
+ </p>
+ {onOpenConnections && (
+ <button type="button" onClick={onOpenConnections} className={mainBtn} data-open-connections>
+ <Plug size={13} aria-hidden="true" /> Open Connections
+ </button>
+ )}
+ </>
+ ) : phase === 'waiting' || phase === 'unchecked' ? (
+ <>
+ <p className="flex items-start gap-1.5 text-zinc-300 break-words">
+ {phase === 'waiting' && <Loader2 size={14} className="mt-0.5 shrink-0 animate-spin motion-reduce:animate-none text-sky-300" aria-hidden="true" />}
+ <span>
+ {state.link
+ ? `Your browser blocked the new tab. Open the sign-in to connect ${meta.name}.`
+ : phase === 'waiting'
+ ? `Finish signing in to ${meta.name} in ${where}. This updates by itself when you’re done.`
+ : `Finish signing in to ${meta.name} in ${where}. Once you have, its tools reach your bots from their next turn.`}
+ </span>
+ </p>
+ <div className="flex flex-wrap items-center gap-2">
+ {state.link ? (
+ <a href={state.link} target="_blank" rel="noopener noreferrer" className={mainBtn} data-sign-in-link>
+ Open the sign-in <ExternalLink size={13} aria-hidden="true" />
+ <span className="sr-only">(opens in a new tab)</span>
+ </a>
+ ) : (
+ again
+ )}
+ </div>
+ </>
+ ) : phase === 'timed_out' ? (
+ <>
+ <p className="text-zinc-300 break-words">
+ The sign-in hasn’t finished yet. If you closed it, open it again; if you finished, the connection shows in Connections.
+ </p>
+ <div className="flex flex-wrap items-center gap-2">
+ {again}
+ {onOpenConnections && (
+ <button type="button" onClick={onOpenConnections} className={quietBtn}>
+ Open Connections
+ </button>
+ )}
+ </div>
+ </>
+ ) : (
+ <>
+ {phase === 'error' && (
+ <p role="alert" className="flex items-start gap-1.5 rounded-lg border border-rose-500/30 bg-rose-500/10 px-2.5 py-1.5 text-xs text-rose-200 break-words">
+ <AlertTriangle size={13} className="mt-px shrink-0" aria-hidden="true" />
+ <span>{state.message}</span>
+ </p>
+ )}
+ <div className="flex flex-wrap items-center gap-2">
+ <button type="button" onClick={onConnect} disabled={phase === 'opening'} className={mainBtn} data-connect>
+ {phase === 'opening' ? <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <Plug size={13} aria-hidden="true" />}
+ {phase === 'opening' ? 'Opening the sign-in…' : phase === 'error' ? 'Try again' : 'Connect'}
+ </button>
+ </div>
+ <p className="text-[11px] text-zinc-500 break-words">
+ You sign in on {meta.name}’s own page, through Composio, which keeps the sign-in on its servers. Nothing connects until you do.
+ </p>
+ </>
+ )}
+ </div>
+ </div>
+ </section>
+ );
+};
+
+export interface ConnectionSuggestionCardProps {
+ meta: ConnectionSuggestionMeta;
+ messageId: string;
+ kwantName: string;
+ kwantId?: string;
+ onOpenConnections?: () => void;
+ flash?: boolean;
+ api?: ConnectApi;
+}
+
+/** A bot's offer to connect an app (message meta kind "connection_suggestion") with one-tap Connect. */
+export const ConnectionSuggestionCard: React.FC<ConnectionSuggestionCardProps> = ({ api = defaultConnectApi, ...props }) => {
+ const [state, setState] = useState<CardState>(() => initialState(props.meta));
+ const stopRef = useRef<(() => void) | null>(null);
+ const mac = inMacApp();
+
+ // An app connected earlier (or from another card) shows as connected when the card appears.
+ useEffect(() => {
+ if (props.meta.composio !== 'ready') return;
+ let live = true;
+ connectedNow(api, props.meta.app).then((c) => {
+ if (live && c) setState((s) => (s.phase === 'ready' ? { phase: 'connected' } : s));
+ });
+ return () => {
+ live = false;
+ };
+ }, [api, props.meta.app, props.meta.composio]);
+
+ useEffect(() => () => stopRef.current?.(), []);
+
+ const connect = () => {
+ stopRef.current?.();
+ stopRef.current = startConnect(props.meta.app, setState, { api, mac });
+ };
+
+ return <ConnectionSuggestionView {...props} state={state} mac={mac} onConnect={connect} />;
+};
diff --git a/frontend/src/connectionSuggestions.ts b/frontend/src/connectionSuggestions.ts
new file mode 100644
index 00000000..79b6ac1f
--- /dev/null
+++ b/frontend/src/connectionSuggestions.ts
@@ -0,0 +1,174 @@
+// A bot's offer to connect an app it can't reach (message meta kind "connection_suggestion", from
+// src/server/connection_suggest.rs). Connect starts the app's sign-in on Composio through the
+// person-only POST /api/connections/composio/apps/:slug/connect, opens it outside kwant, and watches
+// GET /api/connections/composio/apps/:slug/status until the app is connected. Nothing connects until
+// the person signs in on the app's own page.
+
+import { parseMetaObject } from './questions';
+import { ConnectionsError, connectionsApi } from './connections';
+import { inMacApp, pollUntil } from './externalLinks';
+
+/** Whether the space's Composio connector could start a sign-in when the bot posted the card. */
+export type ComposioReady = 'ready' | 'off' | 'needs_key' | 'not_added';
+
+export interface ConnectionSuggestionMeta {
+ kind: 'connection_suggestion';
+ app: string;
+ name: string;
+ reason: string;
+ composio: ComposioReady;
+ kwant_id: string | null;
+}
+
+const READY: ComposioReady[] = ['ready', 'off', 'needs_key', 'not_added'];
+
+export function parseConnectionMeta(raw: unknown): ConnectionSuggestionMeta | null {
+ const m = parseMetaObject(raw);
+ if (!m || m.kind !== 'connection_suggestion') return null;
+ const app = typeof m.app === 'string' ? m.app.trim() : '';
+ if (!/^[a-z0-9_-]{1,64}$/.test(app)) return null;
+ const name = typeof m.name === 'string' && m.name.trim() ? m.name.trim() : app;
+ return {
+ kind: 'connection_suggestion',
+ app,
+ name,
+ reason: typeof m.reason === 'string' ? m.reason.trim() : '',
+ composio: READY.includes(m.composio as ComposioReady) ? (m.composio as ComposioReady) : 'ready',
+ kwant_id: typeof m.kwant_id === 'string' ? m.kwant_id : null,
+ };
+}
+
+/** Why Connect can't start yet, in the card's words; null when it can. */
+export function composioMissingText(r: ComposioReady): string | null {
+ switch (r) {
+ case 'not_added':
+ return 'Connecting apps goes through Composio, which isn’t added yet. Add it in Connections first (free account at composio.dev).';
+ case 'needs_key':
+ return 'Composio is added but has no API key yet. Add your Composio API key in Connections first.';
+ case 'off':
+ return 'The Composio connector is switched off. Switch it on in Connections first.';
+ default:
+ return null;
+ }
+}
+
+/**
+ * Where the card is:
+ * - `ready`: Connect.
+ * - `missing`: Composio can't start a sign-in; the reason and a way to Connections.
+ * - `opening`: asking the server for the sign-in address.
+ * - `waiting`: the sign-in is open outside kwant; the card watches for it to finish.
+ * - `connected`: the server reports the app connected.
+ * - `timed_out`: no finished sign-in seen in 10 minutes.
+ * - `unchecked`: this server can't report whether the app is connected, so the card never claims it.
+ * - `error`: the sign-in couldn't start.
+ */
+export type CardPhase = 'ready' | 'missing' | 'opening' | 'waiting' | 'connected' | 'timed_out' | 'unchecked' | 'error';
+
+export interface CardState {
+ phase: CardPhase;
+ /** `missing` and `error`: what to tell the person. */
+ message?: string;
+ /** `waiting`: the sign-in address when no tab could be opened, so the person can open it themselves. */
+ link?: string;
+}
+
+export const initialState = (meta: Pick<ConnectionSuggestionMeta, 'composio'>): CardState => {
+ const missing = composioMissingText(meta.composio);
+ return missing ? { phase: 'missing', message: missing } : { phase: 'ready' };
+};
+
+export interface ConnectApi {
+ connect: (slug: string) => Promise<{ redirect_url: string }>;
+ status: (slug: string) => Promise<{ connected: boolean }>;
+}
+
+export const defaultConnectApi: ConnectApi = {
+ connect: connectionsApi.connectComposioApp,
+ status: connectionsApi.composioAppStatus,
+};
+
+/** A 409 from either call: Composio isn't added, has no key or no user, so Connect can't work. */
+const composioRefused = (e: unknown) => e instanceof ConnectionsError && e.status === 409;
+/** A 404 from the status call: an older server without it. */
+const noStatusRoute = (e: unknown) => e instanceof ConnectionsError && e.status === 404;
+
+/** Whether the app is already connected; null when unknown (older server, Composio unusable, offline). */
+export async function connectedNow(api: ConnectApi, slug: string): Promise<boolean | null> {
+ try {
+ return (await api.status(slug)).connected === true;
+ } catch {
+ return null;
+ }
+}
+
+type OpenWin = Pick<Window, 'open'> & { location: Pick<Location, 'assign'> };
+
+/**
+ * One press of Connect (or "Open the sign-in again"): starts the sign-in, opens it outside kwant and
+ * watches the server until the app is connected. Must be called inside the click, so the browser lets
+ * the new tab open. Reports every change through `onState` and returns a function that stops watching.
+ */
+export function startConnect(
+ slug: string,
+ onState: (s: CardState) => void,
+ {
+ api = defaultConnectApi,
+ win = window as unknown as OpenWin,
+ mac = inMacApp(),
+ everyMs,
+ forMs,
+ }: { api?: ConnectApi; win?: OpenWin; mac?: boolean; everyMs?: number; forMs?: number } = {},
+): () => void {
+ let stop: (() => void) | null = null;
+ let cancelled = false;
+ // Open the tab now, while the click still counts as the person's; the address comes after the fetch.
+ // The Mac app opens no second window: its outside links go to the default browser.
+ const tab = mac ? null : win.open('', '_blank');
+ if (tab) tab.opener = null;
+ onState({ phase: 'opening' });
+ (async () => {
+ let url: string;
+ try {
+ url = (await api.connect(slug)).redirect_url;
+ } catch (e) {
+ tab?.close();
+ if (cancelled) return;
+ onState(
+ composioRefused(e)
+ ? { phase: 'missing', message: e instanceof Error ? e.message : 'Composio can’t start this sign-in. Check it in Connections.' }
+ : { phase: 'error', message: e instanceof Error ? e.message : 'The sign-in didn’t start. Try again.' },
+ );
+ return;
+ }
+ if (cancelled) {
+ tab?.close();
+ return;
+ }
+ let link: string | undefined;
+ if (tab) tab.location.href = url;
+ else if (mac) win.location.assign(url);
+ else link = url; // blocked: the card shows the address as a link, which a click always opens
+ onState({ phase: 'waiting', link });
+ let outcome: CardState | null = null;
+ stop = pollUntil(
+ async () => {
+ try {
+ return (await api.status(slug)).connected === true;
+ } catch (e) {
+ if (noStatusRoute(e)) outcome = { phase: 'unchecked', link };
+ else if (composioRefused(e)) outcome = { phase: 'missing', message: (e as Error).message };
+ else return false;
+ return true;
+ }
+ },
+ () => onState(outcome ?? { phase: 'connected' }),
+ { everyMs, forMs, onTimeout: () => onState({ phase: 'timed_out' }) },
+ );
+ if (cancelled) stop();
+ })();
+ return () => {
+ cancelled = true;
+ stop?.();
+ };
+}
diff --git a/frontend/src/connections.ts b/frontend/src/connections.ts
index 6b13a36e..b8a7e9b6 100644
--- a/frontend/src/connections.ts
+++ b/frontend/src/connections.ts
@@ -115,6 +115,16 @@ export const connectionsApi = {
/** Starts signing in to one Composio app; the answer is the address to open. */
connectComposioApp: (slug: string) =>
call<{ redirect_url: string; warning: string }>(`/api/connections/composio/apps/${enc(slug)}/connect`, 'POST'),
+ /**
+ * Whether one Composio app is connected for the connector's user. A server without this route (or one
+ * that answers something else) is a 404, so callers stop asking instead of polling forever.
+ */
+ composioAppStatus: async (slug: string): Promise<{ connected: boolean }> => {
+ const answer = await call<unknown>(`/api/connections/composio/apps/${enc(slug)}/status`);
+ const connected = answer && typeof answer === 'object' ? (answer as { connected?: unknown }).connected : undefined;
+ if (typeof connected !== 'boolean') throw new ConnectionsError('This server can’t tell whether an app is connected yet.', 404);
+ return { connected };
+ },
/** "Check now" for an MCP server: the server records the result as its last check. */
testMcp: (serverId: string) => call<{ ok?: boolean; error?: string }>(`/api/mcp/servers/${enc(serverId)}/test`, 'POST'),
};
diff --git a/frontend/tests/connectionSuggestions.test.mjs b/frontend/tests/connectionSuggestions.test.mjs
new file mode 100644
index 00000000..7913385a
--- /dev/null
+++ b/frontend/tests/connectionSuggestions.test.mjs
@@ -0,0 +1,261 @@
+// Ada (2026-10-28): a bot's "connect this app" card (meta kind connection_suggestion, from #106) gets
+// a one-tap Connect that opens the sign-in outside kwant, watches until the app is connected and then
+// says so. Without a usable Composio connector it says why and links to Connections instead.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {} };
+
+const m = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { ConnectionSuggestionView } from './src/components/ConnectionSuggestionCard';
+ export * from './src/connectionSuggestions';
+ export { connectionsApi, ConnectionsError } from './src/connections';
+ export const view = (p) =>
+ renderToStaticMarkup(React.createElement(ConnectionSuggestionView, { messageId: 'm1', kwantName: 'Scout', onConnect: () => {}, onOpenConnections: () => {}, ...p }));
+`);
+
+const text = (html) => html.replace(/<[^>]+>/g, ' ').replace(/’/g, "'").replace(/&#x27;|&#39;/g, "'").replace(/&quot;/g, '"').replace(/&amp;/g, '&').replace(/\s+/g, ' ').trim();
+const buttons = (html) => [...html.matchAll(/<(?:button|a)[^>]*>([\s\S]*?)<\/(?:button|a)>/g)].map((x) => text(x[1]));
+const raw = (over = {}) => ({
+ kind: 'connection_suggestion',
+ kwant_id: 'k1',
+ provider: 'composio',
+ app: 'google_search_console',
+ name: 'Google Search Console',
+ reason: 'It shows which pages Google indexed.',
+ composio: 'ready',
+ connect: '/api/connections/composio/apps/google_search_console/connect',
+ ...over,
+});
+const meta = (over) => m.parseConnectionMeta(raw(over));
+
+// ---------------------------------------------------------------- the message meta
+
+test('the card meta is read from the message, and anything else is left to other cards', () => {
+ assert.deepEqual(meta(), {
+ kind: 'connection_suggestion',
+ app: 'google_search_console',
+ name: 'Google Search Console',
+ reason: 'It shows which pages Google indexed.',
+ composio: 'ready',
+ kwant_id: 'k1',
+ });
+ assert.equal(m.parseConnectionMeta(JSON.stringify(raw())).app, 'google_search_console', 'stored meta can be a JSON string');
+ assert.equal(m.parseConnectionMeta(raw({ kind: 'mcp_suggestion' })), null);
+ assert.equal(m.parseConnectionMeta(raw({ app: '../connect' })), null, 'only a plain slug goes into the URL');
+ assert.equal(m.parseConnectionMeta(raw({ app: 'Gmail' })), null);
+ assert.equal(meta({ name: '' }).name, 'google_search_console', 'no name: the slug');
+ assert.equal(meta({ composio: 'weird' }).composio, 'ready', 'an unknown value lets Connect try; the server answers 409 if it can not');
+ assert.equal(meta({ kwant_id: undefined }).kwant_id, null);
+});
+
+// ---------------------------------------------------------------- each state, drawn
+
+test('ready: one Connect button, the app, the bot and why, and that nothing connects yet', () => {
+ const html = m.view({ meta: meta(), state: m.initialState(meta()) });
+ assert.match(html, /data-connection-card="ready"/);
+ assert.deepEqual(buttons(html), ['Connect']);
+ const t = text(html);
+ assert.match(t, /Scout suggests a connection/);
+ assert.match(t, /Google Search Console/);
+ assert.match(t, /Why: It shows which pages Google indexed\./);
+ assert.match(t, /Nothing connects until you do\./);
+ assert.match(t, /through Composio, which keeps the sign-in on its servers/);
+ assert.doesNotMatch(t, /Connected/);
+});
+
+test('connecting: the button waits, then the card says where to finish and offers the sign-in again', () => {
+ const opening = m.view({ meta: meta(), state: { phase: 'opening' } });
+ assert.match(opening, /<button[^>]*disabled=""[^>]*data-connect/);
+ assert.deepEqual(buttons(opening), ['Opening the sign-in…']);
+
+ const tab = m.view({ meta: meta(), state: { phase: 'waiting' } });
+ assert.match(text(tab), /Finish signing in to Google Search Console in the new tab\. This updates by itself when you're done\./);
+ assert.deepEqual(buttons(tab), ['Open the sign-in again']);
+ assert.match(tab, /aria-live="polite"/, 'the change to Connected is announced');
+
+ const mac = m.view({ meta: meta(), state: { phase: 'waiting' }, mac: true });
+ assert.match(text(mac), /in your browser\. This updates by itself/);
+
+ const blocked = m.view({ meta: meta(), state: { phase: 'waiting', link: 'https://connect.composio.dev/link/abc' } });
+ assert.match(text(blocked), /Your browser blocked the new tab/);
+ assert.match(blocked, /<a href="https:\/\/connect\.composio\.dev\/link\/abc" target="_blank" rel="noopener noreferrer"/);
+ assert.deepEqual(buttons(blocked), ['Open the sign-in (opens in a new tab)']);
+});
+
+test('connected: says so, and no button is left', () => {
+ const html = m.view({ meta: meta(), state: { phase: 'connected' } });
+ assert.match(html, /data-connection-card="connected"/);
+ assert.match(text(html), /Connected\. Scout can use Google Search Console from its next turn\./);
+ assert.deepEqual(buttons(html), []);
+});
+
+test('Composio missing, without a key or off: the reason and Open Connections instead of Connect', () => {
+ for (const [composio, reason] of [
+ ['not_added', /Composio, which isn't added yet\. Add it in Connections first/],
+ ['needs_key', /has no API key yet\. Add your Composio API key in Connections first/],
+ ['off', /switched off\. Switch it on in Connections first/],
+ ]) {
+ const st = m.initialState(meta({ composio }));
+ assert.equal(st.phase, 'missing', composio);
+ const html = m.view({ meta: meta({ composio }), state: st });
+ assert.match(text(html), reason, composio);
+ assert.deepEqual(buttons(html), ['Open Connections'], composio);
+ }
+ assert.equal(m.composioMissingText('ready'), null);
+});
+
+test('timed out, unchecked and error: never a false "Connected", always a way on', () => {
+ const late = m.view({ meta: meta(), state: { phase: 'timed_out' } });
+ assert.match(text(late), /hasn't finished yet/);
+ assert.deepEqual(buttons(late), ['Open the sign-in again', 'Open Connections']);
+
+ const older = m.view({ meta: meta(), state: { phase: 'unchecked' } });
+ assert.match(text(older), /Once you have, its tools reach your bots from their next turn\./);
+ assert.doesNotMatch(text(older), /Connected|updates by itself/);
+ assert.doesNotMatch(older, /animate-spin/, 'nothing pretends to wait');
+
+ const err = m.view({ meta: meta(), state: { phase: 'error', message: 'Couldn’t reach the server.' } });
+ assert.match(err, /role="alert"/);
+ assert.deepEqual(buttons(err), ['Try again']);
+});
+
+// ---------------------------------------------------------------- one press of Connect
+
+const fakeWin = ({ blocked = false } = {}) => {
+ const w = { opened: [], assigned: [], tabs: [] };
+ w.open = (url, target) => {
+ w.opened.push([url, target]);
+ if (blocked) return null;
+ const tab = { opener: 'kwant', closed: false, location: { href: url }, close() { this.closed = true; } };
+ w.tabs.push(tab);
+ return tab;
+ };
+ w.location = { assign: (u) => w.assigned.push(u) };
+ return w;
+};
+const err = (status, msg = 'nope') => new m.ConnectionsError(msg, status);
+const fakeApi = ({ connect = async () => ({ redirect_url: 'https://connect.composio.dev/link/abc' }), statuses = [] } = {}) => {
+ const api = { connects: 0, checks: 0 };
+ api.connect = async (slug) => {
+ api.connects++;
+ api.slug = slug;
+ return connect();
+ };
+ api.status = async () => {
+ const next = statuses[Math.min(api.checks++, statuses.length - 1)];
+ if (next instanceof Error) throw next;
+ return { connected: !!next };
+ };
+ return api;
+};
+const run = (opts) =>
+ new Promise((resolve) => {
+ const seen = [];
+ const stop = m.startConnect('google_search_console', (s) => {
+ seen.push(s);
+ if (!['opening', 'waiting'].includes(s.phase)) resolve({ seen, stop });
+ }, { everyMs: 1, forMs: 200, ...opts });
+ });
+const phases = (seen) => seen.map((s) => s.phase);
+
+test('browser: the tab opens inside the click, goes to the sign-in, and the card turns Connected', async () => {
+ const win = fakeWin();
+ const api = fakeApi({ statuses: [false, err(502), false, true] });
+ const { seen } = await run({ win, api, mac: false });
+ assert.deepEqual(win.opened, [['', '_blank']], 'opened before the fetch, so popup blockers allow it');
+ assert.equal(win.tabs[0].opener, null, 'the sign-in page cannot reach back into kwant');
+ assert.equal(win.tabs[0].location.href, 'https://connect.composio.dev/link/abc');
+ assert.equal(api.slug, 'google_search_console');
+ assert.deepEqual(phases(seen), ['opening', 'waiting', 'connected'], 'a failed check just waits for the next');
+ assert.equal(seen[1].link, undefined);
+ assert.equal(api.checks, 4);
+});
+
+test('Mac app: no second window; the sign-in goes to the default browser and the card still turns Connected', async () => {
+ const win = fakeWin();
+ const { seen } = await run({ win, api: fakeApi({ statuses: [true] }), mac: true });
+ assert.deepEqual(win.opened, []);
+ assert.deepEqual(win.assigned, ['https://connect.composio.dev/link/abc']);
+ assert.deepEqual(phases(seen), ['opening', 'waiting', 'connected']);
+});
+
+test('a blocked tab: the card offers the sign-in as a link and keeps watching', async () => {
+ const win = fakeWin({ blocked: true });
+ const { seen } = await run({ win, api: fakeApi({ statuses: [false, true] }), mac: false });
+ assert.equal(seen[1].link, 'https://connect.composio.dev/link/abc');
+ assert.deepEqual(win.assigned, [], 'kwant itself never leaves for Composio');
+ assert.equal(phases(seen).at(-1), 'connected');
+});
+
+test('Connect refused: 409 means Composio is not usable (missing), anything else is an error; the empty tab closes', async () => {
+ let win = fakeWin();
+ let r = await run({ win, api: fakeApi({ connect: async () => { throw err(409, 'Add the Composio connector first.'); } }), mac: false });
+ assert.deepEqual(r.seen.at(-1), { phase: 'missing', message: 'Add the Composio connector first.' });
+ assert.equal(win.tabs[0].closed, true);
+
+ win = fakeWin();
+ r = await run({ win, api: fakeApi({ connect: async () => { throw err(502, 'Composio didn’t answer.'); } }), mac: false });
+ assert.deepEqual(r.seen.at(-1), { phase: 'error', message: 'Composio didn’t answer.' });
+ assert.equal(win.tabs[0].closed, true);
+});
+
+test('watching ends honestly: an older server gives "unchecked", a 409 gives "missing", 10 minutes give "timed out"', async () => {
+ let r = await run({ win: fakeWin(), api: fakeApi({ statuses: [err(404)] }), mac: false });
+ assert.equal(r.seen.at(-1).phase, 'unchecked');
+ r = await run({ win: fakeWin(), api: fakeApi({ statuses: [err(409, 'Switch Composio on.')] }), mac: false });
+ assert.deepEqual(r.seen.at(-1), { phase: 'missing', message: 'Switch Composio on.' });
+ r = await run({ win: fakeWin(), api: fakeApi({ statuses: [false] }), mac: false, forMs: 10 });
+ assert.equal(r.seen.at(-1).phase, 'timed_out');
+});
+
+test('stopping (card gone, or pressed again) ends the watching', async () => {
+ const api = fakeApi({ statuses: [false] });
+ const seen = [];
+ const stop = m.startConnect('google_search_console', (s) => seen.push(s), { win: fakeWin(), api, mac: false, everyMs: 1, forMs: 10_000 });
+ await new Promise((r) => setTimeout(r, 20));
+ stop();
+ const checks = api.checks;
+ await new Promise((r) => setTimeout(r, 20));
+ assert.ok(checks > 0);
+ assert.ok(api.checks <= checks + 1, 'no more checks after stop');
+ assert.ok(!seen.some((s) => s.phase === 'connected' || s.phase === 'timed_out'));
+});
+
+test('already connected when the card appears: shown as connected; unknown stays unknown', async () => {
+ assert.equal(await m.connectedNow(fakeApi({ statuses: [true] }), 'gmail'), true);
+ assert.equal(await m.connectedNow(fakeApi({ statuses: [false] }), 'gmail'), false);
+ assert.equal(await m.connectedNow(fakeApi({ statuses: [err(404)] }), 'gmail'), null);
+});
+
+// ---------------------------------------------------------------- the status call
+
+test('the status call reads {connected}, and a server without the route is a 404, not "connected"', async () => {
+ const prev = globalThis.fetch;
+ const answers = [
+ [200, { connected: true }],
+ [200, { connected: false }],
+ [200, null], // the app page from an older server's fallback
+ [404, null],
+ [409, { error: 'add the Composio connector first' }],
+ ];
+ const urls = [];
+ globalThis.fetch = async (url) => {
+ urls.push(url);
+ const [status, body] = answers.shift();
+ return new Response(body === null ? '<!doctype html>' : JSON.stringify(body), { status });
+ };
+ try {
+ assert.deepEqual(await m.connectionsApi.composioAppStatus('google_search_console'), { connected: true });
+ assert.equal(urls[0], '/api/connections/composio/apps/google_search_console/status');
+ assert.deepEqual(await m.connectionsApi.composioAppStatus('x'), { connected: false });
+ await assert.rejects(m.connectionsApi.composioAppStatus('x'), (e) => e.status === 404);
+ await assert.rejects(m.connectionsApi.composioAppStatus('x'), (e) => e.status === 404);
+ await assert.rejects(m.connectionsApi.composioAppStatus('x'), (e) => e.status === 409 && /Add the Composio connector first/.test(e.message));
+ } finally {
+ globalThis.fetch = prev;
+ }
+});