🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
fix agent session group not working
arvinxxc632b22d9714
diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.tsindex ab7c94be45a..51a20110966 100644--- a/packages/database/src/models/agent.ts+++ b/packages/database/src/models/agent.ts@@ -418,6 +418,19 @@ export class AgentModel {.where(and(eq(agents.id, agentId), eq(agents.userId, this.userId)));};+ /**+ * Update the sessionGroupId for an agent+ */+ updateSessionGroupId = async (agentId: string, sessionGroupId: string | null) => {+ const result = await this.db+ .update(agents)+ .set({ sessionGroupId, updatedAt: new Date() })+ .where(and(eq(agents.id, agentId), eq(agents.userId, this.userId)))+ .returning();++ return result[0];+ };+/*** Get a builtin agent by slug, creating it if it doesn't exist.* Builtin agents are standalone agents not bound to sessions.diff --git a/packages/database/src/repositories/agentMigration/index.ts b/packages/database/src/repositories/agentMigration/index.tsindex b0b783308e4..599c420227a 100644--- a/packages/database/src/repositories/agentMigration/index.ts+++ b/packages/database/src/repositories/agentMigration/index.ts@@ -1,6 +1,6 @@-import { and, eq, inArray, isNull } from 'drizzle-orm';+import { and, eq, inArray, isNotNull, isNull } from 'drizzle-orm';-import { agentsToSessions, messages, topics } from '../../schemas';+import { agents, agentsToSessions, messages, sessions, topics } from '../../schemas';import { LobeChatDatabase } from '../../type';type MigrateBySessionParams = { agentId: string; sessionId: string };@@ -180,4 +180,47 @@ export class AgentMigrationRepo {return result[0]?.sessionId ?? null;};++ /**+ * Runtime migration: backfill sessionGroupId for legacy agents+ *+ * This method migrates agents that have:+ * - sessionGroupId IS NULL+ * - Associated session has groupId NOT NULL+ *+ * It copies the session's groupId to the agent's sessionGroupId+ */+ migrateSessionGroupId = async () => {+ // Find all agents that need migration:+ // - Agent's sessionGroupId is NULL+ // - Agent's associated session has a groupId+ const agentsToMigrate = await this.db+ .select({+ agentId: agents.id,+ sessionGroupId: sessions.groupId,+ })+ .from(agents)+ .innerJoin(agentsToSessions, eq(agents.id, agentsToSessions.agentId))+ .innerJoin(sessions, eq(agentsToSessions.sessionId, sessions.id))+ .where(+ and(+ eq(agents.userId, this.userId),+ isNull(agents.sessionGroupId),+ isNotNull(sessions.groupId),+ ),+ );++ if (agentsToMigrate.length === 0) return;++ // Update each agent's sessionGroupId+ // Using individual updates to preserve updatedAt (no auto-update trigger)+ for (const item of agentsToMigrate) {+ if (!item.sessionGroupId) continue;++ await this.db+ .update(agents)+ .set({ sessionGroupId: item.sessionGroupId, updatedAt: agents.updatedAt })+ .where(and(eq(agents.id, item.agentId), eq(agents.userId, this.userId)));+ }+ };}diff --git a/packages/database/src/repositories/home/index.ts b/packages/database/src/repositories/home/index.tsindex 9daa927c1cb..196544d52b8 100644--- a/packages/database/src/repositories/home/index.ts+++ b/packages/database/src/repositories/home/index.ts@@ -39,13 +39,16 @@ export class HomeRepository {// 1. Query all agents (non-virtual) with their session info// Note: We query both agents.pinned and sessions.pinned for backward compatibility// agents.pinned takes priority, falling back to sessions.pinned for legacy data+ // Note: We query both agents.sessionGroupId and sessions.groupId for backward compatibility+ // agents.sessionGroupId takes priority, falling back to sessions.groupId for legacy dataconst agentList = await this.db.select({+ agentSessionGroupId: agents.sessionGroupId,avatar: agents.avatar,description: agents.description,- groupId: sessions.groupId,id: agents.id,pinned: agents.pinned,+ sessionGroupId: sessions.groupId,sessionId: sessions.id,sessionPinned: sessions.pinned,title: agents.title,@@ -116,11 +119,12 @@ export class HomeRepository {private processAgentList(agentItems: Array<{+ agentSessionGroupId: string | null;avatar: string | null;description: string | null;- groupId: string | null;id: string;pinned: boolean | null;+ sessionGroupId: string | null;sessionId: string;sessionPinned: boolean | null;title: string | null;@@ -143,11 +147,12 @@ export class HomeRepository {): SidebarAgentListResponse {// Convert to unified format// For pinned status: agents.pinned takes priority, fallback to sessions.pinned for backward compatibility+ // For groupId: agents.sessionGroupId takes priority, fallback to sessions.groupId for backward compatibilityconst allItems: Array<SidebarAgentItem & { groupId: string | null }> = [...agentItems.map((a) => ({avatar: a.avatar,description: a.description,- groupId: a.groupId,+ groupId: a.agentSessionGroupId ?? a.sessionGroupId,id: a.id,pinned: a.pinned ?? a.sessionPinned ?? false,sessionId: a.sessionId,diff --git a/packages/types/src/agent/item.ts b/packages/types/src/agent/item.tsindex 61093ba7703..3398ced9e38 100644--- a/packages/types/src/agent/item.ts+++ b/packages/types/src/agent/item.ts@@ -93,6 +93,8 @@ export interface AgentItem {params?: any;plugins?: string[];provider?: string | null;+ /** Session group ID for direct grouping */+ sessionGroupId?: string | null;slug?: string | null;systemRole?: string | null;tags?: string[];diff --git a/src/server/routers/lambda/home.ts b/src/server/routers/lambda/home.tsindex a9bd69cf723..6af6f73e97b 100644--- a/src/server/routers/lambda/home.ts+++ b/src/server/routers/lambda/home.ts@@ -1,5 +1,8 @@+import { after } from 'next/server';import { z } from 'zod';+import { AgentModel } from '@/database/models/agent';+import { AgentMigrationRepo } from '@/database/repositories/agentMigration';import { HomeRepository } from '@/database/repositories/home';import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';@@ -9,6 +12,8 @@ const homeProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {return opts.next({ctx: {+ agentMigrationRepo: new AgentMigrationRepo(ctx.serverDB, ctx.userId),+ agentModel: new AgentModel(ctx.serverDB, ctx.userId),homeRepository: new HomeRepository(ctx.serverDB, ctx.userId),},});@@ -16,7 +21,21 @@ const homeProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {export const homeRouter = router({getSidebarAgentList: homeProcedure.query(async ({ ctx }) => {- return ctx.homeRepository.getSidebarAgentList();+ const result = await ctx.homeRepository.getSidebarAgentList();++ // Runtime migration: backfill sessionGroupId for legacy agents+ const runMigration = async () => {+ try {+ await ctx.agentMigrationRepo.migrateSessionGroupId();+ } catch (error) {+ console.error('[AgentMigration] Failed to migrate sessionGroupId:', error);+ }+ };++ // Use Next.js after() for non-blocking execution+ after(runMigration);++ return result;}),searchAgents: homeProcedure@@ -24,6 +43,17 @@ export const homeRouter = router({.query(async ({ input, ctx }) => {return ctx.homeRepository.searchAgents(input.keyword);}),++ updateAgentSessionGroupId: homeProcedure+ .input(+ z.object({+ agentId: z.string(),+ sessionGroupId: z.string().nullable(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ return ctx.agentModel.updateSessionGroupId(input.agentId, input.sessionGroupId);+ }),});export type HomeRouter = typeof homeRouter;diff --git a/src/services/home/index.ts b/src/services/home/index.tsindex 4fd455e654f..7ae97d0aaec 100644--- a/src/services/home/index.ts+++ b/src/services/home/index.ts@@ -15,6 +15,13 @@ export class HomeService {searchAgents = (keyword: string): Promise<SidebarAgentItem[]> => {return lambdaClient.home.searchAgents.query({ keyword });};++ /**+ * Update an agent's session group+ */+ updateAgentSessionGroupId = (agentId: string, sessionGroupId: string | null): Promise<void> => {+ return lambdaClient.home.updateAgentSessionGroupId.mutate({ agentId, sessionGroupId }) as any;+ };}export const homeService = new HomeService();diff --git a/src/store/home/slices/sidebarUI/action.ts b/src/store/home/slices/sidebarUI/action.tsindex dc89b9a4434..c7f2c72ded2 100644--- a/src/store/home/slices/sidebarUI/action.ts+++ b/src/store/home/slices/sidebarUI/action.ts@@ -3,9 +3,9 @@ import { t } from 'i18next';import { StateCreator } from 'zustand/vanilla';import { message } from '@/components/AntdStaticMethods';-import { INBOX_SESSION_ID } from '@/const/session';import { agentService } from '@/services/agent';import { chatGroupService } from '@/services/chatGroup';+import { homeService } from '@/services/home';import { sessionService } from '@/services/session';import type { HomeStore } from '@/store/home/store';import { getSessionStoreState } from '@/store/session';@@ -122,16 +122,10 @@ export const createSidebarUISlice: StateCreator<removeAgent: async (agentId) => {await agentService.removeAgent(agentId);await get().refreshAgentList();-- // If the active agent is deleted, switch to inbox- const sessionStore = getSessionStoreState();- if (agentId === sessionStore.activeId) {- sessionStore.switchSession(INBOX_SESSION_ID);- }},updateAgentGroup: async (agentId, groupId) => {- await sessionService.updateSession(agentId, { group: groupId || 'default' });+ await homeService.updateAgentSessionGroupId(agentId, groupId === 'default' ? null : groupId);await get().refreshAgentList();},