π€― 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(contact): let a workspace's external contact reach their contacts and conversations (#23291)
Arvin Xu5a23c8fe500d
diff --git a/apps/server/src/routers/lambda/__tests__/channel.featureFlag.test.ts b/apps/server/src/routers/lambda/__tests__/channel.featureFlag.test.tsindex 23a18dfa417..a54ca28c0ab 100644--- a/apps/server/src/routers/lambda/__tests__/channel.featureFlag.test.ts+++ b/apps/server/src/routers/lambda/__tests__/channel.featureFlag.test.ts@@ -7,9 +7,9 @@ vi.mock('@/database/core/db-adaptor', () => ({}),}));-vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async (importOriginal) => {const { authedProcedure } = await import('@/libs/trpc/lambda');- return { wsCompatProcedure: authedProcedure };+ return { ...(await importOriginal<object>()), wsExternalCompatProcedure: authedProcedure };});const flags = vi.hoisted(() => ({ enableChannels: false as boolean | undefined }));diff --git a/apps/server/src/routers/lambda/__tests__/channel.wakeConfig.test.ts b/apps/server/src/routers/lambda/__tests__/channel.wakeConfig.test.tsindex c735349d385..37bd187a628 100644--- a/apps/server/src/routers/lambda/__tests__/channel.wakeConfig.test.ts+++ b/apps/server/src/routers/lambda/__tests__/channel.wakeConfig.test.ts@@ -7,9 +7,9 @@ vi.mock('@/database/core/db-adaptor', () => ({}),}));-vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async (importOriginal) => {const { authedProcedure } = await import('@/libs/trpc/lambda');- return { wsCompatProcedure: authedProcedure };+ return { ...(await importOriginal<object>()), wsExternalCompatProcedure: authedProcedure };});vi.mock('@/server/featureFlags', () => ({diff --git a/apps/server/src/routers/lambda/__tests__/externalContact.test.ts b/apps/server/src/routers/lambda/__tests__/externalContact.test.tsnew file mode 100644index 00000000000..d9db4983965--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/externalContact.test.ts@@ -0,0 +1,114 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++/** The caller as Cloud resolves them: a workspace's external contact, or not. */+const caller = vi.hoisted(() => ({ external: true }));++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return {};+ }),+}));+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async (importOriginal) => {+ const { authedProcedure } = await import('@/libs/trpc/lambda');+ const { trpc } = await import('@/libs/trpc/lambda/init');+ return {+ ...(await importOriginal<object>()),+ wsExternalCompatProcedure: authedProcedure.use(+ trpc.middleware(({ next }) =>+ next({ ctx: { isExternalContact: caller.external, workspaceId: 'ws_team' } }),+ ),+ ),+ };+});+vi.mock('@/server/services/channel/featureGate', () => ({+ isChannelEnabled: vi.fn().mockResolvedValue(true),+}));++const contactModel = vi.hoisted(() => ({+ addAgent: vi.fn(),+ list: vi.fn(),+ listRequests: vi.fn(),+ openTo: vi.fn(),+ removeExternal: vi.fn(),+ removeUser: vi.fn(),+ search: vi.fn(),+ sendRequest: vi.fn(),+}));+vi.mock('@/database/models/contact', () => ({+ ContactModel: vi.fn(function () {+ return contactModel;+ }),+}));+vi.mock('@/server/services/contact/notify', () => ({+ notifyContactRequestAfterResponse: vi.fn(),+ notifyContactsChangedAfterResponse: vi.fn(),+}));++const channelService = vi.hoisted(() => ({+ create: vi.fn(),+ join: vi.fn(),+ openDirect: vi.fn(),+ openPeer: vi.fn(),+ repository: { list: vi.fn(), listJoinable: vi.fn() },+}));+vi.mock('@/server/services/channel/ChannelService', () => ({+ ChannelService: vi.fn(function () {+ return channelService;+ }),+}));++const { contactRouter } = await import('../contact');+const { channelRouter } = await import('../channel');++const ctx = { serverDB: {}, userId: 'u_bob' } as any;+const contacts = () => contactRouter.createCaller(ctx);+const channels = () => channelRouter.createCaller(ctx);+const CHANNEL_ID = 'chn_abcdefghijkl';++describe('a workspace external contact', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ caller.external = true;+ contactModel.list.mockResolvedValue([]);+ channelService.repository.list.mockResolvedValue([]);+ channelService.openPeer.mockResolvedValue({ channel: { id: CHANNEL_ID } });+ });++ it('reaches their address book and their one-on-one conversations', async () => {+ await expect(contacts().list()).resolves.toEqual([]);+ await expect(channels().list()).resolves.toEqual({ data: [], success: true });+ await expect(channels().openPeer({ userId: 'u_alice' })).resolves.toEqual({+ data: CHANNEL_ID,+ success: true,+ });+ });++ it('is refused everything else, before the model or service runs', async () => {+ const refused = [+ () => contacts().sendRequest({ userId: 'u_carol' }),+ () => contacts().openToExternal({ userId: 'u_carol' }),+ () => contacts().addAgent({ share: 'helper' }),+ () => channels().listJoinable(),+ () => channels().join({ channelId: CHANNEL_ID }),+ () => channels().openDirect({ agentId: 'agt_team' }),+ () => channels().userCandidates({}),+ ];+ for (const call of refused)+ await expect(call()).rejects.toMatchObject({+ code: 'FORBIDDEN',+ message: 'Not available to external contacts',+ });+ expect(contactModel.sendRequest).not.toHaveBeenCalled();+ expect(contactModel.openTo).not.toHaveBeenCalled();+ expect(channelService.repository.listJoinable).not.toHaveBeenCalled();+ expect(channelService.join).not.toHaveBeenCalled();+ expect(channelService.openDirect).not.toHaveBeenCalled();+ });++ it('leaves members untouched', async () => {+ caller.external = false;+ channelService.repository.listJoinable.mockResolvedValue([]);+ await expect(channels().listJoinable()).resolves.toEqual({ data: [] });+ });+});diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.tsindex e22eec72793..77b00f3642c 100644--- a/apps/server/src/routers/lambda/channel.ts+++ b/apps/server/src/routers/lambda/channel.ts@@ -3,7 +3,10 @@ import { CHANNEL_LIMITS, SIGNAL_DECISION_OUTCOMES } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { z } from 'zod';-import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';+import {+ denyExternalContact,+ wsExternalCompatProcedure,+} from '@/business/server/trpc-middlewares/workspaceAuth';import { SCOPE_READ_MAX_LIMIT, SignalDecisionModel } from '@/database/models/signalDecision';import { ChannelError } from '@/database/repositories/channel';import { router } from '@/libs/trpc/lambda';@@ -29,28 +32,38 @@ const agentSelection = z.object({name: z.string().trim().min(1).max(100).optional(),workingDirectory: z.string().trim().min(1).max(4096).optional(),});-const channelProcedure = wsCompatProcedure.use(serverDatabase).use(async ({ ctx, next }) => {- if (!(await isChannelEnabled(ctx.userId)))- throw new TRPCError({- code: 'FORBIDDEN',- message: 'Channels are not enabled for this account',+const channelBaseProcedure = wsExternalCompatProcedure+ .use(serverDatabase)+ .use(async ({ ctx, next }) => {+ if (!(await isChannelEnabled(ctx.userId)))+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Channels are not enabled for this account',+ });+ const result = await next({+ ctx: {+ channelService: new ChannelService(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ projectModelOptions(ctx),+ ),+ },});- const result = await next({- ctx: {- channelService: new ChannelService(- ctx.serverDB,- ctx.userId,- ctx.workspaceId ?? undefined,- projectModelOptions(ctx),- ),- },+ if (!result.ok && result.error.cause instanceof ChannelError) {+ const cause = result.error.cause;+ throw new TRPCError({ cause, code: cause.code, message: cause.message });+ }+ return result;});- if (!result.ok && result.error.cause instanceof ChannelError) {- const cause = result.error.cause;- throw new TRPCError({ cause, code: cause.code, message: cause.message });- }- return result;-});++/**+ * What a workspace's external contact may do in it: their one-on-one conversations with the+ * members open to them. The Channel repository rechecks the pairing on every open and send.+ */+const externalChannelProcedure = channelBaseProcedure;+/** Everything else is for members (and the personal space) only. */+const channelProcedure = channelBaseProcedure.use(denyExternalContact);export const channelRouter = router({...channelHistoryProcedures,@@ -216,7 +229,7 @@ export const channelRouter = router({data: await ctx.channelService.createGroupFromDirect(input.channelId, input),success: true,})),- detail: channelProcedure+ detail: externalChannelProcedure.input(z.object({before: z.number().int().positive().optional(),@@ -264,7 +277,7 @@ export const channelRouter = router({* The one-on-one conversation with another person: a mutual contact in the personal space, a* fellow member in a workspace.*/- openPeer: channelProcedure+ openPeer: externalChannelProcedure.input(z.object({ userId: z.string().min(1).max(64) })).mutation(async ({ ctx, input }) => {const access = await ctx.channelService.openPeer(input.userId);@@ -286,18 +299,18 @@ export const channelRouter = router({const { readable } = await ctx.channelService.leave(input.channelId);return { readable, success: true };}),- list: channelProcedure.query(async ({ ctx }) => ({+ list: externalChannelProcedure.query(async ({ ctx }) => ({data: await ctx.channelService.repository.list(),success: true,})),- markRead: channelProcedure+ markRead: externalChannelProcedure.input(z.object({ channelId, sequence: z.number().int().nonnegative() })).mutation(async ({ ctx, input }) => ({data: await ctx.channelService.repository.markRead(input.channelId, input.sequence),success: true,})),/** Pins or unpins the conversation atop the caller's own list. */- setPinned: channelProcedure+ setPinned: externalChannelProcedure.input(z.object({ channelId, pinned: z.boolean() })).mutation(async ({ ctx, input }) => ({data: await ctx.channelService.repository.setPinned(input.channelId, input.pinned),@@ -313,7 +326,7 @@ export const channelRouter = router({await ctx.channelService.setMemberMuted(input.channelId, input.memberId, input.muted);return { success: true };}),- editMessage: channelProcedure+ editMessage: externalChannelProcedure.input(z.object({channelId,@@ -368,7 +381,7 @@ export const channelRouter = router({data: await ctx.channelService.retryRouting(input.channelId, input.messageId),success: true,})),- send: channelProcedure+ send: externalChannelProcedure.input(z.object({channelId,diff --git a/apps/server/src/routers/lambda/contact.ts b/apps/server/src/routers/lambda/contact.tsindex 7f139720802..107005c8b52 100644--- a/apps/server/src/routers/lambda/contact.ts+++ b/apps/server/src/routers/lambda/contact.ts@@ -3,8 +3,9 @@ import { TRPCError } from '@trpc/server';import { z } from 'zod';import {+ denyExternalContact,requireWorkspaceRoleWhenScoped,- wsCompatProcedure,+ wsExternalCompatProcedure,} from '@/business/server/trpc-middlewares/workspaceAuth';import { ContactModel } from '@/database/models/contact';import { router } from '@/libs/trpc/lambda';@@ -21,16 +22,27 @@ import {* in a workspace, its external contacts (colleagues are its members). Shared Agents: the caller's* own in the personal space, the workspace's β seen by every member β in a workspace.*/-const contactProcedure = wsCompatProcedure.use(serverDatabase).use(async ({ ctx, next }) => {- if (!(await isChannelEnabled(ctx.userId)))- throw new TRPCError({- code: 'FORBIDDEN',- message: 'Channels are not enabled for this account',+const contactBaseProcedure = wsExternalCompatProcedure+ .use(serverDatabase)+ .use(async ({ ctx, next }) => {+ if (!(await isChannelEnabled(ctx.userId)))+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Channels are not enabled for this account',+ });+ return next({+ ctx: { contactModel: new ContactModel(ctx.serverDB, ctx.userId, ctx.workspaceId) },});- return next({- ctx: { contactModel: new ContactModel(ctx.serverDB, ctx.userId, ctx.workspaceId) },});-});++/**+ * What a workspace's external contact may read there: the members open to them, and dropping+ * one. `ContactModel` narrows each of these to them; requests are answered by id, from the+ * personal space.+ */+const externalContactProcedure = contactBaseProcedure;+/** Everything else is for members (and the personal space) only. */+const contactProcedure = contactBaseProcedure.use(denyExternalContact);const userId = z.string().min(1).max(64);const requestId = z.string().uuid();@@ -38,15 +50,20 @@ const requestId = z.string().uuid();const handle = z.string().trim().min(1).max(512);export const contactRouter = router({- list: contactProcedure.query(async ({ ctx }) => ctx.contactModel.list()),+ list: externalContactProcedure.query(async ({ ctx }) => ctx.contactModel.list()),- search: contactProcedure+ search: externalContactProcedure.input(z.object({ query: handle })).query(async ({ ctx, input }) => ctx.contactModel.search(input.query)),// ββ People ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ- listRequests: contactProcedure.query(async ({ ctx }) => ctx.contactModel.listRequests()),+ /** The workspaces I am an external contact of, whatever the active scope. */+ listExternalWorkspaces: externalContactProcedure.query(async ({ ctx }) =>+ ctx.contactModel.listExternalWorkspaces(),+ ),++ listRequests: externalContactProcedure.query(async ({ ctx }) => ctx.contactModel.listRequests()),// In a workspace this invites someone outside it to be an external contact: a member's act.sendRequest: contactProcedure@@ -70,7 +87,7 @@ export const contactRouter = router({return result;}),- acceptRequest: contactProcedure+ acceptRequest: externalContactProcedure.input(z.object({ requestId })).mutation(async ({ ctx, input }) => {const result = await ctx.contactModel.acceptRequest(input.requestId);@@ -84,7 +101,7 @@ export const contactRouter = router({return result;}),- declineRequest: contactProcedure+ declineRequest: externalContactProcedure.input(z.object({ requestId })).mutation(async ({ ctx, input }) => {const { requesterId } = await ctx.contactModel.declineRequest(input.requestId);@@ -92,7 +109,7 @@ export const contactRouter = router({return { success: true };}),- cancelRequest: contactProcedure+ cancelRequest: externalContactProcedure.input(z.object({ requestId })).mutation(async ({ ctx, input }) => {const { addresseeId } = await ctx.contactModel.cancelRequest(input.requestId);@@ -100,11 +117,13 @@ export const contactRouter = router({return { success: true };}),- removeUser: contactProcedure.input(z.object({ userId })).mutation(async ({ ctx, input }) => {- await ctx.contactModel.removeUser(input.userId);- notifyContactsChangedAfterResponse([ctx.userId, input.userId]);- return { success: true };- }),+ removeUser: externalContactProcedure+ .input(z.object({ userId }))+ .mutation(async ({ ctx, input }) => {+ await ctx.contactModel.removeUser(input.userId);+ notifyContactsChangedAfterResponse([ctx.userId, input.userId]);+ return { success: true };+ }),/** A member opens themselves to one of the workspace's external contacts. */openToExternal: contactProcedure@@ -127,15 +146,17 @@ export const contactRouter = router({}),/** A person's profile, their relation to me and the Agents they share by link. */- userProfile: contactProcedure.input(z.object({ userId })).query(async ({ ctx, input }) => {- const [user, relation, sharedAgents] = await Promise.all([- ctx.contactModel.findUser(input.userId),- ctx.contactModel.relationTo(input.userId),- ctx.contactModel.listSharedAgentsOf(input.userId),- ]);- if (!user) throw new TRPCError({ code: 'NOT_FOUND', message: 'User not found' });- return { relation, sharedAgents, user };- }),+ userProfile: externalContactProcedure+ .input(z.object({ userId }))+ .query(async ({ ctx, input }) => {+ const [user, relation, sharedAgents] = await Promise.all([+ ctx.contactModel.findUser(input.userId),+ ctx.contactModel.relationTo(input.userId),+ ctx.contactModel.listSharedAgentsOf(input.userId),+ ]);+ if (!user) throw new TRPCError({ code: 'NOT_FOUND', message: 'User not found' });+ return { relation, sharedAgents, user };+ }),// ββ Agents ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdiff --git a/packages/business-server/src/trpc-middlewares/workspaceAuth.ts b/packages/business-server/src/trpc-middlewares/workspaceAuth.tsindex 482f07f73f1..1a9e8a3c723 100644--- a/packages/business-server/src/trpc-middlewares/workspaceAuth.ts+++ b/packages/business-server/src/trpc-middlewares/workspaceAuth.ts@@ -36,3 +36,31 @@ export const wsOwnerProcedure = authedProcedure.use(requireWorkspaceId);export const wsAdminProcedure = authedProcedure.use(requireWorkspaceId);export const wsCompatProcedure = authedProcedure.use(cloudWorkspaceAuth);++/**+ * `cloudWorkspaceAuth` for the only routers an external contact of a workspace may reach: the+ * address book and Channels. Cloud admits a non-member paired with a member of the requested+ * workspace there, with `isExternalContact` and no role; every other router keeps treating them+ * as personal. Outside Cloud nobody is an external contact.+ */+export const externalContactWorkspaceAuth = trpc.middleware(async (opts) =>+ opts.next({+ ctx: {+ isExternalContact: false as boolean,+ workspaceSlug: undefined as string | undefined,+ },+ }),+);++export const wsExternalCompatProcedure = authedProcedure.use(externalContactWorkspaceAuth);++/**+ * Refuses a workspace's external contact. Routers on `wsExternalCompatProcedure` put it on every+ * procedure except the few an external contact needs, so a new procedure is closed to them until+ * someone opens it on purpose.+ */+export const denyExternalContact = trpc.middleware(async ({ ctx, next }) => {+ if ((ctx as { isExternalContact?: boolean }).isExternalContact)+ throw new TRPCError({ code: 'FORBIDDEN', message: 'Not available to external contacts' });+ return next();+});diff --git a/packages/database/src/models/__tests__/contact.test.ts b/packages/database/src/models/__tests__/contact.test.tsindex c4a53c50209..06338f61f9f 100644--- a/packages/database/src/models/__tests__/contact.test.ts+++ b/packages/database/src/models/__tests__/contact.test.ts@@ -377,6 +377,18 @@ describe('external contacts of a workspace', () => {await expect(bobInTeam().list()).rejects.toThrow('Not a member of this workspace');});+ it('lists the workspaces I am an external contact of, while a member is paired with me', async () => {+ expect(await bobModel.listExternalWorkspaces()).toEqual([]);+ await inviteBob();+ expect(await bobModel.listExternalWorkspaces()).toEqual([+ { avatar: null, id: teamId, name: 'Team' },+ ]);+ // Members are never external, and the workspace goes once no member is paired with me.+ expect(await aliceModel.listExternalWorkspaces()).toEqual([]);+ await aliceInTeam.removeUser(bob);+ expect(await bobModel.listExternalWorkspaces()).toEqual([]);+ });+it('lets the invitation lapse once the inviter leaves the workspace', async () => {const { requestId } = await carolInTeam.sendRequest(bob);await serverDBdiff --git a/packages/database/src/models/contact.ts b/packages/database/src/models/contact.tsindex 0adcbc6e118..9f085fad71c 100644--- a/packages/database/src/models/contact.ts+++ b/packages/database/src/models/contact.ts@@ -7,6 +7,7 @@ import type {ContactSearchResult,ContactUserItem,ContactUserProfile,+ ContactWorkspace,} from '@lobechat/types';import { TRPCError } from '@trpc/server';import type { SQLWrapper } from 'drizzle-orm';@@ -638,6 +639,43 @@ export class ContactModel {});};+ /**+ * The workspaces I am an external contact of, for the space switcher: paired there with a+ * member who still is one, and not a member myself. Independent of the active scope.+ */+ listExternalWorkspaces = async (): Promise<ContactWorkspace[]> => {+ const myMembership = alias(workspaceMembers, 'my_membership');+ return this.db+ .selectDistinct({ avatar: workspaces.avatar, id: workspaces.id, name: workspaces.name })+ .from(userContacts)+ .innerJoin(workspaces, eq(workspaces.id, userContacts.workspaceId))+ .innerJoin(+ workspaceMembers,+ and(+ eq(workspaceMembers.workspaceId, userContacts.workspaceId),+ eq(workspaceMembers.userId, userContacts.contactUserId),+ isNull(workspaceMembers.deletedAt),+ ),+ )+ .leftJoin(+ myMembership,+ and(+ eq(myMembership.workspaceId, userContacts.workspaceId),+ eq(myMembership.userId, this.userId),+ isNull(myMembership.deletedAt),+ ),+ )+ .where(+ and(+ eq(userContacts.userId, this.userId),+ eq(userContacts.type, 'user'),+ isNotNull(userContacts.workspaceId),+ isNull(myMembership.userId),+ ),+ )+ .orderBy(workspaces.name);+ };+/** Someone paired with a member here who is not a member themselves. */private async isExternal(userId: string) {if (await this.isMember(userId)) return false;diff --git a/packages/types/src/contact.ts b/packages/types/src/contact.tsindex f5fe4285f83..f313431e9b7 100644--- a/packages/types/src/contact.ts+++ b/packages/types/src/contact.ts@@ -68,12 +68,15 @@ export interface ContactRequestItem {workspace?: ContactRequestWorkspace | null;}-export interface ContactRequestWorkspace {+/** A workspace as the address book names it: an invitation's origin, or one I am external to. */+export interface ContactWorkspace {avatar: string | null;id: string;name: string;}+export type ContactRequestWorkspace = ContactWorkspace;+/*** Relation of a search result or profile to the current user, in the active scope. `member`:* a fellow member of the active workspace, reachable without being a contact.