Skip to content

🤯 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.

✅ tests: refactor tests

arvinxx1b32d3a95d3b
diff --git a/packages/database/src/models/__tests__/messages/message.delete.test.ts b/packages/database/src/models/__tests__/messages/message.delete.test.ts
index 196d0bb9e69..7a692ca0524 100644
--- a/packages/database/src/models/__tests__/messages/message.delete.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.delete.test.ts
@@ -4,6 +4,8 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { uuid } from '@/utils/uuid';
import {
+ agents,
+ agentsToSessions,
chatGroups,
messagePlugins,
messageQueries,
@@ -99,6 +101,82 @@ describe('MessageModel Delete Tests', () => {
const result = await serverDB.select().from(messages).where(eq(messages.id, '1'));
expect(result).toHaveLength(1);
});
+
+ it('should update child messages parentId to deleted message parentId', async () => {
+ // Create a tree structure: A -> B -> C
+ // When B is deleted, C should have parentId = A
+ await serverDB.insert(messages).values([
+ { id: 'A', userId, role: 'user', content: 'message A', parentId: null },
+ { id: 'B', userId, role: 'assistant', content: 'message B', parentId: 'A' },
+ { id: 'C', userId, role: 'user', content: 'message C', parentId: 'B' },
+ ]);
+
+ // Delete message B
+ await messageModel.deleteMessage('B');
+
+ // Assert B is deleted
+ const deletedMessage = await serverDB.select().from(messages).where(eq(messages.id, 'B'));
+ expect(deletedMessage).toHaveLength(0);
+
+ // Assert C's parentId is now A (inherited from B's parentId)
+ const messageC = await serverDB.select().from(messages).where(eq(messages.id, 'C'));
+ expect(messageC).toHaveLength(1);
+ expect(messageC[0].parentId).toBe('A');
+
+ // Assert A still exists and is unchanged
+ const messageA = await serverDB.select().from(messages).where(eq(messages.id, 'A'));
+ expect(messageA).toHaveLength(1);
+ expect(messageA[0].parentId).toBeNull();
+ });
+
+ it('should set child messages parentId to null when deleting root message', async () => {
+ // Create a tree structure: A (root) -> B, C
+ // When A is deleted, B and C should have parentId = null
+ await serverDB.insert(messages).values([
+ { id: 'A', userId, role: 'user', content: 'message A', parentId: null },
+ { id: 'B', userId, role: 'assistant', content: 'message B', parentId: 'A' },
+ { id: 'C', userId, role: 'user', content: 'message C', parentId: 'A' },
+ ]);
+
+ // Delete root message A
+ await messageModel.deleteMessage('A');
+
+ // Assert A is deleted
+ const deletedMessage = await serverDB.select().from(messages).where(eq(messages.id, 'A'));
+ expect(deletedMessage).toHaveLength(0);
+
+ // Assert B's parentId is now null
+ const messageB = await serverDB.select().from(messages).where(eq(messages.id, 'B'));
+ expect(messageB).toHaveLength(1);
+ expect(messageB[0].parentId).toBeNull();
+
+ // Assert C's parentId is now null
+ const messageC = await serverDB.select().from(messages).where(eq(messages.id, 'C'));
+ expect(messageC).toHaveLength(1);
+ expect(messageC[0].parentId).toBeNull();
+ });
+
+ it('should only update child messages belonging to the same user', async () => {
+ // Create messages where child belongs to different user
+ await serverDB.insert(messages).values([
+ { id: 'A', userId, role: 'user', content: 'message A', parentId: null },
+ { id: 'B', userId, role: 'assistant', content: 'message B', parentId: 'A' },
+ { id: 'C', userId: otherUserId, role: 'user', content: 'message C', parentId: 'B' },
+ ]);
+
+ // Delete message B
+ await messageModel.deleteMessage('B');
+
+ // Assert B is deleted
+ const deletedMessage = await serverDB.select().from(messages).where(eq(messages.id, 'B'));
+ expect(deletedMessage).toHaveLength(0);
+
+ // Assert C's parentId is NOT updated (belongs to other user)
+ // Due to foreign key constraint with onDelete: 'set null', it will be set to null by DB
+ const messageC = await serverDB.select().from(messages).where(eq(messages.id, 'C'));
+ expect(messageC).toHaveLength(1);
+ expect(messageC[0].parentId).toBeNull();
+ });
});
describe('deleteMessages', () => {
@@ -133,6 +211,98 @@ describe('MessageModel Delete Tests', () => {
const result = await serverDB.select().from(messages).where(eq(messages.id, '1'));
expect(result).toHaveLength(1);
});
+
+ it('should update child messages parentId when deleting parent chain', async () => {
+ // Create a tree: A -> B -> C -> D
+ // Delete [B, C], D should have parentId = A
+ await serverDB.insert(messages).values([
+ { id: 'A', userId, role: 'user', content: 'message A', parentId: null },
+ { id: 'B', userId, role: 'assistant', content: 'message B', parentId: 'A' },
+ { id: 'C', userId, role: 'tool', content: 'message C', parentId: 'B' },
+ { id: 'D', userId, role: 'user', content: 'message D', parentId: 'C' },
+ ]);
+
+ // Delete B and C
+ await messageModel.deleteMessages(['B', 'C']);
+
+ // Assert B and C are deleted
+ const deletedB = await serverDB.select().from(messages).where(eq(messages.id, 'B'));
+ expect(deletedB).toHaveLength(0);
+ const deletedC = await serverDB.select().from(messages).where(eq(messages.id, 'C'));
+ expect(deletedC).toHaveLength(0);
+
+ // Assert D's parentId is now A (skipping deleted B and C)
+ const messageD = await serverDB.select().from(messages).where(eq(messages.id, 'D'));
+ expect(messageD).toHaveLength(1);
+ expect(messageD[0].parentId).toBe('A');
+
+ // Assert A is unchanged
+ const messageA = await serverDB.select().from(messages).where(eq(messages.id, 'A'));
+ expect(messageA).toHaveLength(1);
+ expect(messageA[0].parentId).toBeNull();
+ });
+
+ it('should set child parentId to null when deleting entire parent chain from root', async () => {
+ // Create a tree: A -> B -> C -> D
+ // Delete [A, B, C], D should have parentId = null
+ await serverDB.insert(messages).values([
+ { id: 'A', userId, role: 'user', content: 'message A', parentId: null },
+ { id: 'B', userId, role: 'assistant', content: 'message B', parentId: 'A' },
+ { id: 'C', userId, role: 'tool', content: 'message C', parentId: 'B' },
+ { id: 'D', userId, role: 'user', content: 'message D', parentId: 'C' },
+ ]);
+
+ // Delete A, B, and C
+ await messageModel.deleteMessages(['A', 'B', 'C']);
+
+ // Assert A, B, C are deleted
+ const remaining = await serverDB.select().from(messages).where(eq(messages.userId, userId));
+ expect(remaining).toHaveLength(1);
+ expect(remaining[0].id).toBe('D');
+
+ // Assert D's parentId is null (all ancestors deleted)
+ expect(remaining[0].parentId).toBeNull();
+ });
+
+ it('should handle multiple independent trees when batch deleting', async () => {
+ // Create two independent trees:
+ // Tree 1: A -> B -> C
+ // Tree 2: X -> Y -> Z
+ // Delete [B, Y], C should have parentId = A, Z should have parentId = X
+ await serverDB.insert(messages).values([
+ { id: 'A', userId, role: 'user', content: 'message A', parentId: null },
+ { id: 'B', userId, role: 'assistant', content: 'message B', parentId: 'A' },
+ { id: 'C', userId, role: 'user', content: 'message C', parentId: 'B' },
+ { id: 'X', userId, role: 'user', content: 'message X', parentId: null },
+ { id: 'Y', userId, role: 'assistant', content: 'message Y', parentId: 'X' },
+ { id: 'Z', userId, role: 'user', content: 'message Z', parentId: 'Y' },
+ ]);
+
+ // Delete B and Y
+ await messageModel.deleteMessages(['B', 'Y']);
+
+ // Assert C's parentId is A
+ const messageC = await serverDB.select().from(messages).where(eq(messages.id, 'C'));
+ expect(messageC).toHaveLength(1);
+ expect(messageC[0].parentId).toBe('A');
+
+ // Assert Z's parentId is X
+ const messageZ = await serverDB.select().from(messages).where(eq(messages.id, 'Z'));
+ expect(messageZ).toHaveLength(1);
+ expect(messageZ[0].parentId).toBe('X');
+ });
+
+ it('should handle empty ids array', async () => {
+ await serverDB
+ .insert(messages)
+ .values([{ id: 'A', userId, role: 'user', content: 'message A' }]);
+
+ // Should not throw and not delete anything
+ await messageModel.deleteMessages([]);
+
+ const result = await serverDB.select().from(messages).where(eq(messages.id, 'A'));
+ expect(result).toHaveLength(1);
+ });
});
describe('deleteMessageTranslate', () => {
it('should delete the message translate record', async () => {
@@ -478,4 +648,194 @@ describe('MessageModel Delete Tests', () => {
}
});
});
+
+ describe('batchDeleteByAgentId', () => {
+ it('should delete messages with direct agentId match', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(agents).values([{ id: 'agent-del-1', userId, title: 'Agent Delete 1' }]);
+
+ await trx.insert(messages).values([
+ {
+ id: 'msg-del-1',
+ userId,
+ agentId: 'agent-del-1',
+ role: 'user',
+ content: 'to delete',
+ },
+ {
+ id: 'msg-keep-1',
+ userId,
+ agentId: null,
+ role: 'user',
+ content: 'to keep',
+ },
+ ]);
+ });
+
+ await messageModel.batchDeleteByAgentId('agent-del-1');
+
+ const remaining = await serverDB.query.messages.findMany({
+ where: eq(messages.userId, userId),
+ });
+
+ expect(remaining).toHaveLength(1);
+ expect(remaining[0].id).toBe('msg-keep-1');
+ });
+
+ it('should delete legacy messages by agentId through agentsToSessions lookup', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'session-del', userId }]);
+
+ await trx.insert(agents).values([{ id: 'agent-del-2', userId, title: 'Agent Delete 2' }]);
+
+ await trx
+ .insert(agentsToSessions)
+ .values([{ agentId: 'agent-del-2', sessionId: 'session-del', userId }]);
+
+ await trx.insert(messages).values([
+ {
+ id: 'msg-del-legacy',
+ userId,
+ sessionId: 'session-del',
+ agentId: null,
+ role: 'user',
+ content: 'legacy to delete',
+ },
+ {
+ id: 'msg-keep-2',
+ userId,
+ sessionId: null,
+ agentId: null,
+ role: 'user',
+ content: 'to keep',
+ },
+ ]);
+ });
+
+ await messageModel.batchDeleteByAgentId('agent-del-2');
+
+ const remaining = await serverDB.query.messages.findMany({
+ where: eq(messages.userId, userId),
+ });
+
+ expect(remaining).toHaveLength(1);
+ expect(remaining[0].id).toBe('msg-keep-2');
+ });
+
+ it('should delete both legacy and new messages using OR condition', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'session-del-mixed', userId }]);
+
+ await trx
+ .insert(agents)
+ .values([{ id: 'agent-del-mixed', userId, title: 'Agent Delete Mixed' }]);
+
+ await trx
+ .insert(agentsToSessions)
+ .values([{ agentId: 'agent-del-mixed', sessionId: 'session-del-mixed', userId }]);
+
+ await trx.insert(messages).values([
+ {
+ id: 'msg-del-legacy-mixed',
+ userId,
+ sessionId: 'session-del-mixed',
+ agentId: null,
+ role: 'user',
+ content: 'legacy to delete',
+ },
+ {
+ id: 'msg-del-new-mixed',
+ userId,
+ sessionId: null,
+ agentId: 'agent-del-mixed',
+ role: 'user',
+ content: 'new to delete',
+ },
+ {
+ id: 'msg-keep-mixed',
+ userId,
+ sessionId: null,
+ agentId: null,
+ role: 'user',
+ content: 'to keep',
+ },
+ ]);
+ });
+
+ await messageModel.batchDeleteByAgentId('agent-del-mixed');
+
+ const remaining = await serverDB.query.messages.findMany({
+ where: eq(messages.userId, userId),
+ });
+
+ expect(remaining).toHaveLength(1);
+ expect(remaining[0].id).toBe('msg-keep-mixed');
+ });
+
+ it('should only delete messages belonging to the current user', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(agents).values([
+ { id: 'agent-del-user', userId, title: 'Agent Delete User' },
+ { id: 'agent-del-other', userId: otherUserId, title: 'Agent Delete Other' },
+ ]);
+
+ await trx.insert(messages).values([
+ {
+ id: 'msg-del-user',
+ userId,
+ agentId: 'agent-del-user',
+ role: 'user',
+ content: 'user to delete',
+ },
+ {
+ id: 'msg-keep-other',
+ userId: otherUserId,
+ agentId: 'agent-del-other',
+ role: 'user',
+ content: 'other user keep',
+ },
+ ]);
+ });
+
+ await messageModel.batchDeleteByAgentId('agent-del-user');
+
+ // User's message should be deleted
+ const userMessages = await serverDB.query.messages.findMany({
+ where: eq(messages.userId, userId),
+ });
+ expect(userMessages).toHaveLength(0);
+
+ // Other user's message should remain
+ const otherMessages = await serverDB.query.messages.findMany({
+ where: eq(messages.userId, otherUserId),
+ });
+ expect(otherMessages).toHaveLength(1);
+ expect(otherMessages[0].id).toBe('msg-keep-other');
+ });
+
+ it('should do nothing when agentId has no associated messages', async () => {
+ await serverDB
+ .insert(agents)
+ .values([{ id: 'agent-del-empty', userId, title: 'Agent Delete Empty' }]);
+
+ await serverDB.insert(messages).values([
+ {
+ id: 'msg-keep-empty',
+ userId,
+ agentId: null,
+ role: 'user',
+ content: 'keep this',
+ },
+ ]);
+
+ await messageModel.batchDeleteByAgentId('agent-del-empty');
+
+ const remaining = await serverDB.query.messages.findMany({
+ where: eq(messages.userId, userId),
+ });
+
+ expect(remaining).toHaveLength(1);
+ expect(remaining[0].id).toBe('msg-keep-empty');
+ });
+ });
});
diff --git a/packages/database/src/models/__tests__/messages/message.query.test.ts b/packages/database/src/models/__tests__/messages/message.query.test.ts
index 468bf66d215..cc7ce667ead 100644
--- a/packages/database/src/models/__tests__/messages/message.query.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.query.test.ts
@@ -7,6 +7,7 @@ import { uuid } from '@/utils/uuid';
import {
agents,
+ agentsToSessions,
chatGroups,
chunks,
documents,
@@ -21,6 +22,7 @@ import {
messages,
messagesFiles,
sessions,
+ threads,
topics,
users,
} from '../../../schemas';
@@ -781,6 +783,416 @@ describe('MessageModel Query Tests', () => {
expect(result).toHaveLength(1);
expect(result[0].id).toBe('msg-s1-t1');
});
+
+ describe('query with agentId filter', () => {
+ // ========== Legacy data tests (messages with sessionId only) ==========
+ it('should query legacy messages by agentId through agentsToSessions lookup', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([
+ { id: 'session-for-agent', userId },
+ { id: 'session-other', userId },
+ ]);
+
+ await trx.insert(agents).values([{ id: 'agent1', userId, title: 'Agent 1' }]);
+
+ await trx
+ .insert(agentsToSessions)
+ .values([{ agentId: 'agent1', sessionId: 'session-for-agent', userId }]);
+
+ // Legacy messages: have sessionId but no agentId
+ await trx.insert(messages).values([
+ {
+ id: 'msg-agent-session',
+ userId,
+ sessionId: 'session-for-agent',
+ agentId: null,
+ role: 'user',
+ content: 'legacy message in agent session',
+ createdAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'msg-other-session',
+ userId,
+ sessionId: 'session-other',
+ agentId: null,
+ role: 'user',
+ content: 'message in other session',
+ createdAt: new Date('2023-01-02'),
+ },
+ ]);
+ });
+
+ // Query with agentId should return legacy messages from the associated session
+ const result = await messageModel.query({ agentId: 'agent1' });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('msg-agent-session');
+ });
+
+ // ========== New data tests (messages with agentId directly) ==========
+ it('should query messages with direct agentId match', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(agents).values([{ id: 'agent2', userId, title: 'Agent 2' }]);
+
+ // New messages: have agentId directly stored
+ await trx.insert(messages).values([
+ {
+ id: 'msg-with-agent-id',
+ userId,
+ agentId: 'agent2',
+ sessionId: null,
+ role: 'user',
+ content: 'new message with agentId',
+ createdAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'msg-without-agent-id',
+ userId,
+ agentId: null,
+ sessionId: null,
+ role: 'user',
+ content: 'message without agentId',
+ createdAt: new Date('2023-01-02'),
+ },
+ ]);
+ });
+
+ const result = await messageModel.query({ agentId: 'agent2' });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('msg-with-agent-id');
+ });
+
+ // ========== Mixed data tests (both legacy and new data) ==========
+ it('should query both legacy (sessionId) and new (agentId) messages using OR condition', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'session-for-mixed', userId }]);
+
+ await trx.insert(agents).values([{ id: 'agent-mixed', userId, title: 'Agent Mixed' }]);
+
+ await trx
+ .insert(agentsToSessions)
+ .values([{ agentId: 'agent-mixed', sessionId: 'session-for-mixed', userId }]);
+
+ // Mixed data: legacy message with sessionId and new message with agentId
+ await trx.insert(messages).values([
+ {
+ id: 'msg-legacy',
+ userId,
+ sessionId: 'session-for-mixed',
+ agentId: null,
+ role: 'user',
+ content: 'legacy message',
+ createdAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'msg-new',
+ userId,
+ sessionId: null,
+ agentId: 'agent-mixed',
+ role: 'user',
+ content: 'new message',
+ createdAt: new Date('2023-01-02'),
+ },
+ {
+ id: 'msg-unrelated',
+ userId,
+ sessionId: null,
+ agentId: null,
+ role: 'user',
+ content: 'unrelated message',
+ createdAt: new Date('2023-01-03'),
+ },
+ ]);
+ });
+
+ const result = await messageModel.query({ agentId: 'agent-mixed' });
+
+ // Should return both legacy and new messages
+ expect(result).toHaveLength(2);
+ const ids = result.map((m) => m.id);
+ expect(ids).toContain('msg-legacy');
+ expect(ids).toContain('msg-new');
+ });
+
+ it('should not duplicate messages when both sessionId and agentId point to the same message', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'session-dedup', userId }]);
+
+ await trx.insert(agents).values([{ id: 'agent-dedup', userId, title: 'Agent Dedup' }]);
+
+ await trx
+ .insert(agentsToSessions)
+ .values([{ agentId: 'agent-dedup', sessionId: 'session-dedup', userId }]);
+
+ // Message with both sessionId and agentId (transition period data)
+ await trx.insert(messages).values([
+ {
+ id: 'msg-both',
+ userId,
+ sessionId: 'session-dedup',
+ agentId: 'agent-dedup',
+ role: 'user',
+ content: 'message with both ids',
+ createdAt: new Date('2023-01-01'),
+ },
+ ]);
+ });
+
+ const result = await messageModel.query({ agentId: 'agent-dedup' });
+
+ // Should not duplicate - only return once
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('msg-both');
+ });
+
+ // ========== Edge cases ==========
+ it('should return empty when agentId has no associated session and no direct messages', async () => {
+ await serverDB
+ .insert(agents)
+ .values([{ id: 'agent-no-data', userId, title: 'Agent No Data' }]);
+
+ const result = await messageModel.query({ agentId: 'agent-no-data' });
+
+ expect(result).toHaveLength(0);
+ });
+
+ it('should query messages by agentId only (no associated sessionId in agentsToSessions)', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx
+ .insert(agents)
+ .values([{ id: 'agent-no-session', userId, title: 'Agent No Session' }]);
+
+ // Message with agentId but agent has no session association
+ await trx.insert(messages).values([
+ {
+ id: 'msg-agent-only',
+ userId,
+ agentId: 'agent-no-session',
+ sessionId: null,
+ role: 'user',
+ content: 'agent only message',
+ createdAt: new Date('2023-01-01'),
+ },
+ ]);
+ });
+
+ const result = await messageModel.query({ agentId: 'agent-no-session' });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('msg-agent-only');
+ });
+
+ // ========== User isolation tests ==========
+ it('should only return messages belonging to the current user', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([
+ { id: 'session-isolation', userId },
+ { id: 'session-other-user', userId: otherUserId },
+ ]);
+
+ await trx.insert(agents).values([
+ { id: 'agent-isolation', userId, title: 'Agent Isolation' },
+ { id: 'agent-other', userId: otherUserId, title: 'Agent Other' },
+ ]);
+
+ await trx.insert(agentsToSessions).values([
+ { agentId: 'agent-isolation', sessionId: 'session-isolation', userId },
+ { agentId: 'agent-other', sessionId: 'session-other-user', userId: otherUserId },
+ ]);
+
+ await trx.insert(messages).values([
+ {
+ id: 'msg-user',
+ userId,
+ agentId: 'agent-isolation',
+ role: 'user',
+ content: 'user message',
+ createdAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'msg-other-user',
+ userId: otherUserId,
+ agentId: 'agent-other',
+ role: 'user',
+ content: 'other user message',
+ createdAt: new Date('2023-01-02'),
+ },
+ ]);
+ });
+
+ const result = await messageModel.query({ agentId: 'agent-isolation' });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('msg-user');
+ });
+
+ // ========== Pagination tests ==========
+ it('should support pagination when querying by agentId', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(agents).values([{ id: 'agent-page', userId, title: 'Agent Page' }]);
+
+ await trx.insert(messages).values([
+ {
+ id: 'msg-page-1',
+ userId,
+ agentId: 'agent-page',
+ role: 'user',
+ content: 'page 1',
+ createdAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'msg-page-2',
+ userId,
+ agentId: 'agent-page',
+ role: 'user',
+ content: 'page 2',
+ createdAt: new Date('2023-01-02'),
+ },
+ {
+ id: 'msg-page-3',
+ userId,
+ agentId: 'agent-page',
+ role: 'user',
+ content: 'page 3',
+ createdAt: new Date('2023-01-03'),
+ },
+ ]);
+ });
+
+ const result1 = await messageModel.query({
+ agentId: 'agent-page',
+ current: 0,
+ pageSize: 2,
+ });
+ expect(result1).toHaveLength(2);
+ expect(result1[0].id).toBe('msg-page-1'); // ordered by createdAt asc
+ expect(result1[1].id).toBe('msg-page-2');
+
+ const result2 = await messageModel.query({
+ agentId: 'agent-page',
+ current: 1,
+ pageSize: 2,
+ });
+ expect(result2).toHaveLength(1);
+ expect(result2[0].id).toBe('msg-page-3');
+ });
+
+ it('should work with agentId and topicId filters combined', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'agent-session', userId }]);
+
+ await trx.insert(agents).values([{ id: 'agent1', userId, title: 'Agent 1' }]);
+
+ await trx
+ .insert(agentsToSessions)
+ .values([{ agentId: 'agent1', sessionId: 'agent-session', userId }]);
+
+ await trx.insert(topics).values([
+ { id: 'topic1', sessionId: 'agent-session', userId },
+ { id: 'topic2', sessionId: 'agent-session', userId },
+ ]);
+
+ await trx.insert(messages).values([
+ {
+ id: 'msg-topic1',
+ userId,
+ sessionId: 'agent-session',
+ topicId: 'topic1',
+ role: 'user',
+ content: 'message in topic1',
+ createdAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'msg-topic2',
+ userId,
+ sessionId: 'agent-session',
+ topicId: 'topic2',
+ role: 'user',
+ content: 'message in topic2',
+ createdAt: new Date('2023-01-02'),
+ },
+ ]);
+ });
+
+ // Query with agentId and topicId
+ const result = await messageModel.query({ agentId: 'agent1', topicId: 'topic1' });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('msg-topic1');
+ });
+
+ it('should only lookup agentsToSessions for current user', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([
+ { id: 'user-session', userId },
+ { id: 'other-user-session', userId: otherUserId },
+ ]);
+
+ // Different agent IDs for different users (agent id is primary key)
+ await trx.insert(agents).values([
+ { id: 'user-agent', userId, title: 'User Agent' },
+ { id: 'other-user-agent', userId: otherUserId, title: 'Other User Agent' },
+ ]);
+
+ // Only create agentsToSessions for the other user
+ await trx
+ .insert(agentsToSessions)
+ .values([
+ { agentId: 'other-user-agent', sessionId: 'other-user-session', userId: otherUserId },
+ ]);
+
+ await trx.insert(messages).values([
+ {
+ id: 'msg-user',
+ userId,
+ sessionId: null, // inbox
+ agentId: null,
+ role: 'user',
+ content: 'user message',
+ },
+ {
+ id: 'msg-other-user',
+ userId: otherUserId,
+ sessionId: 'other-user-session',
+ role: 'user',
+ content: 'other user message',
+ },
+ ]);
+ });
+
+ // Query with other user's agentId - should not find association since it belongs to other user
+ // and no direct agentId match either
+ const result = await messageModel.query({ agentId: 'other-user-agent' });
+
+ // Should return empty (no agentId match and no session found for this user)
+ expect(result).toHaveLength(0);
+ });
+
+ // ========== Backward compatibility: sessionId query still works ==========
+ it('should still work with sessionId query (backward compatibility)', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'session-compat', userId }]);
+
+ await trx.insert(messages).values([
+ {
+ id: 'msg-session-compat',
+ userId,
+ sessionId: 'session-compat',
+ role: 'user',
+ content: 'message with sessionId',
+ createdAt: new Date('2023-01-01'),
+ },
+ ]);
+ });
+
+ // Query with sessionId should still work
+ const result = await messageModel.query({ sessionId: 'session-compat' });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('msg-session-compat');
+ });
+ });
});
describe('queryAll', () => {
@@ -1145,6 +1557,254 @@ describe('MessageModel Query Tests', () => {
});
});
+ describe('query messages with threadId filter', () => {
+ it('should filter messages by threadId', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'session1', userId }]);
+ await trx.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
+
+ // Create threads first due to foreign key constraint
+ await trx.insert(threads).values([
+ {
+ id: 'thread1',
+ userId,
+ topicId: 'topic1',
+ sourceMessageId: 'source-msg-1',
+ type: 'standalone',
+ },
+ {
+ id: 'thread2',
+ userId,
+ topicId: 'topic1',
+ sourceMessageId: 'source-msg-2',
+ type: 'standalone',
+ },
+ ]);
+
+ await trx.insert(messages).values([
+ {
+ id: 'msg-thread-1',
+ userId,
+ sessionId: 'session1',
+ threadId: 'thread1',
+ role: 'user',
+ content: 'message in thread 1',
+ createdAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'msg-thread-2',
+ userId,
+ sessionId: 'session1',
+ threadId: 'thread1',
+ role: 'assistant',
+ content: 'another message in thread 1',
+ createdAt: new Date('2023-01-02'),
+ },
+ {
+ id: 'msg-thread-other',
+ userId,
+ sessionId: 'session1',
+ threadId: 'thread2',
+ role: 'user',
+ content: 'message in thread 2',
+ createdAt: new Date('2023-01-03'),
+ },
+ {
+ id: 'msg-no-thread',
+ userId,
+ sessionId: 'session1',
+ threadId: null,
+ role: 'user',
+ content: 'message without thread',
+ createdAt: new Date('2023-01-04'),
+ },
+ ]);
+ });
+
+ // Query messages in specific thread
+ const result = await messageModel.query({ sessionId: 'session1', threadId: 'thread1' });
+
+ expect(result).toHaveLength(2);
+ expect(result[0].id).toBe('msg-thread-1');
+ expect(result[1].id).toBe('msg-thread-2');
+ });
+
+ it('should query messages with null threadId (only non-thread messages)', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'session1', userId }]);
+ await trx.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
+
+ // Create thread first
+ await trx.insert(threads).values([
+ {
+ id: 'thread1',
+ userId,
+ topicId: 'topic1',
+ sourceMessageId: 'source-msg-1',
+ type: 'standalone',
+ },
+ ]);
+
+ await trx.insert(messages).values([
+ {
+ id: 'msg-no-thread-1',
+ userId,
+ sessionId: 'session1',
+ threadId: null,
+ role: 'user',
+ content: 'message without thread 1',
+ createdAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'msg-no-thread-2',
+ userId,
+ sessionId: 'session1',
+ threadId: null,
+ role: 'assistant',
+ content: 'message without thread 2',
+ createdAt: new Date('2023-01-02'),
+ },
+ {
+ id: 'msg-thread-1',
+ userId,
+ sessionId: 'session1',
+ threadId: 'thread1',
+ role: 'user',
+ content: 'message in thread 1',
+ createdAt: new Date('2023-01-03'),
+ },
+ ]);
+ });
+
+ // Query with explicit null threadId should return only non-thread messages
+ const result = await messageModel.query({ sessionId: 'session1', threadId: null });
+
+ expect(result).toHaveLength(2);
+ expect(result[0].id).toBe('msg-no-thread-1');
+ expect(result[1].id).toBe('msg-no-thread-2');
+ });
+
+ it('should query messages with combined sessionId, topicId and threadId filters', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'session1', userId }]);
+ await trx.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
+
+ // Create threads first
+ await trx.insert(threads).values([
+ {
+ id: 'thread1',
+ userId,
+ topicId: 'topic1',
+ sourceMessageId: 'source-msg-1',
+ type: 'standalone',
+ },
+ {
+ id: 'thread2',
+ userId,
+ topicId: 'topic1',
+ sourceMessageId: 'source-msg-2',
+ type: 'standalone',
+ },
+ ]);
+
+ await trx.insert(messages).values([
+ {
+ id: 'msg-all-filters',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: 'thread1',
+ role: 'user',
+ content: 'message with all filters',
+ createdAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'msg-diff-thread',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: 'thread2',
+ role: 'user',
+ content: 'message with different thread',
+ createdAt: new Date('2023-01-02'),
+ },
+ {
+ id: 'msg-no-thread',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'user',
+ content: 'message without thread',
+ createdAt: new Date('2023-01-03'),
+ },
+ ]);
+ });
+
+ // Query specific session, topic and thread combination
+ const result = await messageModel.query({
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: 'thread1',
+ });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('msg-all-filters');
+ });
+
+ it('should query messages by threadId with sessionId but without topicId', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'session1', userId }]);
+ await trx.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
+
+ // Create threads first
+ await trx.insert(threads).values([
+ {
+ id: 'thread1',
+ userId,
+ topicId: 'topic1',
+ sourceMessageId: 'source-msg-1',
+ type: 'standalone',
+ },
+ {
+ id: 'thread2',
+ userId,
+ topicId: 'topic1',
+ sourceMessageId: 'source-msg-2',
+ type: 'standalone',
+ },
+ ]);
+
+ await trx.insert(messages).values([
+ {
+ id: 'msg-thread-1',
+ userId,
+ sessionId: 'session1',
+ threadId: 'thread1',
+ role: 'user',
+ content: 'message in thread 1',
+ createdAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'msg-thread-2',
+ userId,
+ sessionId: 'session1',
+ threadId: 'thread2',
+ role: 'user',
+ content: 'message in thread 2',
+ createdAt: new Date('2023-01-02'),
+ },
+ ]);
+ });
+
+ // Query by sessionId and threadId without topicId
+ const result = await messageModel.query({ sessionId: 'session1', threadId: 'thread1' });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('msg-thread-1');
+ });
+ });
+
describe('findMessageQueriesById', () => {
it('should return undefined for non-existent message query', async () => {
const result = await messageModel.findMessageQueriesById('non-existent-id');
@@ -1184,4 +1844,1036 @@ describe('MessageModel Query Tests', () => {
});
});
});
+
+ describe('getThreadParentMessages', () => {
+ it('should return only source message for Standalone thread type', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'session1', userId }]);
+ await trx.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
+
+ // Create main conversation messages
+ await trx.insert(messages).values([
+ {
+ id: 'msg1',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'user',
+ content: 'first message',
+ createdAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'msg2',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'assistant',
+ content: 'second message',
+ createdAt: new Date('2023-01-02'),
+ },
+ {
+ id: 'msg3',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'user',
+ content: 'third message - source',
+ createdAt: new Date('2023-01-03'),
+ },
+ {
+ id: 'msg4',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'assistant',
+ content: 'fourth message',
+ createdAt: new Date('2023-01-04'),
+ },
+ ]);
+ });
+
+ const result = await messageModel.getThreadParentMessages({
+ sourceMessageId: 'msg3',
+ topicId: 'topic1',
+ threadType: 'standalone' as any,
+ });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('msg3');
+ expect(result[0].content).toBe('third message - source');
+ });
+
+ it('should return all messages up to source message for Continuation thread type', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'session1', userId }]);
+ await trx.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
+
+ // Create main conversation messages
+ await trx.insert(messages).values([
+ {
+ id: 'msg1',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'user',
+ content: 'first message',
+ createdAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'msg2',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'assistant',
+ content: 'second message',
+ createdAt: new Date('2023-01-02'),
+ },
+ {
+ id: 'msg3',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'user',
+ content: 'third message - source',
+ createdAt: new Date('2023-01-03'),
+ },
+ {
+ id: 'msg4',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'assistant',
+ content: 'fourth message - after source',
+ createdAt: new Date('2023-01-04'),
+ },
+ ]);
+ });
+
+ const result = await messageModel.getThreadParentMessages({
+ sourceMessageId: 'msg3',
+ topicId: 'topic1',
+ threadType: 'continuation' as any,
+ });
+
+ // Should include msg1, msg2, msg3 (up to and including source)
+ // Should NOT include msg4 (after source)
+ expect(result).toHaveLength(3);
+ expect(result[0].id).toBe('msg1');
+ expect(result[1].id).toBe('msg2');
+ expect(result[2].id).toBe('msg3');
+ });
+
+ it('should exclude messages from other threads in Continuation mode', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'session1', userId }]);
+ await trx.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
+
+ // Create thread first due to foreign key constraint
+ await trx.insert(threads).values([
+ {
+ id: 'thread1',
+ userId,
+ topicId: 'topic1',
+ sourceMessageId: 'msg2',
+ type: 'standalone',
+ },
+ ]);
+
+ await trx.insert(messages).values([
+ {
+ id: 'msg1',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'user',
+ content: 'main message 1',
+ createdAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'msg2',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'assistant',
+ content: 'main message 2 - source',
+ createdAt: new Date('2023-01-02'),
+ },
+ {
+ id: 'msg-in-thread',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: 'thread1',
+ role: 'user',
+ content: 'message in thread',
+ createdAt: new Date('2023-01-02T12:00:00'), // Same day but in thread
+ },
+ {
+ id: 'msg3',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'user',
+ content: 'main message 3 - new source',
+ createdAt: new Date('2023-01-03'),
+ },
+ ]);
+ });
+
+ const result = await messageModel.getThreadParentMessages({
+ sourceMessageId: 'msg3',
+ topicId: 'topic1',
+ threadType: 'continuation' as any,
+ });
+
+ // Should include msg1, msg2, msg3 (main conversation only)
+ // Should NOT include msg-in-thread (belongs to another thread)
+ expect(result).toHaveLength(3);
+ expect(result.map((m) => m.id)).toEqual(['msg1', 'msg2', 'msg3']);
+ });
+
+ it('should return empty array for non-existent source message', async () => {
+ const result = await messageModel.getThreadParentMessages({
+ sourceMessageId: 'non-existent',
+ topicId: 'topic1',
+ threadType: 'continuation' as any,
+ });
+
+ expect(result).toHaveLength(0);
+ });
+
+ it('should return messages in chronological order', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'session1', userId }]);
+ await trx.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
+
+ // Insert in non-chronological order
+ await trx.insert(messages).values([
+ {
+ id: 'msg3',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'user',
+ content: 'third',
+ createdAt: new Date('2023-01-03'),
+ },
+ {
+ id: 'msg1',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'user',
+ content: 'first',
+ createdAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'msg2',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'assistant',
+ content: 'second',
+ createdAt: new Date('2023-01-02'),
+ },
+ ]);
+ });
+
+ const result = await messageModel.getThreadParentMessages({
+ sourceMessageId: 'msg3',
+ topicId: 'topic1',
+ threadType: 'continuation' as any,
+ });
+
+ // Should be in chronological order regardless of insert order
+ expect(result).toHaveLength(3);
+ expect(result[0].id).toBe('msg1');
+ expect(result[1].id).toBe('msg2');
+ expect(result[2].id).toBe('msg3');
+ });
+ });
+
+ describe('query with threadId - complete thread data', () => {
+ it('should return parent messages + thread messages for Continuation type', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'session1', userId }]);
+ await trx.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
+
+ // Create thread with Continuation type
+ await trx.insert(threads).values([
+ {
+ id: 'thread1',
+ userId,
+ topicId: 'topic1',
+ sourceMessageId: 'msg2',
+ type: 'continuation',
+ },
+ ]);
+
+ // Create main conversation messages (parent messages)
+ await trx.insert(messages).values([
+ {
+ id: 'msg1',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'user',
+ content: 'first message',
+ createdAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'msg2',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'assistant',
+ content: 'second message - source',
+ createdAt: new Date('2023-01-02'),
+ },
+ {
+ id: 'msg3',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'user',
+ content: 'third message - after source',
+ createdAt: new Date('2023-01-03'),
+ },
+ // Thread messages
+ {
+ id: 'thread-msg1',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: 'thread1',
+ role: 'user',
+ content: 'thread message 1',
+ createdAt: new Date('2023-01-02T10:00:00'),
+ },
+ {
+ id: 'thread-msg2',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: 'thread1',
+ role: 'assistant',
+ content: 'thread message 2',
+ createdAt: new Date('2023-01-02T11:00:00'),
+ },
+ ]);
+ });
+
+ const result = await messageModel.query({ threadId: 'thread1' });
+
+ // Should include parent messages (msg1, msg2) + thread messages (thread-msg1, thread-msg2)
+ // Should NOT include msg3 (after source message)
+ expect(result).toHaveLength(4);
+ expect(result.map((m) => m.id)).toEqual(['msg1', 'msg2', 'thread-msg1', 'thread-msg2']);
+ });
+
+ it('should return only source message + thread messages for Standalone type', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'session1', userId }]);
+ await trx.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
+
+ // Create thread with Standalone type
+ await trx.insert(threads).values([
+ {
+ id: 'thread1',
+ userId,
+ topicId: 'topic1',
+ sourceMessageId: 'msg2',
+ type: 'standalone',
+ },
+ ]);
+
+ // Create main conversation messages
+ await trx.insert(messages).values([
+ {
+ id: 'msg1',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'user',
+ content: 'first message',
+ createdAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'msg2',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'assistant',
+ content: 'second message - source',
+ createdAt: new Date('2023-01-02'),
+ },
+ {
+ id: 'msg3',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'user',
+ content: 'third message',
+ createdAt: new Date('2023-01-03'),
+ },
+ // Thread messages
+ {
+ id: 'thread-msg1',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: 'thread1',
+ role: 'user',
+ content: 'thread message 1',
+ createdAt: new Date('2023-01-02T10:00:00'),
+ },
+ {
+ id: 'thread-msg2',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: 'thread1',
+ role: 'assistant',
+ content: 'thread message 2',
+ createdAt: new Date('2023-01-02T11:00:00'),
+ },
+ ]);
+ });
+
+ const result = await messageModel.query({ threadId: 'thread1' });
+
+ // For Standalone: should include only source message (msg2) + thread messages
+ // Should NOT include msg1 or msg3
+ expect(result).toHaveLength(3);
+ expect(result.map((m) => m.id)).toEqual(['msg2', 'thread-msg1', 'thread-msg2']);
+ });
+
+ it('should return messages in chronological order', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'session1', userId }]);
+ await trx.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
+
+ // Create thread
+ await trx.insert(threads).values([
+ {
+ id: 'thread1',
+ userId,
+ topicId: 'topic1',
+ sourceMessageId: 'msg2',
+ type: 'continuation',
+ },
+ ]);
+
+ // Insert messages in non-chronological order
+ await trx.insert(messages).values([
+ {
+ id: 'thread-msg2',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: 'thread1',
+ role: 'assistant',
+ content: 'thread message 2',
+ createdAt: new Date('2023-01-02T11:00:00'),
+ },
+ {
+ id: 'msg1',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'user',
+ content: 'first message',
+ createdAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'thread-msg1',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: 'thread1',
+ role: 'user',
+ content: 'thread message 1',
+ createdAt: new Date('2023-01-02T10:00:00'),
+ },
+ {
+ id: 'msg2',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'assistant',
+ content: 'second message - source',
+ createdAt: new Date('2023-01-02'),
+ },
+ ]);
+ });
+
+ const result = await messageModel.query({ threadId: 'thread1' });
+
+ // Should be in chronological order: msg1 -> msg2 -> thread-msg1 -> thread-msg2
+ expect(result).toHaveLength(4);
+ expect(result[0].id).toBe('msg1');
+ expect(result[1].id).toBe('msg2');
+ expect(result[2].id).toBe('thread-msg1');
+ expect(result[3].id).toBe('thread-msg2');
+ });
+
+ it('should return only thread messages when thread has no sourceMessageId', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'session1', userId }]);
+ await trx.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
+
+ // Create thread without sourceMessageId
+ await trx.insert(threads).values([
+ {
+ id: 'thread1',
+ userId,
+ topicId: 'topic1',
+ sourceMessageId: null,
+ type: 'continuation',
+ },
+ ]);
+
+ // Create messages
+ await trx.insert(messages).values([
+ {
+ id: 'msg1',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'user',
+ content: 'main message',
+ createdAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'thread-msg1',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: 'thread1',
+ role: 'user',
+ content: 'thread message',
+ createdAt: new Date('2023-01-02'),
+ },
+ ]);
+ });
+
+ const result = await messageModel.query({ threadId: 'thread1' });
+
+ // Should only return thread messages (fallback to original behavior)
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('thread-msg1');
+ });
+
+ it('should exclude messages from other threads', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'session1', userId }]);
+ await trx.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
+
+ // Create two threads
+ await trx.insert(threads).values([
+ {
+ id: 'thread1',
+ userId,
+ topicId: 'topic1',
+ sourceMessageId: 'msg1',
+ type: 'continuation',
+ },
+ {
+ id: 'thread2',
+ userId,
+ topicId: 'topic1',
+ sourceMessageId: 'msg1',
+ type: 'continuation',
+ },
+ ]);
+
+ // Create messages
+ await trx.insert(messages).values([
+ {
+ id: 'msg1',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'user',
+ content: 'source message',
+ createdAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'thread1-msg1',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: 'thread1',
+ role: 'user',
+ content: 'thread 1 message',
+ createdAt: new Date('2023-01-02'),
+ },
+ {
+ id: 'thread2-msg1',
+ userId,
+ sessionId: 'session1',
+ topicId: 'topic1',
+ threadId: 'thread2',
+ role: 'user',
+ content: 'thread 2 message',
+ createdAt: new Date('2023-01-03'),
+ },
+ ]);
+ });
+
+ const result = await messageModel.query({ threadId: 'thread1' });
+
+ // Should include parent (msg1) + thread1 messages only
+ // Should NOT include thread2 messages
+ expect(result).toHaveLength(2);
+ expect(result.map((m) => m.id)).toEqual(['msg1', 'thread1-msg1']);
+ });
+ });
+
+ describe('Group Chat message query scenarios', () => {
+ /**
+ * Scenario 1: Group Chat main channel
+ *
+ * In Group Chat, all messages in the main channel should have:
+ * - groupId: the same group ID
+ * - agentId: different for each agent (user, supervisor, agent-1, agent-2)
+ * - topicId: same topic or null
+ *
+ * When querying by groupId, should return ALL messages regardless of agentId
+ */
+ describe('main channel messages', () => {
+ it('should return all messages from user, supervisor, and multiple agents when querying by groupId', async () => {
+ await serverDB.transaction(async (trx) => {
+ // Create group and agents
+ await trx
+ .insert(chatGroups)
+ .values([{ id: 'group-chat-1', userId, title: 'Group Chat 1' }]);
+
+ await trx.insert(agents).values([
+ { id: 'supervisor-agent', userId, title: 'Supervisor' },
+ { id: 'agent-1', userId, title: 'Data Analyst' },
+ { id: 'agent-2', userId, title: 'Code Writer' },
+ ]);
+
+ await trx.insert(topics).values([{ id: 'topic-group-1', userId }]);
+
+ // Create messages from different agents in the same group
+ await trx.insert(messages).values([
+ // User message
+ {
+ id: 'msg-user',
+ userId,
+ role: 'user',
+ content: 'Analyze the weather data for Hangzhou',
+ groupId: 'group-chat-1',
+ agentId: 'supervisor-agent', // User message uses supervisor's agentId
+ topicId: 'topic-group-1',
+ createdAt: new Date('2024-01-01T10:00:00'),
+ },
+ // Supervisor's first response with tool call
+ {
+ id: 'msg-supervisor-1',
+ userId,
+ role: 'assistant',
+ content: 'I will delegate this to the Data Analyst.',
+ groupId: 'group-chat-1',
+ agentId: 'supervisor-agent',
+ topicId: 'topic-group-1',
+ createdAt: new Date('2024-01-01T10:01:00'),
+ },
+ // Tool message for delegation
+ {
+ id: 'msg-tool-delegate',
+ userId,
+ role: 'tool',
+ content: 'Triggered agent "agent-1" to respond.',
+ groupId: 'group-chat-1',
+ agentId: 'supervisor-agent',
+ topicId: 'topic-group-1',
+ createdAt: new Date('2024-01-01T10:01:30'),
+ },
+ // Agent-1 (Data Analyst) response
+ {
+ id: 'msg-agent1-response',
+ userId,
+ role: 'assistant',
+ content: 'Based on the weather data, Hangzhou has...',
+ groupId: 'group-chat-1',
+ agentId: 'agent-1',
+ topicId: 'topic-group-1',
+ createdAt: new Date('2024-01-01T10:02:00'),
+ },
+ // Supervisor asks Agent-2
+ {
+ id: 'msg-supervisor-2',
+ userId,
+ role: 'assistant',
+ content: 'Let me also get some code analysis.',
+ groupId: 'group-chat-1',
+ agentId: 'supervisor-agent',
+ topicId: 'topic-group-1',
+ createdAt: new Date('2024-01-01T10:03:00'),
+ },
+ // Agent-2 (Code Writer) response
+ {
+ id: 'msg-agent2-response',
+ userId,
+ role: 'assistant',
+ content: 'Here is the code to visualize the data...',
+ groupId: 'group-chat-1',
+ agentId: 'agent-2',
+ topicId: 'topic-group-1',
+ createdAt: new Date('2024-01-01T10:04:00'),
+ },
+ ]);
+ });
+
+ // Query by groupId - should return ALL messages from all agents
+ const result = await messageModel.query({
+ groupId: 'group-chat-1',
+ topicId: 'topic-group-1',
+ });
+
+ // Should return all 6 messages
+ expect(result).toHaveLength(6);
+
+ // Verify each message has correct agentId
+ const messageMap = new Map(result.map((m) => [m.id, m]));
+
+ expect(messageMap.get('msg-user')?.agentId).toBe('supervisor-agent');
+ expect(messageMap.get('msg-supervisor-1')?.agentId).toBe('supervisor-agent');
+ expect(messageMap.get('msg-tool-delegate')?.agentId).toBe('supervisor-agent');
+ expect(messageMap.get('msg-agent1-response')?.agentId).toBe('agent-1');
+ expect(messageMap.get('msg-supervisor-2')?.agentId).toBe('supervisor-agent');
+ expect(messageMap.get('msg-agent2-response')?.agentId).toBe('agent-2');
+
+ // All messages should have the same groupId
+ for (const msg of result) {
+ expect(msg.groupId).toBe('group-chat-1');
+ }
+
+ // Verify chronological order
+ expect(result.map((m) => m.id)).toEqual([
+ 'msg-user',
+ 'msg-supervisor-1',
+ 'msg-tool-delegate',
+ 'msg-agent1-response',
+ 'msg-supervisor-2',
+ 'msg-agent2-response',
+ ]);
+ });
+
+ it('should not return messages from different groups', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(chatGroups).values([
+ { id: 'group-1', userId, title: 'Group 1' },
+ { id: 'group-2', userId, title: 'Group 2' },
+ ]);
+
+ await trx.insert(agents).values([
+ { id: 'agent-g1', userId, title: 'Agent G1' },
+ { id: 'agent-g2', userId, title: 'Agent G2' },
+ ]);
+
+ await trx.insert(messages).values([
+ {
+ id: 'msg-g1',
+ userId,
+ role: 'user',
+ content: 'Message in group 1',
+ groupId: 'group-1',
+ agentId: 'agent-g1',
+ createdAt: new Date('2024-01-01'),
+ },
+ {
+ id: 'msg-g2',
+ userId,
+ role: 'user',
+ content: 'Message in group 2',
+ groupId: 'group-2',
+ agentId: 'agent-g2',
+ createdAt: new Date('2024-01-02'),
+ },
+ ]);
+ });
+
+ const result = await messageModel.query({ groupId: 'group-1' });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('msg-g1');
+ });
+ });
+
+ /**
+ * Scenario 2: Agent's private trajectory (thread)
+ *
+ * When an agent executes a task, it may create messages in its own thread.
+ * These messages should:
+ * - Have the same groupId as the main conversation
+ * - Have the agent's agentId
+ * - Have a threadId pointing to the agent's execution trajectory
+ *
+ * When querying by threadId, should return only the agent's trajectory messages
+ */
+ describe('agent private trajectory (thread)', () => {
+ it('should return only agent-1 trajectory messages when querying by threadId', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx
+ .insert(chatGroups)
+ .values([{ id: 'group-chat-1', userId, title: 'Group Chat' }]);
+
+ await trx.insert(agents).values([
+ { id: 'supervisor', userId, title: 'Supervisor' },
+ { id: 'agent-1', userId, title: 'Data Analyst' },
+ ]);
+
+ await trx.insert(topics).values([{ id: 'topic-1', userId }]);
+
+ // Create thread for agent-1's execution trajectory
+ await trx.insert(threads).values([
+ {
+ id: 'agent-1-trajectory',
+ userId,
+ topicId: 'topic-1',
+ sourceMessageId: 'msg-delegate-to-agent1', // Source is the delegation message
+ type: 'standalone',
+ },
+ ]);
+
+ // Main channel messages
+ await trx.insert(messages).values([
+ // User's request
+ {
+ id: 'msg-user-request',
+ userId,
+ role: 'user',
+ content: 'Analyze weather data',
+ groupId: 'group-chat-1',
+ agentId: 'supervisor',
+ topicId: 'topic-1',
+ threadId: null,
+ createdAt: new Date('2024-01-01T10:00:00'),
+ },
+ // Supervisor delegates to agent-1
+ {
+ id: 'msg-delegate-to-agent1',
+ userId,
+ role: 'assistant',
+ content: 'Delegating to Data Analyst',
+ groupId: 'group-chat-1',
+ agentId: 'supervisor',
+ topicId: 'topic-1',
+ threadId: null,
+ createdAt: new Date('2024-01-01T10:01:00'),
+ },
+ // Agent-1's execution trajectory (in thread)
+ {
+ id: 'msg-agent1-step1',
+ userId,
+ role: 'assistant',
+ content: 'Starting data analysis...',
+ groupId: 'group-chat-1',
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ threadId: 'agent-1-trajectory',
+ createdAt: new Date('2024-01-01T10:02:00'),
+ },
+ {
+ id: 'msg-agent1-tool-call',
+ userId,
+ role: 'tool',
+ content: 'Fetched weather API data',
+ groupId: 'group-chat-1',
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ threadId: 'agent-1-trajectory',
+ createdAt: new Date('2024-01-01T10:02:30'),
+ },
+ {
+ id: 'msg-agent1-step2',
+ userId,
+ role: 'assistant',
+ content: 'Analysis complete. Temperature trend shows...',
+ groupId: 'group-chat-1',
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ threadId: 'agent-1-trajectory',
+ createdAt: new Date('2024-01-01T10:03:00'),
+ },
+ // Final response in main channel (no threadId)
+ {
+ id: 'msg-agent1-final',
+ userId,
+ role: 'assistant',
+ content: 'Here is my analysis summary...',
+ groupId: 'group-chat-1',
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ threadId: null,
+ createdAt: new Date('2024-01-01T10:04:00'),
+ },
+ ]);
+ });
+
+ // Query agent-1's trajectory by threadId
+ const trajectoryResult = await messageModel.query({
+ threadId: 'agent-1-trajectory',
+ });
+
+ // Should return source message + thread messages
+ expect(trajectoryResult).toHaveLength(4);
+ expect(trajectoryResult.map((m) => m.id)).toEqual([
+ 'msg-delegate-to-agent1', // Source message
+ 'msg-agent1-step1',
+ 'msg-agent1-tool-call',
+ 'msg-agent1-step2',
+ ]);
+
+ // All trajectory messages should have the same groupId and agent-1's agentId
+ for (const msg of trajectoryResult.slice(1)) {
+ // Skip source message
+ expect(msg.groupId).toBe('group-chat-1');
+ expect(msg.agentId).toBe('agent-1');
+ expect(msg.threadId).toBe('agent-1-trajectory');
+ }
+
+ // Query main channel by groupId (should include all non-thread messages)
+ const mainChannelResult = await messageModel.query({
+ groupId: 'group-chat-1',
+ topicId: 'topic-1',
+ threadId: null, // Explicitly null to get main channel only
+ });
+
+ // Should return main channel messages only
+ expect(mainChannelResult).toHaveLength(3);
+ expect(mainChannelResult.map((m) => m.id)).toEqual([
+ 'msg-user-request',
+ 'msg-delegate-to-agent1',
+ 'msg-agent1-final',
+ ]);
+ });
+
+ it('should return separate trajectories for different agents', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(chatGroups).values([{ id: 'group-1', userId, title: 'Group' }]);
+
+ await trx.insert(agents).values([
+ { id: 'supervisor', userId, title: 'Supervisor' },
+ { id: 'agent-1', userId, title: 'Agent 1' },
+ { id: 'agent-2', userId, title: 'Agent 2' },
+ ]);
+
+ await trx.insert(topics).values([{ id: 'topic-1', userId }]);
+
+ // Create threads for each agent's trajectory
+ await trx.insert(threads).values([
+ {
+ id: 'agent-1-thread',
+ userId,
+ topicId: 'topic-1',
+ sourceMessageId: 'msg-source-1',
+ type: 'standalone',
+ },
+ {
+ id: 'agent-2-thread',
+ userId,
+ topicId: 'topic-1',
+ sourceMessageId: 'msg-source-2',
+ type: 'standalone',
+ },
+ ]);
+
+ await trx.insert(messages).values([
+ // Source messages
+ {
+ id: 'msg-source-1',
+ userId,
+ role: 'assistant',
+ content: 'Delegating to Agent 1',
+ groupId: 'group-1',
+ agentId: 'supervisor',
+ topicId: 'topic-1',
+ threadId: null,
+ createdAt: new Date('2024-01-01T10:00:00'),
+ },
+ {
+ id: 'msg-source-2',
+ userId,
+ role: 'assistant',
+ content: 'Delegating to Agent 2',
+ groupId: 'group-1',
+ agentId: 'supervisor',
+ topicId: 'topic-1',
+ threadId: null,
+ createdAt: new Date('2024-01-01T10:05:00'),
+ },
+ // Agent-1 trajectory
+ {
+ id: 'msg-agent1-work',
+ userId,
+ role: 'assistant',
+ content: 'Agent 1 working...',
+ groupId: 'group-1',
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ threadId: 'agent-1-thread',
+ createdAt: new Date('2024-01-01T10:01:00'),
+ },
+ // Agent-2 trajectory
+ {
+ id: 'msg-agent2-work',
+ userId,
+ role: 'assistant',
+ content: 'Agent 2 working...',
+ groupId: 'group-1',
+ agentId: 'agent-2',
+ topicId: 'topic-1',
+ threadId: 'agent-2-thread',
+ createdAt: new Date('2024-01-01T10:06:00'),
+ },
+ ]);
+ });
+
+ // Query agent-1's trajectory
+ const agent1Result = await messageModel.query({ threadId: 'agent-1-thread' });
+ expect(agent1Result).toHaveLength(2);
+ expect(agent1Result.map((m) => m.id)).toEqual(['msg-source-1', 'msg-agent1-work']);
+ expect(agent1Result[1].agentId).toBe('agent-1');
+
+ // Query agent-2's trajectory
+ const agent2Result = await messageModel.query({ threadId: 'agent-2-thread' });
+ expect(agent2Result).toHaveLength(2);
+ expect(agent2Result.map((m) => m.id)).toEqual(['msg-source-2', 'msg-agent2-work']);
+ expect(agent2Result[1].agentId).toBe('agent-2');
+
+ // Both trajectories should have the same groupId
+ expect(agent1Result[1].groupId).toBe('group-1');
+ expect(agent2Result[1].groupId).toBe('group-1');
+ });
+ });
+ });
});
diff --git a/packages/database/src/models/__tests__/messages/message.update.test.ts b/packages/database/src/models/__tests__/messages/message.update.test.ts
index 1e8e3373d06..bb24cf3a776 100644
--- a/packages/database/src/models/__tests__/messages/message.update.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.update.test.ts
@@ -471,6 +471,277 @@ describe('MessageModel Update Tests', () => {
});
});
+ describe('updateToolMessage', () => {
+ it('should update content only', async () => {
+ await serverDB.insert(messages).values({
+ id: 'tool-msg-1',
+ userId,
+ role: 'tool',
+ content: 'original content',
+ });
+
+ const result = await messageModel.updateToolMessage('tool-msg-1', {
+ content: 'updated content',
+ });
+
+ expect(result.success).toBe(true);
+
+ const dbResult = await serverDB.select().from(messages).where(eq(messages.id, 'tool-msg-1'));
+ expect(dbResult[0].content).toBe('updated content');
+ });
+
+ it('should update metadata only and merge with existing', async () => {
+ await serverDB.insert(messages).values({
+ id: 'tool-msg-2',
+ userId,
+ role: 'tool',
+ content: 'content',
+ metadata: { existingKey: 'existingValue' },
+ });
+
+ const result = await messageModel.updateToolMessage('tool-msg-2', {
+ metadata: { newKey: 'newValue' },
+ });
+
+ expect(result.success).toBe(true);
+
+ const dbResult = await serverDB.select().from(messages).where(eq(messages.id, 'tool-msg-2'));
+ expect(dbResult[0].metadata).toEqual({
+ existingKey: 'existingValue',
+ newKey: 'newValue',
+ });
+ });
+
+ it('should update pluginState only and merge with existing', async () => {
+ await serverDB.insert(messages).values({
+ id: 'tool-msg-3',
+ userId,
+ role: 'tool',
+ content: 'content',
+ });
+ await serverDB.insert(messagePlugins).values({
+ id: 'tool-msg-3',
+ toolCallId: 'tool-call-1',
+ identifier: 'test-plugin',
+ state: { existingState: 'value1' },
+ userId,
+ });
+
+ const result = await messageModel.updateToolMessage('tool-msg-3', {
+ pluginState: { newState: 'value2' },
+ });
+
+ expect(result.success).toBe(true);
+
+ const pluginResult = await serverDB
+ .select()
+ .from(messagePlugins)
+ .where(eq(messagePlugins.id, 'tool-msg-3'));
+ expect(pluginResult[0].state).toEqual({
+ existingState: 'value1',
+ newState: 'value2',
+ });
+ });
+
+ it('should update pluginError only', async () => {
+ await serverDB.insert(messages).values({
+ id: 'tool-msg-4',
+ userId,
+ role: 'tool',
+ content: 'content',
+ });
+ await serverDB.insert(messagePlugins).values({
+ id: 'tool-msg-4',
+ toolCallId: 'tool-call-1',
+ identifier: 'test-plugin',
+ userId,
+ });
+
+ const pluginError = { type: 'PluginError', message: 'Something went wrong' };
+ const result = await messageModel.updateToolMessage('tool-msg-4', {
+ pluginError,
+ });
+
+ expect(result.success).toBe(true);
+
+ const pluginResult = await serverDB
+ .select()
+ .from(messagePlugins)
+ .where(eq(messagePlugins.id, 'tool-msg-4'));
+ expect(pluginResult[0].error).toEqual(pluginError);
+ });
+
+ it('should update all fields in a single transaction', async () => {
+ await serverDB.insert(messages).values({
+ id: 'tool-msg-5',
+ userId,
+ role: 'tool',
+ content: 'original content',
+ metadata: { originalMeta: true },
+ });
+ await serverDB.insert(messagePlugins).values({
+ id: 'tool-msg-5',
+ toolCallId: 'tool-call-1',
+ identifier: 'test-plugin',
+ state: { originalState: true },
+ userId,
+ });
+
+ const result = await messageModel.updateToolMessage('tool-msg-5', {
+ content: 'new content',
+ metadata: { agentCouncil: true },
+ pluginState: { status: 'completed' },
+ pluginError: { type: 'Warning', message: 'Minor issue' },
+ });
+
+ expect(result.success).toBe(true);
+
+ // Verify message table updates
+ const msgResult = await serverDB.select().from(messages).where(eq(messages.id, 'tool-msg-5'));
+ expect(msgResult[0].content).toBe('new content');
+ expect(msgResult[0].metadata).toEqual({
+ originalMeta: true,
+ agentCouncil: true,
+ });
+
+ // Verify plugin table updates
+ const pluginResult = await serverDB
+ .select()
+ .from(messagePlugins)
+ .where(eq(messagePlugins.id, 'tool-msg-5'));
+ expect(pluginResult[0].state).toEqual({
+ originalState: true,
+ status: 'completed',
+ });
+ expect(pluginResult[0].error).toEqual({ type: 'Warning', message: 'Minor issue' });
+ });
+
+ it('should handle null metadata gracefully', async () => {
+ await serverDB.insert(messages).values({
+ id: 'tool-msg-6',
+ userId,
+ role: 'tool',
+ content: 'content',
+ metadata: null,
+ });
+
+ const result = await messageModel.updateToolMessage('tool-msg-6', {
+ metadata: { newKey: 'newValue' },
+ });
+
+ expect(result.success).toBe(true);
+
+ const dbResult = await serverDB.select().from(messages).where(eq(messages.id, 'tool-msg-6'));
+ expect(dbResult[0].metadata).toEqual({ newKey: 'newValue' });
+ });
+
+ it('should handle null pluginState gracefully', async () => {
+ await serverDB.insert(messages).values({
+ id: 'tool-msg-7',
+ userId,
+ role: 'tool',
+ content: 'content',
+ });
+ await serverDB.insert(messagePlugins).values({
+ id: 'tool-msg-7',
+ toolCallId: 'tool-call-1',
+ identifier: 'test-plugin',
+ state: null,
+ userId,
+ });
+
+ const result = await messageModel.updateToolMessage('tool-msg-7', {
+ pluginState: { newState: 'value' },
+ });
+
+ expect(result.success).toBe(true);
+
+ const pluginResult = await serverDB
+ .select()
+ .from(messagePlugins)
+ .where(eq(messagePlugins.id, 'tool-msg-7'));
+ expect(pluginResult[0].state).toEqual({ newState: 'value' });
+ });
+
+ it('should only update messages belonging to the current user', async () => {
+ await serverDB.insert(messages).values({
+ id: 'tool-msg-other',
+ userId: otherUserId,
+ role: 'tool',
+ content: 'original content',
+ });
+
+ const result = await messageModel.updateToolMessage('tool-msg-other', {
+ content: 'hacked content',
+ });
+
+ expect(result.success).toBe(true);
+
+ // Verify content was NOT updated
+ const dbResult = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.id, 'tool-msg-other'));
+ expect(dbResult[0].content).toBe('original content');
+ });
+
+ it('should skip plugin update if no messagePlugin exists', async () => {
+ await serverDB.insert(messages).values({
+ id: 'tool-msg-no-plugin',
+ userId,
+ role: 'tool',
+ content: 'original content',
+ });
+
+ // No messagePlugin record exists for this message
+ const result = await messageModel.updateToolMessage('tool-msg-no-plugin', {
+ content: 'new content',
+ pluginState: { someState: 'value' },
+ });
+
+ expect(result.success).toBe(true);
+
+ // Message content should still be updated
+ const dbResult = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.id, 'tool-msg-no-plugin'));
+ expect(dbResult[0].content).toBe('new content');
+ });
+
+ it('should return success false on error', async () => {
+ // Don't create any message - this should cause the transaction to succeed
+ // but not update anything (which is still success)
+ const result = await messageModel.updateToolMessage('non-existent-id', {
+ content: 'content',
+ });
+
+ // The method returns success: true even for non-existent messages
+ // because the update query doesn't fail, it just doesn't match any rows
+ expect(result.success).toBe(true);
+ });
+
+ it('should handle empty params gracefully', async () => {
+ await serverDB.insert(messages).values({
+ id: 'tool-msg-empty',
+ userId,
+ role: 'tool',
+ content: 'original content',
+ });
+
+ const result = await messageModel.updateToolMessage('tool-msg-empty', {});
+
+ expect(result.success).toBe(true);
+
+ // Content should remain unchanged
+ const dbResult = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.id, 'tool-msg-empty'));
+ expect(dbResult[0].content).toBe('original content');
+ });
+ });
+
describe('updateMetadata', () => {
it('should update metadata for an existing message', async () => {
// Create test data
@@ -497,7 +768,7 @@ describe('MessageModel Update Tests', () => {
});
});
- it('should merge new metadata with existing metadata using lodash merge behavior', async () => {
+ it('should merge new metadata with existing metadata using es-toolkit merge behavior', async () => {
// Create test data
await serverDB.insert(messages).values({
id: 'msg-merge-metadata',
@@ -522,7 +793,7 @@ describe('MessageModel Update Tests', () => {
newTopLevel: 'value',
});
- // Assert result - 应该使用 lodash merge 行为
+ // Assert result - 应该使用 es-toolkit merge 行为
const result = await serverDB
.select()
.from(messages)
@@ -669,6 +940,258 @@ describe('MessageModel Update Tests', () => {
});
});
+ describe('updateToolArguments', () => {
+ it('should update both assistant tools and tool message plugin using toolCallId', async () => {
+ // Create assistant message with tools
+ await serverDB.insert(messages).values({
+ id: 'assistant-msg-1',
+ userId,
+ role: 'assistant',
+ content: 'Let me search for that',
+ tools: [
+ {
+ id: 'tool-call-1',
+ type: 'builtin',
+ apiName: 'search',
+ arguments: '{"query":"original query"}',
+ identifier: 'web-search',
+ },
+ ],
+ });
+
+ // Create tool message
+ await serverDB.insert(messages).values({
+ id: 'tool-msg-1',
+ userId,
+ role: 'tool',
+ content: 'search result',
+ parentId: 'assistant-msg-1',
+ tool_call_id: 'tool-call-1',
+ });
+
+ // Create plugin record
+ await serverDB.insert(messagePlugins).values({
+ id: 'tool-msg-1',
+ toolCallId: 'tool-call-1',
+ identifier: 'web-search',
+ arguments: '{"query":"original query"}',
+ userId,
+ });
+
+ // Call updateToolArguments using toolCallId
+ const result = await messageModel.updateToolArguments(
+ 'tool-call-1',
+ '{"query":"updated query"}',
+ );
+
+ expect(result.success).toBe(true);
+
+ // Verify plugin arguments updated
+ const pluginResult = await serverDB
+ .select()
+ .from(messagePlugins)
+ .where(eq(messagePlugins.id, 'tool-msg-1'));
+ expect(pluginResult[0].arguments).toBe('{"query":"updated query"}');
+
+ // Verify parent message tools updated
+ const parentResult = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.id, 'assistant-msg-1'));
+ expect((parentResult[0].tools as any)[0].arguments).toBe('{"query":"updated query"}');
+ });
+
+ it('should update only the matching tool in parent message', async () => {
+ // Create assistant message with multiple tools
+ await serverDB.insert(messages).values({
+ id: 'assistant-msg-2',
+ userId,
+ role: 'assistant',
+ content: 'Let me search and calculate',
+ tools: [
+ {
+ id: 'tool-call-search',
+ type: 'builtin',
+ apiName: 'search',
+ arguments: '{"query":"search query"}',
+ identifier: 'web-search',
+ },
+ {
+ id: 'tool-call-calc',
+ type: 'builtin',
+ apiName: 'calculate',
+ arguments: '{"expression":"1+1"}',
+ identifier: 'calculator',
+ },
+ ],
+ });
+
+ // Create tool messages
+ await serverDB.insert(messages).values([
+ {
+ id: 'tool-msg-search',
+ userId,
+ role: 'tool',
+ content: 'search result',
+ parentId: 'assistant-msg-2',
+ tool_call_id: 'tool-call-search',
+ },
+ {
+ id: 'tool-msg-calc',
+ userId,
+ role: 'tool',
+ content: 'calc result',
+ parentId: 'assistant-msg-2',
+ tool_call_id: 'tool-call-calc',
+ },
+ ]);
+
+ // Create plugin records
+ await serverDB.insert(messagePlugins).values([
+ {
+ id: 'tool-msg-search',
+ toolCallId: 'tool-call-search',
+ identifier: 'web-search',
+ arguments: '{"query":"search query"}',
+ userId,
+ },
+ {
+ id: 'tool-msg-calc',
+ toolCallId: 'tool-call-calc',
+ identifier: 'calculator',
+ arguments: '{"expression":"1+1"}',
+ userId,
+ },
+ ]);
+
+ // Update only the search tool using toolCallId
+ const result = await messageModel.updateToolArguments(
+ 'tool-call-search',
+ '{"query":"new search query"}',
+ );
+
+ expect(result.success).toBe(true);
+
+ // Verify parent message tools - only search should be updated
+ const parentResult = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.id, 'assistant-msg-2'));
+ const tools = parentResult[0].tools as any[];
+ expect(tools[0].arguments).toBe('{"query":"new search query"}');
+ expect(tools[1].arguments).toBe('{"expression":"1+1"}'); // Should remain unchanged
+ });
+
+ it('should return success false for non-existent toolCallId', async () => {
+ const result = await messageModel.updateToolArguments(
+ 'non-existent-tool-call',
+ '{"key":"value"}',
+ );
+
+ expect(result.success).toBe(false);
+ });
+
+ it('should only update messages belonging to the current user', async () => {
+ // Create assistant message for other user
+ await serverDB.insert(messages).values({
+ id: 'other-user-assistant',
+ userId: otherUserId,
+ role: 'assistant',
+ content: 'other user message',
+ tools: [
+ {
+ id: 'other-tool-call',
+ type: 'builtin',
+ apiName: 'test',
+ arguments: '{"key":"original"}',
+ identifier: 'test-plugin',
+ },
+ ],
+ });
+
+ // Try to update as different user
+ const result = await messageModel.updateToolArguments('other-tool-call', '{"key":"hacked"}');
+
+ expect(result.success).toBe(false);
+
+ // Verify arguments were NOT updated
+ const assistantResult = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.id, 'other-user-assistant'));
+ expect((assistantResult[0].tools as any)[0].arguments).toBe('{"key":"original"}');
+ });
+
+ it('should complete within acceptable time even with many messages', async () => {
+ const COUNT = 100; // Use 100 records for performance test
+
+ // Create assistant messages with tools
+ const assistantMessagesData = Array.from({ length: COUNT }, (_, i) => ({
+ id: `perf-assistant-${i}`,
+ userId,
+ role: 'assistant' as const,
+ content: `Message ${i}`,
+ tools: [
+ {
+ id: `perf-tool-call-${i}`,
+ type: 'builtin',
+ apiName: 'test',
+ arguments: `{"index":${i}}`,
+ identifier: 'test-plugin',
+ },
+ ],
+ }));
+
+ await serverDB.insert(messages).values(assistantMessagesData);
+
+ // Create tool messages
+ const toolMessagesData = Array.from({ length: COUNT }, (_, i) => ({
+ id: `perf-tool-msg-${i}`,
+ userId,
+ role: 'tool' as const,
+ content: '',
+ parentId: `perf-assistant-${i}`,
+ tool_call_id: `perf-tool-call-${i}`,
+ }));
+
+ await serverDB.insert(messages).values(toolMessagesData);
+
+ // Create message plugins
+ const pluginsData = Array.from({ length: COUNT }, (_, i) => ({
+ id: `perf-tool-msg-${i}`,
+ toolCallId: `perf-tool-call-${i}`,
+ type: 'builtin',
+ apiName: 'test',
+ identifier: 'test-plugin',
+ arguments: `{"index":${i}}`,
+ userId,
+ }));
+
+ await serverDB.insert(messagePlugins).values(pluginsData);
+
+ // Test updating tool arguments - should use indexed lookup, not full scan
+ const targetIndex = Math.floor(COUNT / 2); // Middle of the list
+ const start = performance.now();
+ const result = await messageModel.updateToolArguments(
+ `perf-tool-call-${targetIndex}`,
+ '{"updated":true}',
+ );
+ const duration = performance.now() - start;
+
+ expect(result.success).toBe(true);
+ // Query should complete within 100ms even with many messages
+ // (indexed lookup should be O(1), not O(n))
+ expect(duration).toBeLessThan(30);
+
+ // Verify the update was correct
+ const parentResult = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.id, `perf-assistant-${targetIndex}`));
+ expect((parentResult[0].tools as any)[0].arguments).toBe('{"updated":true}');
+ });
+ });
+
describe('updateTranslate', () => {
it('should insert a new record if message does not exist in messageTranslates table', async () => {
// Create test data
diff --git a/packages/database/src/models/__tests__/messages/messageWithTask.test.ts b/packages/database/src/models/__tests__/messages/messageWithTask.test.ts
new file mode 100644
index 00000000000..d3378cf186a
--- /dev/null
+++ b/packages/database/src/models/__tests__/messages/messageWithTask.test.ts
@@ -0,0 +1,399 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { ThreadStatus, ThreadType } from '@/types/index';
+
+import { messages, sessions, threads, topics, users } from '../../../schemas';
+import { LobeChatDatabase } from '../../../type';
+import { MessageModel } from '../../message';
+import { getTestDB } from '../_util';
+
+const userId = 'message-task-user-test';
+const sessionId = 'message-task-session';
+const topicId = 'message-task-topic';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+const messageModel = new MessageModel(serverDB, userId);
+
+describe('MessageModel - queryWithWhere with task messages', () => {
+ beforeEach(async () => {
+ await serverDB.delete(users);
+
+ // Create test user, session and topic
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(users).values([{ id: userId }]);
+ await tx.insert(sessions).values({ id: sessionId, userId });
+ await tx.insert(topics).values({ id: topicId, userId, sessionId });
+ });
+ });
+
+ afterEach(async () => {
+ await serverDB.delete(users);
+ });
+
+ describe('taskDetail population for task messages', () => {
+ it('should return taskDetail for task messages with associated thread', async () => {
+ const taskMessageId = 'task-msg-1';
+ const threadId = 'thread-for-task-1';
+
+ // Create a task message
+ await serverDB.insert(messages).values({
+ content: 'Execute agent task',
+ id: taskMessageId,
+ role: 'task',
+ sessionId,
+ topicId,
+ userId,
+ });
+
+ // Create an associated thread with sourceMessageId pointing to the task message
+ await serverDB.insert(threads).values({
+ id: threadId,
+ metadata: {
+ duration: 5000,
+ totalCost: 0.05,
+ totalMessages: 10,
+ totalTokens: 1500,
+ totalToolCalls: 3,
+ },
+ sourceMessageId: taskMessageId,
+ status: ThreadStatus.Completed,
+ title: 'Agent Task Execution',
+ topicId,
+ type: ThreadType.Standalone,
+ userId,
+ });
+
+ const result = await messageModel.queryWithWhere();
+
+ expect(result).toHaveLength(1);
+ const taskMessage = result[0];
+ expect(taskMessage.role).toBe('task');
+ expect(taskMessage.taskDetail).toBeDefined();
+ expect(taskMessage.taskDetail).toEqual({
+ duration: 5000,
+ status: ThreadStatus.Completed,
+ threadId: threadId,
+ title: 'Agent Task Execution',
+ totalCost: 0.05,
+ totalMessages: 10,
+ totalTokens: 1500,
+ totalToolCalls: 3,
+ });
+ });
+
+ it('should not return taskDetail for task messages without associated thread', async () => {
+ const taskMessageId = 'task-msg-no-thread';
+
+ // Create a task message without an associated thread
+ await serverDB.insert(messages).values({
+ content: 'Orphan task message',
+ id: taskMessageId,
+ role: 'task',
+ sessionId,
+ topicId,
+ userId,
+ });
+
+ const result = await messageModel.queryWithWhere();
+
+ expect(result).toHaveLength(1);
+ const taskMessage = result[0];
+ expect(taskMessage.role).toBe('task');
+ expect(taskMessage.taskDetail).toBeUndefined();
+ });
+
+ it('should not return taskDetail for non-task messages', async () => {
+ // Create an assistant message
+ await serverDB.insert(messages).values({
+ content: 'Regular assistant message',
+ id: 'assistant-msg-1',
+ role: 'assistant',
+ sessionId,
+ topicId,
+ userId,
+ });
+
+ const result = await messageModel.queryWithWhere();
+
+ expect(result).toHaveLength(1);
+ const assistantMessage = result[0];
+ expect(assistantMessage.role).toBe('assistant');
+ expect(assistantMessage.taskDetail).toBeUndefined();
+ });
+
+ it('should handle multiple task messages with different thread statuses', async () => {
+ // Create multiple task messages
+ await serverDB.insert(messages).values([
+ {
+ content: 'Processing task',
+ createdAt: new Date('2024-01-01'),
+ id: 'task-processing',
+ role: 'task',
+ sessionId,
+ topicId,
+ userId,
+ },
+ {
+ content: 'Completed task',
+ createdAt: new Date('2024-01-02'),
+ id: 'task-completed',
+ role: 'task',
+ sessionId,
+ topicId,
+ userId,
+ },
+ {
+ content: 'Failed task',
+ createdAt: new Date('2024-01-03'),
+ id: 'task-failed',
+ role: 'task',
+ sessionId,
+ topicId,
+ userId,
+ },
+ ]);
+
+ // Create associated threads with different statuses
+ await serverDB.insert(threads).values([
+ {
+ id: 'thread-processing',
+ metadata: { totalTokens: 500 },
+ sourceMessageId: 'task-processing',
+ status: ThreadStatus.Processing,
+ title: 'Processing Thread',
+ topicId,
+ type: ThreadType.Standalone,
+ userId,
+ },
+ {
+ id: 'thread-completed',
+ metadata: {
+ duration: 3000,
+ totalCost: 0.03,
+ totalMessages: 5,
+ totalTokens: 800,
+ totalToolCalls: 2,
+ },
+ sourceMessageId: 'task-completed',
+ status: ThreadStatus.Completed,
+ title: 'Completed Thread',
+ topicId,
+ type: ThreadType.Standalone,
+ userId,
+ },
+ {
+ id: 'thread-failed',
+ metadata: { duration: 1000, totalTokens: 200 },
+ sourceMessageId: 'task-failed',
+ status: ThreadStatus.Failed,
+ title: 'Failed Thread',
+ topicId,
+ type: ThreadType.Standalone,
+ userId,
+ },
+ ]);
+
+ const result = await messageModel.queryWithWhere();
+
+ expect(result).toHaveLength(3);
+
+ const processingTask = result.find((m) => m.id === 'task-processing');
+ expect(processingTask?.taskDetail?.status).toBe(ThreadStatus.Processing);
+ expect(processingTask?.taskDetail?.totalTokens).toBe(500);
+
+ const completedTask = result.find((m) => m.id === 'task-completed');
+ expect(completedTask?.taskDetail?.status).toBe(ThreadStatus.Completed);
+ expect(completedTask?.taskDetail?.duration).toBe(3000);
+ expect(completedTask?.taskDetail?.totalCost).toBe(0.03);
+
+ const failedTask = result.find((m) => m.id === 'task-failed');
+ expect(failedTask?.taskDetail?.status).toBe(ThreadStatus.Failed);
+ expect(failedTask?.taskDetail?.duration).toBe(1000);
+ });
+
+ it('should handle mixed message types correctly', async () => {
+ // Create a mix of message types
+ await serverDB.insert(messages).values([
+ {
+ content: 'User message',
+ createdAt: new Date('2024-01-01'),
+ id: 'user-msg',
+ role: 'user',
+ sessionId,
+ topicId,
+ userId,
+ },
+ {
+ content: 'Assistant response',
+ createdAt: new Date('2024-01-02'),
+ id: 'assistant-msg',
+ role: 'assistant',
+ sessionId,
+ topicId,
+ userId,
+ },
+ {
+ content: 'Task execution',
+ createdAt: new Date('2024-01-03'),
+ id: 'task-msg',
+ role: 'task',
+ sessionId,
+ topicId,
+ userId,
+ },
+ ]);
+
+ // Create thread only for task message
+ await serverDB.insert(threads).values({
+ id: 'task-thread',
+ metadata: { totalTokens: 1000 },
+ sourceMessageId: 'task-msg',
+ status: ThreadStatus.Completed,
+ title: 'Task Thread',
+ topicId,
+ type: ThreadType.Standalone,
+ userId,
+ });
+
+ const result = await messageModel.queryWithWhere();
+
+ expect(result).toHaveLength(3);
+
+ const userMsg = result.find((m) => m.id === 'user-msg');
+ expect(userMsg?.taskDetail).toBeUndefined();
+
+ const assistantMsg = result.find((m) => m.id === 'assistant-msg');
+ expect(assistantMsg?.taskDetail).toBeUndefined();
+
+ const taskMsg = result.find((m) => m.id === 'task-msg');
+ expect(taskMsg?.taskDetail).toBeDefined();
+ expect(taskMsg?.taskDetail?.threadId).toBe('task-thread');
+ });
+
+ it('should not include thread from different user', async () => {
+ const otherUserId = 'other-user-for-task-test';
+ const taskMessageId = 'task-msg-cross-user';
+
+ // Create other user
+ await serverDB.insert(users).values({ id: otherUserId });
+
+ // Create a task message for current user
+ await serverDB.insert(messages).values({
+ content: 'My task message',
+ id: taskMessageId,
+ role: 'task',
+ sessionId,
+ topicId,
+ userId,
+ });
+
+ // Create other user's topic and thread with same sourceMessageId
+ await serverDB.insert(sessions).values({ id: 'other-session', userId: otherUserId });
+ await serverDB.insert(topics).values({
+ id: 'other-topic',
+ sessionId: 'other-session',
+ userId: otherUserId,
+ });
+ await serverDB.insert(threads).values({
+ id: 'other-user-thread',
+ metadata: { totalTokens: 9999 },
+ sourceMessageId: taskMessageId, // Same messageId but different user
+ status: ThreadStatus.Completed,
+ title: 'Other User Thread',
+ topicId: 'other-topic',
+ type: ThreadType.Standalone,
+ userId: otherUserId,
+ });
+
+ const result = await messageModel.queryWithWhere();
+
+ expect(result).toHaveLength(1);
+ const taskMessage = result[0];
+ // Should not get the other user's thread
+ expect(taskMessage.taskDetail).toBeUndefined();
+ });
+
+ it('should handle thread with partial metadata', async () => {
+ const taskMessageId = 'task-msg-partial';
+ const threadId = 'thread-partial-metadata';
+
+ await serverDB.insert(messages).values({
+ content: 'Task with partial metadata',
+ id: taskMessageId,
+ role: 'task',
+ sessionId,
+ topicId,
+ userId,
+ });
+
+ // Create thread with only some metadata fields
+ await serverDB.insert(threads).values({
+ id: threadId,
+ metadata: {
+ totalTokens: 500,
+ // Other fields are missing
+ },
+ sourceMessageId: taskMessageId,
+ status: ThreadStatus.Active,
+ title: 'Partial Metadata Thread',
+ topicId,
+ type: ThreadType.Standalone,
+ userId,
+ });
+
+ const result = await messageModel.queryWithWhere();
+
+ expect(result).toHaveLength(1);
+ const taskMessage = result[0];
+ expect(taskMessage.taskDetail).toEqual({
+ duration: undefined,
+ status: ThreadStatus.Active,
+ threadId: threadId,
+ title: 'Partial Metadata Thread',
+ totalCost: undefined,
+ totalMessages: undefined,
+ totalTokens: 500,
+ totalToolCalls: undefined,
+ });
+ });
+
+ it('should handle thread with no metadata', async () => {
+ const taskMessageId = 'task-msg-no-metadata';
+ const threadId = 'thread-no-metadata';
+
+ await serverDB.insert(messages).values({
+ content: 'Task with no metadata',
+ id: taskMessageId,
+ role: 'task',
+ sessionId,
+ topicId,
+ userId,
+ });
+
+ // Create thread without metadata
+ await serverDB.insert(threads).values({
+ id: threadId,
+ sourceMessageId: taskMessageId,
+ status: ThreadStatus.Pending,
+ topicId,
+ type: ThreadType.Standalone,
+ userId,
+ });
+
+ const result = await messageModel.queryWithWhere();
+
+ expect(result).toHaveLength(1);
+ const taskMessage = result[0];
+ expect(taskMessage.taskDetail).toEqual({
+ duration: undefined,
+ status: ThreadStatus.Pending,
+ threadId: threadId,
+ title: undefined,
+ totalCost: undefined,
+ totalMessages: undefined,
+ totalTokens: undefined,
+ totalToolCalls: undefined,
+ });
+ });
+ });
+});
diff --git a/packages/database/src/models/__tests__/messages/queryWithMessageGroup.test.ts b/packages/database/src/models/__tests__/messages/queryWithMessageGroup.test.ts
new file mode 100644
index 00000000000..ca0db78c5b1
--- /dev/null
+++ b/packages/database/src/models/__tests__/messages/queryWithMessageGroup.test.ts
@@ -0,0 +1,831 @@
+// @vitest-environment node
+import { MessageGroupType } from '@lobechat/types';
+import { and, eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { messageGroups, messages, topics, users } from '../../../schemas';
+import { LobeChatDatabase } from '../../../type';
+import { MessageModel } from '../../message';
+import { getTestDB } from '../_util';
+
+const userId = 'message-query-test-user';
+const topicId = 'test-topic-1';
+
+let messageModel: MessageModel;
+let serverDB: LobeChatDatabase;
+
+beforeEach(async () => {
+ serverDB = await getTestDB();
+
+ // Clean up
+ await serverDB.delete(messageGroups);
+ await serverDB.delete(messages);
+ await serverDB.delete(topics);
+ await serverDB.delete(users);
+
+ // Create test user
+ await serverDB.insert(users).values({ id: userId });
+
+ // Create test topic
+ await serverDB.insert(topics).values({ id: topicId, userId });
+
+ // Initialize model
+ messageModel = new MessageModel(serverDB, userId);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+describe('MessageModel.query with MessageGroup aggregation (LOBE-2066)', () => {
+ /**
+ * Test Scenario 1: Basic query without compression groups
+ * Expected: All messages should be returned normally
+ */
+ describe('query without compression groups', () => {
+ it('should return all messages when no compression groups exist', async () => {
+ // Create test messages
+ await serverDB.insert(messages).values([
+ { id: 'msg-1', content: 'Hello', role: 'user', topicId, userId },
+ { id: 'msg-2', content: 'Hi there!', role: 'assistant', topicId, userId },
+ { id: 'msg-3', content: 'How are you?', role: 'user', topicId, userId },
+ ]);
+
+ const result = await messageModel.query({ topicId });
+
+ expect(result).toHaveLength(3);
+ expect(result.map((m) => m.id)).toEqual(['msg-1', 'msg-2', 'msg-3']);
+ });
+ });
+
+ /**
+ * Test Scenario 2: Query with compression groups
+ * Expected:
+ * - Compressed messages (messageGroupId IS NOT NULL) should be excluded from normal trajectory
+ * - Only uncompressed messages should appear
+ * - Compression group should appear as a special node (role: 'compressedGroup')
+ */
+ describe('query with compression groups - compressed messages filtering', () => {
+ it('should exclude compressed messages from query results', async () => {
+ // Create messages - some will be compressed
+ await serverDB.insert(messages).values([
+ {
+ id: 'msg-comp-1',
+ content: 'Early message 1',
+ role: 'user',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:00:00Z'),
+ },
+ {
+ id: 'msg-comp-2',
+ content: 'Early message 2',
+ role: 'assistant',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:01:00Z'),
+ },
+ {
+ id: 'msg-comp-3',
+ content: 'Early message 3',
+ role: 'user',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:02:00Z'),
+ },
+ {
+ id: 'msg-normal-1',
+ content: 'Recent message 1',
+ role: 'assistant',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:03:00Z'),
+ },
+ {
+ id: 'msg-normal-2',
+ content: 'Recent message 2',
+ role: 'user',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:04:00Z'),
+ },
+ ]);
+
+ // Create a compression group
+ const [compressionGroup] = await serverDB
+ .insert(messageGroups)
+ .values({
+ id: 'comp-group-1',
+ content: 'Summary of early conversation',
+ type: MessageGroupType.Compression,
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:02:30Z'),
+ })
+ .returning();
+
+ // Mark early messages as compressed
+ await serverDB
+ .update(messages)
+ .set({ messageGroupId: compressionGroup.id })
+ .where(inArray(messages.id, ['msg-comp-1', 'msg-comp-2', 'msg-comp-3']));
+
+ // Query messages
+ const result = await messageModel.query({ topicId });
+
+ // Expected behavior:
+ // - Compressed messages (msg-comp-1, msg-comp-2, msg-comp-3) should NOT appear
+ // - Only uncompressed messages (msg-normal-1, msg-normal-2) should appear
+ // - Compression group should appear as a special node (role: 'compressedGroup')
+ // Total: 1 compressedGroup node + 2 normal messages = 3 items
+ expect(result).toHaveLength(3);
+
+ // Verify the compressedGroup node
+ const compressedGroupNode = result.find((m) => m.role === 'compressedGroup');
+ expect(compressedGroupNode).toBeDefined();
+ expect(compressedGroupNode!.id).toBe('comp-group-1');
+ expect(compressedGroupNode!.content).toBe('Summary of early conversation');
+
+ // Verify uncompressed messages
+ const normalMessages = result.filter((m) => m.role !== 'compressedGroup');
+ expect(normalMessages).toHaveLength(2);
+ expect(normalMessages.map((m) => m.id)).toEqual(['msg-normal-1', 'msg-normal-2']);
+ });
+
+ it('should handle multiple compression groups correctly', async () => {
+ // Create messages for multiple compression scenarios
+ await serverDB.insert(messages).values([
+ // First batch to compress
+ {
+ id: 'batch1-1',
+ content: 'Batch 1 msg 1',
+ role: 'user',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:00:00Z'),
+ },
+ {
+ id: 'batch1-2',
+ content: 'Batch 1 msg 2',
+ role: 'assistant',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:01:00Z'),
+ },
+ // Second batch to compress
+ {
+ id: 'batch2-1',
+ content: 'Batch 2 msg 1',
+ role: 'user',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:02:00Z'),
+ },
+ {
+ id: 'batch2-2',
+ content: 'Batch 2 msg 2',
+ role: 'assistant',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:03:00Z'),
+ },
+ // Uncompressed messages
+ {
+ id: 'recent-1',
+ content: 'Recent msg',
+ role: 'user',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:04:00Z'),
+ },
+ ]);
+
+ // Create first compression group
+ const [group1] = await serverDB
+ .insert(messageGroups)
+ .values({
+ id: 'comp-group-batch1',
+ content: 'Summary of batch 1',
+ type: MessageGroupType.Compression,
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:01:30Z'),
+ })
+ .returning();
+
+ // Create second compression group
+ const [group2] = await serverDB
+ .insert(messageGroups)
+ .values({
+ id: 'comp-group-batch2',
+ content: 'Summary of batch 2',
+ type: MessageGroupType.Compression,
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:03:30Z'),
+ })
+ .returning();
+
+ // Mark messages as compressed
+ await serverDB
+ .update(messages)
+ .set({ messageGroupId: group1.id })
+ .where(inArray(messages.id, ['batch1-1', 'batch1-2']));
+ await serverDB
+ .update(messages)
+ .set({ messageGroupId: group2.id })
+ .where(inArray(messages.id, ['batch2-1', 'batch2-2']));
+
+ const result = await messageModel.query({ topicId });
+
+ // Expected:
+ // - 4 compressed messages excluded
+ // - 1 uncompressed message included
+ // - 2 compression groups as special nodes
+ // Total: 2 compressedGroup nodes + 1 message = 3 items
+ expect(result).toHaveLength(3);
+
+ // Verify compression group nodes
+ const compressedGroups = result.filter((m) => m.role === 'compressedGroup');
+ expect(compressedGroups).toHaveLength(2);
+ expect(compressedGroups.map((g) => g.id)).toEqual(
+ expect.arrayContaining(['comp-group-batch1', 'comp-group-batch2']),
+ );
+
+ // Verify uncompressed message
+ const normalMessages = result.filter((m) => m.role !== 'compressedGroup');
+ expect(normalMessages).toHaveLength(1);
+ expect(normalMessages[0].id).toBe('recent-1');
+ });
+ });
+
+ /**
+ * Test Scenario 3: Pinned messages in compression groups
+ * Expected:
+ * - Compression group node should have a `pinnedMessages` array field
+ * - This array should contain messages with `favorite=true` from that group
+ */
+ describe('pinned messages in compression groups', () => {
+ it('should extract pinned messages from compression group', async () => {
+ // Create messages with some marked as favorite
+ await serverDB.insert(messages).values([
+ {
+ id: 'pinned-1',
+ content: 'Important message',
+ role: 'assistant',
+ topicId,
+ userId,
+ favorite: true,
+ createdAt: new Date('2024-01-01T10:00:00Z'),
+ },
+ {
+ id: 'normal-1',
+ content: 'Normal message',
+ role: 'user',
+ topicId,
+ userId,
+ favorite: false,
+ createdAt: new Date('2024-01-01T10:01:00Z'),
+ },
+ {
+ id: 'pinned-2',
+ content: 'Another important message',
+ role: 'user',
+ topicId,
+ userId,
+ favorite: true,
+ createdAt: new Date('2024-01-01T10:02:00Z'),
+ },
+ {
+ id: 'uncompressed-1',
+ content: 'Latest message',
+ role: 'assistant',
+ topicId,
+ userId,
+ favorite: false,
+ createdAt: new Date('2024-01-01T10:03:00Z'),
+ },
+ ]);
+
+ // Create compression group for first 3 messages
+ const [compressionGroup] = await serverDB
+ .insert(messageGroups)
+ .values({
+ id: 'comp-with-pinned',
+ content: 'Summary with pinned messages',
+ type: MessageGroupType.Compression,
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:02:30Z'),
+ })
+ .returning();
+
+ // Mark first 3 messages as compressed
+ await serverDB
+ .update(messages)
+ .set({ messageGroupId: compressionGroup.id })
+ .where(inArray(messages.id, ['pinned-1', 'normal-1', 'pinned-2']));
+
+ const result = await messageModel.query({ topicId });
+
+ // Expected structure:
+ // [
+ // {
+ // role: 'compressedGroup',
+ // id: 'comp-with-pinned',
+ // content: 'Summary with pinned messages',
+ // pinnedMessages: [
+ // { id: 'pinned-1', content: 'Important message', favorite: true },
+ // { id: 'pinned-2', content: 'Another important message', favorite: true },
+ // ],
+ // },
+ // { role: 'assistant', id: 'uncompressed-1', content: 'Latest message' },
+ // ]
+ expect(result).toHaveLength(2);
+
+ // Verify compressedGroup node with pinnedMessages
+ const compressedGroupNode = result.find((m) => m.role === 'compressedGroup') as any;
+ expect(compressedGroupNode).toBeDefined();
+ expect(compressedGroupNode.id).toBe('comp-with-pinned');
+ expect(compressedGroupNode.pinnedMessages).toBeDefined();
+ expect(compressedGroupNode.pinnedMessages).toHaveLength(2);
+ expect(compressedGroupNode.pinnedMessages.map((m: any) => m.id)).toEqual(
+ expect.arrayContaining(['pinned-1', 'pinned-2']),
+ );
+
+ // Verify uncompressed message
+ const normalMessage = result.find((m) => m.role !== 'compressedGroup');
+ expect(normalMessage).toBeDefined();
+ expect(normalMessage!.id).toBe('uncompressed-1');
+ });
+
+ it('should handle compression group with no pinned messages', async () => {
+ // Create messages with no favorites
+ await serverDB.insert(messages).values([
+ {
+ id: 'no-fav-1',
+ content: 'Message 1',
+ role: 'user',
+ topicId,
+ userId,
+ favorite: false,
+ },
+ {
+ id: 'no-fav-2',
+ content: 'Message 2',
+ role: 'assistant',
+ topicId,
+ userId,
+ favorite: false,
+ },
+ {
+ id: 'uncompressed',
+ content: 'Latest',
+ role: 'user',
+ topicId,
+ userId,
+ favorite: false,
+ },
+ ]);
+
+ // Create compression group
+ const [compressionGroup] = await serverDB
+ .insert(messageGroups)
+ .values({
+ id: 'comp-no-pinned',
+ content: 'Summary without pinned',
+ type: MessageGroupType.Compression,
+ topicId,
+ userId,
+ })
+ .returning();
+
+ // Mark first 2 messages as compressed
+ await serverDB
+ .update(messages)
+ .set({ messageGroupId: compressionGroup.id })
+ .where(inArray(messages.id, ['no-fav-1', 'no-fav-2']));
+
+ const result = await messageModel.query({ topicId });
+
+ // Expected: 1 compressedGroup + 1 uncompressed message = 2 items
+ expect(result).toHaveLength(2);
+
+ // Verify compressedGroup node has empty pinnedMessages
+ const compressedGroupNode = result.find((m) => m.role === 'compressedGroup') as any;
+ expect(compressedGroupNode).toBeDefined();
+ expect(compressedGroupNode.pinnedMessages).toBeDefined();
+ expect(compressedGroupNode.pinnedMessages).toHaveLength(0);
+ });
+ });
+
+ /**
+ * Test Scenario 4: Parallel (Compare) Groups
+ * Expected:
+ * - Parallel group messages should be aggregated under a 'compareGroup' node
+ * - The node should have children containing all parallel messages
+ */
+ describe('parallel (compare) groups', () => {
+ it('should aggregate parallel messages under compareGroup node', async () => {
+ // Create user message and parallel assistant responses
+ await serverDB.insert(messages).values([
+ {
+ id: 'user-msg',
+ content: 'Compare GPT-4 and Claude',
+ role: 'user',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:00:00Z'),
+ },
+ // Parallel responses - will be in a compare group
+ {
+ id: 'gpt4-response',
+ content: 'GPT-4 response',
+ role: 'assistant',
+ model: 'gpt-4',
+ provider: 'openai',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:01:00Z'),
+ },
+ {
+ id: 'claude-response',
+ content: 'Claude response',
+ role: 'assistant',
+ model: 'claude-3',
+ provider: 'anthropic',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:01:01Z'),
+ },
+ {
+ id: 'follow-up',
+ content: 'Thanks!',
+ role: 'user',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:02:00Z'),
+ },
+ ]);
+
+ // Create parallel (compare) group
+ const [parallelGroup] = await serverDB
+ .insert(messageGroups)
+ .values({
+ id: 'parallel-group-1',
+ type: 'parallel', // MessageGroupType.Parallel
+ parentMessageId: 'user-msg',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:01:00Z'),
+ })
+ .returning();
+
+ // Mark parallel responses as part of the group
+ await serverDB
+ .update(messages)
+ .set({ messageGroupId: parallelGroup.id })
+ .where(inArray(messages.id, ['gpt4-response', 'claude-response']));
+
+ const result = await messageModel.query({ topicId });
+
+ // Expected structure:
+ // [
+ // { role: 'user', id: 'user-msg', content: 'Compare GPT-4 and Claude' },
+ // {
+ // role: 'compareGroup',
+ // id: 'parallel-group-1',
+ // children: [
+ // { role: 'assistant', id: 'gpt4-response', model: 'gpt-4' },
+ // { role: 'assistant', id: 'claude-response', model: 'claude-3' },
+ // ],
+ // },
+ // { role: 'user', id: 'follow-up', content: 'Thanks!' },
+ // ]
+ expect(result).toHaveLength(3);
+
+ // Verify user message
+ expect(result[0].id).toBe('user-msg');
+ expect(result[0].role).toBe('user');
+
+ // Verify compareGroup node
+ const compareGroupNode = result.find((m) => m.role === 'compareGroup') as any;
+ expect(compareGroupNode).toBeDefined();
+ expect(compareGroupNode.id).toBe('parallel-group-1');
+ expect(compareGroupNode.children).toBeDefined();
+ expect(compareGroupNode.children).toHaveLength(2);
+ expect(compareGroupNode.children.map((c: any) => c.id)).toEqual(
+ expect.arrayContaining(['gpt4-response', 'claude-response']),
+ );
+
+ // Verify follow-up message
+ expect(result[2].id).toBe('follow-up');
+ expect(result[2].role).toBe('user');
+ });
+ });
+
+ /**
+ * Test Scenario 5: Mixed compression and parallel groups
+ * Expected: Proper ordering and aggregation of both group types
+ */
+ describe('mixed compression and parallel groups', () => {
+ it('should handle both compression and parallel groups in same topic', async () => {
+ // Create a complex conversation scenario
+ await serverDB.insert(messages).values([
+ // Early messages to be compressed
+ {
+ id: 'early-1',
+ content: 'Early msg 1',
+ role: 'user',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:00:00Z'),
+ },
+ {
+ id: 'early-2',
+ content: 'Early msg 2',
+ role: 'assistant',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:01:00Z'),
+ },
+ // User asks for comparison
+ {
+ id: 'compare-ask',
+ content: 'Compare models',
+ role: 'user',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:02:00Z'),
+ },
+ // Parallel responses
+ {
+ id: 'model-a',
+ content: 'Model A response',
+ role: 'assistant',
+ model: 'model-a',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:03:00Z'),
+ },
+ {
+ id: 'model-b',
+ content: 'Model B response',
+ role: 'assistant',
+ model: 'model-b',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:03:01Z'),
+ },
+ // Final message
+ {
+ id: 'final',
+ content: 'Thanks for comparison',
+ role: 'user',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:04:00Z'),
+ },
+ ]);
+
+ // Create compression group for early messages
+ const [compGroup] = await serverDB
+ .insert(messageGroups)
+ .values({
+ id: 'comp-group',
+ content: 'Summary of early conversation',
+ type: MessageGroupType.Compression,
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:01:30Z'),
+ })
+ .returning();
+
+ // Create parallel group for model comparisons
+ const [parallelGroup] = await serverDB
+ .insert(messageGroups)
+ .values({
+ id: 'parallel-group',
+ type: 'parallel',
+ parentMessageId: 'compare-ask',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:03:00Z'),
+ })
+ .returning();
+
+ // Mark messages
+ await serverDB
+ .update(messages)
+ .set({ messageGroupId: compGroup.id })
+ .where(inArray(messages.id, ['early-1', 'early-2']));
+ await serverDB
+ .update(messages)
+ .set({ messageGroupId: parallelGroup.id })
+ .where(inArray(messages.id, ['model-a', 'model-b']));
+
+ const result = await messageModel.query({ topicId });
+
+ // Expected structure:
+ // [
+ // { role: 'compressedGroup', id: 'comp-group', content: 'Summary...', pinnedMessages: [] },
+ // { role: 'user', id: 'compare-ask', content: 'Compare models' },
+ // { role: 'compareGroup', id: 'parallel-group', children: [model-a, model-b] },
+ // { role: 'user', id: 'final', content: 'Thanks for comparison' },
+ // ]
+ expect(result).toHaveLength(4);
+
+ // Verify structure
+ const compressedGroup = result.find((m) => m.role === 'compressedGroup');
+ const compareGroup = result.find((m) => m.role === 'compareGroup');
+ const normalMessages = result.filter(
+ (m) => m.role !== 'compressedGroup' && m.role !== 'compareGroup',
+ );
+
+ expect(compressedGroup).toBeDefined();
+ expect(compareGroup).toBeDefined();
+ expect(normalMessages).toHaveLength(2);
+ expect(normalMessages.map((m) => m.id)).toEqual(
+ expect.arrayContaining(['compare-ask', 'final']),
+ );
+ });
+ });
+
+ /**
+ * Test Scenario 6: Trajectory ordering
+ * Expected: Items should be ordered by createdAt correctly,
+ * including MessageGroup nodes at their proper positions
+ */
+ describe('trajectory ordering', () => {
+ it('should order compression groups at correct position in trajectory', async () => {
+ // Create messages with specific timestamps
+ await serverDB.insert(messages).values([
+ {
+ id: 'msg-1',
+ content: 'First',
+ role: 'user',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:00:00Z'),
+ },
+ {
+ id: 'msg-2',
+ content: 'Second',
+ role: 'assistant',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:01:00Z'),
+ },
+ {
+ id: 'msg-3',
+ content: 'Third',
+ role: 'user',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:02:00Z'),
+ },
+ {
+ id: 'msg-4',
+ content: 'Fourth (after compression)',
+ role: 'assistant',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:04:00Z'),
+ },
+ ]);
+
+ // Create compression group with timestamp between msg-3 and msg-4
+ const [compGroup] = await serverDB
+ .insert(messageGroups)
+ .values({
+ id: 'ordered-comp',
+ content: 'Compressed summary',
+ type: MessageGroupType.Compression,
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01T10:03:00Z'), // Between msg-3 and msg-4
+ })
+ .returning();
+
+ // Compress first 3 messages
+ await serverDB
+ .update(messages)
+ .set({ messageGroupId: compGroup.id })
+ .where(inArray(messages.id, ['msg-1', 'msg-2', 'msg-3']));
+
+ const result = await messageModel.query({ topicId });
+
+ // Expected order:
+ // 1. compressedGroup (createdAt: 10:03:00) - represents msgs 1-3
+ // 2. msg-4 (createdAt: 10:04:00)
+ expect(result).toHaveLength(2);
+ expect(result[0].role).toBe('compressedGroup');
+ expect(result[0].id).toBe('ordered-comp');
+ expect(result[1].role).toBe('assistant');
+ expect(result[1].id).toBe('msg-4');
+ });
+ });
+
+ /**
+ * Test Scenario 7: Performance test
+ * Expected: Query with 500 messages should complete within 30ms
+ */
+ describe('performance', () => {
+ it('should query 500 messages within 30ms', async () => {
+ // Create 500 messages
+ const messageData = Array.from({ length: 500 }, (_, i) => ({
+ id: `perf-msg-${i}`,
+ content: `Message content ${i}`,
+ role: i % 2 === 0 ? 'user' : 'assistant',
+ topicId,
+ userId,
+ createdAt: new Date(Date.now() - (500 - i) * 1000), // Spread over time
+ }));
+
+ await serverDB.insert(messages).values(messageData);
+
+ // Warm up query (first query might be slower due to connection/cache)
+ await messageModel.query({ topicId });
+
+ // Measure query performance
+ const startTime = performance.now();
+ const result = await messageModel.query({ topicId });
+ const endTime = performance.now();
+
+ const queryTime = endTime - startTime;
+
+ expect(result).toHaveLength(500);
+ expect(queryTime).toBeLessThan(30);
+
+ console.log(`Query 500 messages took ${queryTime.toFixed(2)}ms`);
+ });
+
+ it('should query 500 messages with compression groups within 30ms', async () => {
+ // Create 500 messages, 400 will be compressed into groups
+ const messageData = Array.from({ length: 500 }, (_, i) => ({
+ id: `perf-comp-msg-${i}`,
+ content: `Message content ${i}`,
+ role: i % 2 === 0 ? 'user' : 'assistant',
+ topicId,
+ userId,
+ favorite: i % 10 === 0, // Every 10th message is pinned
+ createdAt: new Date(Date.now() - (500 - i) * 1000),
+ }));
+
+ await serverDB.insert(messages).values(messageData);
+
+ // Create 4 compression groups, each compressing 100 messages
+ const groups = [];
+ for (let g = 0; g < 4; g++) {
+ const [group] = await serverDB
+ .insert(messageGroups)
+ .values({
+ id: `perf-comp-group-${g}`,
+ content: `Summary of group ${g}`,
+ type: MessageGroupType.Compression,
+ topicId,
+ userId,
+ createdAt: new Date(Date.now() - (400 - g * 100) * 1000),
+ })
+ .returning();
+ groups.push(group);
+
+ // Mark messages 0-99, 100-199, 200-299, 300-399 as compressed
+ const messageIds = Array.from({ length: 100 }, (_, i) => `perf-comp-msg-${g * 100 + i}`);
+ await serverDB
+ .update(messages)
+ .set({ messageGroupId: group.id })
+ .where(inArray(messages.id, messageIds));
+ }
+
+ // Warm up query
+ await messageModel.query({ topicId });
+
+ // Measure query performance
+ const startTime = performance.now();
+ const result = await messageModel.query({ topicId });
+ const endTime = performance.now();
+
+ const queryTime = endTime - startTime;
+
+ // Expected: 4 compressedGroup nodes + 100 uncompressed messages = 104 items
+ expect(result).toHaveLength(104);
+ expect(queryTime).toBeLessThan(30);
+
+ // Verify compressed groups have pinnedMessages
+ const compressedGroups = result.filter((m) => m.role === 'compressedGroup') as any[];
+ expect(compressedGroups).toHaveLength(4);
+
+ // Each group should have ~10 pinned messages (every 10th out of 100)
+ for (const group of compressedGroups) {
+ expect(group.pinnedMessages).toBeDefined();
+ expect(group.pinnedMessages.length).toBeGreaterThanOrEqual(9);
+ expect(group.pinnedMessages.length).toBeLessThanOrEqual(11);
+ }
+
+ console.log(
+ `Query 500 messages with 4 compression groups took ${queryTime.toFixed(2)}ms`,
+ );
+ });
+ });
+});
diff --git a/packages/database/src/models/__tests__/thread.test.ts b/packages/database/src/models/__tests__/thread.test.ts
index de8a1cf4ab0..15445dcb5de 100644
--- a/packages/database/src/models/__tests__/thread.test.ts
+++ b/packages/database/src/models/__tests__/thread.test.ts
@@ -208,7 +208,7 @@ describe('ThreadModel', () => {
await threadModel.update('thread-1', {
title: 'Updated Title',
- status: ThreadStatus.Archived,
+ status: ThreadStatus.Completed,
});
const updated = await serverDB.query.threads.findFirst({
@@ -216,7 +216,7 @@ describe('ThreadModel', () => {
});
expect(updated?.title).toBe('Updated Title');
- expect(updated?.status).toBe(ThreadStatus.Archived);
+ expect(updated?.status).toBe(ThreadStatus.Completed);
});
it('should not update thread belonging to another user', async () => {
diff --git a/packages/database/src/models/__tests__/topic.test.ts b/packages/database/src/models/__tests__/topic.test.ts
deleted file mode 100644
index bab29cd841e..00000000000
--- a/packages/database/src/models/__tests__/topic.test.ts
+++ /dev/null
@@ -1,848 +0,0 @@
-import { eq, inArray } from 'drizzle-orm';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { chatGroups, messages, sessions, topics, users } from '../../schemas';
-import { LobeChatDatabase } from '../../type';
-import { CreateTopicParams, TopicModel } from '../topic';
-import { getTestDB } from './_util';
-
-const userId = 'topic-user-test';
-const sessionId = 'topic-session';
-const serverDB: LobeChatDatabase = await getTestDB();
-const topicModel = new TopicModel(serverDB, userId);
-
-describe('TopicModel', () => {
- beforeEach(async () => {
- await serverDB.delete(users);
-
- // 创建测试数据
- await serverDB.transaction(async (tx) => {
- await tx.insert(users).values({ id: userId });
- await tx.insert(sessions).values({ id: sessionId, userId });
- });
- });
-
- afterEach(async () => {
- // 在每个测试用例之后,清空表
- await serverDB.delete(users);
- });
-
- describe('query', () => {
- it('should query topics by user ID', async () => {
- // 创建一些测试数据
- await serverDB.transaction(async (tx) => {
- await tx.insert(users).values([{ id: '456' }]);
-
- await tx.insert(topics).values([
- { id: '1', userId, sessionId, updatedAt: new Date('2023-01-01') },
- { id: '4', userId, sessionId, updatedAt: new Date('2023-03-01') },
- { id: '2', userId, sessionId, updatedAt: new Date('2023-02-01'), favorite: true },
- { id: '5', userId, sessionId, updatedAt: new Date('2023-05-01'), favorite: true },
- { id: '3', userId: '456', sessionId, updatedAt: new Date('2023-03-01') },
- ]);
- });
-
- // 调用 query 方法
- const result = await topicModel.query({ containerId: sessionId });
-
- // 断言结果
- expect(result).toHaveLength(4);
- expect(result[0].id).toBe('5'); // favorite 的 topic 应该在前面,按照 updatedAt 降序排序
- expect(result[1].id).toBe('2');
- expect(result[2].id).toBe('4'); // 按照 updatedAt 降序排序
- });
-
- it('should query topics with pagination', async () => {
- // 创建测试数据
- await serverDB.insert(topics).values([
- { id: '1', userId, updatedAt: new Date('2023-01-01') },
- { id: '2', userId, updatedAt: new Date('2023-02-01') },
- { id: '3', userId, updatedAt: new Date('2023-03-01') },
- ]);
-
- // 应该返回 2 个 topics
- const result1 = await topicModel.query({ current: 0, pageSize: 2 });
- expect(result1).toHaveLength(2);
-
- // 应该只返回 1 个 topic,并且是第 2 个
- const result2 = await topicModel.query({ current: 1, pageSize: 1 });
- expect(result2).toHaveLength(1);
- expect(result2[0].id).toBe('2');
- });
-
- it('should query topics by session ID', async () => {
- // 创建测试数据
- await serverDB.transaction(async (tx) => {
- await tx.insert(sessions).values([
- { id: 'session1', userId },
- { id: 'session2', userId },
- ]);
-
- await tx.insert(topics).values([
- { id: '1', userId, sessionId: 'session1' },
- { id: '2', userId, sessionId: 'session2' },
- { id: '3', userId }, // 没有 sessionId
- ]);
- });
-
- // 应该只返回属于 session1 的 topic
- const result = await topicModel.query({ containerId: 'session1' });
- expect(result).toHaveLength(1);
- expect(result[0].id).toBe('1');
- });
-
- it('should query topics by group ID', async () => {
- await serverDB.transaction(async (tx) => {
- await tx.insert(chatGroups).values([
- { id: 'chat-group-1', title: 'Chat Group 1', userId },
- { id: 'chat-group-2', title: 'Chat Group 2', userId },
- ]);
-
- await tx.insert(topics).values([
- {
- id: 'group-topic-1',
- userId,
- groupId: 'chat-group-1',
- favorite: true,
- updatedAt: new Date('2023-05-01'),
- },
- {
- id: 'group-topic-2',
- userId,
- groupId: 'chat-group-1',
- favorite: false,
- updatedAt: new Date('2023-04-01'),
- },
- {
- id: 'group-topic-3',
- userId,
- groupId: 'chat-group-2',
- favorite: true,
- updatedAt: new Date('2023-06-01'),
- },
- ]);
- });
-
- const result = await topicModel.query({ containerId: 'chat-group-1' });
-
- expect(result).toHaveLength(2);
- expect(result[0].id).toBe('group-topic-1');
- expect(result[1].id).toBe('group-topic-2');
- });
-
- it('should return topics based on pagination parameters', async () => {
- // 创建测试数据
- await serverDB.insert(topics).values([
- { id: 'topic1', sessionId, userId, updatedAt: new Date('2023-01-01') },
- { id: 'topic2', sessionId, userId, updatedAt: new Date('2023-01-02') },
- { id: 'topic3', sessionId, userId, updatedAt: new Date('2023-01-03') },
- ]);
-
- // 调用 query 方法
- const result1 = await topicModel.query({ containerId: sessionId, current: 0, pageSize: 2 });
- const result2 = await topicModel.query({ containerId: sessionId, current: 1, pageSize: 2 });
-
- // 断言返回结果符合分页要求
- expect(result1).toHaveLength(2);
- expect(result1[0].id).toBe('topic3');
- expect(result1[1].id).toBe('topic2');
-
- expect(result2).toHaveLength(1);
- expect(result2[0].id).toBe('topic1');
- });
- });
-
- describe('findById', () => {
- it('should return a topic by id', async () => {
- // 创建测试数据
- await serverDB.insert(topics).values({ id: 'topic1', sessionId, userId });
-
- // 调用 findById 方法
- const result = await topicModel.findById('topic1');
-
- // 断言返回结果符合预期
- expect(result?.id).toBe('topic1');
- });
-
- it('should return undefined for non-existent topic', async () => {
- // 调用 findById 方法
- const result = await topicModel.findById('non-existent');
-
- // 断言返回 undefined
- expect(result).toBeUndefined();
- });
- });
-
- describe('queryAll', () => {
- it('should return all topics', async () => {
- // 创建测试数据
- await serverDB.insert(topics).values([
- { id: 'topic1', sessionId, userId },
- { id: 'topic2', sessionId, userId },
- ]);
-
- // 调用 queryAll 方法
- const result = await topicModel.queryAll();
-
- // 断言返回所有的 topics
- expect(result).toHaveLength(2);
- expect(result[0].id).toBe('topic1');
- expect(result[1].id).toBe('topic2');
- });
- });
-
- describe('queryByKeyword', () => {
- it('should return topics matching topic title keyword', async () => {
- // 创建测试数据
- await serverDB.transaction(async (tx) => {
- await tx.insert(topics).values([
- { id: 'topic1', title: 'Hello world', sessionId, userId },
- { id: 'topic2', title: 'Goodbye', sessionId, userId },
- ]);
- await tx
- .insert(messages)
- .values([
- { id: 'message1', role: 'assistant', content: 'abc there', topicId: 'topic1', userId },
- ]);
- });
- // 调用 queryByKeyword 方法
- const result = await topicModel.queryByKeyword('hello', sessionId);
-
- // 断言返回匹配关键字的 topic
- expect(result).toHaveLength(1);
- expect(result[0].id).toBe('topic1');
- });
-
- it('should return topics matching message content keyword', async () => {
- // 创建测试数据
- await serverDB.transaction(async (tx) => {
- await tx.insert(topics).values([
- { id: 'topic1', title: 'abc world', sessionId, userId },
- { id: 'topic2', title: 'Goodbye', sessionId, userId },
- ]);
- await tx.insert(messages).values([
- {
- id: 'message1',
- role: 'assistant',
- content: 'Hello there',
- topicId: 'topic1',
- userId,
- },
- ]);
- });
- // 调用 queryByKeyword 方法
- const result = await topicModel.queryByKeyword('hello', sessionId);
-
- // 断言返回匹配关键字的 topic
- expect(result).toHaveLength(1);
- expect(result[0].id).toBe('topic1');
- });
-
- it('should return nothing if not match', async () => {
- // 创建测试数据
- await serverDB.insert(topics).values([
- { id: 'topic1', title: 'Hello world', userId },
- { id: 'topic2', title: 'Goodbye', sessionId, userId },
- ]);
- await serverDB
- .insert(messages)
- .values([
- { id: 'message1', role: 'assistant', content: 'abc there', topicId: 'topic1', userId },
- ]);
-
- // 调用 queryByKeyword 方法
- const result = await topicModel.queryByKeyword('hello', sessionId);
-
- // 断言返回匹配关键字的 topic
- expect(result).toHaveLength(0);
- });
- });
-
- describe('count', () => {
- it('should return total number of topics', async () => {
- // 创建测试数据
- await serverDB.insert(topics).values([
- { id: 'abc_topic1', sessionId, userId },
- { id: 'abc_topic2', sessionId, userId },
- ]);
-
- // 调用 count 方法
- const result = await topicModel.count();
-
- // 断言返回 topics 总数
- expect(result).toBe(2);
- });
- });
-
- describe('delete', () => {
- it('should delete a topic and its associated messages', async () => {
- const topicId = 'topic1';
- await serverDB.transaction(async (tx) => {
- await tx.insert(users).values({ id: '345' });
- await tx.insert(sessions).values([
- { id: 'session1', userId },
- { id: 'session2', userId: '345' },
- ]);
- await tx.insert(topics).values([
- { id: topicId, sessionId: 'session1', userId },
- { id: 'topic2', sessionId: 'session2', userId: '345' },
- ]);
- await tx.insert(messages).values([
- { id: 'message1', role: 'user', topicId: topicId, userId },
- { id: 'message2', role: 'assistant', topicId: topicId, userId },
- { id: 'message3', role: 'user', topicId: 'topic2', userId: '345' },
- ]);
- });
-
- // 调用 delete 方法
- await topicModel.delete(topicId);
-
- // 断言 topic 和关联的 messages 都被删除了
- expect(
- await serverDB.select().from(messages).where(eq(messages.topicId, topicId)),
- ).toHaveLength(0);
- expect(await serverDB.select().from(topics)).toHaveLength(1);
-
- expect(await serverDB.select().from(messages)).toHaveLength(1);
- });
- });
-
- describe('batchDeleteBySessionId', () => {
- it('should delete all topics associated with a session', async () => {
- await serverDB.insert(sessions).values([
- { id: 'session1', userId },
- { id: 'session2', userId },
- ]);
- await serverDB.insert(topics).values([
- { id: 'topic1', sessionId: 'session1', userId },
- { id: 'topic2', sessionId: 'session1', userId },
- { id: 'topic3', sessionId: 'session2', userId },
- { id: 'topic4', userId },
- ]);
-
- // 调用 batchDeleteBySessionId 方法
- await topicModel.batchDeleteBySessionId('session1');
-
- // 断言属于 session1 的 topics 都被删除了
- expect(
- await serverDB.select().from(topics).where(eq(topics.sessionId, 'session1')),
- ).toHaveLength(0);
- expect(await serverDB.select().from(topics)).toHaveLength(2);
- });
- it('should delete all topics associated without sessionId', async () => {
- await serverDB.insert(sessions).values([{ id: 'session1', userId }]);
-
- await serverDB.insert(topics).values([
- { id: 'topic1', sessionId: 'session1', userId },
- { id: 'topic2', sessionId: 'session1', userId },
- { id: 'topic4', userId },
- ]);
-
- // 调用 batchDeleteBySessionId 方法
- await topicModel.batchDeleteBySessionId();
-
- // 断言属于 session1 的 topics 都被删除了
- expect(
- await serverDB.select().from(topics).where(eq(topics.sessionId, 'session1')),
- ).toHaveLength(2);
- expect(await serverDB.select().from(topics)).toHaveLength(2);
- });
- });
-
- describe('batchDeleteByGroupId', () => {
- it('should delete all topics associated with a group', async () => {
- await serverDB.insert(chatGroups).values([
- { id: 'group1', userId, title: 'Group 1' },
- { id: 'group2', userId, title: 'Group 2' },
- ]);
- await serverDB.insert(topics).values([
- { id: 'topic1', groupId: 'group1', userId },
- { id: 'topic2', groupId: 'group1', userId },
- { id: 'topic3', groupId: 'group2', userId },
- { id: 'topic4', userId },
- ]);
-
- // 调用 batchDeleteByGroupId 方法
- await topicModel.batchDeleteByGroupId('group1');
-
- // 断言属于 group1 的 topics 都被删除了
- expect(await serverDB.select().from(topics).where(eq(topics.groupId, 'group1'))).toHaveLength(
- 0,
- );
- expect(await serverDB.select().from(topics)).toHaveLength(2);
- });
-
- it('should delete all topics associated without groupId', async () => {
- await serverDB.insert(chatGroups).values([{ id: 'group1', userId, title: 'Group 1' }]);
-
- await serverDB.insert(topics).values([
- { id: 'topic1', groupId: 'group1', userId },
- { id: 'topic2', groupId: 'group1', userId },
- { id: 'topic4', userId },
- ]);
-
- // 调用 batchDeleteByGroupId 方法
- await topicModel.batchDeleteByGroupId();
-
- // 断言属于 group1 的 topics 都被删除了
- expect(await serverDB.select().from(topics).where(eq(topics.groupId, 'group1'))).toHaveLength(
- 2,
- );
- expect(await serverDB.select().from(topics)).toHaveLength(2);
- });
- });
-
- describe('batchDelete', () => {
- it('should delete multiple topics and their associated messages', async () => {
- await serverDB.transaction(async (tx) => {
- await tx.insert(sessions).values({ id: 'session1', userId });
- await tx.insert(topics).values([
- { id: 'topic1', sessionId: 'session1', userId },
- { id: 'topic2', sessionId: 'session1', userId },
- { id: 'topic3', sessionId: 'session1', userId },
- ]);
- await tx.insert(messages).values([
- { id: 'message1', role: 'user', topicId: 'topic1', userId },
- { id: 'message2', role: 'assistant', topicId: 'topic2', userId },
- { id: 'message3', role: 'user', topicId: 'topic3', userId },
- ]);
- });
-
- // 调用 batchDelete 方法
- await topicModel.batchDelete(['topic1', 'topic2']);
-
- // 断言指定的 topics 和关联的 messages 都被删除了
- expect(await serverDB.select().from(topics)).toHaveLength(1);
- expect(await serverDB.select().from(messages)).toHaveLength(1);
- });
- });
-
- describe('deleteAll', () => {
- it('should delete all topics of the user', async () => {
- await serverDB.insert(users).values({ id: '345' });
- await serverDB.insert(sessions).values([
- { id: 'session1', userId },
- { id: 'session2', userId: '345' },
- ]);
- await serverDB.insert(topics).values([
- { id: 'topic1', sessionId: 'session1', userId },
- { id: 'topic2', sessionId: 'session1', userId },
- { id: 'topic3', sessionId: 'session2', userId: '345' },
- ]);
-
- // 调用 deleteAll 方法
- await topicModel.deleteAll();
-
- // 断言当前用户的所有 topics 都被删除了
- expect(await serverDB.select().from(topics).where(eq(topics.userId, userId))).toHaveLength(0);
- expect(await serverDB.select().from(topics)).toHaveLength(1);
- });
- });
-
- describe('update', () => {
- it('should update a topic', async () => {
- // 创建一个测试 session
- const topicId = '123';
- await serverDB.insert(topics).values({ userId, id: topicId, title: 'Test', favorite: true });
-
- // 调用 update 方法更新 session
- const item = await topicModel.update(topicId, {
- title: 'Updated Test',
- favorite: false,
- });
-
- // 断言更新后的结果
- expect(item).toHaveLength(1);
- expect(item[0].title).toBe('Updated Test');
- expect(item[0].favorite).toBeFalsy();
- });
-
- it('should not update a topic if user ID does not match', async () => {
- // 创建一个测试 topic, 但使用不同的 user ID
- await serverDB.insert(users).values([{ id: '456' }]);
- const topicId = '123';
- await serverDB
- .insert(topics)
- .values({ userId: '456', id: topicId, title: 'Test', favorite: true });
-
- // 尝试更新这个 topic , 应该不会有任何更新
- const item = await topicModel.update(topicId, {
- title: 'Updated Test Session',
- });
-
- expect(item).toHaveLength(0);
- });
- });
-
- describe('create', () => {
- it('should create a new topic and associate messages', async () => {
- const topicData = {
- title: 'New Topic',
- favorite: true,
- sessionId,
- messages: ['message1', 'message2'],
- } satisfies CreateTopicParams;
-
- const topicId = 'new-topic';
-
- // 预先创建一些 messages
- await serverDB.insert(messages).values([
- { id: 'message1', role: 'user', userId, sessionId },
- { id: 'message2', role: 'assistant', userId, sessionId },
- { id: 'message3', role: 'user', userId, sessionId },
- ]);
-
- // 调用 create 方法
- const createdTopic = await topicModel.create(topicData, topicId);
-
- // 断言返回的 topic 数据正确
- expect(createdTopic).toEqual({
- id: topicId,
- title: 'New Topic',
- favorite: true,
- sessionId,
- userId,
- historySummary: null,
- metadata: null,
- groupId: null,
- clientId: null,
- agentId: null,
- content: null,
- editorData: null,
- createdAt: expect.any(Date),
- updatedAt: expect.any(Date),
- accessedAt: expect.any(Date),
- });
-
- // 断言 topic 已在数据库中创建
- const dbTopic = await serverDB.select().from(topics).where(eq(topics.id, topicId));
- expect(dbTopic).toHaveLength(1);
- expect(dbTopic[0]).toEqual(createdTopic);
-
- // 断言关联的 messages 的 topicId 已更新
- const associatedMessages = await serverDB
- .select()
- .from(messages)
- .where(inArray(messages.id, topicData.messages!));
- expect(associatedMessages).toHaveLength(2);
- expect(associatedMessages.every((msg) => msg.topicId === topicId)).toBe(true);
-
- // 断言未关联的 message 的 topicId 没有更新
- const unassociatedMessage = await serverDB
- .select()
- .from(messages)
- .where(eq(messages.id, 'message3'));
-
- expect(unassociatedMessage[0].topicId).toBeNull();
- });
-
- it('should create a new topic without associating messages', async () => {
- const topicData = {
- title: 'New Topic',
- favorite: false,
- sessionId,
- };
-
- const topicId = 'new-topic';
-
- // 调用 create 方法
- const createdTopic = await topicModel.create(topicData, topicId);
-
- // 断言返回的 topic 数据正确
- expect(createdTopic).toEqual({
- id: topicId,
- title: 'New Topic',
- favorite: false,
- clientId: null,
- agentId: null,
- content: null,
- editorData: null,
- groupId: null,
- historySummary: null,
- metadata: null,
- sessionId,
- userId,
- createdAt: expect.any(Date),
- updatedAt: expect.any(Date),
- accessedAt: expect.any(Date),
- });
-
- // 断言 topic 已在数据库中创建
- const dbTopic = await serverDB.select().from(topics).where(eq(topics.id, topicId));
- expect(dbTopic).toHaveLength(1);
- expect(dbTopic[0]).toEqual(createdTopic);
- });
- });
-
- describe('batchCreate', () => {
- it('should batch create topics and update associated messages', async () => {
- // 准备测试数据
- const topicParams = [
- {
- title: 'Topic 1',
- favorite: true,
- sessionId,
- messages: ['message1', 'message2'],
- },
- {
- title: 'Topic 2',
- favorite: false,
- sessionId,
- messages: ['message3'],
- },
- ];
- await serverDB.insert(messages).values([
- { id: 'message1', role: 'user', userId },
- { id: 'message2', role: 'assistant', userId },
- { id: 'message3', role: 'user', userId },
- ]);
-
- // 调用 batchCreate 方法
- const createdTopics = await topicModel.batchCreate(topicParams);
-
- // 断言返回的 topics 数据正确
- expect(createdTopics).toHaveLength(2);
- expect(createdTopics[0]).toMatchObject({
- title: 'Topic 1',
- favorite: true,
- sessionId,
- userId,
- });
- expect(createdTopics[1]).toMatchObject({
- title: 'Topic 2',
- favorite: false,
- sessionId,
- userId,
- });
-
- // 断言 topics 表中的数据正确
- const items = await serverDB.select().from(topics);
- expect(items).toHaveLength(2);
- expect(items[0]).toMatchObject({
- title: 'Topic 1',
- favorite: true,
- sessionId,
- userId,
- });
- expect(items[1]).toMatchObject({
- title: 'Topic 2',
- favorite: false,
- sessionId,
- userId,
- });
-
- // 断言关联的 messages 的 topicId 被正确更新
- const updatedMessages = await serverDB.select().from(messages);
- expect(updatedMessages).toHaveLength(3);
- expect(updatedMessages[0].topicId).toBe(createdTopics[0].id);
- expect(updatedMessages[1].topicId).toBe(createdTopics[0].id);
- expect(updatedMessages[2].topicId).toBe(createdTopics[1].id);
- });
-
- it('should generate topic IDs if not provided', async () => {
- // 准备测试数据
- const topicParams = [
- {
- title: 'Topic 1',
- favorite: true,
- sessionId,
- },
- {
- title: 'Topic 2',
- favorite: false,
- sessionId,
- },
- ];
-
- // 调用 batchCreate 方法
- const createdTopics = await topicModel.batchCreate(topicParams);
-
- // 断言生成了正确的 topic ID
- expect(createdTopics[0].id).toBeDefined();
- expect(createdTopics[1].id).toBeDefined();
- expect(createdTopics[0].id).not.toBe(createdTopics[1].id);
- });
- });
-
- describe('duplicate', () => {
- it('should duplicate a topic and its associated messages', async () => {
- const topicId = 'topic-duplicate';
- const newTitle = 'Duplicated Topic';
-
- // 创建原始的 topic 和 messages
- await serverDB.transaction(async (tx) => {
- await tx.insert(topics).values({ id: topicId, sessionId, userId, title: 'Original Topic' });
- await tx.insert(messages).values([
- { id: 'message1', role: 'user', topicId, userId, content: 'User message' },
- { id: 'message2', role: 'assistant', topicId, userId, content: 'Assistant message' },
- ]);
- });
-
- // 调用 duplicate 方法
- const { topic: duplicatedTopic, messages: duplicatedMessages } = await topicModel.duplicate(
- topicId,
- newTitle,
- );
-
- // 断言复制的 topic 的属性正确
- expect(duplicatedTopic.id).not.toBe(topicId);
- expect(duplicatedTopic.title).toBe(newTitle);
- expect(duplicatedTopic.sessionId).toBe(sessionId);
- expect(duplicatedTopic.userId).toBe(userId);
-
- // 断言复制的 messages 的属性正确
- expect(duplicatedMessages).toHaveLength(2);
- expect(duplicatedMessages[0].id).not.toBe('message1');
- expect(duplicatedMessages[0].topicId).toBe(duplicatedTopic.id);
- expect(duplicatedMessages[0].content).toBe('User message');
- expect(duplicatedMessages[1].id).not.toBe('message2');
- expect(duplicatedMessages[1].topicId).toBe(duplicatedTopic.id);
- expect(duplicatedMessages[1].content).toBe('Assistant message');
- });
-
- it('should throw an error if the topic to duplicate does not exist', async () => {
- const topicId = 'nonexistent-topic';
-
- // 调用 duplicate 方法,期望抛出错误
- await expect(topicModel.duplicate(topicId)).rejects.toThrow(
- `Topic with id ${topicId} not found`,
- );
- });
- });
-
- describe('rank', () => {
- it('should return ranked topics based on message count', async () => {
- // 创建测试数据
- await serverDB.transaction(async (tx) => {
- await tx.insert(topics).values([
- { id: 'topic1', title: 'Topic 1', sessionId, userId },
- { id: 'topic2', title: 'Topic 2', sessionId, userId },
- { id: 'topic3', title: 'Topic 3', sessionId, userId },
- ]);
-
- // topic1 有 3 条消息
- await tx.insert(messages).values([
- { id: 'msg1', role: 'user', topicId: 'topic1', userId },
- { id: 'msg2', role: 'assistant', topicId: 'topic1', userId },
- { id: 'msg3', role: 'user', topicId: 'topic1', userId },
- ]);
-
- // topic2 有 2 条消息
- await tx.insert(messages).values([
- { id: 'msg4', role: 'user', topicId: 'topic2', userId },
- { id: 'msg5', role: 'assistant', topicId: 'topic2', userId },
- ]);
-
- // topic3 有 1 条消息
- await tx.insert(messages).values([{ id: 'msg6', role: 'user', topicId: 'topic3', userId }]);
- });
-
- // 调用 rank 方法
- const result = await topicModel.rank(2);
-
- // 断言返回结果符合预期
- expect(result).toHaveLength(2);
- expect(result[0]).toMatchObject({
- id: 'topic1',
- title: 'Topic 1',
- count: 3,
- sessionId,
- });
- expect(result[1]).toMatchObject({
- id: 'topic2',
- title: 'Topic 2',
- count: 2,
- sessionId,
- });
- });
-
- it('should return empty array if no topics exist', async () => {
- const result = await topicModel.rank();
- expect(result).toHaveLength(0);
- });
-
- it('should respect the limit parameter', async () => {
- // 创建测试数据
- await serverDB.transaction(async (tx) => {
- await tx.insert(topics).values([
- { id: 'topic1', title: 'Topic 1', sessionId, userId },
- { id: 'topic2', title: 'Topic 2', sessionId, userId },
- ]);
-
- await tx.insert(messages).values([
- { id: 'msg1', role: 'user', topicId: 'topic1', userId },
- { id: 'msg2', role: 'user', topicId: 'topic2', userId },
- ]);
- });
-
- // 使用限制为 1 调用 rank 方法
- const result = await topicModel.rank(1);
-
- // 断言只返回一个结果
- expect(result).toHaveLength(1);
- });
- });
-
- describe('count with date filters', () => {
- beforeEach(async () => {
- // 创建测试数据
- await serverDB.insert(topics).values([
- {
- id: 'topic1',
- userId,
- createdAt: new Date('2023-01-01'),
- },
- {
- id: 'topic2',
- userId,
- createdAt: new Date('2023-02-01'),
- },
- {
- id: 'topic3',
- userId,
- createdAt: new Date('2023-03-01'),
- },
- ]);
- });
-
- it('should count topics with start date filter', async () => {
- const result = await topicModel.count({
- startDate: '2023-02-01',
- });
-
- expect(result).toBe(2); // should count topics from Feb 1st onwards
- });
-
- it('should count topics with end date filter', async () => {
- const result = await topicModel.count({
- endDate: '2023-02-01',
- });
-
- expect(result).toBe(2); // should count topics up to Feb 1st
- });
-
- it('should count topics within date range', async () => {
- const result = await topicModel.count({
- range: ['2023-01-15', '2023-02-15'],
- });
-
- expect(result).toBe(1); // should only count topic2
- });
-
- it('should return 0 if no topics match date filters', async () => {
- const result = await topicModel.count({
- range: ['2024-01-01', '2024-12-31'],
- });
-
- expect(result).toBe(0);
- });
-
- it('should handle invalid date filters gracefully', async () => {
- const result = await topicModel.count({
- startDate: 'invalid-date',
- });
-
- expect(result).toBe(3); // should return all topics if date is invalid
- });
- });
-});
diff --git a/packages/database/src/models/__tests__/topics/topic.create.test.ts b/packages/database/src/models/__tests__/topics/topic.create.test.ts
new file mode 100644
index 00000000000..61d8852af7c
--- /dev/null
+++ b/packages/database/src/models/__tests__/topics/topic.create.test.ts
@@ -0,0 +1,257 @@
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { agents, messages, sessions, topics, users } from '../../../schemas';
+import { LobeChatDatabase } from '../../../type';
+import { CreateTopicParams, TopicModel } from '../../topic';
+import { getTestDB } from '../_util';
+
+const userId = 'topic-create-user';
+const userId2 = 'topic-create-user-2';
+const sessionId = 'topic-create-session';
+const serverDB: LobeChatDatabase = await getTestDB();
+const topicModel = new TopicModel(serverDB, userId);
+
+describe('TopicModel - Create', () => {
+ beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(users).values([{ id: userId }, { id: userId2 }]);
+ await tx.insert(sessions).values({ id: sessionId, userId });
+ });
+ });
+
+ afterEach(async () => {
+ await serverDB.delete(users);
+ });
+
+ describe('create', () => {
+ it('should create a new topic and associate messages', async () => {
+ const topicData = {
+ title: 'New Topic',
+ favorite: true,
+ sessionId,
+ messages: ['message1', 'message2'],
+ } satisfies CreateTopicParams;
+
+ const topicId = 'new-topic';
+
+ await serverDB.insert(messages).values([
+ { id: 'message1', role: 'user', userId, sessionId },
+ { id: 'message2', role: 'assistant', userId, sessionId },
+ { id: 'message3', role: 'user', userId, sessionId },
+ ]);
+
+ const createdTopic = await topicModel.create(topicData, topicId);
+
+ expect(createdTopic).toEqual({
+ id: topicId,
+ title: 'New Topic',
+ favorite: true,
+ sessionId,
+ userId,
+ historySummary: null,
+ metadata: null,
+ groupId: null,
+ clientId: null,
+ agentId: null,
+ content: null,
+ editorData: null,
+ createdAt: expect.any(Date),
+ updatedAt: expect.any(Date),
+ accessedAt: expect.any(Date),
+ });
+
+ const dbTopic = await serverDB.select().from(topics).where(eq(topics.id, topicId));
+ expect(dbTopic).toHaveLength(1);
+ expect(dbTopic[0]).toEqual(createdTopic);
+
+ const associatedMessages = await serverDB.select().from(messages).where(inArray(messages.id, topicData.messages!));
+ expect(associatedMessages).toHaveLength(2);
+ expect(associatedMessages.every((msg) => msg.topicId === topicId)).toBe(true);
+
+ const unassociatedMessage = await serverDB.select().from(messages).where(eq(messages.id, 'message3'));
+ expect(unassociatedMessage[0].topicId).toBeNull();
+ });
+
+ it('should create a new topic without associating messages', async () => {
+ const topicData = {
+ title: 'New Topic',
+ favorite: false,
+ sessionId,
+ };
+
+ const topicId = 'new-topic';
+
+ const createdTopic = await topicModel.create(topicData, topicId);
+
+ expect(createdTopic).toEqual({
+ id: topicId,
+ title: 'New Topic',
+ favorite: false,
+ clientId: null,
+ agentId: null,
+ content: null,
+ editorData: null,
+ groupId: null,
+ historySummary: null,
+ metadata: null,
+ sessionId,
+ userId,
+ createdAt: expect.any(Date),
+ updatedAt: expect.any(Date),
+ accessedAt: expect.any(Date),
+ });
+
+ const dbTopic = await serverDB.select().from(topics).where(eq(topics.id, topicId));
+ expect(dbTopic).toHaveLength(1);
+ expect(dbTopic[0]).toEqual(createdTopic);
+ });
+
+ it('should create a new topic with agentId', async () => {
+ await serverDB.insert(agents).values({ id: 'agent-for-topic', userId, title: 'Test Agent' });
+
+ const topicData = {
+ title: 'Topic with Agent',
+ favorite: false,
+ sessionId,
+ agentId: 'agent-for-topic',
+ } satisfies CreateTopicParams;
+
+ const topicId = 'topic-with-agent';
+
+ const createdTopic = await topicModel.create(topicData, topicId);
+
+ expect(createdTopic.id).toBe(topicId);
+ expect(createdTopic.title).toBe('Topic with Agent');
+ expect(createdTopic.agentId).toBe('agent-for-topic');
+ expect(createdTopic.sessionId).toBe(sessionId);
+
+ const dbTopic = await serverDB.select().from(topics).where(eq(topics.id, topicId));
+ expect(dbTopic).toHaveLength(1);
+ expect(dbTopic[0].agentId).toBe('agent-for-topic');
+ });
+
+ it('should create a new topic with only agentId (no sessionId)', async () => {
+ await serverDB.insert(agents).values({ id: 'agent-only', userId, title: 'Agent Only' });
+
+ const topicData = {
+ title: 'Agent Only Topic',
+ favorite: true,
+ agentId: 'agent-only',
+ } satisfies CreateTopicParams;
+
+ const topicId = 'agent-only-topic';
+
+ const createdTopic = await topicModel.create(topicData, topicId);
+
+ expect(createdTopic.agentId).toBe('agent-only');
+ expect(createdTopic.sessionId).toBeNull();
+ });
+ });
+
+ describe('batchCreate', () => {
+ it('should batch create topics and update associated messages', async () => {
+ const topicParams = [
+ { title: 'Topic 1', favorite: true, sessionId, messages: ['message1', 'message2'] },
+ { title: 'Topic 2', favorite: false, sessionId, messages: ['message3'] },
+ ];
+ await serverDB.insert(messages).values([
+ { id: 'message1', role: 'user', userId },
+ { id: 'message2', role: 'assistant', userId },
+ { id: 'message3', role: 'user', userId },
+ ]);
+
+ const createdTopics = await topicModel.batchCreate(topicParams);
+
+ expect(createdTopics).toHaveLength(2);
+ expect(createdTopics[0]).toMatchObject({ title: 'Topic 1', favorite: true, sessionId, userId });
+ expect(createdTopics[1]).toMatchObject({ title: 'Topic 2', favorite: false, sessionId, userId });
+
+ const items = await serverDB.select().from(topics);
+ expect(items).toHaveLength(2);
+ expect(items[0]).toMatchObject({ title: 'Topic 1', favorite: true, sessionId, userId });
+ expect(items[1]).toMatchObject({ title: 'Topic 2', favorite: false, sessionId, userId });
+
+ const updatedMessages = await serverDB.select().from(messages);
+ expect(updatedMessages).toHaveLength(3);
+ expect(updatedMessages[0].topicId).toBe(createdTopics[0].id);
+ expect(updatedMessages[1].topicId).toBe(createdTopics[0].id);
+ expect(updatedMessages[2].topicId).toBe(createdTopics[1].id);
+ });
+
+ it('should generate topic IDs if not provided', async () => {
+ const topicParams = [
+ { title: 'Topic 1', favorite: true, sessionId },
+ { title: 'Topic 2', favorite: false, sessionId },
+ ];
+
+ const createdTopics = await topicModel.batchCreate(topicParams);
+
+ expect(createdTopics[0].id).toBeDefined();
+ expect(createdTopics[1].id).toBeDefined();
+ expect(createdTopics[0].id).not.toBe(createdTopics[1].id);
+ });
+
+ it('should batch create topics with agentId', async () => {
+ await serverDB.insert(agents).values([
+ { id: 'batch-agent-1', userId, title: 'Batch Agent 1' },
+ { id: 'batch-agent-2', userId, title: 'Batch Agent 2' },
+ ]);
+
+ const topicParams = [
+ { title: 'Topic with Agent 1', favorite: true, sessionId, agentId: 'batch-agent-1' },
+ { title: 'Topic with Agent 2', favorite: false, agentId: 'batch-agent-2' },
+ ];
+
+ const createdTopics = await topicModel.batchCreate(topicParams);
+
+ expect(createdTopics).toHaveLength(2);
+ expect(createdTopics[0].agentId).toBe('batch-agent-1');
+ expect(createdTopics[0].sessionId).toBe(sessionId);
+ expect(createdTopics[1].agentId).toBe('batch-agent-2');
+ expect(createdTopics[1].sessionId).toBeNull();
+
+ const dbTopics = await serverDB.select().from(topics).where(inArray(topics.id, createdTopics.map((t) => t.id)));
+ expect(dbTopics).toHaveLength(2);
+ expect(dbTopics.find((t) => t.id === createdTopics[0].id)?.agentId).toBe('batch-agent-1');
+ expect(dbTopics.find((t) => t.id === createdTopics[1].id)?.agentId).toBe('batch-agent-2');
+ });
+ });
+
+ describe('duplicate', () => {
+ it('should duplicate a topic and its associated messages', async () => {
+ const topicId = 'topic-duplicate';
+ const newTitle = 'Duplicated Topic';
+
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(topics).values({ id: topicId, sessionId, userId, title: 'Original Topic' });
+ await tx.insert(messages).values([
+ { id: 'message1', role: 'user', topicId, userId, content: 'User message' },
+ { id: 'message2', role: 'assistant', topicId, userId, content: 'Assistant message' },
+ ]);
+ });
+
+ const { topic: duplicatedTopic, messages: duplicatedMessages } = await topicModel.duplicate(topicId, newTitle);
+
+ expect(duplicatedTopic.id).not.toBe(topicId);
+ expect(duplicatedTopic.title).toBe(newTitle);
+ expect(duplicatedTopic.sessionId).toBe(sessionId);
+ expect(duplicatedTopic.userId).toBe(userId);
+
+ expect(duplicatedMessages).toHaveLength(2);
+ expect(duplicatedMessages[0].id).not.toBe('message1');
+ expect(duplicatedMessages[0].topicId).toBe(duplicatedTopic.id);
+ expect(duplicatedMessages[0].content).toBe('User message');
+ expect(duplicatedMessages[1].id).not.toBe('message2');
+ expect(duplicatedMessages[1].topicId).toBe(duplicatedTopic.id);
+ expect(duplicatedMessages[1].content).toBe('Assistant message');
+ });
+
+ it('should throw an error if the topic to duplicate does not exist', async () => {
+ const topicId = 'nonexistent-topic';
+
+ await expect(topicModel.duplicate(topicId)).rejects.toThrow(`Topic with id ${topicId} not found`);
+ });
+ });
+});
diff --git a/packages/database/src/models/__tests__/topics/topic.delete.test.ts b/packages/database/src/models/__tests__/topics/topic.delete.test.ts
new file mode 100644
index 00000000000..8c921fcf0b7
--- /dev/null
+++ b/packages/database/src/models/__tests__/topics/topic.delete.test.ts
@@ -0,0 +1,328 @@
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import {
+ agents,
+ agentsToSessions,
+ chatGroups,
+ messages,
+ sessions,
+ topics,
+ users,
+} from '../../../schemas';
+import { LobeChatDatabase } from '../../../type';
+import { TopicModel } from '../../topic';
+import { getTestDB } from '../_util';
+
+const userId = 'topic-delete-user';
+const userId2 = 'topic-delete-user-2';
+const sessionId = 'topic-delete-session';
+const serverDB: LobeChatDatabase = await getTestDB();
+const topicModel = new TopicModel(serverDB, userId);
+
+describe('TopicModel - Delete', () => {
+ beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(users).values([{ id: userId }, { id: userId2 }]);
+ await tx.insert(sessions).values({ id: sessionId, userId });
+ });
+ });
+
+ afterEach(async () => {
+ await serverDB.delete(users);
+ });
+
+ describe('delete', () => {
+ it('should delete a topic and its associated messages', async () => {
+ const topicId = 'topic1';
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(users).values({ id: '345' });
+ await tx.insert(sessions).values([
+ { id: 'session1', userId },
+ { id: 'session2', userId: '345' },
+ ]);
+ await tx.insert(topics).values([
+ { id: topicId, sessionId: 'session1', userId },
+ { id: 'topic2', sessionId: 'session2', userId: '345' },
+ ]);
+ await tx.insert(messages).values([
+ { id: 'message1', role: 'user', topicId: topicId, userId },
+ { id: 'message2', role: 'assistant', topicId: topicId, userId },
+ { id: 'message3', role: 'user', topicId: 'topic2', userId: '345' },
+ ]);
+ });
+
+ await topicModel.delete(topicId);
+
+ expect(
+ await serverDB.select().from(messages).where(eq(messages.topicId, topicId)),
+ ).toHaveLength(0);
+ expect(await serverDB.select().from(topics)).toHaveLength(1);
+ expect(await serverDB.select().from(messages)).toHaveLength(1);
+ });
+ });
+
+ describe('batchDeleteBySessionId', () => {
+ it('should delete all topics associated with a session', async () => {
+ await serverDB.insert(sessions).values([
+ { id: 'session1', userId },
+ { id: 'session2', userId },
+ ]);
+ await serverDB.insert(topics).values([
+ { id: 'topic1', sessionId: 'session1', userId },
+ { id: 'topic2', sessionId: 'session1', userId },
+ { id: 'topic3', sessionId: 'session2', userId },
+ { id: 'topic4', userId },
+ ]);
+
+ await topicModel.batchDeleteBySessionId('session1');
+
+ expect(
+ await serverDB.select().from(topics).where(eq(topics.sessionId, 'session1')),
+ ).toHaveLength(0);
+ expect(await serverDB.select().from(topics)).toHaveLength(2);
+ });
+
+ it('should delete all topics associated without sessionId', async () => {
+ await serverDB.insert(sessions).values([{ id: 'session1', userId }]);
+ await serverDB.insert(topics).values([
+ { id: 'topic1', sessionId: 'session1', userId },
+ { id: 'topic2', sessionId: 'session1', userId },
+ { id: 'topic4', userId },
+ ]);
+
+ await topicModel.batchDeleteBySessionId();
+
+ expect(
+ await serverDB.select().from(topics).where(eq(topics.sessionId, 'session1')),
+ ).toHaveLength(2);
+ expect(await serverDB.select().from(topics)).toHaveLength(2);
+ });
+ });
+
+ describe('batchDeleteByGroupId', () => {
+ it('should delete all topics associated with a group', async () => {
+ await serverDB.insert(chatGroups).values([
+ { id: 'group1', userId, title: 'Group 1' },
+ { id: 'group2', userId, title: 'Group 2' },
+ ]);
+ await serverDB.insert(topics).values([
+ { id: 'topic1', groupId: 'group1', userId },
+ { id: 'topic2', groupId: 'group1', userId },
+ { id: 'topic3', groupId: 'group2', userId },
+ { id: 'topic4', userId },
+ ]);
+
+ await topicModel.batchDeleteByGroupId('group1');
+
+ expect(await serverDB.select().from(topics).where(eq(topics.groupId, 'group1'))).toHaveLength(
+ 0,
+ );
+ expect(await serverDB.select().from(topics)).toHaveLength(2);
+ });
+
+ it('should delete all topics associated without groupId', async () => {
+ await serverDB.insert(chatGroups).values([{ id: 'group1', userId, title: 'Group 1' }]);
+ await serverDB.insert(topics).values([
+ { id: 'topic1', groupId: 'group1', userId },
+ { id: 'topic2', groupId: 'group1', userId },
+ { id: 'topic4', userId },
+ ]);
+
+ await topicModel.batchDeleteByGroupId();
+
+ expect(await serverDB.select().from(topics).where(eq(topics.groupId, 'group1'))).toHaveLength(
+ 2,
+ );
+ expect(await serverDB.select().from(topics)).toHaveLength(2);
+ });
+ });
+
+ describe('batchDeleteByAgentId', () => {
+ it('should delete topics with direct agentId match (new data)', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(agents).values([
+ { id: 'delete-agent-1', userId, title: 'Delete Agent 1' },
+ { id: 'delete-agent-2', userId, title: 'Delete Agent 2' },
+ ]);
+ await trx.insert(topics).values([
+ { id: 'topic-agent-1', userId, agentId: 'delete-agent-1' },
+ { id: 'topic-agent-1-b', userId, agentId: 'delete-agent-1' },
+ { id: 'topic-agent-2', userId, agentId: 'delete-agent-2' },
+ ]);
+ });
+
+ await topicModel.batchDeleteByAgentId('delete-agent-1');
+
+ const remainingTopics = await serverDB.select().from(topics).where(eq(topics.userId, userId));
+ expect(remainingTopics).toHaveLength(1);
+ expect(remainingTopics[0].id).toBe('topic-agent-2');
+ });
+
+ it('should delete legacy topics via sessionId lookup', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([
+ { id: 'legacy-session-1', userId },
+ { id: 'legacy-session-2', userId },
+ ]);
+ await trx.insert(agents).values([{ id: 'legacy-agent', userId, title: 'Legacy Agent' }]);
+ await trx
+ .insert(agentsToSessions)
+ .values([{ agentId: 'legacy-agent', sessionId: 'legacy-session-1', userId }]);
+ await trx.insert(topics).values([
+ { id: 'legacy-topic-1', userId, sessionId: 'legacy-session-1', agentId: null },
+ { id: 'legacy-topic-2', userId, sessionId: 'legacy-session-1', agentId: null },
+ { id: 'other-session-topic', userId, sessionId: 'legacy-session-2', agentId: null },
+ ]);
+ });
+
+ await topicModel.batchDeleteByAgentId('legacy-agent');
+
+ const remainingTopics = await serverDB.select().from(topics).where(eq(topics.userId, userId));
+ expect(remainingTopics).toHaveLength(1);
+ expect(remainingTopics[0].id).toBe('other-session-topic');
+ });
+
+ it('should delete both new and legacy topics', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'mixed-del-session', userId }]);
+ await trx
+ .insert(agents)
+ .values([{ id: 'mixed-del-agent', userId, title: 'Mixed Delete Agent' }]);
+ await trx
+ .insert(agentsToSessions)
+ .values([{ agentId: 'mixed-del-agent', sessionId: 'mixed-del-session', userId }]);
+ await trx.insert(topics).values([
+ { id: 'mixed-legacy', userId, sessionId: 'mixed-del-session', agentId: null },
+ { id: 'mixed-new', userId, agentId: 'mixed-del-agent', sessionId: null },
+ { id: 'mixed-both', userId, sessionId: 'mixed-del-session', agentId: 'mixed-del-agent' },
+ ]);
+ });
+
+ await topicModel.batchDeleteByAgentId('mixed-del-agent');
+
+ const remainingTopics = await serverDB.select().from(topics).where(eq(topics.userId, userId));
+ expect(remainingTopics).toHaveLength(0);
+ });
+
+ it('should not delete topics from other users', async () => {
+ const otherUserId = 'other-user-delete-test';
+
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(users).values([{ id: otherUserId }]);
+ await trx
+ .insert(agents)
+ .values([{ id: 'shared-delete-agent', userId, title: 'Shared Agent' }]);
+ await trx.insert(topics).values([
+ { id: 'user-topic-del', userId, agentId: 'shared-delete-agent' },
+ { id: 'other-user-topic-del', userId: otherUserId, agentId: 'shared-delete-agent' },
+ ]);
+ });
+
+ await topicModel.batchDeleteByAgentId('shared-delete-agent');
+
+ const allTopics = await serverDB.select().from(topics);
+ expect(allTopics).toHaveLength(1);
+ expect(allTopics[0].id).toBe('other-user-topic-del');
+ });
+
+ it('should handle agent with no associated session gracefully', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx
+ .insert(agents)
+ .values([{ id: 'no-session-agent', userId, title: 'No Session Agent' }]);
+ await trx
+ .insert(topics)
+ .values([{ id: 'orphan-del-topic', userId, agentId: 'no-session-agent' }]);
+ });
+
+ await topicModel.batchDeleteByAgentId('no-session-agent');
+
+ const remainingTopics = await serverDB.select().from(topics).where(eq(topics.userId, userId));
+ expect(remainingTopics).toHaveLength(0);
+ });
+
+ it('should not delete any topics if agentId does not match', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx
+ .insert(agents)
+ .values([{ id: 'existing-agent', userId, title: 'Existing Agent' }]);
+ await trx
+ .insert(topics)
+ .values([{ id: 'existing-topic', userId, agentId: 'existing-agent' }]);
+ });
+
+ await topicModel.batchDeleteByAgentId('non-existent-agent');
+
+ const remainingTopics = await serverDB.select().from(topics).where(eq(topics.userId, userId));
+ expect(remainingTopics).toHaveLength(1);
+ });
+
+ it('should delete associated messages when topics are deleted', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx
+ .insert(agents)
+ .values([{ id: 'msg-del-agent', userId, title: 'Message Delete Agent' }]);
+ await trx
+ .insert(topics)
+ .values([{ id: 'msg-del-topic', userId, agentId: 'msg-del-agent' }]);
+ await trx.insert(messages).values([
+ { id: 'msg1', userId, role: 'user', topicId: 'msg-del-topic' },
+ { id: 'msg2', userId, role: 'assistant', topicId: 'msg-del-topic' },
+ ]);
+ });
+
+ await topicModel.batchDeleteByAgentId('msg-del-agent');
+
+ const remainingMessages = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.userId, userId));
+ expect(remainingMessages).toHaveLength(0);
+ });
+ });
+
+ describe('batchDelete', () => {
+ it('should delete multiple topics and their associated messages', async () => {
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(sessions).values({ id: 'session1', userId });
+ await tx.insert(topics).values([
+ { id: 'topic1', sessionId: 'session1', userId },
+ { id: 'topic2', sessionId: 'session1', userId },
+ { id: 'topic3', sessionId: 'session1', userId },
+ ]);
+ await tx.insert(messages).values([
+ { id: 'message1', role: 'user', topicId: 'topic1', userId },
+ { id: 'message2', role: 'assistant', topicId: 'topic2', userId },
+ { id: 'message3', role: 'user', topicId: 'topic3', userId },
+ ]);
+ });
+
+ await topicModel.batchDelete(['topic1', 'topic2']);
+
+ expect(await serverDB.select().from(topics)).toHaveLength(1);
+ expect(await serverDB.select().from(messages)).toHaveLength(1);
+ });
+ });
+
+ describe('deleteAll', () => {
+ it('should delete all topics of the user', async () => {
+ await serverDB.insert(users).values({ id: '345' });
+ await serverDB.insert(sessions).values([
+ { id: 'session1', userId },
+ { id: 'session2', userId: '345' },
+ ]);
+ await serverDB.insert(topics).values([
+ { id: 'topic1', sessionId: 'session1', userId },
+ { id: 'topic2', sessionId: 'session1', userId },
+ { id: 'topic3', sessionId: 'session2', userId: '345' },
+ ]);
+
+ await topicModel.deleteAll();
+
+ expect(await serverDB.select().from(topics).where(eq(topics.userId, userId))).toHaveLength(0);
+ expect(await serverDB.select().from(topics)).toHaveLength(1);
+ });
+ });
+});
diff --git a/packages/database/src/models/__tests__/topics/topic.query.test.ts b/packages/database/src/models/__tests__/topics/topic.query.test.ts
new file mode 100644
index 00000000000..c17afde2516
--- /dev/null
+++ b/packages/database/src/models/__tests__/topics/topic.query.test.ts
@@ -0,0 +1,1357 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import {
+ agents,
+ agentsToSessions,
+ chatGroups,
+ messages,
+ sessions,
+ topics,
+ users,
+} from '../../../schemas';
+import { LobeChatDatabase } from '../../../type';
+import { TopicModel } from '../../topic';
+import { getTestDB } from '../_util';
+
+const userId = 'topic-query-user';
+const userId2 = 'topic-query-user-2';
+const sessionId = 'topic-query-session';
+const serverDB: LobeChatDatabase = await getTestDB();
+const topicModel = new TopicModel(serverDB, userId);
+
+describe('TopicModel - Query', () => {
+ beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(users).values([{ id: userId }, { id: userId2 }]);
+ await tx.insert(sessions).values({ id: sessionId, userId });
+ });
+ });
+
+ afterEach(async () => {
+ await serverDB.delete(users);
+ });
+
+ describe('query', () => {
+ it('should query topics by user ID', async () => {
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(users).values([{ id: '456' }]);
+ await tx.insert(topics).values([
+ { id: '1', userId, sessionId, updatedAt: new Date('2023-01-01') },
+ { id: '4', userId, sessionId, updatedAt: new Date('2023-03-01') },
+ { id: '2', userId, sessionId, updatedAt: new Date('2023-02-01'), favorite: true },
+ { id: '5', userId, sessionId, updatedAt: new Date('2023-05-01'), favorite: true },
+ { id: '3', userId: '456', sessionId, updatedAt: new Date('2023-03-01') },
+ ]);
+ });
+
+ const result = await topicModel.query({ containerId: sessionId });
+
+ expect(result.items).toHaveLength(4);
+ expect(result.items[0].id).toBe('5');
+ expect(result.items[1].id).toBe('2');
+ expect(result.items[2].id).toBe('4');
+ });
+
+ it('should query topics with pagination', async () => {
+ await serverDB.insert(topics).values([
+ { id: '1', userId, updatedAt: new Date('2023-01-01') },
+ { id: '2', userId, updatedAt: new Date('2023-02-01') },
+ { id: '3', userId, updatedAt: new Date('2023-03-01') },
+ ]);
+
+ const { items: result1 } = await topicModel.query({ current: 0, pageSize: 2 });
+ expect(result1).toHaveLength(2);
+
+ const { items: result2 } = await topicModel.query({ current: 1, pageSize: 1 });
+ expect(result2).toHaveLength(1);
+ expect(result2[0].id).toBe('2');
+ });
+
+ it('should query topics by session ID', async () => {
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(sessions).values([
+ { id: 'session1', userId },
+ { id: 'session2', userId },
+ ]);
+ await tx.insert(topics).values([
+ { id: '1', userId, sessionId: 'session1' },
+ { id: '2', userId, sessionId: 'session2' },
+ { id: '3', userId },
+ ]);
+ });
+
+ const result = await topicModel.query({ containerId: 'session1' });
+ expect(result.items).toHaveLength(1);
+ expect(result.items[0].id).toBe('1');
+ });
+
+ it('should query topics by group ID using containerId (backward compatible)', async () => {
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(chatGroups).values([
+ { id: 'chat-group-1', title: 'Chat Group 1', userId },
+ { id: 'chat-group-2', title: 'Chat Group 2', userId },
+ ]);
+ await tx.insert(topics).values([
+ {
+ id: 'group-topic-1',
+ userId,
+ groupId: 'chat-group-1',
+ favorite: true,
+ updatedAt: new Date('2023-05-01'),
+ },
+ {
+ id: 'group-topic-2',
+ userId,
+ groupId: 'chat-group-1',
+ favorite: false,
+ updatedAt: new Date('2023-04-01'),
+ },
+ {
+ id: 'group-topic-3',
+ userId,
+ groupId: 'chat-group-2',
+ favorite: true,
+ updatedAt: new Date('2023-06-01'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.query({ containerId: 'chat-group-1' });
+
+ expect(result.items).toHaveLength(2);
+ expect(result.items[0].id).toBe('group-topic-1');
+ expect(result.items[1].id).toBe('group-topic-2');
+ });
+
+ it('should query topics by group ID using groupId parameter', async () => {
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(chatGroups).values([
+ { id: 'chat-group-3', title: 'Chat Group 3', userId },
+ { id: 'chat-group-4', title: 'Chat Group 4', userId },
+ ]);
+ await tx.insert(topics).values([
+ {
+ id: 'group-topic-4',
+ userId,
+ groupId: 'chat-group-3',
+ favorite: true,
+ updatedAt: new Date('2023-05-01'),
+ },
+ {
+ id: 'group-topic-5',
+ userId,
+ groupId: 'chat-group-3',
+ favorite: false,
+ updatedAt: new Date('2023-04-01'),
+ },
+ {
+ id: 'group-topic-6',
+ userId,
+ groupId: 'chat-group-4',
+ favorite: true,
+ updatedAt: new Date('2023-06-01'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.query({ groupId: 'chat-group-3' });
+
+ expect(result.items).toHaveLength(2);
+ expect(result.items[0].id).toBe('group-topic-4');
+ expect(result.items[1].id).toBe('group-topic-5');
+ });
+
+ it('should return topics based on pagination parameters', async () => {
+ await serverDB.insert(topics).values([
+ { id: 'topic1', sessionId, userId, updatedAt: new Date('2023-01-01') },
+ { id: 'topic2', sessionId, userId, updatedAt: new Date('2023-01-02') },
+ { id: 'topic3', sessionId, userId, updatedAt: new Date('2023-01-03') },
+ ]);
+
+ const { items: result1 } = await topicModel.query({
+ containerId: sessionId,
+ current: 0,
+ pageSize: 2,
+ });
+ const { items: result2 } = await topicModel.query({
+ containerId: sessionId,
+ current: 1,
+ pageSize: 2,
+ });
+
+ expect(result1).toHaveLength(2);
+ expect(result1[0].id).toBe('topic3');
+ expect(result1[1].id).toBe('topic2');
+
+ expect(result2).toHaveLength(1);
+ expect(result2[0].id).toBe('topic1');
+ });
+ });
+
+ describe('query with agentId filter', () => {
+ it('should filter legacy topics by agentId through agentsToSessions lookup', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([
+ { id: 'session-for-agent', userId },
+ { id: 'session-other', userId },
+ ]);
+ await trx.insert(agents).values([{ id: 'agent1', userId, title: 'Agent 1' }]);
+ await trx
+ .insert(agentsToSessions)
+ .values([{ agentId: 'agent1', sessionId: 'session-for-agent', userId }]);
+ await trx.insert(topics).values([
+ {
+ id: 'topic-agent-session',
+ userId,
+ sessionId: 'session-for-agent',
+ agentId: null,
+ updatedAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'topic-other-session',
+ userId,
+ sessionId: 'session-other',
+ agentId: null,
+ updatedAt: new Date('2023-01-02'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.query({ agentId: 'agent1' });
+
+ expect(result.items).toHaveLength(1);
+ expect(result.items[0].id).toBe('topic-agent-session');
+ });
+
+ it('should filter new topics by agentId directly', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(agents).values([
+ { id: 'new-agent-1', userId, title: 'New Agent 1' },
+ { id: 'new-agent-2', userId, title: 'New Agent 2' },
+ ]);
+ await trx.insert(topics).values([
+ {
+ id: 'new-topic-1',
+ userId,
+ agentId: 'new-agent-1',
+ sessionId: null,
+ updatedAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'new-topic-2',
+ userId,
+ agentId: 'new-agent-2',
+ sessionId: null,
+ updatedAt: new Date('2023-01-02'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.query({ agentId: 'new-agent-1' });
+
+ expect(result.items).toHaveLength(1);
+ expect(result.items[0].id).toBe('new-topic-1');
+ });
+
+ it('should return both legacy and new topics when querying by agentId', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'mixed-session', userId }]);
+ await trx.insert(agents).values([{ id: 'mixed-agent', userId, title: 'Mixed Agent' }]);
+ await trx
+ .insert(agentsToSessions)
+ .values([{ agentId: 'mixed-agent', sessionId: 'mixed-session', userId }]);
+ await trx.insert(topics).values([
+ {
+ id: 'legacy-topic',
+ userId,
+ sessionId: 'mixed-session',
+ agentId: null,
+ updatedAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'new-topic',
+ userId,
+ sessionId: null,
+ agentId: 'mixed-agent',
+ updatedAt: new Date('2023-01-02'),
+ },
+ {
+ id: 'both-topic',
+ userId,
+ sessionId: 'mixed-session',
+ agentId: 'mixed-agent',
+ updatedAt: new Date('2023-01-03'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.query({ agentId: 'mixed-agent' });
+
+ expect(result.items).toHaveLength(3);
+ expect(result.items.map((t) => t.id).sort()).toEqual([
+ 'both-topic',
+ 'legacy-topic',
+ 'new-topic',
+ ]);
+ });
+
+ it('should not return duplicate topics when both agentId and sessionId match', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'dedup-session', userId }]);
+ await trx.insert(agents).values([{ id: 'dedup-agent', userId, title: 'Dedup Agent' }]);
+ await trx
+ .insert(agentsToSessions)
+ .values([{ agentId: 'dedup-agent', sessionId: 'dedup-session', userId }]);
+ await trx.insert(topics).values([
+ {
+ id: 'dedup-topic',
+ userId,
+ sessionId: 'dedup-session',
+ agentId: 'dedup-agent',
+ updatedAt: new Date('2023-01-01'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.query({ agentId: 'dedup-agent' });
+
+ expect(result.items).toHaveLength(1);
+ expect(result.items[0].id).toBe('dedup-topic');
+ });
+
+ it('should return empty array when agentId has no associated session and no direct agentId match', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'session1', userId }]);
+ await trx
+ .insert(agents)
+ .values([{ id: 'agent-no-match', userId, title: 'Agent No Match' }]);
+ await trx
+ .insert(topics)
+ .values([{ id: 'topic-session1', userId, sessionId: 'session1', agentId: null }]);
+ });
+
+ const result = await topicModel.query({ agentId: 'agent-no-match' });
+
+ expect(result.items).toHaveLength(0);
+ });
+
+ it('should return topics with direct agentId match even without agentsToSessions entry', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(agents).values([{ id: 'orphan-agent', userId, title: 'Orphan Agent' }]);
+ await trx.insert(topics).values([
+ {
+ id: 'orphan-topic',
+ userId,
+ agentId: 'orphan-agent',
+ sessionId: null,
+ updatedAt: new Date('2023-01-01'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.query({ agentId: 'orphan-agent' });
+
+ expect(result.items).toHaveLength(1);
+ expect(result.items[0].id).toBe('orphan-topic');
+ });
+
+ it('should only return topics for current user when querying by agentId', async () => {
+ const otherUserId = 'other-user-for-topic-test';
+
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(users).values([{ id: otherUserId }]);
+ await trx.insert(agents).values([{ id: 'shared-agent-name', userId, title: 'User Agent' }]);
+ await trx.insert(topics).values([
+ { id: 'user-topic', userId, agentId: 'shared-agent-name' },
+ { id: 'other-user-topic', userId: otherUserId, agentId: 'shared-agent-name' },
+ ]);
+ });
+
+ const result = await topicModel.query({ agentId: 'shared-agent-name' });
+
+ expect(result.items).toHaveLength(1);
+ expect(result.items[0].id).toBe('user-topic');
+ });
+
+ it('should only lookup agentsToSessions for current user', async () => {
+ const otherUserId = 'other-user-for-topic-test-2';
+
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(users).values([{ id: otherUserId }]);
+ await trx.insert(sessions).values([
+ { id: 'user-session', userId },
+ { id: 'other-user-session', userId: otherUserId },
+ ]);
+ await trx.insert(agents).values([
+ { id: 'user-agent', userId, title: 'User Agent' },
+ { id: 'other-user-agent', userId: otherUserId, title: 'Other User Agent' },
+ ]);
+ await trx
+ .insert(agentsToSessions)
+ .values([
+ { agentId: 'other-user-agent', sessionId: 'other-user-session', userId: otherUserId },
+ ]);
+ await trx.insert(topics).values([
+ { id: 'topic-user', userId, agentId: 'other-user-agent' },
+ { id: 'topic-other-user', userId: otherUserId, sessionId: 'other-user-session' },
+ ]);
+ });
+
+ const result = await topicModel.query({ agentId: 'other-user-agent' });
+
+ expect(result.items).toHaveLength(1);
+ expect(result.items[0].id).toBe('topic-user');
+ });
+
+ it('should work with agentId and pagination', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx
+ .insert(agents)
+ .values([{ id: 'paginate-agent', userId, title: 'Paginate Agent' }]);
+ await trx.insert(topics).values([
+ {
+ id: 'page-topic1',
+ userId,
+ agentId: 'paginate-agent',
+ updatedAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'page-topic2',
+ userId,
+ agentId: 'paginate-agent',
+ updatedAt: new Date('2023-01-02'),
+ },
+ {
+ id: 'page-topic3',
+ userId,
+ agentId: 'paginate-agent',
+ updatedAt: new Date('2023-01-03'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.query({ agentId: 'paginate-agent', current: 0, pageSize: 2 });
+
+ expect(result.items).toHaveLength(2);
+ expect(result.items[0].id).toBe('page-topic3');
+ expect(result.items[1].id).toBe('page-topic2');
+
+ const { items: result2 } = await topicModel.query({
+ agentId: 'paginate-agent',
+ current: 1,
+ pageSize: 2,
+ });
+ expect(result2).toHaveLength(1);
+ expect(result2[0].id).toBe('page-topic1');
+ });
+
+ it('should work with agentId and favorite sorting', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(agents).values([{ id: 'fav-agent', userId, title: 'Fav Agent' }]);
+ await trx.insert(topics).values([
+ {
+ id: 'fav-topic1',
+ userId,
+ agentId: 'fav-agent',
+ favorite: false,
+ updatedAt: new Date('2023-01-03'),
+ },
+ {
+ id: 'fav-topic2',
+ userId,
+ agentId: 'fav-agent',
+ favorite: true,
+ updatedAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'fav-topic3',
+ userId,
+ agentId: 'fav-agent',
+ favorite: true,
+ updatedAt: new Date('2023-01-02'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.query({ agentId: 'fav-agent' });
+
+ expect(result.items).toHaveLength(3);
+ expect(result.items[0].id).toBe('fav-topic3');
+ expect(result.items[1].id).toBe('fav-topic2');
+ expect(result.items[2].id).toBe('fav-topic1');
+ });
+
+ it('should use containerId when agentId is not provided', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'container-session', userId }]);
+ await trx.insert(topics).values([
+ {
+ id: 'container-topic',
+ userId,
+ sessionId: 'container-session',
+ updatedAt: new Date('2023-01-01'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.query({ containerId: 'container-session' });
+
+ expect(result.items).toHaveLength(1);
+ expect(result.items[0].id).toBe('container-topic');
+ });
+
+ it('should ignore containerId when agentId is provided', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([
+ { id: 'agent-only-session', userId },
+ { id: 'container-only-session', userId },
+ ]);
+ await trx
+ .insert(agents)
+ .values([{ id: 'priority-agent', userId, title: 'Priority Agent' }]);
+ await trx
+ .insert(agentsToSessions)
+ .values([{ agentId: 'priority-agent', sessionId: 'agent-only-session', userId }]);
+ await trx.insert(topics).values([
+ {
+ id: 'agent-topic',
+ userId,
+ sessionId: 'agent-only-session',
+ updatedAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'container-topic',
+ userId,
+ sessionId: 'container-only-session',
+ updatedAt: new Date('2023-01-02'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.query({
+ agentId: 'priority-agent',
+ containerId: 'container-only-session',
+ });
+
+ expect(result.items).toHaveLength(1);
+ expect(result.items[0].id).toBe('agent-topic');
+ });
+
+ it('should prioritize groupId over agentId when both provided', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx
+ .insert(chatGroups)
+ .values([{ id: 'priority-group', title: 'Priority Group', userId }]);
+ await trx
+ .insert(agents)
+ .values([{ id: 'priority-agent', userId, title: 'Priority Agent' }]);
+ await trx.insert(topics).values([
+ {
+ id: 'group-topic',
+ userId,
+ groupId: 'priority-group',
+ updatedAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'agent-topic',
+ userId,
+ agentId: 'priority-agent',
+ updatedAt: new Date('2023-01-02'),
+ },
+ ]);
+ });
+
+ // When groupId is provided, it should only return topics for that group
+ const result = await topicModel.query({
+ groupId: 'priority-group',
+ agentId: 'priority-agent',
+ });
+
+ expect(result.items).toHaveLength(1);
+ expect(result.items[0].id).toBe('group-topic');
+ });
+ });
+
+ describe('isInbox parameter', () => {
+ it('should query legacy inbox topics when isInbox is true', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(agents).values([{ id: 'inbox-agent', userId, title: 'Inbox Agent' }]);
+ await trx.insert(topics).values([
+ {
+ id: 'legacy-inbox-1',
+ userId,
+ sessionId: null,
+ groupId: null,
+ agentId: null,
+ updatedAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'legacy-inbox-2',
+ userId,
+ sessionId: null,
+ groupId: null,
+ agentId: null,
+ updatedAt: new Date('2023-01-02'),
+ },
+ {
+ id: 'new-inbox-topic',
+ userId,
+ sessionId: null,
+ groupId: null,
+ agentId: 'inbox-agent',
+ updatedAt: new Date('2023-01-03'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.query({ agentId: 'inbox-agent', isInbox: true });
+
+ expect(result.items).toHaveLength(3);
+ expect(result.items.map((t) => t.id).sort()).toEqual([
+ 'legacy-inbox-1',
+ 'legacy-inbox-2',
+ 'new-inbox-topic',
+ ]);
+ });
+
+ it('should NOT query legacy inbox topics when isInbox is false or undefined', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(agents).values([{ id: 'normal-agent', userId, title: 'Normal Agent' }]);
+ await trx.insert(topics).values([
+ {
+ id: 'legacy-inbox',
+ userId,
+ sessionId: null,
+ groupId: null,
+ agentId: null,
+ updatedAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'normal-topic',
+ userId,
+ sessionId: null,
+ groupId: null,
+ agentId: 'normal-agent',
+ updatedAt: new Date('2023-01-02'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.query({ agentId: 'normal-agent' });
+
+ expect(result.items).toHaveLength(1);
+ expect(result.items[0].id).toBe('normal-topic');
+ });
+
+ it('should not include topics with unrelated sessionId when querying inbox legacy data', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'some-session', userId }]);
+ await trx.insert(agents).values([{ id: 'inbox-agent-2', userId, title: 'Inbox Agent 2' }]);
+ await trx.insert(topics).values([
+ {
+ id: 'true-legacy-inbox',
+ userId,
+ sessionId: null,
+ groupId: null,
+ agentId: null,
+ updatedAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'session-topic',
+ userId,
+ sessionId: 'some-session',
+ groupId: null,
+ agentId: null,
+ updatedAt: new Date('2023-01-02'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.query({ agentId: 'inbox-agent-2', isInbox: true });
+
+ // Should only include true legacy inbox (no sessionId), not the unrelated session topic
+ expect(result.items).toHaveLength(1);
+ expect(result.items[0].id).toBe('true-legacy-inbox');
+ });
+
+ it('should include topics with associated sessionId via agentsToSessions when isInbox is true', async () => {
+ // This tests the scenario where old users have inbox topics with sessionId
+ // but no agentId, linked via agentsToSessions relation
+ await serverDB.transaction(async (trx) => {
+ // Create inbox session and agent with relation
+ await trx.insert(sessions).values([{ id: 'inbox-session', slug: 'inbox', userId }]);
+ await trx
+ .insert(agents)
+ .values([{ id: 'inbox-agent-linked', userId, title: 'Inbox Agent' }]);
+ await trx
+ .insert(agentsToSessions)
+ .values([{ agentId: 'inbox-agent-linked', sessionId: 'inbox-session', userId }]);
+
+ // Create topics: one with sessionId (legacy), one with agentId (new), one completely orphan
+ await trx.insert(topics).values([
+ {
+ id: 'legacy-session-topic',
+ userId,
+ sessionId: 'inbox-session',
+ groupId: null,
+ agentId: null,
+ updatedAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'new-agentid-topic',
+ userId,
+ sessionId: null,
+ groupId: null,
+ agentId: 'inbox-agent-linked',
+ updatedAt: new Date('2023-01-02'),
+ },
+ {
+ id: 'orphan-legacy-topic',
+ userId,
+ sessionId: null,
+ groupId: null,
+ agentId: null,
+ updatedAt: new Date('2023-01-03'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.query({ agentId: 'inbox-agent-linked', isInbox: true });
+
+ // Should include all three: legacy with sessionId, new with agentId, orphan legacy
+ expect(result.items).toHaveLength(3);
+ expect(result.items.map((t) => t.id).sort()).toEqual([
+ 'legacy-session-topic',
+ 'new-agentid-topic',
+ 'orphan-legacy-topic',
+ ]);
+ });
+
+ it('should not include topics with groupId when querying inbox legacy data', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(chatGroups).values([{ id: 'some-group', title: 'Some Group', userId }]);
+ await trx.insert(agents).values([{ id: 'inbox-agent-3', userId, title: 'Inbox Agent 3' }]);
+ await trx.insert(topics).values([
+ {
+ id: 'true-legacy-inbox-2',
+ userId,
+ sessionId: null,
+ groupId: null,
+ agentId: null,
+ updatedAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'group-topic',
+ userId,
+ sessionId: null,
+ groupId: 'some-group',
+ agentId: null,
+ updatedAt: new Date('2023-01-02'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.query({ agentId: 'inbox-agent-3', isInbox: true });
+
+ expect(result.items).toHaveLength(1);
+ expect(result.items[0].id).toBe('true-legacy-inbox-2');
+ });
+
+ it('should isolate legacy inbox topics by user', async () => {
+ const otherUserId = 'other-inbox-user';
+
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(users).values([{ id: otherUserId }]);
+ await trx.insert(agents).values([{ id: 'inbox-agent-4', userId, title: 'Inbox Agent 4' }]);
+ await trx.insert(topics).values([
+ {
+ id: 'my-legacy-inbox',
+ userId,
+ sessionId: null,
+ groupId: null,
+ agentId: null,
+ updatedAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'other-legacy-inbox',
+ userId: otherUserId,
+ sessionId: null,
+ groupId: null,
+ agentId: null,
+ updatedAt: new Date('2023-01-02'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.query({ agentId: 'inbox-agent-4', isInbox: true });
+
+ expect(result.items).toHaveLength(1);
+ expect(result.items[0].id).toBe('my-legacy-inbox');
+ });
+
+ it('should work with pagination when isInbox is true', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx
+ .insert(agents)
+ .values([{ id: 'inbox-paginate', userId, title: 'Inbox Paginate' }]);
+ await trx.insert(topics).values([
+ {
+ id: 'inbox-page-1',
+ userId,
+ sessionId: null,
+ groupId: null,
+ agentId: null,
+ updatedAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'inbox-page-2',
+ userId,
+ sessionId: null,
+ groupId: null,
+ agentId: null,
+ updatedAt: new Date('2023-01-02'),
+ },
+ {
+ id: 'inbox-page-3',
+ userId,
+ sessionId: null,
+ groupId: null,
+ agentId: 'inbox-paginate',
+ updatedAt: new Date('2023-01-03'),
+ },
+ ]);
+ });
+
+ const result1 = await topicModel.query({
+ agentId: 'inbox-paginate',
+ isInbox: true,
+ current: 0,
+ pageSize: 2,
+ });
+
+ expect(result1.items).toHaveLength(2);
+ expect(result1.total).toBe(3);
+
+ const result2 = await topicModel.query({
+ agentId: 'inbox-paginate',
+ isInbox: true,
+ current: 1,
+ pageSize: 2,
+ });
+
+ expect(result2.items).toHaveLength(1);
+ });
+ });
+
+ describe('findById', () => {
+ it('should return a topic by id', async () => {
+ await serverDB.insert(topics).values({ id: 'topic1', sessionId, userId });
+
+ const result = await topicModel.findById('topic1');
+
+ expect(result?.id).toBe('topic1');
+ });
+
+ it('should return undefined for non-existent topic', async () => {
+ const result = await topicModel.findById('non-existent');
+
+ expect(result).toBeUndefined();
+ });
+ });
+
+ describe('queryAll', () => {
+ it('should return all topics', async () => {
+ await serverDB.insert(topics).values([
+ { id: 'topic1', sessionId, userId },
+ { id: 'topic2', sessionId, userId },
+ ]);
+
+ const result = await topicModel.queryAll();
+
+ expect(result).toHaveLength(2);
+ expect(result[0].id).toBe('topic1');
+ expect(result[1].id).toBe('topic2');
+ });
+ });
+
+ describe('queryByKeyword', () => {
+ it('should return topics matching topic title keyword', async () => {
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(topics).values([
+ { id: 'topic1', title: 'Hello world', sessionId, userId },
+ { id: 'topic2', title: 'Goodbye', sessionId, userId },
+ ]);
+ await tx
+ .insert(messages)
+ .values([
+ { id: 'message1', role: 'assistant', content: 'abc there', topicId: 'topic1', userId },
+ ]);
+ });
+
+ const result = await topicModel.queryByKeyword('hello', sessionId);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('topic1');
+ });
+
+ it('should return topics matching message content keyword', async () => {
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(topics).values([
+ { id: 'topic1', title: 'abc world', sessionId, userId },
+ { id: 'topic2', title: 'Goodbye', sessionId, userId },
+ ]);
+ await tx.insert(messages).values([
+ {
+ id: 'message1',
+ role: 'assistant',
+ content: 'Hello there',
+ topicId: 'topic1',
+ userId,
+ },
+ ]);
+ });
+
+ const result = await topicModel.queryByKeyword('hello', sessionId);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('topic1');
+ });
+
+ it('should return nothing if not match', async () => {
+ await serverDB.insert(topics).values([
+ { id: 'topic1', title: 'Hello world', userId },
+ { id: 'topic2', title: 'Goodbye', sessionId, userId },
+ ]);
+ await serverDB
+ .insert(messages)
+ .values([
+ { id: 'message1', role: 'assistant', content: 'abc there', topicId: 'topic1', userId },
+ ]);
+
+ const result = await topicModel.queryByKeyword('hello', sessionId);
+
+ expect(result).toHaveLength(0);
+ });
+
+ it('should return topics by title when message matches have null topicIds', async () => {
+ await serverDB.transaction(async (tx) => {
+ await tx
+ .insert(topics)
+ .values([{ id: 'title-match-topic', title: 'Search keyword here', sessionId, userId }]);
+ await tx.insert(messages).values([
+ {
+ id: 'orphan-message',
+ role: 'assistant',
+ content: 'Search keyword',
+ topicId: null,
+ userId,
+ },
+ ]);
+ });
+
+ const result = await topicModel.queryByKeyword('keyword', sessionId);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('title-match-topic');
+ });
+ });
+
+ describe('queryRecent', () => {
+ it('should return recent topics with agentId and sessionId', async () => {
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(agents).values([
+ {
+ id: 'agent1',
+ userId,
+ title: 'Agent 1',
+ avatar: 'avatar1.png',
+ backgroundColor: '#ff0000',
+ },
+ {
+ id: 'agent2',
+ userId,
+ title: 'Agent 2',
+ avatar: 'avatar2.png',
+ backgroundColor: '#00ff00',
+ },
+ ]);
+ await tx.insert(topics).values([
+ {
+ id: 'recent-topic-1',
+ title: 'Topic 1',
+ userId,
+ agentId: 'agent1',
+ updatedAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'recent-topic-2',
+ title: 'Topic 2',
+ userId,
+ agentId: 'agent2',
+ updatedAt: new Date('2023-02-01'),
+ },
+ {
+ id: 'recent-topic-3',
+ title: 'Topic 3',
+ userId,
+ agentId: 'agent1',
+ updatedAt: new Date('2023-03-01'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.queryRecent();
+
+ expect(result).toHaveLength(3);
+ expect(result[0].id).toBe('recent-topic-3');
+ expect(result[0].title).toBe('Topic 3');
+ expect(result[0].agentId).toBe('agent1');
+
+ expect(result[1].id).toBe('recent-topic-2');
+ expect(result[1].agentId).toBe('agent2');
+ });
+
+ it('should respect limit parameter', async () => {
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(agents).values([{ id: 'limit-agent', userId, title: 'Limit Agent' }]);
+ await tx.insert(topics).values([
+ { id: 'limit-topic-1', title: 'Topic 1', userId, agentId: 'limit-agent' },
+ { id: 'limit-topic-2', title: 'Topic 2', userId, agentId: 'limit-agent' },
+ { id: 'limit-topic-3', title: 'Topic 3', userId, agentId: 'limit-agent' },
+ ]);
+ });
+
+ const result = await topicModel.queryRecent(2);
+
+ expect(result).toHaveLength(2);
+ });
+
+ it('should return null agentId when topic has groupId but no agentId', async () => {
+ // Topics with groupId are included even without agentId
+ await serverDB.transaction(async (tx) => {
+ await tx
+ .insert(chatGroups)
+ .values([{ id: 'group-for-null-agent', userId, title: 'Test Group' }]);
+ await tx.insert(topics).values([
+ {
+ id: 'no-agent-topic',
+ title: 'Topic without agent',
+ userId,
+ agentId: null,
+ groupId: 'group-for-null-agent',
+ },
+ ]);
+ });
+
+ const result = await topicModel.queryRecent();
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('no-agent-topic');
+ expect(result[0].agentId).toBeNull();
+ expect(result[0].type).toBe('group');
+ });
+
+ it('should only return topics for current user', async () => {
+ const otherUserId = 'other-user-recent';
+
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(users).values([{ id: otherUserId }]);
+ // Create agents for both users (topics need valid agents)
+ await tx.insert(agents).values([
+ { id: 'user-agent-for-recent', userId, title: 'User Agent', virtual: false },
+ {
+ id: 'other-agent-for-recent',
+ userId: otherUserId,
+ title: 'Other Agent',
+ virtual: false,
+ },
+ ]);
+ await tx.insert(topics).values([
+ {
+ id: 'user-recent-topic',
+ title: 'User Topic',
+ userId,
+ agentId: 'user-agent-for-recent',
+ },
+ {
+ id: 'other-recent-topic',
+ title: 'Other Topic',
+ userId: otherUserId,
+ agentId: 'other-agent-for-recent',
+ },
+ ]);
+ });
+
+ const result = await topicModel.queryRecent();
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('user-recent-topic');
+ });
+
+ it('should use default limit of 12', async () => {
+ await serverDB.transaction(async (tx) => {
+ // Create a valid agent for topics
+ await tx
+ .insert(agents)
+ .values([{ id: 'agent-for-limit-test', userId, title: 'Test Agent', virtual: false }]);
+ const topicValues = Array.from({ length: 15 }, (_, i) => ({
+ id: `default-limit-topic-${i}`,
+ title: `Topic ${i}`,
+ userId,
+ agentId: 'agent-for-limit-test',
+ }));
+ await tx.insert(topics).values(topicValues);
+ });
+
+ const result = await topicModel.queryRecent();
+
+ expect(result).toHaveLength(12);
+ });
+
+ it('should correctly assign type based on groupId presence', async () => {
+ // Topics with groupId should be typed as 'group', topics without as 'agent'
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(chatGroups).values([{ id: 'group-for-type', userId, title: 'Type Group' }]);
+ await tx
+ .insert(agents)
+ .values([{ id: 'agent-for-type', userId, title: 'Type Agent', virtual: false }]);
+ await tx.insert(topics).values([
+ {
+ id: 'group-topic-type',
+ title: 'Group Topic',
+ userId,
+ groupId: 'group-for-type',
+ updatedAt: new Date('2023-01-02'),
+ },
+ {
+ id: 'agent-topic-type',
+ title: 'Agent Topic',
+ userId,
+ agentId: 'agent-for-type',
+ updatedAt: new Date('2023-01-01'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.queryRecent();
+
+ expect(result).toHaveLength(2);
+ const groupTopic = result.find((t) => t.id === 'group-topic-type');
+ const agentTopic = result.find((t) => t.id === 'agent-topic-type');
+ expect(groupTopic?.type).toBe('group');
+ expect(agentTopic?.type).toBe('agent');
+ });
+
+ it('should exclude topics from virtual agents', async () => {
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(agents).values([
+ { id: 'normal-agent', userId, title: 'Normal Agent', virtual: false },
+ { id: 'virtual-agent', userId, title: 'Virtual Agent', virtual: true },
+ ]);
+ await tx.insert(topics).values([
+ {
+ id: 'normal-agent-topic',
+ title: 'Normal Topic',
+ userId,
+ agentId: 'normal-agent',
+ updatedAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'virtual-agent-topic',
+ title: 'Virtual Topic',
+ userId,
+ agentId: 'virtual-agent',
+ updatedAt: new Date('2023-01-02'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.queryRecent();
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('normal-agent-topic');
+ expect(result[0].type).toBe('agent');
+ });
+
+ it('should include topics from inbox agent (slug=inbox)', async () => {
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(agents).values([
+ { id: 'inbox-agent', userId, title: 'LobeAI', slug: 'inbox', virtual: true },
+ { id: 'other-virtual', userId, title: 'Other Virtual', virtual: true },
+ ]);
+ await tx.insert(topics).values([
+ {
+ id: 'inbox-topic',
+ title: 'Inbox Topic',
+ userId,
+ agentId: 'inbox-agent',
+ updatedAt: new Date('2023-01-02'),
+ },
+ {
+ id: 'other-virtual-topic',
+ title: 'Other Virtual Topic',
+ userId,
+ agentId: 'other-virtual',
+ updatedAt: new Date('2023-01-01'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.queryRecent();
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('inbox-topic');
+ expect(result[0].type).toBe('agent');
+ });
+
+ it('should include topics with groupId and mark them as group type', async () => {
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(chatGroups).values([{ id: 'test-group', title: 'Test Group', userId }]);
+ await tx.insert(agents).values([{ id: 'group-member', userId, title: 'Group Member' }]);
+ await tx.insert(topics).values([
+ {
+ id: 'group-topic',
+ title: 'Group Topic',
+ userId,
+ groupId: 'test-group',
+ updatedAt: new Date('2023-01-01'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.queryRecent();
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('group-topic');
+ expect(result[0].groupId).toBe('test-group');
+ expect(result[0].type).toBe('group');
+ });
+
+ it('should return mixed results from agent, inbox, and group topics', async () => {
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(chatGroups).values([{ id: 'mixed-group', title: 'Mixed Group', userId }]);
+ await tx.insert(agents).values([
+ { id: 'normal-agent', userId, title: 'Normal Agent', virtual: false },
+ { id: 'inbox-agent', userId, title: 'LobeAI', slug: 'inbox', virtual: true },
+ { id: 'virtual-agent', userId, title: 'Virtual Agent', virtual: true },
+ ]);
+ await tx.insert(topics).values([
+ {
+ id: 'agent-topic',
+ title: 'Agent Topic',
+ userId,
+ agentId: 'normal-agent',
+ updatedAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'inbox-topic',
+ title: 'Inbox Topic',
+ userId,
+ agentId: 'inbox-agent',
+ updatedAt: new Date('2023-01-02'),
+ },
+ {
+ id: 'group-topic',
+ title: 'Group Topic',
+ userId,
+ groupId: 'mixed-group',
+ updatedAt: new Date('2023-01-03'),
+ },
+ {
+ id: 'virtual-topic',
+ title: 'Virtual Topic (should be excluded)',
+ userId,
+ agentId: 'virtual-agent',
+ updatedAt: new Date('2023-01-04'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.queryRecent();
+
+ // Should include: group-topic, inbox-topic, agent-topic
+ // Should exclude: virtual-topic
+ expect(result).toHaveLength(3);
+ expect(result.map((t) => t.id)).toEqual(['group-topic', 'inbox-topic', 'agent-topic']);
+ expect(result[0].type).toBe('group');
+ expect(result[1].type).toBe('agent');
+ expect(result[2].type).toBe('agent');
+ });
+ });
+
+ describe('listTopicsForMemoryExtractor', () => {
+ it('should paginate pending topics and skip extracted ones by default', async () => {
+ await serverDB.insert(topics).values([
+ {
+ createdAt: new Date('2024-01-01T00:00:00Z'),
+ id: 't1',
+ metadata: { userMemoryExtractStatus: 'completed' },
+ userId,
+ },
+ { createdAt: new Date('2024-01-02T00:00:00Z'), id: 't2', userId },
+ {
+ createdAt: new Date('2024-01-03T00:00:00Z'),
+ id: 't3',
+ metadata: { userMemoryExtractStatus: 'pending' },
+ userId,
+ },
+ { createdAt: new Date('2024-01-04T00:00:00Z'), id: 't4', userId: userId2 },
+ ] satisfies Array<typeof topics.$inferInsert>);
+
+ const page1 = await topicModel.listTopicsForMemoryExtractor({ limit: 1 });
+ expect(page1.map((t) => t.id)).toEqual(['t1']);
+
+ const page2 = await topicModel.listTopicsForMemoryExtractor({
+ cursor: { createdAt: page1[0].createdAt, id: page1[0].id },
+ limit: 5,
+ });
+ expect(page2.map((t) => t.id)).toEqual(['t2', 't3']);
+ });
+
+ it('should include extracted topics when ignoreExtracted is true', async () => {
+ await serverDB.insert(topics).values([
+ {
+ createdAt: new Date('2024-02-01T00:00:00Z'),
+ id: 'et1',
+ metadata: { userMemoryExtractStatus: 'completed' },
+ userId,
+ },
+ { createdAt: new Date('2024-02-02T00:00:00Z'), id: 'et2', userId },
+ ] satisfies Array<typeof topics.$inferInsert>);
+
+ const rows = await topicModel.listTopicsForMemoryExtractor({
+ ignoreExtracted: true,
+ limit: 10,
+ });
+
+ expect(rows.map((t) => t.id)).toEqual(['et1', 'et2']);
+ });
+
+ it('should paginate forward from the cursor, excluding items at or before it and including later ones', async () => {
+ const createdAt = new Date('2025-01-20T18:43:33.603Z');
+
+ await serverDB.insert(topics).values([
+ // Before cursor
+ { createdAt: new Date(createdAt.getTime() - 2), id: 'before-old', userId },
+ { createdAt, id: 'before-same-timestamp', userId },
+ // Cursor row
+ { createdAt, id: 'cursor-topic', userId },
+ // Same timestamp, after cursor by ID
+ { createdAt, id: 'cursor-topic-z', userId },
+ // Later timestamps
+ { createdAt: new Date(createdAt.getTime() + 1), id: 'after-1', userId },
+ { createdAt: new Date(createdAt.getTime() + 2), id: 'after-2', userId },
+ // Different user should be ignored
+ { createdAt: new Date(createdAt.getTime() + 3), id: 'other-user', userId: userId2 },
+ ] satisfies Array<typeof topics.$inferInsert>);
+
+ const rows = await topicModel.listTopicsForMemoryExtractor({
+ cursor: { createdAt, id: 'cursor-topic' },
+ limit: 10,
+ });
+
+ expect(rows.map((t) => t.id)).toEqual(['cursor-topic-z', 'after-1', 'after-2']);
+ });
+ });
+});
diff --git a/packages/database/src/models/__tests__/topics/topic.stats.test.ts b/packages/database/src/models/__tests__/topics/topic.stats.test.ts
new file mode 100644
index 00000000000..d99b70c1c5e
--- /dev/null
+++ b/packages/database/src/models/__tests__/topics/topic.stats.test.ts
@@ -0,0 +1,199 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { agents, agentsToSessions, messages, sessions, topics, users } from '../../../schemas';
+import { LobeChatDatabase } from '../../../type';
+import { TopicModel } from '../../topic';
+import { getTestDB } from '../_util';
+
+const userId = 'topic-stats-user';
+const userId2 = 'topic-stats-user-2';
+const sessionId = 'topic-stats-session';
+const serverDB: LobeChatDatabase = await getTestDB();
+const topicModel = new TopicModel(serverDB, userId);
+
+describe('TopicModel - Stats', () => {
+ beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(users).values([{ id: userId }, { id: userId2 }]);
+ await tx.insert(sessions).values({ id: sessionId, userId });
+ });
+ });
+
+ afterEach(async () => {
+ await serverDB.delete(users);
+ });
+
+ describe('count', () => {
+ it('should return total number of topics', async () => {
+ await serverDB.insert(topics).values([
+ { id: 'abc_topic1', sessionId, userId },
+ { id: 'abc_topic2', sessionId, userId },
+ ]);
+
+ const result = await topicModel.count();
+
+ expect(result).toBe(2);
+ });
+
+ describe('count with agentId', () => {
+ it('should count topics with direct agentId match', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(agents).values([
+ { id: 'count-agent-1', userId, title: 'Count Agent 1' },
+ { id: 'count-agent-2', userId, title: 'Count Agent 2' },
+ ]);
+ await trx.insert(topics).values([
+ { id: 'count-topic-1', userId, agentId: 'count-agent-1' },
+ { id: 'count-topic-2', userId, agentId: 'count-agent-1' },
+ { id: 'count-topic-3', userId, agentId: 'count-agent-2' },
+ ]);
+ });
+
+ const result = await topicModel.count({ agentId: 'count-agent-1' });
+ expect(result).toBe(2);
+ });
+
+ it('should count legacy topics via agentsToSessions lookup', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'count-legacy-session', userId }]);
+ await trx.insert(agents).values([{ id: 'count-legacy-agent', userId, title: 'Legacy Agent' }]);
+ await trx.insert(agentsToSessions).values([{ agentId: 'count-legacy-agent', sessionId: 'count-legacy-session', userId }]);
+ await trx.insert(topics).values([
+ { id: 'legacy-count-1', userId, sessionId: 'count-legacy-session', agentId: null },
+ { id: 'legacy-count-2', userId, sessionId: 'count-legacy-session', agentId: null },
+ ]);
+ });
+
+ const result = await topicModel.count({ agentId: 'count-legacy-agent' });
+ expect(result).toBe(2);
+ });
+
+ it('should count both new and legacy topics', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(sessions).values([{ id: 'count-mixed-session', userId }]);
+ await trx.insert(agents).values([{ id: 'count-mixed-agent', userId, title: 'Mixed Agent' }]);
+ await trx.insert(agentsToSessions).values([{ agentId: 'count-mixed-agent', sessionId: 'count-mixed-session', userId }]);
+ await trx.insert(topics).values([
+ { id: 'mixed-count-legacy', userId, sessionId: 'count-mixed-session', agentId: null },
+ { id: 'mixed-count-new', userId, agentId: 'count-mixed-agent', sessionId: null },
+ ]);
+ });
+
+ const result = await topicModel.count({ agentId: 'count-mixed-agent' });
+ expect(result).toBe(2);
+ });
+
+ it('should return 0 when agent has no topics', async () => {
+ await serverDB.insert(agents).values([{ id: 'empty-agent', userId, title: 'Empty Agent' }]);
+
+ const result = await topicModel.count({ agentId: 'empty-agent' });
+ expect(result).toBe(0);
+ });
+ });
+ });
+
+ describe('count with date filters', () => {
+ beforeEach(async () => {
+ await serverDB.insert(topics).values([
+ { id: 'topic1', userId, createdAt: new Date('2023-01-01') },
+ { id: 'topic2', userId, createdAt: new Date('2023-02-01') },
+ { id: 'topic3', userId, createdAt: new Date('2023-03-01') },
+ ]);
+ });
+
+ it('should count topics with start date filter', async () => {
+ const result = await topicModel.count({ startDate: '2023-02-01' });
+
+ expect(result).toBe(2);
+ });
+
+ it('should count topics with end date filter', async () => {
+ const result = await topicModel.count({ endDate: '2023-02-01' });
+
+ expect(result).toBe(2);
+ });
+
+ it('should count topics within date range', async () => {
+ const result = await topicModel.count({ range: ['2023-01-15', '2023-02-15'] });
+
+ expect(result).toBe(1);
+ });
+
+ it('should return 0 if no topics match date filters', async () => {
+ const result = await topicModel.count({ range: ['2024-01-01', '2024-12-31'] });
+
+ expect(result).toBe(0);
+ });
+
+ it('should handle invalid date filters gracefully', async () => {
+ const result = await topicModel.count({ startDate: 'invalid-date' });
+
+ expect(result).toBe(3);
+ });
+ });
+
+ describe('rank', () => {
+ it('should return ranked topics based on message count', async () => {
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(topics).values([
+ { id: 'topic1', title: 'Topic 1', sessionId, userId },
+ { id: 'topic2', title: 'Topic 2', sessionId, userId },
+ { id: 'topic3', title: 'Topic 3', sessionId, userId },
+ ]);
+
+ await tx.insert(messages).values([
+ { id: 'msg1', role: 'user', topicId: 'topic1', userId },
+ { id: 'msg2', role: 'assistant', topicId: 'topic1', userId },
+ { id: 'msg3', role: 'user', topicId: 'topic1', userId },
+ ]);
+
+ await tx.insert(messages).values([
+ { id: 'msg4', role: 'user', topicId: 'topic2', userId },
+ { id: 'msg5', role: 'assistant', topicId: 'topic2', userId },
+ ]);
+
+ await tx.insert(messages).values([{ id: 'msg6', role: 'user', topicId: 'topic3', userId }]);
+ });
+
+ const result = await topicModel.rank(2);
+
+ expect(result).toHaveLength(2);
+ expect(result[0]).toMatchObject({
+ id: 'topic1',
+ title: 'Topic 1',
+ count: 3,
+ sessionId,
+ });
+ expect(result[1]).toMatchObject({
+ id: 'topic2',
+ title: 'Topic 2',
+ count: 2,
+ sessionId,
+ });
+ });
+
+ it('should return empty array if no topics exist', async () => {
+ const result = await topicModel.rank();
+ expect(result).toHaveLength(0);
+ });
+
+ it('should respect the limit parameter', async () => {
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(topics).values([
+ { id: 'topic1', title: 'Topic 1', sessionId, userId },
+ { id: 'topic2', title: 'Topic 2', sessionId, userId },
+ ]);
+
+ await tx.insert(messages).values([
+ { id: 'msg1', role: 'user', topicId: 'topic1', userId },
+ { id: 'msg2', role: 'user', topicId: 'topic2', userId },
+ ]);
+ });
+
+ const result = await topicModel.rank(1);
+
+ expect(result).toHaveLength(1);
+ });
+ });
+});
diff --git a/packages/database/src/models/__tests__/topics/topic.update.test.ts b/packages/database/src/models/__tests__/topics/topic.update.test.ts
new file mode 100644
index 00000000000..cffd336ed0e
--- /dev/null
+++ b/packages/database/src/models/__tests__/topics/topic.update.test.ts
@@ -0,0 +1,55 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { sessions, topics, users } from '../../../schemas';
+import { LobeChatDatabase } from '../../../type';
+import { TopicModel } from '../../topic';
+import { getTestDB } from '../_util';
+
+const userId = 'topic-update-user';
+const sessionId = 'topic-update-session';
+const serverDB: LobeChatDatabase = await getTestDB();
+const topicModel = new TopicModel(serverDB, userId);
+
+describe('TopicModel - Update', () => {
+ beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(users).values([{ id: userId }]);
+ await tx.insert(sessions).values({ id: sessionId, userId });
+ });
+ });
+
+ afterEach(async () => {
+ await serverDB.delete(users);
+ });
+
+ describe('update', () => {
+ it('should update a topic', async () => {
+ const topicId = '123';
+ await serverDB.insert(topics).values({ userId, id: topicId, title: 'Test', favorite: true });
+
+ const item = await topicModel.update(topicId, {
+ title: 'Updated Test',
+ favorite: false,
+ });
+
+ expect(item).toHaveLength(1);
+ expect(item[0].title).toBe('Updated Test');
+ expect(item[0].favorite).toBeFalsy();
+ });
+
+ it('should not update a topic if user ID does not match', async () => {
+ await serverDB.insert(users).values([{ id: '456' }]);
+ const topicId = '123';
+ await serverDB
+ .insert(topics)
+ .values({ userId: '456', id: topicId, title: 'Test', favorite: true });
+
+ const item = await topicModel.update(topicId, {
+ title: 'Updated Test Session',
+ });
+
+ expect(item).toHaveLength(0);
+ });
+ });
+});