Skip to content

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.

migrate data pool from ce to enterprise

Ahmed Essam28b6ee5a9fc1
diff --git a/packages/app/src/backend/routes/api/page/index.ts b/packages/app/src/backend/routes/api/page/index.ts
index d8b1215e..374fd0a8 100644
--- a/packages/app/src/backend/routes/api/page/index.ts
+++ b/packages/app/src/backend/routes/api/page/index.ts
@@ -14,11 +14,10 @@ import teams from './teams';
import templates from './templates';
import user from './user';
import vault from './vault';
-import vectors from './vectors';
const routers = {
domains,
- vectors,
+ // vectors,
agents,
templates,
teams,
diff --git a/packages/app/src/backend/routes/api/page/vectors.ts b/packages/app/src/backend/routes/api/page/vectors.ts
deleted file mode 100644
index 2fca4f62..00000000
--- a/packages/app/src/backend/routes/api/page/vectors.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-import express from 'express';
-import {
- authHeaders,
- forwardToSmythAPIMiddleware,
- smythAPI,
- smythAPIReq,
-} from '../../../utils';
-import {
- checkObjectOwnership,
- extractObjectKeyFromUrl,
- isStorageFile,
-} from '../../../utils/storage.utils';
-import { includeTeamDetails } from '../../../middlewares/auth.mw';
-
-const router = express.Router();
-
-router.get('/vectorsNamespaceList', async (req, res) => {
- try {
- const { page, limit } = req.query;
- const result = await smythAPIReq.get(
- `/vectors/namespaces?page=${page}&limit=${limit}`,
- await authHeaders(req),
- );
- return res.json(result.data);
- } catch (error) {
- console.log('error', error);
- return res.status(500).json({ error });
- }
-});
-
-router.post('/addDatasource', includeTeamDetails, async (req, res) => {
- const url = req.body.url;
- try {
- if (isStorageFile(url)) {
- const key = extractObjectKeyFromUrl(url);
-
- await checkObjectOwnership(key, {
- // @ts-ignore
- teamId: req._team.id,
- // @ts-ignore
- userId: req._team.userId,
- });
- }
- } catch (error) {
- return res.status(403).json({ error: error.message });
- }
- const body = req.body;
- try {
- const result = await smythAPI.post(`/vectors/datasources`, body, await authHeaders(req));
- return res.json({ res: result.data });
- } catch (error) {
- return res.status(error?.response?.status || 500).json({ error: error?.response?.data });
- }
-});
-
-router.get('/datasourceList', async (req, res) => {
- try {
- const { namespaceName, page, limit } = req.query;
- const result = await smythAPIReq.get('/vectors/datasources', {
- params: { namespaceName, page, limit },
- ...(await authHeaders(req)),
- });
- return res.json({ res: result.data });
- } catch (error) {
- console.log('error', error);
- return res.status(500).json({ error });
- }
-});
-
-router.get('/sitemapStatus', async (req, res) => {
- try {
- const { id } = req.query;
- const result = await smythAPIReq.get(
- `/vectors/datasources/${id}/sitemap_status`,
- await authHeaders(req),
- );
- return res.json({ res: result.data });
- } catch (error) {
- console.log('error', error);
- return res.status(500).json({ error });
- }
-});
-
-router.get('/datasourceStatus', async (req, res) => {
- try {
- const { id } = req.query;
- const result = await smythAPIReq.get(
- `/vectors/datasources/${id}/status`,
- await authHeaders(req),
- );
- return res.json({ res: result.data });
- } catch (error) {
- console.log('error', error);
- return res.status(500).json({ error });
- }
-});
-
-router.delete('/deleteDatasource', async (req, res) => {
- try {
- const { id } = req.query;
- const result = await smythAPIReq.delete(`/vectors/datasources/${id}`, await authHeaders(req));
- return res.json({ res: result.data });
- } catch (error) {
- console.log('error', error.response);
- return res.status(error?.response?.status || 500).json({ error: error?.response?.data });
- }
-});
-
-const smythProxy = forwardToSmythAPIMiddleware({ endpointBuilder: (req) => `/vectors${req.url}` });
-
-// forward all other requests to smyth api
-router.get('/*', smythProxy);
-router.post('/*', smythProxy);
-router.put('/*', smythProxy);
-router.delete('/*', smythProxy);
-
-export default router;
diff --git a/packages/app/src/react/app/routeMap.tsx b/packages/app/src/react/app/routeMap.tsx
index 99e6829c..f1198429 100644
--- a/packages/app/src/react/app/routeMap.tsx
+++ b/packages/app/src/react/app/routeMap.tsx
@@ -8,8 +8,6 @@ import AccountPage from '../features/account/pages/AccountPage';
import AgentSettingsBulkCallPage from '../features/agent-settings/pages/AgentSettingsBulkCallPage';
import AgentSettingsPage from '../features/agent-settings/pages/AgentSettingsPage';
import AIChatPage from '../features/ai-chat/pages/ai-chat';
-import DataPage from '../features/data-space/pages/DataPage';
-import DatasourceLibrary from '../features/data-space/pages/DatasourceLibrary';
import DomainsPage from '../features/domains-space/pages/DomainsPage';
import PartnersPage from '../features/partners/pages/PartnersPage';
import FeaturePageUpsell from '../features/subscriptions/components/paywalls/feature-page-upsell';
@@ -27,8 +25,6 @@ import SinglePriceSubscriptionPage from '../features/subscriptions/pages/SingleP
import TemplatesPage from '../features/templates/pages/TemplatesPage';
export const routeMap: IPageRoute[] = [
- { path: '/data', component: DataPage, title: 'Data Pool' },
- { path: '/data/:dataspace', component: DatasourceLibrary, title: 'Datasources' },
{
path: '/domains',
component: DomainsPage,
diff --git a/packages/app/src/react/features/data-space/client/dataspace.api-client.service.ts b/packages/app/src/react/features/data-space/client/dataspace.api-client.service.ts
deleted file mode 100644
index 9b9af804..00000000
--- a/packages/app/src/react/features/data-space/client/dataspace.api-client.service.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import { apiPayloadTypes, apiResultsTypes } from '@react/shared/types';
-
-export const DEFAULT_PAGINATION_LIMIT = 9;
-
-export const getDatasources = async (namespaceName: string, page: number) => {
- const res = await fetch(
- `/api/page/vectors/datasourceList?namespaceName=${namespaceName}&page=${page}&limit=${DEFAULT_PAGINATION_LIMIT}`,
- );
- const json = await res.json();
- return json?.res;
-};
-
-export const addDatasource = async ({ body }: { body: any }) => {
- const res = await fetch(`/api/page/vectors/addDatasource`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(body),
- });
- const json = await res.json();
- return json;
-};
-
-export const deleteDatasource = async ({ id }: { id: string | number }) => {
- const res = await fetch(`/api/page/vectors/deleteDatasource?id=${id}`, {
- method: 'DELETE',
- headers: {
- 'Content-Type': 'application/json',
- },
- });
- const json = await res.json();
- return json;
-};
-
-export const getDSStatus = async (
- id: string | number,
-): Promise<apiResultsTypes.DatasourceStatus> => {
- const res = await fetch(`/api/page/vectors/datasourceStatus?id=${id}`);
- const json = await res.json();
- return json?.res;
-};
-
-export const getDSSitemapStatus = async (
- id: string | number,
-): Promise<apiResultsTypes.DatasourceSitemapStatus> => {
- const res = await fetch(`/api/page/vectors/sitemapStatus?id=${id}`);
- const json = await res.json();
- return json?.res;
-};
-
-export const getVectorsCustomStorage = async () => {
- const res = await fetch('/api/page/vectors/custom_storage');
- const json = await res.json();
- return json as apiResultsTypes.VectorsCustomStorage;
-};
-
-export const saveCustomVectorStorage = async (payload: apiPayloadTypes.SaveCustomVectorStorage) => {
- const res = await fetch('/api/page/vectors/custom_storage', {
- method: 'POST',
- body: JSON.stringify(payload),
- headers: {
- 'Content-Type': 'application/json',
- },
- });
- const json = await res.json();
- return json;
-};
-
-export const deleteCustomVectorStorage = async () => {
- const res = await fetch('/api/page/vectors/custom_storage', {
- method: 'DELETE',
- });
- const json = await res.json();
- return json;
-};
\ No newline at end of file
diff --git a/packages/app/src/react/features/data-space/components/configureCustomStorageTrigger.tsx b/packages/app/src/react/features/data-space/components/configureCustomStorageTrigger.tsx
deleted file mode 100644
index 2bc4a071..00000000
--- a/packages/app/src/react/features/data-space/components/configureCustomStorageTrigger.tsx
+++ /dev/null
@@ -1,67 +0,0 @@
-import { getVectorsCustomStorage } from '@react/features/data-space/client/dataspace.api-client.service';
-import { Button as CustomButton } from '@react/shared/components/ui/newDesign/button';
-import CustomVectorStorageConfigModal from '@src/react/features/data-space/modals/CustomVectorStorageConfigModal';
-import { useQuery } from '@tanstack/react-query';
-import { useState } from 'react';
-import { createPortal } from 'react-dom';
-import { TbDatabaseCog } from 'react-icons/tb';
-
-const ConfigureCustomStorageTrigger = () => {
- const [isConfigureStorageOpen, setIsConfigureStorageOpen] = useState(false);
- const [requestedModalOpen, setRequestModalOpen] = useState(false);
-
- const customConfiguration = useQuery({
- queryKey: ['custom_vector_storage_configuration_get'],
- queryFn: getVectorsCustomStorage,
- refetchOnMount: false,
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
-
- onSuccess: (data) => {
- if (requestedModalOpen) {
- setRequestModalOpen(false);
- setIsConfigureStorageOpen(true);
- }
- },
-
- onError: (error) => {
- if (requestedModalOpen) {
- setRequestModalOpen(false);
- }
- },
- });
-
- return (
- <>
- <CustomButton
- handleClick={() => {
- if (customConfiguration.isLoading) {
- setRequestModalOpen(true);
- }
- setIsConfigureStorageOpen(true);
- }}
- addIcon={true}
- Icon={
- <TbDatabaseCog color="text-v2-blue hover:text-white" className="mr-2" size={'1.2rem'} />
- }
- loading={requestedModalOpen && customConfiguration.isLoading}
- label={'Customize Storage'}
- dataAttributes={{ 'data-test': 'configure-storage-button' }}
- variant="secondary"
- />
-
- {isConfigureStorageOpen &&
- customConfiguration.isSuccess &&
- createPortal(
- <CustomVectorStorageConfigModal
- data={customConfiguration.isLoading ? undefined : customConfiguration.data}
- resetDataAndRefetch={customConfiguration.refetch}
- onClose={() => setIsConfigureStorageOpen(false)}
- />,
- document.body,
- )}
- </>
- );
-};
-
-export default ConfigureCustomStorageTrigger;
diff --git a/packages/app/src/react/features/data-space/components/datasourceFileUpload.tsx b/packages/app/src/react/features/data-space/components/datasourceFileUpload.tsx
deleted file mode 100644
index e2416ad1..00000000
--- a/packages/app/src/react/features/data-space/components/datasourceFileUpload.tsx
+++ /dev/null
@@ -1,135 +0,0 @@
-import FileUpload from '@react/features/data-space/components/fileUpload';
-import { constructS3Url } from '@react/shared/utils/utils';
-import { ChangeEvent, useState } from 'react';
-
-export default function DatasourceFileUpload({
- fileName,
- setFile,
- setUploadedUrl,
- setFileName,
- disableUpload,
- setFileUploadError,
-}) {
- const [isUploaded, setIsUploaded] = useState(null);
- const [uploadLoading, setUploadLoading] = useState(false);
- const [deleteLoading, setDeleteLoading] = useState(false);
-
- const uploadFile = async (fileValue) => {
- const formData = new FormData();
- formData.append('file', fileValue);
- return fetch(`/api/uploads/datasources`, {
- method: 'PUT',
- body: formData,
- })
- .then((response) => {
- if (!response.ok) {
- throw new Error(`Error uploading datasource: ${response.status} ${response.statusText}`);
- }
- setUploadLoading(false);
-
- return response.json();
- })
- .catch((error) => {
- console.error('Error uploading datasource:', error);
- setUploadLoading(false);
- throw error;
- });
- };
-
- const handleFileChange = async (e: ChangeEvent<HTMLInputElement>) => {
- setFileUploadError('');
- const selectedFile = e.target.files[0];
- const { name, type } = selectedFile;
-
- if (!isValidDataSourceFileType(name, type)) {
- setFileUploadError(
- 'Invalid file type. Please upload a .pdf, .doc, .docx, .txt, .xml, .html, or .htm file.',
- );
- e.target.value = '';
- return;
- }
-
- setFile(selectedFile);
- e.target.disabled = true;
- setUploadLoading(true);
-
- try {
- const uploadedFile = await uploadFile(selectedFile);
- const fileURL = constructS3Url(uploadedFile.file.key);
-
- setFileName(name);
- setUploadedUrl(fileURL);
- setIsUploaded(uploadedFile.file);
- } catch (error) {
- console.log(error);
- } finally {
- e.target.disabled = false;
- e.target.value = null;
- setUploadLoading(false);
- }
- };
-
- async function deleteFile(key: string) {
- setDeleteLoading(true);
- return fetch(`/api/uploads/datasources?key=${key}`, {
- method: 'DELETE',
- })
- .then((response) => {
- if (!response.ok) {
- throw new Error(`Error deleting datasource: ${response.status} ${response.statusText}`);
- }
- setDeleteLoading(false);
- return response.json();
- })
- .catch((error) => {
- console.error('Error deleting datasource:', error);
- setDeleteLoading(false);
- throw error;
- });
- }
-
- const handleDelete = async (key) => {
- try {
- await deleteFile(key);
- setFile(null);
- setFileName(null);
- setUploadedUrl(null);
- setIsUploaded(null);
- } catch (error) {
- console.log(error);
- }
- };
-
- const isValidDataSourceFileType = (name: string, type: string) => {
- const allowedExtensions = /(\.pdf|\.doc|\.docx|\.txt|\.xml|\.html|\.htm)$/i;
- const mimeTypes = [
- 'application/pdf',
- 'application/msword',
- 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
- 'text/plain',
- 'application/xml',
- 'text/xml',
- 'text/html',
- ];
-
- return allowedExtensions.test(name) && mimeTypes.includes(type);
- };
-
-
- return (
- <div className="">
- <div className="text-black pb-2">
- Add File <span className="italic text-sm text-gray-500">(.xml, .docx, .pdf) </span>
- </div>
- <FileUpload
- uploadLoading={uploadLoading}
- onChange={handleFileChange}
- fileName={fileName}
- handleDelete={() => handleDelete(isUploaded.key)}
- disableUpload={disableUpload}
- deleteLoading={deleteLoading}
- accept=".pdf,.doc,.docx,.txt,.xml,.html,.htm"
- />
- </div>
- );
-}
diff --git a/packages/app/src/react/features/data-space/components/datasourceTable.tsx b/packages/app/src/react/features/data-space/components/datasourceTable.tsx
deleted file mode 100644
index 64d124ad..00000000
--- a/packages/app/src/react/features/data-space/components/datasourceTable.tsx
+++ /dev/null
@@ -1,144 +0,0 @@
-import { getDatasources } from '@react/features/data-space/client/dataspace.api-client.service';
-import { RefreshIcon } from '@react/shared/components/svgs';
-import TableRowSkeleton from '@react/shared/components/ui/table/table.row.skeleton';
-import { Datasource } from '@react/shared/types/api-results.types';
-import DatasourceTableItem from '@src/react/features/data-space/components/datasourceTableItem';
-import { useQuery } from '@tanstack/react-query';
-import { useState } from 'react';
-
-interface Props {
- namespaceName: string;
- searchQuery: string;
-}
-
-export default function DatasourceTable({ namespaceName, searchQuery }: Props) {
- const [currentPage, setCurrentPage] = useState(1);
- const [dsList, setDsList] = useState<Datasource[]>([]);
- const [totalDatasources, setTotalDatasources] = useState(0);
-
- const dsListQuery = useQuery({
- //@ts-ignore
- queryKey: [`datasources-${namespaceName}`, currentPage],
- queryFn: () => getDatasources(namespaceName, currentPage),
- refetchOnMount: true,
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- onSuccess: (data) => {
- if (currentPage === 1) {
- setDsList(data.dataSources);
- } else {
- setDsList((prev) => [...new Set([...prev, ...data.dataSources])]);
- }
- setTotalDatasources(data.total);
- },
- keepPreviousData: true,
- });
-
- const filteredDatasources = dsList.filter((datasource) =>
- datasource.name.toLowerCase().includes(searchQuery.toLowerCase()),
- );
-
- function removeItem(id: string) {
- const updatedList = filteredDatasources?.filter((item: Datasource) => item.id !== id);
- setDsList(updatedList);
- }
-
- function handleLoadMore() {
- if (!dsListQuery.isFetching) {
- setCurrentPage(currentPage + 1);
- }
- }
-
- /**
- * Renders skeleton loading rows.
- */
- const renderSkeletonLoading = () => {
- return Array.from({ length: 3 }).map((_, i) => (
- <TableRowSkeleton key={i} className="py-5 my-3" />
- ));
- };
-
- return (
- <div className="relative w-full">
- <div className="bg-white rounded-lg w-full">
- <div className="overflow-x-auto">
- <table className="w-full table-auto border border-solid border-gray-100">
- <thead className="bg-gray-50 rounded-lg overflow-hidden">
- <tr>
- <th className="px-4 py-3 text-left text-xs font-semibold text-[#242424] uppercase tracking-wider whitespace-nowrap">
- Data Spaces
- </th>
- <th className="px-4 py-3 text-left text-xs font-semibold text-[#242424] uppercase tracking-wider whitespace-nowrap">
- File Preview
- </th>
- <th className="px-4 py-3 text-left text-xs font-semibold text-[#242424] uppercase tracking-wider whitespace-nowrap">
- Indexing Status
- </th>
- <th className="px-4 py-3 min-w-[80px]"></th>
- </tr>
- </thead>
- <tbody className="bg-white bg-white divide-y divide-gray-200">
- {dsListQuery.isSuccess &&
- filteredDatasources?.length > 0 &&
- filteredDatasources.map((item: Datasource, index) => (
- <DatasourceTableItem
- item={item}
- key={index}
- namespaceName={namespaceName}
- remove={() => removeItem(item.id)}
- />
- ))}
- </tbody>
- </table>
- </div>
-
- {(dsListQuery.isLoading || dsListQuery.isFetching) && renderSkeletonLoading()}
-
- {dsListQuery.isError && !dsListQuery.isLoading && (
- <div className="flex justify-center items-start py-16 pl-12 md:pl-0">
- <div className="max-w-md w-full mx-auto flex flex-col items-center p-4 text-center">
- <h4 className="text-2xl font-medium text-black text-center ml-2 mb-2">
- Error fetching data sources
- </h4>
- </div>
- </div>
- )}
-
- {dsListQuery.isSuccess &&
- filteredDatasources.length === 0 &&
- !dsListQuery.isLoading &&
- !dsListQuery.isFetching && (
- <div className="flex justify-center items-start py-16 pl-12 md:pl-0">
- <div className="max-w-md w-full mx-auto flex flex-col items-center p-4 text-center">
- <h4 className="text-2xl font-medium text-black text-center ml-2 mb-2">
- No data sources found
- </h4>
- {searchQuery && (
- <p className="text-gray-600 mb-8">
- No data sources match your search query: &quot;{searchQuery}&quot;
- </p>
- )}
- </div>
- </div>
- )}
-
- {!searchQuery && filteredDatasources.length < totalDatasources && (
- <div className="px-6 py-4 text-center border border-solid border-gray-200 text-sm">
- <button
- onClick={handleLoadMore}
- type="button"
- className="text-gray-500 hover:underline flex items-center justify-center mx-auto"
- disabled={dsListQuery.isLoading || dsListQuery.isFetching}
- >
- <RefreshIcon
- color="text-gray-500"
- isLoading={dsListQuery.isLoading || dsListQuery.isFetching}
- />
- <span className="mx-2">Load More</span>
- </button>
- </div>
- )}
- </div>
- </div>
- );
-}
diff --git a/packages/app/src/react/features/data-space/components/datasourceTableItem.tsx b/packages/app/src/react/features/data-space/components/datasourceTableItem.tsx
deleted file mode 100644
index 20f87271..00000000
--- a/packages/app/src/react/features/data-space/components/datasourceTableItem.tsx
+++ /dev/null
@@ -1,213 +0,0 @@
-import {
- getDSSitemapStatus,
- getDSStatus,
-} from '@react/features/data-space/client/dataspace.api-client.service';
-import DatasourceInfoModal from '@react/features/data-space/dialogs/datasourceInfo';
-import DeleteDatasourceDialog from '@react/features/data-space/dialogs/deleteDatasource';
-import { Datasource } from '@react/shared/types/api-results.types';
-import { useQuery } from '@tanstack/react-query';
-import { Tooltip } from 'flowbite-react';
-import { random } from 'lodash-es';
-import { Trash2 } from 'lucide-react';
-import { useMemo, useState } from 'react';
-import { createPortal } from 'react-dom';
-import { IoIosInformationCircleOutline } from 'react-icons/io';
-
-type Props = {
- item: Datasource;
- namespaceName: string;
- remove: () => void;
-};
-
-const calculateCompletionPercentage = (stats?: {
- completed?: number;
- pending?: number;
- failed?: number;
- total?: number;
-}) => {
- // const completed = stats?.completed || 0;
- const processed = stats?.total - stats?.pending;
- const total = stats?.total || 0;
- return Math.round((processed / total) * 100);
-};
-
-export default function DatasourceTableItem({ item, namespaceName, remove }: Props) {
- const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
- const [isViewingInfoModal, setIsViewingInfoModal] = useState(false);
-
- const randomRefetchInerval = random(10_000, 20_000, true); // to avoid all sitemaps refetching at the same time (thundering herd problem)
- const statusQuery = useQuery({
- queryKey: [`datasource-status-${item.id}`],
- queryFn: () => getDSStatus(item.id),
- refetchInterval: item.type == 'SITEMAP' ? randomRefetchInerval : false,
- });
-
- const sitemapStatusQuery = useQuery({
- queryKey: [`datasource-sitemap-status-${item.id}`],
- queryFn: () => getDSSitemapStatus(item.id),
- enabled: item.type == 'SITEMAP' ? true : false,
- refetchInterval: item.type == 'SITEMAP' ? randomRefetchInerval : false,
- });
-
- const percentageSpan = (
- <div className="pl-1">
- {isNaN(calculateCompletionPercentage(sitemapStatusQuery?.data?.status))
- ? '0%'
- : calculateCompletionPercentage(sitemapStatusQuery?.data?.status) < 100
- ? calculateCompletionPercentage(sitemapStatusQuery?.data?.status) + '%'
- : ''}
- </div>
- );
-
- const getStatusText = () => {
- const status = statusQuery?.data?.status;
- const sitemapStatus = sitemapStatusQuery?.data?.status;
-
- const percentage = calculateCompletionPercentage(sitemapStatus);
- if (status === 'indexing') {
- return (
- <div className="flex items-center">
- <div className="w-2 h-2 bg-yellow-500 rounded-full mr-2"></div>
- <span className="text-yellow-500">Indexing</span>
- {item.type === 'SITEMAP' && percentageSpan}
- </div>
- );
- } else if (status === 'pending') {
- return (
- <div className="flex items-center">
- <div className="w-2 h-2 bg-yellow-500 rounded-full mr-2"></div>
- <span className="text-yellow-500">Pending</span>
- </div>
- );
- } else if (percentage === 100) {
- return (
- <div className="flex items-center">
- <div className="w-2 h-2 bg-green-500 rounded-full mr-2"></div>
- <span className="text-green-500">Complete</span>
- </div>
- );
- } else if (status === 'done' && percentage < 100) {
- //* NESTED IF
- if (sitemapStatus?.pending > 0) {
- return (
- <div className="flex items-center">
- <div className="w-2 h-2 bg-yellow-500 rounded-full mr-2"></div>
- <span className="text-yellow-500">Indexing</span>
- {percentageSpan}
- </div>
- );
- }
-
- return (
- <div className="flex items-center">
- <div className="w-2 h-2 bg-green-500 rounded-full mr-2"></div>
- <span className="text-green-500">Complete</span>
- </div>
- );
- } else if (status === 'done') {
- return (
- <div className="flex items-center">
- <div className="w-2 h-2 bg-green-500 rounded-full mr-2"></div>
- <span className="text-green-500">Complete</span>
- </div>
- );
- } else if (status === 'failed-retry' || status === 'failed') {
- return (
- <div className="flex items-center">
- <div className="w-2 h-2 bg-red-500 rounded-full mr-2"></div>
- <span className="text-red-500">Indexing Error</span>
- </div>
- );
- } else if (status == 'done-duplicate') {
- return (
- <div className="flex items-center">
- <div className="w-2 h-2 bg-red-500 rounded-full mr-2"></div>
- <span className="text-red-500">Duplicate</span>
- </div>
- );
- } else {
- return (
- <div className="flex items-center">
- <div className="w-2 h-2 bg-gray-500 rounded-full mr-2"></div>
- <span className="text-gray-500">{status || 'Unknown'}</span>
- </div>
- );
- }
- };
-
- const memorizedStatusText = useMemo(() => getStatusText(), [statusQuery, sitemapStatusQuery]);
-
- const statusColumn = statusQuery?.data ? (
- memorizedStatusText
- ) : (
- <div className="flex items-center">
- <div className="w-2 h-2 bg-gray-300 rounded-full mr-2"></div>
- <span className="text-gray-500">Loading...</span>
- </div>
- );
-
- return (
- <>
- <tr className="hover:bg-gray-50 border-b border-solid border-gray-100 h-12">
- <td className="px-6 py-4 whitespace-nowrap">
- <div className="text-sm font-medium text-gray-900">{item?.name}</div>
- </td>
- <td className="px-6 py-4 whitespace-nowrap">
- <div className="text-sm text-gray-500 truncate max-w-[220px]">
- {item?.url?.startsWith('storage:') ? 'File Upload' : item?.url}
- </div>
- </td>
- <td className="px-6 py-4 whitespace-nowrap">
- <div className="flex items-center">
- {statusColumn}
- {item.type === 'SITEMAP' && (
- <IoIosInformationCircleOutline
- cursor="pointer"
- color="#6B7280"
- className="ml-2"
- size={20}
- onClick={() => {
- setIsViewingInfoModal(true);
- }}
- />
- )}
- </div>
- </td>
- <td className="px-6 py-4 text-right">
- <div className="flex items-center justify-end">
- <Tooltip content="Delete Data Source" placement="top" className="min-w-max">
- <Trash2
- className="h-4 w-4 text-[#242424] cursor-pointer"
- onClick={() => setIsDeleteDialogOpen(true)}
- />
- </Tooltip>
- </div>
- </td>
- </tr>
-
- {isViewingInfoModal &&
- item.type === 'SITEMAP' &&
- createPortal(
- <DatasourceInfoModal
- item={item}
- onClose={() => setIsViewingInfoModal(false)}
- status={statusQuery.data?.statusData?.status}
- sitemapStatus={sitemapStatusQuery.data?.status}
- lastCrawledAt={statusQuery.data?.statusData?.lastCrawledAt}
- />,
- document.getElementById('root') as HTMLElement,
- )}
-
- {isDeleteDialogOpen &&
- createPortal(
- <DeleteDatasourceDialog
- item={item}
- onClose={() => setIsDeleteDialogOpen(false)}
- remove={remove}
- namespaceName={namespaceName}
- />,
- document.getElementById('root') as HTMLElement,
- )}
- </>
- );
-}
diff --git a/packages/app/src/react/features/data-space/components/fileUpload.tsx b/packages/app/src/react/features/data-space/components/fileUpload.tsx
deleted file mode 100644
index 6b4c534a..00000000
--- a/packages/app/src/react/features/data-space/components/fileUpload.tsx
+++ /dev/null
@@ -1,110 +0,0 @@
-import { Spinner } from '@react/shared/components/ui/spinner';
-import { FiUploadCloud } from 'react-icons/fi';
-import { TbFile, TbTrash } from 'react-icons/tb';
-
-export default function FileUpload({
- onChange,
- handleDelete,
- fileName,
- uploadLoading,
- disableUpload,
- deleteLoading,
- accept,
-}: {
- onChange: (event: any) => void;
- handleDelete: () => void;
- fileName: string | null;
- uploadLoading: boolean;
- disableUpload: boolean;
- deleteLoading: boolean;
- accept: string;
-}) {
- const handleDragOver = (event) => {
- event.preventDefault();
- event.currentTarget.classList.add('activeDrag');
- };
-
- const handleDragLeave = (event) => {
- event.currentTarget.classList.remove('activeDrag');
- };
-
- const handleDrop = (event) => {
- event.preventDefault();
- event.currentTarget.classList.remove('activeDrag');
-
- const files = event.dataTransfer.files;
- if (files.length) {
- const inputEl = document.getElementById('dropzone-file') as HTMLInputElement;
- inputEl.files = files;
- onChange && onChange({ target: inputEl });
- }
- };
- return (
- <div className="">
- <div className={fileName ? 'hidden' : 'flex items-center justify-center w-full'}>
- <label
- htmlFor="dropzone-file"
- className={` ${
- uploadLoading || disableUpload
- ? 'opacity-50 bg-gray-50 flex flex-col items-center justify-center w-full rounded-lg'
- : 'bg-gray-50 hover:bg-gray-100 flex flex-col items-center justify-center w-full rounded-lg cursor-pointer'
- } `}
- onDragOver={handleDragOver}
- onDragLeave={handleDragLeave}
- onDrop={handleDrop}
- >
- <div className="flex flex-col items-center justify-center pt-5 pb-6 px-4">
- <FiUploadCloud size={28} />
- {uploadLoading ? (
- <Spinner classes="w-5 h-5" />
- ) : (
- <>
- <p className="mb-2 text-sm text-gray-500 dark:text-gray-400">
- Drag and drop your file here or
- <span className="font-semibold"> Click to upload.</span>
- </p>
-
- <p className="text-xs text-gray-500 dark:text-gray-400">
- XML, DOCX or PDF (MAX. 800x400px)
- </p>
- </>
- )}
- </div>
- <input
- id="dropzone-file"
- accept={accept}
- data-multiple="false"
- type="file"
- className="hidden"
- onChange={onChange}
- data-role="file"
- data-mode="drop"
- disabled={uploadLoading || disableUpload}
- />
- </label>
- </div>
- <div className={fileName ? '' : 'hidden'}>
- <div className="flex justify-between bg-gray-50 text-black rounded-lg p-2 gap-2">
- <div className="flex items-center gap-2 overflow-hidden text-ellipsis">
- <TbFile size={22} className="min-w-max" />
- <span className="pl-2 overflow-hidden text-ellipsis max-w-[200px] sm:max-w-full">
- {fileName}{' '}
- </span>
- </div>
-
- <button
- disabled={deleteLoading}
- className=" deleteUpload rounded-full flex items-center"
- type="button"
- >
- {deleteLoading ? (
- <div id="loader" className="circular-loader mr-1"></div>
- ) : (
- <TbTrash size={22} onClick={handleDelete} className="cursor-pointer" />
- )}
- </button>
- </div>
- </div>
- </div>
- );
-}
diff --git a/packages/app/src/react/features/data-space/components/tableRow.tsx b/packages/app/src/react/features/data-space/components/tableRow.tsx
deleted file mode 100644
index 163dd6ab..00000000
--- a/packages/app/src/react/features/data-space/components/tableRow.tsx
+++ /dev/null
@@ -1,303 +0,0 @@
-import {
- calculateCompletionPercentage,
- fetchSitemapStatus,
- fetchStatusData,
-} from '@react/shared/utils/utils';
-import { Tooltip } from 'flowbite-react';
-import { FilePlus, Trash2 } from 'lucide-react';
-import { useEffect, useState } from 'react';
-import { Link } from 'react-router-dom';
-
-const intervals = {};
-
-export default function TableRow({
- index,
- item,
- openNamespaceDeleteDialog,
- handleOpenAddDataDialog,
-}) {
- const [vectorRowData, setVectorRowData] = useState(item);
- const [datasourceLoading, setDatasourceLoading] = useState(false);
- const [statusLoading, setStatusLoading] = useState(false);
-
- // Preload the hovered state image
- useEffect(() => {
- const img = new Image();
- img.src = '/img/icons/PaperPlusBlue.svg';
- }, []);
-
- useEffect(() => {
- if (vectorRowData?.id) {
- (async () => {
- try {
- setDatasourceLoading(true);
- const res = await fetch(
- `/api/page/vectors/datasourceList?namespaceName=${vectorRowData.name}`,
- {
- method: 'GET',
- },
- );
- const data = (await res.json())?.res;
- const dataSource = data.dataSources[0];
- if (dataSource) {
- const { id, name } = dataSource;
-
- setVectorRowData((prev) => ({
- ...prev,
- dataSourceId: id,
- dataSourceName: name,
- }));
- setDatasourceLoading(false);
-
- await fetchStatus(dataSource, vectorRowData.name, setVectorRowData);
- }
- } catch (error) {
- console.error('Error fetching namespace list:', error.message);
- } finally {
- setDatasourceLoading(false);
- }
- })();
- }
- return () => {
- if (intervals[vectorRowData?.dataSourceId]) {
- clearInterval(intervals[vectorRowData?.dataSourceId]);
- delete intervals[vectorRowData?.dataSourceId];
- }
- };
- }, [item]);
-
- const fetchStatus = async (dataSource, name, setData) => {
- try {
- setStatusLoading(true);
- let res = await fetchStatusData(dataSource.id);
- let sitemapStatus = {};
- if (dataSource.type === 'SITEMAP') {
- sitemapStatus = await fetchSitemapStatus(dataSource.id);
- if (
- calculateCompletionPercentage({
- type: dataSource.type,
- statusData: { res, sitemapStatus },
- }) < 100
- ) {
- if (!intervals[dataSource.id]) {
- intervals[dataSource.id] = setInterval(async () => {
- const updatedStatus = await fetchSitemapStatus(dataSource.id);
-
- if (
- calculateCompletionPercentage({
- type: dataSource.type,
- statusData: { res, sitemapStatus: updatedStatus },
- }) === 100
- ) {
- const updatedGlobalStatus = await fetchStatusData(dataSource.id);
-
- setData((prev) => ({
- ...prev,
- statusData: {
- res: updatedGlobalStatus,
- sitemapStatus: updatedStatus,
- },
- }));
-
- clearInterval(intervals[dataSource.id]);
- delete intervals[dataSource.id];
- }
-
- setData((prev) => ({
- ...prev,
- statusData: {
- ...prev.statusData,
- sitemapStatus: updatedStatus,
- },
- }));
- }, 10000);
- }
- } else if (intervals[dataSource.id]) {
- clearInterval(intervals[dataSource.id]);
- delete intervals[dataSource.id];
- }
- }
-
- setData((prev) => ({
- ...prev,
- type: dataSource.type,
- statusData: { res, sitemapStatus },
- }));
- } catch (error) {
- setData((prev) => ({
- ...prev,
- type: dataSource.type,
- statusData: {
- res: {
- res: {
- status: 'failed-retry',
- },
- },
- sitemapStatus: {
- res: {
- status: null,
- },
- },
- },
- }));
- } finally {
- setStatusLoading(false);
- }
- };
-
- const renderSkeletonLoading = () => {
- return <div className="w-32 h-4 bg-gray-200 rounded animate-pulse"></div>;
- };
-
- // Helper function to format file preview content
- const formatFilePreview = () => {
- if (!vectorRowData?.dataSourceName) {
- return 'No data source';
- }
-
- const sourceName = vectorRowData?.dataSourceName;
- const sourceCount = vectorRowData?._count?.dataSources;
- return `${sourceName} (${sourceCount} sources)`;
- };
-
- return (
- <tr
- key={`${vectorRowData.name}_${index}`}
- className="hover:bg-gray-50 border-b border-solid border-gray-100 h-12"
- >
- {/* Data Space Name Column */}
- <td className="px-4 py-4 whitespace-nowrap">
- <Link to={`/data/${vectorRowData.name}`}>
- <Tooltip
- content={vectorRowData.name}
- trigger="hover"
- placement="top"
- className="min-w-max max-w-xs break-words"
- style="dark"
- arrow={false}
- >
- <div className="text-sm font-medium text-gray-900 truncate cursor-pointer hover:text-blue-600 inline-block">
- {vectorRowData.name}
- </div>
- </Tooltip>
- </Link>
- </td>
-
- {/* File Preview Column */}
- <td className="px-4 py-4 whitespace-nowrap">
- {datasourceLoading ? (
- <div className="flex items-center">{renderSkeletonLoading()}</div>
- ) : !vectorRowData?.dataSourceName ? (
- <Link to={`/data/${vectorRowData.name}`}>
- <div className="text-sm text-gray-500">No data source</div>
- </Link>
- ) : (
- <Link to={`/data/${vectorRowData.name}`}>
- <div className="text-sm text-gray-500 flex items-center cursor-pointer hover:text-blue-600">
- <Tooltip
- content={formatFilePreview()}
- trigger="hover"
- placement="top"
- className="min-w-max max-w-md break-words"
- style="dark"
- arrow={false}
- >
- <div className="flex items-center">
- <span className="truncate max-w-[200px]">{vectorRowData?.dataSourceName}</span>
- <span className="ml-2 whitespace-nowrap">{`(${vectorRowData?._count?.dataSources} sources)`}</span>
- </div>
- </Tooltip>
- <i className="ml-2 text-blue-500 fas fa-edit cursor-pointer flex-shrink-0"></i>
- </div>
- </Link>
- )}
- </td>
-
- {/* Index Status Column - No tooltip needed for status */}
- <td className="px-4 py-4 whitespace-nowrap">
- <Link to={`/data/${vectorRowData.name}`}>
- {statusLoading ? (
- <div className="flex items-center">{renderSkeletonLoading()}</div>
- ) : (
- <div className="text-sm">
- {vectorRowData?.statusData && vectorRowData?.statusData.res?.res?.status ? (
- vectorRowData?.type === 'SITEMAP' ? (
- <div className="flex items-center">
- <div className="capitalize">
- {vectorRowData?.statusData.res?.res?.status === 'indexing' ? (
- <div className="flex items-center text-yellow-500">
- <span>● Indexing</span>
- </div>
- ) : (
- <div className="flex items-center text-green-500">
- <span>● Complete</span>
- </div>
- )}
- </div>
- {vectorRowData?.statusData.res?.res?.status !== 'failed-retry' && (
- <div className="pl-1">
- {isNaN(calculateCompletionPercentage(item))
- ? ''
- : calculateCompletionPercentage(item) < 100
- ? calculateCompletionPercentage(item) + '%'
- : ''}
- </div>
- )}
- </div>
- ) : (
- <div className="flex items-center">
- <div className="capitalize">
- {vectorRowData?.statusData.res?.res?.status == 'indexing' ? (
- <div className="flex items-center text-yellow-500">
- <span>● Indexing</span>
- </div>
- ) : (
- <div className="flex items-center text-green-500">
- <span>● Complete</span>
- </div>
- )}
- </div>
- </div>
- )
- ) : (
- <div className="text-gray-500">
- <span className="capitalize">Not Indexed</span>
- </div>
- )}
- </div>
- )}
- </Link>
- </td>
-
- {/* Actions Column */}
- <td className="px-4 py-4 whitespace-nowrap text-right">
- <div className="flex items-center justify-end space-x-2">
- <Tooltip
- content="Add Data Source"
- trigger="hover"
- placement="top"
- style="dark"
- arrow={false}
- >
- <FilePlus
- className="h-4 w-4 text-[#242424] cursor-pointer hover:text-blue-600"
- onClick={handleOpenAddDataDialog}
- />
- </Tooltip>
- <Tooltip
- content="Delete Data Space"
- trigger="hover"
- placement="top"
- style="dark"
- arrow={false}
- >
- <Trash2
- className="h-4 w-4 text-[#242424] cursor-pointer hover:text-red-600"
- onClick={() => openNamespaceDeleteDialog(vectorRowData.name)}
- />
- </Tooltip>
- </div>
- </td>
- </tr>
- );
-}
diff --git a/packages/app/src/react/features/data-space/components/vectorsTable.tsx b/packages/app/src/react/features/data-space/components/vectorsTable.tsx
deleted file mode 100644
index e132c6e6..00000000
--- a/packages/app/src/react/features/data-space/components/vectorsTable.tsx
+++ /dev/null
@@ -1,147 +0,0 @@
-import TableRow from '@react/features/data-space/components/tableRow';
-import AddDatasourceDialog from '@react/features/data-space/dialogs/addDatasource';
-import DeleteNamespace from '@react/features/data-space/dialogs/deleteNamespace';
-import { extractError } from '@react/shared/utils/errors';
-import { Dispatch, FC, SetStateAction, useState } from 'react';
-import { toast } from 'react-toastify';
-
-interface DataItem {
- name: string;
- id: string;
-}
-
-interface VectorsTableProps {
- dataArray: DataItem[];
- setNamespaceData?: Dispatch<SetStateAction<any[]>>;
- handleNamespacesAfterDelete?: () => void;
-}
-
-const VectorsTable: FC<VectorsTableProps> = ({
- setNamespaceData,
- handleNamespacesAfterDelete,
- dataArray,
-}) => {
- const [namespaceState, setNamespaceState] = useState({
- deleteNamespaceInput: '',
- selectedNamespace: '',
- deleteNamespaceDialog: false,
- deleteNamespaceLoading: false,
- deleteNamespaceError: '',
- });
-
- const [addDataSourceState, setAddDataSourceState] = useState({
- dataSourceNameInput: '',
- dataSourceDialog: false,
- addDataSourceLoading: false,
- addDataSourceError: false,
- dataSourceType: 'SITEMAP',
- dataSourceURL: '',
- message: false,
- sourceCategory: 'URL',
- uploadedFile: false,
- selectedItem: '',
- fetchStatusFunction: false,
- setDataSourceArray: false,
- });
-
- const openNamespaceDeleteDialog = (value: string) => {
- setNamespaceState({
- ...namespaceState,
- deleteNamespaceDialog: true,
- selectedNamespace: value,
- deleteNamespaceInput: '',
- deleteNamespaceError: '',
- });
- };
-
- const handleChange = (value: string) => {
- setNamespaceState({ ...namespaceState, deleteNamespaceInput: value, deleteNamespaceError: '' });
- };
-
- const handleNamespaceDelete = async (value: string) => {
- setNamespaceState({ ...namespaceState, deleteNamespaceLoading: true });
- try {
- await fetch(`/api/page/vectors/namespaces/${value}`, {
- method: 'DELETE',
- });
- toast.success('Data Space Deleted Successfully');
- setNamespaceData?.(dataArray.filter((item) => item.name !== value));
- handleNamespacesAfterDelete?.();
- setNamespaceState({
- ...namespaceState,
- deleteNamespaceLoading: false,
- deleteNamespaceDialog: false,
- });
- } catch (error: any) {
- const errorMessage =
- error.status === 403 && extractError(error) === 'Forbidden'
- ? 'You are not authorized to delete this data space'
- : extractError(error) || 'An error occurred while deleting the data space';
- setNamespaceState({
- ...namespaceState,
- deleteNamespaceLoading: false,
- deleteNamespaceError: errorMessage,
- });
- }
- };
-
- return (
- <div className="relative w-full">
- <div className="bg-white rounded-lg w-full">
- <div className="overflow-x-auto">
- <table className="w-full table-fixed border border-solid border-gray-100">
- <thead className="bg-gray-50 rounded-lg overflow-hidden">
- <tr>
- <th className="px-4 py-3 text-left text-xs font-semibold text-[#242424] uppercase tracking-wider w-1/4">
- Data Spaces
- </th>
- <th className="px-4 py-3 text-left text-xs font-semibold text-[#242424] uppercase tracking-wider w-2/5">
- File Preview
- </th>
- <th className="px-4 py-3 text-left text-xs font-semibold text-[#242424] uppercase tracking-wider w-1/4">
- Indexing Status
- </th>
- <th className="px-4 py-3 w-[100px]"></th>
- </tr>
- </thead>
- <tbody className="bg-white divide-y divide-gray-200">
- {dataArray &&
- dataArray?.map((item, index) => {
- return (
- <TableRow
- item={item}
- index={index}
- openNamespaceDeleteDialog={openNamespaceDeleteDialog}
- handleOpenAddDataDialog={() =>
- setAddDataSourceState({
- ...addDataSourceState,
- dataSourceDialog: true,
- selectedItem: item.name,
- })
- }
- key={`${item.name}_${index}`}
- />
- );
- })}
- </tbody>
- </table>
- </div>
- </div>
- <DeleteNamespace
- namespaceState={namespaceState}
- open={namespaceState.deleteNamespaceDialog}
- onClose={() => setNamespaceState({ ...namespaceState, deleteNamespaceDialog: false })}
- handleChange={handleChange}
- handleNamespaceDelete={handleNamespaceDelete}
- />
- {addDataSourceState.dataSourceDialog && (
- <AddDatasourceDialog
- namespaceName={addDataSourceState.selectedItem}
- onClose={() => setAddDataSourceState({ ...addDataSourceState, dataSourceDialog: false })}
- />
- )}
- </div>
- );
-};
-
-export default VectorsTable;
diff --git a/packages/app/src/react/features/data-space/dialogs/addDatasource.tsx b/packages/app/src/react/features/data-space/dialogs/addDatasource.tsx
deleted file mode 100644
index 373016ca..00000000
--- a/packages/app/src/react/features/data-space/dialogs/addDatasource.tsx
+++ /dev/null
@@ -1,228 +0,0 @@
-import { addDatasource } from '@react/features/data-space/client/dataspace.api-client.service';
-import DatasourceFileUpload from '@react/features/data-space/components/datasourceFileUpload';
-import { Input as CustomInput } from '@react/shared/components/ui/input';
-import Modal from '@react/shared/components/ui/modals/Modal';
-import { Button as CustomButton } from '@react/shared/components/ui/newDesign/button';
-import { queryClient } from '@react/shared/query-client';
-import { SmythAPIError } from '@react/shared/types/api-results.types';
-import { extractError } from '@react/shared/utils/errors';
-import { autoDetectDSFileType } from '@react/shared/utils/utils';
-import { useMutation } from '@tanstack/react-query';
-import { useState } from 'react';
-import { toast } from 'react-toastify';
-import * as yup from 'yup';
-
-type Props = {
- namespaceName: string;
- onClose: () => void;
-};
-
-export const autoDetectDSByURL = (url: string) => {
- let _url: URL | null = null;
-
- try {
- _url = new URL(url);
- } catch (error) {
- return null;
- }
-
- // if no extension, consider it as a webpage
- if (_url.pathname.split('.').length == 1) return 'WEBPAGE';
- // if it's a youtube video, consider it as a transcript
- if (_url.hostname === 'www.youtube.com' || _url.hostname === 'youtube.com') {
- return 'TRANSCRIPT';
- }
-
- const ext = _url.pathname.split('.').pop().toLowerCase();
-
- switch (ext) {
- case 'pdf':
- return 'PDF';
- case 'xml':
- return 'SITEMAP';
- case 'html':
- case 'htm':
- case 'txt':
- return 'WEBPAGE';
- case 'doc':
- case 'docx':
- return 'WORD';
- default:
- return null;
- }
-};
-
-type DsForm = 'URL' | 'FILE';
-
-const AddDatasourceDialog = ({ namespaceName, onClose }: Props) => {
- const [dsFile, setDsFile] = useState<File>();
- const [uploadedFileUrl, setUploadedFileUrl] = useState('');
- const [fileName, setFileName] = useState('');
- const [disableUpload, setDisableUpload] = useState(false);
- const [dsDetails, setDsDetails] = useState({ name: '', type: '', url: '' });
- const [errorMessage, setErrorMessage] = useState('');
- const [fileUploadError, setFileUploadError] = useState('');
-
- const [errors, setValidationErrors] = useState({
- url: null,
- name: null,
- });
- const urlSchema = yup.string().url();
-
- const handleDataSourceChange = (value: string, dsForm: DsForm) => {
- if (dsForm !== 'URL') return;
- setValidationErrors((prev) => ({ ...prev, url: null }));
- // if value does not include http or https, add it
- // const completeUrl = value.includes('http') ? value.trim() : `https://${value.trim()}`;
- const type = autoDetectDSByURL(value);
- setDsDetails({
- ...dsDetails,
- type,
- url: value?.trim(),
- });
- if (!value?.trim()) {
- setDisableUpload(false);
- } else {
- setDisableUpload(true);
- }
- };
-
- const addDsMutation = useMutation({
- mutationFn: addDatasource,
-
- onError: (error: SmythAPIError) => {
- const _errorMessage =
- error.status === 403 && extractError(error) === 'Forbidden'
- ? 'You are not authorized to add a new data source'
- : extractError(error) || 'An error occurred. Please try again later.';
- setErrorMessage(_errorMessage);
- console.log(error);
- },
- onSuccess: () => {
- toast.success('Data source added successfully');
- queryClient.invalidateQueries({ queryKey: [`datasources-${namespaceName}`] });
- },
- });
-
- // TODO: refactor function
- const handlePostDataSource = async (url: string, name: string, namespaceName: string, type) => {
- if (!name?.trim()) {
- setValidationErrors((prev) => ({ ...prev, name: 'Please enter a name for the datasource.' }));
- return;
- }
-
- if ((!dsFile || !uploadedFileUrl) && !urlSchema.isValidSync(url)) {
- // in case not file was uploaded, and the url is not valid
- setValidationErrors((prev) => ({ ...prev, url: 'Please enter a valid URL.' }));
- return;
- }
-
- let urlValue = '';
- let typeValue = '';
-
- if (dsFile) {
- urlValue = uploadedFileUrl;
- typeValue = await autoDetectDSFileType(dsFile);
- } else if (url !== '') {
- urlValue = url;
- typeValue = type;
- }
-
- try {
- const data = await addDsMutation.mutateAsync({
- body: {
- name: name,
- namespaceName,
- type: typeValue,
- url: urlValue,
- },
- });
-
- onClose();
- } catch (error) {
- console.log(error);
- }
- };
-
- return (
- <>
- <Modal
- onClose={onClose}
- title="Add Data Source"
- panelWidthClasses="mx-auto w-[290px] sm:w-[400px]"
- >
- <div className="modal-body">
- <div className="flex flex-col gap-4">
- <div className="w-full pb-4">
- <CustomInput
- label="Name"
- labelExample="(required)"
- value={dsDetails.name}
- onChange={(event) => {
- setValidationErrors((prev) => ({ ...prev, name: null }));
- setDsDetails({ ...dsDetails, name: event.target.value });
- }}
- fullWidth
- placeholder="Type data source name"
- id="datasourceInput"
- required={true}
- />
- {errors?.name && <div className="text-red-600 text-sm">{errors.name}</div>}
- </div>
-
- <DatasourceFileUpload
- disableUpload={disableUpload}
- fileName={fileName}
- setFile={setDsFile}
- setUploadedUrl={setUploadedFileUrl}
- setFileName={setFileName}
- setFileUploadError={setFileUploadError}
- />
- <div className="py-4 text-center text-black">OR</div>
-
- <div>
- <CustomInput
- value={dsDetails.url}
- fullWidth
- placeholder="Type data source URL"
- label="Enter URL"
- labelExample="(sitemap or website URL)"
- disabled={!!dsFile}
- onChange={(event) => handleDataSourceChange(event.target.value, 'URL')}
- />
-
- {dsDetails.type && (
- <div className="success-message pt-1" id="verify-message">
- <span id="selectedType">{dsDetails.type} </span> format automatically detected.
- </div>
- )}
- {errors?.url && <div className="text-red-600 text-sm">{errors.url}</div>}
- </div>
-
- {addDsMutation.isError && (
- <div className="pt-2 text-red-600 text-sm">{errorMessage}</div>
- )}
-
- {!addDsMutation.isError && fileUploadError && (
- <div className="pt-2 text-red-600 text-sm">{fileUploadError}</div>
- )}
-
- <div className="flex gap-3 mt-4 ">
- <CustomButton
- type="submit"
- className="justify-center flex-1"
- disabled={addDsMutation.isLoading}
- label={'Add Data Source'}
- loading={addDsMutation.isLoading}
- handleClick={() =>
- handlePostDataSource(dsDetails.url, dsDetails.name, namespaceName, dsDetails.type)
- }
- />
- </div>
- </div>
- </div>
- </Modal>
- </>
- );
-};
-export default AddDatasourceDialog;
diff --git a/packages/app/src/react/features/data-space/dialogs/addNamespace.tsx b/packages/app/src/react/features/data-space/dialogs/addNamespace.tsx
deleted file mode 100644
index 5446ca26..00000000
--- a/packages/app/src/react/features/data-space/dialogs/addNamespace.tsx
+++ /dev/null
@@ -1,353 +0,0 @@
-import { getVectorsCustomStorage } from '@react/features/data-space/client/dataspace.api-client.service';
-import { Input as CustomInput } from '@react/shared/components/ui/input';
-import Modal from '@react/shared/components/ui/modals/Modal';
-import config from '@src/builder-ui/config';
-import plansDev from '@src/react/features/subscriptions/data/plans.v4.dev.json';
-import plansProd from '@src/react/features/subscriptions/data/plans.v4.prod.json';
-import { generatePricingUrl } from '@src/react/features/subscriptions/utils';
-import { Button } from '@src/react/shared/components/ui/newDesign/button';
-import { useAuthCtx } from '@src/react/shared/contexts/auth.context';
-import { PRICING_PLANS_V4 } from '@src/react/shared/enums';
-import { extractError } from '@src/react/shared/utils/errors';
-import { cn, navigateTo } from '@src/react/shared/utils/general';
-import { useQuery } from '@tanstack/react-query';
-import { ArrowUpRightIcon } from 'lucide-react';
-import { ChangeEvent, FormEvent, useState } from 'react';
-import { toast } from 'react-toastify';
-
-type AddNamespaceDialogComponent = {
- handleClick: (useUserCustomStorage?: boolean) => void;
- disableBtn: boolean;
- onClose: () => void;
- open: boolean;
- loading: boolean;
- handleChange: (event: ChangeEvent<HTMLInputElement>) => void;
- inputValue: string;
- namespaceError: boolean | string;
-};
-
-enum OptionType {
- CONTINUE_FREE = 'continue-free',
- STARTUP = 'startup',
-}
-
-const pricingTiers = config.env.IS_DEV ? plansDev : plansProd;
-
-export default function AddNamespaceDialog({
- handleClick,
- disableBtn,
- onClose,
- open,
- loading,
- handleChange,
- inputValue,
- namespaceError,
-}: AddNamespaceDialogComponent) {
- const [useUserCustomStorage, setUseUserCustomStorage] = useState(false);
- const [isLoading, setIsLoading] = useState(false);
-
- const customConfiguration = useQuery({
- queryKey: ['custom_vector_storage_configuration_get'],
- queryFn: getVectorsCustomStorage,
- refetchOnMount: false,
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- });
-
- const {
- userInfo: { subs: userSubs },
- refreshUserData,
- } = useAuthCtx();
-
- const isBuilderPlan = userSubs.plan.paid && userSubs.plan.name === PRICING_PLANS_V4.BUILDER;
- const showUpgradeInfo = !userSubs.plan.paid || isBuilderPlan;
-
- const [selectedOption, setSelectedOption] = useState(OptionType.CONTINUE_FREE);
-
- const handleSubmit = (e: FormEvent) => {
- e.preventDefault();
- if (selectedOption === OptionType.CONTINUE_FREE) {
- handleClick(useUserCustomStorage);
- } else {
- if (isBuilderPlan) {
- changePaymentPlan();
- return;
- }
- const startupPlanPricing = pricingTiers.find(
- (tier) => tier.name === PRICING_PLANS_V4.STARTUP,
- );
- const url = generatePricingUrl(
- startupPlanPricing?.buttonAction,
- startupPlanPricing?.priceIds,
- );
- navigateTo(url, false, '_blank');
- }
- };
-
- const changePaymentPlan = async () => {
- try {
- setIsLoading(true);
- const res = await fetch('/api/page/plans/subscriptions/v2/change-plan', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- newPriceIds:
- pricingTiers.find((tier) => tier.name === PRICING_PLANS_V4.STARTUP)?.priceIds ?? [],
- isUserAcknowledged: true,
- }),
- });
-
- const responseData = await res.json();
-
- try {
- let parsedMessage = JSON.parse(responseData?.message);
- if (parsedMessage && parsedMessage.warnings && Array.isArray(parsedMessage.warnings)) {
- toast.warning(parsedMessage.warnings.join('\n'));
- } else {
- toast.success('Your subscription has been updated.');
- }
- } catch {
- // do nothing
- toast.success('Your subscription has been updated.');
- }
- await new Promise((resolve) => setTimeout(resolve, 2000));
- await refreshUserData();
- setTimeout(() => navigateTo('/my-plan', false), 500);
- } catch (error) {
- const errorMessage = extractError(error);
- toast.error(errorMessage || 'Something went wrong. Please try again.');
- } finally {
- setIsLoading(false);
- }
- };
-
- return (
- <Modal
- title="Create Data Space"
- isOpen={open}
- onClose={onClose}
- panelWidthClasses="min-w-[300px] md:w-[512px]"
- panelWrapperClasses="flex justify-center"
- >
- <div className="flex flex-col gap-4 mt-6">
- {/* Modal content */}
- <div>
- {showUpgradeInfo && (
- <p className="text-gray-600 text-sm leading-relaxed mb-4">
- Set up a Data Space to unlock your agents' ability to search, automate, and learn from
- your data—using RAG and other tools.
- </p>
- )}
-
- <form onSubmit={handleSubmit}>
- <div className="flex flex-col gap-6 mb-6">
- {/* Data Space Name Input */}
- <CustomInput
- placeholder="Type Data Space Name"
- value={inputValue}
- onChange={handleChange}
- required
- fullWidth
- label="Name"
- />
-
- {/* Plan Selection */}
- {showUpgradeInfo && (
- <div className="w-full">
- <div className="text-gray-700 mb-2 text-sm font-normal">Select Plan</div>
- <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
- {/* Continue for now option */}
- <div className="relative">
- <input
- type="radio"
- id="continue-free"
- name="plan"
- value="continue-free"
- checked={selectedOption === OptionType.CONTINUE_FREE}
- onChange={(e) => setSelectedOption(e.target.value as OptionType)}
- className="sr-only"
- />
- <label
- htmlFor="continue-free"
- className={`flex flex-col p-4 rounded-md cursor-pointer transition-all duration-200 ${
- selectedOption === OptionType.CONTINUE_FREE
- ? 'border border-solid bg-blue-50 border-blue-500'
- : 'border border-solid bg-gray-50 border-gray-300 hover:border-gray-400'
- }`}
- >
- <div className="flex items-center justify-between mb-1">
- <h4 className="text-gray-900 font-medium text-sm">Continue for now</h4>
- <div
- className={`w-4 h-4 border-2 rounded-full flex items-center justify-center ${
- selectedOption === OptionType.CONTINUE_FREE
- ? 'border-blue-500 bg-blue-500'
- : 'border-gray-300'
- }`}
- >
- <div
- className={`w-1.5 h-1.5 bg-white rounded-full ${
- selectedOption === OptionType.CONTINUE_FREE
- ? 'opacity-100'
- : 'opacity-0'
- }`}
- ></div>
- </div>
- </div>
- <p className="text-gray-600 text-xs">Limited features</p>
- </label>
- </div>
-
- {/* Startup Plan */}
- <div className="relative">
- <input
- type="radio"
- id="startup"
- name="plan"
- value="startup"
- checked={selectedOption === OptionType.STARTUP}
- onChange={(e) => setSelectedOption(e.target.value as OptionType)}
- className="sr-only"
- />
- <label
- htmlFor="startup"
- className={`flex flex-col p-4 rounded-md cursor-pointer transition-all duration-200 ${
- selectedOption === OptionType.STARTUP
- ? 'border border-solid bg-blue-50 border-blue-500'
- : 'border border-solid bg-gray-50 border-gray-300 hover:border-gray-400'
- }`}
- >
- <div className="flex items-center justify-between mb-1">
- <h4
- className={`font-medium text-sm ${
- selectedOption === OptionType.STARTUP
- ? 'text-blue-700'
- : 'text-gray-900'
- }`}
- >
- Startup
- </h4>
- <div
- className={`w-4 h-4 border-2 rounded-full flex items-center justify-center ${
- selectedOption === OptionType.STARTUP
- ? 'border-blue-500 bg-blue-500'
- : 'border-gray-300'
- }`}
- >
- <div
- className={`w-1.5 h-1.5 bg-white rounded-full ${
- selectedOption === OptionType.STARTUP ? 'opacity-100' : 'opacity-0'
- }`}
- ></div>
- </div>
- </div>
- <p
- className={`text-xs ${
- selectedOption === OptionType.STARTUP
- ? 'text-blue-600'
- : 'text-gray-600'
- }`}
- >
- Get started now
- </p>
- </label>
- </div>
- </div>
- </div>
- )}
- </div>
-
- {/* Custom Storage Section - Smooth transition */}
- {!customConfiguration.isLoading && customConfiguration.data?.isConfigured && (
- <div
- className={`w-full transition-all duration-500 ease-in-out overflow-hidden ${
- selectedOption === OptionType.CONTINUE_FREE
- ? 'max-h-32 opacity-100 transform translate-y-0'
- : 'max-h-0 opacity-0 transform -translate-y-2'
- }`}
- >
- <div className="pb-6">
- <div
- className={cn(
- 'flex items-center space-x-3 bg-white p-4 transition-colors duration-200',
- 'border border-solid border-gray-200 hover:border-gray-300 rounded-lg',
- )}
- >
- <label className="relative inline-flex items-center cursor-pointer">
- <input
- type="checkbox"
- value=""
- className="sr-only peer"
- checked={useUserCustomStorage}
- onChange={(e) => {
- setUseUserCustomStorage(e.target.checked);
- }}
- />
- <div
- className={cn(
- 'w-11 h-6 bg-gray-200 rounded-full',
- 'peer peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800',
- 'dark:border-gray-600 peer-checked:bg-blue-600',
- 'after:absolute after:top-0.5 after:left-[2px] after:bg-white after:border-gray-300',
- 'after:border after:rounded-full after:h-5 after:w-5 after:transition-all',
- 'dark:bg-gray-700 peer-checked:after:translate-x-full',
- "peer-checked:after:border-white after:content-[''] ",
- )}
- ></div>
- <span className="flex flex-col items-start ml-3">
- <span className="text-sm font-medium text-gray-900 dark:text-gray-300">
- Use Custom Storage
- </span>
- <p className="text-xs text-gray-500 mt-0.5">
- Connect your saved storage configuration
- </p>
- </span>
- </label>
- </div>
- </div>
- </div>
- )}
-
- {/* Plan-specific warnings */}
- {selectedOption === OptionType.CONTINUE_FREE && showUpgradeInfo && (
- <div className="bg-amber-50 border border-amber-200 rounded-md p-3 mb-4">
- <p className="text-amber-800 text-xs">
- <strong>Note:</strong> Without upgrading to Startup, you will be unable to use RAG
- applications and other advanced features.
- </p>
- </div>
- )}
-
- {/* Subscription info */}
- {selectedOption === OptionType.STARTUP && showUpgradeInfo && (
- <p className="text-gray-500 text-xs mb-4 flex flex-wrap">
- Continuing will start a monthly Startup plan subscription.&nbsp;
- <a
- href="https://smythos.com/pricing/"
- target="_blank"
- className="text-blue-600 hover:text-blue-700 underline flex"
- >
- Learn More <ArrowUpRightIcon className="w-4 h-4" />
- </a>
- </p>
- )}
-
- {/* Action buttons */}
-
- <Button
- className="w-full"
- loading={loading || isLoading}
- disabled={!inputValue.trim() || disableBtn}
- type="submit"
- >
- {showUpgradeInfo ? 'Continue' : 'Add Data Space'}
- </Button>
- </form>
- </div>
-
- {namespaceError && <div className="pt-2 text-red-600">{namespaceError}</div>}
- </div>
- </Modal>
- );
-}
diff --git a/packages/app/src/react/features/data-space/dialogs/datasourceInfo.tsx b/packages/app/src/react/features/data-space/dialogs/datasourceInfo.tsx
deleted file mode 100644
index d209123f..00000000
--- a/packages/app/src/react/features/data-space/dialogs/datasourceInfo.tsx
+++ /dev/null
@@ -1,102 +0,0 @@
-import Modal from '@react/shared/components/ui/modals/Modal';
-import { Button as CustomButton } from '@react/shared/components/ui/newDesign/button';
-import { Datasource } from '@react/shared/types/api-results.types';
-import { Progress } from 'flowbite-react';
-import { FaRegCheckCircle, FaRegClock } from 'react-icons/fa'; // for pending and done
-import { MdOutlineErrorOutline, MdOutlineLink } from 'react-icons/md'; // for failed
-
-type Props = {
- onClose: () => void;
- item: Datasource;
- status: 'done' | 'pending' | 'indexing' | 'failed-retry' | 'failed' | 'done-duplicate' | null;
- lastCrawledAt: string;
- sitemapStatus?: {
- total: number;
- completed: number;
- pending: number;
- failed: number;
- nextCrawlAt?: string;
- } | null;
-};
-
-const DatasourceInfoModal = ({ onClose, item, sitemapStatus, status, lastCrawledAt }: Props) => {
- const processed = sitemapStatus?.total - sitemapStatus?.pending;
- const percentage = sitemapStatus ? Math.round((processed / sitemapStatus.total) * 100) : 0;
- const failed = sitemapStatus ? sitemapStatus.failed : 0;
- const pending = sitemapStatus ? sitemapStatus.pending : 0;
- const completed = sitemapStatus ? sitemapStatus.completed : 0;
-
- const formattedNextCrawlAt = sitemapStatus?.nextCrawlAt
- ? new Date(sitemapStatus.nextCrawlAt).toLocaleDateString('en-US', {
- weekday: 'long',
- year: 'numeric',
- month: 'long',
- day: 'numeric',
- })
- : 'N/A';
- const formattedLastCrawlAt = lastCrawledAt
- ? new Date(lastCrawledAt).toLocaleDateString('en-US', {
- weekday: 'long',
- year: 'numeric',
- month: 'long',
- day: 'numeric',
- })
- : 'N/A';
-
- return (
- <Modal title="Data Source Details" onClose={() => onClose()}>
- <div className="modal-body">
- <div className="flex flex-col gap-4">
- <div className="w-full pb-4">
- <div className="mt-4 flex flex-col gap-4">
- <p>
- <span className="font-bold">Name:</span> {item.name}
- </p>
- <p>
- <span className="font-bold">Source:</span>{' '}
- {item?.url?.startsWith('storage:') ? 'File Upload' : item?.url}
- </p>
- <p>
- <span className="font-bold">Last Crawl:</span>{' '}
- {status === 'done' || status === 'done-duplicate' ? formattedLastCrawlAt : 'N/A'}
- </p>
- <p>
- <span className="font-bold">Next Crawl:</span> {formattedNextCrawlAt}
- </p>
- </div>
-
- {item.type == 'SITEMAP' && (
- <>
- <Progress progress={percentage} className="mt-4 progress-bar-custom" color="blue" />
- <div className="flex gap-4 mt-4">
- <div className="flex items-center">
- <FaRegClock className="text-primary" />
- <span className="pl-2">Pending: {pending}</span>
- </div>
- <div className="flex items-center">
- <FaRegCheckCircle className="text-primary" />
- <span className="pl-2">Completed: {completed}</span>
- </div>
- <div className="flex items-center">
- <MdOutlineErrorOutline className="text-primary" />
- <span className="pl-2">Failed: {failed}</span>
- </div>
- <div className="flex items-center">
- <MdOutlineLink className="text-primary" />
- <span className="pl-2">Total: {sitemapStatus?.total}</span>
- </div>
- </div>
- </>
- )}
-
- <div className="flex justify-end mt-8">
- <CustomButton label="Close" handleClick={() => onClose()} className="text-white" />
- </div>
- </div>
- </div>
- </div>
- </Modal>
- );
-};
-
-export default DatasourceInfoModal;
diff --git a/packages/app/src/react/features/data-space/dialogs/deleteDatasource.tsx b/packages/app/src/react/features/data-space/dialogs/deleteDatasource.tsx
deleted file mode 100644
index 5998a0d1..00000000
--- a/packages/app/src/react/features/data-space/dialogs/deleteDatasource.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import { deleteDatasource } from '@react/features/data-space/client/dataspace.api-client.service';
-import Modal from '@react/shared/components/ui/modals/Modal';
-import { Button as CustomButton } from '@react/shared/components/ui/newDesign/button';
-import { queryClient } from '@react/shared/query-client';
-import { Datasource, SmythAPIError } from '@react/shared/types/api-results.types';
-import { extractError } from '@react/shared/utils/errors';
-import { useMutation } from '@tanstack/react-query';
-import { useState } from 'react';
-import { toast } from 'react-toastify';
-
-interface Props {
- onClose: () => void;
- item: Datasource;
- namespaceName: string;
- remove: () => void;
-}
-
-export default function DeleteDatasourceDialog({ onClose, item, namespaceName, remove }: Props) {
- const [errorMessage, setErrorMessage] = useState('');
-
- const deleteMutation = useMutation({
- mutationFn: () => deleteDatasource({ id: item.id }),
-
- onError: (error: SmythAPIError) => {
- let _errorMessage =
- error.status === 403 && extractError(error) === 'Forbidden'
- ? 'You are not authorized to delete this data source'
- : extractError(error) || 'An error occurred. Please try again later.';
- setErrorMessage(_errorMessage);
- console.log(error);
- },
- onSuccess: () => {
- toast.success('Datasource deleted successfully');
- queryClient.invalidateQueries({ queryKey: [`datasources-${namespaceName}`] });
- remove();
- },
- });
-
- return (
- <Modal onClose={onClose} title="Confirm Datasource Deletion">
- <div className="modal-body">
- <div className="text mt-2">
- Please be aware that deleting this <b className="text-black">datasource</b> will
- permanently remove it from your records. This action is irreversible.{' '}
- </div>
-
- {deleteMutation.isError && <p className="text-red-500 py-4">{errorMessage}</p>}
-
- <CustomButton
- handleClick={async () => {
- await deleteMutation.mutateAsync();
- onClose();
- }}
- disabled={deleteMutation.isLoading}
- loading={deleteMutation.isLoading}
- fullWidth
- label="Delete"
- className="mt-5"
- />
- </div>
- </Modal>
- );
-}
diff --git a/packages/app/src/react/features/data-space/dialogs/deleteNamespace.tsx b/packages/app/src/react/features/data-space/dialogs/deleteNamespace.tsx
deleted file mode 100644
index aab5afa4..00000000
--- a/packages/app/src/react/features/data-space/dialogs/deleteNamespace.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-import { Input as CustomInput } from '@react/shared/components/ui/input';
-import Modal from '@src/react/shared/components/ui/modals/Modal';
-import { Button } from '@src/react/shared/components/ui/newDesign/button';
-import { Trash2 } from 'lucide-react';
-
-export default function DeleteNamespace({
- namespaceState,
- open,
- onClose,
- handleChange,
- handleNamespaceDelete,
-}) {
- return (
- <div>
- <Modal
- title="Confirm Data Space Deletion"
- isOpen={open}
- onClose={onClose}
- panelWrapperClasses="min-w-[300px] md:w-full flex justify-center"
- >
- <div className="flex flex-col gap-4 my-6">
- <div className="text-sm ">
- Please be aware that deleting this Data Space will permanently remove it from your
- records.
- </div>
- <div className="text-sm pb-4">
- Type the data space name to confirm :{' '}
- <span className="font-bold">{namespaceState.selectedNamespace}</span>{' '}
- </div>
-
- <CustomInput
- value={namespaceState.deleteNamespaceInput}
- onChange={(event) => handleChange(event.target.value)}
- fullWidth
- placeholder="Type Data Space Name"
- id="namespaceDeleteInput"
- error={namespaceState.deleteNamespaceError}
- errorMessage={namespaceState.deleteNamespaceError}
- />
- </div>
- <Button
- className='w-full'
- loading={namespaceState.deleteNamespaceLoading}
- handleClick={() => handleNamespaceDelete(namespaceState.selectedNamespace)}
- disabled={
- namespaceState.deleteNamespaceInput !== namespaceState.selectedNamespace ||
- namespaceState.deleteNamespaceLoading
- }
- addIcon
- Icon={<Trash2 size={16} className='mr-1' />}
- >
- Delete
- </Button>
- </Modal>
- </div>
- );
-}
diff --git a/packages/app/src/react/features/data-space/modals/CustomVectorStorageConfigModal.tsx b/packages/app/src/react/features/data-space/modals/CustomVectorStorageConfigModal.tsx
deleted file mode 100644
index fecdd8f7..00000000
--- a/packages/app/src/react/features/data-space/modals/CustomVectorStorageConfigModal.tsx
+++ /dev/null
@@ -1,335 +0,0 @@
-import {
- deleteCustomVectorStorage,
- saveCustomVectorStorage,
-} from '@react/features/data-space/client/dataspace.api-client.service';
-import Modal from '@react/shared/components/ui/modals/Modal';
-import { Button as CustomButton } from '@react/shared/components/ui/newDesign/button';
-import { SmythAPIError, VectorsCustomStorage } from '@react/shared/types/api-results.types';
-import { SMYTHOS_DOCS_URL } from '@src/shared/constants/general';
-import { useMutation } from '@tanstack/react-query';
-import { Tooltip } from 'flowbite-react';
-import { ErrorMessage, Field, Form, Formik } from 'formik';
-import { useState } from 'react';
-import { FaCircleExclamation } from 'react-icons/fa6';
-import { IoInformationCircleOutline } from 'react-icons/io5';
-import { toast } from 'react-toastify';
-import * as Yup from 'yup';
-
-type Props = {
- onClose: () => void;
- data: VectorsCustomStorage;
- resetDataAndRefetch: () => void;
-};
-
-const inputClass = ` bg-white
- border
- text-gray-900
- rounded
- block
- w-full
- outline-none
- focus:outline-none
- focus:ring-0
- focus:ring-offset-0
- focus:ring-shadow-none
- text-sm
- font-normal
- placeholder:text-sm
- placeholder:font-normal
- border-gray-300 border-b-gray-500 focus:border-b-2 focus:border-b-blue-500 focus-visible:border-b-2 focus-visible:border-b-blue-500
-`;
-
-// Create a custom error component
-const CustomErrorMessage = ({ children }) => (
- <span className="flex items-start text-[12px] text-red-500 font-normal mt-2">
- <FaCircleExclamation className="text-red-500 mr-1 w-[10px] h-[10px] mt-[3px]" />
- {children}
- </span>
-);
-
-const CustomVectorStorageConfigModal = ({
- onClose,
- data,
- resetDataAndRefetch: refetchData,
-}: Props) => {
- const [existingConfigPrompts, setExistingConfigPrompts] = useState({
- showDeleteExistingConfigModal: false,
- hasAccepedDeletingExistingConfig: false,
- });
-
- const initialValues = {
- apiKey: data?.storage?.apiKey || '',
- indexName: data?.storage?.indexName || '',
- environment: data?.storage?.environment || '',
- projectUrl: data?.storage?.projectUrl || '',
- };
-
- const validationSchema = Yup.object().shape({
- apiKey: Yup.string().required('API Key is required'),
- indexName: Yup.string().required('Index Name is required'),
- environment: Yup.string().required('Environment is required'),
- projectUrl: Yup.string().url('Invalid URL').required('Project URL is required'),
- });
-
- const saveConfigMutation = useMutation({
- mutationFn: saveCustomVectorStorage,
- mutationKey: ['custom_vector_storage_configuration_save'],
-
- onSuccess: () => {
- toast.success('Configuration saved successfully');
- refetchData();
- },
- });
-
- const deleteConfigMutation = useMutation({
- mutationFn: deleteCustomVectorStorage,
- mutationKey: ['custom_vector_storage_configuration_delete'],
-
- onError: (error: SmythAPIError) => {
- toast.error(error.error.message ?? 'Something went wrong');
- console.log(error);
- },
- onSuccess: () => {
- toast.success('Configuration deleted successfully');
- },
- });
-
- const handleSubmit = async (
- values: {
- apiKey: string;
- environment: string;
- indexName: string;
- projectUrl: string;
- },
- { setSubmitting },
- ) => {
- // IF data is configured, prompt the user to delete the existing configuration first
- if (data.isConfigured && !existingConfigPrompts.hasAccepedDeletingExistingConfig) {
- setExistingConfigPrompts((prev) => ({ ...prev, showDeleteExistingConfigModal: true }));
- } else {
- await saveConfigMutation.mutateAsync({
- apiKey: values.apiKey,
- environment: values.environment,
- indexName: values.indexName,
- projectUrl: values.projectUrl,
- });
- onClose();
- }
- setSubmitting(false);
- };
-
- const tutorialInfo = (
- <a href={`${SMYTHOS_DOCS_URL}/agent-collaboration/data-pool/custom-storage`} target="_blank" rel="noreferrer">
- <IoInformationCircleOutline
- size="1.2rem"
- cursor={'pointer'}
- className="hover:text-primary-500 dark:hover:text-primary-400 hover:scale-110 transition-all inline-block "
- />
- </a>
- );
-
- return (
- <>
- <Modal onClose={onClose} title="Pinecone Configuration">
- <div className="modal-body">
- <Formik
- initialValues={initialValues}
- validationSchema={validationSchema}
- onSubmit={handleSubmit}
- >
- {({ resetForm, isSubmitting, dirty }) => (
- <Form className="flex flex-col justify-between mt-6 gap-4">
- <div>
- <label
- htmlFor="apiKey"
- className="flex items-start gap-2 text-gray-700 mb-1 text-sm font-normal"
- >
- <span>
- API Key <span className="text-red-500">*</span>
- </span>
- <Tooltip
- content={
- <span>
- Enter your Pinecone API key to authenticate requests to your vector
- database.{' '}
- <a
- href={`${SMYTHOS_DOCS_URL}/agent-collaboration/data-pool/custom-storage`}
- target="_blank"
- rel="noreferrer"
- className="text-primary-500 hover:text-primary-400 hover:underline"
- >
- Learn more
- </a>
- </span>
- }
- style="light"
- placement="right"
- >
- <span className="text-gray-500 text-sm inline-flex items-center cursor-help">
- <IoInformationCircleOutline size="1.2rem" />
- </span>
- </Tooltip>
- </label>
- <Field
- name="apiKey"
- type="text"
- placeholder="e.g. 123-456-7890"
- id="apiKey"
- className={inputClass}
- />
- <ErrorMessage name="apiKey" component={CustomErrorMessage} />
- </div>
-
- <div>
- <label
- htmlFor="indexName"
- className="flex items-start gap-2 text-gray-700 mb-1 text-sm font-normal"
- >
- Index Name <span className="text-red-500">*</span>
- </label>
- <Field
- name="indexName"
- type="text"
- placeholder="e.g. index1"
- id="indexName"
- className={inputClass}
- />
- <ErrorMessage name="indexName" component={CustomErrorMessage} />
- </div>
-
- <div>
- <label
- htmlFor="environment"
- className="flex items-start gap-2 text-gray-700 mb-1 text-sm font-normal"
- >
- Environment/Region
- </label>
- <Field
- name="environment"
- type="text"
- placeholder="e.g. us-west4-gcp"
- id="environment"
- className={inputClass}
- />
- <ErrorMessage name="environment" component={CustomErrorMessage} />
- </div>
-
- <div>
- <label
- htmlFor="projectUrl"
- className="flex items-start gap-2 text-gray-700 mb-1 text-sm font-normal"
- >
- Index Host
- </label>
- <Field
- name="projectUrl"
- type="url"
- placeholder="e.g. https://index1-0000.svc.us-west4-gcp.pinecone.io"
- className={inputClass}
- />
- <ErrorMessage name="projectUrl" component={CustomErrorMessage} />
- </div>
-
- <p className="text-sm text-gray-500 dark:text-gray-400">
- {/* tell the user that he needs to have an index that its vector dimentation is 1536 (tell him in a friendly way) */}
- <b>Note:</b> Make sure that the index has a vector dimension of <b>1536</b>.
- </p>
-
- {/* {submission error span} */}
- {saveConfigMutation.isError && (
- <span className="text-red-500 text-sm">
- {(saveConfigMutation?.error as any)?.error?.message ?? 'Something went wrong'}
- </span>
- )}
-
- <div className="flex gap-3 mt-4 ">
- {data.isConfigured && (
- <CustomButton
- className="flex-0.5"
- type="button"
- label="Delete"
- isDelete
- handleClick={() =>
- setExistingConfigPrompts((prev) => ({
- ...prev,
- showDeleteExistingConfigModal: true,
- }))
- }
- />
- )}
- <CustomButton
- type="submit"
- className="flex-1"
- disabled={
- isSubmitting ||
- saveConfigMutation.isLoading ||
- (!dirty && !existingConfigPrompts.hasAccepedDeletingExistingConfig)
- }
- label={'Save Configuration'}
- loading={saveConfigMutation.isLoading}
- />
- </div>
- </Form>
- )}
- </Formik>
- </div>
-
- {existingConfigPrompts.showDeleteExistingConfigModal && (
- <Modal
- onClose={() =>
- setExistingConfigPrompts((prev) => ({
- ...prev,
- showDeleteExistingConfigModal: false,
- }))
- }
- title="Delete Existing Configuration"
- >
- <div className="modal-body">
- <div className="flex flex-col gap-4">
- <p>
- Are you sure you want to delete the existing configuration? <br /> <br />
- <b>Note:</b> This will delete all existing namespaces associated with this
- configuration.
- </p>
- <div className="flex gap-3 mt-4 ">
- <CustomButton
- className="flex-1"
- variant="secondary"
- type="button"
- handleClick={() =>
- setExistingConfigPrompts((prev) => ({
- ...prev,
- showDeleteExistingConfigModal: false,
- }))
- }
- label="Cancel"
- />
- <CustomButton
- type="button"
- isDelete
- handleClick={async () => {
- if (deleteConfigMutation.isLoading) return;
- await deleteConfigMutation.mutateAsync();
- refetchData();
- setExistingConfigPrompts((prev) => ({
- ...prev,
- showDeleteExistingConfigModal: false,
- hasAccepedDeletingExistingConfig: true,
- }));
- }}
- disabled={deleteConfigMutation.isLoading}
- loading={deleteConfigMutation.isLoading}
- label="Delete"
- className="justify-center flex-1"
- />
- </div>
- </div>
- </div>
- </Modal>
- )}
- </Modal>
- </>
- );
-};
-
-export default CustomVectorStorageConfigModal;
diff --git a/packages/app/src/react/features/data-space/pages/DataPage.tsx b/packages/app/src/react/features/data-space/pages/DataPage.tsx
deleted file mode 100644
index 25ad1dbe..00000000
--- a/packages/app/src/react/features/data-space/pages/DataPage.tsx
+++ /dev/null
@@ -1,271 +0,0 @@
-import { DEFAULT_PAGINATION_LIMIT } from '@react/features/data-space/client/dataspace.api-client.service';
-import ConfigureCustomStorageTrigger from '@react/features/data-space/components/configureCustomStorageTrigger';
-import VectorsTable from '@react/features/data-space/components/vectorsTable';
-import AddNamespaceDialog from '@react/features/data-space/dialogs/addNamespace';
-import { RefreshIcon } from '@react/shared/components/svgs';
-import { Input as CustomInput } from '@react/shared/components/ui/input';
-import { Button as CustomButton } from '@react/shared/components/ui/newDesign/button';
-import TableRowSkeleton from '@react/shared/components/ui/table/table.row.skeleton';
-import { useAuthCtx } from '@react/shared/contexts/auth.context';
-import { useScreenSize } from '@react/shared/hooks/useScreenSize';
-import { extractError } from '@react/shared/utils/errors';
-import { SMYTHOS_DOCS_URL } from '@src/shared/constants/general';
-import { ChangeEvent, FC, useCallback, useEffect, useMemo, useState } from 'react';
-import { toast } from 'react-toastify';
-
-/**
- * Type definition for a Namespace entity.
- */
-type Namespace = {
- id: string;
- name: string;
- // Add other properties as needed
-};
-
-const DataPage: FC = () => {
- const [namespaceData, setNamespaceData] = useState<Namespace[]>([]);
- const [addNamespaceLoading, setAddNamespaceLoading] = useState<boolean>(false);
- const [openNamespaceDialog, setOpenNamespaceDialog] = useState<boolean>(false);
- const [namespaceError, setNamespaceError] = useState<boolean | string>(false);
- const [inputValue, setInputValue] = useState<string>('');
- const [loading, setLoading] = useState<boolean>(false);
- const [searchQuery, setSearchQuery] = useState<string>('');
- const [page, setPage] = useState<number>(1);
- const [hasMore, setHasMore] = useState<boolean>(true);
-
- const { hasReadOnlyPageAccess } = useAuthCtx();
- const isReadOnlyAccess: boolean = hasReadOnlyPageAccess('/data');
- const { isSmallScreen } = useScreenSize();
-
- /**
- * Fetches all namespaces from the API and updates the state.
- */
- const fetchAndProcessData = useCallback(async (currentPage: number = 1) => {
- try {
- setLoading(true);
- const response: any = await fetch(
- `/api/page/vectors/vectorsNamespaceList?page=${currentPage}&limit=${DEFAULT_PAGINATION_LIMIT}`,
- ).then((res) => res.json());
- const { namespaces, total } = response;
-
- setNamespaceData(currentPage === 1 ? namespaces : (prev) => [...prev, ...namespaces]);
- setHasMore(namespaces.length === DEFAULT_PAGINATION_LIMIT);
- } catch (error) {
- console.error('Error fetching namespaces:', error);
- toast.error('Failed to fetch namespaces');
- } finally {
- setLoading(false);
- }
- }, []);
-
- useEffect(() => {
- fetchAndProcessData();
- }, [fetchAndProcessData]);
-
- /**
- * Handles the addition of a new namespace.
- * @param useUserCustomStorage - Indicates if custom storage should be used.
- */
- const handleClick = async (useUserCustomStorage: boolean) => {
- setAddNamespaceLoading(true);
- try {
- const data: any = await fetch('/api/page/vectors/namespaces', {
- headers: {
- 'Content-Type': 'application/json',
- },
- method: 'POST',
- body: JSON.stringify({
- name: inputValue,
- useCustomVectorStorage: useUserCustomStorage || false,
- }),
- }).then((res) => res.json());
- const namespace: Namespace = data.namespace;
- setNamespaceData((prev) => [namespace, ...prev]);
- toast.success('Data Space added successfully');
- setAddNamespaceLoading(false);
- setOpenNamespaceDialog(false);
- setInputValue('');
- } catch (error: any) {
- console.error('Error adding namespace:', error);
- setAddNamespaceLoading(false);
- const _errorMessage =
- error.status === 403 && extractError(error) === 'Forbidden'
- ? 'You are not authorized to add data space'
- : extractError(error) || 'An error occurred while adding the data space';
- setNamespaceError(_errorMessage);
- }
- };
-
- /**
- * Handles changes to the input value.
- * @param value - The new input value.
- */
- const handleChange = (value: string) => {
- setInputValue(value);
- setNamespaceError(false);
- };
-
- /**
- * Closes the Add Namespace dialog and resets input.
- */
- const handleClose = () => {
- setOpenNamespaceDialog(false);
- setInputValue('');
- };
-
- /**
- * Handles changes to the search query.
- * @param value - The new search query.
- */
- const handleSearchChange = (value: string) => {
- setSearchQuery(value);
- };
-
- /**
- * Renders skeleton loading rows.
- */
- const renderSkeletonLoading = () => {
- return Array.from({ length: 3 }).map((_, i) => (
- <TableRowSkeleton key={i} className="py-5 my-3" />
- ));
- };
-
- /**
- * Handles actions after a namespace is deleted.
- */
- const handleNamespacesAfterDelete = () => {
- fetchAndProcessData();
- };
-
- /**
- * Loads more namespaces by increasing the display count.
- */
- const handleLoadMore = () => {
- const nextPage = page + 1;
- setPage(nextPage);
- fetchAndProcessData(nextPage);
- };
-
- /**
- * Filters and slices the namespace data based on the search query.
- */
- const filteredNamespaceData: Namespace[] = useMemo(() => {
- return namespaceData.filter((namespace) =>
- namespace.name.toLowerCase().includes(searchQuery.toLowerCase()),
- );
- }, [namespaceData, searchQuery]);
-
- return (
- <div className={`${isSmallScreen ? 'small-screen-sidebar-margin' : ''}`}>
- <div className="flex items-center justify-end flex-wrap md:flex-nowrap pb-6">
- <div className="w-max flex justify-center items-center flex-wrap md:flex-nowrap">
- <div className="flex md:justify-ce items-center flex-wrap md:flex-nowrap gap-2">
- <div className="relative">
- <CustomInput
- isSearch={true}
- placeholder="Search Data Space"
- onChange={(e: ChangeEvent<HTMLInputElement>) => handleSearchChange(e.target.value)}
- value={searchQuery}
- />
- <i className="absolute left-3 top-3 text-gray-400"></i>
- </div>
- {!isReadOnlyAccess && (
- <>
- <ConfigureCustomStorageTrigger />
- {namespaceData.length > 0 && (
- <CustomButton
- handleClick={() => setOpenNamespaceDialog(true)}
- addIcon={true}
- label="Add Data Space"
- dataAttributes={{ 'data-test': 'add-data-space-button' }}
- />
- )}
- </>
- )}
- </div>
- </div>
- </div>
- <div className="bg-white rounded-lg overflow-hidden">
- {filteredNamespaceData.length > 0 && (
- <VectorsTable
- setNamespaceData={setNamespaceData}
- dataArray={filteredNamespaceData}
- handleNamespacesAfterDelete={handleNamespacesAfterDelete}
- />
- )}
- {/* Display message when no namespaces are found after search */}
- {!loading && filteredNamespaceData.length === 0 && (
- <div className="flex justify-center items-start py-16 md:pl-0">
- <div className="max-w-md w-full mx-auto flex flex-col items-center p-4 text-center">
- {namespaceData.length === 0 ? (
- <>
- <h4 className="text-xl md:text-2xl font-medium text-black text-center mb-2">
- Create your first data space
- </h4>
- <p className="mb-8 text-sm md:text-base">
- Use data space to import your external data into SmythOS.
- </p>
- <div className="flex justify-between items-center gap-4 mt-2 w-full flex-col md:flex-row">
- <CustomButton
- handleClick={() => {
- window.open(
- `${SMYTHOS_DOCS_URL}/agent-collaboration/data-pool/data-spaces`,
- '_blank',
- 'noopener,noreferrer',
- );
- }}
- className="flex-1 w-[190px] md:w-auto"
- label={'Learn more'}
- variant="secondary"
- />
- <CustomButton
- handleClick={() => setOpenNamespaceDialog(true)}
- addIcon={true}
- label={'Add Data Space'}
- className="flex-1 w-[190px] md:w-auto"
- />
- </div>
- </>
- ) : (
- <div className="text-center">
- <h4 className="text-xl font-medium text-gray-700 mb-2">
- No matching data spaces found
- </h4>
- <p className="text-gray-600">
- No data spaces match your search query: &quot;{searchQuery}&quot;
- </p>
- </div>
- )}
- </div>
- </div>
- )}
- {loading && renderSkeletonLoading()}
- {!searchQuery && hasMore && (
- <div className="px-6 py-4 text-center border border-solid border-gray-200 rounded-lg text-sm">
- <button
- onClick={handleLoadMore}
- type="button"
- className="text-gray-500 hover:underline flex items-center justify-center mx-auto"
- disabled={loading}
- >
- <RefreshIcon color="text-gray-500" isLoading={loading} />
- <span className="mx-2">Load More</span>
- </button>
- </div>
- )}
- </div>
- <AddNamespaceDialog
- onClose={handleClose}
- handleClick={(useUserCustomStorage: boolean) => handleClick(useUserCustomStorage)}
- disableBtn={inputValue.trim() === '' || addNamespaceLoading}
- open={openNamespaceDialog}
- loading={addNamespaceLoading}
- handleChange={(event: ChangeEvent<HTMLInputElement>) => handleChange(event.target.value)}
- inputValue={inputValue}
- namespaceError={namespaceError}
- />
- </div>
- );
-};
-
-export default DataPage;
diff --git a/packages/app/src/react/features/data-space/pages/DatasourceLibrary.tsx b/packages/app/src/react/features/data-space/pages/DatasourceLibrary.tsx
deleted file mode 100644
index 6ca1ef54..00000000
--- a/packages/app/src/react/features/data-space/pages/DatasourceLibrary.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-import AddDatasourceDialog from '@react/features/data-space/dialogs/addDatasource';
-import HeaderSearch from '@react/shared/components/headerSearch';
-import { useAuthCtx } from '@react/shared/contexts/auth.context';
-import { useScreenSize } from '@react/shared/hooks/useScreenSize';
-import DatasourceTable from '@src/react/features/data-space/components/datasourceTable';
-import { Breadcrumb } from 'flowbite-react';
-import { ChangeEvent, useState } from 'react';
-import { createPortal } from 'react-dom';
-import { HiHome } from 'react-icons/hi';
-import { Link, useParams } from 'react-router-dom';
-
-export default function DatasourceLibrary() {
- const param = useParams();
- const namespaceName = param?.dataspace;
-
- const [isCreateDSDialogOpen, setIsDSDialogOpen] = useState(false);
- const [searchQuery, setSearchQuery] = useState('');
- const { isSmallScreen } = useScreenSize();
-
- const { hasReadOnlyPageAccess } = useAuthCtx();
- const isReadOnlyAccess = hasReadOnlyPageAccess('/data');
-
- const breadcrumb = (
- <Breadcrumb aria-label="Breadcrumb" className="mb-2 sm:mb-0">
- <Breadcrumb.Item icon={HiHome}>
- <Link to="/agents">Home</Link>
- </Breadcrumb.Item>
- <Breadcrumb.Item>
- <Link to={`/data`}>Data Spaces</Link>
- </Breadcrumb.Item>
- <Breadcrumb.Item>{namespaceName}</Breadcrumb.Item>
- </Breadcrumb>
- );
-
- const handleSearchChange = (e: ChangeEvent<HTMLInputElement>) => {
- setSearchQuery(e.target.value);
- };
-
- return (
- <div className={`w-full h-full ${isSmallScreen ? 'small-screen-sidebar-margin' : ''}`}>
- <div className="flex justify-between flex-col md:flex-row items-start md:items-center mb-4">
- {breadcrumb}
- <div className="w-full md:w-auto mt-4 md:mt-0">
- <HeaderSearch
- handleClick={() => setIsDSDialogOpen(true)}
- label="Add Source"
- addIcon
- search
- placeholder="Search"
- isReadOnlyAccess={isReadOnlyAccess}
- handleChange={handleSearchChange}
- />
- </div>
- </div>
-
- <div className="w-full overflow-hidden">
- <div className="w-full overflow-x-auto rounded-lg">
- <DatasourceTable namespaceName={namespaceName} searchQuery={searchQuery} />
- </div>
- </div>
-
- {isCreateDSDialogOpen &&
- createPortal(
- <AddDatasourceDialog
- namespaceName={namespaceName}
- onClose={() => setIsDSDialogOpen(false)}
- />,
- document.getElementById('root') as HTMLElement,
- )}
- </div>
- );
-}
diff --git a/packages/app/src/react/shared/constants/navigation.ts b/packages/app/src/react/shared/constants/navigation.ts
index de462006..3a597878 100644
--- a/packages/app/src/react/shared/constants/navigation.ts
+++ b/packages/app/src/react/shared/constants/navigation.ts
@@ -3,7 +3,6 @@ import { SMYTHOS_DOCS_URL } from '@src/shared/constants/general';
import {
BinaryTreeIcon,
BookIcon,
- DatabaseIcon,
DiscordIcon,
GridIcon,
HomeIcon,
@@ -20,24 +19,24 @@ export type SidebarMenuItem = {
name: string;
icon: React.FC;
visible: boolean | ((ctx: any) => boolean);
+ order?: number;
};
export const getSidebarMenuItems = (): SidebarMenuItem[] => {
let pluginItems = (
plugins.getPluginsByTarget(PluginTarget.SidebarMenuItems, PluginType.Config) as {
- config: any;
+ config: SidebarMenuItem;
}[]
).flatMap((item) => item.config);
return [
- { url: '/agents', name: 'Home', icon: HomeIcon, visible: true },
- { url: '/domains', name: 'Subdomains', icon: BinaryTreeIcon, visible: true },
- { url: '/data/', name: 'Data Pool', icon: DatabaseIcon, visible: true },
- { url: '/analytics', name: 'Analytics', icon: LineChartIcon, visible: true },
- { url: '/vault', name: 'Vault', icon: KeyIcon, visible: true },
- { url: '/templates', name: 'Templates', icon: GridIcon, visible: true },
+ { url: '/agents', name: 'Home', icon: HomeIcon, visible: true, order: 1 },
+ { url: '/domains', name: 'Subdomains', icon: BinaryTreeIcon, visible: true, order: 3 },
+ { url: '/analytics', name: 'Analytics', icon: LineChartIcon, visible: true, order: 4 },
+ { url: '/vault', name: 'Vault', icon: KeyIcon, visible: true, order: 5 },
+ { url: '/templates', name: 'Templates', icon: GridIcon, visible: true, order: 6 },
...pluginItems,
- ];
+ ].sort((a, b) => (a.order || 0) - (b.order || 0));
};
export const bottomLinks = [
diff --git a/packages/app/src/react/shared/types/api-payload.types.ts b/packages/app/src/react/shared/types/api-payload.types.ts
index 4ab78b3e..e221adcd 100644
--- a/packages/app/src/react/shared/types/api-payload.types.ts
+++ b/packages/app/src/react/shared/types/api-payload.types.ts
@@ -39,46 +39,7 @@ export interface UpdateTeamMemberRoleRequest {
export interface PostDomainRequest {
name: string;
}
-export interface SaveCustomVectorStorage {
- projectUrl: string;
- apiKey: string;
- indexName: string;
- environment: string;
-}
-/*
-{
- "jobType": "AGENT_SCHEDULE",
- "name": "Send Message",
- "data": {
- "componentId": "component_1",
- "agentId": "clpc800ik9ti44wpjpitt",
- "body": {
- "foo": "bar"
- }
- },
- "options": {
- "repeat": {
- "patternDetails": {
- "daysOfWeek": [
- 0,
- 1,
- 2,
- 3,
- 4,
- 5,
- 6
- ],
- "repeatEveryUnit": "hour",
- "repeatEvery": 1
- },
- "limit": 10,
- "startDate": "2021-01-01T00:00:00.000Z",
- "endDate": "2021-01-01T00:00:00.000Z"
- }
- }
-}
-*/
export interface CreateAgentScheduledJobRequest {
jobType: 'AGENT_SCHEDULE';
name?: string;
diff --git a/packages/app/src/react/shared/types/api-results.types.ts b/packages/app/src/react/shared/types/api-results.types.ts
index 1cbc7bf3..5d38e223 100644
--- a/packages/app/src/react/shared/types/api-results.types.ts
+++ b/packages/app/src/react/shared/types/api-results.types.ts
@@ -35,17 +35,6 @@ export interface Invitation {
teamRole: TeamRole;
}
-export interface VectorsCustomStorage {
- isConfigured: boolean;
- storage?: {
- projectId: string;
- apiKey: string;
- indexName: string;
- environment: string;
- projectUrl: string;
- } | null;
-}
-
// should not be here
export interface SmythAPIError {
error: { code: string; message: string; errKey?: string };
@@ -178,33 +167,6 @@ export type AgentScheduledJobLog = {
sessionTag?: string;
} | null;
-export interface Datasource {
- updatedAt: string;
- createdAt: string;
- id: string;
- name: string;
- type: 'SITEMAP' | 'WEBPAGE' | 'WORD' | 'TRANSCRIPT' | 'PDF';
- url: string;
-}
-
-export type DatasourceStatus = {
- status: 'done' | 'pending' | 'indexing' | 'failed-retry' | 'failed' | 'done-duplicate';
- statusData: {
- status: 'done' | 'pending' | 'indexing' | 'failed-retry' | 'failed' | 'done-duplicate';
- lastCrawledAt: string;
- };
-};
-
-export type DatasourceSitemapStatus = {
- status: {
- total: number;
- completed: number;
- pending: number;
- failed: number;
- nextCrawlAt?: string;
- };
-};
-
export interface BulkAgentCallJob {
data: string;
status: 'pending' | 'completed' | 'failed';
diff --git a/packages/app/src/react/shared/utils/utils.ts b/packages/app/src/react/shared/utils/utils.ts
index 1711be11..580fb431 100644
--- a/packages/app/src/react/shared/utils/utils.ts
+++ b/packages/app/src/react/shared/utils/utils.ts
@@ -64,23 +64,6 @@ export const validateDomains = (domains: string[]): boolean => {
}
return true;
};
-export const calculateCompletionPercentage = (stats) => {
- const completed = stats?.statusData?.sitemapStatus?.res?.status?.completed || 0;
- const total = stats?.statusData?.sitemapStatus?.res?.status?.total || 0;
- return Math.round((completed / total) * 100);
-};
-
-export const fetchStatusData = async (datasourceId) => {
- const statusDataResponse = await fetch(`/api/page/vectors/datasourceStatus?id=${datasourceId}`);
- const statusData = await statusDataResponse.json();
- return statusData;
-};
-
-export const fetchSitemapStatus = async (datasourceID) => {
- const sitemapStatusResponse = await fetch(`/api/page/vectors/sitemapStatus?id=${datasourceID}`);
- const sitemapData = await sitemapStatusResponse.json();
- return sitemapData;
-};
export interface LocalStorageArrayRetriever {
get: (childKey: string) => any;
@@ -131,4 +114,3 @@ export const createLocalStorageArrayRetriever = (parentKey: string): LocalStorag
export function cn(...classes: any[]): string {
return classes.filter(Boolean).join(' ');
}
-
diff --git a/packages/app/tsconfig.json b/packages/app/tsconfig.json
index 92790332..6f0ba0d8 100644
--- a/packages/app/tsconfig.json
+++ b/packages/app/tsconfig.json
@@ -23,8 +23,6 @@
"src/**/*",
"node_modules/@types",
"eslint.config.js",
- "../../../src/react/features/onboarding/constants",
- "../../../src/react/features/onboarding/utils"
- ],
+ ],
"exclude": ["node_modules"]
}