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.

Feat/connections credentials (#363)

Ahmed Essam69faeb2c45f3
diff --git a/packages/app/src/backend/config.ts b/packages/app/src/backend/config.ts
index c378c30e..cbd0642f 100644
--- a/packages/app/src/backend/config.ts
+++ b/packages/app/src/backend/config.ts
@@ -57,6 +57,7 @@ const config = {
PROD_AGENT_DOMAIN: process.env.PROD_AGENT_DOMAIN || 'agent.pstage.smyth.ai',
REDIS_HOST: process.env.REDIS_HOST,
REDIS_PORT: process.env.REDIS_PORT,
+ SMYTHOS_EDITION: process.env.SMYTHOS_EDITION,
AWS_ACCESS_KEY_ID: process.env.AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY: process.env.AWS_SECRET_ACCESS_KEY,
diff --git a/packages/app/src/backend/routes/api/component/DataSourceIndexer.ts b/packages/app/src/backend/routes/api/component/DataSourceIndexer.ts
index 0a338672..6299a6f9 100644
--- a/packages/app/src/backend/routes/api/component/DataSourceIndexer.ts
+++ b/packages/app/src/backend/routes/api/component/DataSourceIndexer.ts
@@ -1,8 +1,23 @@
+import axios from 'axios';
import { Router } from 'express';
+import config from '../../../config';
import { authHeaders, smythAPIReq } from '../../../utils';
const router = Router();
+const getAuthHeaders = (req: any) => {
+ const headers: Record<string, string> = {};
+
+ if (req.user?.accessToken) {
+ headers['Authorization'] = `Bearer ${req.user.accessToken}`;
+ }
+
+ // Add debug header for routing through debugger server
+ headers['x-smyth-debug'] = 'true';
+
+ return headers;
+};
+
router.get('/namespaces', async (req, res) => {
try {
const result = await smythAPIReq.get('/vectors/namespaces', await authHeaders(req));
@@ -13,4 +28,28 @@ router.get('/namespaces', async (req, res) => {
}
});
+router.get('/v2/namespaces', async (req, res) => {
+ const url = `${config.env.API_SERVER}/user/data-pools/namespaces`;
+
+ try {
+ const result = await axios.get(url, {
+ headers: getAuthHeaders(req),
+ });
+
+ return res.json(result.data.namespaces);
+ } catch (error) {
+ console.error('Error fetching namespaces:', error?.response?.data || error.message);
+
+ const errorData = error?.response?.data;
+
+ if (errorData && typeof errorData === 'object') {
+ return res.status(error?.response?.status || 500).json(errorData);
+ }
+
+ return res.status(error?.response?.status || 500).json({
+ error: errorData || 'Failed to fetch namespaces',
+ });
+ }
+});
+
export default router;
diff --git a/packages/app/src/backend/routes/api/credentials/dependencies/CredentialDependency.ts b/packages/app/src/backend/routes/api/credentials/dependencies/CredentialDependency.ts
new file mode 100644
index 00000000..4ac675a8
--- /dev/null
+++ b/packages/app/src/backend/routes/api/credentials/dependencies/CredentialDependency.ts
@@ -0,0 +1,15 @@
+export interface IDependencyResult {
+ errors: string[];
+ warnings: string[];
+}
+
+export abstract class CredentialDependency {
+ constructor(
+ protected readonly req: any,
+ protected readonly credentialId: string,
+ ) {}
+
+ public abstract checkDependency(): Promise<IDependencyResult>;
+ public abstract deleteDependencies(): Promise<void>;
+ public abstract isGroupMatch(credentialGroup: string): boolean;
+}
diff --git a/packages/app/src/backend/routes/api/credentials/dependencies/NamespacesDependency.ts b/packages/app/src/backend/routes/api/credentials/dependencies/NamespacesDependency.ts
new file mode 100644
index 00000000..59f89e2c
--- /dev/null
+++ b/packages/app/src/backend/routes/api/credentials/dependencies/NamespacesDependency.ts
@@ -0,0 +1,66 @@
+import config from '@src/backend/config';
+import axios from 'axios';
+import { CredentialDependency, IDependencyResult } from './CredentialDependency';
+
+export class NamespacesDependency extends CredentialDependency {
+ private state: IDependencyResult = {
+ errors: [],
+ warnings: [],
+ };
+ constructor(req: any, credentialId: string) {
+ super(req, credentialId);
+ }
+
+ async checkDependency(): Promise<IDependencyResult> {
+ // get namespaces that use this credential
+ let namespaces: any[] = [];
+ try {
+ const url = `${config.env.API_SERVER}/user/data-pools/namespaces`;
+
+ const res = await axios.get(url, {
+ headers: await this.getAuthHeaders(this.req),
+ });
+ namespaces = res.data.namespaces;
+ } catch (error: any) {
+ throw new Error(error?.response?.data?.message || 'Failed to get namespaces');
+ }
+
+ const linkedNamespaces = namespaces.filter(
+ (namespace: any) => namespace.credentialId === this.credentialId,
+ );
+
+ if (linkedNamespaces.length > 0) {
+ this.state.warnings.push(
+ `This credential is linked to ${linkedNamespaces.length} namespaces`,
+ );
+ }
+
+ return this.state;
+ }
+
+ async deleteDependencies(): Promise<void> {
+ throw new Error('Not implemented');
+ }
+
+ private async getAuthHeaders(req: any) {
+ const headers: Record<string, string> = {};
+
+ if (req.user?.accessToken) {
+ headers['Authorization'] = `Bearer ${req.user.accessToken}`;
+ }
+
+ console.log('headers: x-smyth-team-id', req.headers['x-smyth-team-id']);
+ if (req.headers['x-smyth-team-id']) {
+ headers['x-smyth-team-id'] = req.headers['x-smyth-team-id'];
+ }
+
+ // Add debug header for routing through debugger server
+ headers['x-smyth-debug'] = 'true';
+
+ return headers;
+ }
+
+ isGroupMatch(credGroup: string) {
+ return credGroup === 'vector_db_creds';
+ }
+}
diff --git a/packages/app/src/backend/routes/api/credentials/dependencies/index.ts b/packages/app/src/backend/routes/api/credentials/dependencies/index.ts
new file mode 100644
index 00000000..1dedb3da
--- /dev/null
+++ b/packages/app/src/backend/routes/api/credentials/dependencies/index.ts
@@ -0,0 +1,42 @@
+import { CredentialDependency, type IDependencyResult } from './CredentialDependency';
+import { NamespacesDependency } from './NamespacesDependency';
+
+// Re-export for convenience
+export { CredentialDependency, IDependencyResult };
+
+export class CredentialDependenciesChecker {
+ private dependencies: CredentialDependency[] = [];
+
+ constructor(
+ private readonly req: any,
+ private readonly credentialId: string,
+ private readonly credentialGroup: string,
+ ) {
+ this.dependencies = [this.initIfMatch(NamespacesDependency)].filter(Boolean);
+ }
+
+ async checkDependencies(): Promise<IDependencyResult> {
+ const result: IDependencyResult = {
+ errors: [],
+ warnings: [],
+ };
+
+ for (const dependency of this.dependencies) {
+ const dependencyResult = await dependency.checkDependency();
+ result.errors.push(...dependencyResult.errors);
+ result.warnings.push(...dependencyResult.warnings);
+ }
+
+ return result;
+ }
+
+ private initIfMatch(
+ DependencyClass: new (req: any, credentialId: string) => CredentialDependency,
+ ): CredentialDependency | null {
+ const instance = new DependencyClass(this.req, this.credentialId);
+ if (instance.isGroupMatch(this.credentialGroup)) {
+ return instance;
+ }
+ return null;
+ }
+}
diff --git a/packages/app/src/backend/routes/api/credentials/router.ts b/packages/app/src/backend/routes/api/credentials/router.ts
new file mode 100644
index 00000000..e887183b
--- /dev/null
+++ b/packages/app/src/backend/routes/api/credentials/router.ts
@@ -0,0 +1,393 @@
+/**
+ * Credentials Router
+ *
+ * Handles CRUD operations for team credentials (vector databases, etc.)
+ * Credentials are stored in team settings with groups for organization
+ *
+ * Structure:
+ * - group: Category (e.g., 'vector_database')
+ * - settingKey: Unique credential ID
+ * - settingValue: JSON string containing { provider, credentials, name }
+ */
+
+import axios from 'axios';
+import express, { Request, Response } from 'express';
+import config from '../../../config';
+import { includeTeamDetails } from '../../../middlewares/auth.mw';
+import { authHeaders } from '../../../utils/api.utils';
+import { CredentialDependenciesChecker } from './dependencies';
+import {
+ deleteVaultKeysFromCredentials,
+ resolveVaultKeys,
+ sanitizeCredentials,
+ storeSensitiveFieldsInVault,
+} from './vault-helpers';
+
+export const credentialsRouter = express.Router();
+
+const smythAPIBaseUrl = `${config.env.SMYTH_API_BASE_URL}/v1`;
+
+/**
+ * Get all credentials for a specific group
+ * GET /api/credentials?group=vector_database
+ */
+credentialsRouter.get('/', includeTeamDetails, async (req: Request, res: Response) => {
+ const group = req.query.group as string;
+
+ if (!group) {
+ return res.status(400).json({
+ success: false,
+ error: 'Group parameter is required',
+ });
+ }
+
+ try {
+ const response = await axios.get(`${smythAPIBaseUrl}/teams/settings`, {
+ params: { group },
+ ...(await authHeaders(req)),
+ });
+
+ // Parse the settings response - middleware returns array of settings
+ const settingsArray = response.data?.data || response.data?.settings || [];
+
+ // If it's an object instead of array, convert to array
+ let settingsList: Array<{ settingKey: string; settingValue: string }> = [];
+ if (Array.isArray(settingsArray)) {
+ settingsList = settingsArray;
+ } else if (typeof settingsArray === 'object') {
+ // If it's an object, convert to array format
+ settingsList = Object.entries(settingsArray).map(([key, value]: [string, any]) => ({
+ settingKey: key,
+ settingValue: typeof value === 'object' ? JSON.stringify(value) : value,
+ }));
+ }
+
+ const credentials = settingsList
+ .map((setting: { settingKey: string; settingValue: string }) => {
+ try {
+ const parsedValue =
+ typeof setting.settingValue === 'string'
+ ? JSON.parse(setting.settingValue)
+ : setting.settingValue;
+
+ // Sanitize credentials to hide vault key references
+ const sanitizedCredentials = parsedValue.credentials
+ ? sanitizeCredentials(parsedValue.credentials)
+ : {};
+
+ return {
+ id: setting.settingKey,
+ ...parsedValue,
+ credentials: sanitizedCredentials,
+ };
+ } catch (error) {
+ console.error(`Error parsing credential ${setting.settingKey}:`, error);
+ return null;
+ }
+ })
+ .filter(Boolean);
+
+ res.json({
+ success: true,
+ data: credentials,
+ });
+ } catch (error: any) {
+ console.error('Error fetching credentials:', error?.message);
+ console.error('Full error:', error?.response?.data);
+ res.status(error?.response?.status || 500).json({
+ success: false,
+ error: error?.response?.data?.message || 'Failed to fetch credentials',
+ });
+ }
+});
+
+/**
+ * Get a specific credential by ID
+ * GET /api/credentials/:id?group=vector_database&resolveVaultKeys=true
+ */
+credentialsRouter.get('/:id', includeTeamDetails, async (req: Request, res: Response) => {
+ const { id } = req.params;
+ const group = req.query.group as string;
+ const shouldResolveVaultKeys = req.query.resolveVaultKeys === 'true';
+
+ if (!group) {
+ return res.status(400).json({
+ success: false,
+ error: 'Group parameter is required',
+ });
+ }
+
+ try {
+ const response = await axios.get(`${smythAPIBaseUrl}/teams/settings/${id}`, {
+ params: { group },
+ ...(await authHeaders(req)),
+ });
+
+ const settingValue = response.data?.setting?.settingValue;
+ if (!settingValue) {
+ return res.status(404).json({
+ success: false,
+ error: 'Credential not found',
+ });
+ }
+
+ const credential = typeof settingValue === 'string' ? JSON.parse(settingValue) : settingValue;
+
+ // Resolve vault keys if requested (for editing)
+ let credentials = credential.credentials || {};
+ if (shouldResolveVaultKeys) {
+ credentials = await resolveVaultKeys(credentials, req);
+ } else {
+ credentials = sanitizeCredentials(credentials);
+ }
+
+ res.json({
+ success: true,
+ data: {
+ id,
+ ...credential,
+ credentials,
+ },
+ });
+ } catch (error: any) {
+ if (error?.response?.status === 404) {
+ return res.status(404).json({
+ success: false,
+ error: 'Credential not found',
+ });
+ }
+
+ console.error('Error fetching credential:', error?.message);
+ res.status(error?.response?.status || 500).json({
+ success: false,
+ error: error?.response?.data?.message || 'Failed to fetch credential',
+ });
+ }
+});
+
+/**
+ * Create a new credential
+ * POST /api/credentials
+ * Body: { group, name, provider, credentials: { fieldName: { value, sensitive }, ... } }
+ */
+credentialsRouter.post('/', includeTeamDetails, async (req: Request, res: Response) => {
+ const { group, name, provider, credentials } = req.body;
+
+ // Validation
+ if (!group || !name || !provider || !credentials) {
+ return res.status(400).json({
+ success: false,
+ error: 'Missing required fields: group, name, provider, credentials',
+ });
+ }
+
+ try {
+ // Generate unique ID for the credential
+ const credentialId = `${group}@cred_${Math.random().toString(36).substring(2, 9)}`;
+
+ // Store sensitive fields in vault and get transformed credentials
+ const transformedCredentials = await storeSensitiveFieldsInVault(
+ credentials,
+ credentialId,
+ req,
+ );
+
+ // Prepare credential data
+ const credentialData = {
+ name,
+ provider,
+ credentials: transformedCredentials,
+ group,
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ };
+
+ // Save to team settings
+ await axios.put(
+ `${smythAPIBaseUrl}/teams/settings`,
+ {
+ settingKey: credentialId,
+ settingValue: JSON.stringify(credentialData),
+ group,
+ },
+ await authHeaders(req),
+ );
+
+ // Return sanitized credentials (with [REDACTED] for sensitive fields)
+ const sanitizedCredentials = sanitizeCredentials(transformedCredentials);
+
+ res.status(201).json({
+ success: true,
+ data: {
+ id: credentialId,
+ name,
+ provider,
+ credentials: sanitizedCredentials,
+ group,
+ createdAt: credentialData.createdAt,
+ updatedAt: credentialData.updatedAt,
+ },
+ message: 'Credential created successfully',
+ });
+ } catch (error: any) {
+ console.error('Error creating credential:', error?.message);
+ res.status(error?.response?.status || 500).json({
+ success: false,
+ error: error?.response?.data?.message || 'Failed to create credential',
+ });
+ }
+});
+
+/**
+ * Update an existing credential
+ * PUT /api/credentials/:id
+ * Body: { group, name, provider, credentials: { fieldName: { value, sensitive }, ... } }
+ */
+credentialsRouter.put('/:id', includeTeamDetails, async (req: Request, res: Response) => {
+ const { id } = req.params;
+ const { group, name, provider, credentials } = req.body;
+
+ // Validation
+ if (!group || !name || !provider || !credentials) {
+ return res.status(400).json({
+ success: false,
+ error: 'Missing required fields: group, name, provider, credentials',
+ });
+ }
+
+ try {
+ // Fetch existing credential to preserve createdAt
+ let createdAt: string | undefined;
+ try {
+ const existing = await axios.get(`${smythAPIBaseUrl}/teams/settings/${id}`, {
+ params: { group },
+ ...(await authHeaders(req)),
+ });
+ const existingData = JSON.parse(existing.data?.setting?.settingValue || '{}');
+ createdAt = existingData.createdAt;
+ } catch (error) {
+ // If not found, we'll create it as a new credential
+ createdAt = new Date().toISOString();
+ }
+
+ // Store sensitive fields in vault and get transformed credentials
+ const transformedCredentials = await storeSensitiveFieldsInVault(credentials, id, req);
+
+ // Prepare updated credential data
+ const credentialData = {
+ name,
+ provider,
+ credentials: transformedCredentials,
+ group,
+ createdAt: createdAt || new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ };
+
+ // Update team settings
+ await axios.put(
+ `${smythAPIBaseUrl}/teams/settings`,
+ {
+ settingKey: id,
+ settingValue: JSON.stringify(credentialData),
+ group,
+ },
+ await authHeaders(req),
+ );
+
+ // Return sanitized credentials (with [REDACTED] for sensitive fields)
+ const sanitizedCredentials = sanitizeCredentials(transformedCredentials);
+
+ res.json({
+ success: true,
+ data: {
+ id,
+ name,
+ provider,
+ credentials: sanitizedCredentials,
+ group,
+ createdAt: credentialData.createdAt,
+ updatedAt: credentialData.updatedAt,
+ },
+ message: 'Credential updated successfully',
+ });
+ } catch (error: any) {
+ console.error('Error updating credential:', error?.message);
+ res.status(error?.response?.status || 500).json({
+ success: false,
+ error: error?.response?.data?.message || 'Failed to update credential',
+ });
+ }
+});
+
+/**
+ * Delete a credential
+ * DELETE /api/credentials/:id?group=vector_database
+ */
+credentialsRouter.delete('/:id', includeTeamDetails, async (req: Request, res: Response) => {
+ const { id } = req.params;
+ const group = req.query.group as string;
+ const consentedWarnings = req.query.consentedWarnings as string;
+
+ if (!group) {
+ return res.status(400).json({
+ success: false,
+ error: 'Group parameter is required',
+ });
+ }
+
+ try {
+ // Fetch existing credential to clean up vault keys
+ const existing = await axios.get(`${smythAPIBaseUrl}/teams/settings/${id}`, {
+ params: { group },
+ ...(await authHeaders(req)),
+ });
+
+ const existingData = JSON.parse(existing.data?.setting?.settingValue || '{}');
+ if (!existingData.credentials) {
+ return res.status(400).json({
+ success: false,
+ error: 'Credential not found',
+ });
+ }
+
+ // check if there are dependencies on this credential
+ const dependenciesChecker = new CredentialDependenciesChecker(req, id, group);
+ const dependenciesResult = await dependenciesChecker.checkDependencies();
+
+ if (dependenciesResult.errors.length > 0) {
+ return res.status(400).json({
+ success: false,
+ error: dependenciesResult.errors.join('\n'),
+ });
+ } else if (consentedWarnings != 'true' && dependenciesResult.warnings.length > 0) {
+ return res.status(200).json({
+ success: false,
+ warnings: dependenciesResult.warnings,
+ });
+ }
+
+ // Delete associated vault keys
+ await deleteVaultKeysFromCredentials(existingData.credentials, req?._team?.id, req).catch(
+ (error) => {
+ console.warn('[Credentials] Could not delete vault keys:', error);
+ },
+ );
+
+ // Delete the credential from team settings
+ await axios.delete(`${smythAPIBaseUrl}/teams/settings/${id}`, {
+ params: { group },
+ ...(await authHeaders(req)),
+ });
+
+ res.json({
+ success: true,
+ message: 'Credential deleted successfully',
+ });
+ } catch (error: any) {
+ console.error('Error deleting credential:', error?.message);
+ res.status(error?.response?.status || 500).json({
+ success: false,
+ error: error?.response?.data?.message || 'Failed to delete credential',
+ });
+ }
+});
diff --git a/packages/app/src/backend/routes/api/credentials/vault-helpers.ts b/packages/app/src/backend/routes/api/credentials/vault-helpers.ts
new file mode 100644
index 00000000..1c33905b
--- /dev/null
+++ b/packages/app/src/backend/routes/api/credentials/vault-helpers.ts
@@ -0,0 +1,208 @@
+/**
+ * Vault Helpers for Credentials
+ *
+ * Utilities for storing and resolving sensitive credential fields in vault.
+ * Based on the OAuth vault pattern from vault.ts
+ */
+
+import { VAULT_SCOPE_CREDENTIALS } from '@src/shared/constants/general';
+import { Request } from 'express';
+import Vault from '../../../services/SmythVault.class';
+
+const vault = new Vault();
+
+/**
+ * Pattern to identify vault keys in credential values
+ * Format: {{KEY(keyName)}}
+ */
+const VAULT_KEY_PATTERN = /{{KEY\((.*?)\)}}/;
+
+/**
+ * Checks if a value is a vault key reference
+ */
+export function isVaultKey(value: string): string | null {
+ if (typeof value !== 'string') return null;
+ const match = value.match(VAULT_KEY_PATTERN);
+ return match ? match[1] : null;
+}
+
+/**
+ * Checks if credentials object contains any vault key references
+ */
+export function hasVaultKeys(credentials: Record<string, any>): boolean {
+ return Object.values(credentials).some((value) => {
+ if (typeof value === 'string') {
+ return isVaultKey(value) !== null;
+ }
+ return false;
+ });
+}
+
+/**
+ * Stores sensitive credential fields in vault
+ *
+ * @param credentials - Credentials object with { key: { value, sensitive } } structure
+ * @param credentialId - Unique identifier for the credential
+ * @param req - Express request object
+ * @returns Transformed credentials with vault key references for sensitive fields
+ */
+export async function storeSensitiveFieldsInVault(
+ credentials: Record<string, { value: string; sensitive: boolean }>,
+ credentialId: string,
+ req: Request
+): Promise<Record<string, string>> {
+ const transformedCredentials: Record<string, string> = {};
+ const storePromises: Array<Promise<any>> = [];
+
+ for (const [fieldKey, fieldData] of Object.entries(credentials)) {
+ const { value, sensitive } = fieldData;
+
+ if (sensitive && value) {
+ // Store sensitive field in vault
+ const vaultKeyName = `${credentialId}_${fieldKey}`;
+ const keyData = {
+ team: req?._team?.id,
+ owner: req?._user?.email,
+ name: vaultKeyName,
+ key: value,
+ scope: [VAULT_SCOPE_CREDENTIALS],
+ };
+
+ const storePromise = vault.set({
+ req,
+ data: keyData,
+ keyId: vaultKeyName,
+ }).then((result) => {
+ if (!result?.success) {
+ console.error(`Failed to store sensitive field ${fieldKey} in vault:`, result?.error);
+ throw new Error(`Failed to store sensitive field ${fieldKey} in vault: ${result?.error}`);
+ }
+ return result;
+ });
+
+ storePromises.push(storePromise);
+ transformedCredentials[fieldKey] = `{{KEY(${vaultKeyName})}}`;
+ } else {
+ // Non-sensitive field - store as-is
+ transformedCredentials[fieldKey] = value;
+ }
+ }
+
+ try {
+ await Promise.all(storePromises);
+ } catch (error) {
+ console.error('Failed to store sensitive fields in vault:', error);
+ throw new Error('Failed to store sensitive fields in vault');
+ }
+
+ return transformedCredentials;
+}
+
+/**
+ * Deletes vault keys associated with credential fields
+ *
+ * @param credentials - Credentials object that may contain vault key references
+ * @param teamId - Team ID
+ * @param req - Express request object
+ */
+export async function deleteVaultKeysFromCredentials(
+ credentials: Record<string, any>,
+ teamId: string,
+ req: Request
+): Promise<void> {
+ const vaultKeys: string[] = [];
+
+ // Find all vault key references in credentials
+ for (const value of Object.values(credentials)) {
+ if (typeof value === 'string') {
+ const keyName = isVaultKey(value);
+ if (keyName) {
+ vaultKeys.push(keyName);
+ }
+ }
+ }
+
+ if (vaultKeys.length === 0) {
+ return;
+ }
+
+ console.log('[Credentials] Deleting vault keys:', vaultKeys);
+
+ await Promise.all(
+ vaultKeys.map(async (keyName) => {
+ const result = await vault.delete(keyName, teamId, req);
+ console.log(`[Credentials] Deleted vault key ${keyName}:`, result);
+ })
+ );
+}
+
+/**
+ * Resolves vault key references in credentials to actual values
+ * Used when editing credentials to show actual values to the user
+ *
+ * @param credentials - Credentials object that may contain vault key references
+ * @param req - Express request object
+ * @returns Credentials with resolved values
+ */
+export async function resolveVaultKeys(
+ credentials: Record<string, string>,
+ req: Request
+): Promise<Record<string, string>> {
+ const resolvedCredentials: Record<string, string> = {};
+ const resolvePromises: Array<Promise<void>> = [];
+
+ for (const [fieldKey, fieldValue] of Object.entries(credentials)) {
+ const keyName = isVaultKey(fieldValue);
+
+ if (keyName) {
+ // This is a vault key reference - resolve it
+ const resolvePromise = (async () => {
+ try {
+ const teamId = req?._team?.id;
+ const vaultValue = await vault.get({ team: teamId, keyName }, req);
+
+ if (vaultValue && vaultValue.key) {
+ resolvedCredentials[fieldKey] = vaultValue.key;
+ } else {
+ // If resolution fails, keep the placeholder
+ resolvedCredentials[fieldKey] = '[VAULT KEY NOT FOUND]';
+ console.warn(`[Credentials] Failed to resolve vault key ${keyName}`);
+ }
+ } catch (error) {
+ console.error(`[Credentials] Error resolving vault key ${keyName}:`, error);
+ resolvedCredentials[fieldKey] = '[VAULT KEY ERROR]';
+ }
+ })();
+
+ resolvePromises.push(resolvePromise);
+ } else {
+ // Not a vault key - use as-is
+ resolvedCredentials[fieldKey] = fieldValue;
+ }
+ }
+
+ await Promise.all(resolvePromises);
+ return resolvedCredentials;
+}
+
+/**
+ * Sanitizes credentials by replacing sensitive fields with placeholders
+ * Used when returning credentials to frontend (except when editing)
+ *
+ * @param credentials - Credentials object
+ * @returns Sanitized credentials with [REDACTED] for vault key references
+ */
+export function sanitizeCredentials(credentials: Record<string, string>): Record<string, string> {
+ const sanitized: Record<string, string> = {};
+
+ for (const [fieldKey, fieldValue] of Object.entries(credentials)) {
+ if (isVaultKey(fieldValue)) {
+ sanitized[fieldKey] = '[REDACTED]';
+ } else {
+ sanitized[fieldKey] = fieldValue;
+ }
+ }
+
+ return sanitized;
+}
+
diff --git a/packages/app/src/backend/routes/api/page/datapool.ts b/packages/app/src/backend/routes/api/page/datapool.ts
new file mode 100644
index 00000000..ca823457
--- /dev/null
+++ b/packages/app/src/backend/routes/api/page/datapool.ts
@@ -0,0 +1,211 @@
+/**
+ * Data Pool API Routes
+ *
+ * Proxies requests to API_SERVER/user/datapools/*
+ */
+
+import axios, { AxiosError } from 'axios';
+import express from 'express';
+import FormData from 'form-data';
+import multer from 'multer';
+import config from '../../../config';
+
+const router = express.Router();
+
+// Configure multer for file uploads (memory storage)
+const storage = multer.memoryStorage();
+const upload = multer({
+ storage,
+ limits: {
+ fileSize: 10 * 1024 * 1024, // 10MB max file size
+ },
+});
+
+/**
+ * Get auth headers from request
+ */
+const getAuthHeaders = (req: any) => {
+ const headers: Record<string, string> = {};
+
+ if (req.user?.accessToken) {
+ headers['Authorization'] = `Bearer ${req.user.accessToken}`;
+ }
+
+ console.log('headers: x-smyth-team-id', req.headers['x-smyth-team-id']);
+ if (req.headers['x-smyth-team-id']) {
+ headers['x-smyth-team-id'] = req.headers['x-smyth-team-id'];
+ }
+
+ // Add debug header for routing through debugger server
+ headers['x-smyth-debug'] = 'true';
+
+ return headers;
+};
+
+/**
+ * List all namespaces with pagination
+ * GET /api/page/datapool/namespaces
+ */
+router.get('/namespaces', async (req, res) => {
+ try {
+ const { page, limit } = req.query;
+ const url = `${config.env.API_SERVER}/user/data-pools/namespaces`;
+
+ const result = await axios.get(url, {
+ params: { page, limit },
+ headers: getAuthHeaders(req),
+ });
+
+ return res.json(result.data);
+ } catch (error: unknown) {
+ const axiosError = error as AxiosError;
+ res.status(500).json(axiosError?.response?.data);
+ }
+});
+
+/**
+ * Create a new namespace
+ * POST /api/page/datapool/namespaces
+ */
+router.post('/namespaces', async (req, res) => {
+ try {
+ const url = `${config.env.API_SERVER}/user/data-pools/namespaces`;
+
+ const result = await axios.post(url, req.body, {
+ headers: getAuthHeaders(req),
+ });
+
+ return res.json(result.data);
+ } catch (error: unknown) {
+ const axiosError = error as AxiosError;
+ res.status(500).json(axiosError?.response?.data);
+ }
+});
+
+/**
+ * Delete a namespace
+ * DELETE /api/page/datapool/namespaces/:namespaceId
+ */
+router.delete('/namespaces/:label', async (req, res) => {
+ try {
+ const { label } = req.params;
+ const url = `${config.env.API_SERVER}/user/data-pools/namespaces/${label}`;
+
+ const result = await axios.delete(url, {
+ headers: getAuthHeaders(req),
+ });
+
+ return res.json(result.data);
+ } catch (error: unknown) {
+ const axiosError = error as AxiosError;
+ res.status(500).json(axiosError?.response?.data);
+ }
+});
+
+/**
+ * List all available embedding models
+ * GET /api/page/datapool/embeddings/models
+ */
+router.get('/embeddings/models', async (req, res) => {
+ try {
+ const url = `${config.env.API_SERVER}/user/data-pools/embeddings/models`;
+
+ const result = await axios.get(url, {
+ headers: getAuthHeaders(req),
+ });
+
+ return res.json(result.data);
+ } catch (error: unknown) {
+ const axiosError = error as AxiosError;
+ res.status(500).json(axiosError?.response?.data);
+ }
+});
+
+/**
+ * List all datasources for a namespace
+ * GET /api/page/datapool/namespaces/:namespaceLabel/datasources
+ */
+router.get('/namespaces/:namespaceLabel/datasources', async (req, res) => {
+ try {
+ const { namespaceLabel } = req.params;
+ const url = `${config.env.API_SERVER}/user/data-pools/namespaces/${encodeURIComponent(namespaceLabel)}/datasources`;
+
+ const result = await axios.get(url, {
+ headers: getAuthHeaders(req),
+ });
+
+ return res.json(result.data);
+ } catch (error: unknown) {
+ const axiosError = error as AxiosError;
+ res.status(500).json(axiosError?.response?.data);
+ }
+});
+
+/**
+ * Create a new datasource
+ * POST /api/page/datapool/namespaces/:namespaceLabel/datasources
+ */
+router.post('/namespaces/:namespaceLabel/datasources', upload.single('file'), async (req, res) => {
+ try {
+ const { namespaceLabel } = req.params;
+ const url = `${config.env.API_SERVER}/user/data-pools/namespaces/${encodeURIComponent(namespaceLabel)}/datasources`;
+
+ // Create FormData to forward the file
+ const formData = new FormData();
+ formData.append('datasourceLabel', req.body.datasourceLabel);
+
+ // Add optional chunking parameters
+ if (req.body.chunkSize) {
+ formData.append('chunkSize', req.body.chunkSize);
+ }
+ if (req.body.chunkOverlap) {
+ formData.append('chunkOverlap', req.body.chunkOverlap);
+ }
+
+ // Add optional metadata
+ if (req.body.metadata) {
+ formData.append('metadata', req.body.metadata);
+ }
+
+ if (req.file) {
+ formData.append('file', req.file.buffer, {
+ filename: req.file.originalname,
+ contentType: req.file.mimetype,
+ });
+ }
+
+ const result = await axios.post(url, formData, {
+ headers: {
+ ...getAuthHeaders(req),
+ ...formData.getHeaders(),
+ },
+ });
+
+ return res.json(result.data);
+ } catch (error: unknown) {
+ const axiosError = error as AxiosError;
+ res.status(500).json(axiosError?.response?.data);
+ }
+});
+
+/**
+ * Delete a datasource
+ * DELETE /api/page/datapool/namespaces/:namespaceLabel/datasources/:datasourceId
+ */
+router.delete('/namespaces/:namespaceLabel/datasources/:datasourceId', async (req, res) => {
+ try {
+ const { namespaceLabel, datasourceId } = req.params;
+ const url = `${config.env.API_SERVER}/user/data-pools/namespaces/${encodeURIComponent(namespaceLabel)}/datasources/${encodeURIComponent(datasourceId)}`;
+
+ const result = await axios.delete(url, {
+ headers: getAuthHeaders(req),
+ });
+
+ return res.json(result.data);
+ } catch (error: unknown) {
+ const axiosError = error as AxiosError;
+ res.status(500).json(axiosError?.response?.data);
+ }
+});
+
+export default router;
diff --git a/packages/app/src/backend/routes/api/page/index.ts b/packages/app/src/backend/routes/api/page/index.ts
index 8a238732..e09d8f5a 100644
--- a/packages/app/src/backend/routes/api/page/index.ts
+++ b/packages/app/src/backend/routes/api/page/index.ts
@@ -4,6 +4,7 @@ import agents from './agents';
import builder from './builder';
import { chatRouter } from './chat';
import collection from './collection';
+import datapool from './datapool';
import { onboardRouter } from './onboard';
import teams from './teams';
import user from './user';
@@ -20,6 +21,7 @@ const routers = {
chat: chatRouter,
onboard: onboardRouter,
collection,
+ datapool,
};
export default routers;
diff --git a/packages/app/src/backend/routes/api/router.ts b/packages/app/src/backend/routes/api/router.ts
index 2ac31186..cdcea1a0 100644
--- a/packages/app/src/backend/routes/api/router.ts
+++ b/packages/app/src/backend/routes/api/router.ts
@@ -9,6 +9,7 @@ import { isSmythAlpha, isSmythStaff } from '../../utils';
import { isCustomLLMAllowed } from '../../utils/customLLM';
import agentRouter from './agent/router';
import componentRouters from './component/index';
+import { credentialsRouter } from './credentials/router';
import { feedbackRouter } from './page/feedback';
import pageRouters from './page/index';
import { teamSettingsRouter } from './team-settings/router';
@@ -73,6 +74,7 @@ router.get('/user', async (req, res) => {
router.use('/app/user-settings', userSettingsRouter);
router.use('/app/team-settings', teamSettingsRouter);
+router.use('/app/credentials', credentialsRouter);
router.get('/status', includeTeamDetails, async (req, res) => {
const url = `${config.env.API_SERVER}/health`;
@@ -155,6 +157,7 @@ router.get('/status', includeTeamDetails, async (req, res) => {
team,
server: 'Online',
env: config.env.NODE_ENV,
+ smythos_edition: config.env.SMYTHOS_EDITION,
agent_domain: result?.data?.agent_domain,
frontUrl: config.env.UI_SERVER,
url: config.env.PUB_API_SERVER || config.env.API_SERVER,
@@ -166,7 +169,14 @@ router.get('/status', includeTeamDetails, async (req, res) => {
});
} catch (error) {
res.json({
- status: { user, team, prod_agent_domain: config.env.PROD_AGENT_DOMAIN, server: 'Offline' },
+ status: {
+ user,
+ team,
+ prod_agent_domain: config.env.PROD_AGENT_DOMAIN,
+ server: 'Offline',
+ smythos_edition: config.env.SMYTHOS_EDITION,
+ env: config.env.NODE_ENV,
+ },
});
}
});
diff --git a/packages/app/src/backend/routes/pages/builder-sidebar.ts b/packages/app/src/backend/routes/pages/builder-sidebar.ts
index 67cb1a43..aa34b724 100644
--- a/packages/app/src/backend/routes/pages/builder-sidebar.ts
+++ b/packages/app/src/backend/routes/pages/builder-sidebar.ts
@@ -58,7 +58,15 @@ const baseMenu: Menu = {
{ name: 'FSign', label: 'F:Sign', description: '' },
{ name: 'FTimestamp', label: 'F:Timestamp', description: '' },
],
- 'RAG Data': [],
+ 'RAG Data': [
+ {
+ label: 'Manage My Vector DB',
+ externalLink: '/data',
+ },
+ { name: 'DataSourceLookup', label: 'RAG Search', description: '' },
+ { name: 'DataSourceIndexer', label: 'RAG Remember', description: '' },
+ { name: 'DataSourceCleaner', label: 'RAG Forget', description: '' },
+ ],
Logic: [
{ name: 'LogicAND', description: 'AND', label: 'And', icon: 'LogicAND' },
diff --git a/packages/app/src/builder-ui/components/DataSourceCleaner.class.ts b/packages/app/src/builder-ui/components/DataSourceCleaner.class.ts
new file mode 100644
index 00000000..1f82300a
--- /dev/null
+++ b/packages/app/src/builder-ui/components/DataSourceCleaner.class.ts
@@ -0,0 +1,103 @@
+import { builderStore } from '@src/shared/state_stores/builder/store';
+import { delay } from '../utils/general.utils';
+import { Component } from './Component.class';
+
+// @ts-ignore
+export class DataSourceCleaner extends Component {
+ private namespaces: string[] = [];
+ private isNewComponent: boolean = false;
+
+ protected async prepare(): Promise<any> {
+ this.isNewComponent = Object.keys(this.data).length === 0;
+ const eligibleForV2 =
+ builderStore.getState().serverStatus.edition === 'enterprise' &&
+ !window.location.hostname.includes('smythos.com');
+
+ const componentVersion =
+ this.data.version ?? (this.isNewComponent && eligibleForV2 ? 'v2' : 'v1');
+
+ if (this.isNewComponent && eligibleForV2) {
+ this.data.version = componentVersion;
+ }
+
+ this.updateSettings();
+ }
+
+ protected async updateSettings() {
+ if (!this.data.version || this.data.version === 'v1') {
+ const result = await fetch(
+ `${this.workspace.server}/api/component/DataSourceIndexer/namespaces`,
+ );
+ const namespaces = await result.json();
+ this.namespaces = namespaces.map((item) => ({ value: item.id, text: item.name }));
+ this.settings.namespaceId.options = this.namespaces;
+ if (this.settingsOpen) this.refreshSettingsSidebar();
+ } else if (this.data.version === 'v2') {
+ const result = await fetch(
+ `${this.workspace.server}/api/component/DataSourceIndexer/v2/namespaces`,
+ );
+ const namespaces = await result.json();
+ this.namespaces = namespaces.map((item) => ({ value: item.label, text: item.label }));
+ this.settings.namespaceId.options = this.namespaces;
+ if (this.settingsOpen) this.refreshSettingsSidebar();
+ }
+ }
+
+ protected async init() {
+ this.settings = {
+ namespaceId: {
+ type: 'select',
+ label: 'namespace',
+ help: 'Select the namespace that contains the source to remove.',
+ value: '',
+ options: this.namespaces,
+ },
+
+ id: {
+ type: 'input',
+ label: `source identifier`,
+ help: 'Enter the exact ID used during indexing (a–z, A–Z, 0–9, -, _, .). <a href="https://smythos.com/docs/agent-studio/components/rag-data/rag-forget/?utm_source=studio&utm_medium=tooltip&utm_campaign=rag-forget&utm_content=source-identifier#step-1-specify-the-target-data" target="_blank" class="text-blue-600 hover:text-blue-800">See how to find the ID</a>',
+ value: '',
+ validate: `custom=isValidId`,
+ validateMessage: `It should contain only 'a-z', 'A-Z', '0-9', '-', '_', '.', `,
+ attributes: { 'data-template-vars': 'true' },
+ },
+ };
+
+ const dataEntries = ['namespaceId', 'id'];
+ for (let item of dataEntries) {
+ if (typeof this.data[item] === 'undefined') this.data[item] = this.settings[item].value;
+ }
+
+ this.properties.defaultInputs = [];
+ this.properties.defaultOutputs = ['Success'];
+
+ this.drawSettings.iconCSSClass = 'svg-icon ' + this.constructor.name;
+ this.drawSettings.displayName = 'RAG Forget';
+ this.drawSettings.shortDescription = 'Delete data sources from data pool';
+ this.drawSettings.color = '#fb3464';
+
+ this.drawSettings.showSettings = true;
+ }
+
+ protected async checkSettings() {
+ super.checkSettings();
+
+ if (!this.namespaces || this.namespaces.length == 0) await delay(3000);
+
+ const namespaces = {};
+ this.namespaces.forEach((ns: any) => {
+ namespaces[ns.value] = ns.text;
+ });
+ if (this.data['namespace']) {
+ const nsId = this.data['namespace'];
+ if (!namespaces[nsId]) {
+ console.log('Namespace Missing', nsId);
+ this.addComponentMessage(
+ `Missing Namespace<br /><a href="/data" target="_blank" style="color:#33b;text-decoration:underline">Create one</a> then configure it for this component`,
+ 'alert',
+ );
+ }
+ }
+ }
+}
diff --git a/packages/app/src/builder-ui/components/DataSourceIndexer.class.ts b/packages/app/src/builder-ui/components/DataSourceIndexer.class.ts
new file mode 100644
index 00000000..9da7c56d
--- /dev/null
+++ b/packages/app/src/builder-ui/components/DataSourceIndexer.class.ts
@@ -0,0 +1,141 @@
+import { builderStore } from '@src/shared/state_stores/builder/store';
+import { delay } from '../utils/general.utils';
+import { Component } from './Component.class';
+
+// @ts-ignore
+export class DataSourceIndexer extends Component {
+ private namespaces: string[] = [];
+ private isNewComponent: boolean = false;
+
+ protected async prepare(): Promise<any> {
+ this.isNewComponent = Object.keys(this.data).length === 0;
+ const eligibleForV2 =
+ builderStore.getState().serverStatus.edition === 'enterprise' &&
+ !window.location.hostname.includes('smythos.com');
+
+ const componentVersion =
+ this.data.version ?? (this.isNewComponent && eligibleForV2 ? 'v2' : 'v1');
+
+ if (this.isNewComponent && eligibleForV2) {
+ this.data.version = componentVersion;
+ }
+
+ this.updateSettings();
+
+ return new Promise((resolve) => resolve(true));
+ }
+
+ protected async updateSettings() {
+ if (!this.data.version || this.data.version === 'v1') {
+ const result = await fetch(
+ `${this.workspace.server}/api/component/DataSourceIndexer/namespaces`,
+ );
+ const namespaces = await result.json();
+ this.namespaces = namespaces.map((item) => ({ value: item.id, text: item.name }));
+ this.settings.namespace.options = this.namespaces;
+ if (this.settingsOpen) this.refreshSettingsSidebar();
+ } else if (this.data.version === 'v2') {
+ const result = await fetch(
+ `${this.workspace.server}/api/component/DataSourceIndexer/v2/namespaces`,
+ );
+ const namespaces = await result.json();
+ this.namespaces = namespaces.map((item) => ({ value: item.label, text: item.label }));
+ this.settings.namespace.options = this.namespaces;
+ if (this.settingsOpen) this.refreshSettingsSidebar();
+ }
+ }
+
+ protected async init() {
+ this.settings = {
+ namespace: {
+ type: 'select',
+ label: 'namespace',
+ help: 'Select the memory bucket where this source is stored; keep staging and production separate.',
+ options: this.namespaces,
+ },
+
+ id: {
+ type: 'input',
+ label: `source identifier`,
+ help: 'Stable unique ID for this source; allowed: a–z, A–Z, 0–9, -, _, .; reusing updates the existing entry. <a href="https://smythos.com/docs/agent-studio/components/rag-data/rag-remember/?utm_source=studio&utm_medium=tooltip&utm_campaign=rag-remember&utm_content=source-identifier#step-1-define-the-namespace-and-source-details" target="_blank" class="text-blue-600 hover:text-blue-800">See ID rules</a>',
+ attributes: { 'data-template-vars': 'true' },
+ validate: `custom=isValidId`,
+ validateMessage: `It should contain only 'a-z', 'A-Z', '0-9', '-', '_', '.' `,
+ },
+ name: {
+ type: 'input',
+ label: 'label',
+ help: 'Human-readable name shown in dashboards and logs.',
+ attributes: { 'data-template-vars': 'true' },
+ validate: `maxlength=50`,
+ validateMessage: 'Enter a non-empty label, not more than 50 characters.',
+ },
+ metadata: {
+ type: 'textarea',
+ expandable: true,
+ code: { mode: 'json', theme: 'chrome' },
+ label: `Metadata`,
+ help: 'Optional JSON or text with author, tags, and timestamps to improve search and filtering.',
+ tooltipClasses: 'w-44',
+ arrowClasses: '-ml-11',
+ value: '',
+ validate: `maxlength=500000`,
+ validateMessage: `The metadata length is limitted to 500,000 characters`,
+ attributes: {},
+ },
+
+ ...(this.data.version === 'v2'
+ ? {
+ chunkSize: {
+ type: 'input',
+ label: 'chunk size',
+ help: 'The size of the chunks to split the data into.',
+ value: 1000,
+ },
+ chunkOverlap: {
+ type: 'input',
+ label: 'chunk overlap',
+ help: 'The overlap of the chunks to split the data into.',
+ value: 100,
+ },
+ }
+ : {}),
+ };
+
+ const dataEntries = ['namespace'];
+ for (let item of dataEntries) {
+ if (typeof this.data[item] === 'undefined') this.data[item] = this.settings[item].value;
+ }
+
+ this.properties.defaultInputs = ['Source'];
+ this.properties.defaultOutputs = ['Success'];
+
+ this.drawSettings.iconCSSClass = 'svg-icon ' + this.constructor.name;
+ this.drawSettings.displayName = 'RAG Remember';
+ this.drawSettings.shortDescription = 'Index data sources to data pool';
+ this.drawSettings.color = '#fb3464';
+
+ this.drawSettings.showSettings = true;
+ }
+
+ protected async checkSettings() {
+ super.checkSettings();
+
+ if (!this.namespaces || this.namespaces.length == 0) await delay(3000);
+
+ const namespaces = {};
+ this.namespaces.forEach((ns: any) => {
+ namespaces[ns.value] = ns.text;
+ });
+ if (this.data['namespace']) {
+ const nsId = this.data['namespace'];
+ if (!namespaces[nsId]) {
+ console.log('Namespace Missing', nsId);
+ this.addComponentMessage(
+ `Missing Namespace<br /><a href="/data" target="_blank" style="color:#33b;text-decoration:underline">Create one</a> then configure it for this component`,
+ 'alert',
+ );
+ }
+ }
+ }
+}
diff --git a/packages/app/src/builder-ui/components/DataSourceLookup.class.ts b/packages/app/src/builder-ui/components/DataSourceLookup.class.ts
new file mode 100644
index 00000000..fb9786bc
--- /dev/null
+++ b/packages/app/src/builder-ui/components/DataSourceLookup.class.ts
@@ -0,0 +1,121 @@
+import { builderStore } from '@src/shared/state_stores/builder/store';
+import { delay } from '../utils/general.utils';
+import { Component } from './Component.class';
+
+// @ts-ignore
+export class DataSourceLookup extends Component {
+ private namespaces: string[] = [];
+ private isNewComponent: boolean = false;
+ private componentVersion: string = 'v1';
+
+ protected async prepare(): Promise<any> {
+ this.isNewComponent = Object.keys(this.data).length === 0;
+ const eligibleForV2 =
+ builderStore.getState().serverStatus.edition === 'enterprise' &&
+ !window.location.hostname.includes('smythos.com');
+
+ const componentVersion =
+ this.data.version ?? (this.isNewComponent && eligibleForV2 ? 'v2' : 'v1');
+
+ if (this.isNewComponent && eligibleForV2) {
+ this.data.version = componentVersion;
+ }
+ this.updateSettings();
+ }
+
+ protected async updateSettings() {
+ if (!this.data.version || this.data.version === 'v1') {
+ const result = await fetch(
+ `${this.workspace.server}/api/component/DataSourceIndexer/namespaces`,
+ );
+ const namespaces = await result.json();
+ this.namespaces = namespaces.map((item) => ({ value: item.id, text: item.name }));
+ this.settings.namespace.options = this.namespaces;
+ if (this.settingsOpen) this.refreshSettingsSidebar();
+ } else if (this.data.version === 'v2') {
+ const result = await fetch(
+ `${this.workspace.server}/api/component/DataSourceIndexer/v2/namespaces`,
+ );
+ const namespaces = await result.json();
+ this.namespaces = namespaces.map((item) => ({ value: item.label, text: item.label }));
+ this.settings.namespace.options = this.namespaces;
+ if (this.settingsOpen) this.refreshSettingsSidebar();
+ }
+ }
+
+ protected async init() {
+ this.settings = {
+ namespace: {
+ type: 'select',
+ label: 'namespace',
+ help: 'Select the memory bucket to search, matching the namespace used when indexing. <a href="https://smythos.com/docs/agent-studio/components/rag-data/rag-search/?utm_source=studio&utm_medium=tooltip&utm_campaign=rag-search&utm_content=namespace#step-1-define-the-search-scope" target="_blank" class="text-blue-600 hover:text-blue-800">See namespace mapping</a>',
+ options: this.namespaces,
+ },
+ topK: {
+ type: 'number',
+ label: 'Results count',
+ help: 'Choose how many top matches to return; more can raise cost.',
+ value: 3,
+ validate: `required min=0 custom=isValidInteger`,
+ validateMessage: `Please enter a positive number`,
+ },
+ includeMetadata: {
+ type: 'checkbox',
+ label: 'Include metadata',
+ help: 'Return stored fields like title, URL, tags, and timestamps with each result.',
+ value: false,
+ },
+ scoreThreshold: {
+ type: 'range',
+ label: 'Score threshold',
+ value: 0.5,
+ min: 0,
+ max: 1,
+ step: 0.01,
+ help: 'Hide items below this 0–1 relevance score; higher keeps only strong matches. <a href="https://smythos.com/docs/agent-studio/components/rag-data/rag-search/?utm_source=studio&utm_medium=tooltip&utm_campaign=rag-search&utm_content=score-threshold#step-2-filter-and-format-the-output" target="_blank" class="text-blue-600 hover:text-blue-800">See threshold examples</a>',
+ },
+ includeScore: {
+ type: 'checkbox',
+ label: 'Include score',
+ help: 'Add the similarity score to each item for sorting and debugging.',
+ value: false,
+ },
+ };
+
+ const dataEntries = ['namespace', 'topK', 'scoreThreshold', 'includeScore'];
+ for (let item of dataEntries) {
+ if (typeof this.data[item] === 'undefined') this.data[item] = this.settings[item].value;
+ }
+
+ this.properties.defaultInputs = ['Query'];
+ this.properties.defaultOutputs = ['Results'];
+
+ this.drawSettings.iconCSSClass = 'svg-icon ' + this.constructor.name;
+ this.drawSettings.displayName = 'RAG Search';
+ this.drawSettings.shortDescription = 'Lookup data from data pool';
+ this.drawSettings.color = '#fb3464';
+
+ this.drawSettings.showSettings = true;
+ }
+
+ protected async checkSettings() {
+ super.checkSettings();
+
+ if (!this.namespaces || this.namespaces.length == 0) await delay(3000);
+
+ const namespaces = {};
+ this.namespaces.forEach((ns: any) => {
+ namespaces[ns.value] = ns.text;
+ });
+ if (this.data['namespace']) {
+ const nsId = this.data['namespace'];
+ if (!namespaces[nsId]) {
+ console.log('Namespace Missing', nsId);
+ this.addComponentMessage(
+ `Missing Namespace<br /><a href="/data" target="_blank" style="color:#33b;text-decoration:underline">Create one</a> then configure it for this component`,
+ 'alert',
+ );
+ }
+ }
+ }
+}
diff --git a/packages/app/src/builder-ui/components/index.ts b/packages/app/src/builder-ui/components/index.ts
index 278ae0a3..c229539d 100644
--- a/packages/app/src/builder-ui/components/index.ts
+++ b/packages/app/src/builder-ui/components/index.ts
@@ -37,9 +37,12 @@ import { VisionLLM } from './VisionLLM.class';
import { ZapierAction } from './ZapierAction.class';
import { AgentCard } from './AgentCard.class';
+import { DataSourceCleaner } from './DataSourceCleaner.class';
+import { DataSourceIndexer } from './DataSourceIndexer.class';
+import { DataSourceLookup } from './DataSourceLookup.class';
import { GmailTrigger } from './Triggers/Gmail.trigger';
-import { WhatsAppTrigger } from './Triggers/WhatsApp.trigger';
import { JobSchedulerTrigger } from './Triggers/JobScheduler.trigger';
+import { WhatsAppTrigger } from './Triggers/WhatsApp.trigger';
const baseComponents = {
Component,
@@ -82,6 +85,9 @@ const baseComponents = {
WhatsAppTrigger,
AgentCard,
JobSchedulerTrigger,
+ DataSourceCleaner,
+ DataSourceIndexer,
+ DataSourceLookup,
};
export const getBuilderComponents = () => {
diff --git a/packages/app/src/react/app/routeMap.tsx b/packages/app/src/react/app/routeMap.tsx
index 60ecf922..e651badf 100644
--- a/packages/app/src/react/app/routeMap.tsx
+++ b/packages/app/src/react/app/routeMap.tsx
@@ -1,5 +1,7 @@
import VaultPage from '@react/features/vault/pages/VaultPage';
import AgentsPage from '@src/react/features/agents/pages/AgentsPage';
+import DataPoolPage from '@src/react/features/data-pool/pages/DataPoolPage';
+import DatasourcesPage from '@src/react/features/data-pool/pages/DatasourcesPage';
import { IPageRoute } from '@src/react/shared/types/route';
import AccountDeletedPage from '../features/account/pages/AccountDeletedPage';
import AgentSettingsPage from '../features/agent-settings/pages/AgentSettingsPage';
@@ -60,6 +62,18 @@ export const routeMap: IPageRoute[] = [
component: VaultPage,
layoutOptions: { sidebar: true, topMenu: true },
},
+ {
+ title: 'Data Pool',
+ path: 'data-pool',
+ component: DataPoolPage,
+ layoutOptions: { sidebar: true, topMenu: true, background: 'white' },
+ },
+ {
+ title: 'Datasources',
+ path: 'data-pool/:namespaceLabel/datasources',
+ component: DatasourcesPage,
+ layoutOptions: { sidebar: true, topMenu: true, background: 'white' },
+ },
];
export const routeNames = routeMap.map((route) => route.path);
diff --git a/packages/app/src/react/features/credentials/README.md b/packages/app/src/react/features/credentials/README.md
new file mode 100644
index 00000000..e69de29b
diff --git a/packages/app/src/react/features/credentials/clients/credentials.client.ts b/packages/app/src/react/features/credentials/clients/credentials.client.ts
new file mode 100644
index 00000000..f66ec7d8
--- /dev/null
+++ b/packages/app/src/react/features/credentials/clients/credentials.client.ts
@@ -0,0 +1,212 @@
+/**
+ * Credentials Service
+ *
+ * Handles API calls for credential management
+ */
+
+import type { CredentialConnection } from '../components/create-credentials.modal';
+
+/**
+ * Credential field with sensitivity metadata
+ */
+export interface CredentialFieldValue {
+ value: string;
+ sensitive: boolean;
+}
+
+/**
+ * Credentials with metadata for vault storage
+ */
+export type CredentialsWithMetadata = Record<string, CredentialFieldValue>;
+
+export const credentialsClient = {
+ /**
+ * Fetch all credentials for a specific group
+ */
+ fetchCredentials: async (group: string): Promise<CredentialConnection[]> => {
+ try {
+ const response = await fetch(`/api/app/credentials?group=${encodeURIComponent(group)}`, {
+ method: 'GET',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ });
+
+ if (!response.ok) {
+ console.error('Failed to fetch credentials:', response.statusText);
+ throw new Error('Failed to fetch credentials');
+ }
+
+ const result = await response.json();
+ return result.data || [];
+ } catch (error) {
+ console.error('Error fetching credentials:', error);
+ throw new Error(error.message || 'Failed to fetch credentials');
+ }
+ },
+
+ /**
+ * Fetch a single credential by ID
+ */
+ fetchCredentialById: async (id: string, group: string): Promise<CredentialConnection> => {
+ try {
+ const response = await fetch(
+ `/api/app/credentials/${encodeURIComponent(id)}?group=${encodeURIComponent(group)}`,
+ {
+ method: 'GET',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ },
+ );
+
+ if (!response.ok) {
+ console.error('Failed to fetch credential:', response.statusText);
+ throw new Error('Failed to fetch credential');
+ }
+
+ const result = await response.json();
+ return result.data;
+ } catch (error) {
+ console.error('Error fetching credential:', error);
+ throw new Error(error.message || 'Failed to fetch credential');
+ }
+ },
+
+ /**
+ * Fetch a credential by ID with resolved vault keys (for editing)
+ */
+ fetchCredentialForEdit: async (id: string, group: string): Promise<CredentialConnection> => {
+ try {
+ const response = await fetch(
+ `/api/app/credentials/${encodeURIComponent(id)}?group=${encodeURIComponent(group)}&resolveVaultKeys=true`,
+ {
+ method: 'GET',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ },
+ );
+
+ if (!response.ok) {
+ console.error('Failed to fetch credential for edit:', response.statusText);
+ throw new Error('Failed to fetch credential for edit');
+ }
+
+ const result = await response.json();
+ return result.data;
+ } catch (error) {
+ console.error('Error fetching credential for edit:', error);
+ throw new Error(error.message || 'Failed to fetch credential for edit');
+ }
+ },
+
+ /**
+ * Create a new credential
+ */
+ createCredential: async (data: {
+ group: string;
+ name: string;
+ provider: string;
+ credentials: CredentialsWithMetadata;
+ }): Promise<CredentialConnection> => {
+ try {
+ const response = await fetch('/api/app/credentials', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(data),
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ console.error('Failed to create credential:', errorData);
+ throw new Error(errorData.error || 'Failed to create credential');
+ }
+
+ const result = await response.json();
+ return result.data;
+ } catch (error) {
+ console.error('Error creating credential:', error);
+ throw new Error(error.message || 'Failed to create credential');
+ }
+ },
+
+ /**
+ * Update an existing credential
+ */
+ updateCredential: async (
+ id: string,
+ data: {
+ group: string;
+ name: string;
+ provider: string;
+ credentials: CredentialsWithMetadata;
+ },
+ ): Promise<CredentialConnection> => {
+ try {
+ const response = await fetch(`/api/app/credentials/${encodeURIComponent(id)}`, {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(data),
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ console.error('Failed to update credential:', errorData);
+ throw new Error(errorData.error || 'Failed to update credential');
+ }
+
+ const result = await response.json();
+ return result.data;
+ } catch (error) {
+ console.error('Error updating credential:', error);
+ throw new Error(error.message || 'Failed to update credential');
+ }
+ },
+
+ /**
+ * Delete a credential
+ */
+ deleteCredential: async (
+ id: string,
+ group: string,
+ consentedWarnings: boolean = false,
+ ): Promise<{ success: boolean; warnings?: string[] }> => {
+ try {
+ const url = `/api/app/credentials/${encodeURIComponent(id)}?group=${encodeURIComponent(group)}${consentedWarnings ? '&consentedWarnings=true' : ''}`;
+
+ const response = await fetch(url, {
+ method: 'DELETE',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ });
+
+ const data = await response.json();
+
+ // Handle warnings response (200 with success: false)
+ if (response.ok && !data.success && data.warnings) {
+ return {
+ success: false,
+ warnings: data.warnings,
+ };
+ }
+
+ // Handle error response
+ if (!response.ok) {
+ console.error('Failed to delete credential:', data);
+ throw new Error(data.error || 'Failed to delete credential');
+ }
+
+ // Success
+ return { success: true };
+ } catch (error) {
+ console.error('Error deleting credential:', error);
+ throw new Error(error.message || 'Failed to delete credential');
+ }
+ },
+};
diff --git a/packages/app/src/react/features/credentials/components/create-credentials.modal.tsx b/packages/app/src/react/features/credentials/components/create-credentials.modal.tsx
new file mode 100644
index 00000000..89e0b3e2
--- /dev/null
+++ b/packages/app/src/react/features/credentials/components/create-credentials.modal.tsx
@@ -0,0 +1,578 @@
+/**
+ * CreateCredentialsModal Component
+ *
+ * A two-step modal for creating and editing credentials:
+ * - Step 1: Select provider from dropdown
+ * - Step 2: Fill in dynamic form based on provider's schema
+ *
+ * @component
+ */
+
+import {
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@src/react/shared/components/ui/dialog';
+import { Input } from '@src/react/shared/components/ui/input';
+import { Button as CustomButton } from '@src/react/shared/components/ui/newDesign/button';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@src/react/shared/components/ui/select';
+import React, { useEffect, useMemo, useState } from 'react';
+import { credentialsClient } from '../clients/credentials.client';
+import credentialsSchema from '../credentials-schema.json';
+import { CredentialFormSkeleton } from './credential-form-skeleton';
+
+/**
+ * Field schema definition from credentials-schema.json
+ */
+interface CredentialField {
+ key: string;
+ label: string;
+ type: 'string' | 'password' | 'number' | 'email' | 'url';
+ required: boolean;
+ placeholder?: string;
+}
+
+/**
+ * Provider schema definition
+ */
+interface ProviderSchema {
+ id: string;
+ name: string;
+ group: string;
+ auth_type: string;
+ description: string;
+ logo_url?: string;
+ fields: CredentialField[];
+ docs_url?: string;
+ test_endpoint?: string;
+}
+
+/**
+ * Credential connection (for edit mode)
+ */
+export interface CredentialConnection {
+ id: string;
+ name: string;
+ provider: string;
+ group: string;
+ credentials: Record<string, string>;
+ isActive?: boolean;
+}
+
+/**
+ * Props for CreateCredentialsModal
+ */
+interface CreateCredentialsModalProps {
+ isOpen: boolean;
+ onClose: () => void;
+
+
+ onSuccess?: (data: { id?: string; name: string; provider: string; credentials: Record<string, string>; isEdit: boolean }) => void;
+ group: string;
+ editConnection?: CredentialConnection;
+}
+
+/**
+ * Validates a field value based on its type and requirements
+ */
+const validateField = (field: CredentialField, value: string): string | null => {
+ // Check required fields
+ if (field.required && (!value || value.trim() === '')) {
+ return `${field.label} is required`;
+ }
+
+ // Skip type validation if field is not required and empty
+ if (!value || value.trim() === '') {
+ return null;
+ }
+
+ // Type-specific validation
+ switch (field.type) {
+ case 'email': {
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+ if (!emailRegex.test(value)) {
+ return `${field.label} must be a valid email address`;
+ }
+ break;
+ }
+ case 'url': {
+ try {
+ new URL(value);
+ } catch {
+ return `${field.label} must be a valid URL`;
+ }
+ break;
+ }
+ case 'number': {
+ if (isNaN(Number(value))) {
+ return `${field.label} must be a valid number`;
+ }
+ break;
+ }
+ }
+
+ return null;
+};
+
+/**
+ * CreateCredentialsModal Component
+ */
+export function CreateCredentialsModal({
+ isOpen,
+ onClose,
+ onSuccess,
+ group,
+ editConnection,
+}: CreateCredentialsModalProps) {
+ // Step management (1 = select provider, 2 = fill form)
+ const [step, setStep] = useState<1 | 2>(1);
+
+ // Form state
+ const [connectionName, setConnectionName] = useState<string>('');
+ const [selectedProviderId, setSelectedProviderId] = useState<string>('');
+ const [credentials, setCredentials] = useState<Record<string, string>>({});
+ const [errors, setErrors] = useState<Record<string, string>>({});
+ const [touched, setTouched] = useState<Record<string, boolean>>({});
+ const [isProcessing, setIsProcessing] = useState<boolean>(false);
+ const [isResolvingVaultKeys, setIsResolvingVaultKeys] = useState<boolean>(false);
+
+ // Determine if in edit mode
+ const isEditMode = !!editConnection;
+
+ // Filter providers by group
+ const availableProviders = useMemo(() => {
+ return (credentialsSchema as ProviderSchema[]).filter(
+ (provider) => provider.group === group
+ );
+ }, [group]);
+
+ // Get selected provider schema
+ const selectedProvider = useMemo(() => {
+ return availableProviders.find((p) => p.id === selectedProviderId);
+ }, [availableProviders, selectedProviderId]);
+
+ /**
+ * Initialize form data when opening in edit mode
+ * Resolves vault keys to show actual values
+ */
+ useEffect(() => {
+ const loadConnectionData = async () => {
+ if (isOpen) {
+ if (isEditMode && editConnection) {
+ // Edit mode: resolve vault keys and populate form
+ setIsResolvingVaultKeys(true);
+
+ try {
+ // Fetch credential with resolved vault keys
+ const resolvedCredential = await credentialsClient.fetchCredentialForEdit(
+ editConnection.id,
+ group
+ );
+
+ setConnectionName(resolvedCredential.name);
+ setSelectedProviderId(resolvedCredential.provider);
+ setCredentials(resolvedCredential.credentials);
+ setStep(2); // Go directly to form step
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.error('Error loading credential for edit:', error);
+ // Fallback to unresolved data
+ setConnectionName(editConnection.name);
+ setSelectedProviderId(editConnection.provider);
+ setCredentials(editConnection.credentials);
+ setStep(2);
+ } finally {
+ setIsResolvingVaultKeys(false);
+ }
+ } else {
+ // Create mode: reset form
+ setConnectionName('');
+ setSelectedProviderId('');
+ setCredentials({});
+ setStep(1);
+ setIsResolvingVaultKeys(false);
+ }
+ // Reset validation state
+ setErrors({});
+ setTouched({});
+ }
+ };
+
+ loadConnectionData();
+ }, [isOpen, isEditMode, editConnection, group]);
+
+ /**
+ * Handle provider selection and move to step 2
+ */
+ const handleProviderSelect = (providerId: string) => {
+ setSelectedProviderId(providerId);
+ // Initialize credentials object with empty values
+ const provider = availableProviders.find((p) => p.id === providerId);
+ if (provider) {
+ const initialCredentials: Record<string, string> = {};
+ provider.fields.forEach((field) => {
+ initialCredentials[field.key] = '';
+ });
+ setCredentials(initialCredentials);
+ }
+ setStep(2);
+ };
+
+ /**
+ * Handle going back to step 1
+ */
+ const handleBack = () => {
+ setStep(1);
+ setErrors({});
+ setTouched({});
+ };
+
+ /**
+ * Handle credential field change
+ */
+ const handleCredentialChange = (key: string, value: string) => {
+ setCredentials((prev) => ({ ...prev, [key]: value }));
+
+ // Clear error for this field when user starts typing
+ if (errors[key]) {
+ setErrors((prev) => {
+ const newErrors = { ...prev };
+ delete newErrors[key];
+ return newErrors;
+ });
+ }
+ };
+
+ /**
+ * Handle field blur (mark as touched)
+ */
+ const handleBlur = (key: string) => {
+ setTouched((prev) => ({ ...prev, [key]: true }));
+
+ // Validate field on blur
+ if (selectedProvider) {
+ const field = selectedProvider.fields.find((f) => f.key === key);
+ if (field) {
+ const error = validateField(field, credentials[key] || '');
+ if (error) {
+ setErrors((prev) => ({ ...prev, [key]: error }));
+ }
+ }
+ }
+ };
+
+ /**
+ * Validate all fields
+ */
+ const validateAllFields = (): boolean => {
+ if (!selectedProvider) return false;
+
+ const newErrors: Record<string, string> = {};
+
+ // Validate connection name
+ if (!connectionName.trim()) {
+ newErrors.connectionName = 'Connection name is required';
+ }
+
+ // Validate credential fields
+ selectedProvider.fields.forEach((field) => {
+ const error = validateField(field, credentials[field.key] || '');
+ if (error) {
+ newErrors[field.key] = error;
+ }
+ });
+
+ setErrors(newErrors);
+
+ // Mark all fields as touched
+ const allTouched: Record<string, boolean> = { connectionName: true };
+ selectedProvider.fields.forEach((field) => {
+ allTouched[field.key] = true;
+ });
+ setTouched(allTouched);
+
+ return Object.keys(newErrors).length === 0;
+ };
+
+ /**
+ * Handle form submission
+ */
+ const handleSubmit = async (e: React.FormEvent) => {
+ e.preventDefault();
+
+ if (!validateAllFields()) {
+ return;
+ }
+
+ if (isProcessing || !selectedProviderId) {
+ return;
+ }
+
+ setIsProcessing(true);
+
+ try {
+ // Transform credentials to include sensitivity metadata based on field types
+ const credentialsWithMetadata: Record<string, { value: string; sensitive: boolean }> = {};
+
+ if (selectedProvider) {
+ selectedProvider.fields.forEach((field) => {
+ const value = credentials[field.key] || '';
+ credentialsWithMetadata[field.key] = {
+ value,
+ sensitive: field.type === 'password',
+ };
+ });
+ }
+
+ const credentialData = {
+ group,
+ name: connectionName,
+ provider: selectedProviderId,
+ credentials: credentialsWithMetadata,
+ };
+
+ let result;
+ if (isEditMode && editConnection?.id) {
+ // Update existing credential
+ result = await credentialsClient.updateCredential(editConnection.id, credentialData);
+ } else {
+ // Create new credential
+ result = await credentialsClient.createCredential(credentialData);
+ }
+
+ // Call success callback if provided
+ if (onSuccess) {
+ onSuccess({
+ ...result,
+ isEdit: isEditMode,
+ });
+ }
+
+ // Close modal on success
+ onClose();
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.error('Error submitting credentials:', error);
+
+ // Set error for connection name field to display to user
+ const errorMessage = error instanceof Error ? error.message : 'Failed to save credential. Please try again.';
+ setErrors((prev) => ({
+ ...prev,
+ connectionName: errorMessage,
+ }));
+ setTouched((prev) => ({ ...prev, connectionName: true }));
+ } finally {
+ setIsProcessing(false);
+ }
+ };
+
+ /**
+ * Get input type for HTML input element
+ */
+ const getInputType = (fieldType: CredentialField['type']): string => {
+ switch (fieldType) {
+ case 'password':
+ return 'password';
+ case 'email':
+ return 'email';
+ case 'url':
+ return 'url';
+ case 'number':
+ return 'number';
+ default:
+ return 'text';
+ }
+ };
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onClose}>
+ <DialogContent className="sm:max-w-[600px] max-h-[80vh] overflow-y-auto">
+ <DialogHeader>
+ <DialogTitle>
+ {isEditMode ? 'Edit Credential Connection' : 'Add Credential Connection'}
+ </DialogTitle>
+ </DialogHeader>
+
+ <form onSubmit={handleSubmit}>
+ {isResolvingVaultKeys ? (
+ <CredentialFormSkeleton />
+ ) : (
+ <div className="grid gap-4 py-4">
+ {/* Step 1: Provider Selection (only shown in create mode) */}
+ {step === 1 && !isEditMode && (
+ <div className="space-y-4">
+ <div>
+ <label className="text-gray-700 mb-1 text-sm font-normal flex items-center">
+ Select Provider <span className="text-red-500 ml-1">*</span>
+ </label>
+ <Select
+ value={selectedProviderId}
+ onValueChange={handleProviderSelect}
+ disabled={isProcessing}
+ >
+ <SelectTrigger className="w-full" disabled={isProcessing || isResolvingVaultKeys}>
+ <SelectValue placeholder="Choose a provider..." />
+ </SelectTrigger>
+ <SelectContent>
+ {availableProviders.length === 0 ? (
+ <div className="px-2 py-1.5 text-sm text-muted-foreground">
+ No providers available for this group
+ </div>
+ ) : (
+ availableProviders.map((provider) => (
+ <SelectItem key={provider.id} value={provider.id}>
+ <div className="flex items-start gap-2">
+ {provider.logo_url && (
+ <img
+ src={provider.logo_url}
+ alt={provider.name}
+ className="w-5 h-5 mt-0.5 object-contain flex-shrink-0"
+ />
+ )}
+ <div className="flex flex-col">
+ <span className="font-medium">{provider.name}</span>
+ {provider.description && (
+ <span className="text-xs text-muted-foreground">
+ {provider.description}
+ </span>
+ )}
+ </div>
+ </div>
+ </SelectItem>
+ ))
+ )}
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+ )}
+
+ {/* Step 2: Dynamic Form */}
+ {step === 2 && selectedProvider && (
+ <div className="space-y-4">
+ {/* Connection Name */}
+ <div>
+ <Input
+ label="Connection Name"
+ required
+ fullWidth
+ placeholder="e.g., My Vector Database"
+ value={connectionName}
+ onChange={(e) => {
+ setConnectionName(e.target.value);
+ if (errors.connectionName) {
+ setErrors((prev) => {
+ const newErrors = { ...prev };
+ delete newErrors.connectionName;
+ return newErrors;
+ });
+ }
+ }}
+ onBlur={() => {
+ setTouched((prev) => ({ ...prev, connectionName: true }));
+ if (!connectionName.trim()) {
+ setErrors((prev) => ({
+ ...prev,
+ connectionName: 'Connection name is required',
+ }));
+ }
+ }}
+ error={touched.connectionName && !!errors.connectionName}
+ errorMessage={errors.connectionName}
+ disabled={isProcessing}
+ />
+ </div>
+
+ {/* Provider Info */}
+ <div className="bg-gray-50 border border-gray-200 rounded-md p-3">
+ <div className="flex items-center justify-between">
+ <div className="flex items-start gap-2">
+ {selectedProvider.logo_url && (
+ <img
+ src={selectedProvider.logo_url}
+ alt={selectedProvider.name}
+ className="w-5 h-5 mt-0.5 object-contain flex-shrink-0"
+ />
+ )}
+ <div>
+ <p className="text-sm font-medium text-gray-900">
+ {selectedProvider.name}
+ </p>
+ <p className="text-xs text-gray-500 mt-1">
+ {selectedProvider.description}
+ </p>
+ </div>
+ </div>
+ {selectedProvider.docs_url && (
+ <a
+ href={selectedProvider.docs_url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-xs text-blue-600 hover:text-blue-800 underline"
+ >
+ Documentation
+ </a>
+ )}
+ </div>
+ </div>
+
+ {/* Dynamic Fields */}
+ {selectedProvider.fields.map((field) => (
+ <div key={field.key}>
+ <Input
+ label={field.label}
+ required={field.required}
+ fullWidth
+ type={getInputType(field.type)}
+ placeholder={field.placeholder || `Enter ${field.label.toLowerCase()}`}
+ value={credentials[field.key] || ''}
+ onChange={(e) => handleCredentialChange(field.key, e.target.value)}
+ onBlur={() => handleBlur(field.key)}
+ error={touched[field.key] && !!errors[field.key]}
+ errorMessage={errors[field.key]}
+ disabled={isProcessing || isResolvingVaultKeys}
+ />
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+
+ <DialogFooter>
+ {step === 2 && !isEditMode && (
+ <CustomButton
+ variant="secondary"
+ type="button"
+ handleClick={handleBack}
+ disabled={isProcessing}
+ label="Back"
+ />
+ )}
+ <CustomButton
+ variant="primary"
+ type="submit"
+ loading={isProcessing || isResolvingVaultKeys}
+ disabled={
+ isProcessing ||
+ isResolvingVaultKeys ||
+ (step === 1 && !selectedProviderId && !isEditMode) ||
+ (step === 2 && (!connectionName.trim() || Object.keys(errors).length > 0))
+ }
+ label={isEditMode ? 'Save Changes' : step === 1 ? 'Continue' : 'Create Connection'}
+ />
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
diff --git a/packages/app/src/react/features/credentials/components/credential-form-skeleton.tsx b/packages/app/src/react/features/credentials/components/credential-form-skeleton.tsx
new file mode 100644
index 00000000..3fad2419
--- /dev/null
+++ b/packages/app/src/react/features/credentials/components/credential-form-skeleton.tsx
@@ -0,0 +1,36 @@
+/**
+ * CredentialFormSkeleton Component
+ *
+ * Loading skeleton for credential form while resolving vault keys
+ */
+
+import React from 'react';
+
+export function CredentialFormSkeleton() {
+ return (
+ <div className="grid gap-4 py-4 animate-pulse">
+ {/* Connection Name Field Skeleton */}
+ <div className="space-y-2">
+ <div className="h-4 w-32 bg-gray-200 rounded"></div>
+ <div className="h-10 w-full bg-gray-100 rounded border border-gray-200"></div>
+ </div>
+
+ {/* Credential Fields Skeleton (2-3 fields) */}
+ {[1, 2].map((index) => (
+ <div key={index} className="space-y-2">
+ <div className="h-4 w-24 bg-gray-200 rounded"></div>
+ <div className="h-10 w-full bg-gray-100 rounded border border-gray-200"></div>
+ </div>
+ ))}
+
+ {/* Loading Message */}
+ <div className="flex items-center justify-center py-4">
+ <div className="flex items-center gap-3 text-muted-foreground">
+ <div className="animate-spin rounded-full h-5 w-5 border-2 border-primary border-t-transparent"></div>
+ <p className="text-sm">Loading credential data...</p>
+ </div>
+ </div>
+ </div>
+ );
+}
+
diff --git a/packages/app/src/react/features/credentials/components/credentials-list-skeleton.tsx b/packages/app/src/react/features/credentials/components/credentials-list-skeleton.tsx
new file mode 100644
index 00000000..b4b3d128
--- /dev/null
+++ b/packages/app/src/react/features/credentials/components/credentials-list-skeleton.tsx
@@ -0,0 +1,67 @@
+/**
+ * CredentialsListSkeleton Component
+ *
+ * Loading skeleton for credentials list table
+ */
+
+import React from 'react';
+
+interface CredentialsListSkeletonProps {
+ /**
+ * Number of skeleton rows to display
+ * @default 3
+ */
+ rows?: number;
+}
+
+export function CredentialsListSkeleton({ rows = 3 }: CredentialsListSkeletonProps) {
+ return (
+ <div className="animate-pulse">
+ {/* Table Header */}
+ <div className="flex items-center border-b pb-2 mb-2">
+ <div className="w-1/3 pr-4">
+ <div className="h-3 w-32 bg-gray-200 rounded"></div>
+ </div>
+ <div className="w-1/3 px-4">
+ <div className="h-3 w-24 bg-gray-200 rounded"></div>
+ </div>
+ <div className="w-1/3 pl-4 flex justify-end">
+ <div className="h-3 w-16 bg-gray-200 rounded"></div>
+ </div>
+ </div>
+
+ {/* Table Rows */}
+ {Array.from({ length: rows }).map((_, index) => (
+ <div
+ key={index}
+ className="flex items-center border-t py-3"
+ >
+ {/* Connection Name Column */}
+ <div className="w-1/3 pr-4">
+ <div className="h-4 bg-gray-100 rounded" style={{ width: `${60 + Math.random() * 30}%` }}></div>
+ </div>
+
+ {/* Provider Column */}
+ <div className="w-1/3 px-4">
+ <div className="h-4 bg-gray-100 rounded" style={{ width: `${50 + Math.random() * 20}%` }}></div>
+ </div>
+
+ {/* Actions Column */}
+ <div className="w-1/3 pl-4 flex justify-end gap-1">
+ <div className="h-8 w-8 bg-gray-100 rounded"></div>
+ <div className="h-8 w-8 bg-gray-100 rounded"></div>
+ </div>
+ </div>
+ ))}
+
+ {/* Loading Message */}
+ <div className="flex items-center justify-center py-6 border-t">
+ <div className="flex items-center gap-3 text-muted-foreground">
+ <div className="animate-spin rounded-full h-4 w-4 border-2 border-primary border-t-transparent"></div>
+ <p className="text-sm">Loading connections...</p>
+ </div>
+ </div>
+ </div>
+ );
+}
+
diff --git a/packages/app/src/react/features/credentials/components/delete-credentials.modal.tsx b/packages/app/src/react/features/credentials/components/delete-credentials.modal.tsx
new file mode 100644
index 00000000..ecdb4b55
--- /dev/null
+++ b/packages/app/src/react/features/credentials/components/delete-credentials.modal.tsx
@@ -0,0 +1,247 @@
+/**
+ * Delete Credentials Confirmation Modal
+ *
+ * Requires user to type credential name to confirm deletion.
+ * Encapsulates all credential deletion logic within the credentials feature.
+ *
+ * @component
+ */
+
+import {
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@src/react/shared/components/ui/dialog';
+import { Input } from '@src/react/shared/components/ui/input';
+import { Button as CustomButton } from '@src/react/shared/components/ui/newDesign/button';
+import { errorToast, successToast } from '@src/shared/components/toast';
+import { ChangeEvent, FC, useEffect, useState } from 'react';
+import { credentialsClient } from '../clients/credentials.client';
+
+interface DeleteCredentialsModalProps {
+ isOpen: boolean;
+ credentialId: string;
+ credentialName: string;
+ group: string;
+ onClose: () => void;
+ onSuccess?: () => void;
+}
+
+export const DeleteCredentialsModal: FC<DeleteCredentialsModalProps> = ({
+ isOpen,
+ credentialId,
+ credentialName,
+ group,
+ onClose,
+ onSuccess,
+}) => {
+ const [confirmText, setConfirmText] = useState<string>('');
+ const [isDeleting, setIsDeleting] = useState<boolean>(false);
+ const [error, setError] = useState<string | null>(null);
+ const [warnings, setWarnings] = useState<string[] | null>(null);
+ const [showWarnings, setShowWarnings] = useState<boolean>(false);
+
+ // Reset state when dialog opens/closes
+ useEffect(() => {
+ if (isOpen) {
+ setConfirmText('');
+ setError(null);
+ setIsDeleting(false);
+ setWarnings(null);
+ setShowWarnings(false);
+ }
+ }, [isOpen]);
+
+ const handleConfirmTextChange = (e: ChangeEvent<HTMLInputElement>) => {
+ setConfirmText(e.target.value);
+ setError(null);
+ };
+
+ const handleConfirm = async () => {
+ // Step 1: Validate credential name
+ if (confirmText !== credentialName) {
+ setError('Credential name does not match');
+ return;
+ }
+
+ setIsDeleting(true);
+ setError(null);
+
+ try {
+ // Try to delete without consent first
+ const result = await credentialsClient.deleteCredential(credentialId, group, false);
+
+ // If warnings are returned, show them
+ if (!result.success && result.warnings && result.warnings.length > 0) {
+ setWarnings(result.warnings);
+ setShowWarnings(true);
+ setIsDeleting(false);
+ return;
+ }
+
+ // Success - no warnings
+ successToast('Credential deleted successfully.');
+ onClose();
+ onSuccess?.();
+ } catch (err) {
+ const errorMessage = err instanceof Error ? err.message : 'Failed to delete credential. Please try again.';
+ errorToast(errorMessage);
+ setIsDeleting(false);
+ }
+ };
+
+ const handleConfirmWithWarnings = async () => {
+ setIsDeleting(true);
+ setError(null);
+
+ try {
+ // Delete with consent
+ const result = await credentialsClient.deleteCredential(credentialId, group, true);
+
+ if (result.success) {
+ successToast('Credential deleted successfully.');
+ onClose();
+ onSuccess?.();
+ } else {
+ throw new Error('Failed to delete credential');
+ }
+ } catch (err) {
+ const errorMessage = err instanceof Error ? err.message : 'Failed to delete credential. Please try again.';
+ errorToast(errorMessage);
+ setIsDeleting(false);
+ }
+ };
+
+ const handleBackFromWarnings = () => {
+ setShowWarnings(false);
+ setWarnings(null);
+ };
+
+ const isValid = confirmText === credentialName;
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onClose}>
+ <DialogContent className="sm:max-w-[500px]">
+ <DialogHeader>
+ <DialogTitle>
+ {showWarnings ? 'Confirm Deletion with Warnings' : 'Delete Credential'}
+ </DialogTitle>
+ </DialogHeader>
+
+ {/* Step 1: Normal confirmation */}
+ {!showWarnings && (
+ <div className="py-4 space-y-4">
+ <div className="bg-red-50 border border-red-200 rounded-md p-4">
+ <p className="text-sm text-red-800">
+ <strong>Warning:</strong> This action cannot be undone. This will permanently delete
+ the credential connection and may affect any resources using it.
+ </p>
+ </div>
+
+ <div className="space-y-2">
+ <p className="text-sm text-gray-700">
+ Please type <strong className="font-semibold text-gray-900">{credentialName}</strong>{' '}
+ to confirm deletion.
+ </p>
+ <Input
+ fullWidth
+ type="text"
+ placeholder="Type credential name"
+ value={confirmText}
+ onChange={handleConfirmTextChange}
+ disabled={isDeleting}
+ error={!!error}
+ errorMessage={error || undefined}
+ autoFocus
+ />
+ </div>
+ </div>
+ )}
+
+ {/* Step 2: Warnings display */}
+ {showWarnings && warnings && (
+ <div className="py-4 space-y-4">
+ <div className="bg-amber-50 border border-amber-300 rounded-md p-4">
+ <div className="flex items-start gap-2">
+ <div className="flex-shrink-0 mt-0.5">
+ <svg
+ className="w-5 h-5 text-amber-600"
+ fill="currentColor"
+ viewBox="0 0 20 20"
+ >
+ <path
+ fillRule="evenodd"
+ d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z"
+ clipRule="evenodd"
+ />
+ </svg>
+ </div>
+ <div className="flex-1">
+ <h4 className="text-sm font-semibold text-amber-800 mb-2">
+ ⚠️ Dependencies Detected
+ </h4>
+ <p className="text-sm text-amber-700 mb-3">
+ This credential is currently being used by the following resources:
+ </p>
+ <ul className="space-y-1.5">
+ {warnings.map((warning, index) => (
+ <li key={index} className="text-sm text-amber-800 flex items-start gap-2">
+ <span className="text-amber-600 mt-1">•</span>
+ <span>{warning}</span>
+ </li>
+ ))}
+ </ul>
+ <p className="text-sm text-amber-700 mt-3 font-medium">
+ Are you sure you want to proceed? This may break existing functionality.
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Footer buttons */}
+ <DialogFooter>
+ {!showWarnings ? (
+ <>
+ <CustomButton
+ variant="secondary"
+ label="Cancel"
+ handleClick={onClose}
+ disabled={isDeleting}
+ />
+ <CustomButton
+ variant="primary"
+ label={isDeleting ? 'Checking...' : 'Delete Credential'}
+ handleClick={handleConfirm}
+ disabled={!isValid || isDeleting}
+ loading={isDeleting}
+ className="bg-red-600 hover:bg-red-700 text-white disabled:bg-gray-100 disabled:hover:bg-gray-100 disabled:text-gray-500"
+ />
+ </>
+ ) : (
+ <>
+ <CustomButton
+ variant="secondary"
+ label="Cancel"
+ handleClick={handleBackFromWarnings}
+ disabled={isDeleting}
+ />
+ <CustomButton
+ variant="primary"
+ label={isDeleting ? 'Deleting...' : 'Delete Anyway'}
+ handleClick={handleConfirmWithWarnings}
+ disabled={isDeleting}
+ loading={isDeleting}
+ className="bg-amber-600 hover:bg-amber-700 text-white disabled:bg-gray-100 disabled:hover:bg-gray-100 disabled:text-gray-500"
+ />
+ </>
+ )}
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
diff --git a/packages/app/src/react/features/credentials/credentials-schema.json b/packages/app/src/react/features/credentials/credentials-schema.json
new file mode 100644
index 00000000..b27ccbc1
--- /dev/null
+++ b/packages/app/src/react/features/credentials/credentials-schema.json
@@ -0,0 +1,54 @@
+[
+ {
+ "id": "Pinecone",
+ "name": "Pinecone",
+ "group": "vector_db_creds",
+ "auth_type": "credentials",
+ "description": "Connect to Pinecone vector database",
+ "logo_url": "https://t2.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=https://app.pinecone.io/organizations/-NVAEezkbrqkW5cJ3zbx/projects/1a8c05fd-85bb-4266-95af-f4eb26225b0d/indexes/main/browser&size=32",
+ "fields": [
+ {
+ "key": "apiKey",
+ "label": "API Key",
+ "type": "password",
+ "required": true,
+ "placeholder": "Enter your Pinecone API key"
+ },
+ {
+ "key": "indexName",
+ "label": "Index Name",
+ "type": "string",
+ "required": true,
+ "placeholder": "Enter your Pinecone index name"
+ }
+ ],
+ "docs_url": "https://docs.pinecone.io",
+ "test_endpoint": "https://api.pinecone.io/v1/health"
+ },
+ {
+ "id": "Milvus",
+ "name": "Milvus",
+ "group": "vector_db_creds",
+ "auth_type": "credentials",
+ "description": "Connect to Milvus vector database",
+ "logo_url": "https://t3.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=https://milvus.io/docs/string.md&size=48",
+ "fields": [
+ {
+ "key": "address",
+ "label": "Address",
+ "type": "string",
+ "required": true,
+ "placeholder": "Enter your Milvus address"
+ },
+ {
+ "key": "token",
+ "label": "Token",
+ "type": "string",
+ "required": true,
+ "placeholder": "Enter your Milvus token"
+ }
+ ],
+ "docs_url": "https://milvus.io/",
+ "test_endpoint": "https://milvus.io/"
+ }
+ ]
\ No newline at end of file
diff --git a/packages/app/src/react/features/credentials/hooks/use-credentials.ts b/packages/app/src/react/features/credentials/hooks/use-credentials.ts
new file mode 100644
index 00000000..e93c0ba2
--- /dev/null
+++ b/packages/app/src/react/features/credentials/hooks/use-credentials.ts
@@ -0,0 +1,147 @@
+/**
+ * Hook for managing credential connections
+ *
+ * Fetches and manages credential connections from the backend API.
+ *
+ * @module use-credentials
+ */
+
+import { useEffect, useMemo, useState } from 'react';
+import { credentialsClient } from '../clients/credentials.client';
+import type { CredentialConnection } from '../components/create-credentials.modal';
+
+/**
+ * Custom hook to fetch and manage credential connections
+ *
+ * @param group - Group filter (e.g., 'vector_database')
+ * @returns Object containing credentials data, loading state, error, and refetch function
+ *
+ * @example
+ * ```tsx
+ * const { credentials, isLoading, error, refetch } = useCredentials('vector_database');
+ * ```
+ */
+export function useCredentials(group: string) {
+ const [credentials, setCredentials] = useState<CredentialConnection[]>([]);
+ const [isLoading, setIsLoading] = useState<boolean>(true);
+ const [error, setError] = useState<string | undefined>(undefined);
+
+ /**
+ * Fetch credentials from the API
+ */
+ const fetchCredentials = async () => {
+ if (!group) {
+ setCredentials([]);
+ setIsLoading(false);
+ return;
+ }
+
+ setIsLoading(true);
+ setError(undefined);
+
+ try {
+ const data = await credentialsClient.fetchCredentials(group);
+ setCredentials(data);
+ } catch (err: any) {
+ console.error('Error fetching credentials:', err);
+ setError(err.message || 'Failed to fetch credentials');
+ setCredentials([]);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ // Fetch on mount and when group changes
+ useEffect(() => {
+ fetchCredentials();
+ }, [group]);
+
+ // Sort alphabetically by name
+ const sortedCredentials = useMemo(() => {
+ return [...credentials].sort((a, b) =>
+ a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }),
+ );
+ }, [credentials]);
+
+ return {
+ /** Array of credential connections */
+ credentials: sortedCredentials,
+ /** Whether credentials are currently loading */
+ isLoading,
+ /** Error message if fetch failed */
+ error,
+ /** Function to manually refetch credentials */
+ refetch: fetchCredentials,
+ };
+}
+
+/**
+ * Get a single credential connection by ID
+ *
+ * @param id - The credential connection ID
+ * @param group - The credential group
+ * @returns Object with credential data, loading state, and error
+ *
+ * @example
+ * ```tsx
+ * const { credential, isLoading, error } = useCredentialById('cred-1', 'vector_database');
+ * ```
+ */
+export function useCredentialById(id: string, group: string) {
+ const [credential, setCredential] = useState<CredentialConnection | undefined>(undefined);
+ const [isLoading, setIsLoading] = useState<boolean>(true);
+ const [error, setError] = useState<string | undefined>(undefined);
+
+ useEffect(() => {
+ if (!id || !group) {
+ setCredential(undefined);
+ setIsLoading(false);
+ return;
+ }
+
+ const fetchCredential = async () => {
+ setIsLoading(true);
+ setError(undefined);
+
+ try {
+ const data = await credentialsClient.fetchCredentialById(id, group);
+ setCredential(data);
+ } catch (err: any) {
+ console.error('Error fetching credential:', err);
+ setError(err.message || 'Failed to fetch credential');
+ setCredential(undefined);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ fetchCredential();
+ }, [id, group]);
+
+ return {
+ credential,
+ isLoading,
+ error,
+ };
+}
+
+/**
+ * Get credentials by provider from a list
+ *
+ * @param credentials - Array of credentials
+ * @param provider - The provider ID (e.g., 'piencone')
+ * @returns Filtered array of credentials for that provider
+ *
+ * @example
+ * ```tsx
+ * const pineconeCredentials = useCredentialsByProvider(allCredentials, 'piencone');
+ * ```
+ */
+export function useCredentialsByProvider(
+ credentials: CredentialConnection[],
+ provider: string,
+): CredentialConnection[] {
+ return useMemo(() => {
+ return credentials.filter((cred) => cred.provider === provider);
+ }, [credentials, provider]);
+}
diff --git a/packages/app/src/react/features/data-pool/client/datapool.client.ts b/packages/app/src/react/features/data-pool/client/datapool.client.ts
new file mode 100644
index 00000000..b6dfcf0a
--- /dev/null
+++ b/packages/app/src/react/features/data-pool/client/datapool.client.ts
@@ -0,0 +1,179 @@
+/**
+ * Data Pool API Client
+ *
+ * Handles API calls for data pool/namespace management
+ */
+
+import type {
+ CreateNamespaceRequest,
+ CreateNamespaceResponse,
+ EmbeddingModel,
+ ListNamespacesResponse,
+ Namespace,
+} from '../types';
+
+/**
+ * Extract error message from nested error structure
+ */
+export const extractErrorMessage = (error: unknown, defaultMessage: string): string => {
+ console.log('error', error);
+ // Type guard to check if error is an object
+ let extractedMessage = defaultMessage;
+
+ if (typeof error === 'object' && error !== null) {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const errorObj = error as Record<string, any>;
+
+ if (typeof error === 'string') {
+ extractedMessage = error;
+ } else if (typeof errorObj.error === 'string') {
+ extractedMessage = errorObj.error;
+ } else if (
+ typeof errorObj.error === 'object' &&
+ errorObj.error !== null &&
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ typeof (errorObj.error as Record<string, any>).error === 'string'
+ ) {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ extractedMessage = (errorObj.error as Record<string, any>).error;
+ } else if (typeof errorObj.message === 'string') {
+ extractedMessage = errorObj.message;
+ }
+
+ if (extractedMessage.includes('Please provide an API key')) {
+ extractedMessage = extractedMessage.replace(
+ 'via credentials or GOOGLE_AI_API_KEY environment variable',
+ 'via the Vault page',
+ );
+ }
+ }
+
+ // Handle string error
+
+ return extractedMessage;
+};
+
+export const dataPoolClient = {
+ /**
+ * Fetch all namespaces
+ */
+ listNamespaces: async (params?: {
+ page?: number;
+ limit?: number;
+ }): Promise<ListNamespacesResponse> => {
+ try {
+ const queryParams = new URLSearchParams();
+ if (params?.page) queryParams.set('page', params.page.toString());
+ if (params?.limit) queryParams.set('limit', params.limit.toString());
+
+ const url = `/api/page/datapool/namespaces${queryParams.toString() ? `?${queryParams.toString()}` : ''}`;
+
+ const response = await fetch(url, {
+ method: 'GET',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}));
+ throw errorData;
+ }
+
+ const result = await response.json();
+ return result;
+ } catch (error) {
+ if (error instanceof Error) {
+ throw error;
+ }
+ throw new Error(extractErrorMessage(error, 'Failed to create namespace'));
+ }
+ },
+
+ /**
+ * Create a new namespace
+ */
+ createNamespace: async (data: CreateNamespaceRequest): Promise<Namespace> => {
+ try {
+ const response = await fetch('/api/page/datapool/namespaces', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(data),
+ });
+
+ if (!response.ok) {
+ let errorData;
+ try {
+ errorData = await response.json();
+ } catch {
+ throw new Error('Failed to create namespace. Server returned an invalid response.');
+ }
+
+ const errorMessage = extractErrorMessage(errorData, 'Failed to create namespace');
+ throw new Error(errorMessage);
+ }
+
+ const result: CreateNamespaceResponse = await response.json();
+ return result.namespace;
+ } catch (error) {
+ if (error instanceof Error) {
+ throw error;
+ }
+ throw new Error(extractErrorMessage(error, 'Failed to create namespace'));
+ }
+ },
+
+ /**
+ * Fetch all available embedding models
+ */
+ listEmbeddingModels: async (): Promise<EmbeddingModel[]> => {
+ try {
+ const response = await fetch('/api/page/datapool/embeddings/models', {
+ method: 'GET',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}));
+ throw errorData;
+ }
+
+ const result = await response.json();
+ return result.models || [];
+ } catch (error) {
+ if (error instanceof Error) {
+ throw error;
+ }
+ throw new Error(extractErrorMessage(error, 'Failed to fetch embedding models'));
+ }
+ },
+
+ /**
+ * Delete a namespace
+ */
+ deleteNamespace: async (label: string): Promise<void> => {
+ try {
+ const response = await fetch(`/api/page/datapool/namespaces/${encodeURIComponent(label)}`, {
+ method: 'DELETE',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}));
+ const errorMessage = extractErrorMessage(errorData, 'Failed to delete namespace');
+ throw new Error(errorMessage);
+ }
+ } catch (error) {
+ if (error instanceof Error) {
+ throw error;
+ }
+ throw new Error('Failed to delete namespace');
+ }
+ },
+};
diff --git a/packages/app/src/react/features/data-pool/client/datasource.client.ts b/packages/app/src/react/features/data-pool/client/datasource.client.ts
new file mode 100644
index 00000000..53d99adf
--- /dev/null
+++ b/packages/app/src/react/features/data-pool/client/datasource.client.ts
@@ -0,0 +1,119 @@
+/**
+ * Datasource API Client
+ *
+ * Handles all datasource-related API calls
+ */
+
+import type {
+ CreateDatasourceRequest,
+ CreateDatasourceResponse,
+ Datasource,
+ ListDatasourcesResponse,
+} from '../types/datasource.types';
+import { extractErrorMessage } from './datapool.client';
+
+export const datasourceClient = {
+ /**
+ * List all datasources for a namespace
+ */
+ listDatasources: async (namespaceLabel: string): Promise<Datasource[]> => {
+ try {
+ const response = await fetch(
+ `/api/page/datapool/namespaces/${encodeURIComponent(namespaceLabel)}/datasources`,
+ {
+ method: 'GET',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ },
+ );
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}));
+ const errorMessage = extractErrorMessage(errorData, 'Failed to fetch datasources');
+ throw new Error(errorMessage);
+ }
+
+ const result: ListDatasourcesResponse = await response.json();
+ return result.datasources || [];
+ } catch (error) {
+ if (error instanceof Error) {
+ throw error;
+ }
+ throw new Error('Failed to fetch datasources');
+ }
+ },
+
+ /**
+ * Create a new datasource
+ */
+ createDatasource: async (
+ namespaceLabel: string,
+ request: CreateDatasourceRequest,
+ ): Promise<Datasource> => {
+ try {
+ const formData = new FormData();
+ formData.append('datasourceLabel', request.datasourceLabel);
+ formData.append('file', request.file);
+
+ if (request.chunkSize !== undefined) {
+ formData.append('chunkSize', String(request.chunkSize));
+ }
+ if (request.chunkOverlap !== undefined) {
+ formData.append('chunkOverlap', String(request.chunkOverlap));
+ }
+ if (request.metadata !== undefined) {
+ formData.append('metadata', JSON.stringify(request.metadata));
+ }
+
+ const response = await fetch(
+ `/api/page/datapool/namespaces/${encodeURIComponent(namespaceLabel)}/datasources`,
+ {
+ method: 'POST',
+ body: formData,
+ },
+ );
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}));
+ throw errorData;
+ }
+
+ const result: CreateDatasourceResponse = await response.json();
+ return result.datasource;
+ } catch (error) {
+ if (error instanceof Error) {
+ throw error;
+ }
+ throw new Error(extractErrorMessage(error, 'Failed to create datasource'));
+ }
+ },
+
+ /**
+ * Delete a datasource
+ */
+ deleteDatasource: async (namespaceLabel: string, datasourceId: string): Promise<void> => {
+ try {
+ const response = await fetch(
+ `/api/page/datapool/namespaces/${encodeURIComponent(namespaceLabel)}/datasources/${encodeURIComponent(datasourceId)}`,
+ {
+ method: 'DELETE',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ },
+ );
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}));
+ const errorMessage = extractErrorMessage(errorData, 'Failed to delete datasource');
+ throw new Error(errorMessage);
+ }
+ } catch (error) {
+ if (error instanceof Error) {
+ throw error;
+ }
+ throw new Error('Failed to delete datasource');
+ }
+ },
+};
diff --git a/packages/app/src/react/features/data-pool/components/CreateNamespaceModal.tsx b/packages/app/src/react/features/data-pool/components/CreateNamespaceModal.tsx
new file mode 100644
index 00000000..eb8f3174
--- /dev/null
+++ b/packages/app/src/react/features/data-pool/components/CreateNamespaceModal.tsx
@@ -0,0 +1,392 @@
+/**
+ * Create Namespace Modal
+ *
+ * Modal for creating a new data space/namespace
+ */
+
+import {
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@src/react/shared/components/ui/dialog';
+import { Input } from '@src/react/shared/components/ui/input';
+import { Button as CustomButton } from '@src/react/shared/components/ui/newDesign/button';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@src/react/shared/components/ui/select';
+import { errorToast, successToast } from '@src/shared/components/toast';
+import { PlusCircle } from 'lucide-react';
+import { ChangeEvent, FC, useEffect, useState } from 'react';
+import {
+ CreateCredentialsModal
+} from '../../credentials/components/create-credentials.modal';
+import credentialsSchema from '../../credentials/credentials-schema.json';
+import { dataPoolClient } from '../client/datapool.client';
+import { useDataPoolContext } from '../contexts/data-pool.context';
+import type { EmbeddingModel } from '../types';
+
+interface CreateNamespaceModalProps {
+ isOpen: boolean;
+ onClose: () => void;
+ onSuccess: () => void;
+}
+
+interface ProviderSchema {
+ id: string;
+ name: string;
+ logo_url?: string;
+}
+
+export const CreateNamespaceModal: FC<CreateNamespaceModalProps> = ({
+ isOpen,
+ onClose,
+ onSuccess,
+}) => {
+ const { credentials, credentialsLoading, getCredentialById, refetchCredentials } = useDataPoolContext();
+ const [name, setName] = useState('');
+ const [selectedCredentialId, setSelectedCredentialId] = useState('');
+ const [embeddingModels, setEmbeddingModels] = useState<EmbeddingModel[]>([]);
+ const [selectedModelId, setSelectedModelId] = useState('');
+ const [dimensions, setDimensions] = useState<string>('');
+ const [isCreating, setIsCreating] = useState(false);
+ const [isLoadingModels, setIsLoadingModels] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ // State for Create Credentials Modal
+ const [isCreateCredModalOpen, setIsCreateCredModalOpen] = useState(false);
+
+ /**
+ * Get provider logo URL from schema
+ */
+ const getProviderLogo = (providerId: string): string | undefined => {
+ const provider = (credentialsSchema as ProviderSchema[]).find((p) => p.id === providerId);
+ return provider?.logo_url;
+ };
+
+ // Fetch embedding models when modal opens
+ useEffect(() => {
+ const fetchEmbeddingModels = async () => {
+ if (isOpen && embeddingModels.length === 0) {
+ setIsLoadingModels(true);
+ try {
+ const models = await dataPoolClient.listEmbeddingModels();
+ setEmbeddingModels(models);
+ // Pre-select first model if available
+ if (models.length > 0) {
+ setSelectedModelId(models[0].model);
+ }
+ } catch {
+ // Silently fail - user will see empty dropdown
+ } finally {
+ setIsLoadingModels(false);
+ }
+ }
+ };
+
+ fetchEmbeddingModels();
+ }, [isOpen, embeddingModels.length]);
+
+ // Reset form when modal opens/closes
+ useEffect(() => {
+ if (isOpen) {
+ setName('');
+ setSelectedCredentialId('');
+ setDimensions('');
+ setError(null);
+ }
+ }, [isOpen]);
+
+ /**
+ * Handle create namespace
+ */
+ const handleCreate = async () => {
+ // Validation
+ if (!name.trim()) {
+ setError('Please enter a name for the data space');
+ return;
+ }
+
+ if (!selectedCredentialId) {
+ setError('Please select a vector database provider');
+ return;
+ }
+
+ setIsCreating(true);
+ setError(null);
+
+ try {
+ // Prepare embeddings config
+ const embeddingsConfig = selectedModelId
+ ? {
+ modelId: selectedModelId,
+ dimensions: dimensions ? parseInt(dimensions, 10) : undefined,
+ }
+ : undefined;
+
+ await dataPoolClient.createNamespace({
+ label: name.trim(),
+ credentialId: selectedCredentialId,
+ embeddings: embeddingsConfig,
+ });
+
+ successToast('Data space created successfully');
+ onSuccess();
+ onClose();
+ } catch (err: any) {
+ const errorMessage = err?.message || 'Failed to create data space. Please try again.';
+ setError(errorMessage);
+ errorToast(errorMessage);
+ } finally {
+ setIsCreating(false);
+ }
+ };
+
+ /**
+ * Handle credential selection change
+ */
+ const handleCredentialChange = (value: string) => {
+ // If "create_new" is selected, open the create credentials modal
+ if (value === '__create_new__') {
+ setIsCreateCredModalOpen(true);
+ return;
+ }
+
+ setSelectedCredentialId(value);
+ setError(null);
+ };
+
+ /**
+ * Handle successful credential creation
+ */
+ const handleCredentialCreated = (data: {
+ id?: string;
+ name: string;
+ provider: string;
+ credentials: Record<string, string>;
+ isEdit: boolean;
+ }) => {
+ // Close the create credentials modal
+ setIsCreateCredModalOpen(false);
+
+ // Refetch credentials to get the new one
+ refetchCredentials();
+
+ // Auto-select the newly created credential
+ if (data.id) {
+ setSelectedCredentialId(data.id);
+ successToast('Connection created successfully. You can now use it.');
+ }
+ };
+
+ /**
+ * Handle name input change
+ */
+ const handleNameChange = (e: ChangeEvent<HTMLInputElement>) => {
+ setName(e.target.value);
+ setError(null);
+ };
+
+ const isFormValid = name.trim() !== '' && selectedCredentialId !== '' && selectedModelId !== '';
+
+ return (
+ <>
+ <Dialog
+ open={isOpen} onOpenChange={onClose}>
+ <DialogContent className={'sm:max-w-[500px] max-h-[90vh] overflow-y-auto'}>
+ <DialogHeader>
+ <DialogTitle>Create Data Space</DialogTitle>
+ <p className="text-sm text-gray-600 mt-1">
+ Set up a Data Space to unlock your agents' ability to search, automate, and learn
+ from your data — using RAG and other tools
+ </p>
+ </DialogHeader>
+
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ handleCreate();
+ }}
+ >
+ <div className="grid gap-4 py-4">
+ {/* Provider Selection */}
+ <div className="space-y-2">
+ <label className="text-gray-700 mb-1 text-sm font-normal flex items-center">
+ Vector Database Provider <span className="text-red-500 ml-1">*</span>
+ </label>
+ <Select
+ value={selectedCredentialId}
+ onValueChange={handleCredentialChange}
+ disabled={credentialsLoading || isCreating}
+ >
+ <SelectTrigger className="w-full" disabled={credentialsLoading || isCreating}>
+ <SelectValue placeholder="Select a provider">
+ {selectedCredentialId && (() => {
+ const selectedCred = getCredentialById(selectedCredentialId);
+ const logo = selectedCred ? getProviderLogo(selectedCred.provider) : undefined;
+ return (
+ <div className="flex items-center gap-2">
+ {logo && (
+ <img
+ src={logo}
+ alt={selectedCred?.name || 'Provider'}
+ className="w-5 h-5 object-contain"
+ />
+ )}
+ <span>{selectedCred?.name}</span>
+ </div>
+ );
+ })()}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {/* Create New Connection Option */}
+ <SelectItem value="__create_new__">
+ <div className="flex items-center gap-2 text-blue-600 font-medium">
+ <PlusCircle className="w-4 h-4" />
+ <span>Create New Connection</span>
+ </div>
+ </SelectItem>
+
+ {/* Separator */}
+ {credentials.length > 0 && (
+ <div className="border-t border-gray-200 my-1" />
+ )}
+
+ {/* Existing Credentials */}
+ {credentials.length === 0 ? (
+ <div className="px-2 py-1.5 text-sm text-muted-foreground">
+ No connections found
+ </div>
+ ) : (
+ credentials.map((cred) => {
+ const logo = getProviderLogo(cred.provider);
+ return (
+ <SelectItem key={cred.id} value={cred.id}>
+ <div className="flex items-center gap-2">
+ {logo && (
+ <img
+ src={logo}
+ alt={cred.name}
+ className="w-5 h-5 object-contain"
+ />
+ )}
+ <span>{cred.name}</span>
+ </div>
+ </SelectItem>
+ );
+ })
+ )}
+ </SelectContent>
+ </Select>
+ </div>
+
+ {/* Name Input */}
+ <div className="space-y-2">
+ <Input
+ label="Name"
+ required
+ fullWidth
+ type="text"
+ placeholder="Name your data space"
+ value={name}
+ onChange={handleNameChange}
+ disabled={isCreating}
+ error={!!error}
+ errorMessage={error || undefined}
+ />
+ </div>
+
+ {/* Embedding Model Selection and Dimensions - Side by Side */}
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ {/* Embedding Model Selection */}
+ <div className="space-y-2">
+ <label className="text-gray-700 mb-1 text-sm font-normal flex items-center">
+ Embedding Model <span className="text-red-500 ml-1">*</span>
+ </label>
+ <Select
+ value={selectedModelId}
+ onValueChange={setSelectedModelId}
+ disabled={isLoadingModels || isCreating}
+ >
+ <SelectTrigger className="w-full" disabled={isLoadingModels || isCreating}>
+ <SelectValue placeholder="Select an embedding model" />
+ </SelectTrigger>
+ <SelectContent>
+ {isLoadingModels ? (
+ <div className="px-2 py-1.5 text-sm text-muted-foreground">
+ Loading models...
+ </div>
+ ) : embeddingModels.length === 0 ? (
+ <div className="px-2 py-1.5 text-sm text-muted-foreground">
+ No models available
+ </div>
+ ) : (
+ embeddingModels.map((model) => (
+ <SelectItem key={model.model} value={model.model}>
+ {model.label}
+ </SelectItem>
+ ))
+ )}
+ </SelectContent>
+ </Select>
+ </div>
+
+ {/* Dimensions Input */}
+ <div className="space-y-2">
+ <label className="text-gray-700 mb-1 text-sm font-normal flex items-center">
+ Vector Dimensions
+ </label>
+ <input
+ type="number"
+ placeholder="e.g., 1536 (optional)"
+ value={dimensions}
+ onChange={(e: ChangeEvent<HTMLInputElement>) => setDimensions(e.target.value)}
+ disabled={isCreating}
+ className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-100 disabled:cursor-not-allowed text-sm"
+ />
+ <p className="text-xs text-gray-500">
+ Leave empty for default
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <DialogFooter>
+ <CustomButton
+ variant="secondary"
+ type="button"
+ label="Cancel"
+ handleClick={onClose}
+ disabled={isCreating}
+ />
+ <CustomButton
+ variant="primary"
+ type="submit"
+ label={isCreating ? 'Creating...' : 'Create'}
+ disabled={!isFormValid || isCreating || credentialsLoading || isLoadingModels}
+ loading={isCreating}
+ />
+ </DialogFooter>
+ </form>
+ </DialogContent>
+
+
+ </Dialog>
+
+ {/* Create Credentials Modal */}
+ <CreateCredentialsModal
+ isOpen={isCreateCredModalOpen}
+ onClose={() => setIsCreateCredModalOpen(false)}
+ onSuccess={handleCredentialCreated}
+ group="vector_db_creds"
+ />
+ </>
+ );
+};
+
diff --git a/packages/app/src/react/features/data-pool/components/DatasourcesTable.tsx b/packages/app/src/react/features/data-pool/components/DatasourcesTable.tsx
new file mode 100644
index 00000000..e8bf4354
--- /dev/null
+++ b/packages/app/src/react/features/data-pool/components/DatasourcesTable.tsx
@@ -0,0 +1,115 @@
+/**
+ * Datasources Table Component
+ *
+ * Displays datasources in a table with actions
+ */
+
+import { Button } from '@src/react/shared/components/ui/button';
+import { Tooltip } from 'flowbite-react';
+import { Eye, FileText, Trash2 } from 'lucide-react';
+import { FC } from 'react';
+import type { Datasource } from '../types/datasource.types';
+
+interface DatasourcesTableProps {
+ datasources: Datasource[];
+ onDelete: (datasource: Datasource) => void;
+ onView: (datasource: Datasource) => void;
+}
+
+export const DatasourcesTable: FC<DatasourcesTableProps> = ({ datasources, onDelete, onView }) => {
+ const formatSize = (sizeMb: number | undefined): string => {
+ if (!sizeMb) return '0 B';
+
+ if (sizeMb < 0.001) {
+ // Less than 1 KB, show in Bytes
+ return `${Math.round(sizeMb * 1024 * 1024)} B`;
+ } else if (sizeMb < 1) {
+ // Less than 1 MB, show in KB
+ return `${(sizeMb * 1024).toFixed(2)} KB`;
+ } else {
+ // Show in MB
+ return `${sizeMb.toFixed(2)} MB`;
+ }
+ };
+
+ const formatDate = (dateString: Date | string | undefined): string => {
+ if (!dateString) return 'N/A';
+ try {
+ const date = new Date(dateString);
+ return date.toLocaleDateString('en-US', {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ });
+ } catch {
+ return String(dateString);
+ }
+ };
+
+ const getFileIcon = () => {
+ return <FileText className="w-5 h-5 text-blue-600" />;
+ };
+
+ return (
+ <div className="overflow-x-auto">
+ <table className="w-full min-w-[600px] text-sm text-left">
+ <thead className="text-xs text-gray-500 uppercase bg-gray-50 border-b">
+ <tr>
+ <th className="px-6 py-3">Name</th>
+ <th className="px-6 py-3">Size</th>
+ <th className="px-6 py-3">Created</th>
+ <th className="px-6 py-3 text-center">Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ {datasources.map((datasource) => (
+ <tr key={datasource.id} className="border-b hover:bg-gray-50">
+ {/* Name */}
+ <td className="px-6 py-4 font-medium text-gray-900" title={datasource.name}>
+ <div className="flex items-center gap-2">
+ {getFileIcon()}
+ <span>{datasource.name}</span>
+ </div>
+ </td>
+
+
+
+ {/* Size */}
+ <td className="px-6 py-4 text-gray-700">{formatSize(datasource.datasourceSizeMb)}</td>
+
+ {/* Created */}
+ <td className="px-6 py-4 text-gray-700">{formatDate(datasource.createdAt)}</td>
+
+ {/* Actions */}
+ <td className="px-6 py-4">
+ <div className="flex items-center justify-center gap-2">
+ <Tooltip content="View Details">
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => onView(datasource)}
+ className="hover:text-blue-500"
+ >
+ <Eye className="h-4 w-4" />
+ </Button>
+ </Tooltip>
+ <Tooltip content="Delete">
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => onDelete(datasource)}
+ className="hover:text-red-500"
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ </Tooltip>
+ </div>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ );
+};
+
diff --git a/packages/app/src/react/features/data-pool/components/DeleteDatasourceDialog.tsx b/packages/app/src/react/features/data-pool/components/DeleteDatasourceDialog.tsx
new file mode 100644
index 00000000..e9dc31c6
--- /dev/null
+++ b/packages/app/src/react/features/data-pool/components/DeleteDatasourceDialog.tsx
@@ -0,0 +1,121 @@
+/**
+ * Delete Datasource Confirmation Dialog
+ *
+ * Requires user to type datasource label to confirm deletion
+ */
+
+import {
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@src/react/shared/components/ui/dialog';
+import { Input } from '@src/react/shared/components/ui/input';
+import { Button as CustomButton } from '@src/react/shared/components/ui/newDesign/button';
+import { ChangeEvent, FC, useEffect, useState } from 'react';
+
+interface DeleteDatasourceDialogProps {
+ isOpen: boolean;
+ datasourceName: string;
+ onClose: () => void;
+ onConfirm: () => Promise<void>;
+}
+
+export const DeleteDatasourceDialog: FC<DeleteDatasourceDialogProps> = ({
+ isOpen,
+ datasourceName,
+ onClose,
+ onConfirm,
+}) => {
+ const [confirmText, setConfirmText] = useState<string>('');
+ const [isDeleting, setIsDeleting] = useState<boolean>(false);
+ const [error, setError] = useState<string | null>(null);
+
+ // Reset state when dialog opens/closes
+ useEffect(() => {
+ if (isOpen) {
+ setConfirmText('');
+ setError(null);
+ setIsDeleting(false);
+ }
+ }, [isOpen]);
+
+ const handleConfirmTextChange = (e: ChangeEvent<HTMLInputElement>) => {
+ setConfirmText(e.target.value);
+ setError(null);
+ };
+
+ const handleConfirm = async () => {
+ if (confirmText !== datasourceName) {
+ setError('Datasource name does not match');
+ return;
+ }
+
+ setIsDeleting(true);
+ try {
+ await onConfirm();
+ onClose();
+ } catch {
+ // Error handling is done in parent component
+ setIsDeleting(false);
+ }
+ };
+
+ const isValid = confirmText === datasourceName;
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onClose}>
+ <DialogContent className="sm:max-w-[500px]">
+ <DialogHeader>
+ <DialogTitle>Delete Datasource</DialogTitle>
+ </DialogHeader>
+
+ <div className="py-4 space-y-4">
+ <div className="bg-red-50 border border-red-200 rounded-md p-4">
+ <p className="text-sm text-red-800">
+ <strong>Warning:</strong> This action cannot be undone. This will permanently delete
+ the datasource and all associated data from the vector database.
+ </p>
+ </div>
+
+ <div className="space-y-2">
+ <p className="text-sm text-gray-700">
+ Please type <strong className="font-semibold text-gray-900">{datasourceName}</strong>{' '}
+ to confirm deletion.
+ </p>
+ <Input
+ fullWidth
+ type="text"
+ placeholder="Type datasource name"
+ value={confirmText}
+ onChange={handleConfirmTextChange}
+ disabled={isDeleting}
+ error={!!error}
+ errorMessage={error || undefined}
+ autoFocus
+ />
+ </div>
+ </div>
+
+ <DialogFooter>
+ <CustomButton
+ variant="secondary"
+ label="Cancel"
+ handleClick={onClose}
+ disabled={isDeleting}
+ />
+ <CustomButton
+ variant="primary"
+ label={isDeleting ? 'Deleting...' : 'Delete Datasource'}
+ handleClick={handleConfirm}
+ disabled={!isValid || isDeleting}
+ loading={isDeleting}
+ className="bg-red-600 hover:bg-red-700 text-white disabled:bg-gray-100 disabled:hover:bg-gray-100 disabled:text-gray-500"
+ />
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
diff --git a/packages/app/src/react/features/data-pool/components/DeleteNamespaceDialog.tsx b/packages/app/src/react/features/data-pool/components/DeleteNamespaceDialog.tsx
new file mode 100644
index 00000000..28174a22
--- /dev/null
+++ b/packages/app/src/react/features/data-pool/components/DeleteNamespaceDialog.tsx
@@ -0,0 +1,122 @@
+/**
+ * Delete Namespace Confirmation Dialog
+ *
+ * Requires user to type namespace label to confirm deletion
+ */
+
+import {
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@src/react/shared/components/ui/dialog';
+import { Input } from '@src/react/shared/components/ui/input';
+import { Button as CustomButton } from '@src/react/shared/components/ui/newDesign/button';
+import { ChangeEvent, FC, useEffect, useState } from 'react';
+
+interface DeleteNamespaceDialogProps {
+ isOpen: boolean;
+ namespaceName: string;
+ onClose: () => void;
+ onConfirm: () => Promise<void>;
+}
+
+export const DeleteNamespaceDialog: FC<DeleteNamespaceDialogProps> = ({
+ isOpen,
+ namespaceName,
+ onClose,
+ onConfirm,
+}) => {
+ const [confirmText, setConfirmText] = useState<string>('');
+ const [isDeleting, setIsDeleting] = useState<boolean>(false);
+ const [error, setError] = useState<string | null>(null);
+
+ // Reset state when dialog opens/closes
+ useEffect(() => {
+ if (isOpen) {
+ setConfirmText('');
+ setError(null);
+ setIsDeleting(false);
+ }
+ }, [isOpen]);
+
+ const handleConfirmTextChange = (e: ChangeEvent<HTMLInputElement>) => {
+ setConfirmText(e.target.value);
+ setError(null);
+ };
+
+ const handleConfirm = async () => {
+ if (confirmText !== namespaceName) {
+ setError('Data space name does not match');
+ return;
+ }
+
+ setIsDeleting(true);
+ try {
+ await onConfirm();
+ onClose();
+ } catch {
+ // Error handling is done in parent component
+ setIsDeleting(false);
+ }
+ };
+
+ const isValid = confirmText === namespaceName;
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onClose}>
+ <DialogContent className="sm:max-w-[500px]">
+ <DialogHeader>
+ <DialogTitle>Delete Data Space</DialogTitle>
+ </DialogHeader>
+
+ <div className="py-4 space-y-4">
+ <div className="bg-red-50 border border-red-200 rounded-md p-4">
+ <p className="text-sm text-red-800">
+ <strong>Warning:</strong> This action cannot be undone. This will permanently delete
+ the data space and all associated data.
+ </p>
+ </div>
+
+ <div className="space-y-2">
+ <p className="text-sm text-gray-700">
+ Please type <strong className="font-semibold text-gray-900">{namespaceName}</strong>{' '}
+ to confirm deletion.
+ </p>
+ <Input
+ fullWidth
+ type="text"
+ placeholder="Type data space name"
+ value={confirmText}
+ onChange={handleConfirmTextChange}
+ disabled={isDeleting}
+ error={!!error}
+ errorMessage={error || undefined}
+ autoFocus
+ />
+ </div>
+ </div>
+
+ <DialogFooter>
+ <CustomButton
+ variant="secondary"
+ label="Cancel"
+ handleClick={onClose}
+ disabled={isDeleting}
+ />
+ <CustomButton
+ variant="primary"
+ label={isDeleting ? 'Deleting...' : 'Delete Data Space'}
+ handleClick={handleConfirm}
+ disabled={!isValid || isDeleting}
+ loading={isDeleting}
+ // when not disabled (only when not disabled!!)
+ className="bg-red-600 hover:bg-red-700 text-white disabled:bg-gray-100 disabled:hover:bg-gray-100 disabled:text-gray-500"
+ />
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
diff --git a/packages/app/src/react/features/data-pool/components/FreePlanUpgradePrompt.tsx b/packages/app/src/react/features/data-pool/components/FreePlanUpgradePrompt.tsx
new file mode 100644
index 00000000..79eb6b8d
--- /dev/null
+++ b/packages/app/src/react/features/data-pool/components/FreePlanUpgradePrompt.tsx
@@ -0,0 +1,68 @@
+/**
+ * Free Plan Upgrade Prompt
+ *
+ * Shows upgrade prompt for free plan users
+ */
+
+import { Button as CustomButton } from '@src/react/shared/components/ui/newDesign/button';
+import { FC } from 'react';
+
+interface FreePlanUpgradePromptProps {
+ namespaceName: string;
+ onUpgrade: () => void;
+}
+
+export const FreePlanUpgradePrompt: FC<FreePlanUpgradePromptProps> = ({
+ namespaceName,
+ onUpgrade,
+}) => {
+ return (
+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
+ <div className="relative bg-white rounded-lg shadow-lg w-full max-w-md mx-4 p-6">
+ <div className="mb-4">
+ <div className="inline-block px-3 py-1 mb-3 text-xs font-medium text-blue-600 bg-blue-50 rounded-full">
+ Free Users
+ </div>
+ <h2 className="text-xl font-semibold text-gray-900 mb-2">Create Data Space</h2>
+ </div>
+
+ {/* Provider */}
+ <div className="mb-4">
+ <label className="block text-sm font-medium text-gray-700 mb-1">Provider</label>
+ <div className="px-4 py-2 bg-gray-50 border border-gray-300 rounded-md text-gray-900">
+ Default
+ </div>
+ </div>
+
+ {/* Name */}
+ <div className="mb-6">
+ <label className="block text-sm font-medium text-gray-700 mb-1">Name</label>
+ <div className="px-4 py-2 bg-gray-50 border border-gray-300 rounded-md text-gray-900">
+ {namespaceName}
+ </div>
+ </div>
+
+ {/* Action Buttons */}
+ <div className="flex items-center gap-3">
+ <CustomButton
+ variant="secondary"
+ label="Basic (Limited features)"
+ className="flex-1"
+ disabled
+ />
+ <CustomButton
+ label="Upgrade to Startup"
+ handleClick={onUpgrade}
+ className="flex-1"
+ />
+ </div>
+
+ <p className="text-xs text-gray-600 text-center mt-4">
+ Without upgrading to startup, you will be unable to use RAG applications and other
+ advance features.
+ </p>
+ </div>
+ </div>
+ );
+};
+
diff --git a/packages/app/src/react/features/data-pool/components/NamespaceTable.tsx b/packages/app/src/react/features/data-pool/components/NamespaceTable.tsx
new file mode 100644
index 00000000..1d95953b
--- /dev/null
+++ b/packages/app/src/react/features/data-pool/components/NamespaceTable.tsx
@@ -0,0 +1,166 @@
+/**
+ * Namespace Table Component
+ *
+ * Displays namespaces in a table with actions
+ */
+
+import { Button } from '@src/react/shared/components/ui/button';
+import { Tooltip } from 'flowbite-react';
+import { FilePlus, Sparkles, Trash2 } from 'lucide-react';
+import { FC, useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import credentialsSchema from '../../credentials/credentials-schema.json';
+import { useDataPoolContext } from '../contexts/data-pool.context';
+import type { NamespaceWithProvider } from '../types';
+import { UploadDatasourceDialog } from './UploadDatasourceDialog';
+
+interface NamespaceTableProps {
+ namespaces: NamespaceWithProvider[];
+ onDelete: (namespace: NamespaceWithProvider) => void;
+}
+
+interface ProviderSchema {
+ id: string;
+ name: string;
+ logo_url?: string;
+}
+
+export const NamespaceTable: FC<NamespaceTableProps> = ({ namespaces, onDelete }) => {
+ const { getCredentialById } = useDataPoolContext();
+ const navigate = useNavigate();
+ const [uploadDialogNamespace, setUploadDialogNamespace] = useState<string | null>(null);
+
+ /**
+ * Get provider logo URL from schema
+ */
+ const getProviderLogo = (providerId: string): string | undefined => {
+ const provider = (credentialsSchema as ProviderSchema[]).find((p) => p.id === providerId);
+ return provider?.logo_url;
+ };
+
+ return (
+ <div className="overflow-x-auto overflow-y-hidden">
+ <table className="w-full min-w-[600px] text-sm text-left">
+ <thead className="text-xs text-gray-500 uppercase bg-gray-50 border-b">
+ <tr>
+ <th className="px-6 py-3">Data Space Name</th>
+ <th className="px-6 py-3">Provider</th>
+ <th className="px-6 py-3 text-center">Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ {namespaces.map((namespace) => {
+ const credential = getCredentialById(namespace.credentialId);
+ const providerLogo = credential ? getProviderLogo(credential.provider) : undefined;
+
+ // Format model name for display (truncate if too long)
+ const getShortModelName = (modelId: string) => {
+ const maxLength = 20;
+ if (modelId.length > maxLength) {
+ return modelId.substring(0, maxLength) + '...';
+ }
+ return modelId;
+ };
+
+ return (
+ <tr
+ key={namespace.label}
+ className="border-b hover:bg-gray-100 cursor-pointer transition-colors text-left"
+ onClick={() =>
+ navigate(`/data-pool/${encodeURIComponent(namespace.label)}/datasources`)
+ }
+ >
+ {/* Name with Embeddings Badge */}
+ <td className="px-6 py-4 cursor-pointer" title={namespace.label}>
+ <div className="flex items-center gap-2 flex-wrap min-h-0">
+ <span className="font-medium text-gray-900 hover:underline truncate">
+ {namespace.label}
+ </span>
+ {namespace.embeddings && (
+ <div
+ onClick={(e) => e.stopPropagation()}
+ className="shrink-0"
+ title={`${namespace.embeddings.modelId}${namespace.embeddings.dimensions ? ` · ${namespace.embeddings.dimensions} dimensions` : ''}`}
+ >
+ <div className="inline-flex items-center gap-1 px-2 py-0.5 bg-purple-50 border border-purple-200 rounded-md text-purple-700 hover:bg-purple-100 transition-colors">
+ <Sparkles className="h-3 w-3 shrink-0" />
+ <span className="text-xs font-medium hidden sm:inline">
+ {getShortModelName(namespace.embeddings.modelId)}
+ </span>
+ {namespace.embeddings.dimensions && (
+ <span className="text-xs text-purple-500">
+ <span className="hidden sm:inline">· </span>
+ {namespace.embeddings.dimensions}d
+ </span>
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ </td>
+
+ {/* Provider */}
+ <td className="px-6 py-4 text-gray-700">
+ <div className="flex items-center gap-2">
+ {providerLogo && (
+ <img
+ src={providerLogo}
+ alt={credential?.name || 'Provider'}
+ className="w-5 h-5 object-contain"
+ />
+ )}
+ <span>{credential?.name || 'Deleted'}</span>
+ </div>
+ </td>
+
+ {/* Actions */}
+ <td
+ className="px-6 py-4"
+ onClick={(e) => {
+ e.stopPropagation();
+ }}
+ >
+ <div className="flex items-center justify-center">
+ <Tooltip content="Add Datasource">
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => setUploadDialogNamespace(namespace.label)}
+ className="hover:text-blue-500"
+ >
+ <FilePlus className="h-4 w-4 text-[#242424] cursor-pointer hover:text-blue-600" />
+ </Button>
+ </Tooltip>
+ <Tooltip content="Delete">
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => onDelete(namespace)}
+ className="hover:text-red-500"
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ </Tooltip>
+ </div>
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+
+ {/* Upload Datasource Dialog */}
+ {uploadDialogNamespace && (
+ <UploadDatasourceDialog
+ isOpen={!!uploadDialogNamespace}
+ namespaceLabel={uploadDialogNamespace}
+ onClose={() => setUploadDialogNamespace(null)}
+ onSuccess={() => {
+ setUploadDialogNamespace(null);
+ // Optionally show success message
+ }}
+ />
+ )}
+ </div>
+ );
+};
diff --git a/packages/app/src/react/features/data-pool/components/UploadDatasourceDialog.tsx b/packages/app/src/react/features/data-pool/components/UploadDatasourceDialog.tsx
new file mode 100644
index 00000000..41e5f0b1
--- /dev/null
+++ b/packages/app/src/react/features/data-pool/components/UploadDatasourceDialog.tsx
@@ -0,0 +1,449 @@
+/**
+ * Upload Datasource Dialog
+ *
+ * Allows users to upload datasources via file upload or raw text
+ */
+
+import {
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@src/react/shared/components/ui/dialog';
+import { Input } from '@src/react/shared/components/ui/input';
+import { JsonEditor } from '@src/react/shared/components/ui/json-editor';
+import { Button as CustomButton } from '@src/react/shared/components/ui/newDesign/button';
+import { errorToast, successToast } from '@src/shared/components/toast';
+import { FileText, Upload, X } from 'lucide-react';
+import { ChangeEvent, FC, useCallback, useEffect, useState } from 'react';
+import { datasourceClient } from '../client/datasource.client';
+
+interface UploadDatasourceDialogProps {
+ isOpen: boolean;
+ namespaceLabel: string;
+ onClose: () => void;
+ onSuccess: () => void;
+}
+
+type UploadMode = 'file' | 'text';
+
+export const UploadDatasourceDialog: FC<UploadDatasourceDialogProps> = ({
+ isOpen,
+ namespaceLabel,
+ onClose,
+ onSuccess,
+}) => {
+ const [mode, setMode] = useState<UploadMode>('file');
+ const [datasourceLabel, setDatasourceLabel] = useState<string>('');
+ const [file, setFile] = useState<File | null>(null);
+ const [rawText, setRawText] = useState<string>('');
+ const [chunkSize, setChunkSize] = useState<string>('');
+ const [chunkOverlap, setChunkOverlap] = useState<string>('');
+ const [metadata, setMetadata] = useState<string>('');
+ const [isDragging, setIsDragging] = useState<boolean>(false);
+ const [isUploading, setIsUploading] = useState<boolean>(false);
+ const [error, setError] = useState<string | null>(null);
+
+ // Reset state when dialog opens/closes
+ useEffect(() => {
+ if (isOpen) {
+ setMode('file');
+ setDatasourceLabel('');
+ setFile(null);
+ setRawText('');
+ setChunkSize('');
+ setChunkOverlap('');
+ setMetadata('');
+ setIsDragging(false);
+ setIsUploading(false);
+ setError(null);
+ }
+ }, [isOpen]);
+
+ const handleDragOver = useCallback((e: React.DragEvent) => {
+ e.preventDefault();
+ setIsDragging(true);
+ }, []);
+
+ const handleDragLeave = useCallback((e: React.DragEvent) => {
+ e.preventDefault();
+ setIsDragging(false);
+ }, []);
+
+ const handleDrop = useCallback((e: React.DragEvent) => {
+ e.preventDefault();
+ setIsDragging(false);
+
+ const droppedFile = e.dataTransfer.files[0];
+ if (droppedFile) {
+ validateAndSetFile(droppedFile);
+ }
+ }, []);
+
+ const validateAndSetFile = (selectedFile: File) => {
+ const allowedTypes = [
+ 'text/plain',
+ 'application/pdf',
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ ];
+ const allowedExtensions = ['.txt', '.pdf', '.docx'];
+ const ext = selectedFile.name.toLowerCase().substring(selectedFile.name.lastIndexOf('.'));
+
+ if (!allowedTypes.includes(selectedFile.type) && !allowedExtensions.includes(ext)) {
+ setError('Only .txt, .pdf, and .docx files are allowed');
+ return;
+ }
+
+ if (selectedFile.size > 10 * 1024 * 1024) {
+ setError('File size must be less than 10MB');
+ return;
+ }
+
+ setFile(selectedFile);
+ setError(null);
+
+ // Auto-populate label if empty
+ if (!datasourceLabel) {
+ const nameWithoutExt = selectedFile.name.substring(0, selectedFile.name.lastIndexOf('.'));
+ setDatasourceLabel(nameWithoutExt);
+ }
+ };
+
+ const handleFileSelect = (e: ChangeEvent<HTMLInputElement>) => {
+ const selectedFile = e.target.files?.[0];
+ if (selectedFile) {
+ validateAndSetFile(selectedFile);
+ }
+ };
+
+ const handleRemoveFile = () => {
+ setFile(null);
+ setError(null);
+ };
+
+ const handleUpload = async () => {
+ if (!datasourceLabel.trim()) {
+ setError('Datasource label is required');
+ return;
+ }
+
+ let fileToUpload: File | null = null;
+
+ if (mode === 'file') {
+ if (!file) {
+ setError('Please select a file');
+ return;
+ }
+ fileToUpload = file;
+ } else {
+ if (!rawText.trim()) {
+ setError('Please enter some text');
+ return;
+ }
+ // Convert raw text to a file
+ const blob = new Blob([rawText], { type: 'text/plain' });
+ fileToUpload = new File([blob], `${datasourceLabel}.txt`, { type: 'text/plain' });
+ }
+
+ // Validate metadata if provided
+ let parsedMetadata: Record<string, unknown> | undefined;
+ if (metadata.trim()) {
+ try {
+ parsedMetadata = JSON.parse(metadata);
+ if (typeof parsedMetadata !== 'object' || parsedMetadata === null) {
+ setError('Metadata must be a valid JSON object');
+ return;
+ }
+ } catch (err) {
+ setError('Invalid JSON in metadata: ' + (err as Error).message);
+ return;
+ }
+ }
+
+ setIsUploading(true);
+ try {
+ const parsedChunkSize = parseInt(chunkSize, 10);
+ const parsedChunkOverlap = parseInt(chunkOverlap, 10);
+
+ await datasourceClient.createDatasource(namespaceLabel, {
+ datasourceLabel: datasourceLabel.trim(),
+ file: fileToUpload,
+ chunkSize: !isNaN(parsedChunkSize) && parsedChunkSize > 0 ? parsedChunkSize : undefined,
+ chunkOverlap: !isNaN(parsedChunkOverlap) && parsedChunkOverlap >= 0 ? parsedChunkOverlap : undefined,
+ metadata: parsedMetadata,
+ });
+ successToast('Datasource uploaded successfully');
+ onSuccess();
+ onClose();
+ } catch (error: unknown) {
+ const errorMessage = (error as Error)?.message || 'Failed to upload datasource';
+ errorToast(errorMessage);
+ setError(errorMessage);
+ } finally {
+ setIsUploading(false);
+ }
+ };
+
+ const formatFileSize = (bytes: number): string => {
+ if (bytes === 0) return '0 Bytes';
+ const k = 1024;
+ const sizes = ['Bytes', 'KB', 'MB', 'GB'];
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
+ return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
+ };
+
+ const isValid =
+ datasourceLabel.trim() !== '' &&
+ (mode === 'file' ? file !== null : rawText.trim() !== '');
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onClose}>
+ <DialogContent className="sm:max-w-[700px] max-h-[90vh] overflow-hidden flex flex-col">
+ <DialogHeader>
+ <DialogTitle>Upload Datasource</DialogTitle>
+ </DialogHeader>
+
+ <div className="flex-1 overflow-y-auto py-4 space-y-4 px-1">
+ {/* Datasource Label */}
+ <div className="space-y-2">
+ <Input
+ label="Datasource Label"
+ required
+ fullWidth
+ type="text"
+ placeholder="Enter a name for your datasource"
+ value={datasourceLabel}
+ onChange={(e: ChangeEvent<HTMLInputElement>) => {
+ setDatasourceLabel(e.target.value);
+ setError(null);
+ }}
+ disabled={isUploading}
+ error={!!error && !datasourceLabel.trim()}
+ />
+ </div>
+
+ {/* Mode Selection */}
+ <div className="flex gap-2">
+ <button
+ type="button"
+ onClick={() => setMode('file')}
+ disabled={isUploading}
+ className={`flex-1 py-3 px-4 rounded-lg border-2 transition-all ${
+ mode === 'file'
+ ? 'border-blue-500 bg-blue-50 text-blue-700'
+ : 'border-gray-200 hover:border-gray-300 text-gray-700'
+ } ${isUploading ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}
+ >
+ <div className="flex flex-col items-center gap-2">
+ <Upload className="w-5 h-5" />
+ <span className="font-medium">Upload File</span>
+ </div>
+ </button>
+ <button
+ type="button"
+ onClick={() => setMode('text')}
+ disabled={isUploading}
+ className={`flex-1 py-3 px-4 rounded-lg border-2 transition-all ${
+ mode === 'text'
+ ? 'border-blue-500 bg-blue-50 text-blue-700'
+ : 'border-gray-200 hover:border-gray-300 text-gray-700'
+ } ${isUploading ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}
+ >
+ <div className="flex flex-col items-center gap-2">
+ <FileText className="w-5 h-5" />
+ <span className="font-medium">Raw Text</span>
+ </div>
+ </button>
+ </div>
+
+ {/* File Upload Mode */}
+ {mode === 'file' && (
+ <div className="space-y-3">
+ {!file ? (
+ <div
+ onDragOver={handleDragOver}
+ onDragLeave={handleDragLeave}
+ onDrop={handleDrop}
+ className={`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${
+ isDragging
+ ? 'border-blue-500 bg-blue-50'
+ : 'border-gray-300 hover:border-gray-400'
+ }`}
+ >
+ <Upload className="w-12 h-12 mx-auto text-gray-400 mb-3" />
+ <p className="text-gray-700 font-medium mb-1">
+ Drag and drop your file here
+ </p>
+ <p className="text-sm text-gray-500 mb-3">or</p>
+ <label className="inline-block">
+ <input
+ type="file"
+ className="hidden"
+ accept=".txt,.pdf,.docx"
+ onChange={handleFileSelect}
+ disabled={isUploading}
+ />
+ <span className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 cursor-pointer inline-block">
+ Browse Files
+ </span>
+ </label>
+ <p className="text-xs text-gray-500 mt-3">
+ Supported formats: .txt, .pdf, .docx (Max 10MB)
+ </p>
+ </div>
+ ) : (
+ <div className="border border-gray-200 rounded-lg p-4 bg-gray-50">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-3 flex-1 min-w-0">
+ <FileText className="w-10 h-10 text-blue-600 flex-shrink-0" />
+ <div className="flex-1 min-w-0">
+ <p className="font-medium text-gray-900 truncate">{file.name}</p>
+ <p className="text-sm text-gray-500">{formatFileSize(file.size)}</p>
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={handleRemoveFile}
+ disabled={isUploading}
+ className="p-1 hover:bg-gray-200 rounded transition-colors"
+ >
+ <X className="w-5 h-5 text-gray-600" />
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Raw Text Mode */}
+ {mode === 'text' && (
+ <div className="space-y-2">
+ <label className="text-gray-700 text-sm font-normal">
+ Text Content <span className="text-red-500">*</span>
+ </label>
+ <textarea
+ value={rawText}
+ onChange={(e) => {
+ setRawText(e.target.value);
+ setError(null);
+ }}
+ disabled={isUploading}
+ placeholder="Paste or type your text content here..."
+ // make font size smaller: font-size-sm
+ className="w-full h-64 px-3 py-2 border text-sm border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-100 disabled:cursor-not-allowed resize-none font-light"
+ />
+ <p className="text-xs text-gray-500">
+ This text will be saved as a .txt file
+ </p>
+ </div>
+ )}
+
+ {/* Advanced Configuration - Collapsible */}
+ <details className="border-t pt-4 mt-4">
+ <summary className="text-md font-semibold mb-2 text-gray-900 cursor-pointer hover:text-blue-600 transition-colors flex items-center gap-2">
+ <span>⚙️</span> Advanced Configuration
+ </summary>
+ <div className="mt-3 space-y-6">
+ {/* Chunking Configuration */}
+ <div className="space-y-3">
+ <h4 className="text-sm font-medium text-gray-800 flex items-center gap-2">
+ <span>📄</span> Chunking Settings
+ </h4>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ {/* Chunk Size */}
+ <div className="space-y-2">
+ <label className="text-gray-700 text-sm font-normal flex items-center gap-1">
+ Chunk Size
+ <span className="text-gray-400 text-xs">(optional)</span>
+ </label>
+ <input
+ type="number"
+ min="100"
+ max="10000"
+ value={chunkSize}
+ onChange={(e: ChangeEvent<HTMLInputElement>) => setChunkSize(e.target.value)}
+ disabled={isUploading}
+ placeholder="1000"
+ className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-100 disabled:cursor-not-allowed text-sm"
+ />
+ <p className="text-xs text-gray-500">
+ Maximum characters per chunk
+ </p>
+ </div>
+
+ {/* Chunk Overlap */}
+ <div className="space-y-2">
+ <label className="text-gray-700 text-sm font-normal flex items-center gap-1">
+ Chunk Overlap
+ <span className="text-gray-400 text-xs">(optional)</span>
+ </label>
+ <input
+ type="number"
+ min="0"
+ max="1000"
+ value={chunkOverlap}
+ onChange={(e: ChangeEvent<HTMLInputElement>) => setChunkOverlap(e.target.value)}
+ disabled={isUploading}
+ placeholder="200"
+ className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-100 disabled:cursor-not-allowed text-sm"
+ />
+ <p className="text-xs text-gray-500">
+ Overlapping characters between chunks
+ </p>
+ </div>
+ </div>
+ <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg">
+ <p className="text-xs text-blue-800">
+ <strong>💡 Tip:</strong> Larger chunks preserve more context but may be less
+ precise. Overlap helps maintain continuity between chunks. Use defaults for most
+ cases.
+ </p>
+ </div>
+ </div>
+
+ {/* Metadata Configuration */}
+ <div className="space-y-3 border-t pt-4">
+ <h4 className="text-sm font-medium text-gray-800 flex items-center gap-2">
+ <span>🏷️</span> Custom Metadata
+ </h4>
+ <JsonEditor
+ value={metadata}
+ onChange={setMetadata}
+ placeholder={'{\n "author": "John Doe",\n "category": "research",\n "tags": ["ai", "ml"]\n}'}
+ disabled={isUploading}
+ height="150px"
+ />
+ <div className="p-3 bg-amber-50 border border-amber-200 rounded-lg">
+ <p className="text-xs text-amber-800">
+ <strong>📝 Note:</strong> Add custom metadata as JSON to enrich your datasource with additional information. This is optional and can be used for filtering and organization.
+ </p>
+ </div>
+ </div>
+ </div>
+ </details>
+
+ {/* Error Message */}
+ {error && <p className="text-sm text-red-600">{error}</p>}
+ </div>
+
+ <DialogFooter>
+ <CustomButton
+ variant="secondary"
+ label="Cancel"
+ handleClick={onClose}
+ disabled={isUploading}
+ />
+ <CustomButton
+ variant="primary"
+ label={isUploading ? 'Uploading...' : 'Upload'}
+ handleClick={handleUpload}
+ disabled={!isValid || isUploading}
+ loading={isUploading}
+ />
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
diff --git a/packages/app/src/react/features/data-pool/components/ViewDatasourceDialog.tsx b/packages/app/src/react/features/data-pool/components/ViewDatasourceDialog.tsx
new file mode 100644
index 00000000..1c1a8efb
--- /dev/null
+++ b/packages/app/src/react/features/data-pool/components/ViewDatasourceDialog.tsx
@@ -0,0 +1,262 @@
+/**
+ * View Datasource Dialog
+ *
+ * Displays detailed information about a datasource
+ */
+
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from '@src/react/shared/components/ui/dialog';
+import { Tooltip } from 'flowbite-react';
+import { Calendar, Database, FileText, Hash } from 'lucide-react';
+import { FC, lazy, Suspense, useEffect, useState } from 'react';
+import { FaRegCopy } from 'react-icons/fa6';
+import type { Datasource } from '../types/datasource.types';
+
+const SyntaxHighlighter = lazy(() =>
+ import('react-syntax-highlighter').then((mod) => ({ default: mod.Light })),
+);
+
+// Import dark theme
+import { atomOneDark } from 'react-syntax-highlighter/dist/esm/styles/hljs';
+
+interface ViewDatasourceDialogProps {
+ isOpen: boolean;
+ datasource: Datasource | null;
+ onClose: () => void;
+}
+
+export const ViewDatasourceDialog: FC<ViewDatasourceDialogProps> = ({
+ isOpen,
+ datasource,
+ onClose,
+}) => {
+ const [copied, setCopied] = useState(false);
+
+ useEffect(() => {
+ if (copied) {
+ const timeout = setTimeout(() => {
+ setCopied(false);
+ }, 1000);
+ return () => clearTimeout(timeout);
+ }
+ }, [copied]);
+
+ if (!datasource) return null;
+
+ const formatSize = (sizeMb: number | undefined): string => {
+ if (!sizeMb) return '0 B';
+
+ if (sizeMb < 0.001) {
+ // Less than 1 KB, show in Bytes
+ return `${Math.round(sizeMb * 1024 * 1024)} B`;
+ } else if (sizeMb < 1) {
+ // Less than 1 MB, show in KB
+ return `${(sizeMb * 1024).toFixed(2)} KB`;
+ } else {
+ // Show in MB
+ return `${sizeMb.toFixed(2)} MB`;
+ }
+ };
+
+ const formatDate = (dateString: Date | string | undefined): string => {
+ if (!dateString) return 'N/A';
+ try {
+ const date = new Date(dateString);
+ return date.toLocaleString('en-US', {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ hour: '2-digit',
+ minute: '2-digit',
+ });
+ } catch {
+ return String(dateString);
+ }
+ };
+
+ const parseMetadata = (): Record<string, unknown> => {
+ try {
+ return JSON.parse(datasource.metadata);
+ } catch {
+ return {};
+ }
+ };
+
+ const metadata = parseMetadata();
+ const vectorCount = datasource.vectorIds?.length || 0;
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onClose}>
+ <DialogContent className="sm:max-w-[700px] max-h-[90vh] overflow-y-auto overflow-x-hidden">
+ <DialogHeader>
+ <DialogTitle>Datasource Details</DialogTitle>
+ </DialogHeader>
+
+ <div className="space-y-6 py-4 overflow-hidden">
+ {/* Header Info Cards */}
+ <div className="grid grid-cols-2 gap-4">
+ {/* Name Card */}
+ <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 overflow-hidden">
+ <div className="flex items-center gap-2 mb-2">
+ <FileText className="w-5 h-5 text-blue-600" />
+ <span className="text-sm font-medium text-blue-900">Name</span>
+ </div>
+ <p className="text-lg font-semibold text-blue-900 truncate" title={datasource.name}>
+ {datasource.name}
+ </p>
+ </div>
+
+ {/* Vector Count Card */}
+ <div className="bg-purple-50 border border-purple-200 rounded-lg p-4">
+ <div className="flex items-center gap-2 mb-2">
+ <Hash className="w-5 h-5 text-purple-600" />
+ <span className="text-sm font-medium text-purple-900">Vectors</span>
+ </div>
+ <p className="text-lg font-semibold text-purple-900">
+ {vectorCount.toLocaleString()}
+ </p>
+ </div>
+
+ {/* Size Card */}
+ <div className="bg-green-50 border border-green-200 rounded-lg p-4">
+ <div className="flex items-center gap-2 mb-2">
+ <Database className="w-5 h-5 text-green-600" />
+ <span className="text-sm font-medium text-green-900">Size</span>
+ </div>
+ <p className="text-lg font-semibold text-green-900">
+ {formatSize(datasource.datasourceSizeMb)}
+ </p>
+ </div>
+
+ {/* Created Date Card */}
+ <div className="bg-amber-50 border border-amber-200 rounded-lg p-4">
+ <div className="flex items-center gap-2 mb-2">
+ <Calendar className="w-5 h-5 text-amber-600" />
+ <span className="text-sm font-medium text-amber-900">Created</span>
+ </div>
+ <p className="text-sm font-semibold text-amber-900">
+ {formatDate(datasource.createdAt)}
+ </p>
+ </div>
+ </div>
+
+ {/* Chunking Configuration */}
+ {(datasource.chunkSize !== undefined || datasource.chunkOverlap !== undefined) && (
+ <div className="bg-indigo-50 border border-indigo-200 rounded-lg p-4">
+ <h3 className="text-sm font-semibold text-indigo-900 mb-3 flex items-center gap-2">
+ <span>⚙️</span> Chunking Configuration
+ </h3>
+ <div className="grid grid-cols-2 gap-4">
+ {datasource.chunkSize !== undefined && (
+ <div>
+ <span className="text-xs text-indigo-600 font-medium">Chunk Size</span>
+ <p className="text-lg font-semibold text-indigo-900 mt-1">
+ {datasource.chunkSize.toLocaleString()} <span className="text-sm font-normal">chars</span>
+ </p>
+ </div>
+ )}
+ {datasource.chunkOverlap !== undefined && (
+ <div>
+ <span className="text-xs text-indigo-600 font-medium">Chunk Overlap</span>
+ <p className="text-lg font-semibold text-indigo-900 mt-1">
+ {datasource.chunkOverlap.toLocaleString()} <span className="text-sm font-normal">chars</span>
+ </p>
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+
+ {/* Metadata Section */}
+ <div className="space-y-2">
+ <h3 className="text-lg font-semibold text-gray-900">Metadata</h3>
+ <div className="relative bg-[#282c34] border border-gray-700 rounded-lg overflow-hidden">
+ <div className="absolute top-3 right-3 z-10">
+ <Tooltip content={copied ? 'Copied!' : 'Copy'} placement="top">
+ <button
+ onClick={() => {
+ navigator.clipboard.writeText(JSON.stringify(metadata, null, 2));
+ setCopied(true);
+ }}
+ className="p-2 hover:bg-gray-700 rounded transition-colors"
+ >
+ <FaRegCopy className="w-4 h-4 text-gray-300" />
+ </button>
+ </Tooltip>
+ </div>
+ <Suspense fallback={<div className="p-4 text-sm text-gray-300">Loading...</div>}>
+ <div className="overflow-x-auto">
+ <SyntaxHighlighter
+ language="json"
+ style={atomOneDark}
+ customStyle={{
+ margin: 0,
+ padding: '1rem',
+ fontSize: '0.875rem',
+ backgroundColor: '#282c34',
+ borderRadius: '0.5rem',
+ }}
+ wrapLongLines={true}
+ >
+ {JSON.stringify(metadata, null, 2)}
+ </SyntaxHighlighter>
+ </div>
+ </Suspense>
+ </div>
+ </div>
+
+ {/* Source Text Section */}
+ {datasource.text && (
+ <div className="space-y-2">
+ <h3 className="text-lg font-semibold text-gray-900">Source Text</h3>
+ <div className="bg-gray-50 border border-gray-200 rounded-lg p-4 max-h-64 overflow-y-auto overflow-x-hidden">
+ <pre className="text-sm text-gray-700 whitespace-pre-wrap break-words break-all font-mono overflow-wrap-anywhere">
+ {datasource.text}
+ </pre>
+ </div>
+ </div>
+ )}
+
+ {/* Vector IDs Section (Collapsible) */}
+ {vectorCount > 0 && (
+ <details className="space-y-2">
+ <summary className="text-lg font-semibold text-gray-900 cursor-pointer hover:text-blue-600 transition-colors">
+ Vector IDs ({vectorCount})
+ </summary>
+ <div className="bg-gray-50 border border-gray-200 rounded-lg p-4 max-h-48 overflow-y-auto overflow-x-hidden">
+ <ul className="space-y-1">
+ {datasource.vectorIds.map((vectorId, index) => (
+ <li
+ key={vectorId}
+ className="text-xs text-gray-600 font-mono py-1 px-2 hover:bg-gray-100 rounded break-all"
+ >
+ {index + 1}. {vectorId}
+ </li>
+ ))}
+ </ul>
+ </div>
+ </details>
+ )}
+
+ {/* Additional Info */}
+ <div className="bg-gray-50 border border-gray-200 rounded-lg p-4 space-y-2">
+ <h3 className="text-sm font-semibold text-gray-900">Additional Information</h3>
+ <div className="text-sm">
+ <div>
+ <span className="text-gray-600">Datasource ID:</span>
+ <p className="font-mono text-xs text-gray-900 break-all mt-1" title={datasource.id}>
+ {datasource.id}
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
diff --git a/packages/app/src/react/features/data-pool/components/index.ts b/packages/app/src/react/features/data-pool/components/index.ts
new file mode 100644
index 00000000..3d110872
--- /dev/null
+++ b/packages/app/src/react/features/data-pool/components/index.ts
@@ -0,0 +1,8 @@
+/**
+ * Data Pool Components
+ */
+
+export { CreateNamespaceModal } from './CreateNamespaceModal';
+export { FreePlanUpgradePrompt } from './FreePlanUpgradePrompt';
+export { NamespaceTable } from './NamespaceTable';
+
diff --git a/packages/app/src/react/features/data-pool/contexts/data-pool.context.tsx b/packages/app/src/react/features/data-pool/contexts/data-pool.context.tsx
new file mode 100644
index 00000000..7cd9214d
--- /dev/null
+++ b/packages/app/src/react/features/data-pool/contexts/data-pool.context.tsx
@@ -0,0 +1,108 @@
+/**
+ * Data Pool Context
+ *
+ * Provides shared state for the Data Pool feature
+ */
+
+import { createContext, FC, ReactNode, useContext, useEffect, useMemo, useState } from 'react';
+import { useCredentials } from '../../credentials/hooks/use-credentials';
+import type { CredentialConnection } from '../../credentials/components/create-credentials.modal';
+import type { Namespace, NamespaceWithProvider } from '../types';
+
+interface DataPoolContextValue {
+ // Credentials
+ credentials: CredentialConnection[];
+ credentialsLoading: boolean;
+ credentialsError: string | undefined;
+ refetchCredentials: () => void;
+
+ // Helper to get credential by ID
+ getCredentialById: (id: string) => CredentialConnection | undefined;
+
+ // Helper to get provider name
+ getProviderName: (credentialId: string) => string;
+
+ // Helper to enrich namespace with provider info
+ enrichNamespaceWithProvider: (namespace: Namespace) => NamespaceWithProvider;
+}
+
+const DataPoolContext = createContext<DataPoolContextValue | undefined>(undefined);
+
+interface DataPoolProviderProps {
+ children: ReactNode;
+}
+
+export const DataPoolProvider: FC<DataPoolProviderProps> = ({ children }) => {
+ // Fetch vector database credentials
+ const {
+ credentials,
+ isLoading: credentialsLoading,
+ error: credentialsError,
+ refetch: refetchCredentials,
+ } = useCredentials('vector_db_creds');
+
+ /**
+ * Get credential by ID
+ */
+ const getCredentialById = (id: string): CredentialConnection | undefined => {
+ return credentials.find((cred) => cred.id === id);
+ };
+
+ /**
+ * Get provider name for a credential ID
+ */
+ const getProviderName = (credentialId: string): string => {
+ const credential = getCredentialById(credentialId);
+ if (!credential) return 'Unknown';
+
+ // Map provider IDs to display names
+ const providerNames: Record<string, string> = {
+ piencone: 'Pinecone',
+ 'pinecone-1': 'Pinecone',
+ milvus: 'Milvus',
+ qdrant: 'Qdrant',
+ pgvector: 'PGVector',
+ weaviate: 'Weaviate',
+ chroma: 'Chroma',
+ };
+
+ return providerNames[credential.provider] || credential.provider;
+ };
+
+ /**
+ * Enrich namespace with provider information
+ */
+ const enrichNamespaceWithProvider = (namespace: Namespace): NamespaceWithProvider => {
+ const credential = getCredentialById(namespace.credentialId);
+ return {
+ ...namespace,
+ credential,
+ provider: credential?.provider,
+ providerName: getProviderName(namespace.credentialId),
+ };
+ };
+
+ const value: DataPoolContextValue = {
+ credentials,
+ credentialsLoading,
+ credentialsError,
+ refetchCredentials,
+ getCredentialById,
+ getProviderName,
+ enrichNamespaceWithProvider,
+ };
+
+ return <DataPoolContext.Provider value={value}>{children}</DataPoolContext.Provider>;
+};
+
+/**
+ * Hook to use Data Pool context
+ */
+export const useDataPoolContext = (): DataPoolContextValue => {
+ const context = useContext(DataPoolContext);
+ if (!context) {
+ throw new Error('useDataPoolContext must be used within DataPoolProvider');
+ }
+ return context;
+};
+
diff --git a/packages/app/src/react/features/data-pool/pages/DataPoolPage.tsx b/packages/app/src/react/features/data-pool/pages/DataPoolPage.tsx
new file mode 100644
index 00000000..29f24f11
--- /dev/null
+++ b/packages/app/src/react/features/data-pool/pages/DataPoolPage.tsx
@@ -0,0 +1,297 @@
+/**
+ * Data Pool Page
+ *
+ * Main page for managing data pools/namespaces
+ */
+
+import { Input as CustomInput } from '@src/react/shared/components/ui/input';
+import { Button as CustomButton } from '@src/react/shared/components/ui/newDesign/button';
+import TableRowSkeleton from '@src/react/shared/components/ui/table/table.row.skeleton';
+import { useScreenSize } from '@src/react/shared/hooks/useScreenSize';
+import { errorToast, successToast } from '@src/shared/components/toast';
+import { SMYTHOS_DOCS_URL } from '@src/shared/constants/general';
+import { ChangeEvent, FC, useCallback, useEffect, useMemo, useState } from 'react';
+import { dataPoolClient } from '../client/datapool.client';
+import { CreateNamespaceModal } from '../components/CreateNamespaceModal';
+import { DeleteNamespaceDialog } from '../components/DeleteNamespaceDialog';
+import { NamespaceTable } from '../components/NamespaceTable';
+import { DataPoolProvider, useDataPoolContext } from '../contexts/data-pool.context';
+import type { Namespace, NamespaceWithProvider } from '../types';
+import { DEFAULT_PAGINATION_LIMIT } from '../types';
+
+const DataPoolPageContent: FC = () => {
+ const [namespaces, setNamespaces] = useState<Namespace[]>([]);
+ const [loading, setLoading] = useState<boolean>(false);
+ const [searchQuery, setSearchQuery] = useState<string>('');
+ const [page, setPage] = useState<number>(1);
+ const [hasMore, setHasMore] = useState<boolean>(true);
+ const [isCreateModalOpen, setIsCreateModalOpen] = useState<boolean>(false);
+ const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState<boolean>(false);
+ const [namespaceToDelete, setNamespaceToDelete] = useState<NamespaceWithProvider | null>(null);
+
+ const { enrichNamespaceWithProvider, credentials, credentialsLoading } = useDataPoolContext();
+ const { isSmallScreen } = useScreenSize();
+
+ /**
+ * Fetch namespaces from API
+ */
+ const fetchNamespaces = useCallback(
+ async (currentPage: number = 1) => {
+ try {
+ setLoading(true);
+ const response = await dataPoolClient.listNamespaces({
+ page: currentPage,
+ limit: DEFAULT_PAGINATION_LIMIT,
+ });
+
+ const { namespaces: fetchedNamespaces } = response;
+
+ setNamespaces((prev) =>
+ currentPage === 1 ? fetchedNamespaces : [...prev, ...fetchedNamespaces],
+ );
+ setHasMore(fetchedNamespaces.length === DEFAULT_PAGINATION_LIMIT);
+ } catch (error: unknown) {
+ const errorMessage = (error as Error)?.message || 'Failed to fetch data spaces. Please try again.';
+ errorToast(errorMessage);
+ } finally {
+ setLoading(false);
+ }
+ },
+ [],
+ );
+
+ // Fetch on mount
+ useEffect(() => {
+ fetchNamespaces();
+ }, [fetchNamespaces]);
+
+ /**
+ * Handle load more
+ */
+ const handleLoadMore = () => {
+ const nextPage = page + 1;
+ setPage(nextPage);
+ fetchNamespaces(nextPage);
+ };
+
+ /**
+ * Handle search change
+ */
+ const handleSearchChange = (value: string) => {
+ setSearchQuery(value);
+ };
+
+ /**
+ * Handle create success
+ */
+ const handleCreateSuccess = () => {
+ setPage(1);
+ fetchNamespaces(1);
+ };
+
+ /**
+ * Open delete confirmation dialog
+ */
+ const handleDeleteClick = (namespace: NamespaceWithProvider) => {
+ setNamespaceToDelete(namespace);
+ setIsDeleteDialogOpen(true);
+ };
+
+ /**
+ * Close delete confirmation dialog
+ */
+ const handleCloseDeleteDialog = () => {
+ setIsDeleteDialogOpen(false);
+ setNamespaceToDelete(null);
+ };
+
+ /**
+ * Confirm and execute delete namespace
+ */
+ const handleConfirmDelete = async () => {
+ if (!namespaceToDelete) return;
+
+ try {
+ // Call API to delete
+ await dataPoolClient.deleteNamespace(namespaceToDelete.label);
+
+ // Manually remove from list without refetching
+ setNamespaces((prev) => prev.filter((ns) => ns.label !== namespaceToDelete.label));
+
+ successToast('Data space deleted successfully');
+ handleCloseDeleteDialog();
+ } catch (error: unknown) {
+ const errorMessage = (error as Error)?.message || 'Failed to delete data space. Please try again.';
+ errorToast(errorMessage);
+ throw error; // Re-throw to let dialog handle loading state
+ }
+ };
+
+ /**
+ * Filter namespaces based on search query
+ */
+ const filteredNamespaces: NamespaceWithProvider[] = useMemo(() => {
+ const enriched = namespaces.map((ns) => enrichNamespaceWithProvider(ns));
+
+ if (!searchQuery) return enriched;
+
+ return enriched.filter((ns) =>
+ ns.label?.toLowerCase().includes(searchQuery.toLowerCase()) ?? false,
+ );
+ }, [namespaces, searchQuery, enrichNamespaceWithProvider]);
+
+ /**
+ * Render skeleton loading rows
+ */
+ const renderSkeletonLoading = () => {
+ return Array.from({ length: 3 }).map((_, i) => (
+ <TableRowSkeleton key={i} className="py-5 my-3" />
+ ));
+ };
+
+ return (
+ <div className={`${isSmallScreen ? 'small-screen-sidebar-margin' : ''} container mx-auto py-6`}>
+ {/* Header Section */}
+
+ {/* Show a highlighted, beautiful info card if there are no credentials */}
+ {/* {credentials.length === 0 && !credentialsLoading && (
+ <AddCredentialBanner />
+ )} */}
+ <div className="flex items-center justify-end flex-wrap md:flex-nowrap pb-6 gap-2">
+ {/* Search Input */}
+ <div className="relative">
+ <CustomInput
+ isSearch={true}
+ placeholder="Search Data Space"
+ onChange={(e: ChangeEvent<HTMLInputElement>) => handleSearchChange(e.target.value)}
+ value={searchQuery}
+ />
+ </div>
+
+ {/* Add Data Space Button */}
+ {namespaces.length > 0 && (
+ <CustomButton
+ handleClick={() => setIsCreateModalOpen(true)}
+ addIcon={true}
+ label="Add Data Space"
+ disabled={credentialsLoading}
+ />
+ )}
+ </div>
+
+ {/* Main Content */}
+ <div className="bg-white rounded-lg overflow-hidden border border-gray-200">
+ {/* Table */}
+ {filteredNamespaces.length > 0 && (
+ <NamespaceTable
+ namespaces={filteredNamespaces}
+ onDelete={handleDeleteClick}
+ />
+ )}
+
+ {/* Empty State */}
+ {!loading && filteredNamespaces.length === 0 && (
+ <div className="flex justify-center items-start py-16">
+ <div className="max-w-md w-full mx-auto flex flex-col items-center p-4 text-center">
+ {namespaces.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 text-gray-600">
+ 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={() => setIsCreateModalOpen(true)}
+ addIcon={true}
+ label="Add Data Space"
+ className="flex-1 w-[190px] md:w-auto"
+ disabled={credentialsLoading
+ // || credentials.length === 0
+
+ }
+ />
+ </div>
+ {/* {credentials.length === 0 && !credentialsLoading && (
+ <p className="text-xs text-amber-600 mt-4">
+ Please add a vector database connection in the Vault page first.
+ </p>
+ )} */}
+ </>
+ ) : (
+ <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 State */}
+ {loading && renderSkeletonLoading()}
+
+ {/* Load More */}
+ {!searchQuery && hasMore && !loading && namespaces.length > 0 && (
+ <div className="px-6 py-4 text-center border-t">
+ <button
+ onClick={handleLoadMore}
+ type="button"
+ className="text-gray-500 hover:underline"
+ >
+ Load More
+ </button>
+ </div>
+ )}
+ </div>
+
+ {/* Create Namespace Modal */}
+ <CreateNamespaceModal
+ isOpen={isCreateModalOpen}
+ onClose={() => setIsCreateModalOpen(false)}
+ onSuccess={handleCreateSuccess}
+ />
+
+ {/* Delete Namespace Confirmation Dialog */}
+ {namespaceToDelete && (
+ <DeleteNamespaceDialog
+ isOpen={isDeleteDialogOpen}
+ namespaceName={namespaceToDelete.label}
+ onClose={handleCloseDeleteDialog}
+ onConfirm={handleConfirmDelete}
+ />
+ )}
+ </div>
+ );
+};
+
+/**
+ * Data Pool Page with Context Provider
+ */
+const DataPoolPage: FC = () => {
+ return (
+ <DataPoolProvider>
+ <DataPoolPageContent />
+ </DataPoolProvider>
+ );
+};
+
+export default DataPoolPage;
+
diff --git a/packages/app/src/react/features/data-pool/pages/DatasourcesPage.tsx b/packages/app/src/react/features/data-pool/pages/DatasourcesPage.tsx
new file mode 100644
index 00000000..63c7487f
--- /dev/null
+++ b/packages/app/src/react/features/data-pool/pages/DatasourcesPage.tsx
@@ -0,0 +1,283 @@
+/**
+ * Datasources Page
+ *
+ * Displays and manages datasources for a specific namespace
+ */
+
+import { Input as CustomInput } from '@src/react/shared/components/ui/input';
+import { Button as CustomButton } from '@src/react/shared/components/ui/newDesign/button';
+import TableRowSkeleton from '@src/react/shared/components/ui/table/table.row.skeleton';
+import { useScreenSize } from '@src/react/shared/hooks/useScreenSize';
+import { errorToast, successToast } from '@src/shared/components/toast';
+import { Breadcrumb } from 'flowbite-react';
+import { ChangeEvent, FC, useCallback, useEffect, useMemo, useState } from 'react';
+import { HiHome } from 'react-icons/hi';
+import { Link, useParams } from 'react-router-dom';
+import { datasourceClient } from '../client/datasource.client';
+import { DatasourcesTable } from '../components/DatasourcesTable';
+import { DeleteDatasourceDialog } from '../components/DeleteDatasourceDialog';
+import { UploadDatasourceDialog } from '../components/UploadDatasourceDialog';
+import { ViewDatasourceDialog } from '../components/ViewDatasourceDialog';
+import type { Datasource } from '../types/datasource.types';
+
+const DatasourcesPage: FC = () => {
+ const { namespaceLabel } = useParams<{ namespaceLabel: string }>();
+ const [datasources, setDatasources] = useState<Datasource[]>([]);
+ const [loading, setLoading] = useState<boolean>(false);
+ const [searchQuery, setSearchQuery] = useState<string>('');
+ const [isUploadDialogOpen, setIsUploadDialogOpen] = useState<boolean>(false);
+ const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState<boolean>(false);
+ const [isViewDialogOpen, setIsViewDialogOpen] = useState<boolean>(false);
+ const [datasourceToDelete, setDatasourceToDelete] = useState<Datasource | null>(null);
+ const [datasourceToView, setDatasourceToView] = useState<Datasource | null>(null);
+ const { isSmallScreen } = useScreenSize();
+
+ /**
+ * Fetch datasources from API
+ */
+ const fetchDatasources = useCallback(async () => {
+ if (!namespaceLabel) return;
+
+ try {
+ setLoading(true);
+ const fetchedDatasources = await datasourceClient.listDatasources(namespaceLabel);
+ setDatasources(fetchedDatasources);
+ } catch (error: unknown) {
+ const errorMessage =
+ (error as Error)?.message || 'Failed to fetch datasources. Please try again.';
+ errorToast(errorMessage);
+ } finally {
+ setLoading(false);
+ }
+ }, [namespaceLabel]);
+
+ // Fetch on mount
+ useEffect(() => {
+ fetchDatasources();
+ }, [fetchDatasources]);
+
+ /**
+ * Handle search change
+ */
+ const handleSearchChange = (value: string) => {
+ setSearchQuery(value);
+ };
+
+ /**
+ * Handle upload success
+ */
+ const handleUploadSuccess = () => {
+ fetchDatasources();
+ };
+
+ /**
+ * Open delete confirmation dialog
+ */
+ const handleDeleteClick = (datasource: Datasource) => {
+ setDatasourceToDelete(datasource);
+ setIsDeleteDialogOpen(true);
+ };
+
+ /**
+ * Close delete confirmation dialog
+ */
+ const handleCloseDeleteDialog = () => {
+ setIsDeleteDialogOpen(false);
+ setDatasourceToDelete(null);
+ };
+
+ /**
+ * Open view details dialog
+ */
+ const handleViewClick = (datasource: Datasource) => {
+ setDatasourceToView(datasource);
+ setIsViewDialogOpen(true);
+ };
+
+ /**
+ * Close view details dialog
+ */
+ const handleCloseViewDialog = () => {
+ setIsViewDialogOpen(false);
+ setDatasourceToView(null);
+ };
+
+ /**
+ * Confirm and execute delete datasource
+ */
+ const handleConfirmDelete = async () => {
+ if (!datasourceToDelete || !namespaceLabel) return;
+
+ try {
+ // Call API to delete
+ await datasourceClient.deleteDatasource(namespaceLabel, datasourceToDelete.id);
+
+ // Manually remove from list without refetching
+ setDatasources((prev) => prev.filter((ds) => ds.id !== datasourceToDelete.id));
+
+ successToast('Datasource deleted successfully');
+ handleCloseDeleteDialog();
+ } catch (error: unknown) {
+ const errorMessage =
+ (error as Error)?.message || 'Failed to delete datasource. Please try again.';
+ errorToast(errorMessage);
+ throw error; // Re-throw to let dialog handle loading state
+ }
+ };
+
+ /**
+ * Filter datasources based on search query
+ */
+ const filteredDatasources: Datasource[] = useMemo(() => {
+ if (!searchQuery) return datasources;
+
+ return datasources.filter(
+ (ds) =>
+ ds.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
+ ds.id.toLowerCase().includes(searchQuery.toLowerCase()),
+ );
+ }, [datasources, searchQuery]);
+
+ /**
+ * Render skeleton loading rows
+ */
+ const renderSkeletonLoading = () => {
+ return Array.from({ length: 3 }).map((_, i) => <TableRowSkeleton key={i} className="py-5 my-3" />);
+ };
+
+ const breadcrumb = (
+ <Breadcrumb aria-label="Breadcrumb" className="mb-4">
+ <Breadcrumb.Item icon={HiHome}>
+ <Link to="/">Home</Link>
+ </Breadcrumb.Item>
+ <Breadcrumb.Item>
+ <Link to="/data-pool">Data Spaces</Link>
+ </Breadcrumb.Item>
+ <Breadcrumb.Item>{namespaceLabel}</Breadcrumb.Item>
+ </Breadcrumb>
+ );
+
+ if (!namespaceLabel) {
+ return (
+ <div className="container mx-auto py-6">
+ <p className="text-red-600">Error: No namespace label provided</p>
+ </div>
+ );
+ }
+
+ return (
+ <div className={`${isSmallScreen ? 'small-screen-sidebar-margin' : ''} container mx-auto py-6`}>
+ {/* Breadcrumb */}
+ {breadcrumb}
+
+ {/* Header Section */}
+ <div className="flex items-center justify-between flex-wrap md:flex-nowrap pb-6 gap-2">
+ <div>
+ <h1 className="text-2xl font-semibold text-gray-900">Datasources</h1>
+ <p className="text-sm text-gray-600 mt-1">
+ Manage datasources for <span className="font-medium">{namespaceLabel}</span>
+ </p>
+ </div>
+
+ <div className="flex items-center gap-2">
+ {/* Search Input */}
+ <div className="relative">
+ <CustomInput
+ isSearch={true}
+ placeholder="Search datasources"
+ onChange={(e: ChangeEvent<HTMLInputElement>) => handleSearchChange(e.target.value)}
+ value={searchQuery}
+ />
+ </div>
+
+ {/* Upload Datasource Button */}
+ {datasources.length > 0 && (
+ <CustomButton
+ handleClick={() => setIsUploadDialogOpen(true)}
+ addIcon={true}
+ label="Upload Source"
+ />
+ )}
+ </div>
+ </div>
+
+ {/* Main Content */}
+ <div className="bg-white rounded-lg overflow-hidden border border-gray-200">
+ {/* Table */}
+ {filteredDatasources.length > 0 && (
+ <DatasourcesTable
+ datasources={filteredDatasources}
+ onDelete={handleDeleteClick}
+ onView={handleViewClick}
+ />
+ )}
+
+ {/* Empty State */}
+ {!loading && filteredDatasources.length === 0 && (
+ <div className="flex justify-center items-start py-16">
+ <div className="max-w-md w-full mx-auto flex flex-col items-center p-4 text-center">
+ {datasources.length === 0 ? (
+ <>
+ <h4 className="text-xl md:text-2xl font-medium text-black text-center mb-2">
+ Upload your first datasource
+ </h4>
+ <p className="mb-8 text-sm md:text-base text-gray-600">
+ Add files or text content to index in this data space.
+ </p>
+ <CustomButton
+ handleClick={() => setIsUploadDialogOpen(true)}
+ addIcon={true}
+ label="Upload Source"
+ className="w-[190px]"
+ />
+ </>
+ ) : (
+ <div className="text-center">
+ <h4 className="text-xl font-medium text-gray-700 mb-2">
+ No matching datasources found
+ </h4>
+ <p className="text-gray-600">
+ No datasources match your search query: &quot;{searchQuery}&quot;
+ </p>
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+
+ {/* Loading State */}
+ {loading && renderSkeletonLoading()}
+ </div>
+
+ {/* Upload Datasource Dialog */}
+ {namespaceLabel && (
+ <UploadDatasourceDialog
+ isOpen={isUploadDialogOpen}
+ namespaceLabel={namespaceLabel}
+ onClose={() => setIsUploadDialogOpen(false)}
+ onSuccess={handleUploadSuccess}
+ />
+ )}
+
+ {/* Delete Datasource Confirmation Dialog */}
+ {datasourceToDelete && (
+ <DeleteDatasourceDialog
+ isOpen={isDeleteDialogOpen}
+ datasourceName={datasourceToDelete.name}
+ onClose={handleCloseDeleteDialog}
+ onConfirm={handleConfirmDelete}
+ />
+ )}
+
+ {/* View Datasource Details Dialog */}
+ <ViewDatasourceDialog
+ isOpen={isViewDialogOpen}
+ datasource={datasourceToView}
+ onClose={handleCloseViewDialog}
+ />
+ </div>
+ );
+};
+
+export default DatasourcesPage;
+
diff --git a/packages/app/src/react/features/data-pool/types/datasource.types.ts b/packages/app/src/react/features/data-pool/types/datasource.types.ts
new file mode 100644
index 00000000..3515fe67
--- /dev/null
+++ b/packages/app/src/react/features/data-pool/types/datasource.types.ts
@@ -0,0 +1,35 @@
+/**
+ * Datasource Types
+ */
+
+export interface Datasource {
+ namespaceId: string;
+ // indexName: string;
+ name: string;
+ metadata: string;
+ text?: string;
+ vectorIds: string[];
+ id: string;
+ candidateId: string;
+ candidateRole: string;
+ datasourceSizeMb?: number;
+ createdAt?: Date;
+ chunkSize?: number;
+ chunkOverlap?: number;
+}
+
+export interface CreateDatasourceRequest {
+ datasourceLabel: string;
+ file: File;
+ chunkSize?: number;
+ chunkOverlap?: number;
+ metadata?: Record<string, unknown>;
+}
+
+export interface CreateDatasourceResponse {
+ datasource: Datasource;
+}
+
+export interface ListDatasourcesResponse {
+ datasources: Datasource[];
+}
diff --git a/packages/app/src/react/features/data-pool/types/index.ts b/packages/app/src/react/features/data-pool/types/index.ts
new file mode 100644
index 00000000..8981ce9f
--- /dev/null
+++ b/packages/app/src/react/features/data-pool/types/index.ts
@@ -0,0 +1,81 @@
+/**
+ * Data Pool Types
+ */
+
+import type { CredentialConnection } from '../../credentials/components/create-credentials.modal';
+
+/**
+ * Namespace entity from the API
+ */
+export interface Namespace {
+ namespaceId: string;
+ label: string;
+ credentialId: string;
+ embeddings?: {
+ modelId: string;
+ dimensions?: number;
+ };
+ createdAt?: string;
+ updatedAt?: string;
+}
+
+/**
+ * Namespace with resolved credential info
+ */
+export interface NamespaceWithProvider extends Namespace {
+ provider?: string;
+ providerName?: string;
+ credential?: CredentialConnection;
+}
+
+/**
+ * API Response for listing namespaces
+ */
+export interface ListNamespacesResponse {
+ namespaces: Namespace[];
+ total: number;
+}
+
+/**
+ * API Response for creating a namespace
+ */
+export interface CreateNamespaceResponse {
+ namespace: Namespace;
+}
+
+/**
+ * Embedding model from API
+ */
+export interface EmbeddingModel {
+ provider: string;
+ model: string;
+ label: string;
+}
+
+/**
+ * Request payload for creating a namespace
+ */
+export interface CreateNamespaceRequest {
+ label: string;
+ credentialId: string;
+ embeddings?: {
+ modelId: string;
+ dimensions?: number;
+ };
+}
+
+/**
+ * Default pagination limit for namespace list
+ */
+export const DEFAULT_PAGINATION_LIMIT = 10;
+
+/**
+ * Re-export datasource types
+ */
+export type {
+ Datasource,
+ CreateDatasourceRequest,
+ CreateDatasourceResponse,
+ ListDatasourcesResponse,
+} from './datasource.types';
+
diff --git a/packages/app/src/react/features/vault/components/vector-databases.tsx b/packages/app/src/react/features/vault/components/vector-databases.tsx
new file mode 100644
index 00000000..d90f2485
--- /dev/null
+++ b/packages/app/src/react/features/vault/components/vector-databases.tsx
@@ -0,0 +1,275 @@
+/**
+ * VectorDatabases Component
+ *
+ * Displays and manages vector database credential connections.
+ * Features:
+ * - List all vector database connections
+ * - Create new connections
+ * - Edit existing connections
+ * - Delete connections
+ * - Test connections
+ * - Duplicate connections
+ *
+ * @component
+ */
+
+import { Button } from '@src/react/shared/components/ui/button';
+import { Button as CustomButton } from '@src/react/shared/components/ui/newDesign/button';
+import { successToast } from '@src/shared/components/toast';
+import { Tooltip } from 'flowbite-react';
+import { Info, Pencil, PlusCircle, Trash2 } from 'lucide-react';
+import { useState } from 'react';
+import {
+ CreateCredentialsModal,
+ type CredentialConnection,
+} from '../../credentials/components/create-credentials.modal';
+import { CredentialsListSkeleton } from '../../credentials/components/credentials-list-skeleton';
+import { DeleteCredentialsModal } from '../../credentials/components/delete-credentials.modal';
+import credentialsSchema from '../../credentials/credentials-schema.json';
+import { useCredentials } from '../../credentials/hooks/use-credentials';
+
+/**
+ * Provider schema definition
+ */
+interface ProviderSchema {
+ id: string;
+ name: string;
+ group: string;
+ auth_type: string;
+ description: string;
+ logo_url?: string;
+ fields: Array<{
+ key: string;
+ label: string;
+ type: string;
+ required: boolean;
+ placeholder?: string;
+ }>;
+ docs_url?: string;
+ test_endpoint?: string;
+}
+
+/**
+ * VectorDatabases Component
+ */
+export function VectorDatabases() {
+ // State
+ const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
+ const [editingConnection, setEditingConnection] = useState<CredentialConnection | undefined>();
+ const [deletingConnection, setDeletingConnection] = useState<CredentialConnection | undefined>();
+
+ // Fetch credentials using the hook
+ const { credentials, isLoading, refetch } = useCredentials('vector_db_creds');
+
+ /**
+ * Get provider display name from schema
+ */
+ const getProviderName = (providerId: string): string => {
+ const provider = (credentialsSchema as ProviderSchema[]).find((p) => p.id === providerId);
+ return provider?.name || providerId;
+ };
+
+ /**
+ * Get provider logo URL from schema
+ */
+ const getProviderLogo = (providerId: string): string | undefined => {
+ const provider = (credentialsSchema as ProviderSchema[]).find((p) => p.id === providerId);
+ return provider?.logo_url;
+ };
+
+ /**
+ * Handle successful credential save (create or update)
+ */
+ const handleSuccess = (data: {
+ id?: string;
+ name: string;
+ provider: string;
+ credentials: Record<string, string>;
+ isEdit: boolean;
+ }) => {
+ // Show success message
+ if (data.isEdit) {
+ successToast('Connection updated successfully.');
+ } else {
+ successToast('Connection created successfully.');
+ }
+
+ // Reset state
+ setEditingConnection(undefined);
+
+ // Refetch the credentials list
+ refetch();
+ };
+
+ /**
+ * Handle edit button click
+ */
+ const handleEditClick = (connection: CredentialConnection) => {
+ setEditingConnection(connection);
+ setIsCreateModalOpen(true);
+ };
+
+ /**
+ * Handle delete button click
+ */
+ const handleDeleteClick = (connection: CredentialConnection) => {
+ setDeletingConnection(connection);
+ };
+
+ /**
+ * Handle successful deletion
+ */
+ const handleDeleteSuccess = () => {
+ setDeletingConnection(undefined);
+ refetch();
+ };
+
+ /**
+ * Handle delete modal close
+ */
+ const handleDeleteModalClose = () => {
+ setDeletingConnection(undefined);
+ };
+
+
+ /**
+ * Handle modal close
+ */
+ const handleModalClose = () => {
+ setIsCreateModalOpen(false);
+ setEditingConnection(undefined);
+ };
+
+ return (
+ <div
+ id="vector-databases"
+ className="rounded-lg bg-card text-card-foreground border border-solid border-gray-200 shadow-sm">
+ <div className="p-6">
+ {/* Header */}
+ <div className="flex items-center justify-between mb-4 pr-2 flex-wrap">
+ <h2 className="flex items-center gap-2 text-lg font-semibold">
+ Vector Databases
+ <Tooltip
+ className="w-72 text-center"
+ content="Manage connections to vector databases for storing and retrieving embeddings"
+ >
+ <Info className="w-4 h-4" />
+ </Tooltip>
+ </h2>
+ </div>
+
+ {/* Table */}
+ <div className="overflow-x-auto">
+ {isLoading ? (
+ <CredentialsListSkeleton rows={3} />
+ ) : credentials.length === 0 ? (
+ <div className="py-8 text-center">
+ <p className="text-muted-foreground mb-2">No vector database connections found</p>
+ <p className="text-sm text-gray-500">
+ Get started by adding your first connection
+ </p>
+ </div>
+ ) : (
+ <table className="w-full min-w-[500px] text-sm text-left table-fixed">
+ <thead className="text-xs text-muted-foreground">
+ <tr>
+ <th className="pr-4 py-2 w-1/3">Connection Name</th>
+ <th className="px-4 py-2 w-1/3">Provider</th>
+ <th className="px-4 py-2 w-1/3 text-right">Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ {credentials.map((connection) => (
+ <tr key={connection.id} className="border-t">
+ {/* Connection Name */}
+ <td className="pr-4 py-3 truncate" title={connection.name}>
+ <span className="font-medium">{connection.name}</span>
+ </td>
+
+ {/* Provider */}
+ <td className="px-4 py-3" title={getProviderName(connection.provider)}>
+ <div className="flex items-center gap-2">
+ {getProviderLogo(connection.provider) && (
+ <img
+ src={getProviderLogo(connection.provider)}
+ alt={getProviderName(connection.provider)}
+ className="w-5 h-5 object-contain"
+ />
+ )}
+ <span className="truncate">{getProviderName(connection.provider)}</span>
+ </div>
+ </td>
+
+ {/* Actions */}
+ <td className="pl-4 py-3">
+ <div className="flex items-center justify-end gap-1">
+ {/* Edit Button */}
+ <Tooltip content="Edit">
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => handleEditClick(connection)}
+ >
+ <Pencil className="h-4 w-4" />
+ </Button>
+ </Tooltip>
+
+ {/* Delete Button */}
+ <Tooltip content="Delete">
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => handleDeleteClick(connection)}
+ >
+ <Trash2 className="h-4 w-4 hover:text-red-500" />
+ </Button>
+ </Tooltip>
+ </div>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+
+ {/* Add Button */}
+ <div className="w-full flex justify-center mt-4">
+ <CustomButton
+ variant="secondary"
+ addIcon
+ Icon={<PlusCircle className="mr-2 h-4 w-4" />}
+ handleClick={() => {
+ setEditingConnection(undefined);
+ setIsCreateModalOpen(true);
+ }}
+ label="Add Vector Database"
+ disabled={isLoading}
+ />
+ </div>
+ </div>
+
+ {/* Create/Edit Modal */}
+ <CreateCredentialsModal
+ isOpen={isCreateModalOpen}
+ onClose={handleModalClose}
+ onSuccess={handleSuccess}
+ group="vector_db_creds"
+ editConnection={editingConnection}
+ />
+
+ {/* Delete Confirmation Modal */}
+ {deletingConnection && (
+ <DeleteCredentialsModal
+ isOpen={!!deletingConnection}
+ credentialId={deletingConnection.id}
+ credentialName={deletingConnection.name}
+ group="vector_db_creds"
+ onClose={handleDeleteModalClose}
+ onSuccess={handleDeleteSuccess}
+ />
+ )}
+ </div>
+ );
+}
+
diff --git a/packages/app/src/react/features/vault/pages/VaultPage.tsx b/packages/app/src/react/features/vault/pages/VaultPage.tsx
index 7b233185..fbafabfa 100644
--- a/packages/app/src/react/features/vault/pages/VaultPage.tsx
+++ b/packages/app/src/react/features/vault/pages/VaultPage.tsx
@@ -6,12 +6,13 @@ import { PluginComponents } from '@src/react/shared/plugins/PluginComponents';
import { PluginTarget } from '@src/react/shared/plugins/Plugins';
import { errorToast, successToast } from '@src/shared/components/toast';
import { Loader2 } from 'lucide-react';
-import React, { useMemo } from 'react';
+import React, { useEffect, useMemo } from 'react';
import { CiExport } from 'react-icons/ci';
import { ApiKeys } from '../components/api-keys';
import { OAuthConnections } from '../components/oauth-connections';
import UserCustomModels from '../components/user-custom-models';
import { UserModels } from '../components/user-models';
+import { VectorDatabases } from '../components/vector-databases';
import { useVault } from '../hooks/use-vault';
export default function VaultPage() {
@@ -21,7 +22,7 @@ export default function VaultPage() {
const hasBuiltinModels = useMemo(() => {
const flags = userInfo?.subs?.plan?.properties?.flags;
return (
- // @ts-ignore
+ // @ts-expect-error - flags is not typed
flags?.hasBuiltinModels || userInfo?.subs?.plan?.isDefaultPlan === true
);
}, [userInfo?.subs?.plan]);
@@ -49,6 +50,20 @@ export default function VaultPage() {
}
};
+ useEffect(() => {
+ if (window.location.hash) {
+ async function scrollToHash() {
+ const id = window.location.hash.replace('#', '');
+ await new Promise(resolve => setTimeout(resolve, 1000));
+ const el = document.getElementById(id);
+ if (el) {
+ el.scrollIntoView({ behavior: 'smooth' });
+ }
+ }
+ scrollToHash();
+ }
+ }, [isLoading]);
+
if (isLoading) {
return (
<div className="flex items-center justify-center min-h-screen">
@@ -87,6 +102,8 @@ export default function VaultPage() {
<PluginComponents targetId={PluginTarget.VaultPageEnterpriseModels} />
<OAuthConnections />
+ {window.location.hostname === 'localhost' && <VectorDatabases />}
+
<ErrorBoundarySuspense
loadingFallback={<div>Loading...</div>}
errorFallback={() => <div>Error loading API keys</div>}
@@ -97,3 +114,4 @@ export default function VaultPage() {
</TooltipProvider>
);
}
+
diff --git a/packages/app/src/react/shared/components/sidebar/Sidebar.tsx b/packages/app/src/react/shared/components/sidebar/Sidebar.tsx
index 8476fe35..bfd2784b 100644
--- a/packages/app/src/react/shared/components/sidebar/Sidebar.tsx
+++ b/packages/app/src/react/shared/components/sidebar/Sidebar.tsx
@@ -39,6 +39,8 @@ export const Sidebar: React.FC = () => {
access['/templates'] = getPageAccess('/templates')?.read;
access['/domains'] = getPageAccess('/domains')?.read;
access['/data/'] = getPageAccess('/data')?.read;
+ access['/data-pool'] = getPageAccess('/data')?.read;
+ // access['/data-pool'] = getPageAccess('/data-pool')?.read || true; // Default to true for community edition
access['/analytics'] = getPageAccess('/analytics')?.read;
access['/teams/settings'] = getPageAccess('/teams/members')?.read;
@@ -47,7 +49,7 @@ export const Sidebar: React.FC = () => {
const showCustomLogo =
currentTeam?.parentId && companyLogo?.url && getPageAccess('/teams/members')?.read;
- let menuItems = getSidebarMenuItems().filter((item) => {
+ const menuItems = getSidebarMenuItems().filter((item) => {
const isVisible =
typeof item.visible === 'boolean'
? item.visible
diff --git a/packages/app/src/react/shared/components/ui/json-editor.tsx b/packages/app/src/react/shared/components/ui/json-editor.tsx
new file mode 100644
index 00000000..3b1d34de
--- /dev/null
+++ b/packages/app/src/react/shared/components/ui/json-editor.tsx
@@ -0,0 +1,85 @@
+import { ChangeEvent, FC, useEffect, useState } from 'react';
+
+interface JsonEditorProps {
+ value: string;
+ onChange: (value: string) => void;
+ placeholder?: string;
+ disabled?: boolean;
+ height?: string;
+ error?: string | null;
+}
+
+/**
+ * A simple JSON editor component with syntax validation
+ * Can be upgraded to use Ace Editor or CodeMirror in the future
+ */
+export const JsonEditor: FC<JsonEditorProps> = ({
+ value,
+ onChange,
+ placeholder = '{\n "key": "value"\n}',
+ disabled = false,
+ height = '200px',
+ error = null,
+}) => {
+ const [localError, setLocalError] = useState<string | null>(null);
+
+ const handleChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
+ const newValue = e.target.value;
+ onChange(newValue);
+
+ // Validate JSON if not empty
+ if (newValue.trim()) {
+ try {
+ JSON.parse(newValue);
+ setLocalError(null);
+ } catch (err) {
+ setLocalError((err as Error).message);
+ }
+ } else {
+ setLocalError(null);
+ }
+ };
+
+ useEffect(() => {
+ // Clear local error when external error is provided
+ if (error) {
+ setLocalError(null);
+ }
+ }, [error]);
+
+ const displayError = error || localError;
+
+ return (
+ <div className="w-full">
+ <div className="relative">
+ <textarea
+ value={value}
+ onChange={handleChange}
+ placeholder={placeholder}
+ disabled={disabled}
+ className={`
+ w-full px-3 py-2
+ border ${displayError ? 'border-red-300' : 'border-gray-300'}
+ rounded-md shadow-sm
+ focus:outline-none focus:ring-2
+ ${displayError ? 'focus:ring-red-500 focus:border-red-500' : 'focus:ring-blue-500 focus:border-blue-500'}
+ disabled:bg-gray-100 disabled:cursor-not-allowed
+ font-mono text-sm
+ resize-y
+ `}
+ style={{
+ minHeight: height,
+ tabSize: 2,
+ }}
+ spellCheck={false}
+ />
+ </div>
+ {displayError && (
+ <p className="mt-1 text-xs text-red-600">
+ {displayError}
+ </p>
+ )}
+ </div>
+ );
+};
+
diff --git a/packages/app/src/react/shared/constants/navigation.ts b/packages/app/src/react/shared/constants/navigation.ts
index 9268e540..aa99a18a 100644
--- a/packages/app/src/react/shared/constants/navigation.ts
+++ b/packages/app/src/react/shared/constants/navigation.ts
@@ -1,6 +1,7 @@
import { plugins, PluginTarget, PluginType } from '@src/react/shared/plugins/Plugins';
import { SMYTHOS_DOCS_URL } from '@src/shared/constants/general';
-import { BookIcon, DiscordIcon, HomeIcon, KeyIcon } from '../components/svgs';
+import { builderStore } from '@src/shared/state_stores/builder/store';
+import { BookIcon, DatabaseIcon, DiscordIcon, HomeIcon, KeyIcon } from '../components/svgs';
export const PRICING_PLAN_REDIRECT = 'https://smythos.com/pricing/';
@@ -21,9 +22,17 @@ export const getSidebarMenuItems = (): SidebarMenuItem[] => {
}[]
).flatMap((item) => item.config);
+ const devItems =
+ builderStore.getState().serverStatus?.env == 'DEV' &&
+ builderStore.getState().serverStatus?.edition == 'enterprise' &&
+ !window.location.hostname.includes('smythos.com')
+ ? [{ url: '/data-pool', name: 'Data Pool V2', icon: DatabaseIcon, visible: true, order: 8 }]
+ : [];
+
return [
{ url: '/agents', name: 'Home', icon: HomeIcon, visible: true, order: 1 },
{ url: '/vault', name: 'Vault', icon: KeyIcon, visible: true, order: 5 },
+ ...devItems,
...pluginItems,
].sort((a, b) => (a.order || 0) - (b.order || 0));
};
diff --git a/packages/app/src/shared/constants/acl.constant.json b/packages/app/src/shared/constants/acl.constant.json
index 109ca63a..0cb96ccf 100644
--- a/packages/app/src/shared/constants/acl.constant.json
+++ b/packages/app/src/shared/constants/acl.constant.json
@@ -23,6 +23,7 @@
"/templates": { "access": "", "name": "Templates" },
"/domains": { "access": "", "name": "Domains" },
"/data": { "access": "", "name": "Data Pool" },
+ "/data-pool": { "access": "", "name": "Data Pool" },
"/vault": { "access": "", "name": "Vault" },
"/analytics": { "access": "", "name": "Analytics" },
"/my-plan": { "access": "", "name": "My Plan" },
diff --git a/packages/app/src/shared/constants/general.ts b/packages/app/src/shared/constants/general.ts
index 1a8b2f33..9c79d792 100644
--- a/packages/app/src/shared/constants/general.ts
+++ b/packages/app/src/shared/constants/general.ts
@@ -100,10 +100,12 @@ export const AGENTS_WITH_NEXT_STEPS_SHOWN = 'agentsWithNextStepsShown';
export const VAULT_SCOPE_AGENT_LLM = 'AgentLLM';
export const VAULT_SCOPE_OAUTH_CONNECTIONS = 'OAuthConnections';
+export const VAULT_SCOPE_CREDENTIALS = 'Credentials';
export const HIDDEN_VAULT_SCOPE = '_hidden';
export const MANAGED_VAULT_SCOPES = [
VAULT_SCOPE_AGENT_LLM,
VAULT_SCOPE_OAUTH_CONNECTIONS,
+ VAULT_SCOPE_CREDENTIALS,
HIDDEN_VAULT_SCOPE,
];
diff --git a/packages/app/src/shared/state_stores/builder/slices/server_status.slice.ts b/packages/app/src/shared/state_stores/builder/slices/server_status.slice.ts
index 2d4beae9..ba43d1dc 100644
--- a/packages/app/src/shared/state_stores/builder/slices/server_status.slice.ts
+++ b/packages/app/src/shared/state_stores/builder/slices/server_status.slice.ts
@@ -16,6 +16,7 @@ export interface ServerStatus {
prod_agent_domain: string;
user: any;
userData: any;
+ edition: string;
}
export interface ServerStatusSlice extends Slice {
@@ -57,6 +58,7 @@ export const serverStatusSlice: StateCreator<BuilderStore, [], [], ServerStatusS
prod_agent_domain: data.prod_agent_domain,
user: data.user,
userData: data.user,
+ edition: data.smythos_edition,
},
});
} catch (err) {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2737528b..3c6d2131 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -7,6 +7,10 @@ settings:
importers:
.:
+ dependencies:
+ form-data:
+ specifier: ^4.0.4
+ version: 4.0.4
devDependencies:
concurrently:
specifier: ^9.1.0
@@ -5188,10 +5192,6 @@ packages:
resolution: {integrity: sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==}
- resolution: {integrity: sha512-qsITQPfmvMOSAdeyZ+12I1c+CKSstAFAwu+97zrnWAbIr5u8wfsExUzCesVLC8NgHuRUqNN4Zy6UPWUTRGslcA==}
- engines: {node: '>= 6'}
-
resolution: {integrity: sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==}
engines: {node: '>= 6'}
@@ -12887,7 +12887,7 @@ snapshots:
dependencies:
follow-redirects: 1.15.9
- form-data: 4.0.3
+ form-data: 4.0.4
proxy-from-env: 1.1.0
transitivePeerDependencies:
- debug
@@ -14570,14 +14570,6 @@ snapshots:
- dependencies:
- asynckit: 0.4.0
- combined-stream: 1.0.8
- es-set-tostringtag: 2.1.0
- hasown: 2.0.2
- mime-types: 2.1.35
-
dependencies:
asynckit: 0.4.0
@@ -16347,7 +16339,7 @@ snapshots:
dependencies:
axios: 0.26.1
- form-data: 4.0.3
+ form-data: 4.0.4
transitivePeerDependencies:
- debug