feat(memory-sources): disable non-syncable toolkits in Add Source picker (#3395)

This commit is contained in:
Cyrus Gray
2026-06-05 17:44:55 +05:30
committed by GitHub
parent ec5c26c170
commit c23d6ff20c
21 changed files with 558 additions and 41 deletions
@@ -8,19 +8,35 @@
* presents them as a dropdown — the user picks an existing OAuth
* connection rather than typing toolkit + connection_id.
*/
import { useCallback, useEffect, useMemo, useState } from 'react';
import debug from 'debug';
import {
type KeyboardEvent as ReactKeyboardEvent,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { listConnections } from '../../lib/composio/composioApi';
import type { ComposioConnection } from '../../lib/composio/types';
import { useT } from '../../lib/i18n/I18nContext';
import {
addMemorySource,
getSupportedToolkits,
type MemorySourceEntry,
SOURCE_KIND_ICONS,
SOURCE_KIND_LABEL_KEYS,
type SourceKind,
} from '../../services/memorySourcesService';
const log = debug('intelligence:add-memory-source-dialog');
/** Safe, PII-free string for an unknown error — message/name only, no stack. */
function errMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
interface AddMemorySourceDialogProps {
open: boolean;
onClose: () => void;
@@ -56,10 +72,14 @@ export function AddMemorySourceDialog({ open, onClose, onAdded }: AddMemorySourc
// Composio connection picker state
const [connections, setConnections] = useState<ComposioConnection[]>([]);
const [loadingConnections, setLoadingConnections] = useState(false);
// Toolkit slugs that can actually sync (backend registry). `null` means the
// set hasn't loaded (or the RPC failed) — in that case we treat every
// connection as supported rather than locking the user out of all of them.
const [supportedToolkits, setSupportedToolkits] = useState<string[] | null>(null);
// Fetch composio connections when user picks the composio kind.
// setState calls live inside the spawned async closure (not the
// synchronous effect body) to satisfy `react-hooks/set-state-in-effect`.
// Fetch composio connections + the supported-toolkit set when the user picks
// the composio kind. setState calls live inside the spawned async closure
// (not the synchronous effect body) to satisfy `react-hooks/set-state-in-effect`.
useEffect(() => {
if (kind !== 'composio') return undefined;
let cancelled = false;
@@ -67,12 +87,21 @@ export function AddMemorySourceDialog({ open, onClose, onAdded }: AddMemorySourc
if (cancelled) return;
setLoadingConnections(true);
try {
const resp = await listConnections();
const [resp, toolkits] = await Promise.all([
listConnections(),
getSupportedToolkits().catch((err: unknown) => {
// Non-fatal: fall back to "everything supported" so the picker
// still works if the supported-toolkit RPC is unavailable.
log('[composio-picker] getSupportedToolkits failed: %s', errMessage(err));
return null;
}),
]);
if (cancelled) return;
setConnections(resp.connections);
setSupportedToolkits(toolkits);
} catch (err) {
if (cancelled) return;
console.warn('[ui-flow][add-memory-source] listConnections failed', err);
log('[add-memory-source] listConnections failed: %s', errMessage(err));
setError(t('memorySources.composioListFailed'));
} finally {
if (!cancelled) setLoadingConnections(false);
@@ -230,6 +259,7 @@ export function AddMemorySourceDialog({ open, onClose, onAdded }: AddMemorySourc
setSelector={setSelector}
connections={connections}
loadingConnections={loadingConnections}
supportedToolkits={supportedToolkits}
connectionId={connectionId}
setConnection={(connId, tk, identityLabel) => {
setConnectionId(connId);
@@ -405,6 +435,8 @@ interface KindFieldsProps {
setSelector: (v: string) => void;
connections: ComposioConnection[];
loadingConnections: boolean;
/** Syncable toolkit slugs; `null` while unknown (treat all as supported). */
supportedToolkits: string[] | null;
connectionId: string;
setConnection: (connectionId: string, toolkit: string, identityLabel: string) => void;
}
@@ -527,9 +559,7 @@ export function deduplicateConnections(
for (const conn of sorted) {
// Always dedup by raw connection id to guard against identity-less dupes.
if (seen.has(conn.id)) {
console.debug(
`[ui-flow][composio-picker] dropping duplicate connection toolkit=${conn.toolkit} id=${conn.id}`
);
log('[composio-picker] dropping duplicate connection toolkit=%s', conn.toolkit);
continue;
}
seen.add(conn.id);
@@ -538,9 +568,7 @@ export function deduplicateConnections(
if (identity) {
const key = `${conn.toolkit}:${identity}`;
if (seen.has(key)) {
console.debug(
`[ui-flow][composio-picker] dropping duplicate connection toolkit=${conn.toolkit} id=${conn.id}`
);
log('[composio-picker] dropping duplicate connection toolkit=%s', conn.toolkit);
continue;
}
seen.add(key);
@@ -554,20 +582,83 @@ export function deduplicateConnections(
return result;
}
/** A connection is syncable when its toolkit ships a provider. A `null`
* supported-set means "unknown" — treat everything as supported so a failed
* lookup never disables the whole picker. */
function isToolkitSupported(toolkit: string, supportedToolkits: string[] | null): boolean {
if (supportedToolkits === null) return true;
return supportedToolkits.includes(toolkit.trim().toLowerCase());
}
interface PickerEntry {
conn: ComposioConnection;
label: string;
supported: boolean;
}
function ComposioPicker({
connections,
loadingConnections,
supportedToolkits,
connectionId,
setConnection,
}: KindFieldsProps) {
const { t } = useT();
const [open, setOpen] = useState(false);
// Index (into `entries`) of the keyboard-highlighted option; -1 when none.
const [activeIndex, setActiveIndex] = useState(-1);
const containerRef = useRef<HTMLDivElement>(null);
const buttonRef = useRef<HTMLButtonElement>(null);
const listboxRef = useRef<HTMLUListElement>(null);
// useMemo must be declared before any early returns (Rules of Hooks).
const accountLabel = t('memorySources.connectionAccount');
const dedupedConnections = useMemo(
() => deduplicateConnections(connections, accountLabel),
[connections, accountLabel]
const entries = useMemo<PickerEntry[]>(() => {
const deduped = deduplicateConnections(connections, accountLabel).map(({ conn, label }) => ({
conn,
label,
supported: isToolkitSupported(conn.toolkit, supportedToolkits),
}));
// Supported connections first so the actionable ones surface at the top;
// stable within each partition (dedup already ranked by health/status).
return [...deduped.filter(e => e.supported), ...deduped.filter(e => !e.supported)];
}, [connections, accountLabel, supportedToolkits]);
// Indexes of keyboard-selectable (supported) options — unsupported rows are
// skipped during arrow navigation, mirroring a native <select>'s disabled opts.
const selectableIndexes = useMemo(
() => entries.map((e, i) => (e.supported ? i : -1)).filter(i => i >= 0),
[entries]
);
const selected = entries.find(e => e.conn.id === connectionId) ?? null;
// Close the popover on outside click or Escape.
useEffect(() => {
if (!open) return undefined;
const onPointerDown = (event: MouseEvent) => {
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
setOpen(false);
}
};
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') setOpen(false);
};
document.addEventListener('mousedown', onPointerDown);
document.addEventListener('keydown', onKeyDown);
return () => {
document.removeEventListener('mousedown', onPointerDown);
document.removeEventListener('keydown', onKeyDown);
};
}, [open]);
// Move keyboard focus into the listbox when it opens so arrow keys work
// immediately. This is a DOM side-effect only — the highlighted index is set
// in the open/close handlers, not here, to avoid setState-in-effect churn.
useEffect(() => {
if (open) listboxRef.current?.focus();
}, [open]);
if (loadingConnections) {
return (
<p className="text-xs text-stone-500 dark:text-neutral-400">
@@ -584,30 +675,177 @@ function ComposioPicker({
);
}
// Highlight the current selection (or first selectable option) and open.
const openListbox = () => {
const selIdx = entries.findIndex(e => e.conn.id === connectionId && e.supported);
setActiveIndex(selIdx >= 0 ? selIdx : (selectableIndexes[0] ?? -1));
setOpen(true);
};
const close = (returnFocus = true) => {
setActiveIndex(-1);
setOpen(false);
if (returnFocus) buttonRef.current?.focus();
};
const select = (entry: PickerEntry) => {
if (!entry.supported) {
log('[composio-picker] ignoring selection of unsupported toolkit=%s', entry.conn.toolkit);
return;
}
setConnection(entry.conn.id, entry.conn.toolkit, entry.label);
close();
};
// Move the highlight to the next/previous selectable option, wrapping around.
const moveActive = (dir: 1 | -1) => {
if (selectableIndexes.length === 0) return;
const pos = selectableIndexes.indexOf(activeIndex);
const nextPos =
pos === -1
? dir === 1
? 0
: selectableIndexes.length - 1
: (pos + dir + selectableIndexes.length) % selectableIndexes.length;
setActiveIndex(selectableIndexes[nextPos]);
};
const onButtonKeyDown = (event: ReactKeyboardEvent<HTMLButtonElement>) => {
// Open with the arrow keys; Enter/Space already toggle via onClick.
if (!open && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) {
event.preventDefault();
openListbox();
}
};
const onListKeyDown = (event: ReactKeyboardEvent<HTMLUListElement>) => {
switch (event.key) {
case 'ArrowDown':
event.preventDefault();
moveActive(1);
break;
case 'ArrowUp':
event.preventDefault();
moveActive(-1);
break;
case 'Home':
event.preventDefault();
if (selectableIndexes.length) setActiveIndex(selectableIndexes[0]);
break;
case 'End':
event.preventDefault();
if (selectableIndexes.length)
setActiveIndex(selectableIndexes[selectableIndexes.length - 1]);
break;
case 'Enter':
case ' ':
event.preventDefault();
if (activeIndex >= 0 && entries[activeIndex]) select(entries[activeIndex]);
break;
case 'Escape':
event.preventDefault();
close();
break;
case 'Tab':
// Let focus leave naturally, but collapse the popover.
setOpen(false);
break;
default:
break;
}
};
const LISTBOX_ID = 'composio-connection-listbox';
const optionId = (entry: PickerEntry) => `composio-opt-${entry.conn.id}`;
const activeOptionId =
activeIndex >= 0 && entries[activeIndex] ? optionId(entries[activeIndex]) : undefined;
return (
<label className="block">
<div className="block" ref={containerRef}>
<span className="text-xs font-medium text-stone-600 dark:text-neutral-400">
{t('memorySources.pickConnection')}
</span>
<select
value={connectionId}
onChange={e => {
const entry = dedupedConnections.find(({ conn }) => conn.id === e.target.value);
if (entry) {
setConnection(entry.conn.id, entry.conn.toolkit, entry.label);
}
}}
className="mt-1 block w-full rounded-md border border-stone-300 bg-white px-3 py-2
text-sm text-stone-900 focus:border-primary-400 focus:outline-none
focus:ring-1 focus:ring-primary-400 dark:border-neutral-600
dark:bg-neutral-800 dark:text-neutral-100 dark:focus:border-primary-500">
<option value="">{t('memorySources.selectConnection')}</option>
{dedupedConnections.map(({ conn, label }) => (
<option key={conn.id} value={conn.id}>
{label}
</option>
))}
</select>
</label>
<div className="relative mt-1">
<button
ref={buttonRef}
type="button"
data-testid="composio-connection-picker"
aria-haspopup="listbox"
aria-expanded={open}
aria-controls={open ? LISTBOX_ID : undefined}
onClick={() => (open ? close(false) : openListbox())}
onKeyDown={onButtonKeyDown}
className="flex w-full items-center justify-between rounded-md border border-stone-300
bg-white px-3 py-2 text-left text-sm text-stone-900
focus:border-primary-400 focus:outline-none focus:ring-1 focus:ring-primary-400
dark:border-neutral-600 dark:bg-neutral-800 dark:text-neutral-100
dark:focus:border-primary-500">
<span className={selected ? '' : 'text-stone-400 dark:text-neutral-500'}>
{selected ? selected.label : t('memorySources.selectConnection')}
</span>
<span aria-hidden className="ml-2 text-stone-400 dark:text-neutral-500">
</span>
</button>
{open && (
<ul
ref={listboxRef}
id={LISTBOX_ID}
role="listbox"
tabIndex={-1}
aria-label={t('memorySources.pickConnection')}
aria-activedescendant={activeOptionId}
onKeyDown={onListKeyDown}
data-testid="composio-connection-listbox"
className="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md border
border-stone-200 bg-white py-1 shadow-lg focus:outline-none
dark:border-neutral-700 dark:bg-neutral-800">
{entries.map((entry, index) => {
const isSelected = entry.conn.id === connectionId;
const isActive = index === activeIndex;
return (
<li
key={entry.conn.id}
id={optionId(entry)}
role="option"
aria-selected={isSelected}
aria-disabled={!entry.supported}
data-testid={`composio-option-${entry.conn.id}`}
data-supported={entry.supported}
data-active={isActive}
onClick={() => select(entry)}
onMouseEnter={() => entry.supported && setActiveIndex(index)}
className={[
'flex items-center justify-between gap-2 px-3 py-2 text-sm',
entry.supported
? 'cursor-pointer text-stone-800 dark:text-neutral-200'
: 'cursor-not-allowed text-stone-400 dark:text-neutral-500',
isActive && entry.supported ? 'bg-primary-50 dark:bg-primary-500/10' : '',
].join(' ')}>
<span className="flex items-center gap-2 truncate">
{isSelected && entry.supported && (
<span aria-hidden className="text-primary-500">
</span>
)}
<span className="truncate">{entry.label}</span>
</span>
{!entry.supported && (
<span
data-testid={`composio-option-coming-soon-${entry.conn.id}`}
className="shrink-0 rounded-full bg-stone-100 px-2 py-0.5 text-[10px]
font-medium uppercase tracking-wide text-stone-500
dark:bg-neutral-700 dark:text-neutral-400">
{t('memorySources.comingSoon')}
</span>
)}
</li>
);
})}
</ul>
)}
</div>
</div>
);
}