SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.
JavaScript a2aagentic-aiai-agentsdevtoolsmcp-clientn8n-alternativeno-codeopen-sourceorchestrationsmythosvisual-builder
Refactor CreateNamespaceModal and UploadDatasourceDialog components for improved readability and functionality. Cleaned up code formatting, added data attributes for testing, and ensured consistent error handling. Enhanced user experience by refining input handling and validation logic.
Salman-Ahamed8f61f733721f
diff --git a/packages/app/src/react/features/data-pool/components/CreateNamespaceModal.tsx b/packages/app/src/react/features/data-pool/components/CreateNamespaceModal.tsxindex cde37fb8..28ce8522 100644--- a/packages/app/src/react/features/data-pool/components/CreateNamespaceModal.tsx+++ b/packages/app/src/react/features/data-pool/components/CreateNamespaceModal.tsx@@ -25,9 +25,7 @@ import { errorToast, successToast } from '@src/shared/components/toast';import { Info, PlusCircle, Settings } from 'lucide-react';import { ChangeEvent, FC, useEffect, useState } from 'react';import { useNavigate } from 'react-router-dom';-import {- CreateCredentialsModal-} from '../../credentials/components/create-credentials.modal';+import { CreateCredentialsModal } from '../../credentials/components/create-credentials.modal';import credentialsSchema from '../../credentials/credentials-schema.json';import { dataPoolClient } from '../client/datapool.client';import { useDataPoolContext } from '../contexts/data-pool.context';@@ -50,7 +48,8 @@ export const CreateNamespaceModal: FC<CreateNamespaceModalProps> = ({onClose,onSuccess,}) => {- const { credentials, credentialsLoading, getCredentialById, refetchCredentials } = useDataPoolContext();+ const { credentials, credentialsLoading, getCredentialById, refetchCredentials } =+ useDataPoolContext();const navigate = useNavigate();const [name, setName] = useState('');const [selectedCredentialId, setSelectedCredentialId] = useState('');@@ -141,7 +140,7 @@ export const CreateNamespaceModal: FC<CreateNamespaceModalProps> = ({successToast('Data space created successfully');onSuccess();onClose();- } catch (err: any) {+ } catch (err) {const errorMessage = err?.message || 'Failed to create data space. Please try again.';setError(errorMessage);errorToast(errorMessage);@@ -159,14 +158,14 @@ export const CreateNamespaceModal: FC<CreateNamespaceModalProps> = ({setIsCreateCredModalOpen(true);return;}-+// If "manage_connections" is selected, navigate to vault pageif (value === '__manage_connections__') {onClose();navigate('/vault');return;}-+setSelectedCredentialId(value);handleDimentionDynamicChange('connection', value);setError(null);@@ -190,10 +189,7 @@ export const CreateNamespaceModal: FC<CreateNamespaceModalProps> = ({setIsDimensionsReadOnly(true);}}---- };+ };/*** Handle successful credential creation@@ -207,10 +203,10 @@ export const CreateNamespaceModal: FC<CreateNamespaceModalProps> = ({}) => {// Close the create credentials modalsetIsCreateCredModalOpen(false);-+// Refetch credentials to get the new onerefetchCredentials();-+// Auto-select the newly created credentialif (data.id) {setSelectedCredentialId(data.id);@@ -226,227 +222,230 @@ export const CreateNamespaceModal: FC<CreateNamespaceModalProps> = ({setError(null);};- const isFormValid = name.trim() !== '' && selectedCredentialId !== '' && selectedModelId !== '' && dimensions !== '';+ const isFormValid =+ name.trim() !== '' &&+ selectedCredentialId !== '' &&+ selectedModelId !== '' &&+ dimensions !== '';return (<>- <Dialog- open={isOpen} onOpenChange={onClose}>- <DialogContent className={'sm:max-w-[500px] max-h-[90vh] overflow-y-auto'}>- <DialogHeader>- <DialogTitle>Create Data Space</DialogTitle>- <p className="text-sm text-gray-600 mt-1">- Set up a Data Space to unlock your agents' ability to search, automate, and learn- from your data — using RAG and other tools- </p>- </DialogHeader>-- <form- onSubmit={(e) => {- e.preventDefault();- handleCreate();- }}- >- <div className="grid gap-4 py-4">- {/* Provider Selection */}- <div className="space-y-2">- <label className="text-gray-700 mb-1 text-sm font-normal flex items-center">- Vector Database Provider <span className="text-red-500 ml-1">*</span>- </label>- <Select- value={selectedCredentialId}- onValueChange={handleCredentialChange}- disabled={credentialsLoading || isCreating}- >- <SelectTrigger className="w-full" disabled={credentialsLoading || isCreating}>- <SelectValue placeholder="Select a provider">- {selectedCredentialId && (() => {- const selectedCred = getCredentialById(selectedCredentialId);- const logo = selectedCred ? getProviderLogo(selectedCred.provider) : undefined;- return (- <div className="flex items-center gap-2">- {logo && (- <img- src={logo}- alt={selectedCred?.name || 'Provider'}- className="w-5 h-5 object-contain"- />- )}- <span>{selectedCred?.name}</span>- {selectedCred?.isManaged && (- <span className="text-xs text-gray-500">Managed</span>- )}- </div>- );- })()}- </SelectValue>- </SelectTrigger>- <SelectContent>- {/* Create New Connection Option */}- <SelectItem value="__create_new__">- <div className="flex items-center gap-2 text-blue-600 font-medium">- <PlusCircle className="w-4 h-4" />- <span>Create New Connection</span>- </div>- </SelectItem>-- {/* Manage Connections Option */}- <SelectItem value="__manage_connections__">- <div className="flex items-center gap-2 text-gray-600 font-medium">- <Settings className="w-4 h-4" />- <span>Manage Connections</span>- </div>- </SelectItem>-- {/* Separator */}- {credentials.length > 0 && (- <div className="border-t border-gray-200 my-1" />- )}-- {/* Existing Credentials */}- {credentials.length === 0 ? (- <div className="px-2 py-1.5 text-sm text-muted-foreground">- No connections found- </div>- ) : (- credentials.map((cred) => {- const logo = getProviderLogo(cred.provider);- return (- <SelectItem key={cred.id} value={cred.id}>- <div className="flex items-center gap-2">- {logo && (- <img- src={logo}- alt={cred.name}- className="w-5 h-5 object-contain"- />- )}- <span>{cred.name}</span>- {cred.isManaged && (- <span className="text-xs text-gray-500">Managed</span>- )}- </div>- </SelectItem>- );- })- )}- </SelectContent>- </Select>- </div>-- {/* Name Input */}- <div className="space-y-2">- <Input- label="Name"- required- fullWidth- type="text"- placeholder="Name your data space"- value={name}- onChange={handleNameChange}- disabled={isCreating}- error={!!error}- errorMessage={error || undefined}- />- </div>-- {/* Embedding Model Selection and Dimensions - Side by Side */}- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">- {/* Embedding Model Selection */}+ <Dialog open={isOpen} onOpenChange={onClose}>+ <DialogContent className={'sm:max-w-[500px] max-h-[90vh] overflow-y-auto'}>+ <DialogHeader>+ <DialogTitle>Create Data Space</DialogTitle>+ <p className="text-sm text-gray-600 mt-1">+ Set up a Data Space to unlock your agents' ability to search, automate, and learn+ from your data — using RAG and other tools+ </p>+ </DialogHeader>++ <form+ onSubmit={(e) => {+ e.preventDefault();+ handleCreate();+ }}+ >+ <div className="grid gap-4 py-4">+ {/* Provider Selection */}<div className="space-y-2"><label className="text-gray-700 mb-1 text-sm font-normal flex items-center">- Embedding Model <span className="text-red-500 ml-1">*</span>+ Vector Database Provider <span className="text-red-500 ml-1">*</span></label><Select- value={selectedModelId}- onValueChange={(value) => {-- setSelectedModelId(value);- handleDimentionDynamicChange('embedding_model', value);- }}- disabled={isLoadingModels || isCreating}+ data-qa="provider-select"+ value={selectedCredentialId}+ onValueChange={handleCredentialChange}+ disabled={credentialsLoading || isCreating}>- <SelectTrigger className="w-full" disabled={isLoadingModels || isCreating}>- <SelectValue placeholder="Select an embedding model" />+ <SelectTrigger className="w-full" disabled={credentialsLoading || isCreating}>+ <SelectValue placeholder="Select a provider">+ {selectedCredentialId &&+ (() => {+ const selectedCred = getCredentialById(selectedCredentialId);+ const logo = selectedCred+ ? getProviderLogo(selectedCred.provider)+ : undefined;+ return (+ <div className="flex items-center gap-2">+ {logo && (+ <img+ src={logo}+ alt={selectedCred?.name || 'Provider'}+ className="w-5 h-5 object-contain"+ />+ )}+ <span>{selectedCred?.name}</span>+ {selectedCred?.isManaged && (+ <span className="text-xs text-gray-500">Managed</span>+ )}+ </div>+ );+ })()}+ </SelectValue></SelectTrigger><SelectContent>- {isLoadingModels ? (- <div className="px-2 py-1.5 text-sm text-muted-foreground">- Loading models...+ {/* Create New Connection Option */}+ <SelectItem value="__create_new__">+ <div className="flex items-center gap-2 text-blue-600 font-medium">+ <PlusCircle className="w-4 h-4" />+ <span>Create New Connection</span>+ </div>+ </SelectItem>++ {/* Manage Connections Option */}+ <SelectItem value="__manage_connections__">+ <div className="flex items-center gap-2 text-gray-600 font-medium">+ <Settings className="w-4 h-4" />+ <span>Manage Connections</span></div>- ) : embeddingModels.length === 0 ? (+ </SelectItem>++ {/* Separator */}+ {credentials.length > 0 && <div className="border-t border-gray-200 my-1" />}++ {/* Existing Credentials */}+ {credentials.length === 0 ? (<div className="px-2 py-1.5 text-sm text-muted-foreground">- No models available+ No connections found</div>) : (- embeddingModels.map((model) => (- <SelectItem key={model.model} value={model.model}>- {model.label}- </SelectItem>- ))+ credentials.map((cred) => {+ const logo = getProviderLogo(cred.provider);+ return (+ <SelectItem key={cred.id} value={cred.id}>+ <div className="flex items-center gap-2">+ {logo && (+ <img+ src={logo}+ alt={cred.name}+ className="w-5 h-5 object-contain"+ />+ )}+ <span>{cred.name}</span>+ {cred.isManaged && (+ <span className="text-xs text-gray-500">Managed</span>+ )}+ </div>+ </SelectItem>+ );+ }))}</SelectContent></Select></div>- {/* Dimensions Input */}+ {/* Name Input */}<div className="space-y-2">- <label className="text-gray-700 text-sm font-normal flex items-center">- Vector Dimensions- <Tooltip>- <TooltipTrigger asChild>- <Info className="w-4 h-4 cursor-help ml-1" />- </TooltipTrigger>- <TooltipContent side="right" className="w-[200px] text-center">- <p>- The dimension should match the one configured in your vector database provider.- </p>- </TooltipContent>- </Tooltip>- </label>- <input- type="number"- placeholder="e.g., 1536"- value={dimensions}- onChange={(e: ChangeEvent<HTMLInputElement>) => setDimensions(e.target.value)}+ <Input+ label="Name"+ required+ fullWidth+ type="text"+ placeholder="Name your data space"+ value={name}+ onChange={handleNameChange}disabled={isCreating}- readOnly={isDimensionsReadOnly}- className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-100 disabled:cursor-not-allowed text-sm"+ error={!!error}+ errorMessage={error || undefined}/></div>++ {/* Embedding Model Selection and Dimensions - Side by Side */}+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">+ {/* Embedding Model Selection */}+ <div className="space-y-2">+ <label className="text-gray-700 mb-1 text-sm font-normal flex items-center">+ Embedding Model <span className="text-red-500 ml-1">*</span>+ </label>+ <Select+ value={selectedModelId}+ data-qa="embedding-model-select"+ disabled={isLoadingModels || isCreating}+ onValueChange={(value) => {+ setSelectedModelId(value);+ handleDimentionDynamicChange('embedding_model', value);+ }}+ >+ <SelectTrigger className="w-full" disabled={isLoadingModels || isCreating}>+ <SelectValue placeholder="Select an embedding model" />+ </SelectTrigger>+ <SelectContent>+ {isLoadingModels ? (+ <div className="px-2 py-1.5 text-sm text-muted-foreground">+ Loading models...+ </div>+ ) : embeddingModels.length === 0 ? (+ <div className="px-2 py-1.5 text-sm text-muted-foreground">+ No models available+ </div>+ ) : (+ embeddingModels.map((model) => (+ <SelectItem key={model.model} value={model.model}>+ {model.label}+ </SelectItem>+ ))+ )}+ </SelectContent>+ </Select>+ </div>++ {/* Dimensions Input */}+ <div className="space-y-2">+ <label className="text-gray-700 text-sm font-normal flex items-center">+ Vector Dimensions+ <Tooltip>+ <TooltipTrigger asChild>+ <Info className="w-4 h-4 cursor-help ml-1" />+ </TooltipTrigger>+ <TooltipContent side="right" className="w-[200px] text-center">+ <p>+ The dimension should match the one configured in your vector database+ provider.+ </p>+ </TooltipContent>+ </Tooltip>+ </label>+ <input+ type="number"+ placeholder="e.g., 1536"+ value={dimensions}+ onChange={(e: ChangeEvent<HTMLInputElement>) => setDimensions(e.target.value)}+ disabled={isCreating}+ readOnly={isDimensionsReadOnly}+ className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-100 disabled:cursor-not-allowed text-sm"+ />+ </div>+ </div></div>- </div>-- <DialogFooter>- <CustomButton- variant="secondary"- type="button"- label="Cancel"- handleClick={onClose}- disabled={isCreating}- />- <CustomButton- variant="primary"- type="submit"- label={isCreating ? 'Creating...' : 'Create'}- disabled={!isFormValid || isCreating || credentialsLoading || isLoadingModels}- loading={isCreating}- />- </DialogFooter>- </form>- </DialogContent>--- </Dialog>-- {/* Create Credentials Modal */}- <CreateCredentialsModal- isOpen={isCreateCredModalOpen}- onClose={() => setIsCreateCredModalOpen(false)}- onSuccess={handleCredentialCreated}- group="vector_db_creds"- />- </>++ <DialogFooter>+ <CustomButton+ variant="secondary"+ type="button"+ label="Cancel"+ handleClick={onClose}+ disabled={isCreating}+ />+ <CustomButton+ variant="primary"+ type="submit"+ label={isCreating ? 'Creating...' : 'Create'}+ disabled={!isFormValid || isCreating || credentialsLoading || isLoadingModels}+ loading={isCreating}+ />+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>++ {/* Create Credentials Modal */}+ <CreateCredentialsModal+ isOpen={isCreateCredModalOpen}+ onClose={() => setIsCreateCredModalOpen(false)}+ onSuccess={handleCredentialCreated}+ group="vector_db_creds"+ />+ </>);};-diff --git a/packages/app/src/react/features/data-pool/components/UploadDatasourceDialog.tsx b/packages/app/src/react/features/data-pool/components/UploadDatasourceDialog.tsxindex 41e5f0b1..d27fd5e0 100644--- a/packages/app/src/react/features/data-pool/components/UploadDatasourceDialog.tsx+++ b/packages/app/src/react/features/data-pool/components/UploadDatasourceDialog.tsx@@ -79,7 +79,7 @@ export const UploadDatasourceDialog: FC<UploadDatasourceDialogProps> = ({if (droppedFile) {validateAndSetFile(droppedFile);}- }, []);+ }, []); // eslint-disable-line react-hooks/exhaustive-depsconst validateAndSetFile = (selectedFile: File) => {const allowedTypes = [@@ -170,7 +170,8 @@ export const UploadDatasourceDialog: FC<UploadDatasourceDialogProps> = ({datasourceLabel: datasourceLabel.trim(),file: fileToUpload,chunkSize: !isNaN(parsedChunkSize) && parsedChunkSize > 0 ? parsedChunkSize : undefined,- chunkOverlap: !isNaN(parsedChunkOverlap) && parsedChunkOverlap >= 0 ? parsedChunkOverlap : undefined,+ chunkOverlap:+ !isNaN(parsedChunkOverlap) && parsedChunkOverlap >= 0 ? parsedChunkOverlap : undefined,metadata: parsedMetadata,});successToast('Datasource uploaded successfully');@@ -190,12 +191,11 @@ export const UploadDatasourceDialog: FC<UploadDatasourceDialogProps> = ({const k = 1024;const sizes = ['Bytes', 'KB', 'MB', 'GB'];const i = Math.floor(Math.log(bytes) / Math.log(k));- return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];+ return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i];};const isValid =- datasourceLabel.trim() !== '' &&- (mode === 'file' ? file !== null : rawText.trim() !== '');+ datasourceLabel.trim() !== '' && (mode === 'file' ? file !== null : rawText.trim() !== '');return (<Dialog open={isOpen} onOpenChange={onClose}>@@ -272,17 +272,16 @@ export const UploadDatasourceDialog: FC<UploadDatasourceDialogProps> = ({}`}><Upload className="w-12 h-12 mx-auto text-gray-400 mb-3" />- <p className="text-gray-700 font-medium mb-1">- Drag and drop your file here- </p>+ <p className="text-gray-700 font-medium mb-1">Drag and drop your file here</p><p className="text-sm text-gray-500 mb-3">or</p><label className="inline-block"><inputtype="file"className="hidden"+ disabled={isUploading}accept=".txt,.pdf,.docx"onChange={handleFileSelect}- disabled={isUploading}+ data-qa="file-dropzone-input"/><span className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 cursor-pointer inline-block">Browse Files@@ -333,9 +332,7 @@ export const UploadDatasourceDialog: FC<UploadDatasourceDialogProps> = ({// make font size smaller: font-size-smclassName="w-full h-64 px-3 py-2 border text-sm border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-100 disabled:cursor-not-allowed resize-none font-light"/>- <p className="text-xs text-gray-500">- This text will be saved as a .txt file- </p>+ <p className="text-xs text-gray-500">This text will be saved as a .txt file</p></div>)}@@ -367,9 +364,7 @@ export const UploadDatasourceDialog: FC<UploadDatasourceDialogProps> = ({placeholder="1000"className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-100 disabled:cursor-not-allowed text-sm"/>- <p className="text-xs text-gray-500">- Maximum characters per chunk- </p>+ <p className="text-xs text-gray-500">Maximum characters per chunk</p></div>{/* Chunk Overlap */}@@ -383,14 +378,14 @@ export const UploadDatasourceDialog: FC<UploadDatasourceDialogProps> = ({min="0"max="1000"value={chunkOverlap}- onChange={(e: ChangeEvent<HTMLInputElement>) => setChunkOverlap(e.target.value)}+ onChange={(e: ChangeEvent<HTMLInputElement>) =>+ setChunkOverlap(e.target.value)+ }disabled={isUploading}placeholder="200"className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-100 disabled:cursor-not-allowed text-sm"/>- <p className="text-xs text-gray-500">- Overlapping characters between chunks- </p>+ <p className="text-xs text-gray-500">Overlapping characters between chunks</p></div></div><div className="p-3 bg-blue-50 border border-blue-200 rounded-lg">@@ -410,13 +405,17 @@ export const UploadDatasourceDialog: FC<UploadDatasourceDialogProps> = ({<JsonEditorvalue={metadata}onChange={setMetadata}- placeholder={'{\n "author": "John Doe",\n "category": "research",\n "tags": ["ai", "ml"]\n}'}+ placeholder={+ '{\n "author": "John Doe",\n "category": "research",\n "tags": ["ai", "ml"]\n}'+ }disabled={isUploading}height="150px"/><div className="p-3 bg-amber-50 border border-amber-200 rounded-lg"><p className="text-xs text-amber-800">- <strong>📝 Note:</strong> Add custom metadata as JSON to enrich your datasource with additional information. This is optional and can be used for filtering and organization.+ <strong>📝 Note:</strong> Add custom metadata as JSON to enrich your datasource+ with additional information. This is optional and can be used for filtering and+ organization.</p></div></div>@@ -446,4 +445,3 @@ export const UploadDatasourceDialog: FC<UploadDatasourceDialogProps> = ({</Dialog>);};-diff --git a/packages/app/src/react/shared/components/ui/select.tsx b/packages/app/src/react/shared/components/ui/select.tsxindex 184fc06e..18caa851 100644--- a/packages/app/src/react/shared/components/ui/select.tsx+++ b/packages/app/src/react/shared/components/ui/select.tsx@@ -4,7 +4,70 @@ import * as React from 'react';import { cn } from '@react/shared/utils/general';-const Select = SelectPrimitive.Root;+/**+ * Props for the Select component with data-* attribute support on hidden native select+ */+interface SelectProps extends React.ComponentPropsWithoutRef<typeof SelectPrimitive.Root> {+ /** Data attribute for QA/testing - applied to hidden native select */+ 'data-qa'?: string;+ /** Data attribute for testing libraries - applied to hidden native select */+ 'data-testid'?: string;+ /** Allow any other data-* attributes */+ [key: `data-${string}`]: string | undefined;+}++/**+ * Select component wrapper that supports data-* attributes on the hidden native select+ * Radix UI's Select.Root doesn't render DOM, so we wrap it to apply attributes to the hidden select+ *+ * @example+ * <Select data-qa="my-select" data-testid="test-select" value={value} onValueChange={onChange}>+ * <SelectTrigger>...</SelectTrigger>+ * <SelectContent>...</SelectContent>+ * </Select>+ */+const Select = React.forwardRef<HTMLDivElement, SelectProps>((props, forwardedRef) => {+ const internalRef = React.useRef<HTMLDivElement>(null);+ const ref = (forwardedRef as React.RefObject<HTMLDivElement>) ?? internalRef;++ // Memoize separated props to avoid unnecessary re-renders+ const { dataAttributes, selectProps } = React.useMemo(() => {+ const data: Record<string, string> = {};+ const select: Record<string, unknown> = {};++ Object.entries(props).forEach(([key, value]) => {+ if (key.startsWith('data-') && value !== undefined && value !== null) {+ data[key] = String(value);+ } else if (key !== 'children') {+ select[key] = value;+ }+ });++ return { dataAttributes: data, selectProps: select };+ }, [props]);++ /**+ * Apply data-* attributes to the hidden native select element+ * Radix creates this internally for accessibility/form submission+ */+ React.useEffect(() => {+ if (Object.keys(dataAttributes).length > 0 && ref && 'current' in ref && ref.current) {+ const hiddenSelect = ref.current.querySelector('select');+ if (hiddenSelect) {+ Object.entries(dataAttributes).forEach(([key, value]) => {+ hiddenSelect.setAttribute(key, value);+ });+ }+ }+ }, [dataAttributes, ref]);++ return (+ <div ref={ref}>+ <SelectPrimitive.Root {...selectProps}>{props.children}</SelectPrimitive.Root>+ </div>+ );+});+Select.displayName = 'Select';const SelectValue = SelectPrimitive.Value;