🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
:white_check_mark: tests: add more tests case
arvinxxb5d33e656430
diff --git a/packages/database/src/models/userMemory/__tests__/context.test.ts b/packages/database/src/models/userMemory/__tests__/context.test.tsnew file mode 100644index 00000000000..3cfe4005f68--- /dev/null+++ b/packages/database/src/models/userMemory/__tests__/context.test.ts@@ -0,0 +1,284 @@+// @vitest-environment node+import { beforeEach, describe, expect, it } from 'vitest';++import { NewUserMemoryContext, userMemories, userMemoriesContexts, users } from '../../../schemas';+import { LobeChatDatabase } from '../../../type';+import { getTestDB } from '../../__tests__/_util';+import { UserMemoryContextModel } from '../context';++const userId = 'context-test-user';+const otherUserId = 'other-context-user';++let contextModel: UserMemoryContextModel;+const serverDB: LobeChatDatabase = await getTestDB();++beforeEach(async () => {+ // Clean up+ await serverDB.delete(users);++ // Create test users+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);++ // Initialize model+ contextModel = new UserMemoryContextModel(serverDB, userId);+});++describe('UserMemoryContextModel', () => {+ describe('create', () => {+ it('should create a new context', async () => {+ const contextData: Omit<NewUserMemoryContext, 'userId'> = {+ title: 'Test Context',+ description: 'Test context description',+ type: 'work',+ currentStatus: 'active',+ };++ const result = await contextModel.create(contextData);++ expect(result).toBeDefined();+ expect(result.id).toBeDefined();+ expect(result.title).toBe('Test Context');+ expect(result.description).toBe('Test context description');+ expect(result.type).toBe('work');+ expect(result.currentStatus).toBe('active');+ });++ it('should auto-assign userId from model', async () => {+ const result = await contextModel.create({+ title: 'User Context',+ });++ expect(result.userId).toBe(userId);+ });+ });++ describe('query', () => {+ beforeEach(async () => {+ // Create test contexts+ await serverDB.insert(userMemoriesContexts).values([+ {+ id: 'context-1',+ userId,+ title: 'Context 1',+ createdAt: new Date('2024-01-01T10:00:00Z'),+ },+ {+ id: 'context-2',+ userId,+ title: 'Context 2',+ createdAt: new Date('2024-01-02T10:00:00Z'),+ },+ {+ id: 'other-context',+ userId: otherUserId,+ title: 'Other User Context',+ createdAt: new Date('2024-01-03T10:00:00Z'),+ },+ ]);+ });++ it('should return contexts for current user only', async () => {+ const result = await contextModel.query();++ expect(result).toHaveLength(2);+ expect(result.every((c) => c.userId === userId)).toBe(true);+ });++ it('should order by createdAt desc', async () => {+ const result = await contextModel.query();++ expect(result[0].id).toBe('context-2'); // Most recent first+ expect(result[1].id).toBe('context-1');+ });++ it('should respect limit parameter', async () => {+ const result = await contextModel.query(1);++ expect(result).toHaveLength(1);+ expect(result[0].id).toBe('context-2');+ });++ it('should not return other users contexts', async () => {+ const result = await contextModel.query();++ const otherContext = result.find((c) => c.id === 'other-context');+ expect(otherContext).toBeUndefined();+ });+ });++ describe('findById', () => {+ beforeEach(async () => {+ await serverDB.insert(userMemoriesContexts).values([+ {+ id: 'find-context-1',+ userId,+ title: 'Find Context 1',+ },+ {+ id: 'find-context-other',+ userId: otherUserId,+ title: 'Other User Context',+ },+ ]);+ });++ it('should find context by ID for current user', async () => {+ const result = await contextModel.findById('find-context-1');++ expect(result).toBeDefined();+ expect(result?.id).toBe('find-context-1');+ expect(result?.title).toBe('Find Context 1');+ });++ it('should return undefined for non-existent context', async () => {+ const result = await contextModel.findById('non-existent');++ expect(result).toBeUndefined();+ });++ it('should not find contexts belonging to other users', async () => {+ const result = await contextModel.findById('find-context-other');++ expect(result).toBeUndefined();+ });+ });++ describe('update', () => {+ beforeEach(async () => {+ await serverDB.insert(userMemoriesContexts).values([+ {+ id: 'update-context',+ userId,+ title: 'Original Title',+ description: 'Original description',+ },+ {+ id: 'other-user-context',+ userId: otherUserId,+ title: 'Other User Context',+ },+ ]);+ });++ it('should update context', async () => {+ await contextModel.update('update-context', {+ title: 'Updated Title',+ description: 'Updated description',+ });++ const updated = await contextModel.findById('update-context');+ expect(updated?.title).toBe('Updated Title');+ expect(updated?.description).toBe('Updated description');+ });++ it('should not update contexts belonging to other users', async () => {+ await contextModel.update('other-user-context', {+ title: 'Hacked Title',+ });++ // Verify the other user's context was not updated+ const result = await serverDB.query.userMemoriesContexts.findFirst({+ where: (c, { eq }) => eq(c.id, 'other-user-context'),+ });+ expect(result?.title).toBe('Other User Context');+ });+ });++ describe('delete', () => {+ it('should delete context and associated user memories', async () => {+ // Create a user memory first+ const [memory] = await serverDB+ .insert(userMemories)+ .values({+ id: 'associated-memory',+ userId,+ title: 'Associated Memory',+ lastAccessedAt: new Date(),+ })+ .returning();++ // Create context with associated memory+ await serverDB.insert(userMemoriesContexts).values({+ id: 'delete-context',+ userId,+ title: 'Context to Delete',+ userMemoryIds: [memory.id],+ });++ const result = await contextModel.delete('delete-context');++ expect(result.success).toBe(true);++ // Verify context was deleted+ const deletedContext = await contextModel.findById('delete-context');+ expect(deletedContext).toBeUndefined();++ // Verify associated memory was also deleted+ const deletedMemory = await serverDB.query.userMemories.findFirst({+ where: (m, { eq }) => eq(m.id, 'associated-memory'),+ });+ expect(deletedMemory).toBeUndefined();+ });++ it('should return success: false for non-existent context', async () => {+ const result = await contextModel.delete('non-existent');++ expect(result.success).toBe(false);+ });++ it('should not delete contexts belonging to other users', async () => {+ await serverDB.insert(userMemoriesContexts).values({+ id: 'other-delete-context',+ userId: otherUserId,+ title: 'Other User Context',+ });++ const result = await contextModel.delete('other-delete-context');++ expect(result.success).toBe(false);++ // Verify the context still exists+ const stillExists = await serverDB.query.userMemoriesContexts.findFirst({+ where: (c, { eq }) => eq(c.id, 'other-delete-context'),+ });+ expect(stillExists).toBeDefined();+ });++ it('should handle context without associated memories', async () => {+ await serverDB.insert(userMemoriesContexts).values({+ id: 'no-memories-context',+ userId,+ title: 'Context without memories',+ userMemoryIds: [],+ });++ const result = await contextModel.delete('no-memories-context');++ expect(result.success).toBe(true);+ });+ });++ describe('deleteAll', () => {+ beforeEach(async () => {+ await serverDB.insert(userMemoriesContexts).values([+ { id: 'user-context-1', userId, title: 'User Context 1' },+ { id: 'user-context-2', userId, title: 'User Context 2' },+ { id: 'other-context', userId: otherUserId, title: 'Other Context' },+ ]);+ });++ it('should delete all contexts for current user only', async () => {+ await contextModel.deleteAll();++ // Verify user's contexts were deleted+ const userContexts = await contextModel.query();+ expect(userContexts).toHaveLength(0);++ // Verify other user's context still exists+ const otherContext = await serverDB.query.userMemoriesContexts.findFirst({+ where: (c, { eq }) => eq(c.id, 'other-context'),+ });+ expect(otherContext).toBeDefined();+ });+ });+});diff --git a/packages/database/src/models/userMemory/__tests__/experience.test.ts b/packages/database/src/models/userMemory/__tests__/experience.test.tsnew file mode 100644index 00000000000..58572f5d26e--- /dev/null+++ b/packages/database/src/models/userMemory/__tests__/experience.test.ts@@ -0,0 +1,317 @@+// @vitest-environment node+import { beforeEach, describe, expect, it } from 'vitest';++import {+ NewUserMemoryExperience,+ userMemories,+ userMemoriesExperiences,+ users,+} from '../../../schemas';+import { LobeChatDatabase } from '../../../type';+import { getTestDB } from '../../__tests__/_util';+import { UserMemoryExperienceModel } from '../experience';++const userId = 'experience-test-user';+const otherUserId = 'other-experience-user';++let experienceModel: UserMemoryExperienceModel;+const serverDB: LobeChatDatabase = await getTestDB();++beforeEach(async () => {+ // Clean up+ await serverDB.delete(users);++ // Create test users+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);++ // Initialize model+ experienceModel = new UserMemoryExperienceModel(serverDB, userId);+});++describe('UserMemoryExperienceModel', () => {+ describe('create', () => {+ it('should create a new experience', async () => {+ const experienceData: Omit<NewUserMemoryExperience, 'userId'> = {+ type: 'lesson',+ situation: 'When debugging code',+ reasoning: 'Checking logs helps identify issues',+ action: 'Read logs first',+ keyLearning: 'Always check logs before debugging',+ };++ const result = await experienceModel.create(experienceData);++ expect(result).toBeDefined();+ expect(result.id).toBeDefined();+ expect(result.type).toBe('lesson');+ expect(result.situation).toBe('When debugging code');+ expect(result.action).toBe('Read logs first');+ });++ it('should auto-assign userId from model', async () => {+ const result = await experienceModel.create({+ type: 'insight',+ situation: 'Test situation',+ });++ expect(result.userId).toBe(userId);+ });+ });++ describe('query', () => {+ beforeEach(async () => {+ // Create test experiences+ await serverDB.insert(userMemoriesExperiences).values([+ {+ id: 'experience-1',+ userId,+ type: 'lesson',+ situation: 'Situation 1',+ createdAt: new Date('2024-01-01T10:00:00Z'),+ },+ {+ id: 'experience-2',+ userId,+ type: 'insight',+ situation: 'Situation 2',+ createdAt: new Date('2024-01-02T10:00:00Z'),+ },+ {+ id: 'other-experience',+ userId: otherUserId,+ type: 'lesson',+ situation: 'Other Situation',+ createdAt: new Date('2024-01-03T10:00:00Z'),+ },+ ]);+ });++ it('should return experiences for current user only', async () => {+ const result = await experienceModel.query();++ expect(result).toHaveLength(2);+ expect(result.every((e) => e.userId === userId)).toBe(true);+ });++ it('should order by createdAt desc', async () => {+ const result = await experienceModel.query();++ expect(result[0].id).toBe('experience-2'); // Most recent first+ expect(result[1].id).toBe('experience-1');+ });++ it('should respect limit parameter', async () => {+ const result = await experienceModel.query(1);++ expect(result).toHaveLength(1);+ expect(result[0].id).toBe('experience-2');+ });++ it('should not return other users experiences', async () => {+ const result = await experienceModel.query();++ const otherExperience = result.find((e) => e.id === 'other-experience');+ expect(otherExperience).toBeUndefined();+ });+ });++ describe('findById', () => {+ beforeEach(async () => {+ await serverDB.insert(userMemoriesExperiences).values([+ {+ id: 'find-experience-1',+ userId,+ type: 'lesson',+ situation: 'Find Situation 1',+ },+ {+ id: 'find-experience-other',+ userId: otherUserId,+ type: 'lesson',+ situation: 'Other Situation',+ },+ ]);+ });++ it('should find experience by ID for current user', async () => {+ const result = await experienceModel.findById('find-experience-1');++ expect(result).toBeDefined();+ expect(result?.id).toBe('find-experience-1');+ expect(result?.situation).toBe('Find Situation 1');+ });++ it('should return undefined for non-existent experience', async () => {+ const result = await experienceModel.findById('non-existent');++ expect(result).toBeUndefined();+ });++ it('should not find experiences belonging to other users', async () => {+ const result = await experienceModel.findById('find-experience-other');++ expect(result).toBeUndefined();+ });+ });++ describe('update', () => {+ beforeEach(async () => {+ await serverDB.insert(userMemoriesExperiences).values([+ {+ id: 'update-experience',+ userId,+ type: 'lesson',+ situation: 'Original Situation',+ action: 'Original Action',+ },+ {+ id: 'other-user-experience',+ userId: otherUserId,+ type: 'lesson',+ situation: 'Other Situation',+ },+ ]);+ });++ it('should update experience', async () => {+ await experienceModel.update('update-experience', {+ situation: 'Updated Situation',+ action: 'Updated Action',+ });++ const updated = await experienceModel.findById('update-experience');+ expect(updated?.situation).toBe('Updated Situation');+ expect(updated?.action).toBe('Updated Action');+ });++ it('should not update experiences belonging to other users', async () => {+ await experienceModel.update('other-user-experience', {+ situation: 'Hacked Situation',+ });++ // Verify the other user's experience was not updated+ const result = await serverDB.query.userMemoriesExperiences.findFirst({+ where: (e, { eq }) => eq(e.id, 'other-user-experience'),+ });+ expect(result?.situation).toBe('Other Situation');+ });+ });++ describe('delete', () => {+ it('should delete experience and associated user memory', async () => {+ // Create a user memory first+ const [memory] = await serverDB+ .insert(userMemories)+ .values({+ id: 'experience-memory',+ userId,+ title: 'Experience Memory',+ lastAccessedAt: new Date(),+ })+ .returning();++ // Create experience with associated memory+ await serverDB.insert(userMemoriesExperiences).values({+ id: 'delete-experience',+ userId,+ type: 'lesson',+ situation: 'Experience to Delete',+ userMemoryId: memory.id,+ });++ const result = await experienceModel.delete('delete-experience');++ expect(result.success).toBe(true);++ // Verify experience was deleted+ const deletedExperience = await experienceModel.findById('delete-experience');+ expect(deletedExperience).toBeUndefined();++ // Verify associated memory was also deleted+ const deletedMemory = await serverDB.query.userMemories.findFirst({+ where: (m, { eq }) => eq(m.id, 'experience-memory'),+ });+ expect(deletedMemory).toBeUndefined();+ });++ it('should return success: false for non-existent experience', async () => {+ const result = await experienceModel.delete('non-existent');++ expect(result.success).toBe(false);+ });++ it('should return success: false for experience without userMemoryId', async () => {+ await serverDB.insert(userMemoriesExperiences).values({+ id: 'no-memory-experience',+ userId,+ type: 'lesson',+ situation: 'No memory linked',+ userMemoryId: null,+ });++ const result = await experienceModel.delete('no-memory-experience');++ expect(result.success).toBe(false);+ });++ it('should not delete experiences belonging to other users', async () => {+ // Create memory for other user+ const [otherMemory] = await serverDB+ .insert(userMemories)+ .values({+ id: 'other-experience-memory',+ userId: otherUserId,+ title: 'Other Memory',+ lastAccessedAt: new Date(),+ })+ .returning();++ await serverDB.insert(userMemoriesExperiences).values({+ id: 'other-delete-experience',+ userId: otherUserId,+ type: 'lesson',+ situation: 'Other Experience',+ userMemoryId: otherMemory.id,+ });++ const result = await experienceModel.delete('other-delete-experience');++ expect(result.success).toBe(false);++ // Verify the experience still exists+ const stillExists = await serverDB.query.userMemoriesExperiences.findFirst({+ where: (e, { eq }) => eq(e.id, 'other-delete-experience'),+ });+ expect(stillExists).toBeDefined();+ });+ });++ describe('deleteAll', () => {+ beforeEach(async () => {+ await serverDB.insert(userMemoriesExperiences).values([+ { id: 'user-experience-1', userId, type: 'lesson', situation: 'User Experience 1' },+ { id: 'user-experience-2', userId, type: 'insight', situation: 'User Experience 2' },+ {+ id: 'other-experience',+ userId: otherUserId,+ type: 'lesson',+ situation: 'Other Experience',+ },+ ]);+ });++ it('should delete all experiences for current user only', async () => {+ await experienceModel.deleteAll();++ // Verify user's experiences were deleted+ const userExperiences = await experienceModel.query();+ expect(userExperiences).toHaveLength(0);++ // Verify other user's experience still exists+ const otherExperience = await serverDB.query.userMemoriesExperiences.findFirst({+ where: (e, { eq }) => eq(e.id, 'other-experience'),+ });+ expect(otherExperience).toBeDefined();+ });+ });+});diff --git a/packages/database/src/models/userMemory/__tests__/preference.test.ts b/packages/database/src/models/userMemory/__tests__/preference.test.tsnew file mode 100644index 00000000000..c76b652c95a--- /dev/null+++ b/packages/database/src/models/userMemory/__tests__/preference.test.ts@@ -0,0 +1,325 @@+// @vitest-environment node+import { beforeEach, describe, expect, it } from 'vitest';++import {+ NewUserMemoryPreference,+ userMemories,+ userMemoriesPreferences,+ users,+} from '../../../schemas';+import { LobeChatDatabase } from '../../../type';+import { getTestDB } from '../../__tests__/_util';+import { UserMemoryPreferenceModel } from '../preference';++const userId = 'preference-test-user';+const otherUserId = 'other-preference-user';++let preferenceModel: UserMemoryPreferenceModel;+const serverDB: LobeChatDatabase = await getTestDB();++beforeEach(async () => {+ // Clean up+ await serverDB.delete(users);++ // Create test users+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);++ // Initialize model+ preferenceModel = new UserMemoryPreferenceModel(serverDB, userId);+});++describe('UserMemoryPreferenceModel', () => {+ describe('create', () => {+ it('should create a new preference', async () => {+ const preferenceData: Omit<NewUserMemoryPreference, 'userId'> = {+ type: 'communication',+ conclusionDirectives: 'Prefer concise responses',+ suggestions: 'Use bullet points when possible',+ };++ const result = await preferenceModel.create(preferenceData);++ expect(result).toBeDefined();+ expect(result.id).toBeDefined();+ expect(result.type).toBe('communication');+ expect(result.conclusionDirectives).toBe('Prefer concise responses');+ expect(result.suggestions).toBe('Use bullet points when possible');+ });++ it('should auto-assign userId from model', async () => {+ const result = await preferenceModel.create({+ type: 'style',+ conclusionDirectives: 'Test directive',+ });++ expect(result.userId).toBe(userId);+ });+ });++ describe('query', () => {+ beforeEach(async () => {+ // Create test preferences+ await serverDB.insert(userMemoriesPreferences).values([+ {+ id: 'preference-1',+ userId,+ type: 'communication',+ conclusionDirectives: 'Directive 1',+ createdAt: new Date('2024-01-01T10:00:00Z'),+ },+ {+ id: 'preference-2',+ userId,+ type: 'style',+ conclusionDirectives: 'Directive 2',+ createdAt: new Date('2024-01-02T10:00:00Z'),+ },+ {+ id: 'other-preference',+ userId: otherUserId,+ type: 'communication',+ conclusionDirectives: 'Other Directive',+ createdAt: new Date('2024-01-03T10:00:00Z'),+ },+ ]);+ });++ it('should return preferences for current user only', async () => {+ const result = await preferenceModel.query();++ expect(result).toHaveLength(2);+ expect(result.every((p) => p.userId === userId)).toBe(true);+ });++ it('should order by createdAt desc', async () => {+ const result = await preferenceModel.query();++ expect(result[0].id).toBe('preference-2'); // Most recent first+ expect(result[1].id).toBe('preference-1');+ });++ it('should respect limit parameter', async () => {+ const result = await preferenceModel.query(1);++ expect(result).toHaveLength(1);+ expect(result[0].id).toBe('preference-2');+ });++ it('should not return other users preferences', async () => {+ const result = await preferenceModel.query();++ const otherPreference = result.find((p) => p.id === 'other-preference');+ expect(otherPreference).toBeUndefined();+ });+ });++ describe('findById', () => {+ beforeEach(async () => {+ await serverDB.insert(userMemoriesPreferences).values([+ {+ id: 'find-preference-1',+ userId,+ type: 'communication',+ conclusionDirectives: 'Find Directive 1',+ },+ {+ id: 'find-preference-other',+ userId: otherUserId,+ type: 'communication',+ conclusionDirectives: 'Other Directive',+ },+ ]);+ });++ it('should find preference by ID for current user', async () => {+ const result = await preferenceModel.findById('find-preference-1');++ expect(result).toBeDefined();+ expect(result?.id).toBe('find-preference-1');+ expect(result?.conclusionDirectives).toBe('Find Directive 1');+ });++ it('should return undefined for non-existent preference', async () => {+ const result = await preferenceModel.findById('non-existent');++ expect(result).toBeUndefined();+ });++ it('should not find preferences belonging to other users', async () => {+ const result = await preferenceModel.findById('find-preference-other');++ expect(result).toBeUndefined();+ });+ });++ describe('update', () => {+ beforeEach(async () => {+ await serverDB.insert(userMemoriesPreferences).values([+ {+ id: 'update-preference',+ userId,+ type: 'communication',+ conclusionDirectives: 'Original Directive',+ suggestions: 'Original Suggestion',+ },+ {+ id: 'other-user-preference',+ userId: otherUserId,+ type: 'communication',+ conclusionDirectives: 'Other Directive',+ },+ ]);+ });++ it('should update preference', async () => {+ await preferenceModel.update('update-preference', {+ conclusionDirectives: 'Updated Directive',+ suggestions: 'Updated Suggestion',+ });++ const updated = await preferenceModel.findById('update-preference');+ expect(updated?.conclusionDirectives).toBe('Updated Directive');+ expect(updated?.suggestions).toBe('Updated Suggestion');+ });++ it('should not update preferences belonging to other users', async () => {+ await preferenceModel.update('other-user-preference', {+ conclusionDirectives: 'Hacked Directive',+ });++ // Verify the other user's preference was not updated+ const result = await serverDB.query.userMemoriesPreferences.findFirst({+ where: (p, { eq }) => eq(p.id, 'other-user-preference'),+ });+ expect(result?.conclusionDirectives).toBe('Other Directive');+ });+ });++ describe('delete', () => {+ it('should delete preference and associated user memory', async () => {+ // Create a user memory first+ const [memory] = await serverDB+ .insert(userMemories)+ .values({+ id: 'preference-memory',+ userId,+ title: 'Preference Memory',+ lastAccessedAt: new Date(),+ })+ .returning();++ // Create preference with associated memory+ await serverDB.insert(userMemoriesPreferences).values({+ id: 'delete-preference',+ userId,+ type: 'communication',+ conclusionDirectives: 'Preference to Delete',+ userMemoryId: memory.id,+ });++ const result = await preferenceModel.delete('delete-preference');++ expect(result.success).toBe(true);++ // Verify preference was deleted+ const deletedPreference = await preferenceModel.findById('delete-preference');+ expect(deletedPreference).toBeUndefined();++ // Verify associated memory was also deleted+ const deletedMemory = await serverDB.query.userMemories.findFirst({+ where: (m, { eq }) => eq(m.id, 'preference-memory'),+ });+ expect(deletedMemory).toBeUndefined();+ });++ it('should return success: false for non-existent preference', async () => {+ const result = await preferenceModel.delete('non-existent');++ expect(result.success).toBe(false);+ });++ it('should return success: false for preference without userMemoryId', async () => {+ await serverDB.insert(userMemoriesPreferences).values({+ id: 'no-memory-preference',+ userId,+ type: 'communication',+ conclusionDirectives: 'No memory linked',+ userMemoryId: null,+ });++ const result = await preferenceModel.delete('no-memory-preference');++ expect(result.success).toBe(false);+ });++ it('should not delete preferences belonging to other users', async () => {+ // Create memory for other user+ const [otherMemory] = await serverDB+ .insert(userMemories)+ .values({+ id: 'other-preference-memory',+ userId: otherUserId,+ title: 'Other Memory',+ lastAccessedAt: new Date(),+ })+ .returning();++ await serverDB.insert(userMemoriesPreferences).values({+ id: 'other-delete-preference',+ userId: otherUserId,+ type: 'communication',+ conclusionDirectives: 'Other Preference',+ userMemoryId: otherMemory.id,+ });++ const result = await preferenceModel.delete('other-delete-preference');++ expect(result.success).toBe(false);++ // Verify the preference still exists+ const stillExists = await serverDB.query.userMemoriesPreferences.findFirst({+ where: (p, { eq }) => eq(p.id, 'other-delete-preference'),+ });+ expect(stillExists).toBeDefined();+ });+ });++ describe('deleteAll', () => {+ beforeEach(async () => {+ await serverDB.insert(userMemoriesPreferences).values([+ {+ id: 'user-preference-1',+ userId,+ type: 'communication',+ conclusionDirectives: 'User Preference 1',+ },+ {+ id: 'user-preference-2',+ userId,+ type: 'style',+ conclusionDirectives: 'User Preference 2',+ },+ {+ id: 'other-preference',+ userId: otherUserId,+ type: 'communication',+ conclusionDirectives: 'Other Preference',+ },+ ]);+ });++ it('should delete all preferences for current user only', async () => {+ await preferenceModel.deleteAll();++ // Verify user's preferences were deleted+ const userPreferences = await preferenceModel.query();+ expect(userPreferences).toHaveLength(0);++ // Verify other user's preference still exists+ const otherPreference = await serverDB.query.userMemoriesPreferences.findFirst({+ where: (p, { eq }) => eq(p.id, 'other-preference'),+ });+ expect(otherPreference).toBeDefined();+ });+ });+});diff --git a/packages/database/src/repositories/agentGroup/index.test.ts b/packages/database/src/repositories/agentGroup/index.test.tsindex 1c4a0f2f8e4..c094e843eff 100644--- a/packages/database/src/repositories/agentGroup/index.test.ts+++ b/packages/database/src/repositories/agentGroup/index.test.ts@@ -519,4 +519,251 @@ describe('AgentGroupRepository', () => {expect(result.agents).toEqual([expect.objectContaining({ role: 'supervisor' })]);});});++ describe('checkAgentsBeforeRemoval', () => {+ beforeEach(async () => {+ // Create a group+ await serverDB.insert(chatGroups).values({+ id: 'check-removal-group',+ title: 'Check Removal Group',+ userId,+ });++ // Create virtual and non-virtual agents+ await serverDB.insert(agents).values([+ {+ avatar: 'virtual-avatar.png',+ description: 'Virtual agent description',+ id: 'virtual-agent',+ title: 'Virtual Agent',+ userId,+ virtual: true,+ },+ {+ avatar: 'regular-avatar.png',+ description: 'Regular agent description',+ id: 'regular-agent',+ title: 'Regular Agent',+ userId,+ virtual: false,+ },+ {+ id: 'another-regular',+ title: 'Another Regular',+ userId,+ virtual: false,+ },+ ]);++ // Link agents to group+ await serverDB.insert(chatGroupsAgents).values([+ { agentId: 'virtual-agent', chatGroupId: 'check-removal-group', order: 0, userId },+ { agentId: 'regular-agent', chatGroupId: 'check-removal-group', order: 1, userId },+ { agentId: 'another-regular', chatGroupId: 'check-removal-group', order: 2, userId },+ ]);+ });++ it('should separate virtual and non-virtual agents', async () => {+ const result = await agentGroupRepo.checkAgentsBeforeRemoval('check-removal-group', [+ 'virtual-agent',+ 'regular-agent',+ 'another-regular',+ ]);++ expect(result.virtualAgents).toHaveLength(1);+ expect(result.virtualAgents).toEqual([+ expect.objectContaining({+ avatar: 'virtual-avatar.png',+ description: 'Virtual agent description',+ id: 'virtual-agent',+ title: 'Virtual Agent',+ }),+ ]);++ expect(result.nonVirtualAgentIds).toHaveLength(2);+ expect(result.nonVirtualAgentIds).toEqual(+ expect.arrayContaining(['regular-agent', 'another-regular']),+ );+ });++ it('should return empty arrays for empty input', async () => {+ const result = await agentGroupRepo.checkAgentsBeforeRemoval('check-removal-group', []);++ expect(result.virtualAgents).toEqual([]);+ expect(result.nonVirtualAgentIds).toEqual([]);+ });++ it('should only return virtual agents when all are virtual', async () => {+ const result = await agentGroupRepo.checkAgentsBeforeRemoval('check-removal-group', [+ 'virtual-agent',+ ]);++ expect(result.virtualAgents).toHaveLength(1);+ expect(result.virtualAgents[0].id).toBe('virtual-agent');+ expect(result.nonVirtualAgentIds).toEqual([]);+ });++ it('should only return non-virtual agents when none are virtual', async () => {+ const result = await agentGroupRepo.checkAgentsBeforeRemoval('check-removal-group', [+ 'regular-agent',+ 'another-regular',+ ]);++ expect(result.virtualAgents).toEqual([]);+ expect(result.nonVirtualAgentIds).toEqual(+ expect.arrayContaining(['regular-agent', 'another-regular']),+ );+ });++ it('should not include agents belonging to other users', async () => {+ // Create agent for other user+ await serverDB.insert(agents).values({+ id: 'other-user-agent',+ title: 'Other User Agent',+ userId: otherUserId,+ virtual: true,+ });++ const result = await agentGroupRepo.checkAgentsBeforeRemoval('check-removal-group', [+ 'virtual-agent',+ 'other-user-agent',+ ]);++ // Should only include current user's virtual agent+ expect(result.virtualAgents).toHaveLength(1);+ expect(result.virtualAgents[0].id).toBe('virtual-agent');+ expect(result.nonVirtualAgentIds).toEqual([]);+ });+ });++ describe('removeAgentsFromGroup', () => {+ beforeEach(async () => {+ // Create a group+ await serverDB.insert(chatGroups).values({+ id: 'remove-group',+ title: 'Remove Group',+ userId,+ });++ // Create virtual and non-virtual agents+ await serverDB.insert(agents).values([+ { id: 'remove-virtual', title: 'Virtual to Remove', userId, virtual: true },+ { id: 'remove-regular', title: 'Regular to Remove', userId, virtual: false },+ { id: 'keep-agent', title: 'Keep Agent', userId, virtual: false },+ ]);++ // Link agents to group+ await serverDB.insert(chatGroupsAgents).values([+ { agentId: 'remove-virtual', chatGroupId: 'remove-group', order: 0, userId },+ { agentId: 'remove-regular', chatGroupId: 'remove-group', order: 1, userId },+ { agentId: 'keep-agent', chatGroupId: 'remove-group', order: 2, userId },+ ]);+ });++ it('should remove agents from group and delete virtual agents', async () => {+ const result = await agentGroupRepo.removeAgentsFromGroup('remove-group', [+ 'remove-virtual',+ 'remove-regular',+ ]);++ expect(result.removedFromGroup).toBe(2);+ expect(result.deletedVirtualAgentIds).toEqual(['remove-virtual']);++ // Verify agents were removed from group+ const groupAgents = await serverDB.query.chatGroupsAgents.findMany({+ where: (cga, { eq }) => eq(cga.chatGroupId, 'remove-group'),+ });+ expect(groupAgents).toHaveLength(1);+ expect(groupAgents[0].agentId).toBe('keep-agent');++ // Verify virtual agent was deleted+ const deletedVirtual = await serverDB.query.agents.findFirst({+ where: (a, { eq }) => eq(a.id, 'remove-virtual'),+ });+ expect(deletedVirtual).toBeUndefined();++ // Verify regular agent still exists (just removed from group)+ const regularAgent = await serverDB.query.agents.findFirst({+ where: (a, { eq }) => eq(a.id, 'remove-regular'),+ });+ expect(regularAgent).toBeDefined();+ });++ it('should not delete virtual agents when deleteVirtualAgents is false', async () => {+ const result = await agentGroupRepo.removeAgentsFromGroup(+ 'remove-group',+ ['remove-virtual'],+ false,+ );++ expect(result.removedFromGroup).toBe(1);+ expect(result.deletedVirtualAgentIds).toEqual([]);++ // Verify virtual agent still exists+ const virtualAgent = await serverDB.query.agents.findFirst({+ where: (a, { eq }) => eq(a.id, 'remove-virtual'),+ });+ expect(virtualAgent).toBeDefined();+ });++ it('should return empty result for empty input', async () => {+ const result = await agentGroupRepo.removeAgentsFromGroup('remove-group', []);++ expect(result.removedFromGroup).toBe(0);+ expect(result.deletedVirtualAgentIds).toEqual([]);+ });++ it('should remove only non-virtual agents correctly', async () => {+ const result = await agentGroupRepo.removeAgentsFromGroup('remove-group', ['remove-regular']);++ expect(result.removedFromGroup).toBe(1);+ expect(result.deletedVirtualAgentIds).toEqual([]);++ // Verify agent was removed from group+ const groupAgents = await serverDB.query.chatGroupsAgents.findMany({+ where: (cga, { eq }) => eq(cga.chatGroupId, 'remove-group'),+ });+ expect(groupAgents).toHaveLength(2);+ expect(groupAgents.map((g) => g.agentId)).not.toContain('remove-regular');++ // Verify agent still exists+ const agent = await serverDB.query.agents.findFirst({+ where: (a, { eq }) => eq(a.id, 'remove-regular'),+ });+ expect(agent).toBeDefined();+ });++ it('should handle multiple virtual agents', async () => {+ // Add another virtual agent+ await serverDB.insert(agents).values({+ id: 'remove-virtual-2',+ title: 'Virtual 2 to Remove',+ userId,+ virtual: true,+ });+ await serverDB.insert(chatGroupsAgents).values({+ agentId: 'remove-virtual-2',+ chatGroupId: 'remove-group',+ order: 3,+ userId,+ });++ const result = await agentGroupRepo.removeAgentsFromGroup('remove-group', [+ 'remove-virtual',+ 'remove-virtual-2',+ ]);++ expect(result.removedFromGroup).toBe(2);+ expect(result.deletedVirtualAgentIds).toEqual(+ expect.arrayContaining(['remove-virtual', 'remove-virtual-2']),+ );++ // Verify both virtual agents were deleted+ const virtualAgents = await serverDB.query.agents.findMany({+ where: (a, { and, eq, inArray }) =>+ and(eq(a.userId, userId), inArray(a.id, ['remove-virtual', 'remove-virtual-2'])),+ });+ expect(virtualAgents).toHaveLength(0);+ });+ });});diff --git a/packages/database/src/repositories/knowledge/index.test.ts b/packages/database/src/repositories/knowledge/index.test.tsindex 8175407f6a2..e492997ba73 100644--- a/packages/database/src/repositories/knowledge/index.test.ts+++ b/packages/database/src/repositories/knowledge/index.test.ts@@ -309,4 +309,415 @@ describe('KnowledgeRepo', () => {expect(results[0].name).toBe('Meeting Notes');});});++ describe('query - category filters', () => {+ beforeEach(async () => {+ // Create files of different types+ await serverDB.insert(files).values([+ {+ id: 'image-file',+ fileType: 'image/png',+ name: 'photo.png',+ size: 1024,+ url: 'image-url',+ userId,+ },+ {+ id: 'video-file',+ fileType: 'video/mp4',+ name: 'video.mp4',+ size: 2048,+ url: 'video-url',+ userId,+ },+ {+ id: 'audio-file',+ fileType: 'audio/mp3',+ name: 'music.mp3',+ size: 512,+ url: 'audio-url',+ userId,+ },+ {+ id: 'html-file',+ fileType: 'text/html',+ name: 'page.html',+ size: 256,+ url: 'html-url',+ userId,+ },+ ]);+ });++ it('should filter by Images category', async () => {+ const results = await knowledgeRepo.query({ category: FilesTabs.Images });++ expect(results).toHaveLength(1);+ expect(results[0].name).toBe('photo.png');+ expect(results[0].fileType).toBe('image/png');+ });++ it('should filter by Videos category', async () => {+ const results = await knowledgeRepo.query({ category: FilesTabs.Videos });++ expect(results).toHaveLength(1);+ expect(results[0].name).toBe('video.mp4');+ expect(results[0].fileType).toBe('video/mp4');+ });++ it('should filter by Audios category', async () => {+ const results = await knowledgeRepo.query({ category: FilesTabs.Audios });++ expect(results).toHaveLength(1);+ expect(results[0].name).toBe('music.mp3');+ expect(results[0].fileType).toBe('audio/mp3');+ });++ it('should filter by Websites category', async () => {+ const results = await knowledgeRepo.query({ category: FilesTabs.Websites });++ expect(results).toHaveLength(1);+ expect(results[0].name).toBe('page.html');+ expect(results[0].fileType).toBe('text/html');+ });+ });++ describe('query - sorting', () => {+ beforeEach(async () => {+ await serverDB.insert(files).values([+ {+ id: 'file-a',+ fileType: 'application/pdf',+ name: 'a-file.pdf',+ size: 100,+ url: 'url-a',+ userId,+ createdAt: new Date('2024-01-01T10:00:00Z'),+ updatedAt: new Date('2024-01-05T10:00:00Z'),+ },+ {+ id: 'file-b',+ fileType: 'application/pdf',+ name: 'b-file.pdf',+ size: 200,+ url: 'url-b',+ userId,+ createdAt: new Date('2024-01-02T10:00:00Z'),+ updatedAt: new Date('2024-01-03T10:00:00Z'),+ },+ ]);+ });++ it('should sort by name ascending', async () => {+ const results = await knowledgeRepo.query({+ category: FilesTabs.All,+ sorter: 'name',+ sortType: 'asc',+ });++ expect(results[0].name).toBe('a-file.pdf');+ expect(results[1].name).toBe('b-file.pdf');+ });++ it('should sort by name descending', async () => {+ const results = await knowledgeRepo.query({+ category: FilesTabs.All,+ sorter: 'name',+ sortType: 'desc',+ });++ expect(results[0].name).toBe('b-file.pdf');+ expect(results[1].name).toBe('a-file.pdf');+ });++ it('should sort by size ascending', async () => {+ const results = await knowledgeRepo.query({+ category: FilesTabs.All,+ sorter: 'size',+ sortType: 'asc',+ });++ expect(results[0].size).toBe(100);+ expect(results[1].size).toBe(200);+ });+ });++ describe('query - pagination', () => {+ beforeEach(async () => {+ // Create 5 files+ const testFiles = Array.from({ length: 5 }, (_, i) => ({+ id: `paginate-file-${i}`,+ fileType: 'application/pdf',+ name: `file-${i}.pdf`,+ size: 100 * (i + 1),+ url: `url-${i}`,+ userId,+ createdAt: new Date(`2024-01-0${i + 1}T10:00:00Z`),+ }));++ await serverDB.insert(files).values(testFiles);+ });++ it('should respect limit parameter', async () => {+ const results = await knowledgeRepo.query({ limit: 2 });++ expect(results).toHaveLength(2);+ });++ it('should respect offset parameter', async () => {+ const results = await knowledgeRepo.query({ limit: 2, offset: 2 });++ expect(results).toHaveLength(2);+ });+ });++ describe('queryRecent', () => {+ beforeEach(async () => {+ // Create files with different updated times+ await serverDB.insert(files).values([+ {+ id: 'recent-file-1',+ fileType: 'application/pdf',+ name: 'recent-1.pdf',+ size: 1024,+ url: 'url-1',+ userId,+ updatedAt: new Date('2024-01-03T10:00:00Z'),+ },+ {+ id: 'recent-file-2',+ fileType: 'application/pdf',+ name: 'recent-2.pdf',+ size: 1024,+ url: 'url-2',+ userId,+ updatedAt: new Date('2024-01-01T10:00:00Z'),+ },+ {+ id: 'other-user-file',+ fileType: 'application/pdf',+ name: 'other-recent.pdf',+ size: 1024,+ url: 'url-other',+ userId: otherUserId,+ updatedAt: new Date('2024-01-05T10:00:00Z'),+ },+ ]);++ // Create documents+ await serverDB.insert(documents).values([+ {+ id: 'recent-doc-1',+ content: 'Recent document content',+ fileType: 'custom/other',+ filename: 'recent-doc.txt',+ source: 'api-source',+ sourceType: 'api',+ totalCharCount: 100,+ totalLineCount: 10,+ userId,+ updatedAt: new Date('2024-01-02T10:00:00Z'),+ },+ ]);+ });++ it('should return recent items ordered by updatedAt desc', async () => {+ const results = await knowledgeRepo.queryRecent(10);++ // Should return items for current user only, ordered by updatedAt desc+ expect(results).toHaveLength(3);+ expect(results[0].name).toBe('recent-1.pdf'); // Most recent+ expect(results[1].name).toBe('recent-doc.txt');+ expect(results[2].name).toBe('recent-2.pdf'); // Least recent+ });++ it('should respect limit parameter', async () => {+ const results = await knowledgeRepo.queryRecent(2);++ expect(results).toHaveLength(2);+ });++ it('should not return other users items', async () => {+ const results = await knowledgeRepo.queryRecent(10);++ const otherUserItem = results.find((item) => item.name === 'other-recent.pdf');+ expect(otherUserItem).toBeUndefined();+ });+ });++ describe('deleteItem', () => {+ beforeEach(async () => {+ await serverDB.insert(files).values({+ id: 'delete-file',+ fileType: 'application/pdf',+ name: 'to-delete.pdf',+ size: 1024,+ url: 'delete-url',+ userId,+ });++ await serverDB.insert(documents).values({+ id: 'delete-doc',+ content: 'Document to delete',+ fileType: 'custom/other',+ filename: 'to-delete-doc.txt',+ source: 'source',+ sourceType: 'api',+ totalCharCount: 100,+ totalLineCount: 10,+ userId,+ });+ });++ it('should delete a file by id', async () => {+ await knowledgeRepo.deleteItem('delete-file', 'file');++ // Verify file was deleted+ const result = await serverDB.query.files.findFirst({+ where: (f, { eq }) => eq(f.id, 'delete-file'),+ });+ expect(result).toBeUndefined();+ });++ it('should delete a document by id', async () => {+ await knowledgeRepo.deleteItem('delete-doc', 'document');++ // Verify document was deleted+ const result = await serverDB.query.documents.findFirst({+ where: (d, { eq }) => eq(d.id, 'delete-doc'),+ });+ expect(result).toBeUndefined();+ });+ });++ describe('deleteMany', () => {+ beforeEach(async () => {+ await serverDB.insert(files).values([+ {+ id: 'delete-many-file-1',+ fileType: 'application/pdf',+ name: 'delete-1.pdf',+ size: 1024,+ url: 'url-1',+ userId,+ },+ {+ id: 'delete-many-file-2',+ fileType: 'application/pdf',+ name: 'delete-2.pdf',+ size: 1024,+ url: 'url-2',+ userId,+ },+ ]);++ await serverDB.insert(documents).values([+ {+ id: 'delete-many-doc-1',+ content: 'Delete doc 1',+ fileType: 'custom/other',+ filename: 'delete-doc-1.txt',+ source: 'source',+ sourceType: 'api',+ totalCharCount: 100,+ totalLineCount: 10,+ userId,+ },+ ]);+ });++ it('should delete multiple items of mixed types', async () => {+ await knowledgeRepo.deleteMany([+ { id: 'delete-many-file-1', sourceType: 'file' },+ { id: 'delete-many-file-2', sourceType: 'file' },+ { id: 'delete-many-doc-1', sourceType: 'document' },+ ]);++ // Verify files were deleted+ const file1 = await serverDB.query.files.findFirst({+ where: (f, { eq }) => eq(f.id, 'delete-many-file-1'),+ });+ const file2 = await serverDB.query.files.findFirst({+ where: (f, { eq }) => eq(f.id, 'delete-many-file-2'),+ });+ const doc1 = await serverDB.query.documents.findFirst({+ where: (d, { eq }) => eq(d.id, 'delete-many-doc-1'),+ });++ expect(file1).toBeUndefined();+ expect(file2).toBeUndefined();+ expect(doc1).toBeUndefined();+ });++ it('should handle empty items array', async () => {+ // Should not throw+ await expect(knowledgeRepo.deleteMany([])).resolves.not.toThrow();+ });++ it('should delete only files when no documents provided', async () => {+ await knowledgeRepo.deleteMany([{ id: 'delete-many-file-1', sourceType: 'file' }]);++ // Verify only specified file was deleted+ const file1 = await serverDB.query.files.findFirst({+ where: (f, { eq }) => eq(f.id, 'delete-many-file-1'),+ });+ const file2 = await serverDB.query.files.findFirst({+ where: (f, { eq }) => eq(f.id, 'delete-many-file-2'),+ });++ expect(file1).toBeUndefined();+ expect(file2).toBeDefined();+ });+ });++ describe('findById', () => {+ beforeEach(async () => {+ await serverDB.insert(files).values({+ id: 'find-file',+ fileType: 'application/pdf',+ name: 'find-me.pdf',+ size: 1024,+ url: 'find-url',+ userId,+ });++ await serverDB.insert(documents).values({+ id: 'find-doc',+ content: 'Find this document',+ fileType: 'custom/other',+ filename: 'find-me-doc.txt',+ source: 'source',+ sourceType: 'api',+ totalCharCount: 100,+ totalLineCount: 10,+ userId,+ });+ });++ it('should find a file by id', async () => {+ const result = await knowledgeRepo.findById('find-file', 'file');++ expect(result).toBeDefined();+ expect(result?.name).toBe('find-me.pdf');+ });++ it('should find a document by id', async () => {+ const result = await knowledgeRepo.findById('find-doc', 'document');++ expect(result).toBeDefined();+ expect(result?.filename).toBe('find-me-doc.txt');+ });++ it('should return undefined for non-existent file', async () => {+ const result = await knowledgeRepo.findById('non-existent', 'file');++ expect(result).toBeUndefined();+ });++ it('should return undefined for non-existent document', async () => {+ const result = await knowledgeRepo.findById('non-existent', 'document');++ expect(result).toBeUndefined();+ });+ });});