AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
import {
Permission,
connectionTemplate,
isNil,
} from '@activepieces/core-utils';
import {
PieceMetadataModel,
PieceMetadataModelSummary,
} from '@activepieces/pieces-framework';
import {
AppConnectionScope,
AppConnectionStatus,
AppConnectionWithoutSensitiveData,
PieceAudienceFilter,
} from '@activepieces/shared';
import { t } from 'i18next';
import {
Plus,
Globe,
Key,
Cable,
Check,
Unplug,
X,
LucideIcon,
} from 'lucide-react';
import { useState } from 'react';
import { CreateOrEditConnectionDialog } from '@/app/connections/create-edit-connection-dialog';
import { PermissionNeededTooltip } from '@/components/custom/permission-needed-tooltip';
import { SearchableSelect } from '@/components/custom/searchable-select';
import { Button } from '@/components/ui/button';
import {
Select,
SelectAction,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from '@/components/ui/tooltip';
import {
appConnectionsQueries,
appConnectionUtils,
} from '@/features/connections';
import { piecesHooks } from '@/features/pieces';
import {
useAuthorization,
useIsPlatformAdmin,
} from '@/hooks/authorization-hooks';
import { authenticationSession } from '@/lib/authentication-session';
import { cn } from '@/lib/utils';
export function ConnectionSelect({
piece,
value,
onChange,
disabled,
}: ConnectionSelectProps) {
const [connectionDialogOpen, setConnectionDialogOpen] = useState(false);
const [selectConnectionOpen, setSelectConnectionOpen] = useState(false);
const [reconnectConnection, setReconnectConnection] =
useState<AppConnectionWithoutSensitiveData | null>(null);
//in case of reconnection we need to use the piece version from the connection
const { pieceModel: pieceWithCorrectVersion, isLoading: isLoadingPiece } =
piecesHooks.usePiece({
name: piece.name,
version: reconnectConnection?.pieceVersion ?? piece.version,
audience: PieceAudienceFilter.ALL,
});
const hasPermissionToCreateConnection = useAuthorization().checkAccess(
Permission.WRITE_APP_CONNECTION,
);
const {
data: connections,
isLoading: isLoadingConnections,
isError: isConnectionsError,
refetch,
} = appConnectionsQueries.useAppConnections({
request: {
pieceName: piece.name,
projectId: authenticationSession.getProjectId()!,
limit: 1000,
},
pieceAuth: piece.auth,
extraKeys: [piece.name, authenticationSession.getProjectId()!],
staleTime: 0,
});
const selectedConnection = connections?.data?.find(
(connection) =>
connection.externalId === connectionTemplate.unwrapExternalId(value),
);
const isSelectedConnectionGlobal =
selectedConnection?.scope === AppConnectionScope.PLATFORM;
// The create/reconnect dialog runs in global (PLATFORM) scope ONLY when
// reconnecting an existing global connection. Creating a brand-new connection
// from a project flow must default to PROJECT scope, otherwise it silently
// inherits the selected connection's platform scope and (for non-admins) hits
// the platform-admin-only global-connections endpoint (GIT-1587).
const isReconnectingGlobalConnection =
reconnectConnection?.scope === AppConnectionScope.PLATFORM;
const isPlatformAdmin = useIsPlatformAdmin();
const statusDisplay = selectedConnection
? getConnectionStatusDisplay(selectedConnection.status)
: null;
const canShowConnectionStatus =
!!selectedConnection && (!isSelectedConnectionGlobal || isPlatformAdmin);
const openReconnectDialog = () => {
setReconnectConnection(selectedConnection ?? null);
setSelectConnectionOpen(false);
setConnectionDialogOpen(true);
};
if (isLoadingConnections || isConnectionsError || !pieceWithCorrectVersion) {
return (
<SearchableSelect
options={[]}
disabled={true}
loading={isLoadingConnections}
placeholder={
isConnectionsError
? t("Couldn't load your connections.")
: t('Select a connection')
}
value={value}
onChange={() => {}}
showDeselect={false}
showRefresh={isConnectionsError}
onRefresh={() => refetch()}
/>
);
}
return (
<>
<CreateOrEditConnectionDialog
reconnectConnection={reconnectConnection}
isGlobalConnection={isReconnectingGlobalConnection}
piece={pieceWithCorrectVersion}
key={`CreateOrEditConnectionDialog-open-${connectionDialogOpen}`}
open={connectionDialogOpen}
setOpen={async (open, connection) => {
setConnectionDialogOpen(open);
const createdValue = connectionTemplate.wrapExternalId(
connection?.externalId,
);
if (!isNil(createdValue)) {
await refetch();
onChange(createdValue);
}
}}
></CreateOrEditConnectionDialog>
<Select
key={value ?? ''}
open={selectConnectionOpen}
onOpenChange={setSelectConnectionOpen}
value={value ?? ''}
onValueChange={onChange}
disabled={disabled}
>
<div className="relative">
{value && !disabled && canShowConnectionStatus && statusDisplay && (
<div className="z-50 absolute right-8 top-1.5 flex items-center gap-1.5 pointer-events-none">
<span className="flex items-center gap-1 text-xs text-gray-11 select-none pointer-events-none">
<statusDisplay.Icon
className={cn(
'size-3.5 shrink-0',
statusDisplay.iconClassName,
)}
/>
{statusDisplay.label}
</span>
<Tooltip>
<TooltipTrigger asChild>
<span className="inline-flex pointer-events-auto">
<Button
variant="ghost"
size="icon-xs"
loading={isLoadingPiece}
onClick={(e) => {
e.stopPropagation();
openReconnectDialog();
}}
disabled={!hasPermissionToCreateConnection}
>
<Cable className="size-3.5" />
</Button>
</span>
</TooltipTrigger>
<TooltipContent>
{!hasPermissionToCreateConnection
? t('Permission needed')
: t('Reconnect')}
</TooltipContent>
</Tooltip>
</div>
)}
<SelectTrigger
className="flex gap-2 items-center"
aria-label={t('Connection')}
>
<SelectValue
className="truncate grow shrink"
placeholder={t('Select a connection')}
data-testid="select-connection-value"
>
<SelectedConnectionLabel
value={value}
connections={connections?.data ?? []}
/>
</SelectValue>
<div className="grow"></div>
{value && !disabled && canShowConnectionStatus && statusDisplay && (
<span
aria-hidden
className="z-50 opacity-0 pointer-events-none flex items-center gap-1.5"
>
<span className="flex items-center gap-1 text-xs">
<statusDisplay.Icon className="size-3.5 shrink-0" />
{statusDisplay.label}
</span>
<span className="size-6 shrink-0" />
</span>
)}
</SelectTrigger>
</div>
<SelectContent>
<PermissionNeededTooltip
hasPermission={hasPermissionToCreateConnection}
>
<SelectAction
onClick={() => {
setSelectConnectionOpen(false);
setReconnectConnection(null);
setConnectionDialogOpen(true);
}}
disabled={!hasPermissionToCreateConnection}
>
<span
className={cn('flex items-center gap-1 text-accent-11 w-full', {
'text-gray-11 cursor-not-allowed':
!hasPermissionToCreateConnection,
})}
>
<Plus size={16} />
{t('Create Connection')}
</span>
</SelectAction>
</PermissionNeededTooltip>
{connections &&
connections.data &&
connections.data?.map((connection) => {
const connectionValue = connectionTemplate.wrapExternalId(
connection.externalId,
);
if (isNil(connectionValue)) {
return null;
}
const accountIdentifier =
appConnectionUtils.getConnectionAccountIdentifier(connection);
const rowStatus =
connection.status !== AppConnectionStatus.ACTIVE
? getConnectionStatusDisplay(connection.status)
: null;
return (
<SelectItem
value={connectionValue}
key={connection.externalId}
className="*:[span]:last:w-full"
>
<div className="flex items-center gap-2 w-full min-w-0">
{connection.usingSecretManager && (
<Key size={16} className="shrink-0" />
)}
{connection.scope === AppConnectionScope.PLATFORM && (
<Globe size={16} className="shrink-0" />
)}
<span className="truncate min-w-0">
{connection.displayName}
</span>
{accountIdentifier && (
<span className="ml-auto shrink-0 truncate max-w-[50%] text-xs text-gray-11">
{accountIdentifier}
</span>
)}
{rowStatus && (
<span
className={cn(
'flex items-center gap-1 text-xs text-gray-11 shrink-0',
{ 'ml-auto': !accountIdentifier },
)}
>
<rowStatus.Icon
className={cn(
'size-3.5 shrink-0',
rowStatus.iconClassName,
)}
/>
{rowStatus.label}
</span>
)}
</div>
</SelectItem>
);
})}
</SelectContent>
</Select>
</>
);
}
function SelectedConnectionLabel({
value,
connections,
}: {
value: string | undefined;
connections: AppConnectionWithoutSensitiveData[];
}) {
if (isNil(value) || value === '') {
return null;
}
const connection = connections.find(
(connection) =>
connection.externalId === connectionTemplate.unwrapExternalId(value),
);
if (isNil(connection)) {
return (
<div className="truncate grow shrink flex items-center gap-2 text-gray-11">
<Unplug size={16} className="shrink-0 text-danger-11" />
{t('Connection not found')}
</div>
);
}
return (
<div className="truncate grow shrink flex items-center gap-2">
{connection.scope === AppConnectionScope.PLATFORM && (
<Globe size={16} className="shrink-0" />
)}
{connection.displayName}
</div>
);
}
function getConnectionStatusDisplay(status: AppConnectionStatus): {
Icon: LucideIcon;
iconClassName: string;
label: string;
} {
switch (status) {
case AppConnectionStatus.ACTIVE:
return {
Icon: Check,
iconClassName: 'text-success-11',
label: t('Connected'),
};
case AppConnectionStatus.ERROR:
return {
Icon: X,
iconClassName: 'text-danger-11',
label: t('Error'),
};
case AppConnectionStatus.MISSING:
return {
Icon: Unplug,
iconClassName: 'text-gray-11',
label: t('Missing'),
};
}
}
type ConnectionSelectProps = {
piece: PieceMetadataModelSummary | PieceMetadataModel;
value: string | undefined;
onChange: (value: string) => void;
disabled?: boolean;
};