🤯 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
✨ feat: add db and schema feature
arvinxx9e47c33e9f4b
diff --git a/packages/const/src/url.ts b/packages/const/src/url.tsindex 8a0ab5531eb..75891eb610b 100644--- a/packages/const/src/url.ts+++ b/packages/const/src/url.ts@@ -1,8 +1,5 @@-import qs from 'query-string';import urlJoin from 'url-join';-import { INBOX_SESSION_ID } from './session';-const isDev = process.env.NODE_ENV === 'development';export const UTM_SOURCE = 'chat_preview';@@ -47,11 +44,14 @@ export const AGENTS_INDEX_GITHUB = 'https://github.com/lobehub/lobe-chat-agents'export const AGENTS_INDEX_GITHUB_ISSUE = urlJoin(AGENTS_INDEX_GITHUB, 'issues/new');export const AGENTS_OFFICIAL_URL = 'https://lobehub.com/agent';-export const SESSION_CHAT_URL = (id: string = INBOX_SESSION_ID, mobile?: boolean) =>- qs.stringifyUrl({- query: mobile ? { session: id, showMobileWorkspace: mobile } : { session: id },- url: '/chat',- });+export const SESSION_CHAT_URL = (agentId: string, mobile?: boolean) => {+ if (mobile) return `/agent/${agentId}`;+ return `/agent/${agentId}`;+};++export const GROUP_CHAT_URL = (groupId: string) => `/group/${groupId}`;++export const LIBRARY_URL = (id: string) => urlJoin('/resource/library', id);export const imageUrl = (filename: string) => `/images/${filename}`;diff --git a/packages/database/src/models/chatGroup.ts b/packages/database/src/models/chatGroup.tsindex 478d3fdacbf..be7918b8d85 100644--- a/packages/database/src/models/chatGroup.ts+++ b/packages/database/src/models/chatGroup.ts@@ -58,7 +58,7 @@ export class ChatGroupModel {return groups.map((group) => ({...group,- members: groupAgentMap.get(group.id) || [],+ agents: groupAgentMap.get(group.id) || [],}));}@@ -102,7 +102,6 @@ export class ChatGroupModel {agentId,chatGroupId: group.id,order: index,- role: 'assistant',userId: this.userId,}));@@ -144,17 +143,29 @@ export class ChatGroupModel {return result;}- async addAgentsToGroup(groupId: string, agentIds: string[]): Promise<ChatGroupAgentItem[]> {+ /**+ * Add multiple agents to a group.+ * Automatically skips agents that are already in the group.+ *+ * @returns Object containing:+ * - `added`: Agents that were newly added to the group+ * - `existing`: Agent IDs that were already in the group (skipped)+ */+ async addAgentsToGroup(+ groupId: string,+ agentIds: string[],+ ): Promise<{ added: NewChatGroupAgent[]; existing: string[] }> {const group = await this.findById(groupId);if (!group) throw new Error('Group not found');const existingAgents = await this.getGroupAgents(groupId);- const existingAgentIds = new Set(existingAgents.map((a) => a.id));+ const existingAgentIds = new Set(existingAgents.map((a) => a.agentId));const newAgentIds = agentIds.filter((id) => !existingAgentIds.has(id));+ const existingIds = agentIds.filter((id) => existingAgentIds.has(id));if (newAgentIds.length === 0) {- return [];+ return { added: [], existing: existingIds };}const newAgents: NewChatGroupAgent[] = newAgentIds.map((agentId) => ({@@ -164,7 +175,9 @@ export class ChatGroupModel {userId: this.userId,}));- return this.db.insert(chatGroupsAgents).values(newAgents).returning();+ const added = await this.db.insert(chatGroupsAgents).values(newAgents).returning();++ return { added, existing: existingIds };}async removeAgentFromGroup(groupId: string, agentId: string): Promise<void> {@@ -173,6 +186,20 @@ export class ChatGroupModel {.where(and(eq(chatGroupsAgents.chatGroupId, groupId), eq(chatGroupsAgents.agentId, agentId)));}+ /**+ * Batch remove multiple agents from a group.+ * More efficient than calling removeAgentFromGroup multiple times.+ */+ async removeAgentsFromGroup(groupId: string, agentIds: string[]): Promise<void> {+ if (agentIds.length === 0) return;++ await this.db+ .delete(chatGroupsAgents)+ .where(+ and(eq(chatGroupsAgents.chatGroupId, groupId), inArray(chatGroupsAgents.agentId, agentIds)),+ );+ }+async updateAgentInGroup(groupId: string,agentId: string,diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.tsindex cfa0536044c..2430ad55f88 100644--- a/packages/database/src/models/message.ts+++ b/packages/database/src/models/message.ts@@ -8,22 +8,43 @@ import {ChatVideoItem,CreateMessageParams,DBMessageItem,+ IThreadType,MessagePluginItem,ModelRankItem,NewMessageQueryParams,QueryMessageParams,+ TaskDetail,+ ThreadStatus,+ ThreadType,UIChatMessage,UpdateMessageParams,UpdateMessageRAGParams,} from '@lobechat/types';import type { HeatmapsProps } from '@lobehub/charts';import dayjs from 'dayjs';-import { and, asc, count, desc, eq, gt, inArray, isNotNull, isNull, like, sql } from 'drizzle-orm';+import {+ SQL,+ and,+ asc,+ count,+ desc,+ eq,+ gt,+ inArray,+ isNotNull,+ isNull,+ like,+ lte,+ not,+ or,+ sql,+} from 'drizzle-orm';import { merge } from '@/utils/merge';import { today } from '@/utils/time';import {+ agentsToSessions,chunks,documents,embeddings,@@ -36,11 +57,34 @@ import {messageTranslates,messages,messagesFiles,+ threads,} from '../schemas';import { LobeChatDatabase } from '../type';import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';import { idGenerator } from '../utils/idGenerator';+/**+ * Options for querying messages with relations+ */+export interface QueryMessagesOptions {+ /**+ * Current page number (0-indexed)+ */+ current?: number;+ /**+ * Number of messages per page+ */+ pageSize?: number;+ /**+ * Post-process function for file URLs+ */+ postProcessUrl?: (path: string | null, file: { fileType: string }) => Promise<string>;+ /**+ * Custom where condition for message filtering+ */+ where?: SQL;+}+export class MessageModel {private userId: string;private db: LobeChatDatabase;@@ -51,16 +95,95 @@ export class MessageModel {}// **************** Query *************** //++ /**+ * Query messages by params (high-level API)+ *+ * This is the main query method that handles common query patterns.+ * For custom queries, use `queryWithWhere` directly.+ */query = async (- { current = 0, pageSize = 1000, sessionId, topicId, groupId }: QueryMessageParams = {},+ {+ agentId,+ current = 0,+ pageSize = 1000,+ sessionId,+ topicId,+ groupId,+ threadId,+ }: QueryMessageParams = {},options: {- groupAssistantMessages?: boolean;postProcessUrl?: (path: string | null, file: { fileType: string }) => Promise<string>;} = {},) => {+ // Build agent condition (handles legacy sessionId lookup)+ let agentCondition: SQL | undefined;+ if (agentId) {+ agentCondition = await this.buildAgentCondition(agentId);+ } else if (sessionId) {+ agentCondition = this.matchSession(sessionId);+ }++ // For thread queries, we need to fetch complete thread data (parent + thread messages)+ if (threadId) {+ const threadCondition = await this.buildThreadQueryCondition(threadId);+ return this.queryWithWhere({+ current,+ pageSize,+ postProcessUrl: options.postProcessUrl,+ // Thread queries optionally add agent/session scope if provided+ where: agentCondition ? and(agentCondition, threadCondition) : threadCondition,+ });+ }++ // For Group Chat queries: filter by groupId only (not agentId)+ // In Group Chat, all messages (user, supervisor, workers) should have groupId+ // and may have different agentIds, so we only filter by groupId + topicId+ if (groupId) {+ const whereCondition = and(+ eq(messages.groupId, groupId),+ this.matchTopic(topicId),+ this.matchThread(threadId),+ );++ return this.queryWithWhere({+ current,+ pageSize,+ postProcessUrl: options.postProcessUrl,+ where: whereCondition,+ });+ }++ // Standard query with session/topic/group filters+ const whereCondition = and(+ agentCondition ?? this.matchSession(sessionId),+ this.matchTopic(topicId),+ this.matchGroup(groupId),+ this.matchThread(threadId),+ );++ return this.queryWithWhere({+ current,+ pageSize,+ postProcessUrl: options.postProcessUrl,+ where: whereCondition,+ });+ };++ /**+ * Query messages with full relations (files, plugins, translations, etc.)+ *+ * This is the low-level query method that accepts a custom where condition.+ * Use this for building custom query scenarios.+ *+ * @param options - Query options including where condition and pagination+ * @returns Messages with all related data+ */+ queryWithWhere = async (options: QueryMessagesOptions = {}): Promise<UIChatMessage[]> => {+ const { where, current = 0, pageSize = 1000, postProcessUrl } = options;const offset = current * pageSize;- // 1. get basic messages+ // 1. get basic messages with joinsconst result = await this.db.select({/* eslint-disable sort-keys-fix/sort-keys-fix*/@@ -113,14 +236,7 @@ export class MessageModel {/* eslint-enable */}).from(messages)- .where(- and(- eq(messages.userId, this.userId),- this.matchSession(sessionId),- this.matchTopic(topicId),- this.matchGroup(groupId),- ),- )+ .where(and(eq(messages.userId, this.userId), where)).leftJoin(messagePlugins, eq(messagePlugins.id, messages.id)).leftJoin(messageTranslates, eq(messageTranslates.id, messages.id)).leftJoin(messageTTS, eq(messageTTS.id, messages.id))@@ -149,9 +265,7 @@ export class MessageModel {const relatedFileList = await Promise.all(rawRelatedFileList.map(async (file) => ({...file,- url: options.postProcessUrl- ? await options.postProcessUrl(file.url, file as any)- : (file.url as string),+ url: postProcessUrl ? await postProcessUrl(file.url, file as any) : (file.url as string),})),);@@ -202,7 +316,7 @@ export class MessageModel {.innerJoin(files, eq(fileChunks.fileId, files.id)).where(inArray(messageQueryChunks.messageId, messageIds));- // 3. get relative message query+ // 4. get relative message queryconst messageQueriesList = await this.db.select({id: messageQueries.id,@@ -213,6 +327,45 @@ export class MessageModel {.from(messageQueries).where(inArray(messageQueries.messageId, messageIds));+ // 5. get thread info for task messages+ const taskMessageIds = result.filter((m) => m.role === 'task').map((m) => m.id as string);++ let threadMap = new Map<string, TaskDetail>();++ if (taskMessageIds.length > 0) {+ const threadData = await this.db+ .select({+ metadata: threads.metadata,+ sourceMessageId: threads.sourceMessageId,+ status: threads.status,+ threadId: threads.id,+ title: threads.title,+ })+ .from(threads)+ .where(+ and(eq(threads.userId, this.userId), inArray(threads.sourceMessageId, taskMessageIds)),+ );++ threadMap = new Map(+ threadData.map((t) => {+ const metadata = t.metadata as Record<string, unknown> | null;+ return [+ t.sourceMessageId!,+ {+ duration: metadata?.duration as number | undefined,+ status: t.status as ThreadStatus,+ threadId: t.threadId,+ title: t.title ?? undefined,+ totalCost: metadata?.totalCost as number | undefined,+ totalMessages: metadata?.totalMessages as number | undefined,+ totalTokens: metadata?.totalTokens as number | undefined,+ totalToolCalls: metadata?.totalToolCalls as number | undefined,+ },+ ];+ }),+ );+ }+return result.map(({ model, provider, translate, ttsId, ttsFile, ttsContentMd5, ttsVoice, ...item }) => {const messageQuery = messageQueriesList.find((relation) => relation.messageId === item.id);@@ -260,6 +413,8 @@ export class MessageModel {ragQuery: messageQuery?.rewriteQuery,ragQueryId: messageQuery?.id,ragRawQuery: messageQuery?.userQuery,+ // Add taskDetail for task messages+ taskDetail: item.role === 'task' ? threadMap.get(item.id as string) : undefined,videoList: videoList.filter((relation) => relation.messageId === item.id)// eslint-disable-next-line @typescript-eslint/no-unused-vars@@ -269,12 +424,115 @@ export class MessageModel {);};+ /**+ * Build where condition for thread queries+ *+ * Returns a condition that matches both parent messages and thread messages.+ */+ private buildThreadQueryCondition = async (threadId: string): Promise<SQL | undefined> => {+ // Fetch the thread info to get sourceMessageId and type+ const thread = await this.db.query.threads.findFirst({+ where: and(eq(threads.id, threadId), eq(threads.userId, this.userId)),+ });++ if (!thread?.sourceMessageId || !thread?.topicId) {+ // Fallback to simple thread query if no source message+ return eq(messages.threadId, threadId);+ }++ // Get parent messages based on thread type+ const parentMessages = await this.getThreadParentMessages({+ sourceMessageId: thread.sourceMessageId,+ threadType: thread.type as IThreadType,+ topicId: thread.topicId,+ });++ const parentMessageIds = parentMessages.map((m) => m.id);++ if (parentMessageIds.length === 0) {+ return eq(messages.threadId, threadId);+ }++ // Match either thread messages or parent messages+ return or(eq(messages.threadId, threadId), inArray(messages.id, parentMessageIds));+ };++ /**+ * Build agent condition with legacy sessionId support+ */+ private buildAgentCondition = async (agentId: string): Promise<SQL | undefined> => {+ // 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+ return associatedSessionId+ ? or(eq(messages.agentId, agentId), eq(messages.sessionId, associatedSessionId))+ : eq(messages.agentId, agentId);+ };+findById = async (id: string) => {return this.db.query.messages.findFirst({where: and(eq(messages.id, id), eq(messages.userId, this.userId)),});};+ /**+ * Get parent messages for a thread+ *+ * @param params - Parameters for getting parent messages+ * @param params.sourceMessageId - The ID of the source message that started the thread+ * @param params.topicId - The topic ID the thread belongs to+ * @param params.threadType - The type of thread (Continuation or Standalone)+ * @returns Parent messages based on thread type:+ * - Continuation: All messages from the topic up to and including the source message+ * - Standalone: Only the source message itself+ */+ getThreadParentMessages = async (params: {+ sourceMessageId: string;+ threadType: IThreadType;+ topicId: string;+ }): Promise<DBMessageItem[]> => {+ const { sourceMessageId, topicId, threadType } = params;++ // For Standalone type, only return the source message+ if (threadType === ThreadType.Standalone) {+ const sourceMessage = await this.db.query.messages.findFirst({+ where: and(eq(messages.id, sourceMessageId), eq(messages.userId, this.userId)),+ });++ return sourceMessage ? [sourceMessage as DBMessageItem] : [];+ }++ // For Continuation type, get the source message first to know its createdAt+ const sourceMessage = await this.db.query.messages.findFirst({+ where: and(eq(messages.id, sourceMessageId), eq(messages.userId, this.userId)),+ });++ if (!sourceMessage) return [];++ // Get all main conversation messages up to and including the source message+ const result = await this.db+ .select()+ .from(messages)+ .where(+ and(+ eq(messages.userId, this.userId),+ eq(messages.topicId, topicId),+ isNull(messages.threadId), // Only main conversation messages (not in any thread)+ lte(messages.createdAt, sourceMessage.createdAt),+ ),+ )+ .orderBy(asc(messages.createdAt));++ return result as DBMessageItem[];+ };+findMessageQueriesById = async (messageId: string) => {const result = await this.db.select({@@ -455,6 +713,19 @@ export class MessageModel {return result.length > n;};+ /**+ * Count messages up to a limit, useful for avoiding full table scans+ */+ countUpTo = async (n: number): Promise<number> => {+ const result = await this.db+ .select({ id: messages.id })+ .from(messages)+ .where(eq(messages.userId, this.userId))+ .limit(n);++ return result.length;+ };+// **************** Create *************** //create = async (@@ -609,6 +880,153 @@ export class MessageModel {return this.db.update(messagePlugins).set(value).where(eq(messagePlugins.id, id));};+ /**+ * Update tool message with content, metadata, pluginState, and pluginError in a single transaction+ * This prevents race conditions when updating multiple fields+ */+ updateToolMessage = async (+ id: string,+ params: {+ content?: string;+ metadata?: Record<string, any>;+ pluginError?: any;+ pluginState?: Record<string, any>;+ },+ ): Promise<{ success: boolean }> => {+ const { content, metadata, pluginState, pluginError } = params;++ try {+ await this.db.transaction(async (trx) => {+ // Update messages table (content, metadata)+ if (content !== undefined || metadata !== undefined) {+ const messageUpdateData: Record<string, any> = {};++ if (content !== undefined) {+ messageUpdateData.content = content;+ }++ if (metadata !== undefined) {+ // Need to merge with existing metadata+ const existingMessage = await trx.query.messages.findFirst({+ where: and(eq(messages.id, id), eq(messages.userId, this.userId)),+ });+ messageUpdateData.metadata = merge(existingMessage?.metadata || {}, metadata);+ }++ if (Object.keys(messageUpdateData).length > 0) {+ await trx+ .update(messages)+ .set(messageUpdateData)+ .where(and(eq(messages.id, id), eq(messages.userId, this.userId)));+ }+ }++ // Update messagePlugins table (pluginState, pluginError)+ if (pluginState !== undefined || pluginError !== undefined) {+ const pluginItem = await trx.query.messagePlugins.findFirst({+ where: eq(messagePlugins.id, id),+ });++ if (pluginItem) {+ const pluginUpdateData: Record<string, any> = {};++ if (pluginState !== undefined) {+ pluginUpdateData.state = merge(pluginItem.state || {}, pluginState);+ }++ if (pluginError !== undefined) {+ pluginUpdateData.error = pluginError;+ }++ if (Object.keys(pluginUpdateData).length > 0) {+ await trx+ .update(messagePlugins)+ .set(pluginUpdateData)+ .where(eq(messagePlugins.id, id));+ }+ }+ }+ });++ return { success: true };+ } catch (error) {+ console.error('Update tool message error:', error);+ return { success: false };+ }+ };++ /**+ * Update tool arguments by toolCallId - updates both tool message plugin.arguments+ * and parent assistant message tools[].arguments in a single transaction+ *+ * This method uses toolCallId (the stable identifier from AI response) instead of+ * tool message ID, which allows updating arguments even when the tool message+ * hasn't been persisted yet (e.g., during intervention pending state).+ *+ * @param toolCallId - The tool call ID (stable identifier from AI response)+ * @param args - The new arguments string (already stringified JSON)+ */+ updateToolArguments = async (toolCallId: string, args: string): Promise<{ success: boolean }> => {+ try {+ await this.db.transaction(async (trx) => {+ // 1. Find tool plugin and tool message with parentId in one query+ const [toolResult] = await trx+ .select({+ parentId: messages.parentId,+ toolPluginId: messagePlugins.id,+ })+ .from(messagePlugins)+ .innerJoin(messages, eq(messages.id, messagePlugins.id))+ .where(and(eq(messagePlugins.toolCallId, toolCallId), eq(messages.userId, this.userId)))+ .limit(1);++ if (!toolResult?.parentId) {+ throw new Error(`No tool message found with toolCallId: ${toolCallId}`);+ }++ // 2. Get parent assistant message's tools+ const [parentMessage] = await trx+ .select({ id: messages.id, tools: messages.tools })+ .from(messages)+ .where(eq(messages.id, toolResult.parentId))+ .limit(1);++ if (!parentMessage?.tools) {+ throw new Error(`No parent assistant message found for toolCallId: ${toolCallId}`);+ }++ const parentTools = parentMessage.tools as ChatToolPayload[];++ // 3. Update the parent assistant message's tools[].arguments+ const updatedTools = parentTools.map((tool) => {+ if (tool.id === toolCallId) {+ return { ...tool, arguments: args };+ }+ return tool;+ });++ // Execute both updates in parallel+ await Promise.all([+ // Update tool plugin arguments+ trx+ .update(messagePlugins)+ .set({ arguments: args })+ .where(eq(messagePlugins.id, toolResult.toolPluginId)),+ // Update parent assistant message's tools+ trx+ .update(messages)+ .set({ tools: updatedTools })+ .where(eq(messages.id, parentMessage.id)),+ ]);+ });++ return { success: true };+ } catch (error) {+ console.error('Update tool arguments error:', error);+ return { success: false };+ }+ };+updateTranslate = async (id: string, translate: Partial<ChatTranslate>) => {const result = await this.db.query.messageTranslates.findFirst({where: and(eq(messageTranslates.id, id)),@@ -672,7 +1090,14 @@ export class MessageModel {// If the message to be deleted is not found, return directlyif (message.length === 0) return;- // 2. Check if the message contains tools+ // 2. Update child messages' parentId to the current message's parentId+ // This preserves the tree structure when deleting a node+ await tx+ .update(messages)+ .set({ parentId: message[0].parentId })+ .where(and(eq(messages.parentId, id), eq(messages.userId, this.userId)));++ // 3. Check if the message contains toolsconst toolCallIds = (message[0].tools as ChatToolPayload[])?.map((tool) => tool.id).filter(Boolean);@@ -680,7 +1105,7 @@ export class MessageModel {let relatedMessageIds: string[] = [];if (toolCallIds?.length > 0) {- // 3. If the message contains tools, query all associated message ids+ // 4. If the message contains tools, query all associated message idsconst res = await tx.select({ id: messagePlugins.id }).from(messagePlugins)@@ -689,18 +1114,110 @@ export class MessageModel {relatedMessageIds = res.map((row) => row.id);}- // 4. Merge the list of message ids to be deleted+ // 5. Merge the list of message ids to be deletedconst messageIdsToDelete = [id, ...relatedMessageIds];- // 5. Delete all related messages- await tx.delete(messages).where(inArray(messages.id, messageIdsToDelete));+ // 6. Delete all related messages+ await tx+ .delete(messages)+ .where(and(eq(messages.userId, this.userId), inArray(messages.id, messageIdsToDelete)));});};- deleteMessages = async (ids: string[]) =>- this.db- .delete(messages)- .where(and(eq(messages.userId, this.userId), inArray(messages.id, ids)));+ deleteMessages = async (ids: string[]) => {+ if (ids.length === 0) return;++ return this.db.transaction(async (tx) => {+ // 1. Query all messages to be deleted with their parentId+ const toDelete = await tx+ .select({ id: messages.id, parentId: messages.parentId })+ .from(messages)+ .where(and(eq(messages.userId, this.userId), inArray(messages.id, ids)));++ if (toDelete.length === 0) return;++ // 2. Build id -> parentId map and deleteSet+ const parentMap = new Map<string, string | null>();+ const deleteSet = new Set<string>();+ for (const msg of toDelete) {+ parentMap.set(msg.id, msg.parentId);+ deleteSet.add(msg.id);+ }++ // 3. Find the final ancestor for each deleted message (first ancestor not in deleteSet)+ const finalAncestorMap = new Map<string, string | null>();++ const findFinalAncestor = (id: string): string | null => {+ if (finalAncestorMap.has(id)) return finalAncestorMap.get(id)!;++ const parentId = parentMap.get(id);+ if (parentId === null || parentId === undefined) {+ finalAncestorMap.set(id, null);+ return null;+ }++ if (!deleteSet.has(parentId)) {+ // Parent is not being deleted, it's the final ancestor+ finalAncestorMap.set(id, parentId);+ return parentId;+ }++ // Parent is also being deleted, recursively find its ancestor+ const ancestor = findFinalAncestor(parentId);+ finalAncestorMap.set(id, ancestor);+ return ancestor;+ };++ for (const id of deleteSet) {+ findFinalAncestor(id);+ }++ // 4. Query child messages whose parentId points to messages being deleted+ const children = await tx+ .select({ id: messages.id, parentId: messages.parentId })+ .from(messages)+ .where(+ and(+ eq(messages.userId, this.userId),+ inArray(messages.parentId, ids),+ not(inArray(messages.id, ids)),+ ),+ );++ // 5. Update each child's parentId to the final ancestor+ for (const child of children) {+ const newParentId = finalAncestorMap.get(child.parentId!) ?? null;+ await tx.update(messages).set({ parentId: newParentId }).where(eq(messages.id, child.id));+ }++ // 6. Delete the messages+ await tx+ .delete(messages)+ .where(and(eq(messages.userId, this.userId), inArray(messages.id, ids)));+ });+ };++ /**+ * Add files to a message by inserting records into messagesFiles table+ * This associates existing files with a message for display in fileList/imageList/videoList+ */+ addFiles = async (messageId: string, fileIds: string[]): Promise<{ success: boolean }> => {+ if (fileIds.length === 0) return { success: true };++ try {+ await this.db.insert(messagesFiles).values(+ fileIds.map((fileId) => ({+ fileId,+ messageId,+ userId: this.userId,+ })),+ );+ return { success: true };+ } catch (error) {+ console.error('Add files to message error:', error);+ return { success: false };+ }+ };deleteMessageTranslate = async (id: string) =>this.db@@ -737,6 +1254,30 @@ export class MessageModel {return this.db.delete(messages).where(eq(messages.userId, this.userId));};+ /**+ * Deletes multiple messages based on the agentId.+ * This will delete messages that have either:+ * 1. Direct agentId match (new data)+ * 2. SessionId match via agentsToSessions lookup (legacy data)+ */+ 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(messages.agentId, agentId), eq(messages.sessionId, associatedSessionId))+ : eq(messages.agentId, agentId);++ return this.db.delete(messages).where(and(eq(messages.userId, this.userId), agentCondition));+ };+// **************** Helper *************** //private genId = () => idGenerator('messages', 14);@@ -752,4 +1293,9 @@ export class MessageModel {private matchGroup = (groupId?: string | null) =>groupId ? eq(messages.groupId, groupId) : isNull(messages.groupId);++ private matchThread = (threadId?: string | null) => {+ if (!!threadId) return eq(messages.threadId, threadId);+ return isNull(messages.threadId);+ };}diff --git a/packages/database/src/models/thread.ts b/packages/database/src/models/thread.tsindex 6f095d233ec..bc5f09be4b8 100644--- a/packages/database/src/models/thread.ts+++ b/packages/database/src/models/thread.ts@@ -5,8 +5,11 @@ import { ThreadItem, threads } from '../schemas';import { LobeChatDatabase } from '../type';const queryColumns = {+ agentId: threads.agentId,createdAt: threads.createdAt,+ groupId: threads.groupId,id: threads.id,+ metadata: threads.metadata,parentThreadId: threads.parentThreadId,sourceMessageId: threads.sourceMessageId,status: threads.status,diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex c6d29ab80c4..4b97074d578 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -1,12 +1,29 @@import { DBMessageItem, TopicRankItem } from '@lobechat/types';-import { and, count, desc, eq, gt, ilike, inArray, isNull, or, sql } from 'drizzle-orm';--import { TopicItem, messages, topics } from '../schemas';+import {+ SQL,+ and,+ count,+ desc,+ eq,+ gt,+ gte,+ ilike,+ inArray,+ isNull,+ lte,+ ne,+ not,+ or,+ sql,+} from 'drizzle-orm';++import { TopicItem, agents, agentsToSessions, messages, topics } from '../schemas';import { LobeChatDatabase } from '../type';import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';import { idGenerator } from '../utils/idGenerator';export interface CreateTopicParams {+ agentId?: string | null;favorite?: boolean;groupId?: string | null;messages?: string[];@@ -15,11 +32,30 @@ export interface CreateTopicParams {}interface QueryTopicParams {- containerId?: string | null; // sessionId or groupId+ agentId?: string | null;+ /**+ * @deprecated Use agentId or groupId instead. Kept for backward compatibility.+ * Container ID (sessionId or groupId) to filter topics by+ */+ containerId?: string | null;current?: number;+ /**+ * Group ID to filter topics by+ */+ groupId?: string | null;+ /**+ * Whether this is an inbox agent query.+ * When true, also includes legacy inbox topics (sessionId IS NULL AND groupId IS NULL AND agentId IS NULL)+ */+ isInbox?: boolean;pageSize?: number;}+export interface ListTopicsForMemoryExtractorCursor {+ createdAt: Date;+ id: string;+}+export class TopicModel {private userId: string;private db: LobeChatDatabase;@@ -30,27 +66,142 @@ export class TopicModel {}// **************** Query *************** //- query = async ({ current = 0, pageSize = 9999, containerId }: QueryTopicParams = {}) => {+ query = async ({+ agentId,+ containerId,+ current = 0,+ pageSize = 9999,+ groupId,+ isInbox,+ }: QueryTopicParams = {}) => {const offset = current * pageSize;- return (++ // If groupId is provided, query topics by groupId directly+ if (groupId) {+ const whereCondition = and(eq(topics.userId, this.userId), eq(topics.groupId, groupId));++ const [items, totalResult] = await Promise.all([+ this.db+ .select({+ createdAt: topics.createdAt,+ favorite: topics.favorite,+ historySummary: topics.historySummary,+ id: topics.id,+ metadata: topics.metadata,+ title: topics.title,+ updatedAt: topics.updatedAt,+ })+ .from(topics)+ .where(whereCondition)+ .orderBy(desc(topics.favorite), desc(topics.updatedAt))+ .limit(pageSize)+ .offset(offset),+ this.db+ .select({ count: count(topics.id) })+ .from(topics)+ .where(whereCondition),+ ]);++ 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) {+ // 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+ 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);+ }++ // Fetch items and total count in parallel+ // Include sessionId and agentId for migration detection+ const [items, totalResult] = await Promise.all([+ this.db+ .select({+ createdAt: topics.createdAt,+ favorite: topics.favorite,+ historySummary: topics.historySummary,+ id: topics.id,+ metadata: topics.metadata,+ title: topics.title,+ updatedAt: topics.updatedAt,+ })+ .from(topics)+ .where(and(eq(topics.userId, this.userId), agentCondition))+ .orderBy(desc(topics.favorite), desc(topics.updatedAt))+ .limit(pageSize)+ .offset(offset),+ this.db+ .select({ count: count(topics.id) })+ .from(topics)+ .where(and(eq(topics.userId, this.userId), agentCondition)),+ ]);++ return { items, total: totalResult[0].count };+ }++ // Fallback to containerId-based query (backward compatibility)+ const whereCondition = and(eq(topics.userId, this.userId), this.matchContainer(containerId));++ const [items, totalResult] = await Promise.all([this.db.select({+ agentId: topics.agentId,createdAt: topics.createdAt,favorite: topics.favorite,historySummary: topics.historySummary,id: topics.id,metadata: topics.metadata,+ sessionId: topics.sessionId,title: topics.title,updatedAt: topics.updatedAt,}).from(topics)- .where(and(eq(topics.userId, this.userId), this.matchContainer(containerId)))+ .where(whereCondition)// In boolean sorting, false is considered "smaller" than true.// So here we use desc to ensure that topics with favorite as true are in front..orderBy(desc(topics.favorite), desc(topics.updatedAt)).limit(pageSize)- .offset(offset)- );+ .offset(offset),+ this.db+ .select({ count: count(topics.id) })+ .from(topics)+ .where(whereCondition),+ ]);++ // Remove internal fields before returning+ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ const cleanItems = items.map(({ agentId, sessionId, ...rest }) => rest);++ return { items: cleanItems, total: totalResult[0].count };};findById = async (id: string) => {@@ -102,7 +253,10 @@ export class TopicModel {}// Query topics found by message content- const topicIds = topicIdsByMessages.map((t) => t.topicId);+ const topicIds = topicIdsByMessages+ .map((t) => t.topicId)+ .filter((id): id is string => id !== null);+const topicsByMessages = await this.db.query.topics.findMany({orderBy: [desc(topics.updatedAt)],where: and(eq(topics.userId, this.userId), inArray(topics.id, topicIds)),@@ -124,10 +278,35 @@ export class TopicModel {);};count = async (params?: {+ agentId?: string;+ containerId?: string | null;endDate?: string;range?: [string, string];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 result = await this.db.select({count: count(topics.id),@@ -136,6 +315,8 @@ export class TopicModel {.where(genWhere([eq(topics.userId, this.userId),+ agentCondition,+ params?.containerId ? this.matchContainer(params.containerId) : undefined,params?.range? genRangeWhere(params.range, topics.createdAt, (date) => date.toDate()): undefined,@@ -168,6 +349,47 @@ export class TopicModel {.limit(limit);};+ /**+ * Query recent topics for homepage display.+ * Returns basic topic info with agentId/groupId for later resolution.+ * - For agent topics: excludes virtual agents (except inbox)+ * - For group topics: includes topics with groupId+ * - For inbox: includes topics with slug='inbox'+ */+ queryRecent = async (limit: number = 12) => {+ const result = await this.db+ .select({+ agentId: topics.agentId,+ groupId: topics.groupId,+ id: topics.id,+ sessionId: topics.sessionId,+ title: topics.title,+ updatedAt: topics.updatedAt,+ })+ .from(topics)+ .leftJoin(agents, eq(topics.agentId, agents.id))+ .where(+ and(+ eq(topics.userId, this.userId),+ or(+ // Group topics: has groupId+ not(isNull(topics.groupId)),+ // Inbox agent topics+ eq(agents.slug, 'inbox'),+ // Agent topics: exclude virtual agents+ and(isNull(topics.groupId), ne(agents.virtual, true)),+ ),+ ),+ )+ .orderBy(desc(topics.updatedAt))+ .limit(limit);++ return result.map((item) => ({+ ...item,+ type: item.groupId ? ('group' as const) : ('agent' as const),+ }));+ };+// **************** Create *************** //create = async (@@ -177,6 +399,7 @@ export class TopicModel {return this.db.transaction(async (tx) => {const insertData = {...params,+ agentId: params.agentId || null,groupId: params.groupId || null,id,sessionId: params.sessionId || null,@@ -206,6 +429,7 @@ export class TopicModel {.insert(topics).values(topicParams.map((params) => ({+ agentId: params.agentId || null,favorite: params.favorite,groupId: params.sessionId ? null : params.groupId,id: params.id || this.genId(),@@ -312,6 +536,30 @@ export class TopicModel {.where(and(this.matchGroup(groupId), eq(topics.userId, this.userId)));};+ /**+ * 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)+ */+ 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));+ };+/*** Deletes multiple topics and all messages associated with them in a transaction.*/@@ -350,4 +598,47 @@ export class TopicModel {// If neither is provided, match topics with no session or groupreturn and(isNull(topics.sessionId), isNull(topics.groupId));};++ listTopicsForMemoryExtractor = async (+ options: {+ cursor?: ListTopicsForMemoryExtractorCursor;+ endDate?: Date;+ ignoreExtracted?: boolean;+ limit?: number;+ startDate?: Date;+ } = {},+ ) => {+ const cursorCondition = options.cursor+ ? and(+ ne(topics.id, options.cursor.id),+ or(+ gt(topics.createdAt, options.cursor.createdAt),+ and(eq(topics.createdAt, options.cursor.createdAt), gt(topics.id, options.cursor.id)),+ ),+ )+ : undefined;++ return this.db.query.topics.findMany({+ columns: {+ createdAt: true,+ id: true,+ metadata: true,+ userId: true,+ },+ limit: options.limit,+ orderBy: (fields, { asc }) => [asc(fields.createdAt), asc(fields.id)],+ where: and(+ eq(topics.userId, this.userId),+ options.startDate ? gte(topics.createdAt, options.startDate) : undefined,+ options.endDate ? lte(topics.createdAt, options.endDate) : undefined,+ options.ignoreExtracted+ ? undefined+ : or(+ isNull(topics.metadata),+ sql`(${topics.metadata}->'memory_user_memory_extract'->>'extract_status') IS DISTINCT FROM 'completed'`,+ ),+ cursorCondition,+ ),+ });+ };}diff --git a/packages/database/src/repositories/agentGroup/index.test.ts b/packages/database/src/repositories/agentGroup/index.test.tsnew file mode 100644index 00000000000..1c4a0f2f8e4--- /dev/null+++ b/packages/database/src/repositories/agentGroup/index.test.ts@@ -0,0 +1,522 @@+// @vitest-environment node+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import { beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../models/__tests__/_util';+import { agents } from '../../schemas/agent';+import { chatGroups, chatGroupsAgents } from '../../schemas/chatGroup';+import { users } from '../../schemas/user';+import { LobeChatDatabase } from '../../type';+import { AgentGroupRepository } from './index';++const userId = 'agent-group-test-user';+const otherUserId = 'other-agent-group-user';++let agentGroupRepo: AgentGroupRepository;++const serverDB: LobeChatDatabase = await getTestDB();++beforeEach(async () => {+ // Clean up+ await serverDB.delete(users);++ // Create test users+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);++ // Initialize repo+ agentGroupRepo = new AgentGroupRepository(serverDB, userId);+});++describe('AgentGroupRepository', () => {+ describe('findByIdWithAgents', () => {+ it('should return group with its agents (including auto-created supervisor)', async () => {+ // Create test data+ await serverDB.insert(chatGroups).values({+ description: 'Test group description',+ id: 'test-group-1',+ title: 'Test Group',+ userId,+ });++ await serverDB.insert(agents).values([+ {+ avatar: 'avatar1.png',+ description: 'Agent 1 description',+ id: 'agent-1',+ title: 'Agent 1',+ userId,+ },+ {+ avatar: 'avatar2.png',+ description: 'Agent 2 description',+ id: 'agent-2',+ title: 'Agent 2',+ userId,+ },+ ]);++ // Link agents to group with order (as participants)+ await serverDB.insert(chatGroupsAgents).values([+ { agentId: 'agent-1', chatGroupId: 'test-group-1', order: 1, role: 'participant', userId },+ { agentId: 'agent-2', chatGroupId: 'test-group-1', order: 0, role: 'participant', userId },+ ]);++ const result = await agentGroupRepo.findByIdWithAgents('test-group-1');++ expect(result).toMatchObject({+ description: 'Test group description',+ id: 'test-group-1',+ title: 'Test Group',+ });+ // 2 participants + 1 auto-created supervisor+ expect(result!.agents).toHaveLength(3);+ expect(result!.supervisorAgentId).toBeDefined();++ // Verify agents structure: supervisor first, then participants ordered by order field+ expect(result!.agents).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ isSupervisor: true, title: 'Supervisor', virtual: true }),+ expect.objectContaining({ id: 'agent-1', isSupervisor: false, title: 'Agent 1' }),+ expect.objectContaining({ id: 'agent-2', isSupervisor: false, title: 'Agent 2' }),+ ]),+ );+ });++ it('should return null for non-existent group', async () => {+ const result = await agentGroupRepo.findByIdWithAgents('non-existent-group');++ expect(result).toBeNull();+ });++ it('should auto-create supervisor when no agents assigned', async () => {+ await serverDB.insert(chatGroups).values({+ id: 'empty-group',+ title: 'Empty Group',+ userId,+ });++ const result = await agentGroupRepo.findByIdWithAgents('empty-group');++ expect(result).toMatchObject({+ id: 'empty-group',+ title: 'Empty Group',+ });+ expect(result!.supervisorAgentId).toBeDefined();+ // Should have auto-created supervisor+ expect(result!.agents).toEqual([+ expect.objectContaining({ isSupervisor: true, title: 'Supervisor', virtual: true }),+ ]);+ });++ it('should not return groups belonging to other users', async () => {+ // Create group for other user+ await serverDB.insert(chatGroups).values({+ id: 'other-user-group',+ title: 'Other User Group',+ userId: otherUserId,+ });++ const result = await agentGroupRepo.findByIdWithAgents('other-user-group');++ expect(result).toBeNull();+ });++ it('should return full agent details including all fields', async () => {+ // Create supervisor agent first+ await serverDB.insert(agents).values({+ id: 'detail-supervisor',+ title: 'Supervisor',+ userId,+ virtual: true,+ });++ // Create group+ await serverDB.insert(chatGroups).values({+ config: { scene: 'casual' },+ id: 'detail-group',+ title: 'Detail Group',+ userId,+ });++ // Create agent with all fields+ await serverDB.insert(agents).values({+ avatar: 'test-avatar.png',+ backgroundColor: '#ff0000',+ description: 'Full agent description',+ id: 'full-agent',+ model: 'gpt-4',+ provider: 'openai',+ systemRole: 'You are a helpful assistant',+ title: 'Full Agent',+ userId,+ });++ // Link supervisor and participant agents+ await serverDB.insert(chatGroupsAgents).values([+ {+ agentId: 'detail-supervisor',+ chatGroupId: 'detail-group',+ order: -1,+ role: 'supervisor',+ userId,+ },+ {+ agentId: 'full-agent',+ chatGroupId: 'detail-group',+ order: 0,+ role: 'participant',+ userId,+ },+ ]);++ const result = await agentGroupRepo.findByIdWithAgents('detail-group');++ expect(result).toMatchObject({+ id: 'detail-group',+ supervisorAgentId: 'detail-supervisor',+ title: 'Detail Group',+ });+ // 1 supervisor + 1 participant+ expect(result!.agents).toHaveLength(2);++ // Verify agents include full details+ expect(result!.agents).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ id: 'detail-supervisor', isSupervisor: true, virtual: true }),+ expect.objectContaining({+ avatar: 'test-avatar.png',+ backgroundColor: '#ff0000',+ description: 'Full agent description',+ id: 'full-agent',+ isSupervisor: false,+ model: 'gpt-4',+ provider: 'openai',+ systemRole: 'You are a helpful assistant',+ title: 'Full Agent',+ }),+ ]),+ );+ });++ it('should return group with config', async () => {+ await serverDB.insert(chatGroups).values({+ config: {+ maxResponseInRow: 3,+ responseOrder: 'sequential',+ scene: 'productive',+ },+ description: 'Group with config',+ id: 'config-group',+ pinned: true,+ title: 'Config Group',+ userId,+ });++ const result = await agentGroupRepo.findByIdWithAgents('config-group');++ expect(result).not.toBeNull();+ expect(result!.config).toEqual({+ maxResponseInRow: 3,+ responseOrder: 'sequential',+ scene: 'productive',+ });+ expect(result!.pinned).toBe(true);+ });++ it('should return supervisorAgentId when supervisor exists', async () => {+ // Create group+ await serverDB.insert(chatGroups).values({+ id: 'supervisor-group',+ title: 'Group with Supervisor',+ userId,+ });++ // Create supervisor and participant agents+ await serverDB.insert(agents).values([+ { id: 'supervisor-agent', title: 'Supervisor', userId, virtual: true },+ { id: 'participant-agent', title: 'Participant', userId },+ ]);++ // Link agents with roles+ await serverDB.insert(chatGroupsAgents).values([+ {+ agentId: 'supervisor-agent',+ chatGroupId: 'supervisor-group',+ order: -1,+ role: 'supervisor',+ userId,+ },+ {+ agentId: 'participant-agent',+ chatGroupId: 'supervisor-group',+ order: 0,+ role: 'participant',+ userId,+ },+ ]);++ const result = await agentGroupRepo.findByIdWithAgents('supervisor-group');++ expect(result).toMatchObject({+ id: 'supervisor-group',+ supervisorAgentId: 'supervisor-agent',+ });+ expect(result!.agents).toHaveLength(2);++ // Verify agents order: supervisor first due to order: -1+ expect(result!.agents).toEqual([+ expect.objectContaining({ id: 'supervisor-agent', isSupervisor: true }),+ expect.objectContaining({ id: 'participant-agent', isSupervisor: false }),+ ]);+ });++ it('should auto-create virtual supervisor when no supervisor exists', async () => {+ // Create group without supervisor+ await serverDB.insert(chatGroups).values({+ config: {+ orchestratorModel: 'gpt-4o',+ orchestratorProvider: 'openai',+ scene: 'casual',+ },+ id: 'no-supervisor-group',+ title: 'Group without Supervisor',+ userId,+ });++ await serverDB.insert(agents).values({+ id: 'regular-agent',+ title: 'Regular Agent',+ userId,+ });++ await serverDB.insert(chatGroupsAgents).values({+ agentId: 'regular-agent',+ chatGroupId: 'no-supervisor-group',+ role: 'participant',+ userId,+ });++ const result = await agentGroupRepo.findByIdWithAgents('no-supervisor-group');++ expect(result).toMatchObject({+ id: 'no-supervisor-group',+ title: 'Group without Supervisor',+ });+ // Supervisor should be auto-created+ expect(result!.supervisorAgentId).toBeDefined();+ // Should have 2 agents: auto-created supervisor + regular agent+ expect(result!.agents).toHaveLength(2);++ // Verify agents include auto-created supervisor with config from group+ expect(result!.agents).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ isSupervisor: true,+ model: 'gpt-4o',+ provider: 'openai',+ title: 'Supervisor',+ virtual: true,+ }),+ expect.objectContaining({+ id: 'regular-agent',+ isSupervisor: false,+ title: 'Regular Agent',+ }),+ ]),+ );++ // Calling again should return the same supervisor (not create another one)+ const result2 = await agentGroupRepo.findByIdWithAgents('no-supervisor-group');+ expect(result2!.supervisorAgentId).toBe(result!.supervisorAgentId);+ expect(result2!.agents).toHaveLength(2);+ });++ it('should auto-create supervisor for group with empty agents', async () => {+ await serverDB.insert(chatGroups).values({+ id: 'empty-agents-group',+ title: 'Empty Agents Group',+ userId,+ });++ const result = await agentGroupRepo.findByIdWithAgents('empty-agents-group');++ expect(result).toMatchObject({+ id: 'empty-agents-group',+ title: 'Empty Agents Group',+ });+ expect(result!.supervisorAgentId).toBeDefined();+ // Only the auto-created supervisor+ expect(result!.agents).toEqual([+ expect.objectContaining({ isSupervisor: true, title: 'Supervisor', virtual: true }),+ ]);+ });++ it('should inject group-supervisor slug for supervisor agent', async () => {+ // Create group+ await serverDB.insert(chatGroups).values({+ id: 'slug-test-group',+ title: 'Slug Test Group',+ userId,+ });++ // Create supervisor and participant agents+ await serverDB.insert(agents).values([+ { id: 'slug-supervisor', slug: null, title: 'Supervisor', userId, virtual: true },+ { id: 'slug-participant', slug: 'custom-slug', title: 'Participant', userId },+ ]);++ // Link agents with roles+ await serverDB.insert(chatGroupsAgents).values([+ {+ agentId: 'slug-supervisor',+ chatGroupId: 'slug-test-group',+ order: -1,+ role: 'supervisor',+ userId,+ },+ {+ agentId: 'slug-participant',+ chatGroupId: 'slug-test-group',+ order: 0,+ role: 'participant',+ userId,+ },+ ]);++ const result = await agentGroupRepo.findByIdWithAgents('slug-test-group');++ expect(result).not.toBeNull();+ expect(result!.agents).toHaveLength(2);++ // Verify supervisor has injected slug+ const supervisor = result!.agents.find((a) => a.isSupervisor);+ expect(supervisor).toBeDefined();+ expect(supervisor!.slug).toBe(BUILTIN_AGENT_SLUGS.groupSupervisor);++ // Verify participant keeps original slug+ const participant = result!.agents.find((a) => !a.isSupervisor);+ expect(participant).toBeDefined();+ expect(participant!.slug).toBe('custom-slug');+ });++ it('should inject group-supervisor slug for auto-created supervisor', async () => {+ await serverDB.insert(chatGroups).values({+ id: 'auto-slug-group',+ title: 'Auto Slug Group',+ userId,+ });++ const result = await agentGroupRepo.findByIdWithAgents('auto-slug-group');++ expect(result).not.toBeNull();+ expect(result!.agents).toHaveLength(1);++ // Verify auto-created supervisor has injected slug+ const supervisor = result!.agents[0];+ expect(supervisor.isSupervisor).toBe(true);+ expect(supervisor.slug).toBe(BUILTIN_AGENT_SLUGS.groupSupervisor);+ });+ });++ describe('createGroupWithSupervisor', () => {+ it('should create group with supervisor agent', async () => {+ const result = await agentGroupRepo.createGroupWithSupervisor({+ config: {+ orchestratorModel: 'gpt-4',+ orchestratorProvider: 'openai',+ scene: 'productive',+ },+ title: 'New Group with Supervisor',+ });++ expect(result).toMatchObject({+ group: expect.objectContaining({ title: 'New Group with Supervisor' }),+ });+ expect(result.supervisorAgentId).toBeDefined();+ expect(result.agents).toEqual([expect.objectContaining({ role: 'supervisor' })]);++ // Verify supervisor agent was created with correct config+ const groupDetail = await agentGroupRepo.findByIdWithAgents(result.group.id);+ expect(groupDetail).toMatchObject({+ supervisorAgentId: result.supervisorAgentId,+ });+ expect(groupDetail!.agents).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: result.supervisorAgentId,+ model: 'gpt-4',+ provider: 'openai',+ title: 'Supervisor',+ virtual: true,+ }),+ ]),+ );+ });++ it('should create group with supervisor and member agents', async () => {+ // Create member agents first+ await serverDB.insert(agents).values([+ { id: 'member-1', title: 'Member 1', userId },+ { id: 'member-2', title: 'Member 2', userId },+ ]);++ const result = await agentGroupRepo.createGroupWithSupervisor(+ { title: 'Group with Members' },+ ['member-1', 'member-2'],+ );++ expect(result).toMatchObject({+ group: expect.objectContaining({ title: 'Group with Members' }),+ });+ expect(result.supervisorAgentId).toBeDefined();+ // 1 supervisor + 2 members+ expect(result.agents).toHaveLength(3);++ // Check roles and order+ expect(result.agents).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ order: -1, role: 'supervisor' }),+ expect.objectContaining({ agentId: 'member-1', order: 0, role: 'participant' }),+ expect.objectContaining({ agentId: 'member-2', order: 1, role: 'participant' }),+ ]),+ );+ });++ it('should use custom supervisor config when provided', async () => {+ const result = await agentGroupRepo.createGroupWithSupervisor(+ { title: 'Custom Supervisor Group' },+ [],+ {+ model: 'claude-3-opus',+ provider: 'anthropic',+ title: 'Custom Host',+ },+ );++ const groupDetail = await agentGroupRepo.findByIdWithAgents(result.group.id);+ expect(groupDetail!.agents).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: result.supervisorAgentId,+ model: 'claude-3-opus',+ provider: 'anthropic',+ title: 'Custom Host',+ }),+ ]),+ );+ });++ it('should create group with empty member agents', async () => {+ const result = await agentGroupRepo.createGroupWithSupervisor({+ title: 'Supervisor Only Group',+ });++ expect(result).toMatchObject({+ group: expect.objectContaining({ title: 'Supervisor Only Group' }),+ });+ expect(result.supervisorAgentId).toBeDefined();+ // Only supervisor+ expect(result.agents).toEqual([expect.objectContaining({ role: 'supervisor' })]);+ });+ });+});diff --git a/packages/database/src/repositories/agentGroup/index.ts b/packages/database/src/repositories/agentGroup/index.tsnew file mode 100644index 00000000000..1257ffb5a9e--- /dev/null+++ b/packages/database/src/repositories/agentGroup/index.ts@@ -0,0 +1,307 @@+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import { AgentGroupDetail, AgentGroupMember } from '@lobechat/types';+import { cleanObject } from '@lobechat/utils';+import { and, eq, inArray } from 'drizzle-orm';++import {+ AgentItem,+ ChatGroupItem,+ NewChatGroup,+ NewChatGroupAgent,+ agents,+ chatGroups,+ chatGroupsAgents,+} from '../../schemas';+import { LobeChatDatabase } from '../../type';+import { ChatGroupConfig } from '../../types/chatGroup';++export interface SupervisorAgentConfig {+ model?: string;+ provider?: string;+ title?: string;+}++/**+ * Result of checking agents before removal+ */+export interface RemoveAgentsCheckResult {+ /** Agent IDs that are not virtual and can be safely removed from group */+ nonVirtualAgentIds: string[];+ /** Virtual agents that will be permanently deleted along with their messages */+ virtualAgents: Array<Pick<AgentItem, 'avatar' | 'description' | 'id' | 'title'>>;+}++/**+ * Result of removing agents from group+ */+export interface RemoveAgentsFromGroupResult {+ /** IDs of virtual agents that were permanently deleted */+ deletedVirtualAgentIds: string[];+ /** Number of agents removed from group */+ removedFromGroup: number;+}++export interface CreateGroupWithSupervisorResult {+ agents: NewChatGroupAgent[];+ group: ChatGroupItem;+ supervisorAgentId: string;+}++/**+ * Agent Group Repository - provides agent group detail data+ */+export class AgentGroupRepository {+ private userId: string;+ private db: LobeChatDatabase;++ constructor(db: LobeChatDatabase, userId: string) {+ this.userId = userId;+ this.db = db;+ }++ /**+ * Find a chat group by ID with its associated agents.+ * If no supervisor exists, a virtual supervisor agent is automatically created.+ * @param groupId - The chat group ID+ * @returns AgentGroupDetail with group info, agents array, and supervisor agent ID+ */+ async findByIdWithAgents(groupId: string): Promise<AgentGroupDetail | null> {+ // 1. Find the group+ const group = await this.db.query.chatGroups.findFirst({+ where: and(eq(chatGroups.id, groupId), eq(chatGroups.userId, this.userId)),+ });++ if (!group) return null;++ // 2. Find all agents associated with this group (including role info)+ const groupAgentsWithDetails = await this.db+ .select({+ agent: agents,+ order: chatGroupsAgents.order,+ role: chatGroupsAgents.role,+ })+ .from(chatGroupsAgents)+ .innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))+ .where(eq(chatGroupsAgents.chatGroupId, groupId))+ .orderBy(chatGroupsAgents.order);++ // 3. Extract agent items with isSupervisor flag and find supervisor+ const agentItems: AgentGroupMember[] = [];+ let supervisorAgentId: string | undefined;++ for (const row of groupAgentsWithDetails) {+ const isSupervisor = row.role === 'supervisor';+ agentItems.push(+ cleanObject({+ ...row.agent,+ isSupervisor,+ // Inject builtin agent slug for supervisor+ slug: isSupervisor ? BUILTIN_AGENT_SLUGS.groupSupervisor : row.agent.slug,+ }) as AgentGroupMember,+ );+ if (isSupervisor) {+ supervisorAgentId = row.agent.id;+ }+ }++ // 4. If no supervisor exists, create a virtual supervisor agent+ if (!supervisorAgentId) {+ const groupConfig = group.config as ChatGroupConfig | undefined;++ // Create supervisor agent (virtual agent)+ const [supervisorAgent] = await this.db+ .insert(agents)+ .values({+ model: groupConfig?.orchestratorModel,+ provider: groupConfig?.orchestratorProvider,+ title: 'Supervisor',+ userId: this.userId,+ virtual: true,+ })+ .returning();++ // Add supervisor agent to group with role 'supervisor'+ await this.db.insert(chatGroupsAgents).values({+ agentId: supervisorAgent.id,+ chatGroupId: group.id,+ order: -1, // Supervisor always first (negative order)+ role: 'supervisor',+ userId: this.userId,+ });++ supervisorAgentId = supervisorAgent.id;++ // Insert at the beginning of agents array+ agentItems.unshift(+ cleanObject({+ ...supervisorAgent,+ isSupervisor: true,+ // Inject builtin agent slug for supervisor+ slug: BUILTIN_AGENT_SLUGS.groupSupervisor,+ }) as AgentGroupMember,+ );+ }++ return {+ ...group,+ agents: agentItems,+ supervisorAgentId,+ } as AgentGroupDetail;+ }++ /**+ * Create a chat group with a supervisor agent and optional member agents.+ * The supervisor agent is automatically created as a virtual agent with role 'supervisor'.+ *+ * @param groupParams - Parameters for creating the chat group+ * @param agentMembers - Array of existing agent IDs to add as members (optional)+ * @param supervisorConfig - Optional configuration for the supervisor agent+ * @returns Created group, agents, and supervisor agent ID+ */+ async createGroupWithSupervisor(+ groupParams: Omit<NewChatGroup, 'userId'>,+ agentMembers: string[] = [],+ supervisorConfig?: SupervisorAgentConfig,+ ): Promise<CreateGroupWithSupervisorResult> {+ const groupConfig = groupParams.config as ChatGroupConfig | undefined;++ // 1. Create supervisor agent (virtual agent)+ const [supervisorAgent] = await this.db+ .insert(agents)+ .values({+ model: supervisorConfig?.model ?? groupConfig?.orchestratorModel,+ provider: supervisorConfig?.provider ?? groupConfig?.orchestratorProvider,+ title: supervisorConfig?.title ?? 'Supervisor',+ userId: this.userId,+ virtual: true,+ })+ .returning();++ // 2. Create the group+ const [group] = await this.db+ .insert(chatGroups)+ .values({ ...groupParams, userId: this.userId })+ .returning();++ // 3. Add supervisor agent to group with role 'supervisor'+ const supervisorGroupAgent: NewChatGroupAgent = {+ agentId: supervisorAgent.id,+ chatGroupId: group.id,+ order: -1, // Supervisor always first (negative order)+ role: 'supervisor',+ userId: this.userId,+ };++ // 4. Add member agents to group with role 'participant'+ const memberGroupAgents: NewChatGroupAgent[] = agentMembers.map((agentId, index) => ({+ agentId,+ chatGroupId: group.id,+ order: index,+ role: 'participant',+ userId: this.userId,+ }));++ // 5. Insert all group-agent relationships+ const allGroupAgents = [supervisorGroupAgent, ...memberGroupAgents];+ const insertedAgents = await this.db+ .insert(chatGroupsAgents)+ .values(allGroupAgents)+ .returning();++ return {+ agents: insertedAgents,+ group,+ supervisorAgentId: supervisorAgent.id,+ };+ }++ /**+ * Check which agents are virtual before removing them from a group.+ * This allows the frontend to show a confirmation dialog for virtual agents.+ *+ * @param groupId - The chat group ID+ * @param agentIds - Array of agent IDs to check+ * @returns Object containing virtual and non-virtual agent lists+ */+ async checkAgentsBeforeRemoval(+ groupId: string,+ agentIds: string[],+ ): Promise<RemoveAgentsCheckResult> {+ if (agentIds.length === 0) {+ return { nonVirtualAgentIds: [], virtualAgents: [] };+ }++ // Get agent details for the specified IDs+ const agentDetails = await this.db+ .select({+ avatar: agents.avatar,+ description: agents.description,+ id: agents.id,+ title: agents.title,+ virtual: agents.virtual,+ })+ .from(agents)+ .where(and(eq(agents.userId, this.userId), inArray(agents.id, agentIds)));++ const virtualAgents: RemoveAgentsCheckResult['virtualAgents'] = [];+ const nonVirtualAgentIds: string[] = [];++ for (const agent of agentDetails) {+ if (agent.virtual) {+ virtualAgents.push({+ avatar: agent.avatar,+ description: agent.description,+ id: agent.id,+ title: agent.title,+ });+ } else {+ nonVirtualAgentIds.push(agent.id);+ }+ }++ return { nonVirtualAgentIds, virtualAgents };+ }++ /**+ * Remove agents from a group. Virtual agents will be permanently deleted.+ *+ * @param groupId - The chat group ID+ * @param agentIds - Array of agent IDs to remove+ * @param deleteVirtualAgents - Whether to delete virtual agents (default: true)+ * @returns Result containing counts and deleted virtual agent IDs+ */+ async removeAgentsFromGroup(+ groupId: string,+ agentIds: string[],+ deleteVirtualAgents: boolean = true,+ ): Promise<RemoveAgentsFromGroupResult> {+ if (agentIds.length === 0) {+ return { deletedVirtualAgentIds: [], removedFromGroup: 0 };+ }++ // 1. Check which agents are virtual+ const { virtualAgents } = await this.checkAgentsBeforeRemoval(groupId, agentIds);+ const virtualAgentIds = virtualAgents.map((a) => a.id);++ // 2. Remove all agents from the group (batch delete from junction table)+ await this.db+ .delete(chatGroupsAgents)+ .where(+ and(eq(chatGroupsAgents.chatGroupId, groupId), inArray(chatGroupsAgents.agentId, agentIds)),+ );++ // 3. Delete virtual agents if requested+ // Note: Virtual agents are standalone (no associated sessions), so we can delete them directly+ // The messages sent by these agents in the group chat will remain (orphaned agentId reference)+ if (deleteVirtualAgents && virtualAgentIds.length > 0) {+ await this.db+ .delete(agents)+ .where(and(eq(agents.userId, this.userId), inArray(agents.id, virtualAgentIds)));+ }++ return {+ deletedVirtualAgentIds: deleteVirtualAgents ? virtualAgentIds : [],+ removedFromGroup: agentIds.length,+ };+ }+}diff --git a/packages/database/src/repositories/agentMigration/__tests__/agentMigrationRepo.test.ts b/packages/database/src/repositories/agentMigration/__tests__/agentMigrationRepo.test.tsnew file mode 100644index 00000000000..96168ee441c--- /dev/null+++ b/packages/database/src/repositories/agentMigration/__tests__/agentMigrationRepo.test.ts@@ -0,0 +1,762 @@+import { eq, inArray } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../models/__tests__/_util';+import { agents, messages, sessions, topics, users } from '../../../schemas';+import { LobeChatDatabase } from '../../../type';+import { AgentMigrationRepo } from '../index';++const userId = 'agent-migration-user';+const userId2 = 'agent-migration-user-2';+const sessionId = 'agent-migration-session';+const serverDB: LobeChatDatabase = await getTestDB();+const agentMigrationRepo = new AgentMigrationRepo(serverDB, userId);++describe('AgentMigrationRepo', () => {+ 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('migrateAgentId - inbox migration', () => {+ it('should migrate legacy inbox topics and their messages', async () => {+ const agentId = 'inbox-agent-id';+ await serverDB.insert(agents).values({ id: agentId, userId });++ // Create legacy inbox topics+ const originalUpdatedAt = new Date('2024-01-01T00:00:00Z');+ await serverDB.insert(topics).values([+ {+ id: 'inbox-topic-1',+ userId,+ title: 'Legacy inbox topic 1',+ sessionId: null,+ groupId: null,+ agentId: null,+ updatedAt: originalUpdatedAt,+ },+ {+ id: 'inbox-topic-2',+ userId,+ title: 'Legacy inbox topic 2',+ sessionId: null,+ groupId: null,+ agentId: null,+ updatedAt: originalUpdatedAt,+ },+ ]);++ // Create messages associated with these topics+ await serverDB.insert(messages).values([+ { id: 'msg-1', userId, role: 'user', topicId: 'inbox-topic-1', agentId: null },+ { id: 'msg-2', userId, role: 'assistant', topicId: 'inbox-topic-1', agentId: null },+ { id: 'msg-3', userId, role: 'user', topicId: 'inbox-topic-2', agentId: null },+ ]);++ // Create inbox messages without topicId+ await serverDB.insert(messages).values([+ {+ id: 'msg-inbox-no-topic',+ userId,+ role: 'user',+ sessionId: null,+ topicId: null,+ agentId: null,+ },+ ]);++ // Run migration+ await agentMigrationRepo.migrateAgentId({ agentId, isInbox: true });++ // Verify topics are migrated+ const migratedTopics = await serverDB.query.topics.findMany({+ where: eq(topics.userId, userId),+ });++ expect(migratedTopics).toHaveLength(2);+ migratedTopics.forEach((topic) => {+ expect(topic.agentId).toBe(agentId);+ // updatedAt should be preserved+ expect(topic.updatedAt.getTime()).toBe(originalUpdatedAt.getTime());+ });++ // Verify messages are migrated+ const migratedMessages = await serverDB.query.messages.findMany({+ where: eq(messages.userId, userId),+ });++ expect(migratedMessages).toHaveLength(4);+ migratedMessages.forEach((msg) => {+ expect(msg.agentId).toBe(agentId);+ });+ });++ it('should not migrate topics that already have agentId', async () => {+ const agentId = 'inbox-agent-id';+ const existingAgentId = 'existing-agent-id';+ await serverDB.insert(agents).values([+ { id: agentId, userId },+ { id: existingAgentId, userId },+ ]);++ // Create a topic that already has agentId+ await serverDB.insert(topics).values({+ id: 'topic-with-agent',+ userId,+ title: 'Topic with agent',+ agentId: existingAgentId,+ });++ // Run migration+ await agentMigrationRepo.migrateAgentId({ agentId, isInbox: true });++ // Verify topic was not changed+ const topic = await serverDB.query.topics.findFirst({+ where: eq(topics.id, 'topic-with-agent'),+ });++ expect(topic?.agentId).toBe(existingAgentId);+ });++ it('should not migrate messages that already have agentId', async () => {+ const agentId = 'inbox-agent-id';+ const existingAgentId = 'existing-agent-id';+ await serverDB.insert(agents).values([+ { id: agentId, userId },+ { id: existingAgentId, userId },+ ]);++ // Create legacy inbox topic+ await serverDB.insert(topics).values({+ id: 'inbox-topic',+ userId,+ sessionId: null,+ groupId: null,+ agentId: null,+ });++ // Create messages - one with agentId, one without+ await serverDB.insert(messages).values([+ {+ id: 'msg-with-agent',+ userId,+ role: 'user',+ topicId: 'inbox-topic',+ agentId: existingAgentId,+ },+ { id: 'msg-without-agent', userId, role: 'user', topicId: 'inbox-topic', agentId: null },+ ]);++ // Run migration+ await agentMigrationRepo.migrateAgentId({ agentId, isInbox: true });++ // Verify message with agentId was not changed+ const msgWithAgent = await serverDB.query.messages.findFirst({+ where: eq(messages.id, 'msg-with-agent'),+ });+ expect(msgWithAgent?.agentId).toBe(existingAgentId);++ // Verify message without agentId was migrated+ const msgWithoutAgent = await serverDB.query.messages.findFirst({+ where: eq(messages.id, 'msg-without-agent'),+ });+ expect(msgWithoutAgent?.agentId).toBe(agentId);+ });++ it('should not migrate other user topics or messages', async () => {+ const agentId = 'inbox-agent-id';+ await serverDB.insert(agents).values({ id: agentId, userId });++ // Create legacy inbox topic for user2+ await serverDB.insert(topics).values({+ id: 'user2-topic',+ userId: userId2,+ title: 'User2 legacy inbox topic',+ sessionId: null,+ groupId: null,+ agentId: null,+ });++ // Create message for user2+ await serverDB.insert(messages).values({+ id: 'user2-msg',+ userId: userId2,+ role: 'user',+ topicId: 'user2-topic',+ agentId: null,+ });++ // Run migration for user1+ await agentMigrationRepo.migrateAgentId({ agentId, isInbox: true });++ // Verify user2's topic was not migrated+ const topic = await serverDB.query.topics.findFirst({+ where: eq(topics.id, 'user2-topic'),+ });+ expect(topic?.agentId).toBeNull();++ // Verify user2's message was not migrated+ const msg = await serverDB.query.messages.findFirst({+ where: eq(messages.id, 'user2-msg'),+ });+ expect(msg?.agentId).toBeNull();+ });++ it('should migrate both orphan and sessionId-based legacy data when isInbox with sessionId', async () => {+ const agentId = 'inbox-combined-agent';+ const inboxSessionId = 'inbox-combined-session';+ await serverDB.insert(agents).values({ id: agentId, userId });+ await serverDB.insert(sessions).values({ id: inboxSessionId, userId, slug: 'inbox' });++ // Create orphan legacy inbox topics (sessionId IS NULL, groupId IS NULL, agentId IS NULL)+ await serverDB.insert(topics).values([+ {+ id: 'orphan-inbox-topic-1',+ userId,+ title: 'Orphan inbox topic 1',+ sessionId: null,+ groupId: null,+ agentId: null,+ },+ {+ id: 'orphan-inbox-topic-2',+ userId,+ title: 'Orphan inbox topic 2',+ sessionId: null,+ groupId: null,+ agentId: null,+ },+ ]);++ // Create sessionId-based legacy topics (has sessionId but no agentId)+ await serverDB.insert(topics).values([+ {+ id: 'session-based-topic-1',+ userId,+ title: 'Session-based topic 1',+ sessionId: inboxSessionId,+ groupId: null,+ agentId: null,+ },+ {+ id: 'session-based-topic-2',+ userId,+ title: 'Session-based topic 2',+ sessionId: inboxSessionId,+ groupId: null,+ agentId: null,+ },+ ]);++ // Create messages for orphan topics+ await serverDB.insert(messages).values([+ {+ id: 'orphan-msg-1',+ userId,+ role: 'user',+ topicId: 'orphan-inbox-topic-1',+ sessionId: null,+ agentId: null,+ },+ {+ id: 'orphan-msg-no-topic',+ userId,+ role: 'user',+ sessionId: null,+ topicId: null,+ agentId: null,+ },+ ]);++ // Create messages for session-based topics+ await serverDB.insert(messages).values([+ {+ id: 'session-based-msg-1',+ userId,+ role: 'user',+ topicId: 'session-based-topic-1',+ sessionId: null,+ agentId: null,+ },+ {+ id: 'session-msg-no-topic',+ userId,+ role: 'user',+ sessionId: inboxSessionId,+ topicId: null,+ agentId: null,+ },+ ]);++ // Run migration with isInbox and sessionId+ await agentMigrationRepo.migrateAgentId({+ agentId,+ isInbox: true,+ sessionId: inboxSessionId,+ });++ // Verify all orphan topics are migrated+ const orphanTopics = await serverDB.query.topics.findMany({+ where: inArray(topics.id, ['orphan-inbox-topic-1', 'orphan-inbox-topic-2']),+ });+ expect(orphanTopics).toHaveLength(2);+ orphanTopics.forEach((topic) => {+ expect(topic.agentId).toBe(agentId);+ });++ // Verify all session-based topics are migrated+ const sessionBasedTopics = await serverDB.query.topics.findMany({+ where: inArray(topics.id, ['session-based-topic-1', 'session-based-topic-2']),+ });+ expect(sessionBasedTopics).toHaveLength(2);+ sessionBasedTopics.forEach((topic) => {+ expect(topic.agentId).toBe(agentId);+ });++ // Verify all messages are migrated+ const allMessages = await serverDB.query.messages.findMany({+ where: inArray(messages.id, [+ 'orphan-msg-1',+ 'orphan-msg-no-topic',+ 'session-based-msg-1',+ 'session-msg-no-topic',+ ]),+ });+ expect(allMessages).toHaveLength(4);+ allMessages.forEach((msg) => {+ expect(msg.agentId).toBe(agentId);+ });+ });++ it('should preserve messages updatedAt during inbox migration', async () => {+ const agentId = 'inbox-agent-preserve-time';+ await serverDB.insert(agents).values({ id: agentId, userId });++ // Create legacy inbox topic+ const originalTopicUpdatedAt = new Date('2024-01-15T10:00:00Z');+ await serverDB.insert(topics).values({+ id: 'inbox-topic-preserve',+ userId,+ sessionId: null,+ groupId: null,+ agentId: null,+ updatedAt: originalTopicUpdatedAt,+ });++ // Create messages with specific updatedAt+ const originalMsgUpdatedAt1 = new Date('2024-02-20T14:30:00Z');+ const originalMsgUpdatedAt2 = new Date('2024-03-10T09:15:00Z');+ const originalMsgUpdatedAtNoTopic = new Date('2024-04-05T16:45:00Z');++ await serverDB.insert(messages).values([+ {+ id: 'msg-preserve-1',+ userId,+ role: 'user',+ topicId: 'inbox-topic-preserve',+ agentId: null,+ updatedAt: originalMsgUpdatedAt1,+ },+ {+ id: 'msg-preserve-2',+ userId,+ role: 'assistant',+ topicId: 'inbox-topic-preserve',+ agentId: null,+ updatedAt: originalMsgUpdatedAt2,+ },+ {+ id: 'msg-preserve-no-topic',+ userId,+ role: 'user',+ sessionId: null,+ topicId: null,+ agentId: null,+ updatedAt: originalMsgUpdatedAtNoTopic,+ },+ ]);++ // Run migration+ await agentMigrationRepo.migrateAgentId({ agentId, isInbox: true });++ // Verify topic updatedAt is preserved+ const migratedTopic = await serverDB.query.topics.findFirst({+ where: eq(topics.id, 'inbox-topic-preserve'),+ });+ expect(migratedTopic?.agentId).toBe(agentId);+ expect(migratedTopic?.updatedAt.getTime()).toBe(originalTopicUpdatedAt.getTime());++ // Verify messages updatedAt are preserved+ const msg1 = await serverDB.query.messages.findFirst({+ where: eq(messages.id, 'msg-preserve-1'),+ });+ expect(msg1?.agentId).toBe(agentId);+ expect(msg1?.updatedAt.getTime()).toBe(originalMsgUpdatedAt1.getTime());++ const msg2 = await serverDB.query.messages.findFirst({+ where: eq(messages.id, 'msg-preserve-2'),+ });+ expect(msg2?.agentId).toBe(agentId);+ expect(msg2?.updatedAt.getTime()).toBe(originalMsgUpdatedAt2.getTime());++ const msgNoTopic = await serverDB.query.messages.findFirst({+ where: eq(messages.id, 'msg-preserve-no-topic'),+ });+ expect(msgNoTopic?.agentId).toBe(agentId);+ expect(msgNoTopic?.updatedAt.getTime()).toBe(originalMsgUpdatedAtNoTopic.getTime());+ });+ });++ describe('migrateAgentId - session migration', () => {+ it('should migrate topics and messages by sessionId', async () => {+ const agentId = 'test-agent-id';+ await serverDB.insert(agents).values({ id: agentId, userId });++ // Create legacy topics with sessionId but no agentId+ const originalUpdatedAt = new Date('2024-06-15T12:00:00Z');+ await serverDB.insert(topics).values([+ {+ id: 'session-topic-1',+ userId,+ title: 'Legacy session topic 1',+ sessionId,+ agentId: null,+ updatedAt: originalUpdatedAt,+ },+ {+ id: 'session-topic-2',+ userId,+ title: 'Legacy session topic 2',+ sessionId,+ agentId: null,+ updatedAt: originalUpdatedAt,+ },+ ]);++ // Create messages within these topics+ await serverDB.insert(messages).values([+ { id: 'session-msg-1', userId, role: 'user', topicId: 'session-topic-1', agentId: null },+ {+ id: 'session-msg-2',+ userId,+ role: 'assistant',+ topicId: 'session-topic-2',+ agentId: null,+ },+ ]);++ // Create messages with sessionId but no topicId+ await serverDB.insert(messages).values([+ {+ id: 'session-msg-no-topic',+ userId,+ role: 'user',+ sessionId,+ topicId: null,+ agentId: null,+ },+ ]);++ // Run migration+ await agentMigrationRepo.migrateAgentId({ agentId, sessionId });++ // Verify topics are migrated+ const migratedTopics = await serverDB.query.topics.findMany({+ where: eq(topics.sessionId, sessionId),+ });++ expect(migratedTopics).toHaveLength(2);+ migratedTopics.forEach((topic) => {+ expect(topic.agentId).toBe(agentId);+ // updatedAt should be preserved+ expect(topic.updatedAt.getTime()).toBe(originalUpdatedAt.getTime());+ });++ // Verify all messages are migrated+ const migratedMessages = await serverDB+ .select()+ .from(messages)+ .where(inArray(messages.id, ['session-msg-1', 'session-msg-2', 'session-msg-no-topic']));++ expect(migratedMessages).toHaveLength(3);+ migratedMessages.forEach((msg) => {+ expect(msg.agentId).toBe(agentId);+ });+ });++ it('should not migrate topics from different session', async () => {+ const agentId = 'test-agent-id';+ const otherSessionId = 'other-session-id';+ await serverDB.insert(agents).values({ id: agentId, userId });+ await serverDB.insert(sessions).values({ id: otherSessionId, userId });++ // Create topic for different session+ await serverDB.insert(topics).values({+ id: 'other-session-topic',+ userId,+ title: 'Other session topic',+ sessionId: otherSessionId,+ agentId: null,+ });++ // Create message for different session+ await serverDB.insert(messages).values({+ id: 'other-session-msg',+ userId,+ role: 'user',+ sessionId: otherSessionId,+ agentId: null,+ });++ // Run migration for sessionId+ await agentMigrationRepo.migrateAgentId({ agentId, sessionId });++ // Verify other session's topic was not migrated+ const topic = await serverDB.query.topics.findFirst({+ where: eq(topics.id, 'other-session-topic'),+ });+ expect(topic?.agentId).toBeNull();++ // Verify other session's message was not migrated+ const msg = await serverDB.query.messages.findFirst({+ where: eq(messages.id, 'other-session-msg'),+ });+ expect(msg?.agentId).toBeNull();+ });++ it('should not migrate topics or messages that already have agentId', async () => {+ const agentId = 'test-agent-id';+ const existingAgentId = 'existing-agent-id';+ await serverDB.insert(agents).values([+ { id: agentId, userId },+ { id: existingAgentId, userId },+ ]);++ // Create topic that already has agentId+ await serverDB.insert(topics).values({+ id: 'topic-with-agent',+ userId,+ title: 'Topic with existing agent',+ sessionId,+ agentId: existingAgentId,+ });++ // Create message that already has agentId+ await serverDB.insert(messages).values({+ id: 'msg-with-agent',+ userId,+ role: 'user',+ sessionId,+ agentId: existingAgentId,+ });++ // Run migration+ await agentMigrationRepo.migrateAgentId({ agentId, sessionId });++ // Verify topic was not changed+ const topic = await serverDB.query.topics.findFirst({+ where: eq(topics.id, 'topic-with-agent'),+ });+ expect(topic?.agentId).toBe(existingAgentId);++ // Verify message was not changed+ const msg = await serverDB.query.messages.findFirst({+ where: eq(messages.id, 'msg-with-agent'),+ });+ expect(msg?.agentId).toBe(existingAgentId);+ });++ it('should not migrate other user topics or messages', async () => {+ const agentId = 'test-agent-id';+ const user2SessionId = 'user2-session-id';+ await serverDB.insert(agents).values({ id: agentId, userId });+ await serverDB.insert(sessions).values({ id: user2SessionId, userId: userId2 });++ // Create topic for user2+ await serverDB.insert(topics).values({+ id: 'user2-session-topic',+ userId: userId2,+ title: 'User2 session topic',+ sessionId: user2SessionId,+ agentId: null,+ });++ // Create message for user2+ await serverDB.insert(messages).values({+ id: 'user2-session-msg',+ userId: userId2,+ role: 'user',+ sessionId: user2SessionId,+ agentId: null,+ });++ // Run migration for user1+ await agentMigrationRepo.migrateAgentId({ agentId, sessionId: user2SessionId });++ // Verify user2's topic was not migrated+ const topic = await serverDB.query.topics.findFirst({+ where: eq(topics.id, 'user2-session-topic'),+ });+ expect(topic?.agentId).toBeNull();++ // Verify user2's message was not migrated+ const msg = await serverDB.query.messages.findFirst({+ where: eq(messages.id, 'user2-session-msg'),+ });+ expect(msg?.agentId).toBeNull();+ });++ it('should preserve messages updatedAt during session migration', async () => {+ const agentId = 'session-agent-preserve-time';+ await serverDB.insert(agents).values({ id: agentId, userId });++ // Create legacy session topic+ const originalTopicUpdatedAt = new Date('2024-05-20T08:00:00Z');+ await serverDB.insert(topics).values({+ id: 'session-topic-preserve',+ userId,+ sessionId,+ agentId: null,+ updatedAt: originalTopicUpdatedAt,+ });++ // Create messages with specific updatedAt+ const originalMsgUpdatedAt1 = new Date('2024-06-15T11:30:00Z');+ const originalMsgUpdatedAt2 = new Date('2024-07-01T15:45:00Z');+ const originalMsgUpdatedAtNoTopic = new Date('2024-08-10T09:00:00Z');++ await serverDB.insert(messages).values([+ {+ id: 'session-msg-preserve-1',+ userId,+ role: 'user',+ topicId: 'session-topic-preserve',+ agentId: null,+ updatedAt: originalMsgUpdatedAt1,+ },+ {+ id: 'session-msg-preserve-2',+ userId,+ role: 'assistant',+ topicId: 'session-topic-preserve',+ agentId: null,+ updatedAt: originalMsgUpdatedAt2,+ },+ {+ id: 'session-msg-preserve-no-topic',+ userId,+ role: 'user',+ sessionId,+ topicId: null,+ agentId: null,+ updatedAt: originalMsgUpdatedAtNoTopic,+ },+ ]);++ // Run migration+ await agentMigrationRepo.migrateAgentId({ agentId, sessionId });++ // Verify topic updatedAt is preserved+ const migratedTopic = await serverDB.query.topics.findFirst({+ where: eq(topics.id, 'session-topic-preserve'),+ });+ expect(migratedTopic?.agentId).toBe(agentId);+ expect(migratedTopic?.updatedAt.getTime()).toBe(originalTopicUpdatedAt.getTime());++ // Verify messages updatedAt are preserved+ const msg1 = await serverDB.query.messages.findFirst({+ where: eq(messages.id, 'session-msg-preserve-1'),+ });+ expect(msg1?.agentId).toBe(agentId);+ expect(msg1?.updatedAt.getTime()).toBe(originalMsgUpdatedAt1.getTime());++ const msg2 = await serverDB.query.messages.findFirst({+ where: eq(messages.id, 'session-msg-preserve-2'),+ });+ expect(msg2?.agentId).toBe(agentId);+ expect(msg2?.updatedAt.getTime()).toBe(originalMsgUpdatedAt2.getTime());++ const msgNoTopic = await serverDB.query.messages.findFirst({+ where: eq(messages.id, 'session-msg-preserve-no-topic'),+ });+ expect(msgNoTopic?.agentId).toBe(agentId);+ expect(msgNoTopic?.updatedAt.getTime()).toBe(originalMsgUpdatedAtNoTopic.getTime());+ });+ });++ describe('migrateAgentId - transaction integrity', () => {+ it('should migrate topics and messages atomically', async () => {+ const agentId = 'atomic-agent-id';+ await serverDB.insert(agents).values({ id: agentId, userId });++ // Create legacy topics and messages+ await serverDB.insert(topics).values([+ { id: 'atomic-topic-1', userId, sessionId: null, groupId: null, agentId: null },+ { id: 'atomic-topic-2', userId, sessionId: null, groupId: null, agentId: null },+ ]);++ await serverDB.insert(messages).values([+ { id: 'atomic-msg-1', userId, role: 'user', topicId: 'atomic-topic-1', agentId: null },+ { id: 'atomic-msg-2', userId, role: 'user', topicId: 'atomic-topic-2', agentId: null },+ ]);++ // Run migration+ await agentMigrationRepo.migrateAgentId({ agentId, isInbox: true });++ // Verify all topics and messages are migrated together+ const migratedTopics = await serverDB.query.topics.findMany({+ where: eq(topics.userId, userId),+ });+ const migratedMessages = await serverDB.query.messages.findMany({+ where: eq(messages.userId, userId),+ });++ expect(migratedTopics.every((t) => t.agentId === agentId)).toBe(true);+ expect(migratedMessages.every((m) => m.agentId === agentId)).toBe(true);+ });+ });++ describe('getSessionIdByAgentId', () => {+ it('should return sessionId for an agent', async () => {+ const agentId = 'lookup-agent-id';+ const lookupSessionId = 'lookup-session-id';++ await serverDB.insert(agents).values({ id: agentId, userId });+ await serverDB.insert(sessions).values({ id: lookupSessionId, userId });++ // Import agentsToSessions schema+ const { agentsToSessions } = await import('../../../schemas');+ await serverDB.insert(agentsToSessions).values({+ agentId,+ sessionId: lookupSessionId,+ userId,+ });++ const result = await agentMigrationRepo.getSessionIdByAgentId(agentId);++ expect(result).toBe(lookupSessionId);+ });++ it('should return null for agent without session', async () => {+ const agentId = 'no-session-agent';+ await serverDB.insert(agents).values({ id: agentId, userId });++ const result = await agentMigrationRepo.getSessionIdByAgentId(agentId);++ expect(result).toBeNull();+ });++ it('should return null for non-existent agent', async () => {+ const result = await agentMigrationRepo.getSessionIdByAgentId('non-existent-agent');++ expect(result).toBeNull();+ });+ });+});diff --git a/packages/database/src/repositories/agentMigration/index.ts b/packages/database/src/repositories/agentMigration/index.tsnew file mode 100644index 00000000000..b0b783308e4--- /dev/null+++ b/packages/database/src/repositories/agentMigration/index.ts@@ -0,0 +1,183 @@+import { and, eq, inArray, isNull } from 'drizzle-orm';++import { agentsToSessions, messages, topics } from '../../schemas';+import { LobeChatDatabase } from '../../type';++type MigrateBySessionParams = { agentId: string; sessionId: string };+type MigrateInboxParams = { agentId: string; isInbox: true; sessionId?: string | null };+type MigrateAgentIdParams = MigrateBySessionParams | MigrateInboxParams;++/**+ * AgentMigrationRepo - handles migration of agentId for legacy data+ *+ * This repository is responsible for backfilling agentId to topics and messages+ * that were created before the agentId field was introduced.+ */+export class AgentMigrationRepo {+ private userId: string;+ private db: LobeChatDatabase;++ constructor(db: LobeChatDatabase, userId: string) {+ this.userId = userId;+ this.db = db;+ }++ /**+ * Runtime migration: backfill agentId for all legacy topics and messages+ * Used for progressive migration so future queries don't need agentsToSessions lookup+ *+ * This method migrates both topics and their associated messages in a transaction+ * to ensure data consistency.+ */+ migrateAgentId = async (params: MigrateAgentIdParams) => {+ return this.db.transaction(async (tx) => {+ if ('isInbox' in params && params.isInbox) {+ // Migrate inbox legacy topics and messages+ // 1. Migrate orphan legacy data (sessionId IS NULL)+ await this.migrateInbox(tx, params.agentId);+ // 2. Also migrate legacy data with associated sessionId (if exists)+ if (params.sessionId) {+ await this.migrateBySession(tx, { agentId: params.agentId, sessionId: params.sessionId });+ }+ } else {+ // Migrate session-based legacy topics and messages+ await this.migrateBySession(tx, params as MigrateBySessionParams);+ }+ });+ };++ /**+ * Migrate legacy inbox topics and their messages+ * Inbox topics have: sessionId IS NULL AND groupId IS NULL AND agentId IS NULL+ */+ private migrateInbox = async (tx: LobeChatDatabase, agentId: string) => {+ // 1. Find all legacy inbox topics that need migration+ const legacyTopics = await tx+ .select({ id: topics.id })+ .from(topics)+ .where(+ and(+ eq(topics.userId, this.userId),+ isNull(topics.sessionId),+ isNull(topics.groupId),+ isNull(topics.agentId),+ ),+ );++ if (legacyTopics.length === 0) return;++ const topicIds = legacyTopics.map((t) => t.id);++ // 2. Update topics - preserve original updatedAt to bypass $onUpdate+ await tx+ .update(topics)+ .set({ agentId, updatedAt: topics.updatedAt })+ .where(+ and(+ eq(topics.userId, this.userId),+ isNull(topics.sessionId),+ isNull(topics.groupId),+ isNull(topics.agentId),+ ),+ );++ // 3. Update associated messages that don't have agentId - preserve original updatedAt+ await tx+ .update(messages)+ .set({ agentId, updatedAt: messages.updatedAt })+ .where(+ and(+ eq(messages.userId, this.userId),+ inArray(messages.topicId, topicIds),+ isNull(messages.agentId),+ ),+ );++ // 4. Also update messages without topicId but in inbox (sessionId IS NULL) - preserve original updatedAt+ await tx+ .update(messages)+ .set({ agentId, updatedAt: messages.updatedAt })+ .where(+ and(+ eq(messages.userId, this.userId),+ isNull(messages.sessionId),+ isNull(messages.topicId),+ isNull(messages.agentId),+ ),+ );+ };++ /**+ * Migrate legacy topics and messages for a specific session+ */+ private migrateBySession = async (+ tx: LobeChatDatabase,+ { sessionId, agentId }: MigrateBySessionParams,+ ) => {+ // 1. Find all legacy topics with sessionId that need migration+ const legacyTopics = await tx+ .select({ id: topics.id })+ .from(topics)+ .where(+ and(+ eq(topics.userId, this.userId),+ eq(topics.sessionId, sessionId),+ isNull(topics.agentId),+ ),+ );++ const topicIds = legacyTopics.map((t) => t.id);++ // 2. Update topics - preserve original updatedAt to bypass $onUpdate+ await tx+ .update(topics)+ .set({ agentId, updatedAt: topics.updatedAt })+ .where(+ and(+ eq(topics.userId, this.userId),+ eq(topics.sessionId, sessionId),+ isNull(topics.agentId),+ ),+ );++ // 3. Update associated messages within these topics+ if (topicIds.length > 0) {+ await tx+ .update(messages)+ .set({ agentId, updatedAt: messages.updatedAt })+ .where(+ and(+ eq(messages.userId, this.userId),+ inArray(messages.topicId, topicIds),+ isNull(messages.agentId),+ ),+ );+ }++ // 4. Also update messages without topicId but with this sessionId+ await tx+ .update(messages)+ .set({ agentId, updatedAt: messages.updatedAt })+ .where(+ and(+ eq(messages.userId, this.userId),+ eq(messages.sessionId, sessionId),+ isNull(messages.topicId),+ isNull(messages.agentId),+ ),+ );+ };++ /**+ * Get the associated sessionId for an agent (for backward compatibility lookup)+ */+ getSessionIdByAgentId = async (agentId: string): Promise<string | null> => {+ const result = await this.db+ .select({ sessionId: agentsToSessions.sessionId })+ .from(agentsToSessions)+ .where(and(eq(agentsToSessions.agentId, agentId), eq(agentsToSessions.userId, this.userId)))+ .limit(1);++ return result[0]?.sessionId ?? null;+ };+}diff --git a/packages/database/src/repositories/compression/index.test.ts b/packages/database/src/repositories/compression/index.test.tsnew file mode 100644index 00000000000..8af488fcf82--- /dev/null+++ b/packages/database/src/repositories/compression/index.test.ts@@ -0,0 +1,785 @@+// @vitest-environment node+import { MessageGroupType } from '@lobechat/types';+import { beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../models/__tests__/_util';+import { messageGroups, messages } from '../../schemas/message';+import { topics } from '../../schemas/topic';+import { users } from '../../schemas/user';+import { LobeChatDatabase } from '../../type';+import { CompressionRepository } from './index';++const userId = 'compression-test-user';+const topicId = 'test-topic-1';++let compressionRepo: CompressionRepository;++const serverDB: LobeChatDatabase = await getTestDB();++beforeEach(async () => {+ // 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 repo+ compressionRepo = new CompressionRepository(serverDB, userId);+});++describe('CompressionRepository', () => {+ describe('createCompressionGroup', () => {+ it('should create a compression group', async () => {+ const metadata = {+ compressedAt: new Date().toISOString(),+ compressionStrategy: 'summarize' as const,+ originalMessageCount: 10,+ originalTokenCount: 5000,+ };+ const groupId = await compressionRepo.createCompressionGroup({+ content: 'This is a summary of the conversation.',+ messageIds: [],+ metadata,+ topicId,+ });++ expect(groupId).toBeDefined();++ // Verify the group was created+ const groups = await compressionRepo.getCompressionGroups(topicId);+ expect(groups).toHaveLength(1);+ expect(groups[0].content).toBe('This is a summary of the conversation.');+ expect(groups[0].type).toBe(MessageGroupType.Compression);+ expect(groups[0].metadata).toEqual(metadata);+ });++ it('should create compression group and mark messages as compressed', 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 groupId = await compressionRepo.createCompressionGroup({+ content: 'User greeted and asked how assistant is doing.',+ messageIds: ['msg-1', 'msg-2', 'msg-3'],+ metadata: {+ endMessageId: 'msg-3',+ originalMessageCount: 3,+ startMessageId: 'msg-1',+ },+ topicId,+ });++ // Verify messages are marked as compressed+ const compressedMessages = await compressionRepo.getCompressedMessages(groupId);+ expect(compressedMessages).toHaveLength(3);+ });+ });++ describe('getCompressionGroups', () => {+ it('should return all compression groups for a topic ordered by createdAt', async () => {+ // Create multiple compression groups+ await compressionRepo.createCompressionGroup({+ content: 'First summary',+ messageIds: [],+ metadata: { originalMessageCount: 5 },+ topicId,+ });++ await compressionRepo.createCompressionGroup({+ content: 'Second summary',+ messageIds: [],+ metadata: { originalMessageCount: 10 },+ topicId,+ });++ const groups = await compressionRepo.getCompressionGroups(topicId);+ expect(groups).toHaveLength(2);+ expect(groups[0].content).toBe('First summary');+ expect(groups[1].content).toBe('Second summary');+ });++ it('should not return groups from other topics', async () => {+ const otherTopicId = 'other-topic';+ await serverDB.insert(topics).values({ id: otherTopicId, userId });++ await compressionRepo.createCompressionGroup({+ content: 'Summary for topic 1',+ messageIds: [],+ metadata: {},+ topicId,+ });++ await compressionRepo.createCompressionGroup({+ content: 'Summary for other topic',+ messageIds: [],+ metadata: {},+ topicId: otherTopicId,+ });++ const groups = await compressionRepo.getCompressionGroups(topicId);+ expect(groups).toHaveLength(1);+ expect(groups[0].content).toBe('Summary for topic 1');+ });+ });++ describe('getLatestCompressionGroup', () => {+ it('should return the latest compression group', async () => {+ await compressionRepo.createCompressionGroup({+ content: 'Old summary',+ messageIds: [],+ metadata: {},+ topicId,+ });++ await compressionRepo.createCompressionGroup({+ content: 'Latest summary',+ messageIds: [],+ metadata: {},+ topicId,+ });++ const latest = await compressionRepo.getLatestCompressionGroup(topicId);+ expect(latest).not.toBeNull();+ expect(latest!.content).toBe('Latest summary');+ });++ it('should return null if no compression groups exist', async () => {+ const latest = await compressionRepo.getLatestCompressionGroup(topicId);+ expect(latest).toBeNull();+ });+ });++ describe('updateCompressionContent', () => {+ it('should update compression group content', async () => {+ const groupId = await compressionRepo.createCompressionGroup({+ content: 'Original summary',+ messageIds: [],+ metadata: { originalTokenCount: 1000 },+ topicId,+ });++ await compressionRepo.updateCompressionContent(groupId, 'Updated summary', {+ compressedTokenCount: 100,+ });++ const groups = await compressionRepo.getCompressionGroups(topicId);+ expect(groups[0].content).toBe('Updated summary');+ });+ });++ describe('toggleMessagePin', () => {+ it('should pin a message', async () => {+ await serverDB.insert(messages).values({+ content: 'Important message',+ id: 'msg-pin-test',+ role: 'user',+ topicId,+ userId,+ });++ await compressionRepo.toggleMessagePin('msg-pin-test', true);++ const [message] = await serverDB+ .select()+ .from(messages)+ .where(+ (() => {+ const { eq, and } = require('drizzle-orm');+ return and(eq(messages.id, 'msg-pin-test'), eq(messages.userId, userId));+ })(),+ );++ expect((message.metadata as any)?.pinned).toBe(true);+ });++ it('should unpin a message', async () => {+ await serverDB.insert(messages).values({+ content: 'Pinned message',+ id: 'msg-unpin-test',+ metadata: { pinned: true },+ role: 'user',+ topicId,+ userId,+ });++ await compressionRepo.toggleMessagePin('msg-unpin-test', false);++ const [message] = await serverDB+ .select()+ .from(messages)+ .where(+ (() => {+ const { eq, and } = require('drizzle-orm');+ return and(eq(messages.id, 'msg-unpin-test'), eq(messages.userId, userId));+ })(),+ );++ expect((message.metadata as any)?.pinned).toBe(false);+ });+ });++ describe('getUncompressedMessages', () => {+ it('should return only uncompressed messages', async () => {+ // Create messages+ await serverDB.insert(messages).values([+ { id: 'msg-uncomp-1', content: 'Uncompressed 1', role: 'user', topicId, userId },+ { id: 'msg-uncomp-2', content: 'Uncompressed 2', role: 'assistant', topicId, userId },+ { id: 'msg-comp-1', content: 'To be compressed', role: 'user', topicId, userId },+ ]);++ // Compress one message+ await compressionRepo.createCompressionGroup({+ content: 'Summary',+ messageIds: ['msg-comp-1'],+ metadata: {},+ topicId,+ });++ const uncompressed = await compressionRepo.getUncompressedMessages(topicId);+ expect(uncompressed).toHaveLength(2);+ expect(uncompressed.map((m) => m.id)).toEqual(+ expect.arrayContaining(['msg-uncomp-1', 'msg-uncomp-2']),+ );+ });+ });++ describe('deleteCompressionGroup', () => {+ it('should delete compression group and unmark messages', async () => {+ await serverDB.insert(messages).values([+ { id: 'msg-delete-1', content: 'Message 1', role: 'user', topicId, userId },+ { id: 'msg-delete-2', content: 'Message 2', role: 'assistant', topicId, userId },+ ]);++ const groupId = await compressionRepo.createCompressionGroup({+ content: 'To be deleted',+ messageIds: ['msg-delete-1', 'msg-delete-2'],+ metadata: {},+ topicId,+ });++ // Verify messages are compressed+ let compressedMessages = await compressionRepo.getCompressedMessages(groupId);+ expect(compressedMessages).toHaveLength(2);++ // Delete the group+ await compressionRepo.deleteCompressionGroup(groupId);++ // Verify group is deleted+ const groups = await compressionRepo.getCompressionGroups(topicId);+ expect(groups).toHaveLength(0);++ // Verify messages are uncompressed+ const uncompressed = await compressionRepo.getUncompressedMessages(topicId);+ expect(uncompressed).toHaveLength(2);+ });+ });++ describe('unmarkMessagesFromCompression', () => {+ it('should remove messages from compression group', async () => {+ await serverDB.insert(messages).values([+ { id: 'msg-unmark-1', content: 'Message 1', role: 'user', topicId, userId },+ { id: 'msg-unmark-2', content: 'Message 2', role: 'assistant', topicId, userId },+ ]);++ const groupId = await compressionRepo.createCompressionGroup({+ content: 'Summary',+ messageIds: ['msg-unmark-1', 'msg-unmark-2'],+ metadata: {},+ topicId,+ });++ // Unmark one message+ await compressionRepo.unmarkMessagesFromCompression(['msg-unmark-1']);++ const compressedMessages = await compressionRepo.getCompressedMessages(groupId);+ expect(compressedMessages).toHaveLength(1);+ expect(compressedMessages[0].id).toBe('msg-unmark-2');+ });+ });++ /**+ * Tests for LOBE-2066: MessageGroup aggregation in queryMessage+ *+ * These tests verify the expected behavior for querying messages with compression groups,+ * specifically focusing on:+ * 1. Compressed messages should NOT appear in normal trajectory+ * 2. Compression groups should appear as aggregated nodes+ * 3. Pinned (favorite) messages within compression groups should be extracted+ */+ describe('MessageGroup aggregation query scenarios (LOBE-2066)', () => {+ describe('compressed messages filtering', () => {+ it('should exclude compressed messages from uncompressed query', async () => {+ // Setup: Create 5 messages, compress 3 of them+ await serverDB.insert(messages).values([+ {+ id: 'msg-1',+ content: 'Hello',+ role: 'user',+ topicId,+ userId,+ createdAt: new Date('2024-01-01T10:00:00Z'),+ },+ {+ id: 'msg-2',+ content: 'Hi there!',+ role: 'assistant',+ topicId,+ userId,+ createdAt: new Date('2024-01-01T10:01:00Z'),+ },+ {+ id: 'msg-3',+ content: 'How are you?',+ role: 'user',+ topicId,+ userId,+ createdAt: new Date('2024-01-01T10:02:00Z'),+ },+ {+ id: 'msg-4',+ content: 'I am fine',+ role: 'assistant',+ topicId,+ userId,+ createdAt: new Date('2024-01-01T10:03:00Z'),+ },+ {+ id: 'msg-5',+ content: 'Latest question',+ role: 'user',+ topicId,+ userId,+ createdAt: new Date('2024-01-01T10:04:00Z'),+ },+ ]);++ // Compress the first 3 messages+ await compressionRepo.createCompressionGroup({+ content: 'User greeted assistant and asked how they are.',+ messageIds: ['msg-1', 'msg-2', 'msg-3'],+ metadata: {+ originalMessageCount: 3,+ startMessageId: 'msg-1',+ endMessageId: 'msg-3',+ },+ topicId,+ });++ // Query uncompressed messages+ const uncompressedMessages = await compressionRepo.getUncompressedMessages(topicId);++ // Should only return msg-4 and msg-5+ expect(uncompressedMessages).toHaveLength(2);+ expect(uncompressedMessages.map((m) => m.id)).toEqual(['msg-4', 'msg-5']);+ });++ it('should return all messages as uncompressed when no compression groups exist', async () => {+ await serverDB.insert(messages).values([+ { id: 'msg-no-comp-1', content: 'Message 1', role: 'user', topicId, userId },+ { id: 'msg-no-comp-2', content: 'Message 2', role: 'assistant', topicId, userId },+ { id: 'msg-no-comp-3', content: 'Message 3', role: 'user', topicId, userId },+ ]);++ const uncompressedMessages = await compressionRepo.getUncompressedMessages(topicId);++ expect(uncompressedMessages).toHaveLength(3);+ });+ });++ describe('pinned messages in compression groups', () => {+ it('should identify favorite messages within compression groups', async () => {+ // Setup: Create messages with some marked as favorite+ await serverDB.insert(messages).values([+ {+ id: 'msg-fav-1',+ content: 'Normal message',+ role: 'user',+ topicId,+ userId,+ favorite: false,+ },+ {+ id: 'msg-fav-2',+ content: 'Important code example',+ role: 'assistant',+ topicId,+ userId,+ favorite: true,+ },+ {+ id: 'msg-fav-3',+ content: 'Follow up question',+ role: 'user',+ topicId,+ userId,+ favorite: false,+ },+ {+ id: 'msg-fav-4',+ content: 'Critical answer - pinned',+ role: 'assistant',+ topicId,+ userId,+ favorite: true,+ },+ {+ id: 'msg-fav-5',+ content: 'Latest message',+ role: 'user',+ topicId,+ userId,+ favorite: false,+ },+ ]);++ // Compress messages 1-4+ const groupId = await compressionRepo.createCompressionGroup({+ content: 'Discussion about code with important examples.',+ messageIds: ['msg-fav-1', 'msg-fav-2', 'msg-fav-3', 'msg-fav-4'],+ metadata: {+ originalMessageCount: 4,+ startMessageId: 'msg-fav-1',+ endMessageId: 'msg-fav-4',+ },+ topicId,+ });++ // Query compressed messages to verify+ const compressedMessages = await compressionRepo.getCompressedMessages(groupId);+ expect(compressedMessages).toHaveLength(4);++ // Verify favorite messages within the compression group+ const favoriteMessages = compressedMessages.filter((m) => m.favorite === true);+ expect(favoriteMessages).toHaveLength(2);+ expect(favoriteMessages.map((m) => m.id)).toEqual(+ expect.arrayContaining(['msg-fav-2', 'msg-fav-4']),+ );+ });++ it('should return empty array when compression group has no favorite messages', async () => {+ await serverDB.insert(messages).values([+ {+ id: 'msg-no-fav-1',+ content: 'Message 1',+ role: 'user',+ topicId,+ userId,+ favorite: false,+ },+ {+ id: 'msg-no-fav-2',+ content: 'Message 2',+ role: 'assistant',+ topicId,+ userId,+ favorite: false,+ },+ ]);++ const groupId = await compressionRepo.createCompressionGroup({+ content: 'Summary without any pinned messages.',+ messageIds: ['msg-no-fav-1', 'msg-no-fav-2'],+ metadata: { originalMessageCount: 2 },+ topicId,+ });++ const compressedMessages = await compressionRepo.getCompressedMessages(groupId);+ const favoriteMessages = compressedMessages.filter((m) => m.favorite === true);++ expect(favoriteMessages).toHaveLength(0);+ });++ it('should handle multiple compression groups with pinned messages', async () => {+ // Create messages for two separate compression scenarios+ await serverDB.insert(messages).values([+ // First compression group+ {+ id: 'msg-multi-1',+ content: 'Group 1 msg 1',+ role: 'user',+ topicId,+ userId,+ favorite: false,+ },+ {+ id: 'msg-multi-2',+ content: 'Group 1 pinned',+ role: 'assistant',+ topicId,+ userId,+ favorite: true,+ },+ // Second compression group+ {+ id: 'msg-multi-3',+ content: 'Group 2 msg 1',+ role: 'user',+ topicId,+ userId,+ favorite: true,+ },+ {+ id: 'msg-multi-4',+ content: 'Group 2 msg 2',+ role: 'assistant',+ topicId,+ userId,+ favorite: false,+ },+ {+ id: 'msg-multi-5',+ content: 'Group 2 pinned',+ role: 'user',+ topicId,+ userId,+ favorite: true,+ },+ // Uncompressed message+ {+ id: 'msg-multi-6',+ content: 'Latest uncompressed',+ role: 'assistant',+ topicId,+ userId,+ favorite: false,+ },+ ]);++ // Create first compression group+ const groupId1 = await compressionRepo.createCompressionGroup({+ content: 'First conversation summary',+ messageIds: ['msg-multi-1', 'msg-multi-2'],+ metadata: { originalMessageCount: 2 },+ topicId,+ });++ // Create second compression group+ const groupId2 = await compressionRepo.createCompressionGroup({+ content: 'Second conversation summary',+ messageIds: ['msg-multi-3', 'msg-multi-4', 'msg-multi-5'],+ metadata: { originalMessageCount: 3 },+ topicId,+ });++ // Verify first group has 1 favorite message+ const group1Messages = await compressionRepo.getCompressedMessages(groupId1);+ const group1Favorites = group1Messages.filter((m) => m.favorite === true);+ expect(group1Favorites).toHaveLength(1);+ expect(group1Favorites[0].id).toBe('msg-multi-2');++ // Verify second group has 2 favorite messages+ const group2Messages = await compressionRepo.getCompressedMessages(groupId2);+ const group2Favorites = group2Messages.filter((m) => m.favorite === true);+ expect(group2Favorites).toHaveLength(2);+ expect(group2Favorites.map((m) => m.id)).toEqual(+ expect.arrayContaining(['msg-multi-3', 'msg-multi-5']),+ );++ // Verify uncompressed messages+ const uncompressedMessages = await compressionRepo.getUncompressedMessages(topicId);+ expect(uncompressedMessages).toHaveLength(1);+ expect(uncompressedMessages[0].id).toBe('msg-multi-6');+ });+ });++ describe('compression group as trajectory node', () => {+ it('should return compression groups with content and metadata', async () => {+ await serverDB.insert(messages).values([+ { id: 'msg-traj-1', content: 'Hello', role: 'user', topicId, userId },+ { id: 'msg-traj-2', content: 'Hi!', role: 'assistant', topicId, userId },+ ]);++ const metadata = {+ originalMessageCount: 2,+ originalTokenCount: 150,+ startMessageId: 'msg-traj-1',+ endMessageId: 'msg-traj-2',+ compressedAt: new Date().toISOString(),+ compressionStrategy: 'summarize' as const,+ };++ await compressionRepo.createCompressionGroup({+ content: 'User and assistant exchanged greetings.',+ messageIds: ['msg-traj-1', 'msg-traj-2'],+ metadata,+ topicId,+ });++ const groups = await compressionRepo.getCompressionGroups(topicId);++ expect(groups).toHaveLength(1);+ expect(groups[0]).toMatchObject({+ content: 'User and assistant exchanged greetings.',+ type: MessageGroupType.Compression,+ topicId,+ });+ expect(groups[0].metadata).toMatchObject({+ originalMessageCount: 2,+ originalTokenCount: 150,+ startMessageId: 'msg-traj-1',+ endMessageId: 'msg-traj-2',+ });+ });++ it('should order compression groups by createdAt for trajectory', async () => {+ // Create messages and compression groups with specific timing+ await serverDB.insert(messages).values([+ { id: 'msg-order-1', content: 'Early message', role: 'user', topicId, userId },+ { id: 'msg-order-2', content: 'Middle message', role: 'assistant', topicId, userId },+ { id: 'msg-order-3', content: 'Late message', role: 'user', topicId, userId },+ ]);++ // Create first compression group+ await compressionRepo.createCompressionGroup({+ content: 'First summary',+ messageIds: ['msg-order-1'],+ metadata: { originalMessageCount: 1 },+ topicId,+ });++ // Small delay to ensure different createdAt+ await new Promise((resolve) => setTimeout(resolve, 10));++ // Create second compression group+ await compressionRepo.createCompressionGroup({+ content: 'Second summary',+ messageIds: ['msg-order-2', 'msg-order-3'],+ metadata: { originalMessageCount: 2 },+ topicId,+ });++ const groups = await compressionRepo.getCompressionGroups(topicId);++ expect(groups).toHaveLength(2);+ expect(groups[0].content).toBe('First summary');+ expect(groups[1].content).toBe('Second summary');+ // Verify ordering by createdAt+ expect(new Date(groups[0].createdAt).getTime()).toBeLessThan(+ new Date(groups[1].createdAt).getTime(),+ );+ });+ });++ describe('trajectory assembly scenario', () => {+ it('should support building trajectory with compression groups and uncompressed messages', async () => {+ // This test simulates the full trajectory assembly scenario+ // Setup: Mixed compressed and uncompressed messages++ await serverDB.insert(messages).values([+ // Early messages to be compressed (with one pinned)+ {+ id: 'traj-1',+ content: 'Hello',+ role: 'user',+ topicId,+ userId,+ favorite: false,+ createdAt: new Date('2024-01-01T10:00:00Z'),+ },+ {+ id: 'traj-2',+ content: 'Hi there!',+ role: 'assistant',+ topicId,+ userId,+ favorite: true,+ createdAt: new Date('2024-01-01T10:01:00Z'),+ },+ {+ id: 'traj-3',+ content: 'Important question',+ role: 'user',+ topicId,+ userId,+ favorite: true,+ createdAt: new Date('2024-01-01T10:02:00Z'),+ },+ {+ id: 'traj-4',+ content: 'Detailed answer',+ role: 'assistant',+ topicId,+ userId,+ favorite: false,+ createdAt: new Date('2024-01-01T10:03:00Z'),+ },+ // Recent uncompressed messages+ {+ id: 'traj-5',+ content: 'New question',+ role: 'user',+ topicId,+ userId,+ favorite: false,+ createdAt: new Date('2024-01-01T10:04:00Z'),+ },+ {+ id: 'traj-6',+ content: 'New answer',+ role: 'assistant',+ topicId,+ userId,+ favorite: false,+ createdAt: new Date('2024-01-01T10:05:00Z'),+ },+ ]);++ // Compress early messages+ const groupId = await compressionRepo.createCompressionGroup({+ content: 'Initial conversation with important question and answer.',+ messageIds: ['traj-1', 'traj-2', 'traj-3', 'traj-4'],+ metadata: {+ originalMessageCount: 4,+ startMessageId: 'traj-1',+ endMessageId: 'traj-4',+ },+ topicId,+ });++ // Fetch components for trajectory assembly+ const compressionGroups = await compressionRepo.getCompressionGroups(topicId);+ const uncompressedMessages = await compressionRepo.getUncompressedMessages(topicId);+ const compressedMessages = await compressionRepo.getCompressedMessages(groupId);+ const pinnedMessagesInGroup = compressedMessages.filter((m) => m.favorite === true);++ // Verify trajectory components+ // 1. Compression groups+ expect(compressionGroups).toHaveLength(1);+ expect(compressionGroups[0].content).toBe(+ 'Initial conversation with important question and answer.',+ );++ // 2. Uncompressed messages (recent ones)+ expect(uncompressedMessages).toHaveLength(2);+ expect(uncompressedMessages.map((m) => m.id)).toEqual(['traj-5', 'traj-6']);++ // 3. Pinned messages within compression group (for pinnedMessages field)+ expect(pinnedMessagesInGroup).toHaveLength(2);+ expect(pinnedMessagesInGroup.map((m) => m.id)).toEqual(+ expect.arrayContaining(['traj-2', 'traj-3']),+ );++ // Expected trajectory structure (pseudo):+ // [+ // {+ // role: 'compressedGroup',+ // id: groupId,+ // content: 'Initial conversation with important question and answer.',+ // pinnedMessages: [traj-2, traj-3],+ // },+ // { role: 'user', id: 'traj-5', content: 'New question' },+ // { role: 'assistant', id: 'traj-6', content: 'New answer' },+ // ]+ });+ });+ });+});diff --git a/packages/database/src/repositories/compression/index.ts b/packages/database/src/repositories/compression/index.tsnew file mode 100644index 00000000000..76c186ff62b--- /dev/null+++ b/packages/database/src/repositories/compression/index.ts@@ -0,0 +1,219 @@+import { CompressionGroupMetadata, MessageGroupType } from '@lobechat/types';+import { and, eq, inArray, isNull } from 'drizzle-orm';++import { MessageGroupItem, messageGroups, messages } from '../../schemas';+import { LobeChatDatabase } from '../../type';++export interface CreateCompressionGroupParams {+ content: string;+ editorData?: any;+ messageIds: string[];+ metadata: CompressionGroupMetadata;+ topicId: string;+}++export interface CompressionGroupResult {+ content: string | null;+ createdAt: Date;+ description: string | null;+ editorData: unknown;+ id: string;+ metadata: CompressionGroupMetadata | null;+ topicId: string | null;+ type: string | null;+}++/**+ * Compression Repository - handles message compression operations+ */+export class CompressionRepository {+ private userId: string;+ private db: LobeChatDatabase;++ constructor(db: LobeChatDatabase, userId: string) {+ this.userId = userId;+ this.db = db;+ }++ /**+ * Create a compression group and mark messages as compressed+ */+ async createCompressionGroup(params: CreateCompressionGroupParams): Promise<string> {+ const { topicId, content, editorData, messageIds, metadata } = params;++ // Store metadata in the description field as JSON string+ const description = JSON.stringify(metadata);++ // 1. Create compression group+ const result = (await this.db+ .insert(messageGroups)+ .values({+ content,+ description,+ editorData,+ topicId,+ type: MessageGroupType.Compression,+ userId: this.userId,+ })+ .returning()) as MessageGroupItem[];++ const group = result[0];++ // 2. Mark messages as compressed+ if (messageIds.length > 0) {+ await this.markMessagesAsCompressed(messageIds, group.id);+ }++ return group.id;+ }++ /**+ * Get all compression groups for a topic+ */+ async getCompressionGroups(topicId: string): Promise<CompressionGroupResult[]> {+ const groups = await this.db+ .select()+ .from(messageGroups)+ .where(+ and(+ eq(messageGroups.userId, this.userId),+ eq(messageGroups.topicId, topicId),+ eq(messageGroups.type, MessageGroupType.Compression),+ ),+ )+ .orderBy(messageGroups.createdAt);++ // Parse description field as metadata+ return groups.map((group) => ({+ ...group,+ metadata: group.description ? JSON.parse(group.description) : null,+ })) as unknown as CompressionGroupResult[];+ }++ /**+ * Get the latest compression group for a topic+ */+ async getLatestCompressionGroup(topicId: string): Promise<CompressionGroupResult | null> {+ const groups = await this.getCompressionGroups(topicId);+ return groups.length > 0 ? groups.at(-1)! : null;+ }++ /**+ * Update compression group content+ */+ async updateCompressionContent(+ groupId: string,+ content: string,+ metadata?: Partial<CompressionGroupMetadata>,+ ): Promise<void> {+ const updateData: Record<string, unknown> = {+ content,+ updatedAt: new Date(),+ };++ if (metadata) {+ // Need to merge with existing metadata+ const existing = await this.db+ .select({ description: messageGroups.description })+ .from(messageGroups)+ .where(and(eq(messageGroups.id, groupId), eq(messageGroups.userId, this.userId)));++ const existingMetadata = existing[0]?.description ? JSON.parse(existing[0].description) : {};+ updateData.description = JSON.stringify({ ...existingMetadata, ...metadata });+ }++ await this.db+ .update(messageGroups)+ .set(updateData)+ .where(and(eq(messageGroups.id, groupId), eq(messageGroups.userId, this.userId)));+ }++ /**+ * Mark messages as compressed by associating them with a compression group+ */+ async markMessagesAsCompressed(messageIds: string[], groupId: string): Promise<void> {+ if (messageIds.length === 0) return;++ await this.db+ .update(messages)+ .set({ messageGroupId: groupId })+ .where(and(eq(messages.userId, this.userId), inArray(messages.id, messageIds)));+ }++ /**+ * Unmark messages from compression (remove from compression group)+ */+ async unmarkMessagesFromCompression(messageIds: string[]): Promise<void> {+ if (messageIds.length === 0) return;++ await this.db+ .update(messages)+ .set({ messageGroupId: null })+ .where(and(eq(messages.userId, this.userId), inArray(messages.id, messageIds)));+ }++ /**+ * Toggle pin status for a message+ */+ async toggleMessagePin(messageId: string, pinned: boolean): Promise<void> {+ // Get current metadata+ const [message] = await this.db+ .select({ metadata: messages.metadata })+ .from(messages)+ .where(and(eq(messages.id, messageId), eq(messages.userId, this.userId)));++ if (!message) return;++ const currentMetadata = (message.metadata as Record<string, unknown>) || {};+ const newMetadata = { ...currentMetadata, pinned };++ await this.db+ .update(messages)+ .set({ metadata: newMetadata })+ .where(and(eq(messages.id, messageId), eq(messages.userId, this.userId)));+ }++ /**+ * Get messages that are not compressed (for sending to LLM)+ */+ async getUncompressedMessages(topicId: string) {+ return this.db+ .select()+ .from(messages)+ .where(+ and(+ eq(messages.userId, this.userId),+ eq(messages.topicId, topicId),+ isNull(messages.messageGroupId),+ ),+ )+ .orderBy(messages.createdAt);+ }++ /**+ * Get compressed messages for a specific compression group+ */+ async getCompressedMessages(groupId: string) {+ return this.db+ .select()+ .from(messages)+ .where(and(eq(messages.userId, this.userId), eq(messages.messageGroupId, groupId)))+ .orderBy(messages.createdAt);+ }++ /**+ * Delete a compression group and unmark all associated messages+ */+ async deleteCompressionGroup(groupId: string): Promise<void> {+ // 1. Unmark all messages+ await this.db+ .update(messages)+ .set({ messageGroupId: null })+ .where(and(eq(messages.userId, this.userId), eq(messages.messageGroupId, groupId)));++ // 2. Delete the group+ await this.db+ .delete(messageGroups)+ .where(and(eq(messageGroups.id, groupId), eq(messageGroups.userId, this.userId)));+ }+}diff --git a/packages/database/src/repositories/home/__tests__/index.test.ts b/packages/database/src/repositories/home/__tests__/index.test.tsnew file mode 100644index 00000000000..01860839785--- /dev/null+++ b/packages/database/src/repositories/home/__tests__/index.test.ts@@ -0,0 +1,511 @@+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../models/__tests__/_util';+import * as Schema from '../../../schemas';+import { HomeRepository } from '../index';++const clientDB = await getTestDB();++const userId = 'test-user-id';+const otherUserId = 'other-user-id';+let homeRepo: HomeRepository;++beforeEach(async () => {+ await clientDB.delete(Schema.users);++ // Create test users+ await clientDB.transaction(async (tx) => {+ await tx.insert(Schema.users).values([{ id: userId }, { id: otherUserId }]);+ });++ homeRepo = new HomeRepository(clientDB, userId);+});++afterEach(async () => {+ await clientDB.delete(Schema.users);+});++describe('HomeRepository', () => {+ describe('getSidebarAgentList', () => {+ it('should return empty lists when no agents exist', async () => {+ const result = await homeRepo.getSidebarAgentList();++ expect(result.pinned).toEqual([]);+ expect(result.ungrouped).toEqual([]);+ expect(result.groups).toEqual([]);+ });++ it('should return agents with pinned status from agents table', async () => {+ // Create an agent with pinned=true+ const agentId = 'agent-1';+ const sessionId = 'session-1';++ await clientDB.transaction(async (tx) => {+ await tx.insert(Schema.agents).values({+ id: agentId,+ userId,+ title: 'Pinned Agent',+ pinned: true,+ virtual: false,+ });+ await tx.insert(Schema.sessions).values({+ id: sessionId,+ slug: 'session-1',+ userId,+ });+ await tx.insert(Schema.agentsToSessions).values({+ agentId,+ sessionId,+ userId,+ });+ });++ const result = await homeRepo.getSidebarAgentList();++ expect(result.pinned).toHaveLength(1);+ expect(result.pinned[0].id).toBe(agentId);+ expect(result.pinned[0].pinned).toBe(true);+ expect(result.pinned[0].title).toBe('Pinned Agent');+ expect(result.ungrouped).toHaveLength(0);+ });++ it('should return unpinned agents in ungrouped list', async () => {+ // Create an agent with pinned=false+ const agentId = 'agent-2';+ const sessionId = 'session-2';++ await clientDB.transaction(async (tx) => {+ await tx.insert(Schema.agents).values({+ id: agentId,+ userId,+ title: 'Unpinned Agent',+ pinned: false,+ virtual: false,+ });+ await tx.insert(Schema.sessions).values({+ id: sessionId,+ slug: 'session-2',+ userId,+ });+ await tx.insert(Schema.agentsToSessions).values({+ agentId,+ sessionId,+ userId,+ });+ });++ const result = await homeRepo.getSidebarAgentList();++ expect(result.ungrouped).toHaveLength(1);+ expect(result.ungrouped[0].id).toBe(agentId);+ expect(result.ungrouped[0].pinned).toBe(false);+ expect(result.pinned).toHaveLength(0);+ });++ it('should not include virtual agents', async () => {+ const agentId = 'virtual-agent';+ const sessionId = 'virtual-session';++ await clientDB.transaction(async (tx) => {+ await tx.insert(Schema.agents).values({+ id: agentId,+ userId,+ title: 'Virtual Agent',+ pinned: false,+ virtual: true, // virtual agent+ });+ await tx.insert(Schema.sessions).values({+ id: sessionId,+ slug: 'virtual-session',+ userId,+ });+ await tx.insert(Schema.agentsToSessions).values({+ agentId,+ sessionId,+ userId,+ });+ });++ const result = await homeRepo.getSidebarAgentList();++ expect(result.pinned).toHaveLength(0);+ expect(result.ungrouped).toHaveLength(0);+ });++ it('should correctly categorize multiple agents by pinned status', async () => {+ // Create multiple agents with different pinned status+ await clientDB.transaction(async (tx) => {+ // Pinned agent 1+ await tx.insert(Schema.agents).values({+ id: 'pinned-1',+ userId,+ title: 'Pinned 1',+ pinned: true,+ virtual: false,+ });+ await tx.insert(Schema.sessions).values({+ id: 'session-pinned-1',+ slug: 'session-pinned-1',+ userId,+ });+ await tx.insert(Schema.agentsToSessions).values({+ agentId: 'pinned-1',+ sessionId: 'session-pinned-1',+ userId,+ });++ // Pinned agent 2+ await tx.insert(Schema.agents).values({+ id: 'pinned-2',+ userId,+ title: 'Pinned 2',+ pinned: true,+ virtual: false,+ });+ await tx.insert(Schema.sessions).values({+ id: 'session-pinned-2',+ slug: 'session-pinned-2',+ userId,+ });+ await tx.insert(Schema.agentsToSessions).values({+ agentId: 'pinned-2',+ sessionId: 'session-pinned-2',+ userId,+ });++ // Unpinned agent+ await tx.insert(Schema.agents).values({+ id: 'unpinned-1',+ userId,+ title: 'Unpinned 1',+ pinned: false,+ virtual: false,+ });+ await tx.insert(Schema.sessions).values({+ id: 'session-unpinned-1',+ slug: 'session-unpinned-1',+ userId,+ });+ await tx.insert(Schema.agentsToSessions).values({+ agentId: 'unpinned-1',+ sessionId: 'session-unpinned-1',+ userId,+ });+ });++ const result = await homeRepo.getSidebarAgentList();++ expect(result.pinned).toHaveLength(2);+ expect(result.ungrouped).toHaveLength(1);+ expect(result.pinned.map((a) => a.id)).toContain('pinned-1');+ expect(result.pinned.map((a) => a.id)).toContain('pinned-2');+ expect(result.ungrouped[0].id).toBe('unpinned-1');+ });++ it('should not return agents from other users', async () => {+ // Create agent for other user+ await clientDB.transaction(async (tx) => {+ await tx.insert(Schema.agents).values({+ id: 'other-agent',+ userId: otherUserId,+ title: 'Other User Agent',+ pinned: true,+ virtual: false,+ });+ await tx.insert(Schema.sessions).values({+ id: 'other-session',+ slug: 'other-session',+ userId: otherUserId,+ });+ await tx.insert(Schema.agentsToSessions).values({+ agentId: 'other-agent',+ sessionId: 'other-session',+ userId: otherUserId,+ });+ });++ const result = await homeRepo.getSidebarAgentList();++ expect(result.pinned).toHaveLength(0);+ expect(result.ungrouped).toHaveLength(0);+ });++ describe('backward compatibility - fallback to sessions.pinned', () => {+ it('should fallback to sessions.pinned when agents.pinned is undefined (legacy data)', async () => {+ // Simulate legacy data: agents.pinned is null, but sessions.pinned is true+ const agentId = 'legacy-agent';+ const sessionId = 'legacy-session';++ await clientDB.transaction(async (tx) => {+ await tx.insert(Schema.agents).values({+ id: agentId,+ userId,+ title: 'Legacy Agent',+ virtual: false,+ });+ await tx.insert(Schema.sessions).values({+ id: sessionId,+ slug: 'legacy-session',+ userId,+ pinned: true, // Legacy: pinned was stored on session+ });+ await tx.insert(Schema.agentsToSessions).values({+ agentId,+ sessionId,+ userId,+ });+ });++ const result = await homeRepo.getSidebarAgentList();++ // Should fallback to sessions.pinned = true+ expect(result.pinned).toHaveLength(1);+ expect(result.pinned[0].id).toBe(agentId);+ expect(result.pinned[0].pinned).toBe(true);+ expect(result.ungrouped).toHaveLength(0);+ });++ it('should use agents.pinned when both agents.pinned and sessions.pinned exist (agents.pinned takes priority)', async () => {+ // agents.pinned = false, sessions.pinned = true+ // agents.pinned should take priority+ const agentId = 'priority-agent';+ const sessionId = 'priority-session';++ await clientDB.transaction(async (tx) => {+ await tx.insert(Schema.agents).values({+ id: agentId,+ userId,+ title: 'Priority Agent',+ pinned: false, // Agent says not pinned+ virtual: false,+ });+ await tx.insert(Schema.sessions).values({+ id: sessionId,+ slug: 'priority-session',+ userId,+ pinned: true, // Session says pinned (legacy)+ });+ await tx.insert(Schema.agentsToSessions).values({+ agentId,+ sessionId,+ userId,+ });+ });++ const result = await homeRepo.getSidebarAgentList();++ // agents.pinned = false should take priority+ expect(result.pinned).toHaveLength(0);+ expect(result.ungrouped).toHaveLength(1);+ expect(result.ungrouped[0].id).toBe(agentId);+ expect(result.ungrouped[0].pinned).toBe(false);+ });++ it('should return pinned=false when both agents.pinned and sessions.pinned are null', async () => {+ const agentId = 'both-null-agent';+ const sessionId = 'both-null-session';++ await clientDB.transaction(async (tx) => {+ await tx.insert(Schema.agents).values({+ id: agentId,+ userId,+ title: 'Both Null Agent',+ pinned: null,+ virtual: false,+ });+ await tx.insert(Schema.sessions).values({+ id: sessionId,+ slug: 'both-null-session',+ userId,+ pinned: null,+ });+ await tx.insert(Schema.agentsToSessions).values({+ agentId,+ sessionId,+ userId,+ });+ });++ const result = await homeRepo.getSidebarAgentList();++ // Both null should default to false+ expect(result.pinned).toHaveLength(0);+ expect(result.ungrouped).toHaveLength(1);+ expect(result.ungrouped[0].pinned).toBe(false);+ });+ });+ });++ describe('searchAgents', () => {+ beforeEach(async () => {+ // Create test agents for search+ await clientDB.transaction(async (tx) => {+ // Pinned agent+ await tx.insert(Schema.agents).values({+ id: 'search-pinned',+ userId,+ title: 'Searchable Pinned Agent',+ description: 'A pinned agent for testing',+ pinned: true,+ virtual: false,+ });+ await tx.insert(Schema.sessions).values({+ id: 'session-search-pinned',+ slug: 'session-search-pinned',+ userId,+ });+ await tx.insert(Schema.agentsToSessions).values({+ agentId: 'search-pinned',+ sessionId: 'session-search-pinned',+ userId,+ });++ // Unpinned agent+ await tx.insert(Schema.agents).values({+ id: 'search-unpinned',+ userId,+ title: 'Searchable Unpinned Agent',+ description: 'An unpinned agent for testing',+ pinned: false,+ virtual: false,+ });+ await tx.insert(Schema.sessions).values({+ id: 'session-search-unpinned',+ slug: 'session-search-unpinned',+ userId,+ });+ await tx.insert(Schema.agentsToSessions).values({+ agentId: 'search-unpinned',+ sessionId: 'session-search-unpinned',+ userId,+ });+ });+ });++ it('should return empty array for empty keyword', async () => {+ const result = await homeRepo.searchAgents('');+ expect(result).toEqual([]);+ });++ it('should search agents by title and return correct pinned status', async () => {+ const result = await homeRepo.searchAgents('Searchable Pinned');++ expect(result).toHaveLength(1);+ expect(result[0].id).toBe('search-pinned');+ expect(result[0].pinned).toBe(true);+ });++ it('should search agents by description', async () => {+ const result = await homeRepo.searchAgents('unpinned agent for testing');++ expect(result).toHaveLength(1);+ expect(result[0].id).toBe('search-unpinned');+ expect(result[0].pinned).toBe(false);+ });++ it('should return multiple matching agents with correct pinned status', async () => {+ const result = await homeRepo.searchAgents('Searchable');++ expect(result).toHaveLength(2);++ const pinnedAgent = result.find((a) => a.id === 'search-pinned');+ const unpinnedAgent = result.find((a) => a.id === 'search-unpinned');++ expect(pinnedAgent).toBeDefined();+ expect(pinnedAgent!.pinned).toBe(true);+ expect(unpinnedAgent).toBeDefined();+ expect(unpinnedAgent!.pinned).toBe(false);+ });++ it('should not return virtual agents in search', async () => {+ // Add a virtual agent+ await clientDB.transaction(async (tx) => {+ await tx.insert(Schema.agents).values({+ id: 'virtual-search',+ userId,+ title: 'Searchable Virtual Agent',+ pinned: false,+ virtual: true,+ });+ await tx.insert(Schema.sessions).values({+ id: 'session-virtual-search',+ slug: 'session-virtual-search',+ userId,+ });+ await tx.insert(Schema.agentsToSessions).values({+ agentId: 'virtual-search',+ sessionId: 'session-virtual-search',+ userId,+ });+ });++ const result = await homeRepo.searchAgents('Virtual');++ expect(result).toHaveLength(0);+ });++ describe('backward compatibility - fallback to sessions.pinned', () => {+ it('should fallback to sessions.pinned when agents.pinned is null in search results', async () => {+ // Create legacy agent with pinned on session only+ await clientDB.transaction(async (tx) => {+ await tx.insert(Schema.agents).values({+ id: 'legacy-search',+ userId,+ title: 'Legacy Searchable Agent',+ description: 'A legacy agent',+ pinned: null, // No pinned on agent+ virtual: false,+ });+ await tx.insert(Schema.sessions).values({+ id: 'session-legacy-search',+ slug: 'session-legacy-search',+ userId,+ pinned: true, // Pinned on session (legacy)+ });+ await tx.insert(Schema.agentsToSessions).values({+ agentId: 'legacy-search',+ sessionId: 'session-legacy-search',+ userId,+ });+ });++ const result = await homeRepo.searchAgents('Legacy Searchable');++ expect(result).toHaveLength(1);+ expect(result[0].id).toBe('legacy-search');+ expect(result[0].pinned).toBe(true); // Should fallback to sessions.pinned+ });++ it('should prioritize agents.pinned over sessions.pinned in search results', async () => {+ // Create agent where agents.pinned differs from sessions.pinned+ await clientDB.transaction(async (tx) => {+ await tx.insert(Schema.agents).values({+ id: 'priority-search',+ userId,+ title: 'Priority Searchable Agent',+ pinned: false, // Agent says not pinned+ virtual: false,+ });+ await tx.insert(Schema.sessions).values({+ id: 'session-priority-search',+ slug: 'session-priority-search',+ userId,+ pinned: true, // Session says pinned+ });+ await tx.insert(Schema.agentsToSessions).values({+ agentId: 'priority-search',+ sessionId: 'session-priority-search',+ userId,+ });+ });++ const result = await homeRepo.searchAgents('Priority Searchable');++ expect(result).toHaveLength(1);+ expect(result[0].id).toBe('priority-search');+ expect(result[0].pinned).toBe(false); // agents.pinned should take priority+ });+ });+ });+});diff --git a/packages/database/src/repositories/home/index.test.ts b/packages/database/src/repositories/home/index.test.tsnew file mode 100644index 00000000000..09b76d80097--- /dev/null+++ b/packages/database/src/repositories/home/index.test.ts@@ -0,0 +1,887 @@+// @vitest-environment node+import { beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../models/__tests__/_util';+import { NewAgent, agents } from '../../schemas/agent';+import { NewChatGroup, chatGroups } from '../../schemas/chatGroup';+import { agentsToSessions } from '../../schemas/relations';+import { NewSession, NewSessionGroup, sessionGroups, sessions } from '../../schemas/session';+import { users } from '../../schemas/user';+import { LobeChatDatabase } from '../../type';+import { HomeRepository } from './index';++const userId = 'home-test-user';+const otherUserId = 'other-home-user';++let homeRepo: HomeRepository;++const serverDB: LobeChatDatabase = await getTestDB();++beforeEach(async () => {+ // Clean up+ await serverDB.delete(users);++ // Create test users+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);++ // Initialize repo+ homeRepo = new HomeRepository(serverDB, userId);+});++describe('HomeRepository', () => {+ describe('getSidebarAgentList - empty state', () => {+ it('should return empty arrays when no data exists', async () => {+ const result = await homeRepo.getSidebarAgentList();++ expect(result.pinned).toEqual([]);+ expect(result.groups).toEqual([]);+ expect(result.ungrouped).toEqual([]);+ });+ });++ describe('getSidebarAgentList - agents', () => {+ it('should return agents with their session info', async () => {+ // Create agent+ const [agent] = await serverDB+ .insert(agents)+ .values({+ avatar: 'agent-avatar',+ description: 'Test agent description',+ title: 'Test Agent',+ userId,+ virtual: false,+ })+ .returning();++ // Create session+ const [session] = await serverDB+ .insert(sessions)+ .values({+ pinned: false,+ userId,+ })+ .returning();++ // Link agent to session+ await serverDB.insert(agentsToSessions).values({+ agentId: agent.id,+ sessionId: session.id,+ userId,+ });++ const result = await homeRepo.getSidebarAgentList();++ expect(result.ungrouped).toHaveLength(1);+ expect(result.ungrouped[0]).toMatchObject({+ avatar: 'agent-avatar',+ description: 'Test agent description',+ id: agent.id,+ pinned: false,+ sessionId: session.id,+ title: 'Test Agent',+ type: 'agent',+ });+ });++ it('should exclude virtual agents (like inbox)', async () => {+ // Create virtual agent+ const [virtualAgent] = await serverDB+ .insert(agents)+ .values({+ title: 'Inbox',+ userId,+ virtual: true,+ })+ .returning();++ // Create session for virtual agent+ const [session] = await serverDB+ .insert(sessions)+ .values({+ userId,+ })+ .returning();++ await serverDB.insert(agentsToSessions).values({+ agentId: virtualAgent.id,+ sessionId: session.id,+ userId,+ });++ // Create non-virtual agent+ const [normalAgent] = await serverDB+ .insert(agents)+ .values({+ title: 'Normal Agent',+ userId,+ virtual: false,+ })+ .returning();++ const [normalSession] = await serverDB+ .insert(sessions)+ .values({+ userId,+ })+ .returning();++ await serverDB.insert(agentsToSessions).values({+ agentId: normalAgent.id,+ sessionId: normalSession.id,+ userId,+ });++ const result = await homeRepo.getSidebarAgentList();++ // Should only have the normal agent+ expect(result.ungrouped).toHaveLength(1);+ expect(result.ungrouped[0].title).toBe('Normal Agent');+ });+ });++ describe('getSidebarAgentList - chat groups', () => {+ it('should return chat groups (group chats)', async () => {+ await serverDB.insert(chatGroups).values({+ description: 'Group chat description',+ pinned: false,+ title: 'My Group Chat',+ userId,+ });++ const result = await homeRepo.getSidebarAgentList();++ expect(result.ungrouped).toHaveLength(1);+ expect(result.ungrouped[0]).toMatchObject({+ description: 'Group chat description',+ pinned: false,+ title: 'My Group Chat',+ type: 'group',+ });+ });+ });++ describe('getSidebarAgentList - pinned items', () => {+ it('should separate pinned agents', async () => {+ // Create pinned agent+ const [pinnedAgent] = await serverDB+ .insert(agents)+ .values({+ title: 'Pinned Agent',+ userId,+ virtual: false,+ })+ .returning();++ const [pinnedSession] = await serverDB+ .insert(sessions)+ .values({+ pinned: true,+ userId,+ })+ .returning();++ await serverDB.insert(agentsToSessions).values({+ agentId: pinnedAgent.id,+ sessionId: pinnedSession.id,+ userId,+ });++ // Create unpinned agent+ const [unpinnedAgent] = await serverDB+ .insert(agents)+ .values({+ title: 'Unpinned Agent',+ userId,+ virtual: false,+ })+ .returning();++ const [unpinnedSession] = await serverDB+ .insert(sessions)+ .values({+ pinned: false,+ userId,+ })+ .returning();++ await serverDB.insert(agentsToSessions).values({+ agentId: unpinnedAgent.id,+ sessionId: unpinnedSession.id,+ userId,+ });++ const result = await homeRepo.getSidebarAgentList();++ expect(result.pinned).toHaveLength(1);+ expect(result.pinned[0].title).toBe('Pinned Agent');+ expect(result.ungrouped).toHaveLength(1);+ expect(result.ungrouped[0].title).toBe('Unpinned Agent');+ });++ it('should separate pinned chat groups', async () => {+ await serverDB.insert(chatGroups).values([+ { pinned: true, title: 'Pinned Group', userId },+ { pinned: false, title: 'Unpinned Group', userId },+ ]);++ const result = await homeRepo.getSidebarAgentList();++ expect(result.pinned).toHaveLength(1);+ expect(result.pinned[0].title).toBe('Pinned Group');+ expect(result.ungrouped).toHaveLength(1);+ expect(result.ungrouped[0].title).toBe('Unpinned Group');+ });+ });++ describe('getSidebarAgentList - session groups (folders)', () => {+ it('should organize agents into session groups', async () => {+ // Create session group (folder)+ const [group] = await serverDB+ .insert(sessionGroups)+ .values({+ name: 'Work Agents',+ sort: 1,+ userId,+ })+ .returning();++ // Create agent in group+ const [agent] = await serverDB+ .insert(agents)+ .values({+ title: 'Work Agent',+ userId,+ virtual: false,+ })+ .returning();++ const [session] = await serverDB+ .insert(sessions)+ .values({+ groupId: group.id,+ pinned: false,+ userId,+ })+ .returning();++ await serverDB.insert(agentsToSessions).values({+ agentId: agent.id,+ sessionId: session.id,+ userId,+ });++ const result = await homeRepo.getSidebarAgentList();++ expect(result.groups).toHaveLength(1);+ expect(result.groups[0].name).toBe('Work Agents');+ expect(result.groups[0].items).toHaveLength(1);+ expect(result.groups[0].items[0].title).toBe('Work Agent');+ expect(result.ungrouped).toHaveLength(0);+ });++ it('should organize chat groups into session groups', async () => {+ // Create session group (folder)+ const [group] = await serverDB+ .insert(sessionGroups)+ .values({+ name: 'Team Chats',+ sort: 1,+ userId,+ })+ .returning();++ // Create chat group in session group+ await serverDB.insert(chatGroups).values({+ groupId: group.id,+ pinned: false,+ title: 'Team Chat',+ userId,+ });++ const result = await homeRepo.getSidebarAgentList();++ expect(result.groups).toHaveLength(1);+ expect(result.groups[0].name).toBe('Team Chats');+ expect(result.groups[0].items).toHaveLength(1);+ expect(result.groups[0].items[0].title).toBe('Team Chat');+ expect(result.groups[0].items[0].type).toBe('group');+ });++ it('should return empty groups when no items assigned', async () => {+ await serverDB.insert(sessionGroups).values({+ name: 'Empty Group',+ sort: 1,+ userId,+ });++ const result = await homeRepo.getSidebarAgentList();++ expect(result.groups).toHaveLength(1);+ expect(result.groups[0].name).toBe('Empty Group');+ expect(result.groups[0].items).toHaveLength(0);+ });++ it('should order groups by sort field', async () => {+ await serverDB.insert(sessionGroups).values([+ { name: 'Group C', sort: 3, userId },+ { name: 'Group A', sort: 1, userId },+ { name: 'Group B', sort: 2, userId },+ ]);++ const result = await homeRepo.getSidebarAgentList();++ expect(result.groups).toHaveLength(3);+ expect(result.groups[0].name).toBe('Group A');+ expect(result.groups[1].name).toBe('Group B');+ expect(result.groups[2].name).toBe('Group C');+ });+ });++ describe('getSidebarAgentList - user isolation', () => {+ it('should only return current user agents', async () => {+ // Create agent for current user+ const [userAgent] = await serverDB+ .insert(agents)+ .values({+ title: 'User Agent',+ userId,+ virtual: false,+ })+ .returning();++ const [userSession] = await serverDB+ .insert(sessions)+ .values({+ userId,+ })+ .returning();++ await serverDB.insert(agentsToSessions).values({+ agentId: userAgent.id,+ sessionId: userSession.id,+ userId,+ });++ // Create agent for other user+ const [otherAgent] = await serverDB+ .insert(agents)+ .values({+ title: 'Other User Agent',+ userId: otherUserId,+ virtual: false,+ })+ .returning();++ const [otherSession] = await serverDB+ .insert(sessions)+ .values({+ userId: otherUserId,+ })+ .returning();++ await serverDB.insert(agentsToSessions).values({+ agentId: otherAgent.id,+ sessionId: otherSession.id,+ userId: otherUserId,+ });++ const result = await homeRepo.getSidebarAgentList();++ expect(result.ungrouped).toHaveLength(1);+ expect(result.ungrouped[0].title).toBe('User Agent');+ });++ it('should only return current user chat groups', async () => {+ await serverDB.insert(chatGroups).values([+ { title: 'User Group', userId },+ { title: 'Other User Group', userId: otherUserId },+ ]);++ const result = await homeRepo.getSidebarAgentList();++ expect(result.ungrouped).toHaveLength(1);+ expect(result.ungrouped[0].title).toBe('User Group');+ });++ it('should only return current user session groups', async () => {+ await serverDB.insert(sessionGroups).values([+ { name: 'User Folder', sort: 1, userId },+ { name: 'Other User Folder', sort: 1, userId: otherUserId },+ ]);++ const result = await homeRepo.getSidebarAgentList();++ expect(result.groups).toHaveLength(1);+ expect(result.groups[0].name).toBe('User Folder');+ });+ });++ describe('getSidebarAgentList - sorting', () => {+ it('should sort items by updatedAt descending', async () => {+ const now = new Date();+ const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);+ const twoDaysAgo = new Date(now.getTime() - 2 * 24 * 60 * 60 * 1000);++ // Create agents with different updatedAt+ const [oldAgent] = await serverDB+ .insert(agents)+ .values({+ createdAt: twoDaysAgo,+ title: 'Old Agent',+ updatedAt: twoDaysAgo,+ userId,+ virtual: false,+ })+ .returning();++ const [oldSession] = await serverDB+ .insert(sessions)+ .values({+ userId,+ })+ .returning();++ await serverDB.insert(agentsToSessions).values({+ agentId: oldAgent.id,+ sessionId: oldSession.id,+ userId,+ });++ const [newAgent] = await serverDB+ .insert(agents)+ .values({+ createdAt: now,+ title: 'New Agent',+ updatedAt: now,+ userId,+ virtual: false,+ })+ .returning();++ const [newSession] = await serverDB+ .insert(sessions)+ .values({+ userId,+ })+ .returning();++ await serverDB.insert(agentsToSessions).values({+ agentId: newAgent.id,+ sessionId: newSession.id,+ userId,+ });++ const [midAgent] = await serverDB+ .insert(agents)+ .values({+ createdAt: yesterday,+ title: 'Mid Agent',+ updatedAt: yesterday,+ userId,+ virtual: false,+ })+ .returning();++ const [midSession] = await serverDB+ .insert(sessions)+ .values({+ userId,+ })+ .returning();++ await serverDB.insert(agentsToSessions).values({+ agentId: midAgent.id,+ sessionId: midSession.id,+ userId,+ });++ const result = await homeRepo.getSidebarAgentList();++ expect(result.ungrouped).toHaveLength(3);+ expect(result.ungrouped[0].title).toBe('New Agent');+ expect(result.ungrouped[1].title).toBe('Mid Agent');+ expect(result.ungrouped[2].title).toBe('Old Agent');+ });+ });++ describe('getSidebarAgentList - mixed items', () => {+ it('should return both agents and chat groups in correct categories', async () => {+ // Create session group+ const [folder] = await serverDB+ .insert(sessionGroups)+ .values({+ name: 'My Folder',+ sort: 1,+ userId,+ })+ .returning();++ // Create pinned agent+ const [pinnedAgent] = await serverDB+ .insert(agents)+ .values({+ title: 'Pinned Agent',+ userId,+ virtual: false,+ })+ .returning();++ const [pinnedSession] = await serverDB+ .insert(sessions)+ .values({+ pinned: true,+ userId,+ })+ .returning();++ await serverDB.insert(agentsToSessions).values({+ agentId: pinnedAgent.id,+ sessionId: pinnedSession.id,+ userId,+ });++ // Create grouped agent+ const [groupedAgent] = await serverDB+ .insert(agents)+ .values({+ title: 'Grouped Agent',+ userId,+ virtual: false,+ })+ .returning();++ const [groupedSession] = await serverDB+ .insert(sessions)+ .values({+ groupId: folder.id,+ pinned: false,+ userId,+ })+ .returning();++ await serverDB.insert(agentsToSessions).values({+ agentId: groupedAgent.id,+ sessionId: groupedSession.id,+ userId,+ });++ // Create ungrouped chat group+ await serverDB.insert(chatGroups).values({+ pinned: false,+ title: 'Ungrouped Chat',+ userId,+ });++ // Create pinned chat group+ await serverDB.insert(chatGroups).values({+ pinned: true,+ title: 'Pinned Chat',+ userId,+ });++ const result = await homeRepo.getSidebarAgentList();++ // Verify pinned items+ expect(result.pinned).toHaveLength(2);+ const pinnedTitles = result.pinned.map((p) => p.title);+ expect(pinnedTitles).toContain('Pinned Agent');+ expect(pinnedTitles).toContain('Pinned Chat');++ // Verify grouped items+ expect(result.groups).toHaveLength(1);+ expect(result.groups[0].items).toHaveLength(1);+ expect(result.groups[0].items[0].title).toBe('Grouped Agent');++ // Verify ungrouped items+ expect(result.ungrouped).toHaveLength(1);+ expect(result.ungrouped[0].title).toBe('Ungrouped Chat');+ });+ });++ describe('searchAgents', () => {+ it('should return empty array for empty keyword', async () => {+ const result = await homeRepo.searchAgents('');+ expect(result).toEqual([]);++ const resultWhitespace = await homeRepo.searchAgents(' ');+ expect(resultWhitespace).toEqual([]);+ });++ it('should search agents by title', async () => {+ // Create agents+ const [agent1] = await serverDB+ .insert(agents)+ .values({+ title: 'Coding Assistant',+ userId,+ virtual: false,+ })+ .returning();++ const [session1] = await serverDB.insert(sessions).values({ userId }).returning();++ await serverDB.insert(agentsToSessions).values({+ agentId: agent1.id,+ sessionId: session1.id,+ userId,+ });++ const [agent2] = await serverDB+ .insert(agents)+ .values({+ title: 'Writing Helper',+ userId,+ virtual: false,+ })+ .returning();++ const [session2] = await serverDB.insert(sessions).values({ userId }).returning();++ await serverDB.insert(agentsToSessions).values({+ agentId: agent2.id,+ sessionId: session2.id,+ userId,+ });++ const result = await homeRepo.searchAgents('coding');++ expect(result).toHaveLength(1);+ expect(result[0].title).toBe('Coding Assistant');+ expect(result[0].type).toBe('agent');+ });++ it('should search agents by description', async () => {+ const [agent] = await serverDB+ .insert(agents)+ .values({+ description: 'Helps with Python programming',+ title: 'Code Helper',+ userId,+ virtual: false,+ })+ .returning();++ const [session] = await serverDB.insert(sessions).values({ userId }).returning();++ await serverDB.insert(agentsToSessions).values({+ agentId: agent.id,+ sessionId: session.id,+ userId,+ });++ const result = await homeRepo.searchAgents('python');++ expect(result).toHaveLength(1);+ expect(result[0].title).toBe('Code Helper');+ });++ it('should search chat groups by title', async () => {+ await serverDB.insert(chatGroups).values({+ title: 'Team Discussion',+ userId,+ });++ await serverDB.insert(chatGroups).values({+ title: 'Project Meeting',+ userId,+ });++ const result = await homeRepo.searchAgents('discussion');++ expect(result).toHaveLength(1);+ expect(result[0].title).toBe('Team Discussion');+ expect(result[0].type).toBe('group');+ });++ it('should search chat groups by description', async () => {+ await serverDB.insert(chatGroups).values({+ description: 'Weekly sync about frontend tasks',+ title: 'Frontend Team',+ userId,+ });++ const result = await homeRepo.searchAgents('frontend');++ expect(result).toHaveLength(1);+ expect(result[0].title).toBe('Frontend Team');+ });++ it('should return both agents and chat groups matching the keyword', async () => {+ // Create agent with 'dev' in title+ const [agent] = await serverDB+ .insert(agents)+ .values({+ title: 'Dev Assistant',+ userId,+ virtual: false,+ })+ .returning();++ const [session] = await serverDB.insert(sessions).values({ userId }).returning();++ await serverDB.insert(agentsToSessions).values({+ agentId: agent.id,+ sessionId: session.id,+ userId,+ });++ // Create chat group with 'dev' in title+ await serverDB.insert(chatGroups).values({+ title: 'Dev Team Chat',+ userId,+ });++ const result = await homeRepo.searchAgents('dev');++ expect(result).toHaveLength(2);+ const titles = result.map((r) => r.title);+ expect(titles).toContain('Dev Assistant');+ expect(titles).toContain('Dev Team Chat');+ });++ it('should be case insensitive', async () => {+ const [agent] = await serverDB+ .insert(agents)+ .values({+ title: 'JavaScript Expert',+ userId,+ virtual: false,+ })+ .returning();++ const [session] = await serverDB.insert(sessions).values({ userId }).returning();++ await serverDB.insert(agentsToSessions).values({+ agentId: agent.id,+ sessionId: session.id,+ userId,+ });++ const resultLower = await homeRepo.searchAgents('javascript');+ const resultUpper = await homeRepo.searchAgents('JAVASCRIPT');+ const resultMixed = await homeRepo.searchAgents('JavaScript');++ expect(resultLower).toHaveLength(1);+ expect(resultUpper).toHaveLength(1);+ expect(resultMixed).toHaveLength(1);+ });++ it('should exclude virtual agents', async () => {+ const [virtualAgent] = await serverDB+ .insert(agents)+ .values({+ title: 'Inbox Agent',+ userId,+ virtual: true,+ })+ .returning();++ const [session] = await serverDB.insert(sessions).values({ userId }).returning();++ await serverDB.insert(agentsToSessions).values({+ agentId: virtualAgent.id,+ sessionId: session.id,+ userId,+ });++ const result = await homeRepo.searchAgents('inbox');++ expect(result).toHaveLength(0);+ });++ it('should only return current user items', async () => {+ // Create agent for current user+ const [userAgent] = await serverDB+ .insert(agents)+ .values({+ title: 'Search Test Agent',+ userId,+ virtual: false,+ })+ .returning();++ const [userSession] = await serverDB.insert(sessions).values({ userId }).returning();++ await serverDB.insert(agentsToSessions).values({+ agentId: userAgent.id,+ sessionId: userSession.id,+ userId,+ });++ // Create agent for other user with same title+ const [otherAgent] = await serverDB+ .insert(agents)+ .values({+ title: 'Search Test Agent',+ userId: otherUserId,+ virtual: false,+ })+ .returning();++ const [otherSession] = await serverDB+ .insert(sessions)+ .values({ userId: otherUserId })+ .returning();++ await serverDB.insert(agentsToSessions).values({+ agentId: otherAgent.id,+ sessionId: otherSession.id,+ userId: otherUserId,+ });++ const result = await homeRepo.searchAgents('search test');++ expect(result).toHaveLength(1);+ expect(result[0].id).toBe(userAgent.id);+ });++ it('should sort results by updatedAt descending', async () => {+ const now = new Date();+ const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);++ const [oldAgent] = await serverDB+ .insert(agents)+ .values({+ createdAt: yesterday,+ title: 'Old Search Agent',+ updatedAt: yesterday,+ userId,+ virtual: false,+ })+ .returning();++ const [oldSession] = await serverDB.insert(sessions).values({ userId }).returning();++ await serverDB.insert(agentsToSessions).values({+ agentId: oldAgent.id,+ sessionId: oldSession.id,+ userId,+ });++ const [newAgent] = await serverDB+ .insert(agents)+ .values({+ createdAt: now,+ title: 'New Search Agent',+ updatedAt: now,+ userId,+ virtual: false,+ })+ .returning();++ const [newSession] = await serverDB.insert(sessions).values({ userId }).returning();++ await serverDB.insert(agentsToSessions).values({+ agentId: newAgent.id,+ sessionId: newSession.id,+ userId,+ });++ const result = await homeRepo.searchAgents('search agent');++ expect(result).toHaveLength(2);+ expect(result[0].title).toBe('New Search Agent');+ expect(result[1].title).toBe('Old Search Agent');+ });+ });+});diff --git a/packages/database/src/repositories/home/index.ts b/packages/database/src/repositories/home/index.tsnew file mode 100644index 00000000000..9daa927c1cb--- /dev/null+++ b/packages/database/src/repositories/home/index.ts@@ -0,0 +1,318 @@+import { SidebarAgentItem, SidebarAgentListResponse, SidebarGroup } from '@lobechat/types';+import { cleanObject } from '@lobechat/utils';+import { and, desc, eq, ilike, inArray, or } from 'drizzle-orm';++import {+ agents,+ agentsToSessions,+ chatGroups,+ chatGroupsAgents,+ sessionGroups,+ sessions,+} from '../../schemas';+import { LobeChatDatabase } from '../../type';++// Re-export types for backward compatibility+export type {+ SidebarAgentItem,+ SidebarAgentListResponse,+ SidebarGroup,+ SidebarItemType,+} from '@lobechat/types';++/**+ * Home Repository - provides sidebar agent list data+ */+export class HomeRepository {+ private userId: string;+ private db: LobeChatDatabase;++ constructor(db: LobeChatDatabase, userId: string) {+ this.userId = userId;+ this.db = db;+ }++ /**+ * Get sidebar agent list with pinned, grouped, and ungrouped items+ */+ async getSidebarAgentList(): Promise<SidebarAgentListResponse> {+ // 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+ const agentList = await this.db+ .select({+ avatar: agents.avatar,+ description: agents.description,+ groupId: sessions.groupId,+ id: agents.id,+ pinned: agents.pinned,+ sessionId: sessions.id,+ sessionPinned: sessions.pinned,+ title: agents.title,+ updatedAt: agents.updatedAt,+ })+ .from(agents)+ .innerJoin(agentsToSessions, eq(agents.id, agentsToSessions.agentId))+ .innerJoin(sessions, eq(agentsToSessions.sessionId, sessions.id))+ .where(and(eq(agents.userId, this.userId), eq(agents.virtual, false)))+ .orderBy(desc(agents.updatedAt));++ // 2. Query all chatGroups (group chats)+ const chatGroupList = await this.db+ .select({+ description: chatGroups.description,+ groupId: chatGroups.groupId,+ id: chatGroups.id,+ pinned: chatGroups.pinned,+ title: chatGroups.title,+ updatedAt: chatGroups.updatedAt,+ })+ .from(chatGroups)+ .where(eq(chatGroups.userId, this.userId))+ .orderBy(desc(chatGroups.updatedAt));++ // 2.1 Query member avatars for each chat group+ const chatGroupIds = chatGroupList.map((g) => g.id);+ const memberAvatarsMap = new Map<string, Array<{ avatar: string; background?: string }>>();++ if (chatGroupIds.length > 0) {+ const memberAvatars = await this.db+ .select({+ avatar: agents.avatar,+ backgroundColor: agents.backgroundColor,+ chatGroupId: chatGroupsAgents.chatGroupId,+ })+ .from(chatGroupsAgents)+ .innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))+ .where(inArray(chatGroupsAgents.chatGroupId, chatGroupIds))+ .orderBy(chatGroupsAgents.order);++ for (const member of memberAvatars) {+ const existing = memberAvatarsMap.get(member.chatGroupId) || [];+ if (member.avatar) {+ existing.push({+ avatar: member.avatar,+ background: member.backgroundColor ?? undefined,+ });+ }+ memberAvatarsMap.set(member.chatGroupId, existing);+ }+ }++ // 3. Query all sessionGroups (user-defined folders)+ const groupList = await this.db+ .select({+ id: sessionGroups.id,+ name: sessionGroups.name,+ sort: sessionGroups.sort,+ })+ .from(sessionGroups)+ .where(eq(sessionGroups.userId, this.userId))+ .orderBy(sessionGroups.sort);++ // 4. Process and categorize+ return this.processAgentList(agentList, chatGroupList, groupList, memberAvatarsMap);+ }++ private processAgentList(+ agentItems: Array<{+ avatar: string | null;+ description: string | null;+ groupId: string | null;+ id: string;+ pinned: boolean | null;+ sessionId: string;+ sessionPinned: boolean | null;+ title: string | null;+ updatedAt: Date;+ }>,+ chatGroupItems: Array<{+ description: string | null;+ groupId: string | null;+ id: string;+ pinned: boolean | null;+ title: string | null;+ updatedAt: Date;+ }>,+ groupItems: Array<{+ id: string;+ name: string;+ sort: number | null;+ }>,+ memberAvatarsMap: Map<string, Array<{ avatar: string; background?: string }>>,+ ): SidebarAgentListResponse {+ // Convert to unified format+ // For pinned status: agents.pinned takes priority, fallback to sessions.pinned for backward compatibility+ const allItems: Array<SidebarAgentItem & { groupId: string | null }> = [+ ...agentItems.map((a) => ({+ avatar: a.avatar,+ description: a.description,+ groupId: a.groupId,+ id: a.id,+ pinned: a.pinned ?? a.sessionPinned ?? false,+ sessionId: a.sessionId,+ title: a.title,+ type: 'agent' as const,+ updatedAt: a.updatedAt,+ })),+ ...chatGroupItems.map((g) => ({+ avatar: memberAvatarsMap.get(g.id) ?? null,+ description: g.description,+ groupId: g.groupId,+ id: g.id,+ pinned: g.pinned ?? false,+ sessionId: null,+ title: g.title,+ type: 'group' as const,+ updatedAt: g.updatedAt,+ })),+ ];++ // Sort all items by updatedAt descending+ allItems.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());++ // Categorize: pinned / grouped / ungrouped+ const pinned: SidebarAgentItem[] = [];+ const ungrouped: SidebarAgentItem[] = [];+ const groupedMap = new Map<string, SidebarAgentItem[]>();++ for (const item of allItems) {+ const { groupId, ...sidebarItem } = item;+ const cleanedItem = cleanObject(sidebarItem) as SidebarAgentItem;++ if (item.pinned) {+ pinned.push(cleanedItem);+ } else if (groupId) {+ const existing = groupedMap.get(groupId) || [];+ existing.push(cleanedItem);+ groupedMap.set(groupId, existing);+ } else {+ ungrouped.push(cleanedItem);+ }+ }++ // Build groups array with items+ const groups: SidebarGroup[] = groupItems.map((g) => ({+ id: g.id,+ items: groupedMap.get(g.id) || [],+ name: g.name,+ sort: g.sort,+ }));++ return { groups, pinned, ungrouped };+ }++ /**+ * Search agents and chat groups by keyword+ * Searches in title and description fields+ */+ async searchAgents(keyword: string): Promise<SidebarAgentItem[]> {+ if (!keyword.trim()) return [];++ const searchPattern = `%${keyword.toLowerCase()}%`;++ // 1. Search agents by title or description+ // Note: We query both agents.pinned and sessions.pinned for backward compatibility+ const agentResults = await this.db+ .select({+ avatar: agents.avatar,+ description: agents.description,+ id: agents.id,+ pinned: agents.pinned,+ sessionId: sessions.id,+ sessionPinned: sessions.pinned,+ title: agents.title,+ updatedAt: agents.updatedAt,+ })+ .from(agents)+ .innerJoin(agentsToSessions, eq(agents.id, agentsToSessions.agentId))+ .innerJoin(sessions, eq(agentsToSessions.sessionId, sessions.id))+ .where(+ and(+ eq(agents.userId, this.userId),+ eq(agents.virtual, false),+ or(ilike(agents.title, searchPattern), ilike(agents.description, searchPattern)),+ ),+ )+ .orderBy(desc(agents.updatedAt));++ // 2. Search chat groups by title or description+ const chatGroupResults = await this.db+ .select({+ description: chatGroups.description,+ id: chatGroups.id,+ pinned: chatGroups.pinned,+ title: chatGroups.title,+ updatedAt: chatGroups.updatedAt,+ })+ .from(chatGroups)+ .where(+ and(+ eq(chatGroups.userId, this.userId),+ or(ilike(chatGroups.title, searchPattern), ilike(chatGroups.description, searchPattern)),+ ),+ )+ .orderBy(desc(chatGroups.updatedAt));++ // 2.1 Query member avatars for matching chat groups+ const chatGroupIds = chatGroupResults.map((g) => g.id);+ const memberAvatarsMap = new Map<string, Array<{ avatar: string; background?: string }>>();++ if (chatGroupIds.length > 0) {+ const memberAvatars = await this.db+ .select({+ avatar: agents.avatar,+ backgroundColor: agents.backgroundColor,+ chatGroupId: chatGroupsAgents.chatGroupId,+ })+ .from(chatGroupsAgents)+ .innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))+ .where(inArray(chatGroupsAgents.chatGroupId, chatGroupIds))+ .orderBy(chatGroupsAgents.order);++ for (const member of memberAvatars) {+ const existing = memberAvatarsMap.get(member.chatGroupId) || [];+ if (member.avatar) {+ existing.push({+ avatar: member.avatar,+ background: member.backgroundColor ?? undefined,+ });+ }+ memberAvatarsMap.set(member.chatGroupId, existing);+ }+ }++ // 3. Combine and format results+ // For pinned status: agents.pinned takes priority, fallback to sessions.pinned for backward compatibility+ const results: SidebarAgentItem[] = [+ ...agentResults.map((a) =>+ cleanObject({+ avatar: a.avatar,+ description: a.description,+ id: a.id,+ pinned: a.pinned ?? a.sessionPinned ?? false,+ sessionId: a.sessionId,+ title: a.title,+ type: 'agent' as const,+ updatedAt: a.updatedAt,+ }),+ ),+ ...chatGroupResults.map((g) =>+ cleanObject({+ avatar: memberAvatarsMap.get(g.id),+ description: g.description,+ id: g.id,+ pinned: g.pinned ?? false,+ title: g.title,+ type: 'group' as const,+ updatedAt: g.updatedAt,+ }),+ ),+ ] as SidebarAgentItem[];++ // Sort by updatedAt descending+ results.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());++ return results;+ }+}diff --git a/packages/database/src/schemas/chatGroup.ts b/packages/database/src/schemas/chatGroup.tsindex ff28e1591b1..0952ceeb205 100644--- a/packages/database/src/schemas/chatGroup.ts+++ b/packages/database/src/schemas/chatGroup.ts@@ -97,4 +97,4 @@ export const chatGroupsAgents = pgTable();export type NewChatGroupAgent = typeof chatGroupsAgents.$inferInsert;-export type ChatGroupAgentItem = typeof agents.$inferInsert;+export type ChatGroupAgentItem = typeof chatGroupsAgents.$inferSelect;diff --git a/packages/prompts/src/prompts/groupChat/__snapshots__/index.test.ts.snap b/packages/prompts/src/prompts/groupChat/__snapshots__/index.test.ts.snapindex 99d75d970d1..ab450816a9b 100644--- a/packages/prompts/src/prompts/groupChat/__snapshots__/index.test.ts.snap+++ b/packages/prompts/src/prompts/groupChat/__snapshots__/index.test.ts.snap@@ -12,16 +12,8 @@ Guidelines:- Keep your responses concise and relevant to the ongoing discussion<group_members>-[- {- "id": "user",- "title": "User Name"- },- {- "id": "agent-1",- "title": "Agent One"- }-]+ <member id="user" title="User Name" />+ <member id="agent-1" title="Agent One" /></group_members>Now it's your turn to respond. You are sending message to the group publicly. Please respond as this agent would, considering the full conversation history provided above. Directly return the message content, no other text. You do not need add author name or anything else."diff --git a/packages/prompts/src/prompts/groupChat/index.ts b/packages/prompts/src/prompts/groupChat/index.tsindex 2ee99fa01de..f9ca8d63e0c 100644--- a/packages/prompts/src/prompts/groupChat/index.ts+++ b/packages/prompts/src/prompts/groupChat/index.ts@@ -13,7 +13,10 @@ export interface SupervisorTodoItem {const buildGroupMembersTag = (members: GroupMemberInfo[]): string => {if (!members || members.length === 0) return '';- return `<group_members>\n${JSON.stringify(members, null, 2)}\n</group_members>`;+ const memberList = members+ .map((member) => ` <member id="${member.id}" title="${member.title}" />`)+ .join('\n');+ return `<group_members>\n${memberList}\n</group_members>`;};export const buildGroupChatSystemPrompt = ({diff --git a/packages/prompts/src/prompts/gtd/index.test.ts b/packages/prompts/src/prompts/gtd/index.test.tsnew file mode 100644index 00000000000..db09b7ef3e4--- /dev/null+++ b/packages/prompts/src/prompts/gtd/index.test.ts@@ -0,0 +1,75 @@+import { describe, expect, it } from 'vitest';++import { formatTodoStateSummary } from './index';++describe('formatTodoStateSummary', () => {+ it('should format empty todo list', () => {+ expect(formatTodoStateSummary([])).toMatchInlineSnapshot(`"📋 Current Todo List: (empty)"`);+ });++ it('should format empty todo list with timestamp', () => {+ expect(formatTodoStateSummary([], '2025-01-15T10:30:00.000Z')).toMatchInlineSnapshot(+ `"📋 Current Todo List: (empty) | Updated: 2025-01-15T10:30:00.000Z"`,+ );+ });++ it('should format todo list with only pending items', () => {+ const todos = [+ { text: 'Task A', completed: false },+ { text: 'Task B', completed: false },+ { text: 'Task C', completed: false },+ ];+ expect(formatTodoStateSummary(todos)).toMatchInlineSnapshot(`+ "📋 Current Todo List (3 pending, 0 completed):+ - [ ] Task A+ - [ ] Task B+ - [ ] Task C"+ `);+ });++ it('should format todo list with only completed items', () => {+ const todos = [+ { text: 'Done task 1', completed: true },+ { text: 'Done task 2', completed: true },+ ];+ expect(formatTodoStateSummary(todos)).toMatchInlineSnapshot(`+ "📋 Current Todo List (0 pending, 2 completed):+ - [x] Done task 1+ - [x] Done task 2"+ `);+ });++ it('should format todo list with mixed items', () => {+ const todos = [+ { text: 'Pending task', completed: false },+ { text: 'Completed task', completed: true },+ { text: 'Another pending', completed: false },+ ];+ expect(formatTodoStateSummary(todos)).toMatchInlineSnapshot(`+ "📋 Current Todo List (2 pending, 1 completed):+ - [ ] Pending task+ - [x] Completed task+ - [ ] Another pending"+ `);+ });++ it('should format todo list with timestamp', () => {+ const todos = [+ { text: 'Task 1', completed: false },+ { text: 'Task 2', completed: true },+ ];+ expect(formatTodoStateSummary(todos, '2025-01-15T10:30:00.000Z')).toMatchInlineSnapshot(`+ "📋 Current Todo List (1 pending, 1 completed) | Updated: 2025-01-15T10:30:00.000Z:+ - [ ] Task 1+ - [x] Task 2"+ `);+ });++ it('should handle single item', () => {+ const todos = [{ text: 'Only task', completed: false }];+ expect(formatTodoStateSummary(todos)).toMatchInlineSnapshot(`+ "📋 Current Todo List (1 pending, 0 completed):+ - [ ] Only task"+ `);+ });+});diff --git a/packages/prompts/src/prompts/gtd/index.ts b/packages/prompts/src/prompts/gtd/index.tsnew file mode 100644index 00000000000..9ca67cc2a75--- /dev/null+++ b/packages/prompts/src/prompts/gtd/index.ts@@ -0,0 +1,29 @@+export interface TodoItem {+ completed: boolean;+ text: string;+}++/**+ * Format a unified todo state summary for tool response content+ *+ * @param todos - The current todo items+ * @param updatedAt - Optional timestamp when the list was last updated+ * @returns Formatted string showing current todo list state+ */+export const formatTodoStateSummary = (todos: TodoItem[], updatedAt?: string): string => {+ const timeInfo = updatedAt ? ` | Updated: ${updatedAt}` : '';++ if (todos.length === 0) {+ return `📋 Current Todo List: (empty)${timeInfo}`;+ }++ const completed = todos.filter((t) => t.completed).length;+ const pending = todos.length - completed;++ const lines = todos.map((item) => {+ const checkbox = item.completed ? '- [x]' : '- [ ]';+ return `${checkbox} ${item.text}`;+ });++ return `📋 Current Todo List (${pending} pending, ${completed} completed)${timeInfo}:\n${lines.join('\n')}`;+};diff --git a/packages/prompts/src/prompts/index.ts b/packages/prompts/src/prompts/index.tsindex 2f4d1a17198..8f87a556f44 100644--- a/packages/prompts/src/prompts/index.ts+++ b/packages/prompts/src/prompts/index.ts@@ -1,6 +1,7 @@export * from './chatMessages';export * from './files';export * from './groupChat';+export * from './gtd';export * from './knowledgeBaseQA';export * from './plugin';export * from './search';diff --git a/packages/types/src/agentGroup/index.ts b/packages/types/src/agentGroup/index.tsnew file mode 100644index 00000000000..46d263e98d5--- /dev/null+++ b/packages/types/src/agentGroup/index.ts@@ -0,0 +1,323 @@+import { AgentItem } from '../agent';+import { TaskDetail, UIChatMessage } from '../message';+import { ChatTopic } from '../topic';++export interface LobeChatGroupMetaConfig {+ description: string;+ title: string;+}++export interface LobeChatGroupChatConfig {+ allowDM: boolean;+ enableSupervisor: boolean;+ maxResponseInRow: number;+ openingMessage?: string;+ openingQuestions?: string[];+ orchestratorModel: string;+ orchestratorProvider: string;+ responseOrder: 'sequential' | 'natural';+ responseSpeed: 'slow' | 'medium' | 'fast';+ revealDM: boolean;+ scene: 'casual' | 'productive';+ systemPrompt?: string;+}++// Database config type (flat structure)+export type LobeChatGroupConfig = LobeChatGroupChatConfig;++// Full group type with nested structure for UI components+export interface LobeChatGroupFullConfig {+ chat: LobeChatGroupChatConfig;+ meta: LobeChatGroupMetaConfig;+}++// Chat Group Agent types (independent from schema)+export interface ChatGroupAgent {+ agentId: string;+ chatGroupId: string;+ createdAt: Date;+ enabled?: boolean;+ order?: number;+ role?: string;+ updatedAt: Date;+ userId: string;+}++export interface NewChatGroupAgent {+ agentId: string;+ chatGroupId: string;+ enabled?: boolean;+ order?: number;+ role?: string;+ userId: string;+}++// New Chat Group type for creating groups (independent from schema)+export interface NewChatGroup {+ clientId?: string | null;+ config?: LobeChatGroupConfig | null;+ description?: string | null;+ groupId?: string | null;+ id?: string;+ pinned?: boolean | null;+ title?: string | null;+ userId: string;+}++// Chat Group Item type (independent from schema)+export interface ChatGroupItem {+ accessedAt?: Date;+ clientId?: string | null;+ config?: LobeChatGroupConfig | null;+ createdAt: Date;+ description?: string | null;+ groupId?: string | null;+ id: string;+ pinned?: boolean | null;+ title?: string | null;+ updatedAt: Date;+ userId: string;+}++// Agent item with group role info+export type AgentGroupMember = AgentItem & {+ /**+ * Whether this agent is the supervisor of the group+ */+ isSupervisor: boolean;+};++// Agent Group Detail - extends ChatGroupItem with agents+export interface AgentGroupDetail extends ChatGroupItem {+ agents: AgentGroupMember[];+ /**+ * The supervisor agent ID, if exists+ */+ supervisorAgentId?: string;+}++// ============ Agent Execution Types ============++/**+ * Application context for message storage+ */+export interface ExecAgentAppContext {+ /** Group ID for group chat */+ groupId?: string | null;+ /** Scope identifier */+ scope?: string | null;+ /** Session ID */+ sessionId?: string;+ /** Thread ID for threaded conversations */+ threadId?: string | null;+ /** Topic ID */+ topicId?: string | null;+}++/**+ * Parameters for execAgent - execute a single Agent+ * Either agentId or slug must be provided+ */+export interface ExecAgentParams {+ /** The agent ID to run (either agentId or slug is required) */+ agentId?: string;+ /** Application context for message storage */+ appContext?: ExecAgentAppContext;+ /** Whether to auto-start execution after creating operation (default: true) */+ autoStart?: boolean;+ /** Optional existing message IDs to include in context */+ existingMessageIds?: string[];+ /** The user input/prompt */+ prompt: string;+ /** The agent slug to run (either agentId or slug is required) */+ slug?: string;+}++/**+ * Response from execAgent+ */+export interface ExecAgentResult {+ /** The resolved agent ID */+ agentId: string;+ /** The assistant message ID created for this operation */+ assistantMessageId: string;+ /** Whether the operation was auto-started */+ autoStarted: boolean;+ /** Timestamp when operation was created */+ createdAt: string;+ /** Error message if operation failed to start */+ error?: string;+ /** Status message */+ message: string;+ /** Queue message ID if auto-started */+ messageId?: string;+ /** Operation ID for SSE connection */+ operationId: string;+ /** Operation status */+ status: string;+ /** Whether the operation was created successfully */+ success: boolean;+ /** ISO timestamp */+ timestamp: string;+ /** The topic ID (created or reused) */+ topicId: string;+ /** The user message ID created for this operation */+ userMessageId: string;+}++// ============ Group Agent Execution Types ============++/**+ * Options for creating a new topic in group chat+ */+export interface ExecGroupAgentNewTopicOptions {+ /** Topic title */+ title?: string;+ /** Message IDs to include in the topic */+ topicMessageIds?: string[];+}++/**+ * Parameters for execGroupAgent - execute Supervisor Agent in Group chat+ */+export interface ExecGroupAgentParams {+ /** The Supervisor agent ID */+ agentId: string;+ /** File IDs attached to the message */+ files?: string[];+ /** The Group ID */+ groupId: string;+ /** User message content */+ message: string;+ /** Optional: Create a new topic */+ newTopic?: ExecGroupAgentNewTopicOptions;+ /** Existing topic ID */+ topicId?: string | null;+}++/**+ * Result from execGroupAgent (internal, without messages/topics)+ */+export interface ExecGroupAgentResult {+ /** The assistant message ID created for this operation */+ assistantMessageId: string;+ /** Error message if operation failed to start */+ error?: string;+ /** Whether a new topic was created */+ isCreateNewTopic: boolean;+ /** Operation ID for SSE connection */+ operationId: string;+ /** Whether the operation was created successfully */+ success?: boolean;+ /** The topic ID */+ topicId: string;+ /** The user message ID created for this operation */+ userMessageId: string;+}++/**+ * Response from execGroupAgent (with messages/topics for UI sync)+ */+export interface ExecGroupAgentResponse {+ /** The assistant message ID created for this operation */+ assistantMessageId: string;+ /** Error message if operation failed to start */+ error?: string;+ /** Whether a new topic was created */+ isCreateNewTopic: boolean;+ /** Latest messages in the conversation */+ messages: UIChatMessage[];+ /** Operation ID for SSE connection */+ operationId: string;+ /** Whether the operation was created successfully */+ success?: boolean;+ /** The topic ID */+ topicId: string;+ /** Topics list (if new topic was created) */+ topics?: {+ items: ChatTopic[];+ total: number;+ };+ /** The user message ID created for this operation */+ userMessageId: string;+}++// ============ Group SubAgent Task Execution Types ============++/**+ * Parameters for execGroupSubAgentTask - execute SubAgent task in Group chat+ * This is called by Supervisor to delegate tasks to SubAgents+ */+export interface ExecGroupSubAgentTaskParams {+ /** The SubAgent ID to execute the task */+ agentId: string;+ /** The Group ID (required) */+ groupId: string;+ /** Task instruction/prompt for the SubAgent */+ instruction: string;+ /** The parent message ID (Supervisor's tool call message) */+ parentMessageId: string;+ /** Timeout in milliseconds (optional) */+ timeout?: number;+ /** The Topic ID */+ topicId: string;+}++/**+ * Result from execGroupSubAgentTask+ */+export interface ExecGroupSubAgentTaskResult {+ /** The assistant message ID created for this task */+ assistantMessageId: string;+ /** Error message if task failed to start */+ error?: string;+ /** Operation ID for tracking execution status */+ operationId: string;+ /** Whether the task was created successfully */+ success: boolean;+ /** The Thread ID where the task is executed */+ threadId: string;+}++/**+ * Current activity for real-time progress display+ * Only returned when task is processing+ */+export interface TaskCurrentActivity {+ /** API name, e.g. "search" */+ apiName?: string;+ /** Content preview (truncated) */+ contentPreview?: string;+ /** Plugin identifier, e.g. "lobe-web-browsing" */+ identifier?: string;+ /** Activity type */+ type: 'tool_calling' | 'tool_result' | 'generating';+}++/**+ * Task status query result+ */+export interface TaskStatusResult {+ /** Task completion time (ISO string) */+ completedAt?: string;+ /** Cost information */+ cost?: { total: number };+ /** Current activity for real-time progress display (only when processing) */+ currentActivity?: TaskCurrentActivity;+ /** Error message if task failed */+ error?: string;+ /** Task result content (last assistant message) */+ result?: string;+ /** Current task status */+ status: 'processing' | 'completed' | 'failed' | 'cancel';+ /** Number of steps executed */+ stepCount?: number;+ /** Task detail from Thread table */+ taskDetail?: TaskDetail;+ /** Model usage information */+ usage?: {+ completion_tokens?: number;+ prompt_tokens?: number;+ total_tokens?: number;+ };+}diff --git a/packages/types/src/aiChat.ts b/packages/types/src/aiChat.tsindex 08ce20affac..beab9f02424 100644--- a/packages/types/src/aiChat.ts+++ b/packages/types/src/aiChat.ts@@ -4,6 +4,7 @@ import { UIChatMessage } from './message';import { OpenAIChatMessage } from './openai/chat';import { LobeUniformTool, LobeUniformToolSchema } from './tool';import { ChatTopic } from './topic';+import { IThreadType, ThreadType } from './topic/thread';export interface SendNewMessage {content: string;@@ -12,11 +13,36 @@ export interface SendNewMessage {parentId?: string;}+/**+ * Parameters for creating a new thread along with message+ */+export interface CreateThreadWithMessageParams {+ /** Parent thread ID (for nested threads) */+ parentThreadId?: string;+ /** Source message ID that the thread is branched from (optional for standalone threads) */+ sourceMessageId?: string;+ /** Optional thread title */+ title?: string;+ /** Thread type */+ type: IThreadType;+}+export interface SendMessageServerParams {+ agentId?: string;+ /**+ * Group ID for group chat scenarios+ * Used to associate the topic with a specific group+ */+ groupId?: string;newAssistantMessage: {model: string;provider: string;};+ /**+ * Optional: Create a new thread along with the message+ * If provided, the message will be created in the newly created thread+ */+ newThread?: CreateThreadWithMessageParams;newTopic?: {title?: string;topicMessageIds?: string[];@@ -28,11 +54,21 @@ export interface SendMessageServerParams {topicId?: string;}+export const CreateThreadWithMessageSchema = z.object({+ parentThreadId: z.string().optional(),+ sourceMessageId: z.string().optional(),+ title: z.string().optional(),+ type: z.enum([ThreadType.Continuation, ThreadType.Standalone, ThreadType.Isolation]),+});+export const AiSendMessageServerSchema = z.object({+ agentId: z.string().optional(),+ groupId: z.string().optional(),newAssistantMessage: z.object({model: z.string().optional(),provider: z.string().optional(),}),+ newThread: CreateThreadWithMessageSchema.optional(),newTopic: z.object({title: z.string().optional(),@@ -51,10 +87,17 @@ export const AiSendMessageServerSchema = z.object({export interface SendMessageServerResponse {assistantMessageId: string;+ /**+ * If a new thread was created, this will be the thread ID+ */+ createdThreadId?: string;isCreateNewTopic: boolean;messages: UIChatMessage[];topicId: string;- topics?: ChatTopic[];+ topics?: {+ items: ChatTopic[];+ total: number;+ };userMessageId: string;}diff --git a/packages/types/src/chatGroup/index.ts b/packages/types/src/chatGroup/index.tsdeleted file mode 100644index 52efce5c5e1..00000000000--- a/packages/types/src/chatGroup/index.ts+++ /dev/null@@ -1,47 +0,0 @@-export interface LobeChatGroupMetaConfig {- description: string;- title: string;-}--export interface LobeChatGroupChatConfig {- allowDM: boolean;- enableSupervisor: boolean;- maxResponseInRow: number;- orchestratorModel: string;- orchestratorProvider: string;- responseOrder: 'sequential' | 'natural';- responseSpeed: 'slow' | 'medium' | 'fast';- revealDM: boolean;- scene: 'casual' | 'productive';- systemPrompt?: string;-}--// Database config type (flat structure)-export type LobeChatGroupConfig = LobeChatGroupChatConfig;--// Full group type with nested structure for UI components-export interface LobeChatGroupFullConfig {- chat: LobeChatGroupChatConfig;- meta: LobeChatGroupMetaConfig;-}--// Chat Group Agent types (independent from schema)-export interface ChatGroupAgent {- agentId: string;- chatGroupId: string;- createdAt: Date;- enabled?: boolean;- order?: number;- role?: string;- updatedAt: Date;- userId: string;-}--export interface NewChatGroupAgent {- agentId: string;- chatGroupId: string;- enabled?: boolean;- order?: number;- role?: string;- userId: string;-}diff --git a/packages/types/src/conversation.ts b/packages/types/src/conversation.tsnew file mode 100644index 00000000000..674448922d6--- /dev/null+++ b/packages/types/src/conversation.ts@@ -0,0 +1,185 @@+import { IThreadType } from './topic/thread';++/**+ * Scope types for message map key generation+ * - main: Agent main conversation (default)+ * - thread: Agent thread conversation+ * - group: Group main conversation+ * - group_agent: Agent conversation within a group+ */+export type MessageMapScope =+ | 'main'+ | 'thread'+ | 'group'+ | 'group_agent'+ | 'group_agent_builder'+ | 'page'+ | 'agent_builder';++/**+ * Context for generating message map key with scope-driven architecture+ *+ * Key format: `{scope}_{scopeId}[_{topicId}][_{subTopicId}][_new]`+ *+ * @example+ * ```ts+ * // Main mode - new topic (default scope)+ * { scopeId: 'agt_xxx' } // => 'main_agt_xxx_new'+ *+ * // Main mode - existing topic+ * { scopeId: 'agt_xxx', topicId: 'tpc_yyy' } // => 'main_agt_xxx_tpc_yyy'+ *+ * // Thread mode - new thread+ * { scope: 'thread', scopeId: 'agt_xxx', topicId: 'tpc_yyy', isNew: true }+ * // => 'thread_agt_xxx_tpc_yyy_new'+ *+ * // Thread mode - existing thread+ * { scope: 'thread', scopeId: 'agt_xxx', topicId: 'tpc_yyy', subTopicId: 'thd_zzz' }+ * // => 'thread_agt_xxx_tpc_yyy_thd_zzz'+ *+ * // Group mode - new topic+ * { scope: 'group', scopeId: 'grp_xxx' } // => 'group_grp_xxx_new'+ *+ * // Group mode - existing topic+ * { scope: 'group', scopeId: 'grp_xxx', topicId: 'tpc_yyy' }+ * // => 'group_grp_xxx_tpc_yyy'+ *+ * // Group agent mode - existing agent topic+ * { scope: 'group_agent', scopeId: 'grp_xxx', topicId: 'tpc_yyy', subTopicId: 'tpc_zzz' }+ * // => 'group_agent_grp_xxx_tpc_yyy_tpc_zzz'+ * ```+ */+export interface MessageMapContext {+ /**+ * Whether this is a new/creating state (for optimistic updates)+ */+ isNew?: boolean;+ /**+ * Scope type for the message map+ * @default 'main'+ */+ scope?: MessageMapScope;+ /**+ * Scope identifier (agentId for main/thread, groupId for group/group_agent)+ */+ scopeId: string;+ /**+ * Sub topic identifier (threadId in agent mode, agent's topicId in group mode)+ */+ subTopicId?: string | null;+ /**+ * Topic identifier+ */+ topicId?: string | null;+}++/* eslint-disable typescript-sort-keys/interface */+/**+ * Context for identifying a conversation or message list+ * This is the standard type for all conversation-related context passing+ *+ * @example+ * ```ts+ * // Basic usage - main conversation+ * const context: ConversationContext = { agentId: 'agent-1' };+ *+ * // With topic+ * const topicContext: ConversationContext = {+ * agentId: 'agent-1',+ * topicId: 'topic-1'+ * };+ *+ * // With existing thread+ * const threadContext: ConversationContext = {+ * agentId: 'agent-1',+ * topicId: 'topic-1',+ * threadId: 'thread-1'+ * };+ *+ * // Creating a new thread (isNew + scope: 'thread')+ * const newThreadContext: ConversationContext = {+ * agentId: 'agent-1',+ * topicId: 'topic-1',+ * scope: 'thread',+ * isNew: true,+ * sourceMessageId: 'msg-1',+ * threadType: ThreadType.Standalone,+ * };+ *+ * // Group conversation+ * const groupContext: ConversationContext = {+ * agentId: 'agent-1',+ * groupId: 'group-1',+ * topicId: 'topic-1',+ * scope: 'group',+ * };+ * ```+ */+export interface ConversationContext {+ agentId: string;+ /**+ * Group ID for group conversations+ * Used when scope is 'group' or 'group_agent'+ */+ groupId?: string;+ /**+ * Sub Agent ID for group orchestration scenarios+ * - Used to get Agent config (model, provider, plugins) instead of agentId+ * - Used to set message.agentId (mark message source)+ * - Falls back to agentId if not set+ *+ * @example+ * ```ts+ * // Supervisor executes: no subAgentId needed+ * { agentId: 'supervisor', groupId: 'group-1', scope: 'group' }+ *+ * // Agent speaks in group: use subAgentId for agent config+ * { agentId: 'supervisor', subAgentId: 'agent-1', groupId: 'group-1', scope: 'group' }+ * ```+ */+ subAgentId?: string;+ /**+ * Whether the current agent is the Supervisor in group orchestration+ * - Used to mark assistant messages with metadata.isSupervisor+ * - conversation-flow will transform role to 'supervisor' for UI rendering+ * - context-engine will restore role back to 'assistant' for model+ */+ isSupervisor?: boolean;+ /**+ * Whether this is creating a new conversation (new topic or new thread)+ * Used for optimistic updates+ */+ isNew?: boolean;+ /**+ * Scope type for the conversation+ * - 'main': Agent main conversation (default)+ * - 'thread': Agent thread conversation+ * - 'group': Group main conversation+ * - 'group_agent': Agent conversation within a group+ * @default 'main' (auto-detected based on threadId)+ */+ scope?: MessageMapScope;+ /**+ * @deprecated Use agentId for agent sessions. This field is kept for backward compatibility.+ */+ sessionId?: string;+ /**+ * Source message ID that the thread is branched from+ * Only used when creating a new thread (isNew=true, scope='thread')+ */+ sourceMessageId?: string;+ /**+ * Thread ID (takes highest priority if present)+ * When present, scope is auto-detected as 'thread'+ */+ threadId?: string | null;+ /**+ * Thread type when creating a new thread+ * Only used when creating a new thread (isNew=true, scope='thread')+ */+ threadType?: IThreadType;+ /**+ * Topic ID+ */+ topicId?: string | null;+}diff --git a/packages/types/src/fetch.ts b/packages/types/src/fetch.tsindex de9d7722913..e2dd07fe13a 100644--- a/packages/types/src/fetch.ts+++ b/packages/types/src/fetch.ts@@ -22,6 +22,7 @@ export const ChatErrorType = {PluginFailToTransformArguments: 'PluginFailToTransformArguments',UnknownChatFetchError: 'UnknownChatFetchError',SystemTimeNotMatchError: 'SystemTimeNotMatchError',+ ServerAgentRuntimeError: 'ServerAgentRuntimeError',// ******* Client Errors ******* //BadRequest: 400,diff --git a/packages/types/src/home.ts b/packages/types/src/home.tsnew file mode 100644index 00000000000..68fc8c63bc1--- /dev/null+++ b/packages/types/src/home.ts@@ -0,0 +1,51 @@+/**+ * Sidebar item type - can be an agent or a chat group+ */+export type SidebarItemType = 'agent' | 'group';++/**+ * Avatar item for group members+ */+export interface GroupMemberAvatar {+ avatar: string;+ background?: string;+}++/**+ * Sidebar agent item - represents an agent or chat group in the sidebar+ */+export interface SidebarAgentItem {+ /**+ * Avatar can be:+ * - string: single avatar for agents+ * - GroupMemberAvatar[]: array of member avatars for groups+ * - null: no avatar+ */+ avatar?: GroupMemberAvatar[] | string | null;+ description?: string | null;+ id: string;+ pinned: boolean;+ sessionId?: string | null;+ title: string | null;+ type: SidebarItemType;+ updatedAt: Date;+}++/**+ * Sidebar group - a user-defined folder containing agents+ */+export interface SidebarGroup {+ id: string;+ items: SidebarAgentItem[];+ name: string;+ sort: number | null;+}++/**+ * Response structure for sidebar agent list+ */+export interface SidebarAgentListResponse {+ groups: SidebarGroup[];+ pinned: SidebarAgentItem[];+ ungrouped: SidebarAgentItem[];+}diff --git a/packages/types/src/message/common/index.ts b/packages/types/src/message/common/index.tsindex 35e171ffd42..f2bb1dc314e 100644--- a/packages/types/src/message/common/index.ts+++ b/packages/types/src/message/common/index.ts@@ -1,5 +1,6 @@export * from './base';export * from './image';+export * from './messageGroup';export * from './metadata';export * from './tools';export * from './translate';diff --git a/packages/types/src/message/common/messageGroup.ts b/packages/types/src/message/common/messageGroup.tsnew file mode 100644index 00000000000..725965dbecb--- /dev/null+++ b/packages/types/src/message/common/messageGroup.ts@@ -0,0 +1,57 @@+/* eslint-disable sort-keys-fix/sort-keys-fix , typescript-sort-keys/interface */++/**+ * Message group type+ * - parallel: multi-model parallel conversations+ * - compression: compressed message group+ */+export const MessageGroupType = {+ Parallel: 'parallel',+ Compression: 'compression',+} as const;++export type IMessageGroupType = (typeof MessageGroupType)[keyof typeof MessageGroupType];++/**+ * Metadata for compression type message groups+ */+export interface CompressionGroupMetadata {+ // Compression range+ startMessageId?: string;+ endMessageId?: string;+ pinnedMessageIds?: string[];++ // Statistics+ originalTokenCount?: number;+ compressedTokenCount?: number;+ originalMessageCount?: number;++ // Compression info+ compressionStrategy?: 'summarize';+ compressedAt?: string;+ modelId?: string;+}++/**+ * Message group item+ */+export interface MessageGroupItem {+ id: string;+ userId: string;+ topicId?: string | null;+ parentGroupId?: string | null;+ parentMessageId?: string | null;++ // Metadata+ title?: string | null;+ description?: string | null;++ // Compression fields+ type?: IMessageGroupType | null;+ content?: string | null;+ editorData?: any | null;++ clientId?: string | null;+ createdAt: Date;+ updatedAt: Date;+}diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.tsindex 0efbb95ed83..f6173023b22 100644--- a/packages/types/src/message/common/metadata.ts+++ b/packages/types/src/message/common/metadata.ts@@ -79,6 +79,7 @@ export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceSchecollapsed: z.boolean().optional(),inspectExpanded: z.boolean().optional(),isMultimodal: z.boolean().optional(),+ isSupervisor: z.boolean().optional(),});export interface ModelUsage extends ModelTokensUsage {@@ -130,4 +131,19 @@ export interface MessageMetadata extends ModelUsage, ModelPerformance {isMultimodal?: boolean;// message content is multimodal, display content in the streaming, won't save to dbtempDisplayContent?: string;+ /**+ * Flag indicating if message is from the Supervisor agent in group orchestration+ * Used by conversation-flow to transform role to 'supervisor' for UI rendering+ */+ isSupervisor?: boolean;+ /**+ * Flag indicating if message is pinned (excluded from compression)+ */+ pinned?: boolean;+ /**+ * Task instruction (for role='task' messages)+ * The instruction given by supervisor to the agent+ * Thread's sourceMessageId links back to this message for status tracking+ */+ instruction?: string;}diff --git a/packages/types/src/message/db/params.ts b/packages/types/src/message/db/params.tsindex 176c6a338cc..1bf5117b04b 100644--- a/packages/types/src/message/db/params.ts+++ b/packages/types/src/message/db/params.ts@@ -19,10 +19,12 @@ import {import { UIChatMessage } from '../ui';export interface QueryMessageParams {+ agentId?: string | null;current?: number;groupId?: string | null;pageSize?: number;sessionId?: string | null;+ threadId?: string | null;topicId?: string | null;}@@ -73,7 +75,7 @@ export interface NewMessage {provider?: string | null;quotaId?: string | null;// optional because it has a default function- role: 'user' | 'system' | 'assistant' | 'tool';+ role: 'user' | 'system' | 'assistant' | 'tool' | 'task';// required because it's notNullsessionId?: string | null;threadId?: string | null;diff --git a/packages/types/src/message/ui/chat.ts b/packages/types/src/message/ui/chat.tsindex 9a8d349183f..629a57639b1 100644--- a/packages/types/src/message/ui/chat.ts+++ b/packages/types/src/message/ui/chat.ts@@ -1,5 +1,6 @@import { MetaData } from '../../meta';import { GroundingSearch } from '../../search';+import { ThreadStatus } from '../../topic/thread';import {ChatImageItem,ChatMessageError,@@ -23,8 +24,12 @@ export type UIMessageRoleType =| 'system'| 'assistant'| 'tool'+ | 'task'| 'supervisor'- | 'assistantGroup';+ | 'assistantGroup'+ | 'agentCouncil'+ | 'compressedGroup'+ | 'compareGroup';export interface ChatFileItem {content?: string;@@ -38,6 +43,7 @@ export interface ChatFileItem {export interface AssistantContentBlock {content: string;error?: ChatMessageError | null;+ fileList?: ChatFileItem[];id: string;imageList?: ChatImageItem[];metadata?: Record<string, any>;@@ -53,6 +59,37 @@ interface UIMessageBranch {count: number;}+/**+ * Task execution details for role='task' messages+ * Retrieved from the associated Thread via sourceMessageId+ */+export interface TaskDetail {+ /** Task completion time (ISO string) */+ completedAt?: string;+ /** Execution duration in milliseconds */+ duration?: number;+ /** Error message if task failed */+ error?: string;+ /** Task start time (ISO string) */+ startedAt?: string;+ /** Task status */+ status: ThreadStatus;+ /** Thread ID for navigation */+ threadId: string;+ /** Thread title/summary */+ title?: string;+ /** Total cost in dollars */+ totalCost?: number;+ /** Total messages created during execution */+ totalMessages?: number;+ /** Total execution steps */+ totalSteps?: number;+ /** Total tokens consumed */+ totalTokens?: number;+ /** Total tool calls made */+ totalToolCalls?: number;+}+export interface UIChatMessage {// Group chat fields (alphabetically before other fields)agentId?: string | 'supervisor';@@ -71,7 +108,6 @@ export interface UIChatMessage {error?: ChatMessageError | null;// æ‰©å±•å—æ®µextra?: ChatMessageExtra;-fileList?: ChatFileItem[];/*** this is a deprecated field, only use in client db@@ -83,6 +119,7 @@ export interface UIChatMessage {groupId?: string;id: string;imageList?: ChatImageItem[];+ members?: UIChatMessage[];meta: MetaData;metadata?: MessageMetadata | null;model?: string | null;@@ -99,6 +136,18 @@ export interface UIChatMessage {* Aggregated from all children in group messages*/performance?: ModelPerformance;+ /**+ * Pinned messages within a compression group (role: 'compressedGroup')+ * Messages marked as favorite=true are included here+ */+ pinnedMessages?: {+ content: string | null;+ createdAt: Date;+ id: string;+ model: string | null;+ provider: string | null;+ role: string;+ }[];plugin?: ChatPluginPayload;pluginError?: any;pluginIntervention?: ToolIntervention;@@ -122,6 +171,11 @@ export interface UIChatMessage {* target member ID for DM messages in group chat*/targetId?: string | null;+ /**+ * Task execution details for role='task' messages+ * Retrieved from the associated Thread via sourceMessageId+ */+ taskDetail?: TaskDetail;threadId?: string | null;tool_call_id?: string;tools?: ChatToolPayload[];diff --git a/packages/types/src/message/ui/params.ts b/packages/types/src/message/ui/params.tsindex 28141dc19d6..2634fc7507b 100644--- a/packages/types/src/message/ui/params.ts+++ b/packages/types/src/message/ui/params.ts@@ -1,6 +1,7 @@/* eslint-disable sort-keys-fix/sort-keys-fix , typescript-sort-keys/interface */import { z } from 'zod';+import { ConversationContext } from '../../conversation';import { UploadFileItem } from '../../files';import { MessageSemanticSearchChunk } from '../../rag';import { ChatMessageError, ChatMessageErrorSchema } from '../common/base';@@ -8,10 +9,12 @@ import { ChatPluginPayload, ToolInterventionSchema } from '../common/tools';import { UIChatMessage } from './chat';import { SemanticSearchChunkSchema } from './rag';-export type CreateMessageRoleType = 'user' | 'assistant' | 'tool' | 'supervisor';+export type CreateMessageRoleType = 'user' | 'assistant' | 'tool' | 'task' | 'supervisor';-export interface CreateMessageParams- extends Partial<Omit<UIChatMessage, 'content' | 'role' | 'topicId' | 'chunksList'>> {+export interface CreateMessageParams extends Partial<+ Omit<UIChatMessage, 'content' | 'role' | 'topicId' | 'chunksList'>+> {+ agentId?: string;content: string;error?: ChatMessageError | null;fileChunks?: MessageSemanticSearchChunk[];@@ -20,7 +23,10 @@ export interface CreateMessageParamsprovider?: string;groupId?: string;role: CreateMessageRoleType;- sessionId: string;+ /**+ * @deprecated Use agentId instead+ */+ sessionId?: string;targetId?: string | null;threadId?: string | null;topicId?: string;@@ -35,7 +41,7 @@ export interface CreateNewMessageParams {// ========== Required fields ==========role: CreateMessageRoleType;content: string;- sessionId: string;+ agentId: string;// ========== Tool related ==========tool_call_id?: string;@@ -65,9 +71,25 @@ export interface CreateNewMessageParams {fileChunks?: MessageSemanticSearchChunk[];}+export interface ChatContextContent {+ content: string;+ /**+ * Format of the content. Defaults to text.+ */+ format?: 'xml' | 'text' | 'markdown';+ id: string;+ /**+ * Optional short preview for displaying in UI.+ */+ preview?: string;+ title?: string;+ type: 'text';+}+export interface SendMessageParams {/*** create a thread+ * @deprecated Use ConversationContext.newThread instead*/createThread?: boolean;files?: UploadFileItem[];@@ -82,27 +104,33 @@ export interface SendMessageParams {*/metadata?: Record<string, any>;onlyAddUserMessage?: boolean;-}-export interface SendThreadMessageParams {/**- * create a thread+ * Display messages for the current conversation context.+ * If provided, sendMessage will use these messages instead of querying from store.+ * This decouples sendMessage from store selectors.*/- createNewThread?: boolean;- // files?: UploadFileItem[];- message: string;- onlyAddUserMessage?: boolean;+ messages?: UIChatMessage[];++ /**+ * Parent message ID for the new message.+ * If not provided, will be calculated from messages list.+ */+ parentId?: string;+ /**+ * Additional contextual snippets (e.g., text selections) attached to the request.+ */+ contexts?: ChatContextContent[];}export interface SendGroupMessageParams {files?: UploadFileItem[];- groupId: string;+ context: ConversationContext;message: string;/*** Additional metadata for the message (e.g., mentioned users)*/metadata?: Record<string, any>;- onlyAddUserMessage?: boolean;/*** for group chat*/@@ -111,7 +139,7 @@ export interface SendGroupMessageParams {// ========== Zod Schemas ========== //-const UIMessageRoleTypeSchema = z.enum(['user', 'assistant', 'tool', 'supervisor']);+const UIMessageRoleTypeSchema = z.enum(['user', 'assistant', 'tool', 'task', 'supervisor']);const ChatPluginPayloadSchema = z.object({apiName: z.string(),@@ -125,6 +153,11 @@ export const CreateNewMessageParamsSchema = z// Required fieldsrole: UIMessageRoleTypeSchema,content: z.string(),+ // agentId is required, but can be resolved from sessionId in the router+ agentId: z.string().optional(),+ /**+ * @deprecated Use agentId instead. Will be resolved to agentId in the router.+ */sessionId: z.string().nullable().optional(),// Tool relatedtool_call_id: z.string().optional(),diff --git a/packages/types/src/session/agentSession.ts b/packages/types/src/session/agentSession.tsindex 7b4d553022f..3e748980c8d 100644--- a/packages/types/src/session/agentSession.ts+++ b/packages/types/src/session/agentSession.ts@@ -1,5 +1,5 @@import { AgentItem, LobeAgentConfig } from '../agent';-import { NewChatGroupAgent } from '../chatGroup';+import { NewChatGroupAgent } from '../agentGroup';import { MetaData } from '../meta';export enum LobeSessionType {diff --git a/packages/types/src/stepContext.ts b/packages/types/src/stepContext.tsnew file mode 100644index 00000000000..9329479d951--- /dev/null+++ b/packages/types/src/stepContext.ts@@ -0,0 +1,54 @@+/**+ * Runtime Step Context Types+ *+ * Step Context is computed at the beginning of each Agent Runtime step+ * and injected into Context Engine and Tool Executors.+ *+ * Key principles:+ * 1. Computed by the caller (AgentRuntime), not by Context Engine or Executor+ * 2. Executors read from stepContext, return new state via result.state+ * 3. Replaces the deprecated pluginState passing pattern+ */++/**+ * Todo item structure+ * Duplicated here to avoid circular dependency with builtin-tool-gtd+ */+export interface StepContextTodoItem {+ completed: boolean;+ text: string;+}++/**+ * Todo list structure in step context+ */+export interface StepContextTodos {+ items: StepContextTodoItem[];+ updatedAt: string;+}++/**+ * Runtime Step Context+ *+ * Contains dynamically computed state that changes between steps.+ * Computed from messages at the beginning of each step.+ *+ * @example+ * ```typescript+ * const stepContext = computeStepContext(state);+ * // Pass to Context Engine+ * messagesEngine.process({ messages, stepContext });+ * // Pass to Executor+ * executor.invoke(params, { stepContext, messageId, ... });+ * ```+ */+export interface RuntimeStepContext {+ /**+ * Current todo list state+ * Computed from the latest GTD tool message in the conversation+ */+ todos?: StepContextTodos;++ // Future extensions:+ // plan: StepContextPlan | null;+}diff --git a/packages/types/src/topic/thread.ts b/packages/types/src/topic/thread.tsindex d5dd9618a41..13d07e4a90a 100644--- a/packages/types/src/topic/thread.ts+++ b/packages/types/src/topic/thread.ts@@ -1,28 +1,22 @@import { z } from 'zod';-export enum ThreadType {- Continuation = 'continuation',- Standalone = 'standalone',-}+export const ThreadType = {+ Continuation: 'continuation',+ Isolation: 'isolation',+ Standalone: 'standalone',+} as const;++export type IThreadType = (typeof ThreadType)[keyof typeof ThreadType];export enum ThreadStatus {Active = 'active',- Archived = 'archived',- Deprecated = 'deprecated',-}--export interface ThreadItem {- createdAt: Date;- id: string;- lastActiveAt: Date;- parentThreadId?: string;- sourceMessageId?: string | null;- status: ThreadStatus;- title: string;- topicId: string;- type: ThreadType;- updatedAt: Date;- userId: string;+ Cancel = 'cancel',+ Completed = 'completed',+ Failed = 'failed',+ InReview = 'inReview',+ Pending = 'pending',+ Processing = 'processing',+ Todo = 'todo',}/**@@ -49,18 +43,44 @@ export interface ThreadMetadata {totalToolCalls?: number;}+export interface ThreadItem {+ /** Agent ID for agent task execution */+ agentId?: string | null;+ createdAt: Date;+ /** Group ID for group chat context */+ groupId?: string | null;+ id: string;+ lastActiveAt: Date;+ /** Metadata for agent task execution */+ metadata?: ThreadMetadata;+ parentThreadId?: string;+ sourceMessageId?: string | null;+ status: ThreadStatus;+ title: string;+ topicId: string;+ type: IThreadType;+ updatedAt: Date;+ userId: string;+}+export interface CreateThreadParams {+ /** Agent ID for agent task execution */+ agentId?: string;+ /** Group ID for group chat context */+ groupId?: string;parentThreadId?: string;sourceMessageId?: string;title?: string;topicId: string;- type: ThreadType;+ type: IThreadType;}export const createThreadSchema = z.object({+ agentId: z.string().optional(),+ groupId: z.string().optional(),parentThreadId: z.string().optional(),sourceMessageId: z.string().optional(),title: z.string().optional(),topicId: z.string(),- type: z.nativeEnum(ThreadType),+ type: z.enum([ThreadType.Continuation, ThreadType.Standalone, ThreadType.Isolation]),});diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex ae08ab7f2e2..ca9f72bd879 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -26,12 +26,11 @@ export interface GroupedTopic {export interface TopicUserMemoryExtractRunState {error?: string;- lastConversationDigest?: string;lastMessageAt?: string;lastRunAt?: string;messageCount?: number;processedMemoryCount?: number;- version?: string;+ traceId?: string;}export interface ChatTopicMetadata {@@ -64,6 +63,33 @@ export interface TopicRankItem {title: string | null;}+export interface RecentTopicAgent {+ avatar: string | null;+ backgroundColor: string | null;+ id: string;+ title: string | null;+}++export interface RecentTopicGroupMember {+ avatar: string | null;+ backgroundColor: string | null;+}++export interface RecentTopicGroup {+ id: string;+ members: RecentTopicGroupMember[];+ title: string | null;+}++export interface RecentTopic {+ agent: RecentTopicAgent | null;+ group: RecentTopicGroup | null;+ id: string;+ title: string | null;+ type: 'agent' | 'group';+ updatedAt: Date;+}+export interface CreateTopicParams {favorite?: boolean;groupId?: string | null;@@ -73,7 +99,16 @@ export interface CreateTopicParams {}export interface QueryTopicParams {- containerId?: string | null; // sessionId or groupId+ agentId?: string | null;current?: number;+ /**+ * Group ID to filter topics by+ */+ groupId?: string | null;+ /**+ * Whether this is an inbox agent query.+ * When true, also includes legacy inbox topics (sessionId IS NULL AND groupId IS NULL AND agentId IS NULL)+ */+ isInbox?: boolean;pageSize?: number;}diff --git a/src/config/featureFlags/schema.test.ts b/src/config/featureFlags/schema.test.tsindex 2c0b613f28c..4ad8dd01e8c 100644--- a/src/config/featureFlags/schema.test.ts+++ b/src/config/featureFlags/schema.test.ts@@ -101,19 +101,15 @@ describe('mapFeatureFlagsEnvToState', () => {provider_settings: true,openai_api_key: true,openai_proxy_url: false,- create_session: true,edit_agent: false,- dalle: true,ai_image: true,check_updates: true,welcome_suggest: true,- plugins: true,knowledge_base: false,rag_eval: true,market: true,speech_to_text: true,changelog: false,- pin_list: true,api_key_manage: false,cloud_promotion: true,commercial_hide_github: false,@@ -124,13 +120,10 @@ describe('mapFeatureFlagsEnvToState', () => {expect(mappedState).toMatchObject({isAgentEditable: false,- showCreateSession: true,showProvider: true,showOpenAIApiKey: true,showOpenAIProxyUrl: false,showApiKeyManage: false,- enablePlugins: true,- showDalle: true,showAiImage: true,showChangelog: false,enableCheckUpdates: true,@@ -139,7 +132,6 @@ describe('mapFeatureFlagsEnvToState', () => {enableRAGEval: true,showMarket: true,enableSTT: true,- showPinList: true,showCloudPromotion: true,hideGitHub: false,hideDocs: true,@@ -158,8 +150,7 @@ describe('mapFeatureFlagsEnvToState', () => {const mappedState = mapFeatureFlagsEnvToState(config, userId);expect(mappedState.isAgentEditable).toBe(true); // user-123 is in allowlist- expect(mappedState.showCreateSession).toBe(false); // user-123 is not in allowlist- expect(mappedState.showDalle).toBe(true); // boolean true+expect(mappedState.enableKnowledgeBase).toBe(true); // user-123 is in allowlist});@@ -174,8 +165,6 @@ describe('mapFeatureFlagsEnvToState', () => {const mappedState = mapFeatureFlagsEnvToState(config, userId);expect(mappedState.isAgentEditable).toBe(false);- expect(mappedState.showCreateSession).toBe(false);- expect(mappedState.showDalle).toBe(true);});it('should return false for array flags when no user ID provided', () => {@@ -187,7 +176,6 @@ describe('mapFeatureFlagsEnvToState', () => {const mappedState = mapFeatureFlagsEnvToState(config);expect(mappedState.isAgentEditable).toBe(false);- expect(mappedState.showCreateSession).toBe(true);});it('should handle mixed boolean and array values correctly', () => {@@ -204,8 +192,7 @@ describe('mapFeatureFlagsEnvToState', () => {const mappedState = mapFeatureFlagsEnvToState(config, userId);expect(mappedState.isAgentEditable).toBe(true);- expect(mappedState.showCreateSession).toBe(true);- expect(mappedState.showDalle).toBe(false);+expect(mappedState.showAiImage).toBe(false);expect(mappedState.enableKnowledgeBase).toBe(true);expect(mappedState.enableRAGEval).toBe(true);diff --git a/src/config/featureFlags/schema.ts b/src/config/featureFlags/schema.tsindex b75977ee40a..9d6dc071162 100644--- a/src/config/featureFlags/schema.ts+++ b/src/config/featureFlags/schema.ts@@ -6,7 +6,6 @@ const FeatureFlagValue = z.union([z.boolean(), z.array(z.string())]);export const FeatureFlagsSchema = z.object({check_updates: FeatureFlagValue.optional(),- pin_list: FeatureFlagValue.optional(),// settingsprovider_settings: FeatureFlagValue.optional(),@@ -16,12 +15,8 @@ export const FeatureFlagsSchema = z.object({// profileapi_key_manage: FeatureFlagValue.optional(),-- create_session: FeatureFlagValue.optional(),edit_agent: FeatureFlagValue.optional(),- plugins: FeatureFlagValue.optional(),- dalle: FeatureFlagValue.optional(),ai_image: FeatureFlagValue.optional(),speech_to_text: FeatureFlagValue.optional(),token_counter: FeatureFlagValue.optional(),@@ -37,8 +32,6 @@ export const FeatureFlagsSchema = z.object({// internal flagcloud_promotion: FeatureFlagValue.optional(),- group_chat: FeatureFlagValue.optional(),-// the flags below can only be used with commercial license// if you want to use it in the commercial usage// please contact us for more information: [email protected]@@ -66,20 +59,14 @@ export const evaluateFeatureFlag = (};export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {- pin_list: false,-provider_settings: true,openai_api_key: true,openai_proxy_url: true,api_key_manage: false,-- create_session: true,edit_agent: true,- plugins: true,- dalle: true,ai_image: true,check_updates: true,@@ -95,8 +82,6 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {speech_to_text: true,changelog: true,- group_chat: false,-// the flags below can only be used with commercial license// if you want to use it in the commercial usage// please contact us for more information: [email protected]@@ -107,19 +92,13 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {export const mapFeatureFlagsEnvToState = (config: IFeatureFlags, userId?: string) => {return {isAgentEditable: evaluateFeatureFlag(config.edit_agent, userId),-- showCreateSession: evaluateFeatureFlag(config.create_session, userId),- enableGroupChat: evaluateFeatureFlag(config.group_chat, userId),showProvider: evaluateFeatureFlag(config.provider_settings, userId),- showPinList: evaluateFeatureFlag(config.pin_list, userId),showOpenAIApiKey: evaluateFeatureFlag(config.openai_api_key, userId),showOpenAIProxyUrl: evaluateFeatureFlag(config.openai_proxy_url, userId),showApiKeyManage: evaluateFeatureFlag(config.api_key_manage, userId),- enablePlugins: evaluateFeatureFlag(config.plugins, userId),- showDalle: evaluateFeatureFlag(config.dalle, userId),showAiImage: evaluateFeatureFlag(config.ai_image, userId),showChangelog: evaluateFeatureFlag(config.changelog, userId),diff --git a/src/envs/app.ts b/src/envs/app.tsindex 1d6bfb08cf8..c77b80b1819 100644--- a/src/envs/app.ts+++ b/src/envs/app.ts@@ -60,6 +60,14 @@ export const getAppConfig = () => {SSRF_ALLOW_PRIVATE_IP_ADDRESS: z.boolean().optional(),SSRF_ALLOW_IP_ADDRESS_LIST: z.string().optional(),MARKET_BASE_URL: z.string().optional(),++ /**+ * Enable Queue-based Agent Runtime+ * When true, use QStash for async agent execution (production)+ * When false, execute agent steps synchronously in current process (development)+ * @default false+ */+ enableQueueAgentRuntime: z.boolean().optional(),},runtimeEnv: {// Sentry@@ -94,6 +102,8 @@ export const getAppConfig = () => {SSRF_ALLOW_PRIVATE_IP_ADDRESS: process.env.SSRF_ALLOW_PRIVATE_IP_ADDRESS === '1',SSRF_ALLOW_IP_ADDRESS_LIST: process.env.SSRF_ALLOW_IP_ADDRESS_LIST,MARKET_BASE_URL: process.env.MARKET_BASE_URL,++ enableQueueAgentRuntime: process.env.AGENT_RUNTIME_MODE === 'queue',},});};diff --git a/src/server/ld.ts b/src/server/ld.tsindex 85607245fbe..ee4e92be6d3 100644--- a/src/server/ld.ts+++ b/src/server/ld.ts@@ -1,4 +1,4 @@-import { isString } from 'lodash-es';+import { isString } from 'es-toolkit/compat';import qs from 'query-string';import urlJoin from 'url-join';diff --git a/src/server/manifest.ts b/src/server/manifest.tsindex 27335430e88..5f855abcc5b 100644--- a/src/server/manifest.ts+++ b/src/server/manifest.ts@@ -63,10 +63,10 @@ export class Manifest {screenshots: screenshots.map((item) => this._getScreenshot(item)),short_name: name,splash_pages: null,- start_url: '/chat',+ start_url: '/agent',tab_strip: {new_tab_button: {- url: '/chat',+ url: '/agent',},},theme_color: color,diff --git a/src/server/sitemap.test.ts b/src/server/sitemap.test.tsindex 696d94585b2..faa2e00a0f9 100644--- a/src/server/sitemap.test.ts+++ b/src/server/sitemap.test.ts@@ -59,14 +59,14 @@ describe('Sitemap', () => {// Note: The actual implementation generates URLs like /discover/assistant and /discover/plugin (not category-specific)expect(pageSitemap).toContainEqual(expect.objectContaining({- url: getCanonicalUrl('/discover/assistant'),+ url: getCanonicalUrl('/community/assistant'),changeFrequency: 'daily',priority: 0.7,}),);expect(pageSitemap).toContainEqual(expect.objectContaining({- url: getCanonicalUrl('/discover/plugin'),+ url: getCanonicalUrl('/community/plugin'),changeFrequency: 'daily',priority: 0.7,}),@@ -85,13 +85,13 @@ describe('Sitemap', () => {expect(assistantsSitemap.length).toBe(LOCALE_COUNT);expect(assistantsSitemap).toContainEqual(expect.objectContaining({- url: getCanonicalUrl('/discover/assistant/test-assistant'),+ url: getCanonicalUrl('/community/assistant/test-assistant'),lastModified: '2023-01-01T00:00:00.000Z',}),);expect(assistantsSitemap).toContainEqual(expect.objectContaining({- url: getCanonicalUrl('/discover/assistant/test-assistant?hl=zh-CN'),+ url: getCanonicalUrl('/community/assistant/test-assistant?hl=zh-CN'),lastModified: '2023-01-01T00:00:00.000Z',}),);@@ -113,7 +113,7 @@ describe('Sitemap', () => {expect(firstPageSitemap.length).toBe(100 * LOCALE_COUNT); // 100 items * LOCALE_COUNT localesexpect(firstPageSitemap).toContainEqual(expect.objectContaining({- url: getCanonicalUrl('/discover/assistant/test-assistant-0'),+ url: getCanonicalUrl('/community/assistant/test-assistant-0'),lastModified: '2023-01-01T00:00:00.000Z',}),);@@ -123,7 +123,7 @@ describe('Sitemap', () => {expect(secondPageSitemap.length).toBe(50 * LOCALE_COUNT); // 50 items * LOCALE_COUNT localesexpect(secondPageSitemap).toContainEqual(expect.objectContaining({- url: getCanonicalUrl('/discover/assistant/test-assistant-100'),+ url: getCanonicalUrl('/community/assistant/test-assistant-100'),lastModified: '2023-01-01T00:00:00.000Z',}),);@@ -141,13 +141,13 @@ describe('Sitemap', () => {expect(pluginsSitemap.length).toBe(LOCALE_COUNT);expect(pluginsSitemap).toContainEqual(expect.objectContaining({- url: getCanonicalUrl('/discover/plugin/test-plugin'),+ url: getCanonicalUrl('/community/plugin/test-plugin'),lastModified: '2023-01-01T00:00:00.000Z',}),);expect(pluginsSitemap).toContainEqual(expect.objectContaining({- url: getCanonicalUrl('/discover/plugin/test-plugin?hl=ja-JP'),+ url: getCanonicalUrl('/community/plugin/test-plugin?hl=ja-JP'),lastModified: '2023-01-01T00:00:00.000Z',}),);@@ -185,13 +185,13 @@ describe('Sitemap', () => {expect(modelsSitemap.length).toBe(LOCALE_COUNT);expect(modelsSitemap).toContainEqual(expect.objectContaining({- url: getCanonicalUrl('/discover/model/test:model'),+ url: getCanonicalUrl('/community/model/test:model'),lastModified: '2023-01-01T00:00:00.000Z',}),);expect(modelsSitemap).toContainEqual(expect.objectContaining({- url: getCanonicalUrl('/discover/model/test:model?hl=ko-KR'),+ url: getCanonicalUrl('/community/model/test:model?hl=ko-KR'),lastModified: '2023-01-01T00:00:00.000Z',}),);@@ -229,13 +229,13 @@ describe('Sitemap', () => {expect(providersSitemap.length).toBe(LOCALE_COUNT);expect(providersSitemap).toContainEqual(expect.objectContaining({- url: getCanonicalUrl('/discover/provider/test-provider'),+ url: getCanonicalUrl('/community/provider/test-provider'),lastModified: '2023-01-01T00:00:00.000Z',}),);expect(providersSitemap).toContainEqual(expect.objectContaining({- url: getCanonicalUrl('/discover/provider/test-provider?hl=ar'),+ url: getCanonicalUrl('/community/provider/test-provider?hl=ar'),lastModified: '2023-01-01T00:00:00.000Z',}),);diff --git a/src/server/sitemap.ts b/src/server/sitemap.tsindex 27088d17ad3..31c33b2d6d6 100644--- a/src/server/sitemap.ts+++ b/src/server/sitemap.ts@@ -1,4 +1,4 @@-import { flatten } from 'lodash-es';+import { flatten } from 'es-toolkit/compat';import { MetadataRoute } from 'next';import qs from 'query-string';import urlJoin from 'url-join';@@ -213,7 +213,7 @@ export class Sitemap {const sitmap = pageAssistants.filter((item) => item.identifier) // 过滤掉 identifier 为空的项目.map((item) =>- this._genSitemap(urlJoin('/discover/assistant', item.identifier), {+ this._genSitemap(urlJoin('/community/assistant', item.identifier), {lastModified: item?.lastModified || LAST_MODIFIED,}),);@@ -224,7 +224,7 @@ export class Sitemap {const sitmap = list.filter((item) => item.identifier) // 过滤掉 identifier 为空的项目.map((item) =>- this._genSitemap(urlJoin('/discover/assistant', item.identifier), {+ this._genSitemap(urlJoin('/community/assistant', item.identifier), {lastModified: item?.lastModified || LAST_MODIFIED,}),);@@ -242,7 +242,7 @@ export class Sitemap {const sitmap = pagePlugins.filter((item) => item.identifier) // 过滤掉 identifier 为空的项目.map((item) =>- this._genSitemap(urlJoin('/discover/plugin', item.identifier), {+ this._genSitemap(urlJoin('/community/plugin', item.identifier), {lastModified: item?.lastModified || LAST_MODIFIED,}),);@@ -253,7 +253,7 @@ export class Sitemap {const sitmap = list.filter((item) => item.identifier) // 过滤掉 identifier 为空的项目.map((item) =>- this._genSitemap(urlJoin('/discover/plugin', item.identifier), {+ this._genSitemap(urlJoin('/community/plugin', item.identifier), {lastModified: item?.lastModified || LAST_MODIFIED,}),);@@ -271,7 +271,7 @@ export class Sitemap {const sitmap = pageModels.filter((item) => item.identifier) // 过滤掉 identifier 为空的项目.map((item) =>- this._genSitemap(urlJoin('/discover/model', item.identifier), {+ this._genSitemap(urlJoin('/community/model', item.identifier), {lastModified: item?.lastModified || LAST_MODIFIED,}),);@@ -282,7 +282,7 @@ export class Sitemap {const sitmap = list.filter((item) => item.identifier) // 过滤掉 identifier 为空的项目.map((item) =>- this._genSitemap(urlJoin('/discover/model', item.identifier), {+ this._genSitemap(urlJoin('/community/model', item.identifier), {lastModified: item?.lastModified || LAST_MODIFIED,}),);@@ -294,7 +294,7 @@ export class Sitemap {const sitmap = list.filter((item) => item.identifier) // 过滤掉 identifier 为空的项目.map((item) =>- this._genSitemap(urlJoin('/discover/provider', item.identifier), {+ this._genSitemap(urlJoin('/community/provider', item.identifier), {lastModified: item?.lastModified || LAST_MODIFIED,}),);@@ -305,17 +305,17 @@ export class Sitemap {const hideDocs = serverFeatureFlags().hideDocs;return [...this._genSitemap('/', { noLocales: true }),- ...this._genSitemap('/chat', { noLocales: true }),+ ...this._genSitemap('/agent', { noLocales: true }),...(!hideDocs ? this._genSitemap('/changelog', { noLocales: true }) : []),/* ↓ cloud slot ↓ *//* ↑ cloud slot ↑ */- ...this._genSitemap('/discover', { changeFrequency: 'daily', priority: 0.7 }),- ...this._genSitemap('/discover/assistant', { changeFrequency: 'daily', priority: 0.7 }),- ...this._genSitemap('/discover/mcp', { changeFrequency: 'daily', priority: 0.7 }),- ...this._genSitemap('/discover/plugin', { changeFrequency: 'daily', priority: 0.7 }),- ...this._genSitemap('/discover/model', { changeFrequency: 'daily', priority: 0.7 }),- ...this._genSitemap('/discover/provider', { changeFrequency: 'daily', priority: 0.7 }),+ ...this._genSitemap('/community', { changeFrequency: 'daily', priority: 0.7 }),+ ...this._genSitemap('/community/assistant', { changeFrequency: 'daily', priority: 0.7 }),+ ...this._genSitemap('/community/mcp', { changeFrequency: 'daily', priority: 0.7 }),+ ...this._genSitemap('/community/plugin', { changeFrequency: 'daily', priority: 0.7 }),+ ...this._genSitemap('/community/model', { changeFrequency: 'daily', priority: 0.7 }),+ ...this._genSitemap('/community/provider', { changeFrequency: 'daily', priority: 0.7 }),].filter(Boolean);}getRobots() {diff --git a/src/server/translation.ts b/src/server/translation.tsindex 70a673aed13..8e6cce4ce2c 100644--- a/src/server/translation.ts+++ b/src/server/translation.ts@@ -1,6 +1,4 @@-'use server';--import { get } from 'lodash-es';+import { get } from 'es-toolkit/compat';import { DEFAULT_LANG } from '@/const/locale';import { Locales, NS, normalizeLocale } from '@/locales/resources';