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.

♻️ refactor(topic): drop legacy session→agentId compatibility from topic queries (#15378)

Arvin Xu1e8b5959dae7
diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.ts
index 4bff53e3df8..bb12fc209de 100644
--- a/packages/database/src/models/__tests__/agent.test.ts
+++ b/packages/database/src/models/__tests__/agent.test.ts
@@ -15,6 +15,7 @@ import {
knowledgeBases,
sessionGroups,
sessions,
+ topics,
users,
} from '../../schemas';
import type { LobeChatDatabase } from '../../type';
@@ -2006,4 +2007,82 @@ describe('AgentModel', () => {
expect((result?.params as any)?.topP).toBe(0.5);
});
});
+
+ describe('rank', () => {
+ it('should rank agents by topic count, excluding agents with no topics', async () => {
+ await serverDB.insert(agents).values([
+ { avatar: 'av1', backgroundColor: 'bg1', id: 'ra1', title: 'Agent 1', userId },
+ { id: 'ra2', title: 'Agent 2', userId },
+ { id: 'ra3', title: 'Agent 3', userId }, // no topics → excluded
+ ]);
+ await serverDB.insert(topics).values([
+ { agentId: 'ra1', id: 'rt1', userId },
+ { agentId: 'ra1', id: 'rt2', userId },
+ { agentId: 'ra1', id: 'rt3', userId },
+ { agentId: 'ra2', id: 'rt4', userId },
+ { agentId: 'ra2', id: 'rt5', userId },
+ ]);
+
+ const result = await agentModel.rank();
+
+ expect(result).toHaveLength(2);
+ expect(result[0]).toMatchObject({
+ avatar: 'av1',
+ backgroundColor: 'bg1',
+ count: 3,
+ id: 'ra1',
+ title: 'Agent 1',
+ });
+ expect(result[1]).toMatchObject({ count: 2, id: 'ra2' });
+ });
+
+ it('should include the inbox agent but exclude other virtual agents', async () => {
+ await serverDB.insert(agents).values([
+ { id: 'inbox-agent', slug: 'inbox', title: 'Inbox', userId, virtual: true },
+ { id: 'virtual-agent', title: 'Virtual', userId, virtual: true },
+ { id: 'normal-agent', title: 'Normal', userId },
+ ]);
+ await serverDB.insert(topics).values([
+ { agentId: 'inbox-agent', id: 'it1', userId },
+ { agentId: 'virtual-agent', id: 'vt1', userId },
+ { agentId: 'normal-agent', id: 'nt1', userId },
+ ]);
+
+ const ids = (await agentModel.rank()).map((r) => r.id);
+
+ expect(ids).toContain('inbox-agent');
+ expect(ids).toContain('normal-agent');
+ expect(ids).not.toContain('virtual-agent');
+ });
+
+ it('should only rank the current user agents', async () => {
+ await serverDB.insert(agents).values([
+ { id: 'mine', title: 'Mine', userId },
+ { id: 'theirs', title: 'Theirs', userId: userId2 },
+ ]);
+ await serverDB.insert(topics).values([
+ { agentId: 'mine', id: 'mt1', userId },
+ { agentId: 'theirs', id: 'tt1', userId: userId2 },
+ ]);
+
+ const result = await agentModel.rank();
+
+ expect(result.map((r) => r.id)).toEqual(['mine']);
+ });
+
+ it('should respect the limit parameter', async () => {
+ await serverDB.insert(agents).values([
+ { id: 'la1', title: 'A1', userId },
+ { id: 'la2', title: 'A2', userId },
+ ]);
+ await serverDB.insert(topics).values([
+ { agentId: 'la1', id: 'lt1', userId },
+ { agentId: 'la2', id: 'lt2', userId },
+ ]);
+
+ const result = await agentModel.rank(1);
+
+ expect(result).toHaveLength(1);
+ });
+ });
});
diff --git a/packages/database/src/models/__tests__/session.test.ts b/packages/database/src/models/__tests__/session.test.ts
index da715c528b0..eade2e4afa6 100644
--- a/packages/database/src/models/__tests__/session.test.ts
+++ b/packages/database/src/models/__tests__/session.test.ts
@@ -1299,170 +1299,6 @@ describe('SessionModel', () => {
});
});
- describe('rank', () => {
- it('should return ranked sessions based on topic count', async () => {
- // Create test data
- await serverDB.transaction(async (trx) => {
- // Create sessions
- await trx.insert(sessions).values([
- { id: '1', userId },
- { id: '2', userId },
- { id: '3', userId },
- ]);
-
- // Create agents
- await trx.insert(agents).values([
- { id: 'a1', userId, title: 'Agent 1', avatar: 'avatar1', backgroundColor: 'bg1' },
- { id: 'a2', userId, title: 'Agent 2', avatar: 'avatar2', backgroundColor: 'bg2' },
- { id: 'a3', userId, title: 'Agent 3', avatar: 'avatar3', backgroundColor: 'bg3' },
- ]);
-
- // Link agents to sessions
- await trx.insert(agentsToSessions).values([
- { sessionId: '1', agentId: 'a1', userId },
- { sessionId: '2', agentId: 'a2', userId },
- { sessionId: '3', agentId: 'a3', userId },
- ]);
-
- // Create topics (different counts for ranking)
- await trx.insert(topics).values([
- { id: 't1', sessionId: '1', userId },
- { id: 't2', sessionId: '1', userId },
- { id: 't3', sessionId: '1', userId }, // Session 1 has 3 topics
- { id: 't4', sessionId: '2', userId },
- { id: 't5', sessionId: '2', userId }, // Session 2 has 2 topics
- { id: 't6', sessionId: '3', userId }, // Session 3 has 1 topic
- ]);
- });
-
- // Get ranked sessions with default limit
- const result = await sessionModel.rank();
-
- // Verify results
- expect(result).toHaveLength(3);
- // Should be ordered by topic count (descending)
- expect(result[0]).toMatchObject({
- id: '1',
- count: 3,
- title: 'Agent 1',
- avatar: 'avatar1',
- backgroundColor: 'bg1',
- });
- expect(result[1]).toMatchObject({
- id: '2',
- count: 2,
- title: 'Agent 2',
- avatar: 'avatar2',
- backgroundColor: 'bg2',
- });
- expect(result[2]).toMatchObject({
- id: '3',
- count: 1,
- title: 'Agent 3',
- avatar: 'avatar3',
- backgroundColor: 'bg3',
- });
- });
-
- it('should respect the limit parameter', async () => {
- // Create test data
- await serverDB.transaction(async (trx) => {
- // Create sessions and related data
- await trx.insert(sessions).values([
- { id: '1', userId },
- { id: '2', userId },
- { id: '3', userId },
- ]);
-
- await trx.insert(agents).values([
- { id: 'a1', userId, title: 'Agent 1' },
- { id: 'a2', userId, title: 'Agent 2' },
- { id: 'a3', userId, title: 'Agent 3' },
- ]);
-
- await trx.insert(agentsToSessions).values([
- { sessionId: '1', agentId: 'a1', userId },
- { sessionId: '2', agentId: 'a2', userId },
- { sessionId: '3', agentId: 'a3', userId },
- ]);
-
- await trx.insert(topics).values([
- { id: 't1', sessionId: '1', userId },
- { id: 't2', sessionId: '1', userId },
- { id: 't6', sessionId: '1', userId },
- { id: 't3', sessionId: '2', userId },
- { id: 't8', sessionId: '2', userId },
- { id: 't4', sessionId: '3', userId },
- ]);
- });
-
- // Get ranked sessions with limit of 2
- const result = await sessionModel.rank(2);
-
- // Verify results
- expect(result).toHaveLength(2);
- expect(result[0].id).toBe('1'); // Most topics (2)
- expect(result[1].id).toBe('2'); // Second most topics (1)
- });
-
- it('should include inbox topics in ranking when topics have no sessionId', async () => {
- await serverDB.transaction(async (trx) => {
- await trx.insert(sessions).values([{ id: '1', userId }]);
- await trx
- .insert(agents)
- .values([{ id: 'a1', userId, title: 'Agent 1', avatar: 'av1', backgroundColor: 'bg1' }]);
- await trx.insert(agentsToSessions).values([{ sessionId: '1', agentId: 'a1', userId }]);
-
- // Create topics: 1 for session, 3 for inbox (no sessionId)
- await trx.insert(topics).values([
- { id: 'inbox-t1', userId, sessionId: null },
- { id: 'inbox-t2', userId, sessionId: null },
- { id: 'inbox-t3', userId, sessionId: null },
- { id: 'session-t1', sessionId: '1', userId },
- ]);
- });
-
- const result = await sessionModel.rank();
-
- // Should include both inbox and session entries
- expect(result.length).toBeGreaterThanOrEqual(2);
- // Inbox should have 3 topics and be ranked first
- const inboxEntry = result.find((r) => r.id === 'inbox');
- expect(inboxEntry).toBeDefined();
- expect(inboxEntry?.count).toBe(3);
- // Session should have 1 topic
- const sessionEntry = result.find((r) => r.id === '1');
- expect(sessionEntry).toBeDefined();
- expect(sessionEntry?.count).toBe(1);
- });
-
- it('should handle sessions with no topics', async () => {
- // Create test data
- await serverDB.transaction(async (trx) => {
- await trx.insert(sessions).values([
- { id: '1', userId },
- { id: '2', userId },
- ]);
-
- await trx.insert(agents).values([
- { id: 'a1', userId, title: 'Agent 1' },
- { id: 'a2', userId, title: 'Agent 2' },
- ]);
-
- await trx.insert(agentsToSessions).values([
- { sessionId: '1', agentId: 'a1', userId },
- { sessionId: '2', agentId: 'a2', userId },
- ]);
-
- // No topics created
- });
-
- const result = await sessionModel.rank();
-
- expect(result).toHaveLength(0);
- });
- });
-
describe('hasMoreThanN', () => {
it('should return true when session count is more than N', async () => {
// Create test data
diff --git a/packages/database/src/models/__tests__/topics/topic.delete.test.ts b/packages/database/src/models/__tests__/topics/topic.delete.test.ts
index c190f7df471..c79c3334eac 100644
--- a/packages/database/src/models/__tests__/topics/topic.delete.test.ts
+++ b/packages/database/src/models/__tests__/topics/topic.delete.test.ts
@@ -160,7 +160,7 @@ describe('TopicModel - Delete', () => {
expect(remainingTopics[0].id).toBe('topic-agent-2');
});
- it('should delete legacy topics via sessionId lookup', async () => {
+ it('should not delete legacy session-only topics', async () => {
await serverDB.transaction(async (trx) => {
await trx.insert(sessions).values([
{ id: 'legacy-session-1', userId },
@@ -179,12 +179,12 @@ describe('TopicModel - Delete', () => {
await topicModel.batchDeleteByAgentId('legacy-agent');
+ // Topics carrying only a legacy sessionId are not matched by agentId, so none are deleted.
const remainingTopics = await serverDB.select().from(topics).where(eq(topics.userId, userId));
- expect(remainingTopics).toHaveLength(1);
- expect(remainingTopics[0].id).toBe('other-session-topic');
+ expect(remainingTopics).toHaveLength(3);
});
- it('should delete both new and legacy topics', async () => {
+ it('should delete only topics carrying the agentId, keeping session-only ones', async () => {
await serverDB.transaction(async (trx) => {
await trx.insert(sessions).values([{ id: 'mixed-del-session', userId }]);
await trx
@@ -202,8 +202,10 @@ describe('TopicModel - Delete', () => {
await topicModel.batchDeleteByAgentId('mixed-del-agent');
+ // Only `mixed-legacy` (sessionId only, no agentId) survives.
const remainingTopics = await serverDB.select().from(topics).where(eq(topics.userId, userId));
- expect(remainingTopics).toHaveLength(0);
+ expect(remainingTopics).toHaveLength(1);
+ expect(remainingTopics[0].id).toBe('mixed-legacy');
});
it('should not delete topics from other users', async () => {
diff --git a/packages/database/src/models/__tests__/topics/topic.query.test.ts b/packages/database/src/models/__tests__/topics/topic.query.test.ts
index 72657c51899..b0842624b61 100644
--- a/packages/database/src/models/__tests__/topics/topic.query.test.ts
+++ b/packages/database/src/models/__tests__/topics/topic.query.test.ts
@@ -443,12 +443,9 @@ describe('TopicModel - Query', () => {
});
describe('query with agentId filter', () => {
- it('should filter legacy topics by agentId through agentsToSessions lookup', async () => {
+ it('should not match legacy session-only topics by agentId', async () => {
await serverDB.transaction(async (trx) => {
- await trx.insert(sessions).values([
- { id: 'session-for-agent', userId },
- { id: 'session-other', userId },
- ]);
+ await trx.insert(sessions).values([{ id: 'session-for-agent', userId }]);
await trx.insert(agents).values([{ id: 'agent1', userId, title: 'Agent 1' }]);
await trx
.insert(agentsToSessions)
@@ -461,20 +458,14 @@ describe('TopicModel - Query', () => {
agentId: null,
updatedAt: new Date('2023-01-01'),
},
- {
- id: 'topic-other-session',
- userId,
- sessionId: 'session-other',
- agentId: null,
- updatedAt: new Date('2023-01-02'),
- },
]);
});
+ // Topics carrying only a legacy sessionId are no longer adopted by the
+ // agent query; only `topics.agentId` matches.
const result = await topicModel.query({ agentId: 'agent1' });
- expect(result.items).toHaveLength(1);
- expect(result.items[0].id).toBe('topic-agent-session');
+ expect(result.items).toHaveLength(0);
});
it('should filter new topics by agentId directly', async () => {
@@ -507,7 +498,7 @@ describe('TopicModel - Query', () => {
expect(result.items[0].id).toBe('new-topic-1');
});
- it('should return both legacy and new topics when querying by agentId', async () => {
+ it('should only return topics carrying the agentId, ignoring session-only ones', 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' }]);
@@ -541,12 +532,9 @@ describe('TopicModel - Query', () => {
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',
- ]);
+ // `legacy-topic` (sessionId only, no agentId) is excluded.
+ expect(result.items).toHaveLength(2);
+ expect(result.items.map((t) => t.id).sort()).toEqual(['both-topic', 'new-topic']);
});
it('should not return duplicate topics when both agentId and sessionId match', async () => {
@@ -756,21 +744,15 @@ describe('TopicModel - Query', () => {
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(sessions).values([{ 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',
+ agentId: 'priority-agent',
updatedAt: new Date('2023-01-01'),
},
{
@@ -1203,9 +1185,7 @@ describe('TopicModel - Query', () => {
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
+ it('should adopt only agentId and fully-orphan topics, not session-linked ones, when isInbox is true', async () => {
await serverDB.transaction(async (trx) => {
// Create inbox session and agent with relation
await trx.insert(sessions).values([{ id: 'inbox-session', slug: 'inbox', userId }]);
@@ -1247,10 +1227,10 @@ describe('TopicModel - Query', () => {
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);
+ // `legacy-session-topic` is no longer adopted via the agentsToSessions
+ // lookup; only the agentId match and the fully-orphan fallback remain.
+ expect(result.items).toHaveLength(2);
expect(result.items.map((t) => t.id).sort()).toEqual([
- 'legacy-session-topic',
'new-agentid-topic',
'orphan-legacy-topic',
]);
@@ -1488,7 +1468,7 @@ describe('TopicModel - Query', () => {
});
describe('queryRecent', () => {
- it('should return recent topics with agentId and sessionId', async () => {
+ it('should return recent topics with agentId', async () => {
await serverDB.transaction(async (tx) => {
await tx.insert(agents).values([
{
diff --git a/packages/database/src/models/__tests__/topics/topic.stats.test.ts b/packages/database/src/models/__tests__/topics/topic.stats.test.ts
index 0b9514670f1..a8bb2b70833 100644
--- a/packages/database/src/models/__tests__/topics/topic.stats.test.ts
+++ b/packages/database/src/models/__tests__/topics/topic.stats.test.ts
@@ -54,7 +54,7 @@ describe('TopicModel - Stats', () => {
expect(result).toBe(2);
});
- it('should count legacy topics via agentsToSessions lookup', async () => {
+ it('should not count legacy session-only topics by agentId', async () => {
await serverDB.transaction(async (trx) => {
await trx.insert(sessions).values([{ id: 'count-legacy-session', userId }]);
await trx
@@ -69,11 +69,12 @@ describe('TopicModel - Stats', () => {
]);
});
+ // Topics carrying only a legacy sessionId are no longer counted for the agent.
const result = await topicModel.count({ agentId: 'count-legacy-agent' });
- expect(result).toBe(2);
+ expect(result).toBe(0);
});
- it('should count both new and legacy topics', async () => {
+ it('should count only topics carrying the agentId, ignoring session-only ones', async () => {
await serverDB.transaction(async (trx) => {
await trx.insert(sessions).values([{ id: 'count-mixed-session', userId }]);
await trx
@@ -89,7 +90,7 @@ describe('TopicModel - Stats', () => {
});
const result = await topicModel.count({ agentId: 'count-mixed-agent' });
- expect(result).toBe(2);
+ expect(result).toBe(1);
});
it('should return 0 when agent has no topics', async () => {
@@ -144,10 +145,11 @@ describe('TopicModel - Stats', () => {
describe('rank', () => {
it('should return ranked topics based on message count', async () => {
await serverDB.transaction(async (tx) => {
+ await tx.insert(agents).values([{ id: 'rank-agent', userId, title: 'Rank Agent' }]);
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 },
+ { id: 'topic1', title: 'Topic 1', agentId: 'rank-agent', userId },
+ { id: 'topic2', title: 'Topic 2', agentId: 'rank-agent', userId },
+ { id: 'topic3', title: 'Topic 3', agentId: 'rank-agent', userId },
]);
await tx.insert(messages).values([
@@ -171,13 +173,13 @@ describe('TopicModel - Stats', () => {
id: 'topic1',
title: 'Topic 1',
count: 3,
- sessionId,
+ agentId: 'rank-agent',
});
expect(result[1]).toMatchObject({
id: 'topic2',
title: 'Topic 2',
count: 2,
- sessionId,
+ agentId: 'rank-agent',
});
});
diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.ts
index ef495833867..41b4cabb322 100644
--- a/packages/database/src/models/agent.ts
+++ b/packages/database/src/models/agent.ts
@@ -1,6 +1,7 @@
import { getAgentPersistConfig } from '@lobechat/builtin-agents';
import { DEFAULT_INBOX_AVATAR, INBOX_SESSION_ID } from '@lobechat/const';
-import { and, desc, eq, ilike, inArray, isNull, or, sql } from 'drizzle-orm';
+import type { AgentRankItem } from '@lobechat/types';
+import { and, count, desc, eq, gt, ilike, inArray, isNull, ne, or, sql } from 'drizzle-orm';
import type { PartialDeep } from 'type-fest';
import { merge } from '@/utils/merge';
@@ -15,6 +16,7 @@ import {
files,
knowledgeBases,
sessions,
+ topics,
} from '../schemas';
import type { LobeChatDatabase } from '../type';
@@ -27,6 +29,34 @@ export class AgentModel {
this.db = db;
}
+ /**
+ * Rank the user's agents by topic count (agent usage ranking). Counts topics
+ * directly via `topics.agentId`, so it is agent-native — no sessionId. Mirrors
+ * the recents filter: real agents plus the inbox, excluding other virtual agents.
+ */
+ rank = async (limit: number = 10): Promise<AgentRankItem[]> => {
+ return this.db
+ .select({
+ avatar: agents.avatar,
+ backgroundColor: agents.backgroundColor,
+ count: count(topics.id).as('count'),
+ id: agents.id,
+ title: agents.title,
+ })
+ .from(agents)
+ .leftJoin(topics, eq(topics.agentId, agents.id))
+ .where(
+ and(
+ eq(agents.userId, this.userId),
+ or(eq(agents.slug, INBOX_SESSION_ID), ne(agents.virtual, true)),
+ ),
+ )
+ .groupBy(agents.id)
+ .having(({ count }) => gt(count, 0))
+ .orderBy(desc(sql`count`))
+ .limit(limit);
+ };
+
getAgentConfigById = async (id: string) => {
const agent = await this.db.query.agents.findFirst({
where: and(eq(agents.id, id), eq(agents.userId, this.userId)),
diff --git a/packages/database/src/models/session.ts b/packages/database/src/models/session.ts
index f263c182a35..060bba0ad72 100644
--- a/packages/database/src/models/session.ts
+++ b/packages/database/src/models/session.ts
@@ -1,18 +1,17 @@
-import { DEFAULT_AGENT_CONFIG, DEFAULT_INBOX_AVATAR, INBOX_SESSION_ID } from '@lobechat/const';
+import { DEFAULT_AGENT_CONFIG, INBOX_SESSION_ID } from '@lobechat/const';
import type {
ChatSessionList,
LobeAgentConfig,
LobeAgentSession,
LobeGroupSession,
- SessionRankItem,
} from '@lobechat/types';
-import { and, asc, count, desc, eq, gt, inArray, isNull, not, or, sql } from 'drizzle-orm';
+import { and, asc, count, desc, eq, inArray, not, or, sql } from 'drizzle-orm';
import type { PartialDeep } from 'type-fest';
import { merge } from '@/utils/merge';
import type { AgentItem, NewAgent, NewSession, SessionItem } from '../schemas';
-import { agents, agentsToSessions, sessionGroups, sessions, topics } from '../schemas';
+import { agents, agentsToSessions, sessionGroups, sessions } from '../schemas';
import type { LobeChatDatabase } from '../type';
import { sanitizeBm25Query } from '../utils/bm25';
import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';
@@ -153,53 +152,6 @@ export class SessionModel {
return result[0].count;
};
- _rank = async (limit: number = 10): Promise<SessionRankItem[]> => {
- return this.db
- .select({
- avatar: agents.avatar,
- backgroundColor: agents.backgroundColor,
- count: count(topics.id).as('count'),
- id: sessions.id,
- title: agents.title,
- })
- .from(sessions)
- .where(and(eq(sessions.userId, this.userId)))
- .leftJoin(topics, eq(sessions.id, topics.sessionId))
- .leftJoin(agentsToSessions, eq(sessions.id, agentsToSessions.sessionId))
- .leftJoin(agents, eq(agentsToSessions.agentId, agents.id))
- .groupBy(sessions.id, agentsToSessions.agentId, agents.id)
- .having(({ count }) => gt(count, 0))
- .orderBy(desc(sql`count`))
- .limit(limit);
- };
-
- // TODO: In the future, once Inbox ID is stored in the database, we can directly use the _rank method
- rank = async (limit: number = 10): Promise<SessionRankItem[]> => {
- const inboxResult = await this.db
- .select({
- count: count(topics.id).as('count'),
- })
- .from(topics)
- .where(and(eq(topics.userId, this.userId), isNull(topics.sessionId)));
-
- const inboxCount = inboxResult[0].count;
-
- if (!inboxCount || inboxCount === 0) return this._rank(limit);
-
- const result = await this._rank(limit ? limit - 1 : undefined);
-
- return [
- {
- avatar: DEFAULT_INBOX_AVATAR,
- backgroundColor: null,
- count: inboxCount,
- id: INBOX_SESSION_ID,
- title: 'inbox.title',
- },
- ...result,
- ].sort((a, b) => b.count - a.count);
- };
-
hasMoreThanN = async (n: number): Promise<boolean> => {
const result = await this.db
.select({ id: sessions.id })
diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.ts
index a1433ed1712..8795118f304 100644
--- a/packages/database/src/models/topic.ts
+++ b/packages/database/src/models/topic.ts
@@ -30,7 +30,7 @@ import {
} from 'drizzle-orm';
import type { TopicItem } from '../schemas';
-import { agents, agentsToSessions, messagePlugins, messages, topics } from '../schemas';
+import { agents, messagePlugins, messages, topics } from '../schemas';
import type { LobeChatDatabase } from '../type';
import { sanitizeBm25Query } from '../utils/bm25';
import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';
@@ -284,52 +284,17 @@ export class TopicModel {
return { items, total: totalResult[0].count };
}
- // If agentId is provided, query topics that match either:
- // 1. topics.agentId = agentId (new data with agentId stored directly)
- // 2. topics.sessionId = associated sessionId (legacy data via agentsToSessions lookup)
- // 3. For inbox: sessionId IS NULL AND groupId IS NULL AND agentId IS NULL (legacy inbox data)
+ // If agentId is provided, match topics by `topics.agentId` directly. The
+ // inbox agent additionally adopts very old orphan rows where every owner
+ // column (session / group / agent) is null.
if (agentId) {
- // Get the associated sessionId for backward compatibility with legacy data
- const agentSession = await runTimedStage(
- timing,
- 'db.topic.query.agentSession.select',
- () =>
- this.db
- .select({ sessionId: agentsToSessions.sessionId })
- .from(agentsToSessions)
- .where(
- and(eq(agentsToSessions.agentId, agentId), eq(agentsToSessions.userId, this.userId)),
- )
- .limit(1),
- { hasAgentId: true },
- );
-
- const associatedSessionId = agentSession[0]?.sessionId;
-
- // Build condition to match both new (agentId) and legacy (sessionId) data
- let agentCondition;
- if (isInbox) {
- // For inbox agent: query topics that match:
- // 1. topics.agentId = agentId (new data)
- // 2. topics.sessionId = associatedSessionId (legacy data with session relation)
- // 3. sessionId IS NULL AND groupId IS NULL AND agentId IS NULL (very old legacy inbox data)
- const conditions = [
- eq(topics.agentId, agentId),
- and(isNull(topics.sessionId), isNull(topics.groupId), isNull(topics.agentId)),
- ];
- // Also include topics linked via legacy session relation
- if (associatedSessionId) {
- conditions.push(eq(topics.sessionId, associatedSessionId));
- }
- agentCondition = or(...conditions);
- } else if (associatedSessionId) {
- agentCondition = or(eq(topics.agentId, agentId), eq(topics.sessionId, associatedSessionId));
- } else {
- agentCondition = eq(topics.agentId, agentId);
- }
+ const agentCondition = isInbox
+ ? or(
+ eq(topics.agentId, agentId),
+ and(isNull(topics.sessionId), isNull(topics.groupId), isNull(topics.agentId)),
+ )
+ : eq(topics.agentId, agentId);
- // Fetch items and total count in parallel
- // Include sessionId and agentId for migration detection
const agentWhere = and(
eq(topics.userId, this.userId),
agentCondition,
@@ -363,7 +328,7 @@ export class TopicModel {
.orderBy(...orderBy)
.limit(pageSize)
.offset(offset),
- { current, hasAssociatedSessionId: !!associatedSessionId, isInbox: !!isInbox, pageSize },
+ { current, isInbox: !!isInbox, pageSize },
),
runTimedStage(
timing,
@@ -373,7 +338,7 @@ export class TopicModel {
.select({ count: count(topics.id) })
.from(topics)
.where(agentWhere),
- { hasAssociatedSessionId: !!associatedSessionId, isInbox: !!isInbox },
+ { isInbox: !!isInbox },
),
]);
@@ -530,27 +495,9 @@ export class TopicModel {
startDate?: string;
}): Promise<number> => {
// Build agent-specific condition if agentId is provided
- let agentCondition: SQL | undefined;
- if (params?.agentId) {
- // Get the associated sessionId for backward compatibility with legacy data
- const agentSession = await this.db
- .select({ sessionId: agentsToSessions.sessionId })
- .from(agentsToSessions)
- .where(
- and(
- eq(agentsToSessions.agentId, params.agentId),
- eq(agentsToSessions.userId, this.userId),
- ),
- )
- .limit(1);
-
- const associatedSessionId = agentSession[0]?.sessionId;
-
- // Build condition to match both new (agentId) and legacy (sessionId) data
- agentCondition = associatedSessionId
- ? or(eq(topics.agentId, params.agentId), eq(topics.sessionId, associatedSessionId))
- : eq(topics.agentId, params.agentId);
- }
+ const agentCondition: SQL | undefined = params?.agentId
+ ? eq(topics.agentId, params.agentId)
+ : undefined;
const result = await this.db
.select({
@@ -580,9 +527,9 @@ export class TopicModel {
rank = async (limit: number = 10): Promise<TopicRankItem[]> => {
return this.db
.select({
+ agentId: topics.agentId,
count: count(messages.id).as('count'),
id: topics.id,
- sessionId: topics.sessionId,
title: topics.title,
})
.from(topics)
@@ -872,27 +819,12 @@ export class TopicModel {
};
/**
- * Deletes multiple topics based on the agentId.
- * This will delete topics that have either:
- * 1. Direct agentId match (new data)
- * 2. SessionId match via agentsToSessions lookup (legacy data)
+ * Deletes all topics matching the given agentId (`topics.agentId`).
*/
batchDeleteByAgentId = async (agentId: string) => {
- // Get the associated sessionId for backward compatibility with legacy data
- const agentSession = await this.db
- .select({ sessionId: agentsToSessions.sessionId })
- .from(agentsToSessions)
- .where(and(eq(agentsToSessions.agentId, agentId), eq(agentsToSessions.userId, this.userId)))
- .limit(1);
-
- const associatedSessionId = agentSession[0]?.sessionId;
-
- // Build condition to match both new (agentId) and legacy (sessionId) data
- const agentCondition = associatedSessionId
- ? or(eq(topics.agentId, agentId), eq(topics.sessionId, associatedSessionId))
- : eq(topics.agentId, agentId);
-
- return this.db.delete(topics).where(and(eq(topics.userId, this.userId), agentCondition));
+ return this.db
+ .delete(topics)
+ .where(and(eq(topics.userId, this.userId), eq(topics.agentId, agentId)));
};
/**
diff --git a/packages/types/src/agent/item.ts b/packages/types/src/agent/item.ts
index 60de0376303..a28de497541 100644
--- a/packages/types/src/agent/item.ts
+++ b/packages/types/src/agent/item.ts
@@ -8,6 +8,18 @@ import type { LobeAgentAgencyConfig } from './agencyConfig';
import { AgentChatConfigSchema, type LobeAgentChatConfig } from './chatConfig';
import type { LobeAgentTTSConfig } from './tts';
+/**
+ * A single entry in the agent usage ranking (by topic count). `id` is the
+ * agentId — the ranking is agent-native (no sessionId).
+ */
+export interface AgentRankItem {
+ avatar: string | null;
+ backgroundColor: string | null;
+ count: number;
+ id: string;
+ title: string | null;
+}
+
export interface LobeAgentConfig {
/**
* Agency configuration: device binding, heterogeneous agent provider, etc.
diff --git a/packages/types/src/session/index.ts b/packages/types/src/session/index.ts
index e7e48a5dfef..673a51be98b 100644
--- a/packages/types/src/session/index.ts
+++ b/packages/types/src/session/index.ts
@@ -15,11 +15,3 @@ export interface UpdateSessionParams {
pinned?: boolean;
updatedAt: Date;
}
-
-export interface SessionRankItem {
- avatar: string | null;
- backgroundColor: string | null;
- count: number;
- id: string;
- title: string | null;
-}
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index f9b36978977..bf35cce2c3e 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -222,9 +222,9 @@ export interface ChatTopic extends Omit<BaseDataModel, 'meta'> {
export type ChatTopicMap = Record<string, ChatTopic>;
export interface TopicRankItem {
+ agentId: string | null;
count: number;
id: string;
- sessionId: string | null;
title: string | null;
}
diff --git a/src/routes/(main)/settings/stats/features/rankings/AssistantsRank.tsx b/src/routes/(main)/settings/stats/features/rankings/AssistantsRank.tsx
index 1a060e2c016..67f04892ac0 100644
--- a/src/routes/(main)/settings/stats/features/rankings/AssistantsRank.tsx
+++ b/src/routes/(main)/settings/stats/features/rankings/AssistantsRank.tsx
@@ -7,11 +7,13 @@ import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { DEFAULT_AVATAR } from '@/const/meta';
-import { INBOX_SESSION_ID } from '@/const/session';
+import { SESSION_CHAT_URL } from '@/const/url';
import Link from '@/libs/router/Link';
import { useClientDataSWR } from '@/libs/swr';
-import { sessionService } from '@/services/session';
-import { type SessionRankItem } from '@/types/session';
+import { agentService } from '@/services/agent';
+import { useAgentStore } from '@/store/agent';
+import { builtinAgentSelectors } from '@/store/agent/selectors';
+import { type AgentRankItem } from '@/types/agent';
import StatsFormGroup from '../components/StatsFormGroup';
@@ -19,20 +21,19 @@ export const AssistantsRank = memo<{ mobile?: boolean }>(({ mobile }) => {
const [open, setOpen] = useState(false);
const { t } = useTranslation(['auth', 'chat']);
const navigate = useNavigate();
- const { data, isLoading } = useClientDataSWR('rank-sessions', async () =>
- sessionService.rankSessions(),
+ const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
+ const { data, isLoading } = useClientDataSWR('rank-agents', async () =>
+ agentService.rankAgents(),
);
const showExtra = Boolean(data && data?.length > 5);
- const mapData = (item: SessionRankItem) => {
- const link = qs.stringifyUrl({
- query: {
- session: item.id,
- ...(mobile ? { showMobileWorkspace: true } : {}),
- },
- url: '/agent',
- });
+ const mapData = (item: AgentRankItem) => {
+ const isInbox = item.id === inboxAgentId;
+ const path = SESSION_CHAT_URL(item.id, mobile);
+ const link = mobile
+ ? qs.stringifyUrl({ query: { showMobileWorkspace: true }, url: path })
+ : path;
return {
icon: (
@@ -46,11 +47,9 @@ export const AssistantsRank = memo<{ mobile?: boolean }>(({ mobile }) => {
link,
name: (
<Link href={link} style={{ color: 'inherit' }}>
- {item.title
- ? item.id === INBOX_SESSION_ID
- ? t('inbox.title', { ns: 'chat' })
- : item.title
- : t('defaultAgent', { ns: 'chat' })}
+ {isInbox
+ ? t('inbox.title', { ns: 'chat' })
+ : item.title || t('defaultAgent', { ns: 'chat' })}
</Link>
),
value: item.count,
diff --git a/src/routes/(main)/settings/stats/features/rankings/TopicsRank.tsx b/src/routes/(main)/settings/stats/features/rankings/TopicsRank.tsx
index 32ec55c2a4e..c23edd84191 100644
--- a/src/routes/(main)/settings/stats/features/rankings/TopicsRank.tsx
+++ b/src/routes/(main)/settings/stats/features/rankings/TopicsRank.tsx
@@ -7,10 +7,12 @@ import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
-import { INBOX_SESSION_ID } from '@/const/session';
+import { SESSION_CHAT_TOPIC_URL } from '@/const/url';
import Link from '@/libs/router/Link';
import { useClientDataSWR } from '@/libs/swr';
import { topicService } from '@/services/topic';
+import { useAgentStore } from '@/store/agent';
+import { builtinAgentSelectors } from '@/store/agent/selectors';
import { type TopicRankItem } from '@/types/topic';
import StatsFormGroup from '../components/StatsFormGroup';
@@ -19,6 +21,7 @@ export const TopicsRank = memo<{ mobile?: boolean }>(({ mobile }) => {
const [open, setOpen] = useState(false);
const { t } = useTranslation('auth');
const navigate = useNavigate();
+ const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
const { data, isLoading } = useClientDataSWR('rank-topics', async () =>
topicService.rankTopics(),
);
@@ -26,14 +29,14 @@ export const TopicsRank = memo<{ mobile?: boolean }>(({ mobile }) => {
const showExtra = Boolean(data && data?.length > 5);
const mapData = (item: TopicRankItem) => {
- const link = qs.stringifyUrl({
- query: {
- session: item.sessionId || INBOX_SESSION_ID,
- topic: item.id,
- ...(mobile ? { showMobileWorkspace: true } : {}),
- },
- url: '/agent',
- });
+ // Topics without an agentId fall back to the inbox agent, mirroring the
+ // previous `sessionId || INBOX` behavior in the agent-centric model.
+ const agentId = item.agentId ?? inboxAgentId;
+ const path = agentId ? SESSION_CHAT_TOPIC_URL(agentId, item.id) : '/';
+ const link =
+ mobile && agentId
+ ? qs.stringifyUrl({ query: { showMobileWorkspace: true }, url: path })
+ : path;
return {
icon: <Icon color={cssVar.colorTextDescription} icon={MessageSquareIcon} size={16} />,
link,
diff --git a/src/server/routers/lambda/__tests__/integration/topic.integration.test.ts b/src/server/routers/lambda/__tests__/integration/topic.integration.test.ts
index 9e2a1137ae9..af9e6ca69c3 100644
--- a/src/server/routers/lambda/__tests__/integration/topic.integration.test.ts
+++ b/src/server/routers/lambda/__tests__/integration/topic.integration.test.ts
@@ -191,16 +191,11 @@ describe('Topic Router Integration Tests', () => {
it('should get topics by agentId', async () => {
const caller = topicRouter.createCaller(createTestContext(userId));
- // Create test topic
- await caller.createTopic({
- title: 'Topic 1',
- sessionId: testSessionId,
- });
-
- await caller.createTopic({
- title: 'Topic 2',
- sessionId: testSessionId,
- });
+ // Topics are agent-native: stored with agentId directly
+ await serverDB.insert(topics).values([
+ { title: 'Topic 1', agentId: testAgentId, userId },
+ { title: 'Topic 2', agentId: testAgentId, userId },
+ ]);
// Query using agentId
const result = await caller.getTopics({
@@ -217,10 +212,12 @@ describe('Topic Router Integration Tests', () => {
it('should resolve sessionId to agentId when only sessionId provided', async () => {
const caller = topicRouter.createCaller(createTestContext(userId));
- // Create test topic
- await caller.createTopic({
+ // Agent-native topic; queried via sessionId, which the procedure
+ // reverse-resolves to agentId before matching `topics.agentId`.
+ await serverDB.insert(topics).values({
title: 'Topic for reverse lookup',
- sessionId: testSessionId,
+ agentId: testAgentId,
+ userId,
});
// Query using sessionId (requires reverse lookup of agentId)
@@ -239,13 +236,13 @@ describe('Topic Router Integration Tests', () => {
await serverDB.insert(topics).values([
{
title: 'Cron Topic',
- sessionId: testSessionId,
+ agentId: testAgentId,
trigger: 'cron',
userId,
},
{
title: 'Eval Topic',
- sessionId: testSessionId,
+ agentId: testAgentId,
trigger: 'eval',
userId,
},
@@ -315,18 +312,14 @@ describe('Topic Router Integration Tests', () => {
});
describe('batchDeleteByAgentId', () => {
- it('should batch delete topics by agentId (new data)', async () => {
+ it('should batch delete topics by agentId', async () => {
const caller = topicRouter.createCaller(createTestContext(userId));
- // Create topics with agentId directly (new data structure)
- const topicId1 = await caller.createTopic({
- title: 'Agent Topic 1',
- agentId: testAgentId,
- });
- const topicId2 = await caller.createTopic({
- title: 'Agent Topic 2',
- agentId: testAgentId,
- });
+ // Agent-native topics stored with agentId directly
+ await serverDB.insert(topics).values([
+ { title: 'Agent Topic 1', agentId: testAgentId, userId },
+ { title: 'Agent Topic 2', agentId: testAgentId, userId },
+ ]);
// Batch delete by agentId
await caller.batchDeleteByAgentId({
@@ -337,55 +330,6 @@ describe('Topic Router Integration Tests', () => {
expect(remainingTopics).toHaveLength(0);
});
-
- it('should batch delete topics by agentId (legacy sessionId data)', async () => {
- const caller = topicRouter.createCaller(createTestContext(userId));
-
- // Create topics with sessionId (legacy data structure)
- await caller.createTopic({
- title: 'Legacy Topic 1',
- sessionId: testSessionId,
- });
- await caller.createTopic({
- title: 'Legacy Topic 2',
- sessionId: testSessionId,
- });
-
- // Batch delete by agentId should also delete legacy topics via sessionId mapping
- await caller.batchDeleteByAgentId({
- agentId: testAgentId,
- });
-
- const remainingTopics = await serverDB
- .select()
- .from(topics)
- .where(eq(topics.sessionId, testSessionId));
-
- expect(remainingTopics).toHaveLength(0);
- });
-
- it('should batch delete topics by agentId (mixed data)', async () => {
- const caller = topicRouter.createCaller(createTestContext(userId));
-
- // Create both new (agentId) and legacy (sessionId) topics
- await caller.createTopic({
- title: 'New Agent Topic',
- agentId: testAgentId,
- });
- await caller.createTopic({
- title: 'Legacy Session Topic',
- sessionId: testSessionId,
- });
-
- // Batch delete by agentId should delete both
- await caller.batchDeleteByAgentId({
- agentId: testAgentId,
- });
-
- const remainingTopics = await serverDB.select().from(topics).where(eq(topics.userId, userId));
-
- expect(remainingTopics).toHaveLength(0);
- });
});
// BM25 search requires pg_search extension (ParadeDB), not available in integration test DB
@@ -466,70 +410,36 @@ describe('Topic Router Integration Tests', () => {
});
describe('runtime migration - agentId backfill', () => {
- it('should trigger migration for legacy topics (with sessionId but no agentId)', async () => {
+ it('should backfill agentId for legacy session-only topics on query', async () => {
const caller = topicRouter.createCaller(createTestContext(userId));
- // Directly insert legacy topic with sessionId but no agentId (simulating old data)
+ // Legacy topic: sessionId set, agentId still null (pre-migration data)
const [legacyTopic] = await serverDB
.insert(topics)
- .values({
- title: 'Legacy Topic',
- sessionId: testSessionId,
- agentId: null, // Legacy data has no agentId
- userId,
- })
+ .values({ title: 'Legacy Topic', sessionId: testSessionId, agentId: null, userId })
.returning();
- // Verify the topic has no agentId initially
- const [beforeMigration] = await serverDB
- .select()
- .from(topics)
- .where(eq(topics.id, legacyTopic.id));
- expect(beforeMigration.agentId).toBeNull();
-
- // Query topics using agentId - this should trigger migration
- const result = await caller.getTopics({
- agentId: testAgentId,
- });
-
- // Should return the legacy topic
- expect(result.items).toHaveLength(1);
- expect(result.items[0].id).toBe(legacyTopic.id);
+ // Querying the agent triggers the background backfill via after().
+ await caller.getTopics({ agentId: testAgentId });
- // Wait a bit for the after() callback to execute
+ // Wait for the after() callback to run
await new Promise((resolve) => setTimeout(resolve, 100));
- // Verify the agentId was backfilled
- const [afterMigration] = await serverDB
- .select()
- .from(topics)
- .where(eq(topics.id, legacyTopic.id));
- expect(afterMigration.agentId).toBe(testAgentId);
+ const [migrated] = await serverDB.select().from(topics).where(eq(topics.id, legacyTopic.id));
+ expect(migrated.agentId).toBe(testAgentId);
});
- it('should not migrate topics that already have agentId', async () => {
+ it('should not change topics that already have agentId', async () => {
const caller = topicRouter.createCaller(createTestContext(userId));
- // Create topic with agentId already set
const [topicWithAgentId] = await serverDB
.insert(topics)
- .values({
- title: 'New Topic',
- sessionId: testSessionId,
- agentId: testAgentId, // Already has agentId
- userId,
- })
+ .values({ title: 'New Topic', sessionId: testSessionId, agentId: testAgentId, userId })
.returning();
- // Query topics using agentId
- await caller.getTopics({
- agentId: testAgentId,
- });
-
- // Wait for potential migration
+ await caller.getTopics({ agentId: testAgentId });
await new Promise((resolve) => setTimeout(resolve, 100));
- // Verify the agentId is unchanged
const [afterQuery] = await serverDB
.select()
.from(topics)
@@ -537,80 +447,39 @@ describe('Topic Router Integration Tests', () => {
expect(afterQuery.agentId).toBe(testAgentId);
});
- it('should migrate multiple legacy topics in batch', async () => {
- const caller = topicRouter.createCaller(createTestContext(userId));
-
- // Insert multiple legacy topics
- const legacyTopics = await serverDB
- .insert(topics)
- .values([
- { title: 'Legacy 1', sessionId: testSessionId, agentId: null, userId },
- { title: 'Legacy 2', sessionId: testSessionId, agentId: null, userId },
- { title: 'Legacy 3', sessionId: testSessionId, agentId: null, userId },
- ])
- .returning();
-
- // Query topics using agentId
- const result = await caller.getTopics({
- agentId: testAgentId,
- });
-
- expect(result.items).toHaveLength(3);
-
- // Wait for migration
- await new Promise((resolve) => setTimeout(resolve, 100));
-
- // Verify all topics were migrated
- for (const topic of legacyTopics) {
- const [migrated] = await serverDB.select().from(topics).where(eq(topics.id, topic.id));
- expect(migrated.agentId).toBe(testAgentId);
- }
- });
-
- it('should only migrate topics that match the query', async () => {
- // Create another agent and session
+ it('should only backfill topics under the queried agent session', async () => {
const { agents, agentsToSessions } = await import('@/database/schemas');
const [otherAgent] = await serverDB
.insert(agents)
.values({ userId, title: 'Other Agent' })
.returning();
-
const [otherSession] = await serverDB
.insert(sessions)
.values({ userId, type: 'agent' })
.returning();
-
await serverDB.insert(agentsToSessions).values({
agentId: otherAgent.id,
sessionId: otherSession.id,
userId,
});
- // Insert legacy topics for different sessions
const [topic1] = await serverDB
.insert(topics)
.values({ title: 'Topic 1', sessionId: testSessionId, agentId: null, userId })
.returning();
-
const [topic2] = await serverDB
.insert(topics)
.values({ title: 'Topic 2', sessionId: otherSession.id, agentId: null, userId })
.returning();
const caller = topicRouter.createCaller(createTestContext(userId));
-
- // Query only for testAgentId
await caller.getTopics({ agentId: testAgentId });
-
- // Wait for migration
await new Promise((resolve) => setTimeout(resolve, 100));
- // Only topic1 should be migrated
const [migrated1] = await serverDB.select().from(topics).where(eq(topics.id, topic1.id));
const [migrated2] = await serverDB.select().from(topics).where(eq(topics.id, topic2.id));
-
expect(migrated1.agentId).toBe(testAgentId);
- expect(migrated2.agentId).toBeNull(); // Should not be migrated
+ expect(migrated2.agentId).toBeNull();
});
});
@@ -681,10 +550,10 @@ describe('Topic Router Integration Tests', () => {
expect(result.items.map((t) => t.title)).toContain('New Inbox Topic');
});
- it('should migrate legacy inbox topics when queried', async () => {
+ it('should backfill agentId for legacy inbox topics on query', async () => {
const caller = topicRouter.createCaller(createTestContext(userId));
- // Insert legacy inbox topic
+ // Legacy inbox topic: all owner columns null
const [legacyTopic] = await serverDB
.insert(topics)
.values({
@@ -696,16 +565,10 @@ describe('Topic Router Integration Tests', () => {
})
.returning();
- // Query with isInbox=true
- await caller.getTopics({
- agentId: inboxAgentId,
- isInbox: true,
- });
-
- // Wait for migration
+ // Query with isInbox=true triggers the background backfill
+ await caller.getTopics({ agentId: inboxAgentId, isInbox: true });
await new Promise((resolve) => setTimeout(resolve, 100));
- // Verify agentId was backfilled
const [migrated] = await serverDB.select().from(topics).where(eq(topics.id, legacyTopic.id));
expect(migrated.agentId).toBe(inboxAgentId);
});
diff --git a/src/server/routers/lambda/agent.ts b/src/server/routers/lambda/agent.ts
index 46d4dad6c98..67bfc2ab310 100644
--- a/src/server/routers/lambda/agent.ts
+++ b/src/server/routers/lambda/agent.ts
@@ -285,6 +285,10 @@ export const agentRouter = router({
return ctx.agentModel.queryAgents(input);
}),
+ rankAgents: agentProcedure.input(z.number().max(50).optional()).query(async ({ ctx, input }) => {
+ return ctx.agentModel.rank(input);
+ }),
+
/**
* Remove an agent and its associated session
*/
diff --git a/src/server/routers/lambda/session.ts b/src/server/routers/lambda/session.ts
index 6681e8d5dc2..6525d5562d7 100644
--- a/src/server/routers/lambda/session.ts
+++ b/src/server/routers/lambda/session.ts
@@ -147,10 +147,6 @@ export const sessionRouter = router({
return ctx.sessionModel.query({ current, pageSize });
}),
- rankSessions: sessionProcedure.input(z.number().max(50).optional()).query(async ({ ctx, input }) => {
- return ctx.sessionModel.rank(input);
- }),
-
removeAllSessions: sessionProcedure.mutation(async ({ ctx }) => {
return ctx.sessionModel.deleteAll();
}),
diff --git a/src/services/agent.ts b/src/services/agent.ts
index d2645ee538d..de937176f45 100644
--- a/src/services/agent.ts
+++ b/src/services/agent.ts
@@ -1,4 +1,4 @@
-import { type AgentItem, type LobeAgentConfig } from '@lobechat/types';
+import { type AgentItem, type AgentRankItem, type LobeAgentConfig } from '@lobechat/types';
import { type PartialDeep } from 'type-fest';
import { lambdaClient } from '@/libs/trpc/client';
@@ -232,6 +232,13 @@ class AgentService {
): Promise<{ agentId: string } | null> => {
return lambdaClient.agent.duplicateAgent.mutate({ agentId, newTitle });
};
+
+ /**
+ * Rank the user's agents by topic count (agent usage ranking).
+ */
+ rankAgents = async (limit?: number): Promise<AgentRankItem[]> => {
+ return lambdaClient.agent.rankAgents.query(limit);
+ };
}
export const agentService = new AgentService();
diff --git a/src/services/session/index.ts b/src/services/session/index.ts
index 9b0ece4f30f..ba31fc6d5ce 100644
--- a/src/services/session/index.ts
+++ b/src/services/session/index.ts
@@ -9,7 +9,6 @@ import {
type LobeSessions,
type LobeSessionType,
type SessionGroupItem,
- type SessionRankItem,
type UpdateSessionParams,
} from '@/types/session';
@@ -52,10 +51,6 @@ export class SessionService {
return lambdaClient.session.countSessions.query(params);
};
- rankSessions = async (limit?: number): Promise<SessionRankItem[]> => {
- return lambdaClient.session.rankSessions.query(limit);
- };
-
updateSession = (id: string, data: Partial<UpdateSessionParams>) => {
const { group, pinned, meta, updatedAt } = data;
return lambdaClient.session.updateSession.mutate({