🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(channel): open a project's main agent in its project channel instead of a new direct chat (#23366)
Lobehub Coder0410a4a148e9
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.tsindex a24388f0029..a565c88c839 100644--- a/apps/server/src/routers/lambda/channel.ts+++ b/apps/server/src/routers/lambda/channel.ts@@ -260,14 +260,15 @@ export const channelRouter = router({})),/*** The caller's direct conversation with an Agent, opened on first use for Agents that predate- * direct Channels. Null when the Agent cannot answer in a Channel (no reachable device).+ * direct Channels; a project's main Agent opens in its project's Channel instead. Null when the+ * Agent cannot answer in a Channel (no reachable device).*/openDirect: channelProcedure.input(z.object({ agentId: z.string().min(1) }))- .mutation(async ({ ctx, input }) => {- const access = await ctx.channelService.openDirect(input.agentId);- return { data: access?.channel.id ?? null, success: true };- }),+ .mutation(async ({ ctx, input }) => ({+ data: (await ctx.channelService.openAgent(input.agentId)) ?? null,+ success: true,+ })),/** The direct conversation with another person's Agent, from its share id, handle or link. */openShared: channelProcedure.input(z.object({ share: z.string().trim().min(1).max(512) }))diff --git a/apps/server/src/services/channel/ChannelService.direct.test.ts b/apps/server/src/services/channel/ChannelService.direct.test.tsindex 5a960494ed3..fe25dbb26b5 100644--- a/apps/server/src/services/channel/ChannelService.direct.test.ts+++ b/apps/server/src/services/channel/ChannelService.direct.test.ts@@ -13,6 +13,7 @@ const {findAccess,findDevice,findDirectAccess,+ findProjectMainChannelId,findShare,findSharedAgent,getAgent,@@ -26,6 +27,7 @@ const {findAccess: vi.fn(),findDevice: vi.fn(),findDirectAccess: vi.fn(),+ findProjectMainChannelId: vi.fn(),findShare: vi.fn(),findSharedAgent: vi.fn(),getAgent: vi.fn(),@@ -42,6 +44,9 @@ vi.mock('@/database/repositories/channel', async (original) => ({findDirectAccess = findDirectAccess;},}));+vi.mock('@/database/repositories/channel/projectMainChannel', () => ({+ findProjectMainChannelId,+}));vi.mock('@/database/models/project', () => ({ ProjectModel: class {} }));vi.mock('@/database/models/contact', async (original) => ({...(await original<object>()),@@ -201,6 +206,44 @@ describe('opening the direct Channel of an existing Agent', () => {});});+describe('opening an Agent from the contacts or Agent list', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ create.mockResolvedValue({ channel: { id: 'chn_new' } });+ getAgent.mockResolvedValue({ model: 'gpt-5', name: 'Apollo' });+ });+ const openAgent = () => new ChannelService({} as never, 'owner', 'ws').openAgent('agt_main');++ // Creating a project used to leave two conversations with its main Agent in the list: the+ // project's General Channel and a direct conversation opened on the first click.+ it("opens a project's main Agent in the project's Channel without a direct conversation", async () => {+ findDirectAccess.mockResolvedValue(undefined);+ findProjectMainChannelId.mockResolvedValue('chn_general');++ await expect(openAgent()).resolves.toBe('chn_general');++ expect(findProjectMainChannelId).toHaveBeenCalledWith({}, 'owner', 'ws', 'agt_main');+ expect(create).not.toHaveBeenCalled();+ });++ it('keeps a direct conversation the person already has with that Agent', async () => {+ findDirectAccess.mockResolvedValue({ channel: { id: 'chn_dm', isDeleted: null } });++ await expect(openAgent()).resolves.toBe('chn_dm');++ expect(findProjectMainChannelId).not.toHaveBeenCalled();+ });++ it('opens a direct conversation for an Agent that leads no project', async () => {+ findDirectAccess.mockResolvedValue(undefined);+ findProjectMainChannelId.mockResolvedValue(undefined);++ await expect(openAgent()).resolves.toBe('chn_new');++ expect(create).toHaveBeenCalledWith({ agentConfig: {}, agentId: 'agt_main', title: 'Apollo' });+ });+});+describe('inviting from a direct conversation', () => {beforeEach(() => {vi.resetAllMocks();diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.tsindex 4b6d3a757e1..a6ae642bd18 100644--- a/apps/server/src/services/channel/ChannelService.ts+++ b/apps/server/src/services/channel/ChannelService.ts@@ -22,6 +22,7 @@ import type {ChannelStopScope,} from '@/database/repositories/channel';import { ChannelError, ChannelRepository } from '@/database/repositories/channel';+import { findProjectMainChannelId } from '@/database/repositories/channel/projectMainChannel';import { users } from '@/database/schemas';import { AgentService } from '@/server/services/agent';import { deviceGateway } from '@/server/services/deviceGateway';@@ -305,6 +306,24 @@ export class ChannelService {return this.createDirect(agentId);};+ /**+ * Where a person lands opening an Agent from their contacts or Agent list. A project's main Agent+ * talks in that project's Channel, so it opens there instead of a direct conversation beside it;+ * a direct conversation the person already has with it still opens as it is.+ */+ openAgent = async (agentId: string): Promise<string | undefined> => {+ const existing = await this.repository.findDirectAccess(agentId);+ if (existing) return existing.channel.isDeleted ? undefined : existing.channel.id;+ const projectChannelId = await findProjectMainChannelId(+ this.db,+ this.userId,+ this.workspaceId ?? null,+ agentId,+ );+ if (projectChannelId) return projectChannelId;+ return (await this.createDirect(agentId))?.channel.id;+ };+/*** The one-on-one conversation with a contact (personal space) or a fellow member (workspace).* The stored title is the other person's name fordiff --git a/packages/database/src/repositories/channel/__tests__/projectMainChannel.test.ts b/packages/database/src/repositories/channel/__tests__/projectMainChannel.test.tsnew file mode 100644index 00000000000..f65ed33c5fa--- /dev/null+++ b/packages/database/src/repositories/channel/__tests__/projectMainChannel.test.ts@@ -0,0 +1,102 @@+// @vitest-environment node+import { and, eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { agents, channelMembers, projects, workspaceMembers } from '../../../schemas';+import { ChannelRepository } from '..';+import { findProjectMainChannelId } from '../projectMainChannel';+import { createChannelFixture } from './testUtils';++const db = await getTestDB();+const fixture = createChannelFixture(db, 'channel-project-main');+beforeEach(async () => {+ await fixture.setup();+ await db.insert(workspaceMembers).values([+ { workspaceId: fixture.workspaceId, userId: fixture.ownerId, role: 'owner' },+ { workspaceId: fixture.workspaceId, userId: fixture.memberId },+ ]);+});+afterEach(async () => {+ await db.delete(projects).where(eq(projects.workspaceId, fixture.workspaceId));+ await db.delete(agents).where(eq(agents.workspaceId, fixture.workspaceId));+ await fixture.cleanup();+});++/** A project led by its own main Agent, with the General Channel it starts with. */+const projectWithGeneral = async (visibility: 'private' | 'public' = 'public') => {+ const [agent] = await db+ .insert(agents)+ .values({ title: 'Apollo', userId: fixture.ownerId, workspaceId: fixture.workspaceId })+ .returning();+ const [project] = await db+ .insert(projects)+ .values({+ coordinatorAgentId: agent.id,+ name: 'Apollo',+ userId: fixture.ownerId,+ visibility,+ workspaceId: fixture.workspaceId,+ })+ .returning();+ const owner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);+ const { channel } = await owner.create({+ agents: [{ agentId: agent.id, name: 'Apollo' }],+ projectId: project.id,+ title: 'General',+ });+ return { agent, channel, owner, project };+};++const find = (userId: string, agentId: string) =>+ findProjectMainChannelId(db, userId, fixture.workspaceId, agentId);++describe("a project's main Agent", () => {+ it("is reached in the project's General Channel", async () => {+ const { agent, channel } = await projectWithGeneral();++ expect(await find(fixture.ownerId, agent.id)).toBe(channel.id);+ });++ it('is reached there by a teammate who may open the project without having joined', async () => {+ const { agent, channel } = await projectWithGeneral();++ expect(await find(fixture.memberId, agent.id)).toBe(channel.id);+ });++ it("is not reached through a private project's Channel the teammate cannot read", async () => {+ const { agent } = await projectWithGeneral('private');++ expect(await find(fixture.memberId, agent.id)).toBeUndefined();+ });++ it('prefers the oldest Channel over later project Channels', async () => {+ const { agent, channel, owner, project } = await projectWithGeneral();+ await owner.create({+ agents: [{ agentId: agent.id, name: 'Apollo' }],+ projectId: project.id,+ title: 'Later',+ });++ expect(await find(fixture.ownerId, agent.id)).toBe(channel.id);+ });++ it('skips a Channel the Agent no longer sits in', async () => {+ const { agent, channel } = await projectWithGeneral();+ await db+ .update(channelMembers)+ .set({ status: 'removed' })+ .where(and(eq(channelMembers.channelId, channel.id), eq(channelMembers.actorType, 'agent')));++ expect(await find(fixture.ownerId, agent.id)).toBeUndefined();+ });++ it('is nothing for an Agent that leads no project', async () => {+ const [agent] = await db+ .insert(agents)+ .values({ title: 'Solo', userId: fixture.ownerId, workspaceId: fixture.workspaceId })+ .returning();++ expect(await find(fixture.ownerId, agent.id)).toBeUndefined();+ });+});diff --git a/packages/database/src/repositories/channel/projectMainChannel.ts b/packages/database/src/repositories/channel/projectMainChannel.tsnew file mode 100644index 00000000000..a1f53d0ea1f--- /dev/null+++ b/packages/database/src/repositories/channel/projectMainChannel.ts@@ -0,0 +1,68 @@+import { and, asc, eq, exists, isNull, or } from 'drizzle-orm';++import { channelMembers, channels, projects } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { notTrashed } from '../../utils/softDelete';+import { buildWorkspaceWhere } from '../../utils/workspace';+import { openChannelWhere } from './projectAccess';++/**+ * The group Channel a person reaches a project's main Agent in: the oldest active Channel of a+ * project that Agent leads, with the Agent still seated in it, that the person belongs to or may+ * open. That is the project's General Channel unless it was archived or the Agent left it.+ * Undefined when the Agent leads no readable project, or none of its Channels qualify.+ */+export const findProjectMainChannelId = async (+ db: LobeChatDatabase,+ userId: string,+ workspaceId: string | null,+ agentId: string,+): Promise<string | undefined> => {+ const [row] = await db+ .select({ id: channels.id })+ .from(channels)+ .innerJoin(projects, eq(projects.id, channels.projectId))+ .where(+ and(+ eq(projects.coordinatorAgentId, agentId),+ buildWorkspaceWhere({ userId, workspaceId: workspaceId ?? undefined }, projects),+ isNull(channels.agentId),+ isNull(channels.peerUserId),+ notTrashed(channels.isDeleted),+ eq(channels.status, 'active'),+ workspaceId ? eq(channels.workspaceId, workspaceId) : isNull(channels.workspaceId),+ exists(+ db+ .select({ id: channelMembers.id })+ .from(channelMembers)+ .where(+ and(+ eq(channelMembers.channelId, channels.id),+ eq(channelMembers.actorType, 'agent'),+ eq(channelMembers.agentId, agentId),+ eq(channelMembers.status, 'active'),+ ),+ ),+ ),+ or(+ exists(+ db+ .select({ id: channelMembers.id })+ .from(channelMembers)+ .where(+ and(+ eq(channelMembers.channelId, channels.id),+ eq(channelMembers.actorType, 'user'),+ eq(channelMembers.userId, userId),+ eq(channelMembers.status, 'active'),+ ),+ ),+ ),+ openChannelWhere(db, userId, workspaceId),+ ),+ ),+ )+ .orderBy(asc(channels.createdAt), asc(channels.id))+ .limit(1);+ return row?.id;+};