🤯 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
import { describe, expect, it, vi } from 'vitest';
import { GenerationTopicModel } from '@/database/models/generationTopic';
import { type GenerationTopicItem } from '@/database/schemas/generation';
import { FileService } from '@/server/services/file';
import { GenerationService } from '@/server/services/generation';
import { generationTopicRouter } from '../generationTopic';
vi.mock('@/database/models/generationTopic');
vi.mock('@/server/services/file');
vi.mock('@/server/services/generation');
const deletedTopicWithCover = (mockTopicId: string, mockCoverUrl: string) => ({
id: mockTopicId,
title: 'Deleted Topic',
userId: 'test-user',
coverUrl: mockCoverUrl,
accessedAt: new Date(),
createdAt: new Date(),
updatedAt: new Date(),
});
describe('generationTopicRouter', () => {
const mockCtx = {
userId: 'test-user',
serverDB: {} as any,
};
beforeEach(() => {
vi.clearAllMocks();
});
it('should create a new topic', async () => {
const mockTopicId = 'topic-123';
const mockCreatedTopic = {
id: mockTopicId,
title: '',
userId: 'test-user',
coverUrl: null,
accessedAt: new Date(),
createdAt: new Date(),
updatedAt: new Date(),
};
const mockCreate = vi.fn().mockResolvedValue(mockCreatedTopic);
vi.mocked(GenerationTopicModel).mockImplementation(function () {
return {
create: mockCreate,
} as any;
});
const caller = generationTopicRouter.createCaller(mockCtx);
const result = await caller.createTopic();
expect(result).toBe(mockTopicId);
expect(mockCreate).toHaveBeenCalledWith('', undefined, undefined);
});
it('should create a titled workspace topic with explicit public visibility', async () => {
const mockTopicId = 'topic-public';
const mockCreatedTopic = {
id: mockTopicId,
title: 'A mountain lake at sunrise',
userId: 'test-user',
workspaceId: 'workspace-1',
coverUrl: null,
type: 'image',
visibility: 'public',
accessedAt: new Date(),
createdAt: new Date(),
updatedAt: new Date(),
};
const mockCreate = vi.fn().mockResolvedValue(mockCreatedTopic);
vi.mocked(GenerationTopicModel).mockImplementation(function () {
return {
create: mockCreate,
} as any;
});
const caller = generationTopicRouter.createCaller({
...mockCtx,
workspaceId: 'workspace-1',
});
const result = await caller.createTopic({
title: 'A mountain lake at sunrise',
type: 'image',
visibility: 'public',
});
expect(result).toBe(mockTopicId);
expect(mockCreate).toHaveBeenCalledWith('A mountain lake at sunrise', 'image', 'public');
});
it('should get all generation topics', async () => {
const mockTopics: GenerationTopicItem[] = [
{
id: 'topic-1',
title: 'Test Topic 1',
userId: 'test-user',
workspaceId: null,
coverUrl: 'cover-url-1',
type: 'image',
visibility: 'public',
accessedAt: new Date(),
createdAt: new Date(),
deletedAt: null,
isDeleted: null,
updatedAt: new Date(),
},
{
id: 'topic-2',
title: 'Test Topic 2',
userId: 'test-user',
workspaceId: null,
coverUrl: null,
type: 'image',
visibility: 'public',
accessedAt: new Date(),
createdAt: new Date(),
deletedAt: null,
isDeleted: null,
updatedAt: new Date(),
},
];
const mockQueryAll = vi.fn().mockResolvedValue(mockTopics);
vi.mocked(GenerationTopicModel).mockImplementation(function () {
return {
queryAll: mockQueryAll,
} as any;
});
const caller = generationTopicRouter.createCaller(mockCtx);
const result = await caller.getAllGenerationTopics();
expect(result).toEqual(mockTopics);
expect(mockQueryAll).toHaveBeenCalled();
});
it('should update a topic', async () => {
const mockTopicId = 'topic-123';
const mockUpdateValue = {
title: 'Updated Title',
};
const mockUpdatedTopic = {
id: mockTopicId,
...mockUpdateValue,
userId: 'test-user',
accessedAt: new Date(),
createdAt: new Date(),
updatedAt: new Date(),
};
const mockUpdate = vi.fn().mockResolvedValue(mockUpdatedTopic);
vi.mocked(GenerationTopicModel).mockImplementation(function () {
return {
findById: vi.fn().mockResolvedValue({ id: mockTopicId, userId: 'test-user' }),
update: mockUpdate,
} as any;
});
const caller = generationTopicRouter.createCaller(mockCtx);
const result = await caller.updateTopic({
id: mockTopicId,
value: mockUpdateValue,
});
expect(result).toEqual(mockUpdatedTopic);
expect(mockUpdate).toHaveBeenCalledWith(mockTopicId, mockUpdateValue);
});
it('should not let updateTopic write an arbitrary cover key', async () => {
const mockTopicId = 'topic-123';
const mockUpdate = vi.fn().mockResolvedValue({ id: mockTopicId, title: 'Title' });
vi.mocked(GenerationTopicModel).mockImplementation(function () {
return {
findById: vi.fn().mockResolvedValue({ id: mockTopicId, userId: 'test-user' }),
update: mockUpdate,
} as any;
});
const caller = generationTopicRouter.createCaller(mockCtx);
await caller.updateTopic({
id: mockTopicId,
// A key of another user's object; deleting the topic would delete it
value: { coverUrl: 'files/other-user/private.png', title: 'Title' } as any,
});
expect(mockUpdate).toHaveBeenCalledWith(mockTopicId, { title: 'Title' });
});
it('should update topic cover', async () => {
const mockTopicId = 'topic-123';
const mockCoverUrl = 'https://example.com/cover.jpg';
const mockNewCoverKey = 'generations/covers/new-cover-key.webp';
const mockUpdatedTopic = {
id: mockTopicId,
title: 'Test Topic',
userId: 'test-user',
coverUrl: mockNewCoverKey,
accessedAt: new Date(),
createdAt: new Date(),
updatedAt: new Date(),
};
const mockCreateCoverFromUrl = vi.fn().mockResolvedValue(mockNewCoverKey);
const mockReplaceCover = vi
.fn()
.mockResolvedValue({ previousCoverUrl: null, topic: mockUpdatedTopic });
vi.mocked(GenerationService).mockImplementation(function () {
return {
createCoverFromUrl: mockCreateCoverFromUrl,
} as any;
});
vi.mocked(GenerationTopicModel).mockImplementation(function () {
return {
findById: vi.fn().mockResolvedValue({ id: mockTopicId, userId: 'test-user' }),
replaceCover: mockReplaceCover,
} as any;
});
const caller = generationTopicRouter.createCaller(mockCtx);
const result = await caller.updateTopicCover({
id: mockTopicId,
coverUrl: mockCoverUrl,
});
expect(result).toEqual(mockUpdatedTopic);
expect(mockCreateCoverFromUrl).toHaveBeenCalledWith(mockCoverUrl);
expect(mockReplaceCover).toHaveBeenCalledWith(mockTopicId, mockNewCoverKey);
});
it('should delete the cover actually displaced by the update', async () => {
const mockTopicId = 'topic-123';
// Set after the request read the topic (e.g. by the server success path)
const mockDisplacedCoverKey = 'generations/covers/server-cover.webp';
const mockNewCoverKey = 'generations/covers/new-cover-key.webp';
const mockUpdatedTopic = { coverUrl: mockNewCoverKey, id: mockTopicId, userId: 'test-user' };
const mockDeleteFile = vi.fn().mockResolvedValue(undefined);
vi.mocked(GenerationService).mockImplementation(function () {
return { createCoverFromUrl: vi.fn().mockResolvedValue(mockNewCoverKey) } as any;
});
vi.mocked(GenerationTopicModel).mockImplementation(function () {
return {
findById: vi
.fn()
.mockResolvedValue({ coverUrl: null, id: mockTopicId, userId: 'test-user' }),
replaceCover: vi
.fn()
.mockResolvedValue({ previousCoverUrl: mockDisplacedCoverKey, topic: mockUpdatedTopic }),
} as any;
});
vi.mocked(FileService).mockImplementation(function () {
return { deleteFile: mockDeleteFile } as any;
});
const caller = generationTopicRouter.createCaller(mockCtx);
const result = await caller.updateTopicCover({
coverUrl: 'https://example.com/cover.jpg',
id: mockTopicId,
});
expect(result).toEqual(mockUpdatedTopic);
expect(mockDeleteFile).toHaveBeenCalledWith(mockDisplacedCoverKey);
});
it('should delete a topic without cover', async () => {
const mockTopicId = 'topic-123';
const mockDeletedTopic = {
id: mockTopicId,
title: 'Deleted Topic',
userId: 'test-user',
coverUrl: null,
accessedAt: new Date(),
createdAt: new Date(),
updatedAt: new Date(),
};
// Fix Mock return structure to match the new implementation
const mockDelete = vi.fn().mockResolvedValue({
deletedTopic: mockDeletedTopic,
filesToDelete: [], // No cover, so the file list is empty
});
const mockDeleteFiles = vi.fn();
vi.mocked(GenerationTopicModel).mockImplementation(function () {
return {
delete: mockDelete,
findById: vi.fn().mockResolvedValue(mockDeletedTopic),
} as any;
});
vi.mocked(FileService).mockImplementation(function () {
return {
deleteFiles: mockDeleteFiles,
} as any;
});
const caller = generationTopicRouter.createCaller(mockCtx);
const result = await caller.deleteTopic({ id: mockTopicId });
expect(result).toEqual(mockDeletedTopic);
expect(mockDelete).toHaveBeenCalledWith(mockTopicId);
expect(mockDeleteFiles).not.toHaveBeenCalled(); // no files to delete
});
it('should delete a topic with cover and remove the cover file', async () => {
const mockTopicId = 'topic-123';
const mockCoverUrl = 'generations/covers/cover-key.webp';
const mockDeletedTopic = deletedTopicWithCover(mockTopicId, mockCoverUrl);
// Fix Mock return structure to match the new implementation
const mockDelete = vi.fn().mockResolvedValue({
deletedTopic: mockDeletedTopic,
filesToDelete: [mockCoverUrl], // includes the cover file to delete
});
const mockDeleteFiles = vi.fn().mockResolvedValue(true);
vi.mocked(GenerationTopicModel).mockImplementation(function () {
return {
delete: mockDelete,
findById: vi.fn().mockResolvedValue(mockDeletedTopic),
} as any;
});
vi.mocked(FileService).mockImplementation(function () {
return {
deleteFiles: mockDeleteFiles,
} as any;
});
const caller = generationTopicRouter.createCaller(mockCtx);
const result = await caller.deleteTopic({ id: mockTopicId });
expect(result).toEqual(mockDeletedTopic);
expect(mockDelete).toHaveBeenCalledWith(mockTopicId);
expect(mockDeleteFiles).toHaveBeenCalledWith([mockCoverUrl]); // verify file deletion was called
});
it('should still return deleted topic when file deletion fails', async () => {
const mockTopicId = 'topic-123';
const mockCoverUrl = 'generations/covers/cover-key.webp';
const mockDeletedTopic = deletedTopicWithCover(mockTopicId, mockCoverUrl);
const mockDelete = vi.fn().mockResolvedValue({
deletedTopic: mockDeletedTopic,
filesToDelete: [mockCoverUrl],
});
// Mock file deletion to fail
const mockDeleteFiles = vi.fn().mockRejectedValue(new Error('S3 deletion failed'));
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(function () {});
vi.mocked(GenerationTopicModel).mockImplementation(function () {
return {
delete: mockDelete,
findById: vi.fn().mockResolvedValue(mockDeletedTopic),
} as any;
});
vi.mocked(FileService).mockImplementation(function () {
return {
deleteFiles: mockDeleteFiles,
} as any;
});
const caller = generationTopicRouter.createCaller(mockCtx);
const result = await caller.deleteTopic({ id: mockTopicId });
// Database deletion should succeed even if file deletion fails
expect(result).toEqual(mockDeletedTopic);
expect(mockDelete).toHaveBeenCalledWith(mockTopicId);
expect(mockDeleteFiles).toHaveBeenCalledWith([mockCoverUrl]);
expect(consoleSpy).toHaveBeenCalledWith('Failed to delete files from S3:', expect.any(Error));
consoleSpy.mockRestore();
});
it('should handle topic with multiple files (cover + thumbnails)', async () => {
const mockTopicId = 'topic-123';
const mockCoverUrl = 'generations/covers/cover-key.webp';
const mockThumbnailUrls = ['thumb1.jpg', 'thumb2.jpg', 'thumb3.jpg'];
const mockDeletedTopic = {
id: mockTopicId,
title: 'Deleted Topic with Multiple Files',
userId: 'test-user',
coverUrl: mockCoverUrl,
accessedAt: new Date(),
createdAt: new Date(),
updatedAt: new Date(),
};
const mockDelete = vi.fn().mockResolvedValue({
deletedTopic: mockDeletedTopic,
filesToDelete: [mockCoverUrl, ...mockThumbnailUrls], // includes cover and thumbnails
});
const mockDeleteFiles = vi.fn().mockResolvedValue(true);
vi.mocked(GenerationTopicModel).mockImplementation(function () {
return {
delete: mockDelete,
findById: vi.fn().mockResolvedValue(mockDeletedTopic),
} as any;
});
vi.mocked(FileService).mockImplementation(function () {
return {
deleteFiles: mockDeleteFiles,
} as any;
});
const caller = generationTopicRouter.createCaller(mockCtx);
const result = await caller.deleteTopic({ id: mockTopicId });
expect(result).toEqual(mockDeletedTopic);
expect(mockDelete).toHaveBeenCalledWith(mockTopicId);
expect(mockDeleteFiles).toHaveBeenCalledWith([mockCoverUrl, ...mockThumbnailUrls]);
});
it('should handle partial file deletion failure gracefully', async () => {
const mockTopicId = 'topic-123';
const mockCoverUrl = 'generations/covers/cover-key.webp';
const mockThumbnailUrls = ['thumb1.jpg', 'thumb2.jpg'];
const mockDeletedTopic = deletedTopicWithCover(mockTopicId, mockCoverUrl);
const mockDelete = vi.fn().mockResolvedValue({
deletedTopic: mockDeletedTopic,
filesToDelete: [mockCoverUrl, ...mockThumbnailUrls],
});
// Mock partial failure - some files deleted, others failed
const mockDeleteFiles = vi
.fn()
.mockRejectedValue(new Error('Some files could not be deleted from S3'));
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(function () {});
vi.mocked(GenerationTopicModel).mockImplementation(function () {
return {
delete: mockDelete,
findById: vi.fn().mockResolvedValue(mockDeletedTopic),
} as any;
});
vi.mocked(FileService).mockImplementation(function () {
return {
deleteFiles: mockDeleteFiles,
} as any;
});
const caller = generationTopicRouter.createCaller(mockCtx);
const result = await caller.deleteTopic({ id: mockTopicId });
// Even with partial file deletion failure, topic deletion should succeed
expect(result).toEqual(mockDeletedTopic);
expect(mockDelete).toHaveBeenCalledWith(mockTopicId);
expect(mockDeleteFiles).toHaveBeenCalledWith([mockCoverUrl, ...mockThumbnailUrls]);
expect(consoleSpy).toHaveBeenCalledWith('Failed to delete files from S3:', expect.any(Error));
consoleSpy.mockRestore();
});
it('should return undefined when deleting non-existent topic', async () => {
const mockTopicId = 'non-existent-topic';
// Mock delete method to return undefined for non-existent topic
const mockDelete = vi.fn().mockResolvedValue(undefined);
const mockDeleteFiles = vi.fn();
vi.mocked(GenerationTopicModel).mockImplementation(function () {
return {
delete: mockDelete,
findById: vi.fn().mockResolvedValue(undefined),
} as any;
});
vi.mocked(FileService).mockImplementation(function () {
return {
deleteFiles: mockDeleteFiles,
} as any;
});
const caller = generationTopicRouter.createCaller(mockCtx);
// Expect the function to return undefined for non-existent topic
const result = await caller.deleteTopic({ id: mockTopicId });
expect(result).toBeUndefined();
expect(mockDelete).not.toHaveBeenCalled();
expect(mockDeleteFiles).not.toHaveBeenCalled(); // no files to delete
});
it('should handle edge cases for update with partial data', async () => {
const mockTopicId = 'topic-123';
const mockUpdateValue = {
title: 'Only Title Updated',
};
const mockUpdatedTopic = {
id: mockTopicId,
title: 'Only Title Updated',
userId: 'test-user',
coverUrl: null,
accessedAt: new Date(),
createdAt: new Date(),
updatedAt: new Date(),
};
const mockUpdate = vi.fn().mockResolvedValue(mockUpdatedTopic);
vi.mocked(GenerationTopicModel).mockImplementation(function () {
return {
findById: vi.fn().mockResolvedValue({ id: mockTopicId, userId: 'test-user' }),
update: mockUpdate,
} as any;
});
const caller = generationTopicRouter.createCaller(mockCtx);
const result = await caller.updateTopic({
id: mockTopicId,
value: mockUpdateValue,
});
expect(result).toEqual(mockUpdatedTopic);
expect(mockUpdate).toHaveBeenCalledWith(mockTopicId, mockUpdateValue);
});
it('should handle null values in update', async () => {
const mockTopicId = 'topic-123';
const mockUpdateValue = {
title: null,
};
const mockUpdatedTopic = {
id: mockTopicId,
title: null,
userId: 'test-user',
coverUrl: null,
accessedAt: new Date(),
createdAt: new Date(),
updatedAt: new Date(),
};
const mockUpdate = vi.fn().mockResolvedValue(mockUpdatedTopic);
vi.mocked(GenerationTopicModel).mockImplementation(function () {
return {
findById: vi.fn().mockResolvedValue({ id: mockTopicId, userId: 'test-user' }),
update: mockUpdate,
} as any;
});
const caller = generationTopicRouter.createCaller(mockCtx);
const result = await caller.updateTopic({
id: mockTopicId,
value: mockUpdateValue,
});
expect(result).toEqual(mockUpdatedTopic);
expect(mockUpdate).toHaveBeenCalledWith(mockTopicId, mockUpdateValue);
});
it('should throw NOT_FOUND when updating non-existent topic', async () => {
const mockTopicId = 'non-existent-topic';
const mockUpdateValue = {
title: 'New Title',
};
const mockUpdate = vi.fn().mockResolvedValue(undefined);
vi.mocked(GenerationTopicModel).mockImplementation(function () {
return {
findById: vi.fn().mockResolvedValue(undefined),
update: mockUpdate,
} as any;
});
const caller = generationTopicRouter.createCaller(mockCtx);
await expect(
caller.updateTopic({
id: mockTopicId,
value: mockUpdateValue,
}),
).rejects.toThrow('Generation topic not found');
expect(mockUpdate).not.toHaveBeenCalled();
});
});