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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Connections page: status, last check, users and login storage
Pixel (kwant bot)4e6eb45bf8de
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex a7669bf7..b30759ee 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -28,6 +28,7 @@ import type { RoutineFocus } from './components/RoutinesPanel';import { AwayPage } from './components/AwayView';import { LooseEndsPage } from './components/LooseEndsView';import { ParallelPage } from './components/ParallelUniverseView';+import { ConnectionsPage } from './components/ConnectionsView';import { AlertTriangle, Bot, Check, HelpCircle, Inbox, KeyRound, ListChecks, Loader2, MessageSquare, Settings } from 'lucide-react';import { ChatApproval, OpenChat, approvalFromEvent, lateAnswerText, approvalsForChat, approvalsFromAway, syncApprovals, upsertApproval, withoutApproval } from './approvals';import type { AgentFormData } from './components/NewAgentModal';@@ -281,6 +282,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({// "While you were away": open instead of a chat, and its unseen count for the sidebar badge.const [showAway, setShowAway] = useState(false);const [showLoose, setShowLoose] = useState(false);+ const [showConnections, setShowConnections] = useState(false);const [showParallel, setShowParallel] = useState(false);const [awayCount, setAwayCount] = useState(0);const awaySinceRef = useRef<string | null>(null);@@ -1258,6 +1260,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({setOpenThreadId(null);setShowAway(false);setShowLoose(false);+ setShowConnections(false);setShowParallel(false);setPhoneView('chat');setSelectedTeamId(team.id);@@ -1296,6 +1299,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({setOpenThreadId(null);setShowAway(false);setShowLoose(false);+ setShowConnections(false);setShowParallel(false);setPhoneView('chat');setSelectedId(channel.id);@@ -1312,6 +1316,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({setOpenThreadId(null);setShowAway(false);setShowLoose(false);+ setShowConnections(false);setShowParallel(false);setPhoneView('chat');setSelectedId(kwant.id);@@ -1378,6 +1383,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({knownThreadsRef.current.add(threadId);setShowAway(false);setShowLoose(false);+ setShowConnections(false);setShowParallel(false);if (selectedIdRef.current !== kwant.id || isChannelRef.current) handleSelectKwant(kwant);else playSfx('click');@@ -1393,6 +1399,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({if (!ok) return pushToast('That chat no longer exists.');setShowAway(false);setShowLoose(false);+ setShowConnections(false);setShowParallel(false);};@@ -2557,11 +2564,22 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({onOpenParallel={() => {setShowParallel(true);setShowLoose(false);+ setShowConnections(false);+ setShowAway(false);+ setPhoneView('chat');+ playSfx('click');+ }}+ connectionsActive={showConnections}+ onOpenConnections={() => {+ setShowConnections(true);+ setShowLoose(false);+ setShowParallel(false);setShowAway(false);setPhoneView('chat');playSfx('click');}}onOpenLooseEnds={() => {+ setShowConnections(false);setShowLoose(true);setShowParallel(false);setShowAway(false);@@ -2571,6 +2589,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({onOpenAway={() => {setShowAway(true);setShowLoose(false);+ setShowConnections(false);setShowParallel(false);setPhoneView('chat');playSfx('click');@@ -2584,6 +2603,14 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({/>);const parallel = <ParallelPage onBack={isPhone ? () => { setShowParallel(false); setPhoneView('list'); } : undefined} />;+ const connectionsPage = (+ <ConnectionsPage+ onBack={isPhone ? () => { setShowConnections(false); setPhoneView('list'); } : undefined}+ onOpenTools={() => setIsMcpOpen(true)}+ onOpenAccounts={openSettings}+ onOpenLooseEnds={() => { setShowConnections(false); setShowLoose(true); }}+ />+ );const loose = <LooseEndsPage onBack={isPhone ? () => { setShowLoose(false); setPhoneView('list'); } : undefined} onOpenChat={openThread} />;const chat = (<ChatView@@ -2683,7 +2710,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({contextKey={openCtx}/>);- const mainPane = needsSetup ? setupChecklist : showParallel ? parallel : showLoose ? loose : showAway ? away : !loaded ? (+ const mainPane = needsSetup ? setupChecklist : showParallel ? parallel : showConnections ? connectionsPage : showLoose ? loose : showAway ? away : !loaded ? (<main className="flex-1 flex items-center justify-center text-xs text-zinc-500"><Loader2 size={14} className="mr-2 animate-spin motion-reduce:animate-none" aria-hidden="true" /> Opening {space.name}…</main>@@ -2732,6 +2759,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({if (t.id === 'inbox') {setShowAway(true);setShowLoose(false);+ setShowConnections(false);setShowParallel(false);setPhoneView('chat');return;diff --git a/frontend/src/components/ConnectionsView.tsx b/frontend/src/components/ConnectionsView.tsxnew file mode 100644index 00000000..0cc181fe--- /dev/null+++ b/frontend/src/components/ConnectionsView.tsx@@ -0,0 +1,494 @@+import React, { useCallback, useEffect, useId, useRef, useState } from 'react';+import { AlertTriangle, Bot, ChevronLeft, Github, KeyRound, Loader2, Lock, Mail, Plug, Plus, RefreshCw, Server, UserRound } from 'lucide-react';+import { PERSON_SIGNED_IN_EVENT, requestPersonToken } from '../auth';+import { relativeTime } from '../away';+import { UnlockDialog, usePasswordStore } from './PasswordStorePanel';+import {+ CatalogEntry,+ Connection,+ ConnectionsError,+ ConnectionsList,+ Tone,+ composioBody,+ composioErrorText,+ connectionsApi,+ countsLine,+ groupConnections,+ mcpServerId,+ statusBadge,+ storedLabel,+ usedByText,+} from '../connections';++const TONES: Record<Tone, string> = {+ amber: 'border-amber-500/30 bg-amber-500/10 text-amber-200',+ emerald: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-200',+ rose: 'border-rose-500/30 bg-rose-500/10 text-rose-200',+ zinc: 'border-zinc-700 bg-zinc-800 text-zinc-300',+};++const KIND_ICON: Record<string, React.ReactNode> = {+ mcp: <Server size={14} aria-hidden="true" />,+ account: <UserRound size={14} aria-hidden="true" />,+ browser_login: <KeyRound size={14} aria-hidden="true" />,+ email: <Mail size={14} aria-hidden="true" />,+ github: <Github size={14} aria-hidden="true" />,+};++const actionBtn =+ 'inline-flex items-center gap-1.5 min-h-[36px] sm:min-h-[30px] 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';+const quietBtn = `${actionBtn} border border-zinc-700 bg-zinc-800/80 text-zinc-100 hover:bg-zinc-700 hover:border-zinc-600`;+const field =+ 'w-full min-h-[36px] px-2.5 py-1.5 bg-zinc-950 border border-zinc-800 rounded-lg text-xs text-zinc-100 placeholder:text-zinc-500 focus:outline-none focus:border-sky-500';++/** Where each kind is changed in the app. */+export interface ManageLinks {+ onOpenTools?: () => void;+ onOpenAccounts?: () => void;+ onOpenLooseEnds?: () => void;+}++const manageFor = (kind: string, links: ManageLinks): { label: string; run: () => void } | null => {+ if (kind === 'mcp' && links.onOpenTools) return { label: 'Manage', run: links.onOpenTools };+ if (kind === 'account' && links.onOpenAccounts) return { label: 'Manage', run: links.onOpenAccounts };+ if ((kind === 'email' || kind === 'github') && links.onOpenLooseEnds) return { label: 'Open Loose ends', run: links.onOpenLooseEnds };+ return null;+};++export interface ConnectionRowProps {+ c: Connection;+ now?: number;+ checking?: boolean;+ links?: ManageLinks;+ onCheck?: (c: Connection) => void;+}++export const ConnectionRow: React.FC<ConnectionRowProps> = ({ c, now = Date.now(), checking = false, links = {}, onCheck }) => {+ const id = useId();+ const badge = statusBadge(c.status);+ const manage = manageFor(c.kind, links);+ const canCheck = onCheck && mcpServerId(c) && c.status !== 'off';+ const composio = c.logins_stored === 'composio';+ return (+ <li className="px-3 py-3 sm:px-4" aria-labelledby={`${id}-n`} data-connection={c.id}>+ <div className="flex flex-wrap items-start gap-x-3 gap-y-2">+ <span className="mt-0.5 shrink-0 text-zinc-400">{KIND_ICON[c.kind] ?? <Plug size={14} aria-hidden="true" />}</span>+ <div className="min-w-0 flex-1 basis-48">+ <div className="flex flex-wrap items-center gap-2">+ <h4 id={`${id}-n`} className="text-sm font-medium text-zinc-100 break-all">+ {c.name}+ </h4>+ <span className={`inline-flex items-center px-1.5 py-px rounded border text-[11px] font-medium ${TONES[badge.tone]}`} data-status={c.status}>+ {badge.label}+ </span>+ </div>+ {c.detail && <p className="mt-0.5 text-xs text-zinc-400 break-all">{c.detail}</p>}+ {c.status_detail && (+ <p className={`mt-1 text-xs ${c.status === 'error' ? 'text-rose-300' : 'text-amber-200'} break-words`}>{c.status_detail}</p>+ )}+ <dl className="mt-1.5 flex flex-wrap gap-x-4 gap-y-1 text-[11px] text-zinc-400">+ <div className="flex items-center gap-1">+ <dt className="sr-only">Used by</dt>+ <Bot size={11} aria-hidden="true" />+ <dd>{usedByText(c.used_by, c.status)}</dd>+ </div>+ <div>+ <dt className="sr-only">Last check</dt>+ <dd>{c.last_check ? `Checked ${relativeTime(c.last_check, now)}` : 'Never checked'}</dd>+ </div>+ <div className={composio ? 'text-amber-200' : undefined}>+ <dt className="sr-only">Where the login is stored</dt>+ <dd className="flex items-center gap-1">+ {composio ? <AlertTriangle size={11} aria-hidden="true" /> : <Lock size={11} aria-hidden="true" />}+ {storedLabel(c.logins_stored, c.kind)}+ </dd>+ </div>+ </dl>+ </div>+ {(canCheck || manage) && (+ <div className="flex gap-2 shrink-0">+ {canCheck && (+ <button type="button" className={quietBtn} disabled={checking} onClick={() => onCheck!(c)} aria-label={`Check ${c.name} now`}>+ <RefreshCw size={12} className={checking ? 'animate-spin motion-reduce:animate-none' : ''} aria-hidden="true" />+ {checking ? 'Checking…' : 'Check now'}+ </button>+ )}+ {manage && (+ <button type="button" className={quietBtn} onClick={manage.run} aria-label={`${manage.label}: ${c.name}`}>+ {manage.label}+ </button>+ )}+ </div>+ )}+ </div>+ </li>+ );+};++export interface ComposioCardProps {+ entry: CatalogEntry;+ /** Tests open the form. */+ initialOpen?: boolean;+ onAdd: (url: string, apiKey: string, enabled: boolean) => Promise<string | null>;+ onOpenTools?: () => void;+}++/** The optional Composio connector: what it is, where it keeps sign-ins, and the add form. */+export const ComposioCard: React.FC<ComposioCardProps> = ({ entry, initialOpen = false, onAdd, onOpenTools }) => {+ const id = useId();+ const [open, setOpen] = useState(initialOpen);+ const [url, setUrl] = useState('');+ const [key, setKey] = useState('');+ const [enabled, setEnabled] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [saving, setSaving] = useState(false);++ const submit = async (e: React.FormEvent) => {+ e.preventDefault();+ const body = composioBody(url, key, enabled);+ if ('error' in body) return setError(body.error);+ setSaving(true);+ setError(null);+ const problem = await onAdd(body.url, body.api_key ?? '', body.enabled);+ setSaving(false);+ if (problem) setError(problem);+ else (setOpen(false), setUrl(''), setKey(''), setEnabled(false));+ };++ return (+ <li className="rounded-xl border border-zinc-800 bg-zinc-900/60 p-3 sm:p-4 space-y-3" aria-labelledby={`${id}-n`} data-catalog={entry.id}>+ <div className="flex flex-wrap items-start gap-3">+ <div className="min-w-0 flex-1 basis-56">+ <div className="flex flex-wrap items-center gap-2">+ <h4 id={`${id}-n`} className="text-sm font-medium text-zinc-100">+ {entry.name}+ </h4>+ <span className={`px-1.5 py-px rounded border text-[11px] ${TONES.zinc}`}>Optional</span>+ {entry.added && (+ <span className={`px-1.5 py-px rounded border text-[11px] ${entry.enabled ? TONES.emerald : TONES.zinc}`}>{entry.enabled ? 'Added · on' : 'Added · off'}</span>+ )}+ </div>+ <p className="mt-1 text-xs text-zinc-400">{entry.description}</p>+ </div>+ {!entry.added && !open && (+ <button type="button" className={quietBtn} onClick={() => setOpen(true)} aria-expanded={false}>+ <Plus size={12} aria-hidden="true" /> Add {entry.name}+ </button>+ )}+ {entry.added && onOpenTools && (+ <button type="button" className={quietBtn} onClick={onOpenTools}>+ {entry.enabled ? 'Manage in Tools' : 'Turn on in Tools'}+ </button>+ )}+ </div>++ <p className="flex items-start gap-2 px-3 py-2 rounded-lg border border-amber-500/30 bg-amber-500/10 text-xs text-amber-100" data-warning>+ <AlertTriangle size={14} className="mt-px shrink-0 text-amber-300" aria-hidden="true" />+ <span>{entry.warning}</span>+ </p>++ {open && !entry.added && (+ <form onSubmit={submit} className="space-y-3" aria-label={`Add ${entry.name}`} noValidate>+ <div className="space-y-1">+ <label htmlFor={`${id}-url`} className="block text-xs font-medium text-zinc-200">+ 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-describedby={`${id}-url-h`}+ aria-invalid={error ? true : undefined}+ autoFocus+ />+ <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}-key`} className="block text-xs font-medium text-zinc-200">+ API key <span className="font-normal text-zinc-400">(optional)</span>+ </label>+ <input id={`${id}-key`} className={field} type="password" autoComplete="off" value={key} onChange={(e) => setKey(e.target.value)} aria-describedby={`${id}-key-h`} />+ <p id={`${id}-key-h`} className="text-[11px] text-zinc-400">+ Stored like any tool-server header and never shown again.+ </p>+ </div>+ <label className="flex items-start gap-2 text-xs text-zinc-200">+ <input type="checkbox" className="mt-0.5 accent-sky-500" checked={enabled} onChange={(e) => setEnabled(e.target.checked)} />+ <span>+ Turn it on for my bots now+ <span className="block text-[11px] text-zinc-400">Off by default. Until it’s on, no bot can use it.</span>+ </span>+ </label>+ <div role="status" aria-live="polite">+ {error && <p className="px-3 py-2 rounded-lg border border-rose-500/20 bg-rose-500/5 text-xs text-rose-300">{error}</p>}+ </div>+ <div className="flex flex-wrap gap-2">+ <button type="submit" disabled={saving} className={`${actionBtn} bg-sky-500 text-zinc-950 hover:bg-sky-400`}>+ {saving && <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}+ Add {entry.name}+ </button>+ <button type="button" className={quietBtn} onClick={() => (setOpen(false), setError(null))}>+ Cancel+ </button>+ </div>+ </form>+ )}+ </li>+ );+};++export interface ConnectionsViewProps extends ManageLinks {+ data: ConnectionsList | null;+ loading: boolean;+ error: string | null;+ needsToken?: boolean;+ notice?: { text: string; error: boolean } | null;+ checking?: string | null;+ now?: number;+ onRefresh: () => void;+ onCheck?: (c: Connection) => void;+ onUnlockVault?: () => void;+ onAddComposio: ComposioCardProps['onAdd'];+ onBack?: () => void;+ /** Tests open the Composio form. */+ composioOpen?: boolean;+}++export const ConnectionsView: React.FC<ConnectionsViewProps> = ({+ data,+ loading,+ error,+ needsToken = false,+ notice = null,+ checking = null,+ now = Date.now(),+ onRefresh,+ onCheck,+ onUnlockVault,+ onAddComposio,+ onBack,+ composioOpen = false,+ ...links+}) => {+ const groups = data ? groupConnections(data.connections) : [];+ const vault = data?.vault;+ return (+ <div className="flex-1 flex flex-col h-full bg-zinc-950 overflow-hidden">+ <div className={`h-14 border-b border-zinc-800/80 ${onBack ? 'px-2' : 'px-4'} sm:px-6 flex items-center justify-between gap-3 bg-zinc-900/30 backdrop-blur-sm select-none`}>+ {onBack && (+ <button+ type="button"+ onClick={onBack}+ aria-label="Back to chats"+ className="shrink-0 p-2 -ml-0.5 -mr-2 rounded-lg text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"+ >+ <ChevronLeft size={18} />+ </button>+ )}+ <div className="min-w-0 flex-1">+ <h2 className="text-sm font-semibold text-zinc-100 truncate">Connections</h2>+ <p className="text-[11px] text-zinc-400 truncate mt-0.5">{data ? countsLine(data.connections) : 'Everything your bots reach outside the app'}</p>+ </div>+ <button+ type="button"+ onClick={onRefresh}+ disabled={loading || needsToken}+ className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs text-zinc-300 border border-zinc-700/60 hover:bg-zinc-800 disabled:opacity-60 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"+ >+ <RefreshCw size={12} className={loading ? 'animate-spin motion-reduce:animate-none' : ''} aria-hidden="true" />+ Refresh+ </button>+ </div>++ <div className="flex-1 overflow-y-auto p-4 sm:p-6" aria-busy={loading}>+ <div className="max-w-3xl mx-auto space-y-5">+ <p className="text-[11px] text-zinc-400">Tool servers, accounts and logins your bots use. Logins stay in your own vault on this computer unless a row says otherwise. Nothing secret is shown here.</p>++ {needsToken && (+ <div role="alert" className="px-3 py-2 rounded-lg border border-amber-500/30 bg-amber-500/10 flex flex-wrap items-center gap-2 text-xs text-amber-100">+ <span>Only you can see connections. Confirm it’s you to open them.</span>+ <button type="button" onClick={requestPersonToken} className="ml-auto px-2 py-0.5 rounded border border-amber-500/40 hover:bg-amber-500/10">+ Confirm it’s you+ </button>+ </div>+ )}++ {error && !needsToken && (+ <div role="alert" className="px-3 py-2 rounded-lg border border-rose-500/20 bg-rose-500/5 flex items-center gap-2 text-xs text-rose-300">+ <span>Couldn’t load connections: {error}</span>+ <button type="button" onClick={onRefresh} className="ml-auto px-2 py-0.5 rounded border border-rose-500/30 hover:bg-rose-500/10">+ Retry+ </button>+ </div>+ )}++ <div role="status" aria-live="polite">+ {notice && (+ <p className={`px-3 py-2 rounded-lg border text-xs ${notice.error ? 'border-amber-500/30 bg-amber-500/10 text-amber-200' : 'border-emerald-500/30 bg-emerald-500/10 text-emerald-200'}`}>+ {notice.text}+ </p>+ )}+ </div>++ {!data && loading && (+ <p className="flex items-center gap-2 text-xs text-zinc-400">+ <Loader2 size={14} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Loading…+ </p>+ )}++ {vault && vault.status !== 'ok' && (+ <div className="px-3 py-2 rounded-lg border border-amber-500/30 bg-amber-500/10 flex flex-wrap items-center gap-2 text-xs text-amber-100" data-vault={vault.status}>+ <Lock size={13} aria-hidden="true" />+ <span>{vault.status === 'locked' ? 'Unlock Bitwarden to list saved logins.' : 'Saved logins can’t be read right now, so they aren’t listed.'}</span>+ {vault.status === 'locked' && onUnlockVault && (+ <button type="button" onClick={onUnlockVault} className="ml-auto px-2 py-0.5 rounded border border-amber-500/40 hover:bg-amber-500/10">+ Unlock Bitwarden+ </button>+ )}+ </div>+ )}++ {data &&+ groups.map((g) => {+ const lockedLogins = g.key === 'browser_login' && vault && vault.status !== 'ok';+ return (+ <section key={g.key} aria-labelledby={`conn-${g.key}`} className="space-y-2">+ <h3 id={`conn-${g.key}`} className="text-xs font-semibold text-zinc-300 uppercase tracking-wider">+ {g.label} <span className="font-mono font-normal text-zinc-400">{g.items.length}</span>+ </h3>+ {g.items.length > 0 ? (+ <ul className="rounded-xl border border-zinc-800 bg-zinc-900/60 divide-y divide-zinc-800">+ {g.items.map((c) => (+ <ConnectionRow key={c.id} c={c} now={now} checking={checking === c.id} links={links} onCheck={onCheck} />+ ))}+ </ul>+ ) : (+ <p className="px-3 py-3 rounded-xl border border-dashed border-zinc-800 text-xs text-zinc-400" data-empty={g.key}>+ {lockedLogins ? 'Hidden while Bitwarden is locked.' : g.empty}+ </p>+ )}+ </section>+ );+ })}++ {data && data.catalog.length > 0 && (+ <section aria-labelledby="conn-catalog" className="space-y-2">+ <h3 id="conn-catalog" className="text-xs font-semibold text-zinc-300 uppercase tracking-wider">+ Optional connectors+ </h3>+ <ul className="space-y-2">+ {data.catalog.map((entry) => (+ <ComposioCard key={entry.id} entry={entry} initialOpen={composioOpen} onAdd={onAddComposio} onOpenTools={links.onOpenTools} />+ ))}+ </ul>+ </section>+ )}+ </div>+ </div>+ </div>+ );+};++/** The page: loads the list, checks MCP servers, unlocks the vault and adds Composio. */+export const ConnectionsPage: React.FC<ManageLinks & { onBack?: () => void }> = ({ onBack, ...links }) => {+ const [data, setData] = useState<ConnectionsList | null>(null);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);+ const [needsToken, setNeedsToken] = useState(false);+ const [notice, setNotice] = useState<{ text: string; error: boolean } | null>(null);+ const [checking, setChecking] = useState<string | null>(null);+ const [unlocking, setUnlocking] = useState(false);+ const store = usePasswordStore(unlocking, true);+ const alive = useRef(true);++ const load = useCallback(async () => {+ setLoading(true);+ try {+ const r = await connectionsApi.list();+ if (!alive.current) return;+ setData(r);+ setError(null);+ setNeedsToken(false);+ } catch (e) {+ if (!alive.current) return;+ if (e instanceof ConnectionsError && e.status === 401) setNeedsToken(true);+ else setError(e instanceof Error ? e.message : 'Something went wrong.');+ } finally {+ if (alive.current) setLoading(false);+ }+ }, []);++ useEffect(() => {+ alive.current = true;+ load();+ window.addEventListener(PERSON_SIGNED_IN_EVENT, load);+ return () => {+ alive.current = false;+ window.removeEventListener(PERSON_SIGNED_IN_EVENT, load);+ };+ }, [load]);++ const check = async (c: Connection) => {+ const sid = mcpServerId(c);+ if (!sid || checking) return;+ setChecking(c.id);+ setNotice(null);+ try {+ const r = await connectionsApi.testMcp(sid);+ if (alive.current) setNotice(r.ok === false ? { text: `${c.name}: ${r.error || 'the check failed.'}`, error: true } : { text: `${c.name} answered.`, error: false });+ } catch (e) {+ if (alive.current) setNotice({ text: `Couldn’t check ${c.name}: ${e instanceof Error ? e.message : 'something went wrong.'}`, error: true });+ } finally {+ if (alive.current) setChecking(null);+ load();+ }+ };++ const addComposio = async (url: string, apiKey: string, enabled: boolean): Promise<string | null> => {+ try {+ await connectionsApi.addComposio(apiKey ? { url, api_key: apiKey, enabled } : { url, enabled });+ setNotice({ text: enabled ? 'Composio is added and on.' : 'Composio is added and off. Turn it on in Tools when you want bots to use it.', error: false });+ load();+ return null;+ } catch (e) {+ return composioErrorText(e);+ }+ };++ return (+ <>+ <ConnectionsView+ data={data}+ loading={loading}+ error={error}+ needsToken={needsToken}+ notice={notice}+ checking={checking}+ onRefresh={load}+ onCheck={check}+ onUnlockVault={() => setUnlocking(true)}+ onAddComposio={addComposio}+ onBack={onBack}+ {...links}+ />+ {unlocking && (+ <UnlockDialog+ status={store.status}+ onClose={() => setUnlocking(false)}+ onUnlocked={(s) => {+ store.set(s);+ load();+ }}+ />+ )}+ </>+ );+};diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsxindex 2c21bca6..03440930 100644--- a/frontend/src/components/Sidebar.tsx+++ b/frontend/src/components/Sidebar.tsx@@ -1,5 +1,5 @@import React, { useCallback, useEffect, useState } from 'react';-import { Hash, Plus, CheckCircle2, AlertTriangle, Loader2, Users, ChevronDown, Settings2, X, Crown, UserPlus, Pencil, Inbox, Search, CalendarClock, ShieldOff, ListChecks, Split, Hand } from 'lucide-react';+import { Hash, Plus, CheckCircle2, AlertTriangle, Loader2, Users, ChevronDown, Settings2, X, Crown, UserPlus, Pencil, Inbox, Search, CalendarClock, ShieldOff, ListChecks, Split, Hand, Plug } from 'lucide-react';import { ModernAvatar } from './ModernAvatar';import { playSfx } from '../audio/chiptune';import { badgeText } from '../away';@@ -93,6 +93,8 @@ export interface SidebarProps {awayCount?: number;awayActive?: boolean;looseActive?: boolean;+ connectionsActive?: boolean;+ onOpenConnections?: () => void;onOpenLooseEnds?: () => void;parallelActive?: boolean;onOpenParallel?: () => void;@@ -149,6 +151,8 @@ export const Sidebar: React.FC<SidebarProps> = ({awayCount = 0,awayActive = false,looseActive = false,+ connectionsActive = false,+ onOpenConnections,parallelActive = false,onOpenParallel,onOpenLooseEnds,@@ -298,6 +302,12 @@ export const Sidebar: React.FC<SidebarProps> = ({<span className="truncate flex-1">Parallel Universe</span></button>)}+ {onOpenConnections && (+ <button type="button" onClick={onOpenConnections} aria-current={connectionsActive ? 'page' : undefined} className={navRow(connectionsActive)}>+ <Plug size={15} className={connectionsActive ? 'text-sky-400' : 'text-zinc-500'} aria-hidden="true" />+ <span className="truncate flex-1">Connections</span>+ </button>+ )}<button type="button" onClick={onOpenRoutines} className={navRow(false)}><CalendarClock size={15} className="text-zinc-500" aria-hidden="true" /><span className="truncate flex-1">Routines</span>diff --git a/frontend/src/connections.ts b/frontend/src/connections.tsnew file mode 100644index 00000000..3d7e9ce9--- /dev/null+++ b/frontend/src/connections.ts@@ -0,0 +1,210 @@+// Connections: one list of everything the bots reach outside the app (MCP servers, engine+// accounts, website logins in the vault, the mail and GitHub sources of Loose ends), with status,+// last check, who uses it and where its sign-in is stored. Person-only (docs/connections.md).+//+// Composio is an optional connector, off by default. Wherever it is offered or listed, the page+// says that it keeps sign-ins on Composio's servers.++import { PersonCancelledError, personFetch } from './auth';++export type ConnectionKind = 'mcp' | 'account' | 'browser_login' | 'email' | 'github';+export type ConnectionStatus = 'connected' | 'needs_sign_in' | 'limited' | 'error' | 'off' | 'locked' | 'unknown';+export type LoginsStored = 'vault' | 'kwnt' | 'composio';++export interface UsedBy {+ id: string;+ name: string;+}++export interface Connection {+ id: string;+ kind: ConnectionKind | string;+ name: string;+ detail: string | null;+ status: ConnectionStatus | string;+ status_detail: string | null;+ last_check: string | null;+ used_by: UsedBy[];+ logins_stored: LoginsStored | string;+ manage: string;+}++export interface CatalogEntry {+ id: string;+ kind: string;+ name: string;+ description: string;+ optional: boolean;+ added: boolean;+ connection_id: string | null;+ enabled: boolean;+ logins_stored: string;+ warning: string;+ add: string;+}++export interface VaultSummary {+ status: 'ok' | 'locked' | 'unavailable' | string;+ logins?: number;+ detail?: string;+}++export interface ConnectionsList {+ connections: Connection[];+ counts: Partial<Record<string, number>>;+ vault: VaultSummary;+ catalog: CatalogEntry[];+}++export class ConnectionsError extends Error {+ constructor(message: string, public status: number) {+ super(message);+ }+}++const sentence = (s: string) => {+ const t = s.trim();+ const up = t.charAt(0).toUpperCase() + t.slice(1);+ return /[.!?]$/.test(up) ? up : `${up}.`;+};++async function call<T>(url: string, method = 'GET', body?: unknown): Promise<T> {+ let res: Response;+ try {+ res = await personFetch(url, {+ method,+ cache: 'no-store',+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },+ body: body === undefined ? undefined : JSON.stringify(body),+ });+ } 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);+ }+ 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('This server doesn’t list connections yet. Update the app and try again.', 404);+ throw new ConnectionsError(typeof err === 'string' && err.trim() ? sentence(err) : `Something went wrong (HTTP ${res.status}).`, res.status);+}++const enc = encodeURIComponent;++export const connectionsApi = {+ list: () => call<ConnectionsList>('/api/connections'),+ addComposio: (body: ComposioBody) => call<{ connection_id: string; warning: string }>('/api/connections/composio', 'POST', body),+ /** "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'),+};++/** The groups the page shows, in order. */+export const GROUPS: Array<{ key: string; kinds: string[]; label: string; empty: string }> = [+ { key: 'mcp', kinds: ['mcp'], label: 'Tool servers (MCP)', empty: 'No tool servers yet.' },+ { key: 'account', kinds: ['account'], label: 'Engine accounts', empty: 'No engine accounts yet.' },+ { key: 'browser_login', kinds: ['browser_login'], label: 'Saved website logins', empty: 'No saved website logins.' },+ { key: 'sources', kinds: ['email', 'github'], label: 'Mail and GitHub (Loose ends)', empty: 'No mail or GitHub sources.' },+];++export function groupConnections(list: Connection[]): Array<{ key: string; label: string; empty: string; items: Connection[] }> {+ const known = new Set(GROUPS.flatMap((g) => g.kinds));+ const groups = GROUPS.map((g) => ({ key: g.key, label: g.label, empty: g.empty, items: list.filter((c) => g.kinds.includes(c.kind)) }));+ const other = list.filter((c) => !known.has(c.kind));+ if (other.length) groups.push({ key: 'other', label: 'Other', empty: '', items: other });+ return groups;+}++export type Tone = 'emerald' | 'amber' | 'rose' | 'zinc';++/** The badge for a status: always words, never colour alone. */+export function statusBadge(status: string): { label: string; tone: Tone } {+ switch (status) {+ case 'connected':+ return { label: 'Connected', tone: 'emerald' };+ case 'needs_sign_in':+ return { label: 'Needs sign-in', tone: 'amber' };+ case 'limited':+ return { label: 'Limited', tone: 'amber' };+ case 'error':+ return { label: 'Error', tone: 'rose' };+ case 'off':+ return { label: 'Off', tone: 'zinc' };+ case 'locked':+ return { label: 'Locked', tone: 'amber' };+ default:+ return { label: 'Not checked', tone: 'zinc' };+ }+}++/** Statuses that need the person. */+export const needsAttention = (status: string) => status === 'needs_sign_in' || status === 'error' || status === 'limited' || status === 'locked';++/** "4 connected · 1 needs you · 1 off" for the page header. */+export function countsLine(list: Connection[]): string {+ if (list.length === 0) return 'Nothing connected yet';+ const connected = list.filter((c) => c.status === 'connected').length;+ const attention = list.filter((c) => needsAttention(c.status)).length;+ const off = list.filter((c) => c.status === 'off').length;+ const parts = [`${connected} connected`];+ if (attention) parts.push(`${attention} ${attention === 1 ? 'needs' : 'need'} you`);+ if (off) parts.push(`${off} off`);+ return parts.join(' · ');+}++export function storedLabel(stored: string, kind = ''): string {+ if (kind === 'mcp' && stored === 'kwnt') return 'Keys and settings kept on this computer';+ switch (stored) {+ case 'vault':+ return 'Login in your vault';+ case 'kwnt':+ return 'Login kept on this computer';+ case 'composio':+ return 'Login on Composio’s servers';+ default:+ return `Login stored: ${stored}`;+ }+}++/** "Ada, Lin and 3 more", or who uses it when nobody does. */+export function usedByText(used: UsedBy[], status: string): string {+ if (used.length === 0) return status === 'off' ? 'No bot while it’s off' : 'No bot uses it';+ const names = used.map((u) => u.name);+ if (names.length <= 3) return names.length === 1 ? names[0] : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;+ return `${names.slice(0, 2).join(', ')} and ${names.length - 2} more`;+}++/** The MCP server id inside a connection id (`mcp:<id>`), for "Check now". */+export const mcpServerId = (c: Pick<Connection, 'id' | 'kind'>): string | null =>+ c.kind === 'mcp' && c.id.startsWith('mcp:') ? c.id.slice(4) : null;++export const isComposioUrl = (raw: string): boolean => {+ try {+ const u = new URL(raw.trim());+ const h = u.hostname.toLowerCase();+ return u.protocol === 'https:' && (h === 'composio.dev' || h.endsWith('.composio.dev'));+ } catch {+ return false;+ }+};++export interface ComposioBody {+ url: string;+ api_key?: string;+ enabled: boolean;+}++/** The add form as the API wants it, or why it can't be sent yet. */+export function composioBody(url: string, apiKey: string, enabled: boolean): ComposioBody | { error: string } {+ const u = url.trim();+ if (!u) return { error: 'Paste the MCP URL from your Composio dashboard.' };+ if (!isComposioUrl(u)) return { error: 'That isn’t a Composio address. It should start with https:// and end in composio.dev.' };+ const key = apiKey.trim();+ return key ? { url: u, api_key: key, enabled } : { url: u, enabled };+}++/** What the add form says when the server refuses. */+export function composioErrorText(e: unknown): string {+ if (e instanceof ConnectionsError && e.status === 409) return 'Composio is already added. Change it under Tools instead.';+ if (e instanceof ConnectionsError && e.status === 400) return e.message;+ return e instanceof Error ? e.message : 'Something went wrong.';+}diff --git a/frontend/tests/connections.test.mjs b/frontend/tests/connections.test.mjsnew file mode 100644index 00000000..a671c3bd--- /dev/null+++ b/frontend/tests/connections.test.mjs@@ -0,0 +1,146 @@+// Connections (docs/connections.md): every connection with status, last check, who uses it and+// where its login is stored. Composio is optional, off by default, and always says that it keeps+// sign-ins on Composio's servers.+import assert from 'node:assert/strict';+import test from 'node:test';+import { loadBundled } from './bundle.mjs';++globalThis.localStorage ??= { getItem: () => null, setItem: () => {}, removeItem: () => {} };++const m = await loadBundled(`export * from './src/connections';`);+const ui = await loadBundled(`+ import React from 'react';+ import { renderToStaticMarkup } from 'react-dom/server.browser';+ import { ConnectionsView, ConnectionRow, ComposioCard } from './src/components/ConnectionsView';+ export const view = (props) => renderToStaticMarkup(React.createElement(ConnectionsView, props));+ export const row = (props) => renderToStaticMarkup(React.createElement('ul', null, React.createElement(ConnectionRow, props)));+ export const composio = (props) => renderToStaticMarkup(React.createElement('ul', null, React.createElement(ComposioCard, props)));+`);++const NOW = Date.parse('2026-10-22T12:00:00Z');+const WARNING = "Composio keeps your app sign-ins on Composio's servers, not in kwnt's vault, and your bots' tool calls through it pass through Composio.";+// Shaped like Connection in src/server/connections.rs.+const conn = (over = {}) => ({+ id: 'mcp:s1', kind: 'mcp', name: 'github', detail: 'api.githubcopilot.com', status: 'connected', status_detail: null,+ last_check: '2026-10-22T11:55:00Z', used_by: [{ id: 'k1', name: 'Ada' }, { id: 'k2', name: 'Lin' }], logins_stored: 'kwnt',+ manage: '/api/mcp/servers/s1', ...over,+});+const composioEntry = (over = {}) => ({+ id: 'composio', kind: 'mcp', name: 'Composio', description: 'Hundreds of apps through one MCP server you set up at composio.dev.',+ optional: true, added: false, connection_id: null, enabled: false, logins_stored: 'composio', warning: WARNING, add: '/api/connections/composio', ...over,+});+const list = (over = {}) => ({+ connections: [+ conn(),+ conn({ id: 'account:p1', kind: 'account', name: 'Claude', detail: 'claude · [email protected]', status: 'limited', status_detail: 'Out of quota until 14:00', last_check: null, logins_stored: 'kwnt', manage: '/api/profiles/p1' }),+ conn({ id: 'login:k1:c1', kind: 'browser_login', name: 'github.com', detail: 'me @ https://github.com · saved for Ada', logins_stored: 'vault', used_by: [{ id: 'k1', name: 'Ada' }] }),+ conn({ id: 'source:m1', kind: 'email', name: 'Work mail', detail: 'me @ imap.example.com', status: 'error', status_detail: 'Login refused', logins_stored: 'vault' }),+ ],+ counts: { connected: 2, limited: 1, error: 1 },+ vault: { status: 'ok', logins: 1 },+ catalog: [composioEntry()],+ ...over,+});+const noop = () => {};+const viewProps = (over = {}) => ({ data: list(), loading: false, error: null, now: NOW, onRefresh: noop, onAddComposio: async () => null, ...over });++test('connections group by kind in a fixed order, and unknown kinds still show', () => {+ const g = m.groupConnections([...list().connections, conn({ id: 'x:1', kind: 'calendar', name: 'Cal' })]);+ assert.deepEqual(g.map((x) => x.key), ['mcp', 'account', 'browser_login', 'sources', 'other']);+ assert.deepEqual(g.map((x) => x.items.length), [1, 1, 1, 1, 1]);+});++test('every status has words, not just a colour, and the header counts what needs the person', () => {+ for (const s of ['connected', 'needs_sign_in', 'limited', 'error', 'off', 'locked', 'unknown', 'new_thing']) assert.ok(m.statusBadge(s).label);+ assert.equal(m.statusBadge('weird').label, 'Not checked');+ assert.equal(m.countsLine(list().connections), '2 connected · 2 need you');+ assert.equal(m.countsLine([conn({ status: 'off' })]), '0 connected · 1 off');+ assert.equal(m.countsLine([]), 'Nothing connected yet');+});++test('used-by reads as a sentence and stays short', () => {+ const b = (n) => Array.from({ length: n }, (_, i) => ({ id: `k${i}`, name: `Bot${i}` }));+ assert.equal(m.usedByText(b(1), 'connected'), 'Bot0');+ assert.equal(m.usedByText(b(3), 'connected'), 'Bot0, Bot1 and Bot2');+ assert.equal(m.usedByText(b(6), 'connected'), 'Bot0, Bot1 and 4 more');+ assert.equal(m.usedByText([], 'off'), 'No bot while it’s off');+ assert.equal(m.usedByText([], 'connected'), 'No bot uses it');+});++test('only https composio.dev addresses are accepted, and the key is optional', () => {+ assert.equal(m.isComposioUrl('https://backend.composio.dev/v3/mcp/abc/mcp?user_id=1'), true);+ assert.equal(m.isComposioUrl('https://composio.dev/x'), true);+ assert.equal(m.isComposioUrl('http://backend.composio.dev/x'), false);+ assert.equal(m.isComposioUrl('https://composio.dev.evil.example/x'), false);+ assert.equal(m.isComposioUrl('https://evilcomposio.dev/x'), false);+ assert.ok('error' in m.composioBody('', '', false));+ assert.ok('error' in m.composioBody('https://example.com/mcp', 'k', false));+ assert.deepEqual(m.composioBody(' https://backend.composio.dev/m ', '', false), { url: 'https://backend.composio.dev/m', enabled: false });+ assert.deepEqual(m.composioBody('https://backend.composio.dev/m', ' key ', true), { url: 'https://backend.composio.dev/m', api_key: 'key', enabled: true });+ assert.match(m.composioErrorText(new m.ConnectionsError('x', 409)), /already added/);+});++test('a row shows name, detail, status words, why, used-by, last check and where the login lives', () => {+ const html = ui.row({ c: conn({ status: 'error', status_detail: 'Connection refused' }), now: NOW, onCheck: noop, links: { onOpenTools: noop } });+ for (const t of ['github', 'api.githubcopilot.com', 'Error', 'Connection refused', 'Ada and Lin', 'Checked 5 min ago', 'Keys and settings kept on this computer', 'Check now', 'Manage']) {+ assert.ok(html.includes(t), `row shows "${t}"`);+ }+ assert.ok(ui.row({ c: conn({ last_check: null }), now: NOW }).includes('Never checked'));+ assert.ok(ui.row({ c: conn({ id: 'account:p1', kind: 'account' }), now: NOW }).includes('Login kept on this computer'), 'an account keeps a login, a tool server keeps keys');+ assert.ok(!ui.row({ c: conn({ status: 'off' }), now: NOW, onCheck: noop }).includes('Check now'), 'no check for a server that is off');+ assert.ok(!ui.row({ c: conn({ id: 'account:p1', kind: 'account' }), now: NOW, onCheck: noop }).includes('Check now'), 'only MCP servers can be checked');+});++test('a Composio connection is marked as storing its login on Composio’s servers', () => {+ const html = ui.row({ c: conn({ name: 'composio', logins_stored: 'composio' }), now: NOW });+ assert.ok(html.includes('Login on Composio’s servers'));+ assert.ok(html.includes('text-amber-200'));+});++test('the page groups rows, counts them, and offers Composio as optional with its warning', () => {+ 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']) {+ assert.ok(html.includes(t), `page shows "${t}"`);+ }+ assert.ok(html.includes('Composio keeps your app sign-ins on Composio's servers'), 'the warning is next to the add button');+});++test('the add form is off by default and repeats nothing secret', () => {+ const html = ui.composio({ entry: composioEntry(), initialOpen: true, onAdd: async () => null });+ assert.match(html, /type="url"/);+ assert.match(html, /type="password"/);+ assert.match(html, /<input type="checkbox"[^>]*>/);+ assert.doesNotMatch(html, /type="checkbox"[^>]*checked/, 'the switch starts off');+ assert.ok(html.includes('Off by default'));+ assert.ok(html.includes('Composio keeps your app sign-ins'));+ assert.ok(html.includes('MCP URL') && html.includes('API key'));+});++test('once added, Composio says whether it is on and points at Tools instead of a second add', () => {+ const off = ui.composio({ entry: composioEntry({ added: true, connection_id: 'mcp:c1' }), onAdd: async () => null, onOpenTools: noop });+ assert.ok(off.includes('Added · off') && off.includes('Turn on in Tools'));+ assert.ok(!off.includes('Add Composio'));+ assert.ok(off.includes('Composio keeps your app sign-ins'), 'the warning stays once added');+ const on = ui.composio({ entry: composioEntry({ added: true, enabled: true }), onAdd: async () => null, onOpenTools: noop });+ assert.ok(on.includes('Added · on') && on.includes('Manage in Tools'));+});++test('a locked vault hides saved logins and offers to unlock; loading, error and token states show', () => {+ const locked = ui.view(viewProps({ data: list({ connections: [conn()], vault: { status: 'locked' } }), onUnlockVault: noop }));+ assert.ok(locked.includes('Unlock Bitwarden to list saved logins.'));+ assert.ok(locked.includes('Unlock Bitwarden</button>'));+ assert.ok(locked.includes('Hidden while Bitwarden is locked.'));+ const unavailable = ui.view(viewProps({ data: list({ vault: { status: 'unavailable' } }) }));+ assert.ok(unavailable.includes('can’t be read right now'));+ assert.ok(ui.view(viewProps({ data: null, loading: true })).includes('Loading…'));+ const err = ui.view(viewProps({ data: null, error: 'Something went wrong (HTTP 500).' }));+ assert.ok(err.includes('Couldn’t load connections') && err.includes('Retry'));+ assert.ok(ui.view(viewProps({ data: null, needsToken: true })).includes('Confirm it’s you'));+});++test('empty groups say so instead of leaving a gap', () => {+ const html = ui.view(viewProps({ data: list({ connections: [], catalog: [] }) }));+ assert.ok(html.includes('Nothing connected yet'));+ for (const t of ['No tool servers yet.', 'No engine accounts yet.', 'No saved website logins.', 'No mail or GitHub sources.']) assert.ok(html.includes(t));+ assert.ok(!html.includes('Optional connectors'));+});