🤯 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(channel): let people start personal groups with their contacts (#23492)
Arvin Xud60e43246ebd
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.tsindex bd524ce87f3..5fd3cd85caf 100644--- a/apps/server/src/routers/lambda/channel.ts+++ b/apps/server/src/routers/lambda/channel.ts@@ -69,7 +69,7 @@ const channelProcedure = channelBaseProcedure.use(denyExternalContact);export const channelRouter = router({...channelHistoryProcedures,- /** Without a Channel, the people a new Channel in this workspace can start with. */+ /** Without a Channel, the people a new Channel in this scope can start with. */userCandidates: channelProcedure.input(z.object({ channelId: channelId.optional(), search: z.string().max(100).optional() })).query(async ({ ctx, input }) => ({diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.tsindex d960b52d139..e16f2c4410f 100644--- a/apps/server/src/services/channel/ChannelService.ts+++ b/apps/server/src/services/channel/ChannelService.ts@@ -171,7 +171,7 @@ export class ChannelService {}}- /** A group starts with Agents, workspace people, both, or only its creator. */+ /** A group starts with Agents, people, both, or only its creator. */create = async (input: {agents: ChannelAgentSelection[];/** Seats Agents from outside the project in the project first. */diff --git a/packages/database/src/repositories/channel/README.md b/packages/database/src/repositories/channel/README.mdindex 48bebd2c769..85cfb91b6d5 100644--- a/packages/database/src/repositories/channel/README.md+++ b/packages/database/src/repositories/channel/README.md@@ -39,8 +39,9 @@ name, with the Agent on the device and directory a new Channel would give it(`createAgentDirectChannel`).Inviting from a direct conversation leaves it as it is and starts a group instead(`createGroupFromDirect`): its person and Agent, the Agent in the same channel-local environment,-plus the invited Agents and, in a workspace, people. `userCandidates` lists those people from a-workspace direct conversation; `addUser` still refuses it.+plus the invited Agents and people. `userCandidates` lists those people from a direct+conversation; `addUser` still refuses it. People a group takes are those its inviter can talk with+one-on-one: in a workspace, its members; in the personal space, the inviter's mutual contacts.Group history survives deletion of an author or Agent. Message sender references use `SET NULL`;new writes require exactly one actual sender. Human requests have `userId`, Agent replies havediff --git a/packages/database/src/repositories/channel/__tests__/groupFromDirect.test.ts b/packages/database/src/repositories/channel/__tests__/groupFromDirect.test.tsindex 75b13acc228..b65cad00d53 100644--- a/packages/database/src/repositories/channel/__tests__/groupFromDirect.test.ts+++ b/packages/database/src/repositories/channel/__tests__/groupFromDirect.test.ts@@ -3,7 +3,7 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../../core/getTestDB';-import { agents, channelMembers, channels, workspaceMembers } from '../../../schemas';+import { agents, channelMembers, channels, userContacts, workspaceMembers } from '../../../schemas';import { ChannelRepository } from '..';import { createChannelFixture } from './testUtils';@@ -16,7 +16,10 @@ beforeEach(async () => {{ workspaceId: fixture.workspaceId, userId: fixture.memberId },]);});-afterEach(fixture.cleanup);+afterEach(async () => {+ await db.delete(userContacts);+ await fixture.cleanup();+});const environment = () => ({deviceId: 'device-1',@@ -97,19 +100,35 @@ describe('inviting from a direct conversation', () => {});it.each([- ['people into a personal group', null, { userIds: [fixture.memberId] }],- ['an empty invitation', 'workspace', {}],- ])('refuses %s without creating anything', async (_, scope, invitees) => {+ ['someone who is not a personal contact', null, { userIds: [fixture.memberId] }, 'FORBIDDEN'],+ ['an empty invitation', 'workspace', {}, 'BAD_REQUEST'],+ ])('refuses %s without creating anything', async (_, scope, invitees, code) => {const workspaceId = scope ? fixture.workspaceId : null;const { direct, owner } = await createDirect(workspaceId);await expect(owner.createGroupFromDirect(direct.id, { title: 'Group', ...invitees }),- ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ ).rejects.toMatchObject({ code });expect(await db.select().from(channels).where(eq(channels.userId, fixture.ownerId))).toEqual([expect.objectContaining({ id: direct.id }),]);});+ it('invites a personal contact into the personal group it starts', async () => {+ await db.insert(userContacts).values([+ { contactUserId: fixture.memberId, type: 'user', userId: fixture.ownerId },+ { contactUserId: fixture.ownerId, type: 'user', userId: fixture.memberId },+ ]);+ const { direct, owner } = await createDirect(null);+ const { channel } = await owner.createGroupFromDirect(direct.id, {+ title: 'Group',+ userIds: [fixture.memberId],+ });+ expect(channel.workspaceId).toBeNull();+ expect((await membersOf(channel.id)).map(({ userId }) => userId)).toEqual(+ expect.arrayContaining([fixture.ownerId, fixture.memberId]),+ );+ });+it('only starts groups from a direct conversation', async () => {const { asOwner, channel } = await fixture.createTeamChannel();await expect(diff --git a/packages/database/src/repositories/channel/__tests__/userMembers.test.ts b/packages/database/src/repositories/channel/__tests__/userMembers.test.tsindex 423c06bf2ff..92fab510181 100644--- a/packages/database/src/repositories/channel/__tests__/userMembers.test.ts+++ b/packages/database/src/repositories/channel/__tests__/userMembers.test.ts@@ -1,9 +1,9 @@// @vitest-environment node-import { and, eq } from 'drizzle-orm';+import { and, eq, isNull } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../../core/getTestDB';-import { channelMembers, channels, workspaceMembers } from '../../../schemas';+import { channelMembers, channels, userContacts, workspaceMembers } from '../../../schemas';import { ChannelRepository } from '..';import { createChannelFixture } from './testUtils';@@ -16,7 +16,17 @@ beforeEach(async () => {{ workspaceId: fixture.workspaceId, userId: fixture.memberId },]);});-afterEach(fixture.cleanup);+afterEach(async () => {+ await db.delete(userContacts);+ await fixture.cleanup();+});++/** Makes two people personal contacts, in both directions as an accepted request does. */+const befriend = (a: string, b: string) =>+ db.insert(userContacts).values([+ { contactUserId: b, type: 'user', userId: a },+ { contactUserId: a, type: 'user', userId: b },+ ]);const create = async () => {const owner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);@@ -75,16 +85,12 @@ describe('Channel human membership', () => {expect((await owner.detail(channel.id)).members).toHaveLength(1);});- it('rejects personal, wrong-scope, direct and trashed channels', async () => {+ it('rejects wrong-scope, direct and trashed channels', async () => {const { owner, channel } = await create();const personal = new ChannelRepository(db, fixture.ownerId);await expect(personal.addUser(channel.id, fixture.memberId)).rejects.toMatchObject({code: 'NOT_FOUND',});- const { channel: own } = await personal.create({ title: 'Personal' });- await expect(personal.addUser(own.id, fixture.memberId)).rejects.toMatchObject({- code: 'BAD_REQUEST',- });const agent = await fixture.addAgent(channel.id, 'Direct');const direct = await owner.create({ agentId: agent.agentId!, title: 'Direct' });await expect(owner.addUser(direct.channel.id, fixture.memberId)).rejects.toMatchObject({@@ -171,15 +177,7 @@ describe('Channel human membership', () => {).toEqual([]);});- it('keeps people out of personal Channels and direct conversations', async () => {- const personal = new ChannelRepository(db, fixture.ownerId);- await expect(personal.newChannelUserCandidates()).rejects.toMatchObject({- code: 'BAD_REQUEST',- });- await expect(- personal.create({ title: 'Personal', userIds: [fixture.memberId] }),- ).rejects.toMatchObject({ code: 'BAD_REQUEST' });-+ it('keeps people out of direct conversations', async () => {const { owner, channel } = await create();const agent = await fixture.addAgent(channel.id, 'Direct');await expect(@@ -196,4 +194,79 @@ describe('Channel human membership', () => {await expect(owner.newChannelUserCandidates()).rejects.toMatchObject({ code: 'NOT_FOUND' });});});++ describe('personal groups', () => {+ it('starts a group with mutual contacts, who then talk in it', async () => {+ await befriend(fixture.ownerId, fixture.memberId);+ const owner = new ChannelRepository(db, fixture.ownerId);+ expect(await owner.newChannelUserCandidates('mia')).toEqual([+ expect.objectContaining({ userId: fixture.memberId, username: 'mia' }),+ ]);+ const { channel } = await owner.create({ title: 'Friends', userIds: [fixture.memberId] });+ expect(channel.workspaceId).toBeNull();++ const member = new ChannelRepository(db, fixture.memberId);+ expect(await member.list()).toEqual([+ expect.objectContaining({ id: channel.id, canDelete: false }),+ ]);+ await member.send(channel.id, { content: 'Hi', requestKey: 'hi', routing: 'fallback' });+ expect((await owner.detail(channel.id)).messages[0]).toMatchObject({+ content: 'Hi',+ userId: fixture.memberId,+ });+ // Workspace people are no one's contacts until they connect personally.+ expect(await new ChannelRepository(db, fixture.ownerId, fixture.workspaceId).list()).toEqual(+ [],+ );+ });++ it('invites mutual contacts into an existing group, and only them', async () => {+ const owner = new ChannelRepository(db, fixture.ownerId);+ const { channel } = await owner.create({ title: 'Friends' });+ expect(await owner.userCandidates(channel.id)).toEqual([]);+ await expect(owner.addUser(channel.id, fixture.memberId)).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });++ // One direction alone is a pending friendship, not a contact.+ await db+ .insert(userContacts)+ .values({ contactUserId: fixture.memberId, type: 'user', userId: fixture.ownerId });+ expect(await owner.userCandidates(channel.id)).toEqual([]);+ await db.delete(userContacts);++ await befriend(fixture.ownerId, fixture.memberId);+ expect(await owner.userCandidates(channel.id)).toEqual([+ expect.objectContaining({ userId: fixture.memberId }),+ ]);+ await owner.addUser(channel.id, fixture.memberId);+ expect(await owner.userCandidates(channel.id)).toEqual([]);+ expect((await owner.detail(channel.id)).members).toHaveLength(2);+ });++ it('does not count workspace contacts as personal ones', async () => {+ await db.insert(userContacts).values([+ {+ contactUserId: fixture.memberId,+ type: 'user',+ userId: fixture.ownerId,+ workspaceId: fixture.workspaceId,+ },+ {+ contactUserId: fixture.ownerId,+ type: 'user',+ userId: fixture.memberId,+ workspaceId: fixture.workspaceId,+ },+ ]);+ const owner = new ChannelRepository(db, fixture.ownerId);+ expect(await owner.newChannelUserCandidates()).toEqual([]);+ await expect(+ owner.create({ title: 'Friends', userIds: [fixture.memberId] }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(+ await db.select().from(channels).where(and(eq(channels.userId, fixture.ownerId), isNull(channels.workspaceId))),+ ).toEqual([]);+ });+ });});diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.tsindex 3d66afbf21a..0f758507cf3 100644--- a/packages/database/src/repositories/channel/index.ts+++ b/packages/database/src/repositories/channel/index.ts@@ -148,7 +148,7 @@ export class ChannelRepository {/** Callers check that the project is readable in this scope. */projectId?: string;title: string;- /** Workspace people a group starts with, checked the same way as adding them later. */+ /** People a group starts with, checked the same way as adding them later. */userIds?: string[];/** The direct conversation binds another person's Agent through its live link share. */sharedAgent?: boolean;@@ -207,7 +207,7 @@ export class ChannelRepository {/*** Inviting into a direct conversation starts a group instead, and the direct conversation stays* as it is. The group holds its person and Agent, the Agent keeping its channel-local- * environment, joined by the invited Agents and workspace people.+ * environment, joined by the invited Agents and people.*/createGroupFromDirect = async (channelId: string,@@ -420,15 +420,11 @@ export class ChannelRepository {{ allowArchived: true },);- /** People a new Channel in this workspace can start with. */- newChannelUserCandidates = async (search?: string) => {- const { workspaceId } = this;- if (!workspaceId)- throw new ChannelError('BAD_REQUEST', 'People can only be added to workspace group channels');- return this.db.transaction((tx) =>- newChannelUserCandidates(tx, workspaceId, this.userId, search),+ /** People a new Channel in this scope can start with. */+ newChannelUserCandidates = async (search?: string) =>+ this.db.transaction((tx) =>+ newChannelUserCandidates(tx, this.workspaceId, this.userId, search),);- };userCandidates = async (channelId: string, search?: string) =>this.write(channelId, (tx, access) => channelUserCandidates(tx, access, search), {diff --git a/packages/database/src/repositories/channel/people.ts b/packages/database/src/repositories/channel/people.tsindex 34170e0ef91..d8920393dae 100644--- a/packages/database/src/repositories/channel/people.ts+++ b/packages/database/src/repositories/channel/people.ts@@ -1,10 +1,11 @@import type { SQL } from 'drizzle-orm';import { and, asc, eq, isNull, ne, notExists, or, sql } from 'drizzle-orm';-import { channelMembers, users, workspaceMembers } from '../../schemas';+import { channelMembers, userContacts, users, workspaceMembers } from '../../schemas';import type { Transaction } from '../../type';import { ilikeContains } from '../../utils/like';import { ChannelError } from './error';+import { requirePeerRelation } from './peer';import { audit } from './transaction';import type { ChannelAccess } from './types';@@ -27,39 +28,55 @@ export const requireWorkspaceMember = async (if (!member) throw new ChannelError('NOT_FOUND', 'Workspace member not found');};-const requireWorkspace = async (tx: Transaction, { channel, member }: ChannelAccess) => {- if (!channel.workspaceId)- throw new ChannelError('BAD_REQUEST', 'People can only be added to workspace group channels');- await requireWorkspaceMember(tx, channel.workspaceId, member.userId!);- return channel.workspaceId;+/** A personal contact of `userId` in both directions: someone they can talk with one-on-one. */+const mutualPersonalContact = (userId: string, contactUserId: SQL | string) => {+ const side = (from: SQL | string, to: SQL | string) =>+ sql`exists (select 1 from ${userContacts} where ${userContacts.type} = 'user' and ${userContacts.workspaceId} is null and ${userContacts.userId} = ${from} and ${userContacts.contactUserId} = ${to})`;+ return and(side(userId, contactUserId), side(contactUserId, userId))!;};-const requireGroupWorkspace = async (tx: Transaction, access: ChannelAccess) => {- if (access.channel.agentId)- throw new ChannelError('BAD_REQUEST', 'People can only be added to workspace group channels');- return requireWorkspace(tx, access);+/** Only group Channels take people; a direct conversation starts a group instead. */+const requireGroup = ({ channel }: ChannelAccess) => {+ if (channel.agentId || channel.peerUserId)+ throw new ChannelError('BAD_REQUEST', 'People can only be added to group channels');};-const workspaceUserCandidates = (+/**+ * Who `userId` can bring into a Channel in this scope: in a workspace, its active members; in the+ * personal space, their mutual contacts, the same people they can talk with one-on-one.+ */+const userCandidates = async (tx: Transaction,- workspaceId: string,+ workspaceId: string | null,+ userId: string,exclude: SQL,search: string,) => {+ if (workspaceId) await requireWorkspaceMember(tx, workspaceId, userId);const query = search.trim();- return tx+ const base = tx.select({avatar: users.avatar,fullName: users.fullName,userId: users.id,username: users.username,})- .from(workspaceMembers)- .innerJoin(users, eq(users.id, workspaceMembers.userId))+ .from(users);+ const scoped = workspaceId+ ? base.innerJoin(+ workspaceMembers,+ and(+ eq(workspaceMembers.userId, users.id),+ eq(workspaceMembers.workspaceId, workspaceId),+ isNull(workspaceMembers.deletedAt),+ ),+ )+ : base;+ return scoped.where(and(- eq(workspaceMembers.workspaceId, workspaceId),- isNull(workspaceMembers.deletedAt),+ workspaceId ? undefined : mutualPersonalContact(userId, sql`${users.id}`),+ ne(users.id, userId),exclude,query? or(ilikeContains(users.fullName, query), ilikeContains(users.username, query))@@ -71,25 +88,26 @@ const workspaceUserCandidates = (};/**- * Only active people in this workspace; search the full directory, not a client-side page. A- * direct conversation lists them for the group that inviting from it starts.+ * Only people the caller can bring in that are not already active here; search the full+ * directory, not a client-side page. A direct conversation lists them for the group that inviting+ * from it starts.*/export const channelUserCandidates = async (tx: Transaction,- access: ChannelAccess,+ { channel, member }: ChannelAccess,search = '',-) => {- const workspaceId = await requireWorkspace(tx, access);- return workspaceUserCandidates(+) =>+ userCandidates(tx,- workspaceId,+ channel.workspaceId,+ member.userId!,notExists(tx.select({ id: channelMembers.id }).from(channelMembers).where(and(- eq(channelMembers.channelId, access.channel.id),+ eq(channelMembers.channelId, channel.id),eq(channelMembers.userId, users.id),eq(channelMembers.status, 'active'),),@@ -97,18 +115,14 @@ export const channelUserCandidates = async (),search,);-};-/** The people a new workspace Channel can start with: everyone active except its creator. */-export const newChannelUserCandidates = async (+/** The people a new Channel in this scope can start with: everyone the creator can bring in. */+export const newChannelUserCandidates = (tx: Transaction,- workspaceId: string,+ workspaceId: string | null,userId: string,search = '',-) => {- await requireWorkspaceMember(tx, workspaceId, userId);- return workspaceUserCandidates(tx, workspaceId, ne(users.id, userId), search);-};+) => userCandidates(tx, workspaceId, userId, sql`true`, search);/*** Member metadata naming who added the member, merged into what it already holds. A null inviter,@@ -120,8 +134,16 @@ export const memberInviterMetadata = (invitedBy: string | null) =>: sql`coalesce(${channelMembers.metadata}, '{}'::jsonb) - 'invitedBy'`;export const addChannelUser = async (tx: Transaction, access: ChannelAccess, userId: string) => {- const workspaceId = await requireGroupWorkspace(tx, access);- await requireWorkspaceMember(tx, workspaceId, userId);+ requireGroup(access);+ const { workspaceId } = access.channel;+ const inviterId = access.member.userId!;+ if (workspaceId) {+ await requireWorkspaceMember(tx, workspaceId, inviterId);+ await requireWorkspaceMember(tx, workspaceId, userId);+ } else if (userId !== inviterId) {+ // A personal group takes the inviter's mutual contacts, checked like a one-on-one chat.+ await requirePeerRelation(tx, null, inviterId, userId);+ }const [existing] = await tx.select().from(channelMembers)diff --git a/src/features/Channels/CreateChannel/PeopleOptions.tsx b/src/features/Channels/CreateChannel/PeopleOptions.tsxindex f60f9e581cc..b6368d8de3e 100644--- a/src/features/Channels/CreateChannel/PeopleOptions.tsx+++ b/src/features/Channels/CreateChannel/PeopleOptions.tsx@@ -17,7 +17,7 @@ import { pickerStyles } from './pickerStyles';const CANDIDATE_LIMIT = 50;export interface PeopleSelection {- /** Unset while creating a Channel: every workspace member except the creator. */+ /** Unset while creating a Channel: everyone the creator can bring in, except themselves. */channelId?: string;onChange: Dispatch<SetStateAction<ChannelPersonOption[]>>;value: ChannelPersonOption[];@@ -32,7 +32,7 @@ const PersonAvatar = ({ name, person }: { name: string; person: ChannelPersonOpt<Avatar avatar={person.avatar || DEFAULT_USER_AVATAR} shape={'circle'} size={28} title={name} />);-/** Workspace members who are not in the Channel yet, searched on the server. */+/** People who can join and are not in the Channel yet, searched on the server. */export const PeopleOptions = ({ people, search }: { people: PeopleSelection; search: string }) => {const { t } = useTranslation('channel');const nameOf = usePersonName();diff --git a/src/features/Channels/CreateChannel/index.tsx b/src/features/Channels/CreateChannel/index.tsxindex d654fd76ed9..51022b7c8a8 100644--- a/src/features/Channels/CreateChannel/index.tsx+++ b/src/features/Channels/CreateChannel/index.tsx@@ -5,7 +5,6 @@ import { Hash } from 'lucide-react';import { useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';-import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import AsyncError from '@/components/AsyncError';import type { ChannelPersonOption } from '@/services/channel';import { channelActions } from '@/store/channel';@@ -29,8 +28,6 @@ interface ExistingChannel {id: string;/** The project a project Channel belongs to: it seats only that project's Agents. */projectId: string | null;- /** People can be invited only into workspace Channels. */- workspaceId: string | null;}interface CreateChannelProps {@@ -59,7 +56,8 @@ export const openInviteMembers = (existing: ExistingChannel, onCreated?: (id: st/*** Like starting a group chat: choose members first. The name is optional and defaults to the* members' names; the sidebar renames it later. Inviting into an existing Channel uses the- * same picker without a name. Workspace Channels, new or existing, also list workspace members.+ * same picker without a name. It also lists the people who can join: workspace members in a+ * workspace, mutual contacts in the personal space.*/function CreateChannel({ existing, onCreated, projectId }: CreateChannelProps) {const { t } = useTranslation('channel');@@ -72,9 +70,6 @@ function CreateChannel({ existing, onCreated, projectId }: CreateChannelProps) {const options = useChannelAgentOptions((existing ? existing.projectId : projectId) ?? undefined);const direct = existing?.directAgentName !== undefined;const nameOf = usePersonName();- const activeWorkspaceId = useActiveWorkspaceId();- // People join only workspace Channels: a new one is created in the active workspace.- const canPickPeople = existing ? !!existing.workspaceId : !!activeWorkspaceId;const dirty = !!title.trim() || agents.length > 0 || people.length > 0;// A mask click must not drop what the user typed or picked; ✕ and Esc still close.@@ -163,11 +158,7 @@ function CreateChannel({ existing, onCreated, projectId }: CreateChannelProps) {exclude={existing?.agentIds}options={options}value={agents}- people={- canPickPeople- ? { channelId: existing?.id, onChange: setPeople, value: people }- : undefined- }+ people={{ channelId: existing?.id, onChange: setPeople, value: people }}onChange={setAgents}/></Flexbox>diff --git a/src/features/Channels/MemberStatus.tsx b/src/features/Channels/MemberStatus.tsxindex cb1b5151b05..3355c40bfce 100644--- a/src/features/Channels/MemberStatus.tsx+++ b/src/features/Channels/MemberStatus.tsx@@ -187,7 +187,6 @@ export function MemberStatus({directAgentName: channel.agentId ? (directAgent?.name ?? '') : undefined,id: channel.id,projectId: channel.projectId,- workspaceId: channel.workspaceId,},// Inviting from a direct conversation opens the group it starts.(id) => navigate(CHANNEL_URL(id)),diff --git a/src/features/Channels/Settings/MembersSection.tsx b/src/features/Channels/Settings/MembersSection.tsxindex 96747fc7cd5..14eb1e06a19 100644--- a/src/features/Channels/Settings/MembersSection.tsx+++ b/src/features/Channels/Settings/MembersSection.tsx@@ -29,7 +29,6 @@ export function MembersSection({ detail }: { detail: ChannelDetail }) {),id: channel.id,projectId: channel.projectId,- workspaceId: channel.workspaceId,})}>