Skip to content

🀯 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.

♻️ refactor(contact): move the address book behind business slots (#23614)

Arvin Xufcd202e8ae0d
diff --git a/apps/server/src/routers/lambda/__tests__/agentShare.test.ts b/apps/server/src/routers/lambda/__tests__/agentShare.test.ts
index 0f1088554e3..dfa9ae5e862 100644
--- a/apps/server/src/routers/lambda/__tests__/agentShare.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/agentShare.test.ts
@@ -113,14 +113,13 @@ vi.mock('@/business/server/agent-share/spendGate', () => ({
const mockFilterAddressBookPeople = vi.fn();
const mockListAddressBookPeople = vi.fn();
const mockFindUser = vi.fn();
-vi.mock('@/database/models/contact', () => ({
- ContactModel: vi.fn(function () {
- return {
- filterAddressBookPeople: mockFilterAddressBookPeople,
- findUser: mockFindUser,
- listAddressBookPeople: mockListAddressBookPeople,
- };
- }),
+vi.mock('@/business/server/contact/addressBook', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ getAddressBook: vi.fn(() => ({
+ filterAddressBookPeople: mockFilterAddressBookPeople,
+ findUser: mockFindUser,
+ listAddressBookPeople: mockListAddressBookPeople,
+ })),
}));
const mockGetFeatureFlagsState = vi.fn();
@@ -481,14 +480,14 @@ describe('agentShareRouter', () => {
// A workspace manager other than the owner must see and save the same
// people the run accepts: the runtime keys the book by the Agent owner.
it('keys the address book by the Agent owner, not the calling manager', async () => {
- const { ContactModel } = await import('@/database/models/contact');
+ const { getAddressBook } = await import('@/business/server/contact/addressBook');
const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));
mockAgentOwnerRows.mockResolvedValue([{ userId: 'owner-9' }]);
mockListAddressBookPeople.mockResolvedValue([]);
await caller.listDeviceGrantablePeople({ agentId: 'agent-1' });
- expect(ContactModel).toHaveBeenCalledWith(expect.anything(), 'owner-9', undefined);
+ expect(getAddressBook).toHaveBeenCalledWith(expect.anything(), 'owner-9', undefined);
expect(mockGetFeatureFlagsState).toHaveBeenCalledWith('owner-9');
});
diff --git a/apps/server/src/routers/lambda/__tests__/contact.notify.test.ts b/apps/server/src/routers/lambda/__tests__/contact.notify.test.ts
deleted file mode 100644
index 96c6d3e9d1b..00000000000
--- a/apps/server/src/routers/lambda/__tests__/contact.notify.test.ts
+++ /dev/null
@@ -1,162 +0,0 @@
-// @vitest-environment node
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-const model = vi.hoisted(() => ({
- acceptRequest: vi.fn(),
- cancelRequest: vi.fn(),
- declineRequest: vi.fn(),
- openTo: vi.fn(),
- removeExternal: vi.fn(),
- removeUser: vi.fn(),
- sendRequest: vi.fn(),
-}));
-const { acceptRequest, sendRequest } = model;
-const { contactsChanged, notify, openConversation } = vi.hoisted(() => ({
- contactsChanged: vi.fn(),
- notify: vi.fn(),
- openConversation: vi.fn(),
-}));
-
-vi.mock('@/database/core/db-adaptor', () => ({
- getServerDB: vi.fn(function () {
- return {};
- }),
-}));
-vi.mock('@/server/services/channel/featureGate', () => ({
- isChannelEnabled: vi.fn().mockResolvedValue(true),
-}));
-vi.mock('@/database/models/contact', () => ({
- ContactModel: vi.fn(function () {
- return model;
- }),
-}));
-vi.mock('@/server/services/contact/notify', () => ({
- notifyContactRequestAfterResponse: notify,
- notifyContactsChangedAfterResponse: contactsChanged,
-}));
-
-vi.mock('@/server/services/contact/conversation', () => ({
- openContactConversation: openConversation,
-}));
-
-const { contactRouter } = await import('../contact');
-
-const REQUEST_ID = '6f1c1d2e-4b0a-4c55-9a39-3b1d8f0e2a11';
-
-describe('contactRouter notifications', () => {
- const caller = () => contactRouter.createCaller({ serverDB: {}, userId: 'me' } as any);
-
- beforeEach(() => vi.clearAllMocks());
-
- it('tells the addressee about a new request', async () => {
- sendRequest.mockResolvedValue({ requestId: REQUEST_ID, status: 'pending' });
-
- await expect(caller().sendRequest({ userId: 'them' })).resolves.toEqual({
- requestId: REQUEST_ID,
- status: 'pending',
- });
- expect(notify).toHaveBeenCalledWith({
- actorUserId: 'me',
- kind: 'received',
- recipientUserId: 'them',
- requestId: REQUEST_ID,
- });
- });
-
- it('tells them theirs was accepted when sending answers their pending request', async () => {
- sendRequest.mockResolvedValue({ requestId: REQUEST_ID, status: 'accepted' });
-
- await caller().sendRequest({ userId: 'them' });
- expect(notify).toHaveBeenCalledWith(
- expect.objectContaining({ kind: 'accepted', recipientUserId: 'them' }),
- );
- });
-
- it('tells the requester their request was accepted', async () => {
- acceptRequest.mockResolvedValue({ contactUserId: 'them' });
-
- await expect(caller().acceptRequest({ requestId: REQUEST_ID })).resolves.toEqual({
- contactUserId: 'them',
- });
- expect(notify).toHaveBeenCalledWith({
- actorUserId: 'me',
- kind: 'accepted',
- recipientUserId: 'them',
- requestId: REQUEST_ID,
- });
- });
-
- describe('opens the conversation of the new contacts', () => {
- it('as the requester, in the request scope, on accepting', async () => {
- acceptRequest.mockResolvedValue({ contactUserId: 'them', workspaceId: 'ws' });
- await caller().acceptRequest({ requestId: REQUEST_ID });
- expect(openConversation).toHaveBeenCalledWith({
- addresseeId: 'me',
- db: {},
- requesterId: 'them',
- workspaceId: 'ws',
- });
- });
-
- it('when sending answers their pending request', async () => {
- sendRequest.mockResolvedValue({ requestId: REQUEST_ID, status: 'accepted' });
- await caller().sendRequest({ userId: 'them' });
- expect(openConversation).toHaveBeenCalledWith({
- addresseeId: 'me',
- db: {},
- requesterId: 'them',
- workspaceId: null,
- });
- });
-
- it('not for a request still pending', async () => {
- sendRequest.mockResolvedValue({ requestId: REQUEST_ID, status: 'pending' });
- await caller().sendRequest({ userId: 'them' });
- expect(openConversation).not.toHaveBeenCalled();
- });
- });
-
- it('notifies no one when the request fails', async () => {
- sendRequest.mockRejectedValue(new Error('Already a contact'));
-
- await expect(caller().sendRequest({ userId: 'them' })).rejects.toThrow();
- expect(notify).not.toHaveBeenCalled();
- });
-
- describe('refreshes the address book of both people', () => {
- it('on a new request', async () => {
- sendRequest.mockResolvedValue({ requestId: REQUEST_ID, status: 'pending' });
- await caller().sendRequest({ userId: 'them' });
- expect(contactsChanged).toHaveBeenCalledWith(['me', 'them']);
- });
-
- it('on accepting', async () => {
- acceptRequest.mockResolvedValue({ contactUserId: 'them' });
- await caller().acceptRequest({ requestId: REQUEST_ID });
- expect(contactsChanged).toHaveBeenCalledWith(['me', 'them']);
- });
-
- it('on declining, telling the requester', async () => {
- model.declineRequest.mockResolvedValue({ requesterId: 'them' });
- await caller().declineRequest({ requestId: REQUEST_ID });
- expect(contactsChanged).toHaveBeenCalledWith(['me', 'them']);
- });
-
- it('on withdrawing, telling the addressee', async () => {
- model.cancelRequest.mockResolvedValue({ addresseeId: 'them' });
- await caller().cancelRequest({ requestId: REQUEST_ID });
- expect(contactsChanged).toHaveBeenCalledWith(['me', 'them']);
- });
-
- it('on removing a contact', async () => {
- await caller().removeUser({ userId: 'them' });
- expect(contactsChanged).toHaveBeenCalledWith(['me', 'them']);
- });
-
- it('not when the change fails', async () => {
- model.declineRequest.mockRejectedValue(new Error('Request not found'));
- await expect(caller().declineRequest({ requestId: REQUEST_ID })).rejects.toThrow();
- expect(contactsChanged).not.toHaveBeenCalled();
- });
- });
-});
diff --git a/apps/server/src/routers/lambda/__tests__/externalContact.test.ts b/apps/server/src/routers/lambda/__tests__/externalContact.test.ts
index d9db4983965..0d5a22138b2 100644
--- a/apps/server/src/routers/lambda/__tests__/externalContact.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/externalContact.test.ts
@@ -25,26 +25,6 @@ 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(),
@@ -58,11 +38,9 @@ vi.mock('@/server/services/channel/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';
@@ -70,13 +48,11 @@ 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([]);
+ it('reaches their one-on-one conversations', async () => {
await expect(channels().list()).resolves.toEqual({ data: [], success: true });
await expect(channels().openPeer({ userId: 'u_alice' })).resolves.toEqual({
data: CHANNEL_ID,
@@ -86,9 +62,6 @@ describe('a workspace external contact', () => {
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' }),
@@ -99,8 +72,6 @@ describe('a workspace external contact', () => {
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();
diff --git a/apps/server/src/routers/lambda/agentShare.ts b/apps/server/src/routers/lambda/agentShare.ts
index 6c61613fa69..6c7ed283370 100644
--- a/apps/server/src/routers/lambda/agentShare.ts
+++ b/apps/server/src/routers/lambda/agentShare.ts
@@ -8,12 +8,12 @@ import pMap from 'p-map';
import { z } from 'zod';
import { getAgentShareMonthlySpend } from '@/business/server/agent-share/spendGate';
+import { getAddressBook } from '@/business/server/contact/addressBook';
import { withRbacPermission } from '@/business/server/trpc-middlewares/rbacPermission';
import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
import { AgentModel } from '@/database/models/agent';
import { AgentShareModel } from '@/database/models/agentShare';
import { AgentShareProfileModel } from '@/database/models/agentShareProfile';
-import { ContactModel } from '@/database/models/contact';
import { FileModel } from '@/database/models/file';
import { RbacModel } from '@/database/models/rbac';
import { TopicModel } from '@/database/models/topic';
@@ -207,7 +207,7 @@ const shareAddressBook = async (ctx: AgentSharePermissionContext, agentId: strin
.limit(1);
const ownerId = agent?.userId ?? ctx.userId;
return {
- book: new ContactModel(ctx.serverDB, ownerId, ctx.workspaceId),
+ book: getAddressBook(ctx.serverDB, ownerId, ctx.workspaceId),
enabled: await isChannelEnabled(ownerId),
};
};
@@ -444,7 +444,7 @@ export const agentShareRouter = router({
/**
* Who the execution-environment grant can name: the address book of the
- * share's scope (`ContactModel.listAddressBookPeople`). `unlisted` resolves
+ * share's scope (`AddressBook.listAddressBookPeople`). `unlisted` resolves
* the profiles of already-granted people who have since left that book, so
* the settings page can show them as no longer authorized instead of an id.
* `enabled` is false while the address book itself is off for the caller
diff --git a/apps/server/src/routers/lambda/contact.ts b/apps/server/src/routers/lambda/contact.ts
deleted file mode 100644
index deaab229de0..00000000000
--- a/apps/server/src/routers/lambda/contact.ts
+++ /dev/null
@@ -1,214 +0,0 @@
-import { CONTACT_REQUEST_MESSAGE_MAX_LENGTH } from '@lobechat/types';
-import { TRPCError } from '@trpc/server';
-import { z } from 'zod';
-
-import {
- denyExternalContact,
- requireWorkspaceRoleWhenScoped,
- wsExternalCompatProcedure,
-} from '@/business/server/trpc-middlewares/workspaceAuth';
-import { ContactModel } from '@/database/models/contact';
-import { router } from '@/libs/trpc/lambda';
-import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-import { isChannelEnabled } from '@/server/services/channel/featureGate';
-import { openContactConversation } from '@/server/services/contact/conversation';
-import {
- notifyContactRequestAfterResponse,
- notifyContactsChangedAfterResponse,
-} from '@/server/services/contact/notify';
-
-/**
- * The address book belongs to the Channel experience: contacts are who you can message there.
- * Everything in it belongs to the active scope. People: personal contacts in the personal space;
- * 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 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) },
- });
- });
-
-/**
- * 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();
-/** A username, `@handle`, share id or pasted share link. */
-const handle = z.string().trim().min(1).max(512);
-
-export const contactRouter = router({
- list: externalContactProcedure.query(async ({ ctx }) => ctx.contactModel.list()),
-
- search: externalContactProcedure
- .input(z.object({ query: handle }))
- .query(async ({ ctx, input }) => ctx.contactModel.search(input.query)),
-
- // ── People ────────────────────────────────────────────────────────────
-
- /** 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
- .use(requireWorkspaceRoleWhenScoped('member'))
- .input(
- z.object({
- /** The card message the person was found through, recorded as the request's source. */
- cardMessageId: z.uuid().optional(),
- message: z.string().max(CONTACT_REQUEST_MESSAGE_MAX_LENGTH).optional(),
- userId,
- }),
- )
- .mutation(async ({ ctx, input }) => {
- const result = await ctx.contactModel.sendRequest(input.userId, input.message, {
- cardMessageId: input.cardMessageId,
- });
- // Their pending request is the one answered: they asked, in the active scope.
- if (result.status === 'accepted')
- await openContactConversation({
- addresseeId: ctx.userId,
- db: ctx.serverDB,
- requesterId: input.userId,
- workspaceId: ctx.workspaceId ?? null,
- });
- // Sending while their request is pending accepts theirs, so they hear it was accepted.
- notifyContactRequestAfterResponse({
- actorUserId: ctx.userId,
- kind: result.status === 'accepted' ? 'accepted' : 'received',
- recipientUserId: input.userId,
- requestId: result.requestId,
- });
- notifyContactsChangedAfterResponse([ctx.userId, input.userId]);
- return result;
- }),
-
- acceptRequest: externalContactProcedure
- .input(z.object({ requestId }))
- .mutation(async ({ ctx, input }) => {
- const result = await ctx.contactModel.acceptRequest(input.requestId);
- // Opened by the requester in the request's scope: in a workspace that is the member who
- // invited, while the caller answers from the personal space.
- await openContactConversation({
- addresseeId: ctx.userId,
- db: ctx.serverDB,
- requesterId: result.contactUserId,
- workspaceId: result.workspaceId,
- });
- notifyContactRequestAfterResponse({
- actorUserId: ctx.userId,
- kind: 'accepted',
- recipientUserId: result.contactUserId,
- requestId: input.requestId,
- });
- notifyContactsChangedAfterResponse([ctx.userId, result.contactUserId]);
- return result;
- }),
-
- declineRequest: externalContactProcedure
- .input(z.object({ requestId }))
- .mutation(async ({ ctx, input }) => {
- const { requesterId } = await ctx.contactModel.declineRequest(input.requestId);
- notifyContactsChangedAfterResponse([ctx.userId, requesterId]);
- return { success: true };
- }),
-
- cancelRequest: externalContactProcedure
- .input(z.object({ requestId }))
- .mutation(async ({ ctx, input }) => {
- const { addresseeId } = await ctx.contactModel.cancelRequest(input.requestId);
- notifyContactsChangedAfterResponse([ctx.userId, addresseeId]);
- 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
- .use(requireWorkspaceRoleWhenScoped('member'))
- .input(z.object({ userId }))
- .mutation(async ({ ctx, input }) => {
- await ctx.contactModel.openTo(input.userId);
- notifyContactsChangedAfterResponse([ctx.userId, input.userId]);
- return { success: true };
- }),
-
- /** An owner or admin removes an external contact from the workspace. */
- removeExternal: contactProcedure
- .use(requireWorkspaceRoleWhenScoped('admin'))
- .input(z.object({ userId }))
- .mutation(async ({ ctx, input }) => {
- await ctx.contactModel.removeExternal(input.userId);
- notifyContactsChangedAfterResponse([ctx.userId, input.userId]);
- return { success: true };
- }),
-
- /** A person's profile, their relation to me and the Agents they share by link. */
- 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 ────────────────────────────────────────────────────────────
-
- /** The shared-Agent market: link shares their owners listed, paged by `nextCursor`. */
- listMarketAgents: contactProcedure
- .input(
- z.object({
- cursor: z.object({ createdAt: z.iso.datetime(), id: z.uuid() }).optional(),
- limit: z.number().int().min(1).max(50).default(20),
- query: z.string().trim().max(100).optional(),
- }),
- )
- .query(async ({ ctx, input }) => ctx.contactModel.listMarketAgents(input)),
-
- // Changing a workspace's address book takes a member; a viewer only reads it.
- addAgent: contactProcedure
- .use(requireWorkspaceRoleWhenScoped('member'))
- .input(z.object({ share: handle }))
- .mutation(async ({ ctx, input }) => ctx.contactModel.addAgent(input.share)),
-
- /** Add an Agent from its card message; the owner's card admits the caller to a `card` share. */
- addAgentFromCard: contactProcedure
- .use(requireWorkspaceRoleWhenScoped('member'))
- .input(z.object({ messageId: z.uuid() }))
- .mutation(async ({ ctx, input }) => ctx.contactModel.addAgentFromCard(input.messageId)),
-
- removeAgent: contactProcedure
- .use(requireWorkspaceRoleWhenScoped('member'))
- .input(z.object({ agentId: z.string().min(1).max(64) }))
- .mutation(async ({ ctx, input }) => {
- await ctx.contactModel.removeAgent(input.agentId);
- return { success: true };
- }),
-});
diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.ts
index 0f86569fd2d..63f23cfbbc1 100644
--- a/apps/server/src/routers/lambda/index.ts
+++ b/apps/server/src/routers/lambda/index.ts
@@ -3,6 +3,7 @@
*/
import { accountDeletionRouter } from '@/business/server/lambda-routers/accountDeletion';
import { artifactShareRouter } from '@/business/server/lambda-routers/artifactShare';
+import { contactRouter } from '@/business/server/lambda-routers/contact';
import { fileShareRouter } from '@/business/server/lambda-routers/fileShare';
import { pageShareRouter } from '@/business/server/lambda-routers/pageShare';
import { referralRouter } from '@/business/server/lambda-routers/referral';
@@ -60,7 +61,6 @@ import { comfyuiRouter } from './comfyui';
import { composioRouter } from './composio';
import { configRouter } from './config';
import { connectorRouter } from './connector';
-import { contactRouter } from './contact';
import { dashboardRouter } from './dashboard';
import { deviceRouter } from './device';
import { deviceMetricRouter } from './deviceMetric';
diff --git a/apps/server/src/services/aiAgent/shareGate/deviceAccess.test.ts b/apps/server/src/services/aiAgent/shareGate/deviceAccess.test.ts
index 31335a05b1f..03d46e65407 100644
--- a/apps/server/src/services/aiAgent/shareGate/deviceAccess.test.ts
+++ b/apps/server/src/services/aiAgent/shareGate/deviceAccess.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { ContactModel } from '@/database/models/contact';
+import { getAddressBook } from '@/business/server/contact/addressBook';
import type { LobeChatDatabase } from '@/database/type';
import { resolveShareVisitorDeviceAccess, type ShareDeviceAccessSubject } from './deviceAccess';
@@ -10,10 +10,9 @@ const { filterAddressBookPeople, isChannelEnabled } = vi.hoisted(() => ({
isChannelEnabled: vi.fn(),
}));
vi.mock('@/server/services/channel/featureGate', () => ({ isChannelEnabled }));
-vi.mock('@/database/models/contact', () => ({
- ContactModel: vi.fn(function () {
- return { filterAddressBookPeople };
- }),
+vi.mock('@/business/server/contact/addressBook', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ getAddressBook: vi.fn(() => ({ filterAddressBookPeople })),
}));
const db = {} as LobeChatDatabase;
@@ -27,7 +26,7 @@ describe('resolveShareVisitorDeviceAccess', () => {
beforeEach(() => {
filterAddressBookPeople.mockReset();
isChannelEnabled.mockReset().mockResolvedValue(true);
- vi.mocked(ContactModel).mockClear();
+ vi.mocked(getAddressBook).mockClear();
});
it('denies by default, under `none`, and for a stored legacy `all`', async () => {
@@ -58,7 +57,7 @@ describe('resolveShareVisitorDeviceAccess', () => {
true,
);
// The book is the share owner's scope, not the visitor's.
- expect(ContactModel).toHaveBeenCalledWith(db, 'owner', 'ws-1');
+ expect(getAddressBook).toHaveBeenCalledWith(db, 'owner', 'ws-1');
expect(filterAddressBookPeople).toHaveBeenCalledWith(['visitor-1']);
// Removed from contacts (or left the workspace) after being listed.
@@ -73,7 +72,7 @@ describe('resolveShareVisitorDeviceAccess', () => {
expect(await resolveShareVisitorDeviceAccess(db, share(config, 'ws-1'), 'visitor-1')).toBe(
true,
);
- expect(ContactModel).toHaveBeenCalledWith(db, 'owner', 'ws-1');
+ expect(getAddressBook).toHaveBeenCalledWith(db, 'owner', 'ws-1');
expect(filterAddressBookPeople).toHaveBeenCalledWith(['visitor-1']);
// A stranger, or someone removed from contacts, gets nothing.
diff --git a/apps/server/src/services/aiAgent/shareGate/deviceAccess.ts b/apps/server/src/services/aiAgent/shareGate/deviceAccess.ts
index e9547a3efd4..69728809b93 100644
--- a/apps/server/src/services/aiAgent/shareGate/deviceAccess.ts
+++ b/apps/server/src/services/aiAgent/shareGate/deviceAccess.ts
@@ -1,6 +1,6 @@
import debug from 'debug';
-import { ContactModel } from '@/database/models/contact';
+import { getAddressBook } from '@/business/server/contact/addressBook';
import type { AgentShareConfig } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
import { isChannelEnabled } from '@/server/services/channel/featureGate';
@@ -43,7 +43,7 @@ export interface ShareDeviceAccessSubject {
*
* `contacts` grants every visitor currently in the address book of the
* Agent's scope. `allowlist` grants a listed visitor only while they are still
- * in that address book (`ContactModel.filterAddressBookPeople`):
+ * in that address book (`AddressBook.filterAddressBookPeople`):
* the owner's personal contacts, or the workspace's members and external
* contacts. The list was checked against the same book when written; checking
* again here makes removing a contact, or leaving the workspace, revoke the
@@ -69,7 +69,7 @@ export const resolveShareVisitorDeviceAccess = async (
return false;
}
- const [inBook] = await new ContactModel(
+ const [inBook] = await getAddressBook(
db,
share.ownerId,
share.workspaceId,
diff --git a/apps/server/src/services/channel/ChannelMessagingService.test.ts b/apps/server/src/services/channel/ChannelMessagingService.test.ts
index 243c3307c0d..308b2b90680 100644
--- a/apps/server/src/services/channel/ChannelMessagingService.test.ts
+++ b/apps/server/src/services/channel/ChannelMessagingService.test.ts
@@ -24,11 +24,9 @@ vi.mock('@/database/repositories/channel', async (original) => ({
openAgentPair = openAgentPair;
},
}));
-vi.mock('@/database/models/contact', () => ({
- ContactModel: class {
- findUser = findUser;
- listPeople = listPeople;
- },
+vi.mock('@/business/server/contact/addressBook', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ getAddressBook: () => ({ findUser, listPeople }),
}));
vi.mock('@/database/models/workspace', () => ({
WorkspaceModel: class {
diff --git a/apps/server/src/services/channel/ChannelMessagingService.ts b/apps/server/src/services/channel/ChannelMessagingService.ts
index 49febeb6e01..4fbbb1b6669 100644
--- a/apps/server/src/services/channel/ChannelMessagingService.ts
+++ b/apps/server/src/services/channel/ChannelMessagingService.ts
@@ -14,7 +14,7 @@ import type {
import { CHANNEL_LIMITS } from '@lobechat/types';
import { and, eq } from 'drizzle-orm';
-import { ContactModel } from '@/database/models/contact';
+import { getAddressBook } from '@/business/server/contact/addressBook';
import { WorkspaceModel } from '@/database/models/workspace';
import {
ChannelError,
@@ -27,6 +27,7 @@ import type { LobeChatDatabase } from '@/database/type';
import { appEnv } from '@/envs/app';
import { ChannelService } from './ChannelService';
+import { channelContacts } from './contacts';
import { assertChannelEnabled } from './featureGate';
const DEFAULT_LIMIT = 10;
@@ -107,7 +108,7 @@ export class ChannelMessagingService {
private readonly options: { allowBotRun?: boolean } = {},
) {
this.history = new ChannelHistoryRepository(db, userId, workspaceId);
- this.channels = new ChannelRepository(db, userId, workspaceId);
+ this.channels = new ChannelRepository(db, userId, workspaceId, channelContacts);
}
listChannels = async (params: ChannelListChannelsParams = {}): Promise<ChannelDirectoryPage> => {
@@ -252,7 +253,7 @@ export class ChannelMessagingService {
const limit = params.limit ?? DEFAULT_LIMIT;
if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_LIMIT)
throw new ChannelError('BAD_REQUEST', `Expected a limit between 1 and ${MAX_LIMIT}`);
- const page = await new ContactModel(this.db, this.userId, this.workspaceId).listPeople({
+ const page = await getAddressBook(this.db, this.userId, this.workspaceId).listPeople({
limit,
query: params.query,
});
@@ -311,7 +312,7 @@ export class ChannelMessagingService {
},
requestKey: `agent-dm:${this.operationId}:${requestId}`,
});
- const person = await new ContactModel(this.db, this.userId, this.workspaceId).findUser(userId);
+ const person = await getAddressBook(this.db, this.userId, this.workspaceId).findUser(userId);
return {
channelId: access.channel.id,
diff --git a/apps/server/src/services/channel/ChannelService.direct.test.ts b/apps/server/src/services/channel/ChannelService.direct.test.ts
index e8e2c112ec5..9a754afd7b9 100644
--- a/apps/server/src/services/channel/ChannelService.direct.test.ts
+++ b/apps/server/src/services/channel/ChannelService.direct.test.ts
@@ -48,13 +48,11 @@ vi.mock('@/database/repositories/channel/projectMainChannel', () => ({
findProjectMainChannelId,
}));
vi.mock('@/database/models/project', () => ({ ProjectModel: class {} }));
-vi.mock('@/database/models/contact', async (original) => ({
+vi.mock('@/business/server/contact/addressBook', async (original) => ({
...(await original<object>()),
- ContactModel: class {
- constructor(_db: unknown, userId: string, workspaceId?: string) {
- contactScope(userId, workspaceId);
- }
- findAgentAccess = findSharedAgent;
+ getAddressBook: (_db: unknown, userId: string, workspaceId?: string) => {
+ contactScope(userId, workspaceId);
+ return { findAgentAccess: findSharedAgent };
},
}));
vi.mock('@/database/models/agentShare', () => ({
diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.ts
index e6949d3ddd2..d0125d2a8b8 100644
--- a/apps/server/src/services/channel/ChannelService.ts
+++ b/apps/server/src/services/channel/ChannelService.ts
@@ -12,8 +12,8 @@ import {
import { eq } from 'drizzle-orm';
import pMap from 'p-map';
+import { getAddressBook } from '@/business/server/contact/addressBook';
import { AgentShareModel } from '@/database/models/agentShare';
-import { ContactModel, parseContactHandle } from '@/database/models/contact';
import { DeviceModel } from '@/database/models/device';
import { MessageModel } from '@/database/models/message';
import type { ProjectModelOptions } from '@/database/models/project';
@@ -37,11 +37,13 @@ import { deviceGateway } from '@/server/services/deviceGateway';
import { FileService } from '@/server/services/file';
import { ChannelCoordinator } from './ChannelCoordinator';
+import { channelContacts } from './contacts';
import { notifyChannelDirectMessages } from './directMessage';
import { notifyChannelMentions } from './mention';
import { notifyChannel } from './notify';
import { wakeChannel } from './queue';
import { resolveChannelRoutingConfig } from './routingConfig';
+import { parseShareHandle } from './shareHandle';
/** Environment selection is a request, never trusted device ownership or canonical-path data. */
export interface ChannelAgentSelection {
@@ -75,7 +77,7 @@ export class ChannelService {
/** The caller's project rights, for seating a new Agent in a project Channel's project. */
private readonly projectOptions: ProjectModelOptions = {},
) {
- this.repository = new ChannelRepository(db, userId, workspaceId);
+ this.repository = new ChannelRepository(db, userId, workspaceId, channelContacts);
this.agentService = new AgentService(db, userId, workspaceId);
this.deviceModel = new DeviceModel(db, userId, workspaceId);
this.projectModel = new ProjectModel(db, userId, workspaceId, projectOptions);
@@ -271,7 +273,7 @@ export class ChannelService {
* in the scope the Agent was added in, run in the cloud as the owner.
*/
private createSharedDirect = async (agentId: string) => {
- const shared = await new ContactModel(this.db, this.userId, this.workspaceId).findAgentAccess(
+ const shared = await getAddressBook(this.db, this.userId, this.workspaceId).findAgentAccess(
agentId,
);
if (!shared) return;
@@ -289,7 +291,7 @@ export class ChannelService {
* signed in. Adding it to contacts stays optional. One's own Agent opens as usual.
*/
openShared = async (share: string) => {
- const key = parseContactHandle(share);
+ const key = parseShareHandle(share);
const found = key ? await AgentShareModel.findBySlugOrId(this.db, key) : null;
if (!found || found.visibility !== 'link')
throw new ChannelError('NOT_FOUND', 'Agent not found');
diff --git a/apps/server/src/services/channel/README.md b/apps/server/src/services/channel/README.md
index 8feaed766e1..185a4cfbb50 100644
--- a/apps/server/src/services/channel/README.md
+++ b/apps/server/src/services/channel/README.md
@@ -269,8 +269,7 @@ chosen Agents (`ChannelMessagingService`).
"Let Alice know when you are done" is a message to a person, not a request for an Agent.
`lobe-channel.listPeople` (`lh channel people`) lists who the requester can talk to one-on-one in
-the run's scope (`ContactModel.listPeople`): personal contacts, or in a workspace its other members
-and the external contacts paired with the requester. `lobe-channel.messagePerson` (`lh channel dm`)
+the run's scope (`AddressBook.listPeople`, a business slot that lists nobody by default). `lobe-channel.messagePerson` (`lh channel dm`)
posts into the requester's conversation with that person (`ChannelService.openPeer`, opened on
first use) through `ChannelService.send` (`ChannelMessagingService.messagePerson`).
diff --git a/apps/server/src/services/channel/contacts.ts b/apps/server/src/services/channel/contacts.ts
new file mode 100644
index 00000000000..e23552e1a55
--- /dev/null
+++ b/apps/server/src/services/channel/contacts.ts
@@ -0,0 +1,16 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+
+import {
+ areMutualContacts,
+ getAddressBook,
+ mutualPersonalContactWhere,
+} from '@/business/server/contact/addressBook';
+import type { ChannelContacts } from '@/database/repositories/channel';
+
+/** The address book answering Channel's contact checks, inside the transaction that runs them. */
+export const channelContacts: ChannelContacts = {
+ areMutualContacts,
+ mutualPersonalContactWhere,
+ resolveCard: (tx, userId, workspaceId, input) =>
+ getAddressBook(tx as unknown as LobeChatDatabase, userId, workspaceId).resolveCard(input),
+};
diff --git a/apps/server/src/services/channel/shareHandle.test.ts b/apps/server/src/services/channel/shareHandle.test.ts
new file mode 100644
index 00000000000..0930709e978
--- /dev/null
+++ b/apps/server/src/services/channel/shareHandle.test.ts
@@ -0,0 +1,12 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseShareHandle } from './shareHandle';
+
+describe('parseShareHandle', () => {
+ it('accepts handles, @handles and share links', () => {
+ expect(parseShareHandle('bob')).toBe('bob');
+ expect(parseShareHandle(' @bob ')).toBe('bob');
+ expect(parseShareHandle('https://app.lobehub.com/a/bob-helper/chat?x=1')).toBe('bob-helper');
+ expect(parseShareHandle(' ')).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/channel/shareHandle.ts b/apps/server/src/services/channel/shareHandle.ts
new file mode 100644
index 00000000000..63e1fb28de3
--- /dev/null
+++ b/apps/server/src/services/channel/shareHandle.ts
@@ -0,0 +1,8 @@
+/** Share handles are stored lowercase; accept `@handle`, `/a/handle` and full share URLs. */
+export const parseShareHandle = (query: string): string | undefined => {
+ const trimmed = query.trim();
+ if (!trimmed) return undefined;
+ const fromPath = trimmed.match(/\/a\/([^/?#\s]+)/);
+ const handle = (fromPath ? decodeURIComponent(fromPath[1]) : trimmed).replace(/^@/, '');
+ return handle || undefined;
+};
diff --git a/apps/server/src/services/contact/__tests__/conversation.test.ts b/apps/server/src/services/contact/__tests__/conversation.test.ts
deleted file mode 100644
index 170efc1a919..00000000000
--- a/apps/server/src/services/contact/__tests__/conversation.test.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-// @vitest-environment node
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-const { ChannelService, openPeer } = vi.hoisted(() => {
- const openPeer = vi.fn();
- return {
- ChannelService: vi.fn(function () {
- return { openPeer };
- }),
- openPeer,
- };
-});
-
-vi.mock('@/server/services/channel/ChannelService', () => ({ ChannelService }));
-
-const { openContactConversation } = await import('../conversation');
-
-const db = {} as any;
-
-describe('openContactConversation', () => {
- beforeEach(() => vi.clearAllMocks());
-
- it('opens it as the requester in the request scope', async () => {
- await openContactConversation({ addresseeId: 'b', db, requesterId: 'a', workspaceId: 'ws' });
- expect(ChannelService).toHaveBeenCalledWith(db, 'a', 'ws');
- expect(openPeer).toHaveBeenCalledWith('b');
- });
-
- it('opens it in the personal space without a workspace', async () => {
- await openContactConversation({ addresseeId: 'b', db, requesterId: 'a', workspaceId: null });
- expect(ChannelService).toHaveBeenCalledWith(db, 'a', undefined);
- });
-
- it('never fails the acceptance', async () => {
- const error = vi.spyOn(console, 'error').mockImplementation(() => {});
- openPeer.mockRejectedValue(new Error('You are not contacts'));
- await expect(
- openContactConversation({ addresseeId: 'b', db, requesterId: 'a', workspaceId: null }),
- ).resolves.toBeUndefined();
- expect(error).toHaveBeenCalled();
- });
-});
diff --git a/apps/server/src/services/contact/conversation.ts b/apps/server/src/services/contact/conversation.ts
deleted file mode 100644
index 0b306e72e79..00000000000
--- a/apps/server/src/services/contact/conversation.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import type { LobeChatDatabase } from '@lobechat/database';
-
-import { ChannelService } from '@/server/services/channel/ChannelService';
-
-export interface OpenContactConversationParams {
- /** Who was asked; the other side of the conversation. */
- addresseeId: string;
- db: LobeChatDatabase;
- /** Who sent the request; always allowed to open it in the request's scope. */
- requesterId: string;
- /** The request's scope: `null` is the personal space. */
- workspaceId: string | null;
-}
-
-/**
- * Open the one-on-one conversation of two people who just became contacts, so it lands in both
- * lists without either of them having to start it. Opening is idempotent, and it never fails the
- * acceptance: either person can still open it later from the contact.
- */
-export const openContactConversation = async ({
- addresseeId,
- db,
- requesterId,
- workspaceId,
-}: OpenContactConversationParams) => {
- try {
- await new ChannelService(db, requesterId, workspaceId ?? undefined).openPeer(addresseeId);
- } catch (error) {
- console.error('[contact] Failed to open the conversation of new contacts', {
- addresseeId,
- error,
- requesterId,
- workspaceId,
- });
- }
-};
diff --git a/apps/server/src/services/contact/notify.ts b/apps/server/src/services/contact/notify.ts
deleted file mode 100644
index 4d5245713f4..00000000000
--- a/apps/server/src/services/contact/notify.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import type { NotifyContactRequestParams } from '@/business/server/contact/notifyActivity';
-import { notifyContactRequest } from '@/business/server/contact/notifyActivity';
-import { notifyUsers } from '@/server/services/user/notify';
-import { after } from '@/server/utils/scheduleAfterResponse';
-
-/**
- * Tell the other person about a contact request: a new one, or theirs that was accepted. Runs
- * after the response and never fails the request; repeating a request returns the same id, so
- * its notification dedupes. The business slot is a no-op outside Cloud.
- */
-export const notifyContactRequestAfterResponse = (params: NotifyContactRequestParams) => {
- after(async () => {
- try {
- await notifyContactRequest(params);
- } catch (error) {
- console.error('[contact] Failed to send contact request notification', {
- error,
- kind: params.kind,
- requestId: params.requestId,
- });
- }
- });
-};
-
-/**
- * Refresh the address book of everyone a contact change touched, on every device they have
- * open: the badge for a new request, a request that was answered or withdrawn, a contact added
- * or removed. Include the actor, whose other devices are stale too. Runs after the response.
- */
-export const notifyContactsChangedAfterResponse = (userIds: string[]) => {
- after(() => notifyUsers('contacts', userIds));
-};
diff --git a/packages/business-server/src/lambda-routers/contact.ts b/packages/business-server/src/lambda-routers/contact.ts
new file mode 100644
index 00000000000..023710a6d1b
--- /dev/null
+++ b/packages/business-server/src/lambda-routers/contact.ts
@@ -0,0 +1,3 @@
+import { router } from '@/libs/trpc/lambda';
+
+export const contactRouter = router({});
diff --git a/packages/database/src/models/__tests__/contact.test.ts b/packages/database/src/models/__tests__/contact.test.ts
deleted file mode 100644
index 1c6b268a270..00000000000
--- a/packages/database/src/models/__tests__/contact.test.ts
+++ /dev/null
@@ -1,980 +0,0 @@
-// @vitest-environment node
-import { eq, sql } from 'drizzle-orm';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { getTestDB } from '../../core/getTestDB';
-import {
- agents,
- agentShareGrants,
- agentShares,
- channelMembers,
- channelMessages,
- channels,
- userContactRequests,
- userContacts,
- users,
- workspaceMembers,
- workspaces,
-} from '../../schemas';
-import type { LobeChatDatabase } from '../../type';
-import { AgentShareModel } from '../agentShare';
-import { ContactModel, parseContactHandle } from '../contact';
-
-const serverDB: LobeChatDatabase = await getTestDB();
-
-const alice = 'contact-test-alice';
-const bob = 'contact-test-bob';
-const carol = 'contact-test-carol';
-const bobAgent = 'agt_contact_bob';
-const aliceAgent = 'agt_contact_alice';
-
-const aliceModel = new ContactModel(serverDB, alice);
-const bobModel = new ContactModel(serverDB, bob);
-const carolModel = new ContactModel(serverDB, carol);
-const teamId = 'contact-test-team';
-const aliceInTeam = new ContactModel(serverDB, alice, teamId);
-const carolInTeam = new ContactModel(serverDB, carol, teamId);
-// A model resolves the caller's role in the scope once, like one request; Bob's changes as he
-// joins, so each use gets a fresh one.
-const bobInTeam = () => new ContactModel(serverDB, bob, teamId);
-
-let bobShareId: string;
-
-beforeEach(async () => {
- await serverDB.delete(users);
- await serverDB.insert(users).values([
- { fullName: 'Alice', id: alice, username: 'alice' },
- { fullName: 'Bob', id: bob, username: 'Bob' },
- { id: carol, username: 'carol' },
- ]);
- await serverDB
- .insert(workspaces)
- .values({ id: teamId, name: 'Team', primaryOwnerId: alice, slug: teamId });
- // Alice owns the team and Carol is a member; Bob stays outside it.
- await serverDB.insert(workspaceMembers).values([
- { role: 'owner', userId: alice, workspaceId: teamId },
- { role: 'member', userId: carol, workspaceId: teamId },
- ]);
- await serverDB.insert(agents).values([
- { id: bobAgent, title: 'Bob Helper', userId: bob },
- { id: aliceAgent, title: 'Alice Helper', userId: alice },
- ]);
- const [share] = await serverDB
- .insert(agentShares)
- .values({
- agentId: bobAgent,
- shareConfig: { monthlySpendLimit: 1, slug: 'bob-helper' },
- visibility: 'link',
- })
- .returning();
- bobShareId = share.id;
- await serverDB
- .insert(agentShares)
- .values({ agentId: aliceAgent, shareConfig: { monthlySpendLimit: 1 }, visibility: 'link' });
-});
-
-afterEach(async () => {
- vi.restoreAllMocks();
- await serverDB.delete(userContactRequests);
- await serverDB.delete(userContacts);
- await serverDB.delete(workspaces);
- await serverDB.delete(users);
-});
-
-describe('parseContactHandle', () => {
- it('accepts handles, @handles and share links', () => {
- expect(parseContactHandle('bob')).toBe('bob');
- expect(parseContactHandle(' @bob ')).toBe('bob');
- expect(parseContactHandle('https://app.lobehub.com/a/bob-helper/chat?x=1')).toBe('bob-helper');
- expect(parseContactHandle(' ')).toBeUndefined();
- });
-});
-
-describe('contact requests', () => {
- it('becomes mutual contacts once the addressee accepts', async () => {
- const sent = await aliceModel.sendRequest(bob, 'hi');
- expect(sent.status).toBe('pending');
- expect(await aliceModel.relationTo(bob)).toBe('request_sent');
- expect(await bobModel.relationTo(alice)).toBe('request_received');
-
- const [incoming] = await bobModel.listRequests();
- expect(incoming).toMatchObject({ direction: 'incoming', message: 'hi', user: { id: alice } });
-
- await bobModel.acceptRequest(sent.requestId);
-
- expect((await aliceModel.list()).map((c) => c.type === 'user' && c.user.id)).toEqual([bob]);
- expect((await bobModel.list()).map((c) => c.type === 'user' && c.user.id)).toEqual([alice]);
- expect(await bobModel.listRequests()).toEqual([]);
- });
-
- it('repeating a pending request returns it instead of adding another', async () => {
- const first = await aliceModel.sendRequest(bob);
- const second = await aliceModel.sendRequest(bob);
- expect(second).toEqual(first);
- });
-
- it('a crossing request accepts the pending one', async () => {
- const first = await aliceModel.sendRequest(bob);
- const crossing = await bobModel.sendRequest(alice);
- expect(crossing).toEqual({ requestId: first.requestId, status: 'accepted' });
- expect(await aliceModel.isContact(bob)).toBe(true);
- });
-
- it('only the addressee can accept or decline, only the requester can cancel', async () => {
- const { requestId } = await aliceModel.sendRequest(bob);
- await expect(aliceModel.acceptRequest(requestId)).rejects.toThrow('Request not found');
- await expect(carolModel.declineRequest(requestId)).rejects.toThrow('Request not found');
- await expect(bobModel.cancelRequest(requestId)).rejects.toThrow('Request not found');
-
- await expect(aliceModel.cancelRequest(requestId)).resolves.toEqual({ addresseeId: bob });
- expect(await bobModel.listRequests()).toEqual([]);
- // A new request may follow a cancelled one.
- expect((await aliceModel.sendRequest(bob)).status).toBe('pending');
- });
-
- /**
- * The requester withdraws after the addressee's answer read the request as pending but before
- * it wrote: the withdrawal wins and no contacts appear. Simulated by withdrawing right after
- * the read, inside the answering transaction.
- */
- const withdrawAfterRead = (model: ContactModel) => {
- const target = model as unknown as {
- incomingPending: (tx: LobeChatDatabase, id: string) => Promise<{ id: string }>;
- };
- const read = target.incomingPending.bind(model);
- vi.spyOn(target, 'incomingPending').mockImplementation(async (tx, id) => {
- const request = await read(tx, id);
- await tx
- .update(userContactRequests)
- .set({ status: 'cancelled' })
- .where(eq(userContactRequests.id, request.id));
- return request;
- });
- };
-
- it('does not accept a request withdrawn while it was being accepted', async () => {
- const { requestId } = await aliceModel.sendRequest(bob);
- withdrawAfterRead(bobModel);
-
- await expect(bobModel.acceptRequest(requestId)).rejects.toThrow('Request not found');
-
- expect(await aliceModel.isContact(bob)).toBe(false);
- expect(await bobModel.isContact(alice)).toBe(false);
- const [row] = await serverDB
- .select({ status: userContactRequests.status })
- .from(userContactRequests)
- .where(eq(userContactRequests.id, requestId));
- // The refused answer rolls back with its transaction; it never became accepted.
- expect(row.status).not.toBe('accepted');
- });
-
- it('does not decline a request withdrawn while it was being declined', async () => {
- const { requestId } = await aliceModel.sendRequest(bob);
- withdrawAfterRead(bobModel);
-
- await expect(bobModel.declineRequest(requestId)).rejects.toThrow('Request not found');
-
- const [row] = await serverDB
- .select({ status: userContactRequests.status })
- .from(userContactRequests)
- .where(eq(userContactRequests.id, requestId));
- expect(row.status).not.toBe('declined');
- });
-
- it('rejects requests to yourself and to existing contacts', async () => {
- await expect(aliceModel.sendRequest(alice)).rejects.toThrow('You cannot add yourself');
- const { requestId } = await aliceModel.sendRequest(bob);
- await bobModel.acceptRequest(requestId);
- await expect(aliceModel.sendRequest(bob)).rejects.toThrow('Already a contact');
- });
-
- it('removing a contact removes it on both sides', async () => {
- const { requestId } = await aliceModel.sendRequest(bob);
- await bobModel.acceptRequest(requestId);
- await bobModel.removeUser(alice);
- expect(await aliceModel.list()).toEqual([]);
- expect(await bobModel.list()).toEqual([]);
- });
-});
-
-describe('shared Agents', () => {
- it('adds another person’s Agent by its share handle and grants access', async () => {
- const profile = await aliceModel.addAgent('https://app.lobehub.com/a/bob-helper');
- expect(profile).toMatchObject({ agentId: bobAgent, owner: { id: bob }, shareId: bobShareId });
-
- const [contact] = await aliceModel.list();
- expect(contact).toMatchObject({ available: true, type: 'agent' });
- expect(await aliceModel.findAgentAccess(bobAgent)).toEqual({
- agentId: bobAgent,
- name: null,
- ownerId: bob,
- shareId: bobShareId,
- title: 'Bob Helper',
- workspaceId: null,
- });
- // Adding twice keeps one entry.
- await aliceModel.addAgent(bobShareId);
- expect(await aliceModel.list()).toHaveLength(1);
- });
-
- it('pausing the share keeps the contact but removes access', async () => {
- await aliceModel.addAgent('bob-helper');
- await serverDB.update(agentShares).set({ visibility: 'private' });
-
- const [contact] = await aliceModel.list();
- expect(contact).toMatchObject({ available: false, type: 'agent' });
- expect(await aliceModel.findAgentAccess(bobAgent)).toBeUndefined();
- await expect(carolModel.addAgent('bob-helper')).rejects.toThrow('Agent not found');
- });
-
- it('does not grant access without a contact entry or to your own Agent', async () => {
- expect(await carolModel.findAgentAccess(bobAgent)).toBeUndefined();
- await expect(bobModel.addAgent('bob-helper')).rejects.toThrow('This Agent is already yours');
- });
-
- it('reads only a person’s public profile fields', async () => {
- expect(await aliceModel.findUser(bob)).toEqual({
- avatar: null,
- fullName: 'Bob',
- id: bob,
- username: 'Bob',
- });
- expect(await aliceModel.findUser('missing')).toBeUndefined();
- });
-
- it('lists a person’s link-shared Agents to anyone, contact or not', async () => {
- expect((await carolModel.listSharedAgentsOf(bob)).map((a) => a.agentId)).toEqual([bobAgent]);
- await serverDB.update(agentShares).set({ visibility: 'private' });
- expect(await carolModel.listSharedAgentsOf(bob)).toEqual([]);
- });
-});
-
-describe('shared-Agent market', () => {
- const listIn = (shareConfig: Record<string, unknown>) => ({
- monthlySpendLimit: 1,
- ...shareConfig,
- });
-
- it('lists only link shares their owners listed, without the trashed', async () => {
- expect((await carolModel.listMarketAgents({ limit: 10 })).items).toEqual([]);
-
- await serverDB
- .update(agentShares)
- .set({ shareConfig: listIn({ listedInMarket: true, slug: 'bob-helper' }) })
- .where(eq(agentShares.agentId, bobAgent));
- const { items, nextCursor } = await carolModel.listMarketAgents({ limit: 10 });
- expect(items).toMatchObject([
- { agentId: bobAgent, owner: { id: bob }, slug: 'bob-helper', title: 'Bob Helper' },
- ]);
- expect(nextCursor).toBeNull();
-
- // A paused share or a trashed Agent leaves the market even while still marked listed.
- await serverDB
- .update(agentShares)
- .set({ visibility: 'card' })
- .where(eq(agentShares.agentId, bobAgent));
- expect((await carolModel.listMarketAgents({ limit: 10 })).items).toEqual([]);
- await serverDB
- .update(agentShares)
- .set({ visibility: 'link' })
- .where(eq(agentShares.agentId, bobAgent));
- await serverDB.update(agents).set({ isDeleted: true }).where(eq(agents.id, bobAgent));
- expect((await carolModel.listMarketAgents({ limit: 10 })).items).toEqual([]);
- });
-
- it('pages newest first without repeating a share, and filters by title', async () => {
- await serverDB.update(agentShares).set({ shareConfig: listIn({ listedInMarket: true }) });
- await serverDB
- .update(agentShares)
- .set({ createdAt: new Date('2026-01-01') })
- .where(eq(agentShares.agentId, bobAgent));
- await serverDB
- .update(agentShares)
- .set({ createdAt: new Date('2026-02-01') })
- .where(eq(agentShares.agentId, aliceAgent));
-
- const first = await carolModel.listMarketAgents({ limit: 1 });
- expect(first.items.map((a) => a.agentId)).toEqual([aliceAgent]);
- expect(first.nextCursor).not.toBeNull();
- const second = await carolModel.listMarketAgents({
- cursor: first.nextCursor!,
- limit: 1,
- });
- expect(second.items.map((a) => a.agentId)).toEqual([bobAgent]);
- expect(second.nextCursor).toBeNull();
-
- // Two shares inside one millisecond: the cursor keeps microseconds, so none is skipped.
- await serverDB
- .update(agentShares)
- .set({ createdAt: sql`'2026-03-01T00:00:00.123900Z'::timestamptz` })
- .where(eq(agentShares.agentId, aliceAgent));
- await serverDB
- .update(agentShares)
- .set({ createdAt: sql`'2026-03-01T00:00:00.123800Z'::timestamptz` })
- .where(eq(agentShares.agentId, bobAgent));
- const sameMs = await carolModel.listMarketAgents({ limit: 1 });
- expect(sameMs.nextCursor?.createdAt).toBe('2026-03-01T00:00:00.123900Z');
- const rest = await carolModel.listMarketAgents({ cursor: sameMs.nextCursor!, limit: 1 });
- expect(rest.items.map((a) => a.agentId)).toEqual([bobAgent]);
-
- const found = await carolModel.listMarketAgents({ limit: 10, query: 'bob' });
- expect(found.items.map((a) => a.agentId)).toEqual([bobAgent]);
- });
-});
-
-describe('shared Agents in a workspace', () => {
- it('belong to the workspace: every member sees and can message them', async () => {
- await aliceInTeam.addAgent('bob-helper');
- const [entry] = await serverDB.select().from(userContacts);
- expect(entry).toMatchObject({ agentId: bobAgent, userId: alice, workspaceId: teamId });
-
- for (const member of [aliceInTeam, carolInTeam]) {
- expect(await member.list()).toMatchObject([{ agent: { agentId: bobAgent } }]);
- expect(await member.findAgentAccess(bobAgent)).toMatchObject({ ownerId: bob });
- expect((await member.search('bob-helper'))[0]).toMatchObject({ relation: 'contact' });
- }
- // Neither personal address book holds it.
- expect(await aliceModel.list()).toEqual([]);
- expect(await carolModel.findAgentAccess(bobAgent)).toBeUndefined();
- expect((await aliceModel.search('bob-helper'))[0]).toMatchObject({ relation: 'none' });
- });
-
- it('lists people only in the personal space', async () => {
- await bobModel.sendRequest(alice);
- const [request] = await aliceModel.listRequests();
- await aliceModel.acceptRequest(request.id);
- expect(await aliceModel.list()).toMatchObject([{ type: 'user', user: { id: bob } }]);
- // A personal contact is not a colleague: the workspace lists its members instead.
- expect(await aliceInTeam.list()).toEqual([]);
- expect(await aliceInTeam.isContact(bob)).toBe(false);
- // Nor does it let Bob into the workspace.
- await expect(bobInTeam().list()).rejects.toThrow('Not a member of this workspace');
- });
-
- it('holds an Agent once per workspace, apart from personal entries', async () => {
- await aliceModel.addAgent('bob-helper');
- await aliceInTeam.addAgent('bob-helper');
- await carolInTeam.addAgent(bobShareId);
- expect(await serverDB.select().from(userContacts)).toHaveLength(2);
-
- // Any member removes it for the workspace; the personal entry stays.
- await carolInTeam.removeAgent(bobAgent);
- expect(await aliceInTeam.list()).toEqual([]);
- expect(await aliceModel.list()).toHaveLength(1);
- });
-});
-
-describe('external contacts of a workspace', () => {
- /** Alice invites Bob from the team and Bob accepts it from his personal space. */
- const inviteBob = async () => {
- const { requestId } = await aliceInTeam.sendRequest(bob, 'Join us');
- const [invitation] = await bobModel.listRequests();
- expect(invitation).toMatchObject({
- direction: 'incoming',
- id: requestId,
- user: { id: alice },
- workspace: { id: teamId, name: 'Team' },
- });
- expect(await bobModel.acceptRequest(requestId)).toEqual({
- contactUserId: alice,
- workspaceId: teamId,
- });
- };
-
- it('keeps the invitation in its own scope until it is answered', async () => {
- await aliceInTeam.sendRequest(bob);
- // The inviter sees it in the team, not in her personal space.
- expect(await aliceInTeam.listRequests()).toMatchObject([
- { direction: 'outgoing', user: { id: bob } },
- ]);
- expect(await aliceModel.listRequests()).toEqual([]);
- expect(await carolInTeam.listRequests()).toEqual([]);
- expect(await aliceInTeam.relationTo(bob)).toBe('request_sent');
- expect(await aliceModel.relationTo(bob)).toBe('none');
- // A personal request between the same two people is separate.
- expect(await aliceModel.sendRequest(bob)).toMatchObject({ status: 'pending' });
- });
-
- it('invites only people outside the workspace, and only as a member', async () => {
- await expect(aliceInTeam.sendRequest(carol)).rejects.toThrow('Already a member');
- expect(await aliceInTeam.relationTo(carol)).toBe('member');
- await inviteBob();
- await expect(bobInTeam().sendRequest(carol)).rejects.toThrow('Only members add contacts');
- });
-
- it('shows an external contact only the inviter, and nothing else of the workspace', async () => {
- await carolInTeam.addAgent('bob-helper');
- await inviteBob();
-
- expect(await bobInTeam().list()).toMatchObject([{ type: 'user', user: { id: alice } }]);
- expect(await bobInTeam().search('carol')).toEqual([]);
- expect(await bobInTeam().listRequests()).toEqual([]);
- expect(await bobInTeam().findAgentAccess(bobAgent)).toBeUndefined();
- // His personal address book is untouched.
- expect(await bobModel.list()).toEqual([]);
- });
-
- it('lists every external contact to every member, marking who is open to them', async () => {
- await inviteBob();
- const externals = (items: Awaited<ReturnType<ContactModel['list']>>) =>
- items.filter((item) => item.type === 'user');
-
- expect(externals(await aliceInTeam.list())).toMatchObject([
- { external: { openedToMe: true }, user: { id: bob } },
- ]);
- expect(externals(await carolInTeam.list())).toMatchObject([
- { external: { openedToMe: false }, user: { id: bob } },
- ]);
-
- // Carol opens herself; Bob now sees her too.
- await carolInTeam.openTo(bob);
- expect(externals(await carolInTeam.list())).toMatchObject([
- { external: { openedToMe: true }, user: { id: bob } },
- ]);
- expect((await bobInTeam().list()).map((item) => item.type === 'user' && item.user.id)).toEqual(
- expect.arrayContaining([alice, carol]),
- );
-
- // Closing again only removes her own pairing.
- await carolInTeam.removeUser(bob);
- expect(await bobInTeam().list()).toMatchObject([{ user: { id: alice } }]);
- });
-
- it('opens only to an external contact, never a stranger or a colleague', async () => {
- await expect(carolInTeam.openTo(bob)).rejects.toThrow('External contact not found');
- await expect(carolInTeam.openTo(alice)).rejects.toThrow('External contact not found');
- });
-
- it('lets an owner or admin remove an external contact from the workspace', async () => {
- await inviteBob();
- await carolInTeam.openTo(bob);
- await expect(carolInTeam.removeExternal(bob)).rejects.toThrow('Only owners and admins');
-
- await aliceInTeam.removeExternal(bob);
- expect(await carolInTeam.list()).toEqual([]);
- 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 serverDB
- .update(workspaceMembers)
- .set({ deletedAt: new Date() })
- .where(eq(workspaceMembers.userId, carol));
- await expect(bobModel.acceptRequest(requestId)).rejects.toThrow('Request not found');
- });
-});
-
-describe('people to message', () => {
- const ids = (page: Awaited<ReturnType<ContactModel['listPeople']>>) =>
- page.people.map((person) => person.id);
-
- it('lists personal contacts only, narrowed by name or handle', async () => {
- const { requestId } = await aliceModel.sendRequest(bob);
- await bobModel.acceptRequest(requestId);
-
- expect(await aliceModel.listPeople({ limit: 10 })).toEqual({
- hasMore: false,
- people: [{ avatar: null, fullName: 'Bob', id: bob, username: 'Bob' }],
- });
- expect(ids(await aliceModel.listPeople({ limit: 10, query: ' bo ' }))).toEqual([bob]);
- expect(ids(await aliceModel.listPeople({ limit: 10, query: '@bo' }))).toEqual([bob]);
- expect(ids(await aliceModel.listPeople({ limit: 10, query: 'carol' }))).toEqual([]);
- expect(ids(await carolModel.listPeople({ limit: 10 }))).toEqual([]);
- });
-
- it('lists fellow members, then the external contacts paired with the caller', async () => {
- const { requestId } = await aliceInTeam.sendRequest(bob);
- await bobModel.acceptRequest(requestId);
-
- expect(ids(await aliceInTeam.listPeople({ limit: 10 }))).toEqual([carol, bob]);
- // Bob is not paired with Carol, so she cannot message him.
- expect(ids(await carolInTeam.listPeople({ limit: 10 }))).toEqual([alice]);
- expect(ids(await aliceInTeam.listPeople({ limit: 10, query: '@CAR' }))).toEqual([carol]);
- expect(await aliceInTeam.listPeople({ limit: 1 })).toMatchObject({
- hasMore: true,
- people: [{ id: carol }],
- });
- // An external contact reaches only the members paired with them.
- expect(ids(await bobInTeam().listPeople({ limit: 10 }))).toEqual([alice]);
- });
-});
-
-describe('address book of a scope', () => {
- const dave = 'contact-test-dave';
- const ids = (people: { id: string }[]) => people.map((person) => person.id);
-
- it('holds personal contacts only, and only for their owner', async () => {
- const { requestId } = await aliceModel.sendRequest(bob);
- await bobModel.acceptRequest(requestId);
-
- expect(ids(await aliceModel.listAddressBookPeople())).toEqual([bob]);
- expect(await aliceModel.filterAddressBookPeople([bob, carol, alice])).toEqual([bob]);
- expect(await carolModel.filterAddressBookPeople([bob])).toEqual([]);
- });
-
- it('holds every member and every external contact of a workspace', async () => {
- await serverDB.insert(users).values({ id: dave, username: 'dave' });
- // Alice invites Bob; Carol, who did not invite him, still finds him in the workspace's book.
- const { requestId } = await aliceInTeam.sendRequest(bob);
- await bobModel.acceptRequest(requestId);
-
- expect(ids(await carolInTeam.listAddressBookPeople())).toEqual([alice, bob]);
- expect(await carolInTeam.filterAddressBookPeople([alice, bob, dave, carol])).toEqual([
- alice,
- bob,
- ]);
- // Personal contacts never count for a workspace.
- const { requestId: personal } = await carolModel.sendRequest(dave);
- await new ContactModel(serverDB, dave).acceptRequest(personal);
- expect(await carolInTeam.filterAddressBookPeople([dave])).toEqual([]);
- });
-
- it('drops someone who leaves the workspace or the address book', async () => {
- await serverDB
- .update(workspaceMembers)
- .set({ deletedAt: new Date() })
- .where(eq(workspaceMembers.userId, carol));
- expect(await aliceInTeam.filterAddressBookPeople([carol])).toEqual([]);
-
- const { requestId } = await aliceModel.sendRequest(bob);
- await bobModel.acceptRequest(requestId);
- await aliceModel.removeUser(bob);
- expect(await aliceModel.filterAddressBookPeople([bob])).toEqual([]);
- });
-});
-
-describe('search', () => {
- it('finds people by exact username, case-insensitively, with their relation', async () => {
- const [result] = await aliceModel.search('@BOB');
- expect(result).toMatchObject({ relation: 'none', type: 'user', user: { id: bob } });
- expect(await aliceModel.search('bo')).toEqual([]);
- const [self] = await aliceModel.search('alice');
- expect(self).toMatchObject({ relation: 'self' });
- });
-
- it('finds Agents by share handle and link', async () => {
- const [result] = await aliceModel.search('https://app.lobehub.com/a/bob-helper');
- expect(result).toMatchObject({ agent: { agentId: bobAgent }, relation: 'none', type: 'agent' });
- await aliceModel.addAgent('bob-helper');
- const [added] = await aliceModel.search('bob-helper');
- expect(added).toMatchObject({ relation: 'contact' });
- });
-});
-
-describe('contact edge cases', () => {
- it('treats a bare @ as no handle at all', () => {
- expect(parseContactHandle('@')).toBeUndefined();
- });
-
- it('reports a person already in the address book as a contact', async () => {
- const { requestId } = await aliceModel.sendRequest(bob);
- await bobModel.acceptRequest(requestId);
-
- expect(await aliceModel.relationTo(bob)).toBe('contact');
- });
-
- it('lists a request in both directions', async () => {
- await aliceModel.sendRequest(bob);
-
- const [outgoing] = await aliceModel.listRequests();
- expect(outgoing).toMatchObject({ direction: 'outgoing', user: { id: bob } });
-
- const [incoming] = await bobModel.listRequests();
- expect(incoming).toMatchObject({ direction: 'incoming', user: { id: alice } });
- });
-
- it('declines a pending request without creating a contact', async () => {
- const { requestId } = await aliceModel.sendRequest(bob);
-
- await expect(bobModel.declineRequest(requestId)).resolves.toEqual({ requesterId: alice });
-
- expect(await aliceModel.list()).toEqual([]);
- expect(await aliceModel.relationTo(bob)).toBe('none');
- const [row] = await serverDB
- .select({ status: userContactRequests.status })
- .from(userContactRequests)
- .where(eq(userContactRequests.id, requestId));
- expect(row.status).toBe('declined');
- });
-
- it('rejects a request to somebody who does not exist', async () => {
- await expect(aliceModel.sendRequest('contact-test-missing')).rejects.toThrow('User not found');
- });
-
- it('rejects a request id that is not a uuid', async () => {
- await expect(aliceModel.cancelRequest('not-a-uuid')).rejects.toThrow('Request not found');
- await expect(bobModel.acceptRequest('not-a-uuid')).rejects.toThrow('Request not found');
- await expect(bobModel.declineRequest('not-a-uuid')).rejects.toThrow('Request not found');
- });
-
- it('refuses to add an Agent when the handle names nothing', async () => {
- await expect(aliceModel.addAgent('@')).rejects.toThrow('Agent not found');
- expect(await aliceModel.search('@')).toEqual([]);
- });
-
- it('removes a shared Agent from the address book', async () => {
- await aliceModel.addAgent('bob-helper');
-
- await aliceModel.removeAgent(bobAgent);
-
- expect(await aliceModel.list()).toEqual([]);
- expect(await aliceModel.findAgentAccess(bobAgent)).toBeUndefined();
- });
-
- it('reports an Agent that has no title as having none', async () => {
- await serverDB.insert(agents).values({ id: 'agt_contact_untitled', userId: bob });
- await serverDB.insert(agentShares).values({
- agentId: 'agt_contact_untitled',
- shareConfig: { monthlySpendLimit: 1, slug: 'untitled-helper' },
- visibility: 'link',
- });
-
- const [found] = await aliceModel.search('untitled-helper');
-
- expect(found.type).toBe('agent');
- expect(found.agent?.title).toBeNull();
- });
-
- it('marks your own Agent share as your own', async () => {
- await serverDB
- .update(agentShares)
- .set({ shareConfig: { monthlySpendLimit: 1, slug: 'alice-helper' } })
- .where(eq(agentShares.agentId, aliceAgent));
-
- const [own] = await aliceModel.search('alice-helper');
-
- expect(own).toMatchObject({ agent: { agentId: aliceAgent }, relation: 'self', type: 'agent' });
- });
-});
-
-describe('answering an invitation after the caller joined', () => {
- it('refuses the invitation once the invitee is already a member', async () => {
- const { requestId } = await aliceInTeam.sendRequest(bob, 'Join us');
- // Bob became a member by another route before answering, so the invitation is moot.
- await serverDB
- .insert(workspaceMembers)
- .values({ role: 'member', userId: bob, workspaceId: teamId });
-
- await expect(bobInTeam().acceptRequest(requestId)).rejects.toThrow(
- 'Already a member of this workspace',
- );
- });
-
- it('only a member of the workspace may open themselves to an external contact', async () => {
- // In the personal space there is nothing to open: the caller is not a member of a team.
- await expect(aliceModel.openTo(bob)).rejects.toThrow('Only members open themselves');
- });
-
- it('refuses an invitation whose sender is no longer a member', async () => {
- const { requestId } = await aliceInTeam.sendRequest(bob, 'Join us');
- await serverDB.delete(workspaceMembers).where(eq(workspaceMembers.userId, alice));
-
- await expect(bobModel.acceptRequest(requestId)).rejects.toThrow('Request not found');
- });
-});
-
-describe('removing an external contact who is not one', () => {
- it('refuses a member, and a person the workspace never paired', async () => {
- // Carol is a member of the team, not an external contact.
- await expect(aliceInTeam.removeExternal(carol)).rejects.toThrow('External contact not found');
- await expect(aliceInTeam.removeExternal('contact-test-missing')).rejects.toThrow(
- 'External contact not found',
- );
- });
-});
-
-describe('contact cards', () => {
- const befriend = async (a: ContactModel, b: ContactModel, addressee: string) =>
- b.acceptRequest((await a.sendRequest(addressee)).requestId);
-
- it('shares oneself, a contact or a fellow member, with a server snapshot', async () => {
- await befriend(aliceModel, bobModel, bob);
- expect(await aliceModel.resolveCard({ type: 'user', userId: bob })).toEqual({
- avatar: null,
- name: 'Bob',
- type: 'user',
- userId: bob,
- username: 'Bob',
- });
- expect(await aliceModel.resolveCard({ type: 'user', userId: alice })).toMatchObject({
- name: 'Alice',
- });
- expect(await aliceInTeam.resolveCard({ type: 'user', userId: carol })).toMatchObject({
- name: 'carol',
- });
- });
-
- it('refuses a stranger', async () => {
- await expect(aliceModel.resolveCard({ type: 'user', userId: carol })).rejects.toThrow(
- 'Share only your contacts',
- );
- });
-
- it("shares an Agent whose link share is on, anyone's", async () => {
- expect(await aliceModel.resolveCard({ agentId: bobAgent, type: 'agent' })).toEqual({
- agentId: bobAgent,
- avatar: null,
- backgroundColor: null,
- name: 'Bob Helper',
- ownerName: 'Bob',
- shareId: bobShareId,
- type: 'agent',
- });
- });
-
- it('names an Agent by its personal name, as every list does, over its role title', async () => {
- await serverDB.update(agents).set({ name: 'ζ™šθ―Ί' }).where(eq(agents.id, bobAgent));
-
- expect(await aliceModel.resolveCard({ agentId: bobAgent, type: 'agent' })).toMatchObject({
- name: 'ζ™šθ―Ί',
- });
- });
-
- it('asks the owner to turn sharing on instead of opening it', async () => {
- await serverDB
- .update(agentShares)
- .set({ visibility: 'private' })
- .where(eq(agentShares.agentId, aliceAgent));
- await expect(aliceModel.resolveCard({ agentId: aliceAgent, type: 'agent' })).rejects.toThrow(
- 'Turn on sharing first',
- );
- await expect(bobModel.resolveCard({ agentId: aliceAgent, type: 'agent' })).rejects.toThrow(
- 'Agent not found',
- );
- });
-});
-
-describe('an Agent shared only by card', () => {
- let channelId: string;
- const card = { agentId: bobAgent, type: 'agent' as const };
-
- /** A card of Bob's Agent in the Channel, sent by `sender`. */
- const postCard = async (sender: string, sequence = 1) => {
- const [message] = await serverDB
- .insert(channelMessages)
- .values({
- channelId,
- content: '[Contact card] Bob Helper',
- metadata: { card: { ...(await bobModel.resolveCard(card)), name: 'Bob Helper' } },
- requestKey: `card-${sequence}`,
- routingStatus: 'skipped',
- sequence,
- userId: sender,
- })
- .returning();
- return message.id;
- };
-
- beforeEach(async () => {
- await serverDB
- .update(agentShares)
- .set({ visibility: 'card' })
- .where(eq(agentShares.agentId, bobAgent));
- const [channel] = await serverDB
- .insert(channels)
- .values({ title: 'Card', userId: bob })
- .returning();
- channelId = channel.id;
- await serverDB.insert(channelMembers).values([
- { actorType: 'user', channelId, role: 'owner', userId: bob },
- { actorType: 'user', channelId, role: 'member', userId: alice },
- ]);
- });
-
- afterEach(async () => {
- await serverDB.delete(channels);
- });
-
- it('is shared by its owner only, and its link adds nothing', async () => {
- expect(await bobModel.resolveCard(card)).toMatchObject({ shareId: bobShareId });
- await expect(aliceModel.resolveCard(card)).rejects.toThrow('Agent not found');
- await expect(aliceModel.addAgent(bobShareId)).rejects.toThrow('Agent not found');
- });
-
- it("admits the person who adds it from the owner's card, and only them", async () => {
- const messageId = await postCard(bob);
- expect(await aliceModel.findAgentAccess(bobAgent)).toBeUndefined();
-
- expect(await aliceModel.addAgentFromCard(messageId)).toMatchObject({ agentId: bobAgent });
-
- expect(await aliceModel.findAgentAccess(bobAgent)).toMatchObject({ shareId: bobShareId });
- const [grant] = await serverDB.select().from(agentShareGrants);
- expect(grant).toMatchObject({
- shareId: bobShareId,
- source: { channelId, messageId, type: 'card' },
- userId: alice,
- });
- const item = (await aliceModel.list()).find((entry) => entry.type === 'agent');
- expect(item).toMatchObject({ available: true });
- expect(
- await AgentShareModel.isRunStillAuthorized(serverDB, {
- agentId: bobAgent,
- shareId: bobShareId,
- visitorUserId: alice,
- }),
- ).toBe(true);
- // Neither a run that names nobody nor another person is admitted by Alice's grant.
- for (const visitorUserId of [undefined, carol])
- expect(
- await AgentShareModel.isRunStillAuthorized(serverDB, {
- agentId: bobAgent,
- shareId: bobShareId,
- visitorUserId,
- }),
- ).toBe(false);
- });
-
- it('pauses with the share, and stays admitted when a link share becomes card-only', async () => {
- await aliceModel.addAgentFromCard(await postCard(bob));
- await serverDB
- .update(agentShares)
- .set({ visibility: 'private' })
- .where(eq(agentShares.agentId, bobAgent));
- expect(await aliceModel.findAgentAccess(bobAgent)).toBeUndefined();
-
- await serverDB
- .update(agentShares)
- .set({ visibility: 'card' })
- .where(eq(agentShares.agentId, bobAgent));
- expect(await aliceModel.findAgentAccess(bobAgent)).toMatchObject({ shareId: bobShareId });
- });
-
- it('refuses a card someone else passed on, or one I cannot see', async () => {
- await serverDB
- .insert(channelMembers)
- .values({ actorType: 'user', channelId, role: 'member', userId: carol });
- const passedOn = await postCard(alice, 1);
- await expect(carolModel.addAgentFromCard(passedOn)).rejects.toThrow('Agent not found');
-
- const fromOwner = await postCard(bob, 2);
- await serverDB
- .update(channelMembers)
- .set({ status: 'left' })
- .where(eq(channelMembers.userId, carol));
- await expect(carolModel.addAgentFromCard(fromOwner)).rejects.toThrow('Agent not found');
- expect(await serverDB.select().from(agentShareGrants)).toEqual([]);
- });
-
- it('adds a link share from anyone’s card without granting it', async () => {
- await serverDB
- .update(agentShares)
- .set({ visibility: 'link' })
- .where(eq(agentShares.agentId, bobAgent));
- await serverDB
- .insert(channelMembers)
- .values({ actorType: 'user', channelId, role: 'member', userId: carol });
-
- await carolModel.addAgentFromCard(await postCard(alice));
-
- expect(await carolModel.findAgentAccess(bobAgent)).toMatchObject({ shareId: bobShareId });
- expect(await serverDB.select().from(agentShareGrants)).toEqual([]);
- });
-
- it('lets the owner list and revoke grants', async () => {
- await aliceModel.addAgentFromCard(await postCard(bob));
- const shares = new AgentShareModel(serverDB, bob);
-
- expect(await shares.listGrants(bobAgent)).toEqual([
- expect.objectContaining({ user: expect.objectContaining({ id: alice }) }),
- ]);
- expect(await new AgentShareModel(serverDB, alice).listGrants(bobAgent)).toEqual([]);
-
- expect(await shares.revokeGrant(bobAgent, alice)).toBe(true);
- expect(await aliceModel.findAgentAccess(bobAgent)).toBeUndefined();
- expect(await shares.revokeGrant(bobAgent, alice)).toBe(false);
- });
-
- it('keeps a revoke: an earlier card cannot restore it, a later one from the owner does', async () => {
- const earlier = await postCard(bob, 1);
- await aliceModel.addAgentFromCard(earlier);
- const shares = new AgentShareModel(serverDB, bob);
- await shares.revokeGrant(bobAgent, alice);
-
- await expect(aliceModel.addAgentFromCard(earlier)).rejects.toThrow('Agent not found');
- expect(await aliceModel.findAgentAccess(bobAgent)).toBeUndefined();
- expect(await shares.listGrants(bobAgent)).toEqual([]);
-
- const later = await postCard(bob, 2);
- await serverDB
- .update(channelMessages)
- .set({ createdAt: new Date(Date.now() + 60_000) })
- .where(eq(channelMessages.id, later));
- await aliceModel.addAgentFromCard(later);
- expect(await aliceModel.findAgentAccess(bobAgent)).toMatchObject({ shareId: bobShareId });
- const [grant] = await serverDB.select().from(agentShareGrants);
- expect(grant).toMatchObject({ revokedAt: null, source: { messageId: later } });
- });
-});
-
-describe('a contact request from a card', () => {
- let channelId: string;
- let cardMessageId: string;
-
- beforeEach(async () => {
- const [channel] = await serverDB
- .insert(channels)
- .values({ title: 'Card', userId: alice })
- .returning();
- channelId = channel.id;
- await serverDB.insert(channelMembers).values([
- { actorType: 'user', channelId, role: 'owner', userId: alice },
- { actorType: 'user', channelId, role: 'member', userId: bob },
- ]);
- const [message] = await serverDB
- .insert(channelMessages)
- .values({
- channelId,
- content: '[Contact card] carol',
- metadata: { card: { name: 'carol', type: 'user', userId: carol } },
- requestKey: 'card',
- routingStatus: 'skipped',
- sequence: 1,
- userId: alice,
- })
- .returning();
- cardMessageId = message.id;
- });
-
- afterEach(async () => {
- await serverDB.delete(channels);
- });
-
- it('records who shared the card and shows it to the addressee', async () => {
- await bobModel.sendRequest(carol, undefined, { cardMessageId });
- const [incoming] = await carolModel.listRequests();
- expect(incoming.source).toEqual({
- referrer: { avatar: null, fullName: 'Alice', id: alice, username: 'alice' },
- type: 'card',
- });
- const [row] = await serverDB.select().from(userContactRequests);
- expect(row.source).toEqual({
- channelId,
- messageId: cardMessageId,
- referrerId: alice,
- type: 'card',
- });
- });
-
- it('drops a source the requester cannot see or that names someone else', async () => {
- // Carol is not in the Channel.
- await carolModel.sendRequest(bob, undefined, { cardMessageId });
- // The card shares Carol, not Alice.
- await bobModel.sendRequest(alice, undefined, { cardMessageId });
- const rows = await serverDB.select().from(userContactRequests);
- expect(rows.map((row) => row.source)).toEqual([null, null]);
- expect((await aliceModel.listRequests())[0].source).toBeNull();
- });
-});
diff --git a/packages/database/src/models/contact.ts b/packages/database/src/models/contact.ts
deleted file mode 100644
index 8dc0c3903aa..00000000000
--- a/packages/database/src/models/contact.ts
+++ /dev/null
@@ -1,1196 +0,0 @@
-import type {
- ContactAgentItem,
- ContactAgentProfile,
- ContactCard,
- ContactCardInput,
- ContactItem,
- ContactRelation,
- ContactRequestItem,
- ContactRequestSource,
- ContactSearchResult,
- ContactUserItem,
- ContactUserProfile,
- ContactWorkspace,
-} from '@lobechat/types';
-import { agentDisplayName, channelMessageDeletedAt, contactCardOf } from '@lobechat/types';
-import { TRPCError } from '@trpc/server';
-import type { SQLWrapper } from 'drizzle-orm';
-import { and, desc, eq, exists, inArray, isNotNull, isNull, lt, not, or, sql } from 'drizzle-orm';
-import { alias } from 'drizzle-orm/pg-core';
-
-import {
- agents,
- agentShares,
- channelMembers,
- channelMessages,
- userContactRequests,
- userContacts,
- users,
- workspaceMembers,
- workspaces,
-} from '../schemas';
-import type { LobeChatDatabase } from '../type';
-import { agentShareAdmits } from '../utils/agentShareAdmits';
-import { ilikeContains } from '../utils/like';
-import { notTrashed } from '../utils/softDelete';
-import { isUuid } from '../utils/uuid';
-import { AgentShareModel } from './agentShare';
-import { agentProfileColumns, owners, toAgentProfile } from './contactAgentProfile';
-
-const userProfileColumns = {
- avatar: users.avatar,
- fullName: users.fullName,
- id: users.id,
- username: users.username,
-};
-
-const referrers = alias(users, 'contact_request_referrer');
-
-/**
- * A share's creation time as microsecond ISO text: a `Date` keeps only milliseconds, and a
- * cursor cut to them would skip shares created later within the same millisecond.
- */
-const shareCreatedAtIso = sql<string>`to_char(${agentShares.createdAt} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`;
-
-/** Where a market page ends: the last share's creation time (microsecond ISO) and id. */
-export interface MarketAgentCursor {
- createdAt: string;
- id: string;
-}
-
-/** Who the caller is in the active scope. */
-type ScopeRole = 'personal' | 'member' | 'external';
-
-const WORKSPACE_MANAGER_ROLES = ['owner', 'admin'];
-
-/** `userId` (a value or a column) is an active member of the workspace. */
-const activeMemberWhere = (workspaceId: string, userId: string | SQLWrapper) =>
- and(
- eq(workspaceMembers.workspaceId, workspaceId),
- eq(workspaceMembers.userId, userId as string),
- isNull(workspaceMembers.deletedAt),
- );
-
-/** Share handles are stored lowercase; accept `@handle`, `/a/handle` and full share URLs. */
-export const parseContactHandle = (query: string): string | undefined => {
- const trimmed = query.trim();
- if (!trimmed) return undefined;
- const fromPath = trimmed.match(/\/a\/([^/?#\s]+)/);
- const handle = (fromPath ? decodeURIComponent(fromPath[1]) : trimmed).replace(/^@/, '');
- return handle || undefined;
-};
-
-/**
- * A person's address book and contact requests in one scope. Every method acts as `userId`;
- * another person's rows are only touched as the second half of a mutual relation.
- *
- * People are the scope's. In the personal space they are personal contacts. In a workspace,
- * colleagues are its members and need no entry; the address book holds its external contacts,
- * people outside it paired with the members who opened themselves to them. A member sees every
- * external contact; an external contact sees only the members paired with them and nothing else
- * of the workspace. Agents are the scope's too: in the personal space the caller's own, in a
- * workspace the ones any member added there, which every member sees and may remove.
- */
-export class ContactModel {
- private readonly db: LobeChatDatabase;
- private readonly userId: string;
- private readonly workspaceId: string | null;
-
- constructor(db: LobeChatDatabase, userId: string, workspaceId?: string | null) {
- this.db = db;
- this.userId = userId;
- this.workspaceId = workspaceId || null;
- }
-
- #scopeRole?: Promise<ScopeRole>;
-
- /**
- * Who the caller is in the active scope. In a workspace, an entry pairing them with a member
- * makes them an external contact; anyone else is refused.
- */
- private scopeRole = (): Promise<ScopeRole> => (this.#scopeRole ??= this.loadScopeRole());
-
- private async loadScopeRole(): Promise<ScopeRole> {
- if (!this.workspaceId) return 'personal';
- if (await this.isMember(this.userId)) return 'member';
- const [entry] = await this.db
- .select({ id: userContacts.id })
- .from(userContacts)
- .where(and(this.userEntryWhere(), eq(userContacts.userId, this.userId)))
- .limit(1);
- if (entry) return 'external';
- throw new TRPCError({ code: 'FORBIDDEN', message: 'Not a member of this workspace' });
- }
-
- private async isMember(userId: string) {
- if (!this.workspaceId) return false;
- const [row] = await this.db
- .select({ userId: workspaceMembers.userId })
- .from(workspaceMembers)
- .where(activeMemberWhere(this.workspaceId, userId))
- .limit(1);
- return !!row;
- }
-
- /** The person entries of this scope's address book. */
- private userEntryWhere() {
- return and(
- eq(userContacts.type, 'user'),
- this.workspaceId
- ? eq(userContacts.workspaceId, this.workspaceId)
- : isNull(userContacts.workspaceId),
- );
- }
-
- /** Requests of this scope: personal ones, or the ones members sent from this workspace. */
- private requestScopeWhere() {
- return this.workspaceId
- ? eq(userContactRequests.workspaceId, this.workspaceId)
- : isNull(userContactRequests.workspaceId);
- }
-
- /** The Agent entries of this scope's address book. */
- private agentEntryWhere() {
- return this.workspaceId
- ? and(eq(userContacts.type, 'agent'), eq(userContacts.workspaceId, this.workspaceId))
- : and(
- eq(userContacts.userId, this.userId),
- eq(userContacts.type, 'agent'),
- isNull(userContacts.workspaceId),
- );
- }
-
- list = async (): Promise<ContactItem[]> => {
- const role = await this.scopeRole();
- const [userItems, sharedAgents] = await Promise.all([
- role === 'member' ? this.listExternals() : this.listOwnPeople(role),
- // The workspace's Agents are its members' business, not an external contact's.
- role === 'external'
- ? []
- : this.db
- .select({
- admitted: sql<boolean>`${agentShareAdmits(this.userId)}`,
- createdAt: userContacts.createdAt,
- ...agentProfileColumns,
- })
- .from(userContacts)
- .innerJoin(agents, eq(agents.id, userContacts.agentId))
- .innerJoin(agentShares, eq(agentShares.agentId, agents.id))
- .leftJoin(owners, eq(owners.id, agents.userId))
- .where(this.agentEntryWhere())
- .orderBy(desc(userContacts.createdAt)),
- ]);
-
- const agentItems: ContactAgentItem[] = sharedAgents.map((row) => ({
- agent: toAgentProfile(row),
- // A workspace's Agent entries are shared, but a card share admits each person on their own.
- available: row.admitted && !row.isDeleted,
- createdAt: row.createdAt,
- type: 'agent',
- }));
-
- return [...userItems, ...agentItems];
- };
-
- /**
- * My own entries: personal contacts, or, for an external contact, the members paired with them
- * who are still members.
- */
- private async listOwnPeople(role: ScopeRole): Promise<ContactUserItem[]> {
- const rows = await this.db
- .select({ createdAt: userContacts.createdAt, user: userProfileColumns })
- .from(userContacts)
- .innerJoin(users, eq(users.id, userContacts.contactUserId))
- .where(
- and(
- this.userEntryWhere(),
- eq(userContacts.userId, this.userId),
- role === 'external' ? this.contactIsMember() : undefined,
- ),
- )
- .orderBy(desc(userContacts.createdAt));
- return rows.map((row) => ({ createdAt: row.createdAt, type: 'user', user: row.user }));
- }
-
- /** The entry's `contact_user_id` is an active member of the workspace. */
- private contactIsMember() {
- return exists(
- this.db
- .select({ userId: workspaceMembers.userId })
- .from(workspaceMembers)
- .where(activeMemberWhere(this.workspaceId!, userContacts.contactUserId)),
- );
- }
-
- /** Every external contact of the workspace, as a member sees them. */
- private async listExternals(): Promise<ContactUserItem[]> {
- const rows = await this.db
- .select({
- createdAt: userContacts.createdAt,
- pairedUserId: userContacts.userId,
- user: userProfileColumns,
- })
- .from(userContacts)
- .innerJoin(users, eq(users.id, userContacts.contactUserId))
- .where(and(this.userEntryWhere(), not(this.contactIsMember())))
- .orderBy(userContacts.createdAt);
-
- const byUser = new Map<string, ContactUserItem>();
- for (const row of rows) {
- const openedToMe = row.pairedUserId === this.userId;
- const item = byUser.get(row.user.id);
- if (item) item.external!.openedToMe ||= openedToMe;
- else
- byUser.set(row.user.id, {
- createdAt: row.createdAt,
- external: { openedToMe },
- type: 'user',
- user: row.user,
- });
- }
- return [...byUser.values()].reverse();
- }
-
- // ── People ────────────────────────────────────────────────────────────
-
- /** Whether I am paired with the person in this scope. */
- isContact = async (contactUserId: string): Promise<boolean> => {
- const [row] = await this.db
- .select({ id: userContacts.id })
- .from(userContacts)
- .where(
- and(
- this.userEntryWhere(),
- eq(userContacts.userId, this.userId),
- eq(userContacts.contactUserId, contactUserId),
- ),
- )
- .limit(1);
- return !!row;
- };
-
- /** A person's public profile; only the fields the address book shows. */
- findUser = async (userId: string) => {
- const [user] = await this.db
- .select(userProfileColumns)
- .from(users)
- .where(eq(users.id, userId))
- .limit(1);
- return user;
- };
-
- /**
- * People the caller can talk to one-on-one in this scope, the ones a conversation between two
- * people opens with: personal contacts; in a workspace, its other members, then the external
- * contacts paired with the caller; for an external contact, the members paired with them.
- * `query` narrows by a case-insensitive part of the display name or @handle.
- */
- listPeople = async (options: {
- limit: number;
- query?: string;
- }): Promise<{ hasMore: boolean; people: ContactUserProfile[] }> => {
- const role = await this.scopeRole();
- // A handle is matched without its `@`.
- const query = options.query?.trim().replace(/^@/, '').toLowerCase() || undefined;
- const matches = (person: ContactUserProfile) =>
- !query ||
- [person.fullName, person.username].some((value) => value?.toLowerCase().includes(query));
-
- const contacts =
- role === 'member'
- ? (await this.listExternals()).filter((item) => item.external?.openedToMe)
- : await this.listOwnPeople(role);
- const members =
- role === 'member'
- ? await this.db
- .select(userProfileColumns)
- .from(workspaceMembers)
- .innerJoin(users, eq(users.id, workspaceMembers.userId))
- .where(
- and(
- eq(workspaceMembers.workspaceId, this.workspaceId!),
- isNull(workspaceMembers.deletedAt),
- not(eq(workspaceMembers.userId, this.userId)),
- query
- ? or(ilikeContains(users.fullName, query), ilikeContains(users.username, query))
- : undefined,
- ),
- )
- .orderBy(users.fullName, users.username)
- // One more than asked tells whether more matched.
- .limit(options.limit + 1)
- : [];
-
- const people = [...members, ...contacts.map((item) => item.user).filter(matches)];
- return { hasMore: people.length > options.limit, people: people.slice(0, options.limit) };
- };
-
- /**
- * Everyone in this scope's address book except the caller: personal contacts; in a workspace,
- * its other members and every external contact of it, whoever invited them. Unlike
- * {@link listPeople} this ignores who the caller is in the scope, because it answers for a
- * resource the scope owns (an Agent's share), not for the caller's own conversations.
- */
- listAddressBookPeople = async (): Promise<ContactUserProfile[]> => {
- if (!this.workspaceId) {
- const rows = await this.db
- .select(userProfileColumns)
- .from(userContacts)
- .innerJoin(users, eq(users.id, userContacts.contactUserId))
- .where(and(this.userEntryWhere(), eq(userContacts.userId, this.userId)))
- .orderBy(desc(userContacts.createdAt));
- return rows;
- }
-
- const [members, externals] = await Promise.all([
- this.db
- .select(userProfileColumns)
- .from(workspaceMembers)
- .innerJoin(users, eq(users.id, workspaceMembers.userId))
- .where(
- and(
- eq(workspaceMembers.workspaceId, this.workspaceId),
- isNull(workspaceMembers.deletedAt),
- not(eq(workspaceMembers.userId, this.userId)),
- ),
- )
- .orderBy(users.fullName, users.username),
- this.listExternals(),
- ]);
- return [...members, ...externals.map((item) => item.user)];
- };
-
- /**
- * The subset of `userIds` that {@link listAddressBookPeople} would list, without loading it:
- * the check an access grant re-runs on every use, so removing someone from the address book
- * (or from the workspace) ends what was granted to them.
- */
- filterAddressBookPeople = async (userIds: string[]): Promise<string[]> => {
- const candidates = [...new Set(userIds)].filter((id) => id !== this.userId);
- if (candidates.length === 0) return [];
-
- const entries = await this.db
- .select({ userId: userContacts.contactUserId })
- .from(userContacts)
- .where(
- and(
- this.userEntryWhere(),
- inArray(userContacts.contactUserId, candidates),
- // Personal: my own entries. Workspace: any member's external contact; the paired
- // member side of the same pair is a member, matched below instead.
- this.workspaceId ? not(this.contactIsMember()) : eq(userContacts.userId, this.userId),
- ),
- );
- const members = this.workspaceId
- ? await this.db
- .select({ userId: workspaceMembers.userId })
- .from(workspaceMembers)
- .where(
- and(
- eq(workspaceMembers.workspaceId, this.workspaceId),
- isNull(workspaceMembers.deletedAt),
- inArray(workspaceMembers.userId, candidates),
- ),
- )
- : [];
-
- const found = new Set([...entries, ...members].map((row) => row.userId));
- return candidates.filter((id) => found.has(id));
- };
-
- relationTo = async (otherUserId: string): Promise<ContactRelation> => {
- if (otherUserId === this.userId) return 'self';
- if ((await this.scopeRole()) === 'member' && (await this.isMember(otherUserId)))
- return 'member';
- if (await this.isContact(otherUserId)) return 'contact';
- const [pending] = await this.db
- .select({ requesterId: userContactRequests.requesterId })
- .from(userContactRequests)
- .where(
- and(
- eq(userContactRequests.status, 'pending'),
- this.requestScopeWhere(),
- this.pairWhere(otherUserId),
- ),
- )
- .limit(1);
- if (!pending) return 'none';
- return pending.requesterId === this.userId ? 'request_sent' : 'request_received';
- };
-
- /**
- * Ask `addresseeId` to become mutual contacts. Repeating a pending request returns it; a
- * personal request sent while theirs is pending accepts theirs instead. In a workspace only a
- * member asks, and only someone outside it: it invites them to be its external contact.
- */
- sendRequest = async (
- addresseeId: string,
- message?: string,
- options?: { cardMessageId?: string },
- ): Promise<{ requestId: string; status: 'accepted' | 'pending' }> => {
- if (addresseeId === this.userId)
- throw new TRPCError({ code: 'BAD_REQUEST', message: 'You cannot add yourself' });
- const role = await this.scopeRole();
- if (role === 'external')
- throw new TRPCError({ code: 'FORBIDDEN', message: 'Only members add contacts here' });
- if (role === 'member' && (await this.isMember(addresseeId)))
- throw new TRPCError({ code: 'CONFLICT', message: 'Already a member of this workspace' });
-
- return this.db.transaction(async (tx) => {
- const [addressee] = await tx
- .select({ id: users.id })
- .from(users)
- .where(eq(users.id, addresseeId))
- .limit(1);
- if (!addressee) throw new TRPCError({ code: 'NOT_FOUND', message: 'User not found' });
-
- // Serialize the pair so two crossing requests cannot both stay pending.
- await this.lockPair(tx, addresseeId);
-
- const [existing] = await tx
- .select({ id: userContacts.id })
- .from(userContacts)
- .where(
- and(
- this.userEntryWhere(),
- eq(userContacts.userId, this.userId),
- eq(userContacts.contactUserId, addresseeId),
- ),
- )
- .limit(1);
- if (existing) throw new TRPCError({ code: 'CONFLICT', message: 'Already a contact' });
-
- const [pending] = await tx
- .select({ id: userContactRequests.id, requesterId: userContactRequests.requesterId })
- .from(userContactRequests)
- .where(
- and(
- eq(userContactRequests.status, 'pending'),
- this.requestScopeWhere(),
- this.pairWhere(addresseeId),
- ),
- )
- .limit(1);
- if (pending?.requesterId === this.userId) return { requestId: pending.id, status: 'pending' };
- // Their pending request is answered by mine, unless they withdrew it meanwhile; then mine
- // goes out as a new request.
- if (pending && (await this.accept(tx, pending.id, addresseeId, this.workspaceId)))
- return { requestId: pending.id, status: 'accepted' };
-
- const source = options?.cardMessageId
- ? await this.cardSource(tx, options.cardMessageId, addresseeId)
- : undefined;
- const [created] = await tx
- .insert(userContactRequests)
- .values({
- addresseeId,
- message: message?.trim() || null,
- requesterId: this.userId,
- source: source ?? null,
- workspaceId: this.workspaceId,
- })
- .returning({ id: userContactRequests.id });
- return { requestId: created.id, status: 'pending' };
- });
- };
-
- /**
- * Pending requests of this scope. The personal space has personal requests both ways plus the
- * invitations members sent me from their workspaces, which I answer there before I can enter
- * the workspace. A member sees the invitations they sent from this workspace; an external
- * contact sees none.
- */
- listRequests = async (): Promise<ContactRequestItem[]> => {
- const role = await this.scopeRole();
- if (role === 'external') return [];
- const scope =
- role === 'member'
- ? and(this.requestScopeWhere(), eq(userContactRequests.requesterId, this.userId))
- : or(
- and(
- this.requestScopeWhere(),
- or(
- eq(userContactRequests.requesterId, this.userId),
- eq(userContactRequests.addresseeId, this.userId),
- ),
- ),
- and(
- isNotNull(userContactRequests.workspaceId),
- eq(userContactRequests.addresseeId, this.userId),
- ),
- );
- const rows = await this.db
- .select({
- createdAt: userContactRequests.createdAt,
- id: userContactRequests.id,
- message: userContactRequests.message,
- // Flat: drizzle drops a nested object of this aliased join.
- referrerAvatar: referrers.avatar,
- referrerFullName: referrers.fullName,
- referrerId: referrers.id,
- referrerUsername: referrers.username,
- requesterId: userContactRequests.requesterId,
- source: userContactRequests.source,
- user: userProfileColumns,
- workspaceAvatar: workspaces.avatar,
- workspaceId: workspaces.id,
- workspaceName: workspaces.name,
- })
- .from(userContactRequests)
- .innerJoin(
- users,
- sql`${users.id} = CASE WHEN ${userContactRequests.requesterId} = ${this.userId} THEN ${userContactRequests.addresseeId} ELSE ${userContactRequests.requesterId} END`,
- )
- .leftJoin(workspaces, eq(workspaces.id, userContactRequests.workspaceId))
- .leftJoin(
- referrers,
- eq(referrers.id, sql<string>`${userContactRequests.source} ->> 'referrerId'`),
- )
- .where(and(eq(userContactRequests.status, 'pending'), scope))
- .orderBy(desc(userContactRequests.createdAt));
-
- return rows.map((row) => ({
- createdAt: row.createdAt,
- direction: row.requesterId === this.userId ? 'outgoing' : 'incoming',
- id: row.id,
- message: row.message,
- source:
- row.source?.type === 'card'
- ? {
- referrer: row.referrerId
- ? {
- avatar: row.referrerAvatar,
- fullName: row.referrerFullName,
- id: row.referrerId,
- username: row.referrerUsername,
- }
- : null,
- type: 'card' as const,
- }
- : null,
- user: row.user,
- workspace: row.workspaceId
- ? { avatar: row.workspaceAvatar, id: row.workspaceId, name: row.workspaceName ?? '' }
- : null,
- }));
- };
-
- /**
- * Accept a pending request sent to me; both people become each other's contact in the
- * request's scope. Accepting a member's invitation makes me an external contact of their
- * workspace, paired with them; it lapses once they leave it.
- */
- acceptRequest = async (
- requestId: string,
- ): Promise<{ contactUserId: string; workspaceId: string | null }> =>
- this.db.transaction(async (tx) => {
- const request = await this.incomingPending(tx, requestId);
- const { requesterId, workspaceId } = request;
- if (workspaceId) {
- const members = await tx
- .select({ userId: workspaceMembers.userId })
- .from(workspaceMembers)
- .where(
- and(
- eq(workspaceMembers.workspaceId, workspaceId),
- inArray(workspaceMembers.userId, [requesterId, this.userId]),
- isNull(workspaceMembers.deletedAt),
- ),
- );
- if (!members.some((member) => member.userId === requesterId))
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Request not found' });
- if (members.some((member) => member.userId === this.userId))
- throw new TRPCError({ code: 'CONFLICT', message: 'Already a member of this workspace' });
- }
- await this.lockPair(tx, requesterId, workspaceId);
- if (!(await this.accept(tx, request.id, requesterId, workspaceId)))
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Request not found' });
- return { contactUserId: requesterId, workspaceId };
- });
-
- /** Returns who sent it, so they can be told their request is no longer pending. */
- declineRequest = async (requestId: string): Promise<{ requesterId: string }> =>
- this.db.transaction(async (tx) => {
- const request = await this.incomingPending(tx, requestId);
- // Same rule as accepting: only a request still pending can be answered.
- const [declined] = await tx
- .update(userContactRequests)
- .set({ respondedAt: new Date(), status: 'declined', updatedAt: new Date() })
- .where(
- and(eq(userContactRequests.id, request.id), eq(userContactRequests.status, 'pending')),
- )
- .returning({ id: userContactRequests.id });
- if (!declined) throw new TRPCError({ code: 'NOT_FOUND', message: 'Request not found' });
- return { requesterId: request.requesterId };
- });
-
- /** Returns who it was sent to, so their incoming request can disappear. */
- cancelRequest = async (requestId: string): Promise<{ addresseeId: string }> => {
- if (!isUuid(requestId))
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Request not found' });
- const [cancelled] = await this.db
- .update(userContactRequests)
- .set({ respondedAt: new Date(), status: 'cancelled', updatedAt: new Date() })
- .where(
- and(
- eq(userContactRequests.id, requestId),
- eq(userContactRequests.requesterId, this.userId),
- eq(userContactRequests.status, 'pending'),
- ),
- )
- .returning({ addresseeId: userContactRequests.addresseeId });
- if (!cancelled) throw new TRPCError({ code: 'NOT_FOUND', message: 'Request not found' });
- return { addresseeId: cancelled.addresseeId };
- };
-
- /**
- * Remove a person from my contacts in this scope; the relation is mutual, so both entries go.
- * A member closes themselves to an external contact this way, and an external contact drops a
- * member; once an external contact has no member left, the workspace is gone for them.
- */
- removeUser = async (contactUserId: string) => {
- await this.scopeRole();
- await this.db
- .delete(userContacts)
- .where(and(this.userEntryWhere(), this.entryPairWhere(contactUserId)));
- };
-
- /**
- * A member opens themselves to an external contact of the workspace, who can then see and
- * message them. Each member opens only themselves; the inviter is paired on accepting.
- */
- openTo = async (externalUserId: string) => {
- if ((await this.scopeRole()) !== 'member')
- throw new TRPCError({ code: 'FORBIDDEN', message: 'Only members open themselves' });
- if (externalUserId === this.userId || !(await this.isExternal(externalUserId)))
- throw new TRPCError({ code: 'NOT_FOUND', message: 'External contact not found' });
- await this.db
- .insert(userContacts)
- .values([
- {
- contactUserId: externalUserId,
- type: 'user',
- userId: this.userId,
- workspaceId: this.workspaceId,
- },
- {
- contactUserId: this.userId,
- type: 'user',
- userId: externalUserId,
- workspaceId: this.workspaceId,
- },
- ])
- .onConflictDoNothing();
- };
-
- /**
- * An owner or admin removes an external contact from the workspace: every pairing goes, and
- * so do the invitations still pending for them.
- */
- removeExternal = async (externalUserId: string) => {
- if ((await this.scopeRole()) !== 'member' || !(await this.isManager()))
- throw new TRPCError({ code: 'FORBIDDEN', message: 'Only owners and admins remove them' });
- if (!(await this.isExternal(externalUserId)))
- throw new TRPCError({ code: 'NOT_FOUND', message: 'External contact not found' });
- await this.db.transaction(async (tx) => {
- await tx
- .delete(userContacts)
- .where(
- and(
- this.userEntryWhere(),
- or(
- eq(userContacts.userId, externalUserId),
- eq(userContacts.contactUserId, externalUserId),
- ),
- ),
- );
- await tx
- .update(userContactRequests)
- .set({ respondedAt: new Date(), status: 'cancelled', updatedAt: new Date() })
- .where(
- and(
- this.requestScopeWhere(),
- eq(userContactRequests.addresseeId, externalUserId),
- eq(userContactRequests.status, 'pending'),
- ),
- );
- });
- };
-
- /**
- * 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;
- const [entry] = await this.db
- .select({ id: userContacts.id })
- .from(userContacts)
- .where(and(this.userEntryWhere(), eq(userContacts.userId, userId)))
- .limit(1);
- return !!entry;
- }
-
- private async isManager() {
- const [row] = await this.db
- .select({ role: workspaceMembers.role })
- .from(workspaceMembers)
- .where(activeMemberWhere(this.workspaceId!, this.userId))
- .limit(1);
- return !!row && WORKSPACE_MANAGER_ROLES.includes(row.role);
- }
-
- private entryPairWhere(otherUserId: string) {
- return or(
- and(eq(userContacts.userId, this.userId), eq(userContacts.contactUserId, otherUserId)),
- and(eq(userContacts.userId, otherUserId), eq(userContacts.contactUserId, this.userId)),
- );
- }
-
- /**
- * The source of a request sent from a person's card: only when the card message stands in a
- * Channel I am an active member of and shares exactly the addressee. Anything else is dropped,
- * not refused: the request itself does not depend on its source.
- */
- private cardSource = async (
- tx: Pick<LobeChatDatabase, 'select'>,
- messageId: string,
- addresseeId: string,
- ): Promise<ContactRequestSource | undefined> => {
- const found = await this.findCardMessage(tx, messageId);
- if (found?.card.type !== 'user' || found.card.userId !== addresseeId) return;
- return { channelId: found.channelId, messageId, referrerId: found.senderId, type: 'card' };
- };
-
- /** A live card message in a Channel I am an active member of, with its card. */
- private findCardMessage = async (tx: Pick<LobeChatDatabase, 'select'>, messageId: string) => {
- if (!isUuid(messageId)) return;
- const [row] = await tx
- .select({
- channelId: channelMessages.channelId,
- createdAt: channelMessages.createdAt,
- metadata: channelMessages.metadata,
- senderId: channelMessages.userId,
- })
- .from(channelMessages)
- .innerJoin(
- channelMembers,
- and(
- eq(channelMembers.channelId, channelMessages.channelId),
- eq(channelMembers.userId, this.userId),
- eq(channelMembers.status, 'active'),
- ),
- )
- .where(eq(channelMessages.id, messageId))
- .limit(1);
- const card = contactCardOf(row?.metadata);
- if (!row || !card || channelMessageDeletedAt(row.metadata)) return;
- return { ...row, card };
- };
-
- /**
- * A contact the caller may share as a card, with its snapshot. A person: the caller, one of
- * their contacts, or a fellow member of the workspace. An Agent: its owner may share it while
- * its share is `card` or `link`, and anyone may pass on a `link` share, since anyone signed in
- * can add it anyway. Only the owner's card admits people to a `card` share. An owner whose
- * share is off is told to turn card sharing on (`agentShare.enableCardShare`), never refused
- * outright, so a client can do that and send in one step.
- */
- resolveCard = async (input: ContactCardInput): Promise<ContactCard> => {
- if ((await this.scopeRole()) === 'external')
- throw new TRPCError({ code: 'FORBIDDEN', message: 'Only members share contacts here' });
-
- if (input.type === 'user') {
- const relation = await this.relationTo(input.userId);
- if (relation !== 'self' && relation !== 'contact' && relation !== 'member')
- throw new TRPCError({ code: 'FORBIDDEN', message: 'Share only your contacts' });
- const user = await this.findUser(input.userId);
- if (!user) throw new TRPCError({ code: 'NOT_FOUND', message: 'User not found' });
- return {
- avatar: user.avatar,
- name: user.fullName || user.username,
- type: 'user',
- userId: user.id,
- username: user.username,
- };
- }
-
- const [row] = await this.db
- .select(agentProfileColumns)
- .from(agents)
- .leftJoin(agentShares, eq(agentShares.agentId, agents.id))
- .leftJoin(owners, eq(owners.id, agents.userId))
- .where(and(eq(agents.id, input.agentId), notTrashed(agents.isDeleted)))
- .limit(1);
- const isOwner = !!row && row.ownerId === this.userId;
- const shareable =
- row?.shareId && (row.visibility === 'link' || (row.visibility === 'card' && isOwner));
- if (!shareable) {
- if (isOwner)
- throw new TRPCError({ code: 'PRECONDITION_FAILED', message: 'Turn on sharing first' });
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
- }
- const profile = toAgentProfile({ ...row, shareId: row.shareId! });
- return {
- agentId: profile.agentId,
- avatar: profile.avatar,
- backgroundColor: profile.backgroundColor,
- // The name every list shows: the personal name, else the role title.
- name: agentDisplayName(profile) ?? null,
- ownerName: profile.owner.fullName || profile.owner.username,
- shareId: profile.shareId,
- type: 'agent',
- };
- };
-
- // ── Agents ────────────────────────────────────────────────────────────
-
- /** Add another person's Agent in this scope through its link share (share id or handle). */
- addAgent = async (shareIdOrSlug: string): Promise<ContactAgentProfile> => {
- const share = await this.findLinkShare(shareIdOrSlug);
- if (!share) throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
- if (share.ownerId === this.userId)
- throw new TRPCError({ code: 'BAD_REQUEST', message: 'This Agent is already yours' });
-
- await this.db
- .insert(userContacts)
- .values({
- agentId: share.agentId,
- type: 'agent',
- userId: this.userId,
- workspaceId: this.workspaceId,
- })
- .onConflictDoNothing();
- return toAgentProfile(share);
- };
-
- /**
- * Add another person's Agent from its card in a Channel I am an active member of. A card its
- * owner sent also grants me its share, which is what admits me to a `card` share and keeps me
- * admitted if a `link` share later becomes `card`; a card anyone else passed on only works while
- * the share is `link`, like the link itself.
- */
- addAgentFromCard = async (messageId: string): Promise<ContactAgentProfile> => {
- if ((await this.scopeRole()) === 'external')
- throw new TRPCError({ code: 'FORBIDDEN', message: 'Only members add Agents here' });
- const notFound = () => new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
- const message = await this.findCardMessage(this.db, messageId);
- const card = message?.card;
- if (!message || card?.type !== 'agent') throw notFound();
-
- const [share] = await this.db
- .select(agentProfileColumns)
- .from(agentShares)
- .innerJoin(agents, eq(agents.id, agentShares.agentId))
- .leftJoin(owners, eq(owners.id, agents.userId))
- .where(
- and(
- eq(agentShares.id, card.shareId),
- eq(agents.id, card.agentId),
- notTrashed(agents.isDeleted),
- ),
- )
- .limit(1);
- if (!share?.ownerId) throw notFound();
- if (share.ownerId === this.userId)
- throw new TRPCError({ code: 'BAD_REQUEST', message: 'This Agent is already yours' });
- const fromOwner = message.senderId === share.ownerId;
- if (!(share.visibility === 'link' || (share.visibility === 'card' && fromOwner)))
- throw notFound();
-
- await this.db.transaction(async (tx) => {
- const granted =
- fromOwner &&
- (await AgentShareModel.grant(tx, {
- issuedAt: message.createdAt,
- shareId: share.shareId,
- source: { channelId: message.channelId, messageId, type: 'card' },
- userId: this.userId,
- }));
- // The owner revoked me after sending this card: it no longer admits me to a `card` share.
- if (share.visibility === 'card' && !granted) throw notFound();
- await tx
- .insert(userContacts)
- .values({
- agentId: share.agentId,
- type: 'agent',
- userId: this.userId,
- workspaceId: this.workspaceId,
- })
- .onConflictDoNothing();
- });
- return toAgentProfile(share);
- };
-
- removeAgent = async (agentId: string) => {
- await this.db
- .delete(userContacts)
- .where(and(this.agentEntryWhere(), eq(userContacts.agentId, agentId)));
- };
-
- /**
- * The live share that authorizes me to message another person's Agent: its entry in this
- * scope's address book plus its link share. Returns undefined for my own Agents, which need no
- * share.
- */
- findAgentAccess = async (agentId: string) => {
- if ((await this.scopeRole()) === 'external') return undefined;
- const [row] = await this.db
- .select({
- agentId: agents.id,
- name: agents.name,
- ownerId: agents.userId,
- shareId: agentShares.id,
- title: agents.title,
- workspaceId: agents.workspaceId,
- })
- .from(userContacts)
- .innerJoin(agents, eq(agents.id, userContacts.agentId))
- .innerJoin(agentShares, eq(agentShares.agentId, agents.id))
- .where(
- and(
- this.agentEntryWhere(),
- eq(userContacts.agentId, agentId),
- agentShareAdmits(this.userId),
- notTrashed(agents.isDeleted),
- ),
- )
- .limit(1);
- if (!row?.ownerId || row.ownerId === this.userId) return undefined;
- return { ...row, ownerId: row.ownerId };
- };
-
- /**
- * Agents a person shares by link, for their profile card. A link share is open to anyone
- * signed in, so the list is too; it does not need the person as a contact.
- */
- listSharedAgentsOf = async (ownerId: string): Promise<ContactAgentProfile[]> => {
- const rows = await this.db
- .select(agentProfileColumns)
- .from(agentShares)
- .innerJoin(agents, eq(agents.id, agentShares.agentId))
- .leftJoin(owners, eq(owners.id, agents.userId))
- .where(
- and(
- eq(agents.userId, ownerId),
- eq(agentShares.visibility, 'link'),
- notTrashed(agents.isDeleted),
- ),
- )
- .orderBy(desc(agentShares.createdAt));
- return rows.map(toAgentProfile);
- };
-
- /**
- * The shared-Agent market: link shares whose owners listed them, newest first, one page at a
- * time. Keyset-paged on the share's creation time (id breaks ties), so a share listed while
- * someone scrolls neither repeats nor skips a row. `query` matches the title or description.
- */
- listMarketAgents = async (options: {
- cursor?: MarketAgentCursor;
- limit: number;
- query?: string;
- }): Promise<{ items: ContactAgentProfile[]; nextCursor: MarketAgentCursor | null }> => {
- const { cursor, limit } = options;
- const query = options.query?.trim();
- const rows = await this.db
- .select({ ...agentProfileColumns, shareCreatedAt: shareCreatedAtIso })
- .from(agentShares)
- .innerJoin(agents, eq(agents.id, agentShares.agentId))
- .leftJoin(owners, eq(owners.id, agents.userId))
- .where(
- and(
- eq(agentShares.visibility, 'link'),
- sql`(${agentShares.shareConfig} ->> 'listedInMarket')::boolean IS TRUE`,
- notTrashed(agents.isDeleted),
- query
- ? or(ilikeContains(agents.title, query), ilikeContains(agents.description, query))
- : undefined,
- cursor
- ? or(
- sql`${agentShares.createdAt} < ${cursor.createdAt}::timestamptz`,
- and(
- sql`${agentShares.createdAt} = ${cursor.createdAt}::timestamptz`,
- lt(agentShares.id, cursor.id),
- ),
- )
- : undefined,
- ),
- )
- .orderBy(desc(agentShares.createdAt), desc(agentShares.id))
- .limit(limit + 1);
-
- const page = rows.slice(0, limit);
- const last = page.at(-1);
- return {
- items: page.map(toAgentProfile),
- nextCursor:
- rows.length > limit && last ? { createdAt: last.shareCreatedAt, id: last.shareId } : null,
- };
- };
-
- // ── Search ────────────────────────────────────────────────────────────
-
- /**
- * Exact handle lookup: a person's username and an Agent's share handle, plus a pasted share
- * link. No fuzzy search, so a stranger cannot enumerate accounts.
- */
- search = async (query: string): Promise<ContactSearchResult[]> => {
- const handle = parseContactHandle(query);
- // An external contact finds nothing of the workspace by searching.
- if (!handle || (await this.scopeRole()) === 'external') return [];
- const results: ContactSearchResult[] = [];
-
- const [person] = await this.db
- .select(userProfileColumns)
- .from(users)
- .where(sql`lower(${users.username}) = ${handle.toLowerCase()}`)
- .limit(1);
- if (person)
- results.push({ relation: await this.relationTo(person.id), type: 'user', user: person });
-
- const share = await this.findLinkShare(handle);
- if (share) {
- const relation =
- share.ownerId === this.userId
- ? 'self'
- : (await this.findAgentAccess(share.agentId))
- ? 'contact'
- : 'none';
- results.push({ agent: toAgentProfile(share), relation, type: 'agent' });
- }
-
- return results;
- };
-
- // ── Internals ─────────────────────────────────────────────────────────
-
- private pairWhere(otherUserId: string) {
- return or(
- and(
- eq(userContactRequests.requesterId, this.userId),
- eq(userContactRequests.addresseeId, otherUserId),
- ),
- and(
- eq(userContactRequests.requesterId, otherUserId),
- eq(userContactRequests.addresseeId, this.userId),
- ),
- );
- }
-
- /** Transaction-scoped advisory lock on the unordered pair in one scope. */
- private async lockPair(
- tx: Pick<LobeChatDatabase, 'execute'>,
- otherUserId: string,
- workspaceId: string | null = this.workspaceId,
- ) {
- const [a, b] = [this.userId, otherUserId].sort();
- const key = `contact:${workspaceId ?? 'personal'}:${a}:${b}`;
- await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${key}))`);
- }
-
- private async incomingPending(tx: Pick<LobeChatDatabase, 'select'>, requestId: string) {
- if (!isUuid(requestId))
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Request not found' });
- const [request] = await tx
- .select({
- id: userContactRequests.id,
- requesterId: userContactRequests.requesterId,
- workspaceId: userContactRequests.workspaceId,
- })
- .from(userContactRequests)
- .where(
- and(
- eq(userContactRequests.id, requestId),
- eq(userContactRequests.addresseeId, this.userId),
- eq(userContactRequests.status, 'pending'),
- ),
- )
- .limit(1);
- if (!request) throw new TRPCError({ code: 'NOT_FOUND', message: 'Request not found' });
- return request;
- }
-
- /**
- * Move a request from pending to accepted and add both contact entries. The transition is
- * conditional on the row still being pending: a withdrawal or decline that committed after the
- * request was read wins, and no contacts are added. Returns whether it was accepted.
- */
- private async accept(
- tx: Pick<LobeChatDatabase, 'insert' | 'update'>,
- requestId: string,
- requesterId: string,
- workspaceId: string | null,
- ): Promise<boolean> {
- const now = new Date();
- const [accepted] = await tx
- .update(userContactRequests)
- .set({ respondedAt: now, status: 'accepted', updatedAt: now })
- .where(and(eq(userContactRequests.id, requestId), eq(userContactRequests.status, 'pending')))
- .returning({ id: userContactRequests.id });
- if (!accepted) return false;
- await tx
- .insert(userContacts)
- .values([
- { contactUserId: requesterId, type: 'user', userId: this.userId, workspaceId },
- { contactUserId: this.userId, type: 'user', userId: requesterId, workspaceId },
- ])
- .onConflictDoNothing();
- return true;
- }
-
- private async findLinkShare(shareIdOrSlug: string) {
- const key = parseContactHandle(shareIdOrSlug);
- if (!key) return undefined;
- const [row] = await this.db
- .select(agentProfileColumns)
- .from(agentShares)
- .innerJoin(agents, eq(agents.id, agentShares.agentId))
- .leftJoin(owners, eq(owners.id, agents.userId))
- .where(
- and(
- isUuid(key)
- ? eq(agentShares.id, key)
- : sql`${agentShares.shareConfig} ->> 'slug' = ${key.toLowerCase()}`,
- eq(agentShares.visibility, 'link'),
- notTrashed(agents.isDeleted),
- ),
- )
- .limit(1);
- return row;
- }
-}
diff --git a/packages/database/src/models/contactAgentProfile.ts b/packages/database/src/models/contactAgentProfile.ts
deleted file mode 100644
index cece1afea8f..00000000000
--- a/packages/database/src/models/contactAgentProfile.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import type { ContactAgentProfile } from '@lobechat/types';
-import { sql } from 'drizzle-orm';
-import { alias } from 'drizzle-orm/pg-core';
-
-import { agents, agentShares, users } from '../schemas';
-import { normalizeInboxAgentAvatar, normalizeInboxAgentTitle } from '../utils/inboxAgent';
-
-/** An Agent's owner, joined next to `agents` when an Agent is read through its share. */
-export const owners = alias(users, 'contact_agent_owner');
-
-/** Columns of an Agent reached through its share, with the owner joined as `owners`. */
-export const agentProfileColumns = {
- agentAvatar: agents.avatar,
- agentBackgroundColor: agents.backgroundColor,
- agentDescription: agents.description,
- agentId: agents.id,
- agentName: agents.name,
- agentSlug: agents.slug,
- agentTitle: agents.title,
- isDeleted: agents.isDeleted,
- ownerAvatar: owners.avatar,
- ownerFullName: owners.fullName,
- ownerId: owners.id,
- ownerUsername: owners.username,
- shareId: agentShares.id,
- shareSlug: sql<string | null>`${agentShares.shareConfig} ->> 'slug'`,
- visibility: agentShares.visibility,
-};
-
-type AgentProfileRow = {
- agentAvatar: string | null;
- agentBackgroundColor: string | null;
- agentDescription: string | null;
- agentId: string;
- agentName: string | null;
- agentSlug: string | null;
- agentTitle: string | null;
- ownerAvatar: string | null;
- ownerFullName: string | null;
- ownerId: string | null;
- ownerUsername: string | null;
- shareId: string;
- shareSlug: string | null;
-};
-
-export const toAgentProfile = (row: AgentProfileRow): ContactAgentProfile => ({
- agentId: row.agentId,
- avatar: normalizeInboxAgentAvatar(row.agentAvatar, { slug: row.agentSlug }) ?? null,
- backgroundColor: row.agentBackgroundColor,
- description: row.agentDescription,
- name: row.agentName?.trim() || null,
- owner: {
- avatar: row.ownerAvatar,
- fullName: row.ownerFullName,
- id: row.ownerId ?? '',
- username: row.ownerUsername,
- },
- shareId: row.shareId,
- slug: row.shareSlug,
- title: normalizeInboxAgentTitle(row.agentTitle, { slug: row.agentSlug }) ?? null,
-});
diff --git a/packages/database/src/repositories/channel/__tests__/cardMessage.test.ts b/packages/database/src/repositories/channel/__tests__/cardMessage.test.ts
index 4f019ca5d95..49b73b12a2d 100644
--- a/packages/database/src/repositories/channel/__tests__/cardMessage.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/cardMessage.test.ts
@@ -4,10 +4,11 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
import { userContactRequests, users, workspaceMembers } from '../../../schemas';
+import { tableContacts } from './tableContacts';
import { createChannelFixture } from './testUtils';
const db = await getTestDB();
-const fixture = createChannelFixture(db, 'channel-card');
+const fixture = createChannelFixture(db, 'channel-card', tableContacts);
beforeEach(async () => {
await fixture.setup();
// Cards check the address book, which counts fellow workspace members.
diff --git a/packages/database/src/repositories/channel/__tests__/groupFromDirect.test.ts b/packages/database/src/repositories/channel/__tests__/groupFromDirect.test.ts
index b65cad00d53..bda568439f0 100644
--- a/packages/database/src/repositories/channel/__tests__/groupFromDirect.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/groupFromDirect.test.ts
@@ -5,10 +5,11 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
import { agents, channelMembers, channels, userContacts, workspaceMembers } from '../../../schemas';
import { ChannelRepository } from '..';
+import { tableContacts } from './tableContacts';
import { createChannelFixture } from './testUtils';
const db = await getTestDB();
-const fixture = createChannelFixture(db, 'channel-group-from-direct');
+const fixture = createChannelFixture(db, 'channel-group-from-direct', tableContacts);
beforeEach(async () => {
await fixture.setup();
await db.insert(workspaceMembers).values([
@@ -37,7 +38,7 @@ const createAgent = async (name: string, workspaceId: string | null) => {
const createDirect = async (workspaceId: string | null = fixture.workspaceId) => {
const agent = await createAgent('Ada', workspaceId);
- const owner = new ChannelRepository(db, fixture.ownerId, workspaceId);
+ const owner = new ChannelRepository(db, fixture.ownerId, workspaceId, tableContacts);
const { channel } = await owner.create({
agentConfig: environment(),
agentId: agent.id,
@@ -82,7 +83,7 @@ describe('inviting from a direct conversation', () => {
);
// The direct conversation stays one person and one Agent, and the invitee only sees the group.
expect(await membersOf(direct.id)).toHaveLength(2);
- const invitee = new ChannelRepository(db, fixture.memberId, fixture.workspaceId);
+ const invitee = new ChannelRepository(db, fixture.memberId, fixture.workspaceId, tableContacts);
expect((await invitee.list()).map(({ id }) => id)).toEqual([channel.id]);
});
diff --git a/packages/database/src/repositories/channel/__tests__/peer.test.ts b/packages/database/src/repositories/channel/__tests__/peer.test.ts
index 0a4cacaf83d..1509607e1c0 100644
--- a/packages/database/src/repositories/channel/__tests__/peer.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/peer.test.ts
@@ -3,23 +3,32 @@ import { and, eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
-import { ContactModel } from '../../../models/contact';
import { agents, files, userContacts, users, workspaceMembers } from '../../../schemas';
import { ChannelRepository } from '..';
+import { tableContacts } from './tableContacts';
import { createChannelFixture, jobsOf } from './testUtils';
const db = await getTestDB();
-const fixture = createChannelFixture(db, 'channel-peer');
+const fixture = createChannelFixture(db, 'channel-peer', tableContacts);
const alice = fixture.ownerId;
const bob = fixture.memberId;
-const asAlice = new ChannelRepository(db, alice);
-const asBob = new ChannelRepository(db, bob);
-
-const befriend = async () => {
- const { requestId } = await new ContactModel(db, alice).sendRequest(bob);
- await new ContactModel(db, bob).acceptRequest(requestId);
+const asAlice = new ChannelRepository(db, alice, undefined, tableContacts);
+const asBob = new ChannelRepository(db, bob, undefined, tableContacts);
+
+/** One direction of a contact relation in a scope; both make two people contacts. */
+const addContact = (userId: string, contactUserId: string, workspaceId: string | null = null) =>
+ db.insert(userContacts).values({ contactUserId, type: 'user', userId, workspaceId });
+const pair = async (a: string, b: string, workspaceId: string | null = null) => {
+ await addContact(a, b, workspaceId);
+ await addContact(b, a, workspaceId);
};
+const dropContact = (userId: string, contactUserId: string) =>
+ db
+ .delete(userContacts)
+ .where(and(eq(userContacts.userId, userId), eq(userContacts.contactUserId, contactUserId)));
+
+const befriend = () => pair(alice, bob);
beforeEach(fixture.setup);
afterEach(async () => {
@@ -30,7 +39,7 @@ afterEach(async () => {
describe('a conversation between two contacts', () => {
it('requires the mutual contact relation', async () => {
await expect(asAlice.openPeer(bob, 'Mia')).rejects.toThrow('You are not contacts');
- await new ContactModel(db, alice).sendRequest(bob);
+ await addContact(alice, bob);
await expect(asAlice.openPeer(bob, 'Mia')).rejects.toThrow('You are not contacts');
});
@@ -90,7 +99,7 @@ describe('a conversation between two contacts', () => {
it('goes silent once either person removes the other', async () => {
await befriend();
const { channel } = await asAlice.openPeer(bob, 'Mia');
- await new ContactModel(db, bob).removeUser(alice);
+ await dropContact(bob, alice);
await expect(
asAlice.send(channel.id, { content: 'Still there?', requestKey: 'x', routing: 'fallback' }),
).rejects.toThrow('You are not contacts');
@@ -100,7 +109,8 @@ describe('a conversation between two contacts', () => {
});
describe('a conversation between two workspace members', () => {
- const inTeam = (userId: string) => new ChannelRepository(db, userId, fixture.workspaceId);
+ const inTeam = (userId: string) =>
+ new ChannelRepository(db, userId, fixture.workspaceId, tableContacts);
const join = (...userIds: string[]) =>
db
.insert(workspaceMembers)
@@ -155,8 +165,8 @@ describe('a conversation between two workspace members', () => {
describe('a conversation with an external contact of a workspace', () => {
const carol = 'channel-peer-carol';
- const inTeam = (userId: string) => new ChannelRepository(db, userId, fixture.workspaceId);
- const contactsInTeam = (userId: string) => new ContactModel(db, userId, fixture.workspaceId);
+ const inTeam = (userId: string) =>
+ new ChannelRepository(db, userId, fixture.workspaceId, tableContacts);
/** Alice and Carol are members; Alice invites Bob, who stays outside the workspace. */
const inviteBob = async () => {
@@ -168,8 +178,7 @@ describe('a conversation with an external contact of a workspace', () => {
workspaceId: fixture.workspaceId,
})),
);
- const { requestId } = await contactsInTeam(alice).sendRequest(bob);
- await new ContactModel(db, bob).acceptRequest(requestId);
+ await pair(alice, bob, fixture.workspaceId);
};
afterEach(async () => {
@@ -187,7 +196,7 @@ describe('a conversation with an external contact of a workspace', () => {
'Workspace member not found',
);
await expect(inTeam(carol).openPeer(bob, 'Mia')).rejects.toThrow('Workspace member not found');
- await contactsInTeam(carol).openTo(bob);
+ await pair(carol, bob, fixture.workspaceId);
expect(await inTeam(carol).openPeer(bob, 'Mia')).toBeDefined();
});
@@ -228,7 +237,7 @@ describe('a conversation with an external contact of a workspace', () => {
it('goes silent once the member closes themselves to them', async () => {
await inviteBob();
const { channel } = await inTeam(alice).openPeer(bob, 'Mia');
- await contactsInTeam(alice).removeUser(bob);
+ await dropContact(alice, bob);
await expect(
inTeam(bob).send(channel.id, { content: 'Hello?', requestKey: 'x', routing: 'fallback' }),
).rejects.toThrow('Workspace member not found');
diff --git a/packages/database/src/repositories/channel/__tests__/sharedAgent.test.ts b/packages/database/src/repositories/channel/__tests__/sharedAgent.test.ts
index 172bc1026d9..ca3e2be377e 100644
--- a/packages/database/src/repositories/channel/__tests__/sharedAgent.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/sharedAgent.test.ts
@@ -16,17 +16,18 @@ import {
userSettings,
} from '../../../schemas';
import { ChannelExecutionRepository, ChannelHistoryRepository, ChannelRepository } from '..';
+import { tableContacts } from './tableContacts';
import { createChannelFixture, jobsOf, lease, operationById } from './testUtils';
const db = await getTestDB();
-const fixture = createChannelFixture(db, 'channel-shared-agent');
+const fixture = createChannelFixture(db, 'channel-shared-agent', tableContacts);
const execution = new ChannelExecutionRepository(db);
// The fixture's member is the visitor; its owner shares an Agent.
const visitorId = fixture.memberId;
const ownerId = fixture.ownerId;
const agentId = 'agt_channel_shared';
-const visitor = new ChannelRepository(db, visitorId);
+const visitor = new ChannelRepository(db, visitorId, undefined, tableContacts);
let shareId: string;
@@ -195,15 +196,22 @@ describe('a contact’s shared Agent in a direct conversation', () => {
},
})
.where(eq(agents.id, agentId));
- const { channel } = await new ChannelRepository(db, visitorId, fixture.workspaceId).create({
+ const { channel } = await new ChannelRepository(
+ db,
+ visitorId,
+ fixture.workspaceId,
+ tableContacts,
+ ).create({
agentId,
sharedAgent: true,
title: 'Shared Helper',
});
- const message = await new ChannelRepository(db, visitorId, fixture.workspaceId).send(
- channel.id,
- { content: 'Hello', requestKey: 'routed', routing: 'fallback' },
- );
+ const message = await new ChannelRepository(
+ db,
+ visitorId,
+ fixture.workspaceId,
+ tableContacts,
+ ).send(channel.id, { content: 'Hello', requestKey: 'routed', routing: 'fallback' });
const [job] = await jobsOf(db, message.id);
const routedDevice = vi.fn(async () => ({ deviceId: 'owner-device', online: true }));
@@ -526,7 +534,7 @@ describe('a contact’s shared Agent in a direct conversation', () => {
});
describe('a shared Agent in the visitor’s workspace', () => {
- const inWorkspace = new ChannelRepository(db, visitorId, fixture.workspaceId);
+ const inWorkspace = new ChannelRepository(db, visitorId, fixture.workspaceId, tableContacts);
const open = async () => {
const { channel } = await inWorkspace.create({
diff --git a/packages/database/src/repositories/channel/__tests__/tableContacts.ts b/packages/database/src/repositories/channel/__tests__/tableContacts.ts
new file mode 100644
index 00000000000..197f950b32e
--- /dev/null
+++ b/packages/database/src/repositories/channel/__tests__/tableContacts.ts
@@ -0,0 +1,48 @@
+import { and, eq, isNull, or, sql } from 'drizzle-orm';
+
+import { userContacts, users } from '../../../schemas';
+import type { ChannelContacts } from '../contacts';
+import { ChannelError } from '../error';
+
+/**
+ * Test contacts read from `user_contacts` rows the test inserts: two people are contacts in a scope
+ * when both directions exist there. A card snapshots any existing person: whether the sender may
+ * share them is the address book's rule, tested with it.
+ */
+export const tableContacts: ChannelContacts = {
+ areMutualContacts: async (tx, workspaceId, userId, peerUserId) => {
+ const rows = await tx
+ .select({ userId: userContacts.userId })
+ .from(userContacts)
+ .where(
+ and(
+ eq(userContacts.type, 'user'),
+ workspaceId
+ ? eq(userContacts.workspaceId, workspaceId)
+ : isNull(userContacts.workspaceId),
+ or(
+ and(eq(userContacts.userId, userId), eq(userContacts.contactUserId, peerUserId)),
+ and(eq(userContacts.userId, peerUserId), eq(userContacts.contactUserId, userId)),
+ ),
+ ),
+ );
+ return rows.length >= 2;
+ },
+ mutualPersonalContactWhere: (userId, contactUserId) => {
+ const side = (from: unknown, to: unknown) =>
+ 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))!;
+ },
+ resolveCard: async (tx, _userId, _workspaceId, input) => {
+ if (input.type !== 'user') throw new ChannelError('FORBIDDEN', 'Share only your contacts');
+ const [user] = await tx.select().from(users).where(eq(users.id, input.userId)).limit(1);
+ if (!user) throw new ChannelError('FORBIDDEN', 'Share only your contacts');
+ return {
+ avatar: user.avatar,
+ name: user.fullName || user.username || user.id,
+ type: 'user',
+ userId: user.id,
+ username: user.username,
+ };
+ },
+};
diff --git a/packages/database/src/repositories/channel/__tests__/testUtils.ts b/packages/database/src/repositories/channel/__tests__/testUtils.ts
index dc754e701c2..cb6f7bb920f 100644
--- a/packages/database/src/repositories/channel/__tests__/testUtils.ts
+++ b/packages/database/src/repositories/channel/__tests__/testUtils.ts
@@ -12,6 +12,7 @@ import {
workspaces,
} from '../../../schemas';
import type { LobeChatDatabase } from '../../../type';
+import type { ChannelContacts } from '..';
import { ChannelRepository } from '..';
type AgentFixtureConfig = ChannelMemberConfig & {
@@ -46,7 +47,12 @@ export const lease = { serverDefaultAgentConfig: {}, leaseMs: 60_000, leaseOwner
* Users and a workspace for one test file. Each file passes its own prefix so files can
* share a server database.
*/
-export const createChannelFixture = (db: LobeChatDatabase, prefix: string) => {
+export const createChannelFixture = (
+ db: LobeChatDatabase,
+ prefix: string,
+ /** Who counts as a contact; nobody by default, as without an address book. */
+ contacts?: ChannelContacts,
+) => {
const ownerId = `${prefix}-owner`;
const memberId = `${prefix}-member`;
const workspaceId = `${prefix}-workspace`;
@@ -108,7 +114,7 @@ export const createChannelFixture = (db: LobeChatDatabase, prefix: string) => {
: { heterogeneousProvider: { type: config.runtime } },
})
.returning();
- return new ChannelRepository(db, ownerId, channel.workspaceId).addAgent(channelId, {
+ return new ChannelRepository(db, ownerId, channel.workspaceId, contacts).addAgent(channelId, {
agentId: source.id,
config,
name,
@@ -125,12 +131,12 @@ export const createChannelFixture = (db: LobeChatDatabase, prefix: string) => {
/** A workspace channel owned by `ownerId`, with `memberId` as a plain member. */
const createTeamChannel = async (title = 'Team') => {
- const asOwner = new ChannelRepository(db, ownerId, workspaceId);
+ const asOwner = new ChannelRepository(db, ownerId, workspaceId, contacts);
const { channel, member: owner } = await asOwner.create({ title });
const member = await addPerson(channel.id, memberId, 'member');
return {
- asMember: new ChannelRepository(db, memberId, workspaceId),
+ asMember: new ChannelRepository(db, memberId, workspaceId, contacts),
asOwner,
channel,
member,
diff --git a/packages/database/src/repositories/channel/__tests__/userMembers.test.ts b/packages/database/src/repositories/channel/__tests__/userMembers.test.ts
index cce18ce869e..cabe3082349 100644
--- a/packages/database/src/repositories/channel/__tests__/userMembers.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/userMembers.test.ts
@@ -5,10 +5,11 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
import { channelMembers, channels, userContacts, workspaceMembers } from '../../../schemas';
import { ChannelRepository } from '..';
+import { tableContacts } from './tableContacts';
import { createChannelFixture } from './testUtils';
const db = await getTestDB();
-const fixture = createChannelFixture(db, 'channel-user-members');
+const fixture = createChannelFixture(db, 'channel-user-members', tableContacts);
beforeEach(async () => {
await fixture.setup();
await db.insert(workspaceMembers).values([
@@ -29,7 +30,7 @@ const befriend = (a: string, b: string) =>
]);
const create = async () => {
- const owner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);
+ const owner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId, tableContacts);
const { channel } = await owner.create({ title: 'People' });
return { channel, owner };
};
@@ -44,7 +45,7 @@ describe('Channel human membership', () => {
expect(added).toMatchObject({ role: 'member', status: 'active', userId: fixture.memberId });
expect((await owner.addUser(channel.id, fixture.memberId)).id).toBe(added.id);
expect(await owner.userCandidates(channel.id)).toEqual([]);
- const member = new ChannelRepository(db, fixture.memberId, fixture.workspaceId);
+ const member = new ChannelRepository(db, fixture.memberId, fixture.workspaceId, tableContacts);
expect(await member.list()).toEqual([
expect.objectContaining({ id: channel.id, canDelete: false }),
]);
@@ -87,7 +88,7 @@ describe('Channel human membership', () => {
it('rejects wrong-scope, direct and trashed channels', async () => {
const { owner, channel } = await create();
- const personal = new ChannelRepository(db, fixture.ownerId);
+ const personal = new ChannelRepository(db, fixture.ownerId, undefined, tableContacts);
await expect(personal.addUser(channel.id, fixture.memberId)).rejects.toMatchObject({
code: 'NOT_FOUND',
});
@@ -130,7 +131,7 @@ describe('Channel human membership', () => {
describe('starting a Channel with people', () => {
it('lists everyone in the workspace except the creator, and adds the chosen people', async () => {
- const owner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);
+ const owner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId, tableContacts);
expect(await owner.newChannelUserCandidates()).toEqual([
expect.objectContaining({ userId: fixture.memberId, username: 'mia' }),
]);
@@ -152,7 +153,12 @@ describe('Channel human membership', () => {
]),
);
expect(members).toHaveLength(2);
- const member = new ChannelRepository(db, fixture.memberId, fixture.workspaceId);
+ const member = new ChannelRepository(
+ db,
+ fixture.memberId,
+ fixture.workspaceId,
+ tableContacts,
+ );
expect(await member.list()).toEqual([expect.objectContaining({ id: channel.id })]);
});
@@ -168,7 +174,7 @@ describe('Channel human membership', () => {
});
it('creates nothing when a chosen person is outside the workspace', async () => {
- const owner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);
+ const owner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId, tableContacts);
await expect(
owner.create({ title: 'People', userIds: [fixture.memberId, 'outside-user'] }),
).rejects.toMatchObject({ code: 'NOT_FOUND' });
@@ -190,7 +196,7 @@ describe('Channel human membership', () => {
.update(workspaceMembers)
.set({ deletedAt: new Date() })
.where(eq(workspaceMembers.userId, fixture.ownerId));
- const owner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);
+ const owner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId, tableContacts);
await expect(owner.newChannelUserCandidates()).rejects.toMatchObject({ code: 'NOT_FOUND' });
});
});
@@ -198,14 +204,14 @@ describe('Channel human membership', () => {
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);
+ const owner = new ChannelRepository(db, fixture.ownerId, undefined, tableContacts);
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);
+ const member = new ChannelRepository(db, fixture.memberId, undefined, tableContacts);
expect(await member.list()).toEqual([
expect.objectContaining({ id: channel.id, canDelete: false }),
]);
@@ -215,13 +221,13 @@ describe('Channel human membership', () => {
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(
- [],
- );
+ expect(
+ await new ChannelRepository(db, fixture.ownerId, fixture.workspaceId, tableContacts).list(),
+ ).toEqual([]);
});
it('invites mutual contacts into an existing group, and only them', async () => {
- const owner = new ChannelRepository(db, fixture.ownerId);
+ const owner = new ChannelRepository(db, fixture.ownerId, undefined, tableContacts);
const { channel } = await owner.create({ title: 'Friends' });
expect(await owner.userCandidates(channel.id)).toEqual([]);
await expect(owner.addUser(channel.id, fixture.memberId)).rejects.toMatchObject({
@@ -259,7 +265,7 @@ describe('Channel human membership', () => {
workspaceId: fixture.workspaceId,
},
]);
- const owner = new ChannelRepository(db, fixture.ownerId);
+ const owner = new ChannelRepository(db, fixture.ownerId, undefined, tableContacts);
expect(await owner.newChannelUserCandidates()).toEqual([]);
await expect(
owner.create({ title: 'Friends', userIds: [fixture.memberId] }),
diff --git a/packages/database/src/repositories/channel/contacts.ts b/packages/database/src/repositories/channel/contacts.ts
new file mode 100644
index 00000000000..654d4d41153
--- /dev/null
+++ b/packages/database/src/repositories/channel/contacts.ts
@@ -0,0 +1,38 @@
+import type { ContactCard, ContactCardInput } from '@lobechat/types';
+import type { SQL } from 'drizzle-orm';
+import { sql } from 'drizzle-orm';
+
+import type { Transaction } from '../../type';
+import { ChannelError } from './error';
+
+/**
+ * Who counts as a person's contact, for the checks Channel runs inside its own transactions. The
+ * server supplies it; without one nobody is a contact, so two people talk one-on-one only as
+ * fellow members of a workspace.
+ */
+export interface ChannelContacts {
+ /** Whether two people are contacts in a scope (`null` is the personal space), both ways. */
+ areMutualContacts: (
+ tx: Transaction,
+ workspaceId: string | null,
+ userId: string,
+ peerUserId: string,
+ ) => Promise<boolean>;
+ /** True for the people `userId` can bring into a personal group; `contactUserId` is a column. */
+ mutualPersonalContactWhere: (userId: string, contactUserId: SQL) => SQL;
+ /** The card a person shares into a conversation, checked and snapshotted as it is sent. */
+ resolveCard: (
+ tx: Transaction,
+ userId: string,
+ workspaceId: string | null,
+ input: ContactCardInput,
+ ) => Promise<ContactCard>;
+}
+
+export const noChannelContacts: ChannelContacts = {
+ areMutualContacts: async () => false,
+ mutualPersonalContactWhere: () => sql`false`,
+ resolveCard: async () => {
+ throw new ChannelError('FORBIDDEN', 'Contact cards are not available');
+ },
+};
diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.ts
index c9458a11093..12ec364b33f 100644
--- a/packages/database/src/repositories/channel/index.ts
+++ b/packages/database/src/repositories/channel/index.ts
@@ -37,6 +37,8 @@ import {
} from './agent';
import { openAgentPair } from './agentPair';
import { channelAvatarMembers } from './avatars';
+import type { ChannelContacts } from './contacts';
+import { noChannelContacts } from './contacts';
import { deleteMessage } from './delete';
import { findThread } from './delivery';
import { editMessage } from './edit';
@@ -44,7 +46,7 @@ import { ChannelError } from './error';
import { channelLastMessages } from './lastMessage';
import { leaveChannel, removeChannelMember } from './membership';
import { setMemberMuted } from './mute';
-import { findPeer, lockPeerPair, peerOf, requirePeerRelation } from './peer';
+import { openPeerConversation, peerOf } from './peer';
import { addChannelUser, channelUserCandidates, newChannelUserCandidates } from './people';
import type { ChannelAgentPostInput } from './post';
import { postAgentMessage } from './post';
@@ -88,6 +90,8 @@ export type {
ChannelRoutedDevice,
ChannelRoutedDeviceInput,
} from './claim';
+export type { ChannelContacts } from './contacts';
+export { noChannelContacts } from './contacts';
export type { ChannelErrorCode } from './error';
export { ChannelError } from './error';
export { ChannelExecutionRepository } from './execution';
@@ -134,6 +138,8 @@ export class ChannelRepository {
private readonly db: LobeChatDatabase,
private readonly userId: string,
workspaceId?: string | null,
+ /** Who counts as a contact for one-on-one and personal-group checks; nobody by default. */
+ private readonly contacts: ChannelContacts = noChannelContacts,
) {
this.workspaceId = normalizeWorkspaceId(workspaceId);
this.sections = new ChannelSectionRepository(db, userId, this.workspaceId);
@@ -199,7 +205,8 @@ export class ChannelRepository {
await addAgentMember(tx, channel, member, { agentId, config: params.agentConfig });
for (const agent of params.agents ?? []) await addAgentMember(tx, channel, member, agent);
const access = { channel, member } satisfies ChannelAccess;
- for (const userId of new Set(params.userIds)) await addChannelUser(tx, access, userId);
+ for (const userId of new Set(params.userIds))
+ await addChannelUser(tx, this.contacts, access, userId);
return access;
});
@@ -246,7 +253,8 @@ export class ChannelRepository {
name: bound.name ?? undefined,
});
for (const agent of params.agents ?? []) await addAgentMember(tx, channel, member, agent);
- for (const userId of new Set(params.userIds)) await addChannelUser(tx, access, userId);
+ for (const userId of new Set(params.userIds))
+ await addChannelUser(tx, this.contacts, access, userId);
return access;
},
{ minRole: 'admin' },
@@ -396,7 +404,9 @@ export class ChannelRepository {
};
addUser = async (channelId: string, userId: string) =>
- this.write(channelId, (tx, access) => addChannelUser(tx, access, userId), { minRole: 'admin' });
+ this.write(channelId, (tx, access) => addChannelUser(tx, this.contacts, access, userId), {
+ minRole: 'admin',
+ });
/** Removes a person or an Agent; returns the writers still to stop. See {@link removeChannelMember}. */
removeMember = async (channelId: string, memberId: string): Promise<ChannelJobItem[]> =>
@@ -423,13 +433,17 @@ export class ChannelRepository {
/** 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),
+ newChannelUserCandidates(tx, this.contacts, this.workspaceId, this.userId, search),
);
userCandidates = async (channelId: string, search?: string) =>
- this.write(channelId, (tx, access) => channelUserCandidates(tx, access, search), {
- minRole: 'admin',
- });
+ this.write(
+ channelId,
+ (tx, access) => channelUserCandidates(tx, this.contacts, access, search),
+ {
+ minRole: 'admin',
+ },
+ );
/** Messages in a Channel the caller can read, its live Threads included, matching `query`. */
searchMessages = async (channelId: string, options: ChannelSearchOptions) => {
@@ -739,36 +753,14 @@ export class ChannelRepository {
* existing conversation opens as it is, trashed or not.
*/
openPeer = (peerUserId: string, title: string): Promise<ChannelAccess> =>
- this.db.transaction(async (tx) => {
- if (peerUserId === this.userId)
- throw new ChannelError('BAD_REQUEST', 'You cannot message yourself');
- await requirePeerRelation(tx, this.workspaceId, this.userId, peerUserId);
- // No unique index keeps one conversation per pair: serialize opening it, so two people
- // opening it at once (or one twice) find the first one instead of creating a second.
- await lockPeerPair(tx, this.workspaceId, this.userId, peerUserId);
- const existing = await findPeer(tx, this.workspaceId, this.userId, peerUserId);
- if (existing) return existing;
-
- const [channel] = await tx
- .insert(channels)
- .values({
- peerUserId,
- title,
- userId: this.userId,
- visibility: 'private',
- workspaceId: this.workspaceId,
- })
- .returning();
- const member = await this.addOwner(tx, channel.id);
- await tx.insert(channelMembers).values({
- actorType: 'user',
- channelId: channel.id,
- lastReadSequence: 0,
- role: 'owner',
- userId: peerUserId,
- });
- return { channel, member };
- });
+ this.db.transaction((tx) =>
+ openPeerConversation(tx, this.contacts, {
+ peerUserId,
+ title,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ }),
+ );
/** The conversation in which one of the caller's Agents asks another. See {@link openAgentPair}. */
openAgentPair = (params: Parameters<typeof openAgentPair>[2]): Promise<ChannelAgentPairAccess> =>
@@ -919,7 +911,9 @@ export class ChannelRepository {
/** Posts a message as the caller. See {@link sendMessage} for routing. */
/** Sending into an open project Channel joins it first. */
send = async (channelId: string, input: ChannelSendInput): Promise<ChannelMessageItem> =>
- this.write(channelId, (tx, access) => sendMessage(tx, access, input), { joinOpen: true });
+ this.write(channelId, (tx, access) => sendMessage(tx, access, input, this.contacts), {
+ joinOpen: true,
+ });
/**
* Stops one job (its requester or an admin) or a branch: everything for admins, only the
diff --git a/packages/database/src/repositories/channel/peer.ts b/packages/database/src/repositories/channel/peer.ts
index 7e87ed8a64c..ba58d244a1c 100644
--- a/packages/database/src/repositories/channel/peer.ts
+++ b/packages/database/src/repositories/channel/peer.ts
@@ -1,37 +1,12 @@
import { and, eq, isNull, or, sql } from 'drizzle-orm';
import type { ChannelItem } from '../../schemas';
-import { channelMembers, channels, userContacts, workspaceMembers } from '../../schemas';
+import { channelMembers, channels, workspaceMembers } from '../../schemas';
import type { Transaction } from '../../type';
+import type { ChannelContacts } from './contacts';
import { ChannelError } from './error';
import type { ChannelAccess } from './types';
-/**
- * Whether two people are contacts in a scope, both directions still holding. Removing a contact
- * silences their conversation without deleting its history.
- */
-const areMutualContacts = async (
- tx: Transaction,
- workspaceId: string | null,
- userId: string,
- peerUserId: string,
-) => {
- const rows = await tx
- .select({ userId: userContacts.userId })
- .from(userContacts)
- .where(
- and(
- eq(userContacts.type, 'user'),
- workspaceId ? eq(userContacts.workspaceId, workspaceId) : isNull(userContacts.workspaceId),
- or(
- and(eq(userContacts.userId, userId), eq(userContacts.contactUserId, peerUserId)),
- and(eq(userContacts.userId, peerUserId), eq(userContacts.contactUserId, userId)),
- ),
- ),
- );
- return rows.length >= 2;
-};
-
/** Whether `userId` is an active member of the workspace. */
export const isWorkspaceMember = async (tx: Transaction, workspaceId: string, userId: string) => {
const [member] = await tx
@@ -56,12 +31,13 @@ export const isWorkspaceMember = async (tx: Transaction, workspaceId: string, us
*/
export const requirePeerRelation = async (
tx: Transaction,
+ contacts: ChannelContacts,
workspaceId: string | null,
userId: string,
peerUserId: string,
) => {
if (!workspaceId) {
- if (!(await areMutualContacts(tx, null, userId, peerUserId)))
+ if (!(await contacts.areMutualContacts(tx, null, userId, peerUserId)))
throw new ChannelError('FORBIDDEN', 'You are not contacts');
return;
}
@@ -73,7 +49,7 @@ export const requirePeerRelation = async (
// An external contact talks only with the members paired with them, never another outsider.
if (
(userIsMember || peerIsMember) &&
- (await areMutualContacts(tx, workspaceId, userId, peerUserId))
+ (await contacts.areMutualContacts(tx, workspaceId, userId, peerUserId))
)
return;
throw new ChannelError('NOT_FOUND', 'Workspace member not found');
@@ -126,3 +102,49 @@ export const findPeer = async (
.limit(1);
return row as ChannelAccess | undefined;
};
+
+/**
+ * Opens the pair's conversation, or finds the one that exists, trashed or not. Both people join
+ * it; whoever opens it first owns it.
+ */
+export const openPeerConversation = async (
+ tx: Transaction,
+ contacts: ChannelContacts,
+ {
+ peerUserId,
+ title,
+ userId,
+ workspaceId,
+ }: { peerUserId: string; title: string; userId: string; workspaceId: string | null },
+): Promise<ChannelAccess> => {
+ if (peerUserId === userId) throw new ChannelError('BAD_REQUEST', 'You cannot message yourself');
+ await requirePeerRelation(tx, contacts, workspaceId, userId, peerUserId);
+ // No unique index keeps one conversation per pair: serialize opening it, so two people
+ // opening it at once (or one twice) find the first one instead of creating a second.
+ await lockPeerPair(tx, workspaceId, userId, peerUserId);
+ const existing = await findPeer(tx, workspaceId, userId, peerUserId);
+ if (existing) return existing;
+
+ const [channel] = await tx
+ .insert(channels)
+ .values({ peerUserId, title, userId, visibility: 'private', workspaceId })
+ .returning();
+ const [member] = await tx
+ .insert(channelMembers)
+ .values({
+ actorType: 'user',
+ channelId: channel.id,
+ lastReadSequence: 0,
+ role: 'owner',
+ userId,
+ })
+ .returning();
+ await tx.insert(channelMembers).values({
+ actorType: 'user',
+ channelId: channel.id,
+ lastReadSequence: 0,
+ role: 'owner',
+ userId: peerUserId,
+ });
+ return { channel, member };
+};
diff --git a/packages/database/src/repositories/channel/people.ts b/packages/database/src/repositories/channel/people.ts
index d8920393dae..93b76c7feac 100644
--- a/packages/database/src/repositories/channel/people.ts
+++ b/packages/database/src/repositories/channel/people.ts
@@ -1,9 +1,10 @@
import type { SQL } from 'drizzle-orm';
import { and, asc, eq, isNull, ne, notExists, or, sql } from 'drizzle-orm';
-import { channelMembers, userContacts, users, workspaceMembers } from '../../schemas';
+import { channelMembers, users, workspaceMembers } from '../../schemas';
import type { Transaction } from '../../type';
import { ilikeContains } from '../../utils/like';
+import type { ChannelContacts } from './contacts';
import { ChannelError } from './error';
import { requirePeerRelation } from './peer';
import { audit } from './transaction';
@@ -28,13 +29,6 @@ export const requireWorkspaceMember = async (
if (!member) throw new ChannelError('NOT_FOUND', 'Workspace member not found');
};
-/** 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))!;
-};
-
/** Only group Channels take people; a direct conversation starts a group instead. */
const requireGroup = ({ channel }: ChannelAccess) => {
if (channel.agentId || channel.peerUserId)
@@ -47,6 +41,7 @@ const requireGroup = ({ channel }: ChannelAccess) => {
*/
const userCandidates = async (
tx: Transaction,
+ contacts: ChannelContacts,
workspaceId: string | null,
userId: string,
exclude: SQL,
@@ -75,7 +70,7 @@ const userCandidates = async (
return scoped
.where(
and(
- workspaceId ? undefined : mutualPersonalContact(userId, sql`${users.id}`),
+ workspaceId ? undefined : contacts.mutualPersonalContactWhere(userId, sql`${users.id}`),
ne(users.id, userId),
exclude,
query
@@ -94,11 +89,13 @@ const userCandidates = async (
*/
export const channelUserCandidates = async (
tx: Transaction,
+ contacts: ChannelContacts,
{ channel, member }: ChannelAccess,
search = '',
) =>
userCandidates(
tx,
+ contacts,
channel.workspaceId,
member.userId!,
notExists(
@@ -119,10 +116,11 @@ export const channelUserCandidates = async (
/** The people a new Channel in this scope can start with: everyone the creator can bring in. */
export const newChannelUserCandidates = (
tx: Transaction,
+ contacts: ChannelContacts,
workspaceId: string | null,
userId: string,
search = '',
-) => userCandidates(tx, workspaceId, userId, sql`true`, search);
+) => userCandidates(tx, contacts, workspaceId, userId, sql`true`, search);
/**
* Member metadata naming who added the member, merged into what it already holds. A null inviter,
@@ -133,7 +131,12 @@ export const memberInviterMetadata = (invitedBy: string | null) =>
? sql`coalesce(${channelMembers.metadata}, '{}'::jsonb) || jsonb_build_object('invitedBy', ${invitedBy}::text)`
: sql`coalesce(${channelMembers.metadata}, '{}'::jsonb) - 'invitedBy'`;
-export const addChannelUser = async (tx: Transaction, access: ChannelAccess, userId: string) => {
+export const addChannelUser = async (
+ tx: Transaction,
+ contacts: ChannelContacts,
+ access: ChannelAccess,
+ userId: string,
+) => {
requireGroup(access);
const { workspaceId } = access.channel;
const inviterId = access.member.userId!;
@@ -142,7 +145,7 @@ export const addChannelUser = async (tx: Transaction, access: ChannelAccess, use
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);
+ await requirePeerRelation(tx, contacts, null, inviterId, userId);
}
const [existing] = await tx
.select()
diff --git a/packages/database/src/repositories/channel/send.ts b/packages/database/src/repositories/channel/send.ts
index 89edcde5319..8340190e91c 100644
--- a/packages/database/src/repositories/channel/send.ts
+++ b/packages/database/src/repositories/channel/send.ts
@@ -2,14 +2,14 @@ import type { ChannelMessageMetadata, ChannelRoutingMode, ContactCardInput } fro
import { CHANNEL_LIMITS, contactCardOf, contactCardText } from '@lobechat/types';
import { and, asc, eq, inArray, sql } from 'drizzle-orm';
-import { ContactModel } from '../../models/contact';
import type { ChannelMessageItem } from '../../schemas';
import { channelMembers, channelMessages, channelThreads, files } from '../../schemas';
-import type { LobeChatDatabase, Transaction } from '../../type';
+import type { Transaction } from '../../type';
import { isUuid } from '../../utils/uuid';
import { buildWorkspaceWhere } from '../../utils/workspace';
import { sharedAgentOwner } from './agent';
import { attachFiles, fileIdsByMessage } from './attachments';
+import type { ChannelContacts } from './contacts';
import {
activeMembers,
appendMessage,
@@ -112,6 +112,7 @@ export const sendMessage = async (
tx: Transaction,
{ channel, member }: ChannelAccess,
input: ChannelSendInput,
+ contacts: ChannelContacts,
): Promise<ChannelMessageItem> => {
const { fileIds, mentions } = validateSendInput(input);
const author = await requestAuthor(tx, channel, input.authorAgentMemberId);
@@ -194,6 +195,7 @@ export const sendMessage = async (
if (channel.peerUserId && member.userId)
await requirePeerRelation(
tx,
+ contacts,
channel.workspaceId,
member.userId,
peerOf(channel, member.userId)!,
@@ -324,12 +326,7 @@ export const sendMessage = async (
// Resolved only for a new message: a retry returns the original card as it was sent.
const card =
- input.card &&
- (await new ContactModel(
- tx as unknown as LobeChatDatabase,
- member.userId!,
- channel.workspaceId,
- ).resolveCard(input.card));
+ input.card && (await contacts.resolveCard(tx, member.userId!, channel.workspaceId, input.card));
const metadata = card ? { ...input.metadata, card } : input.metadata;
const message = await appendMessage(tx, {
diff --git a/src/business/client/features/ShareOwnerContactCard.tsx b/src/business/client/features/ShareOwnerContactCard.tsx
new file mode 100644
index 00000000000..d9297f57fa8
--- /dev/null
+++ b/src/business/client/features/ShareOwnerContactCard.tsx
@@ -0,0 +1,11 @@
+import type { ContactUserProfile } from '@lobechat/types';
+
+export interface ShareOwnerContactCardProps {
+ /** The shared Agent's creator, whose limit refused the reply. */
+ owner: ContactUserProfile;
+}
+
+/** The creator's card a refused visitor can act on, to ask them for more. Cloud only. */
+export default function ShareOwnerContactCard(_props: ShareOwnerContactCardProps) {
+ return null;
+}
diff --git a/src/business/server/contact/addressBook.ts b/src/business/server/contact/addressBook.ts
new file mode 100644
index 00000000000..7731aa49a8e
--- /dev/null
+++ b/src/business/server/contact/addressBook.ts
@@ -0,0 +1,63 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import type { ContactCard, ContactCardInput, ContactUserProfile } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import type { SQL } from 'drizzle-orm';
+import { sql } from 'drizzle-orm';
+
+import type { Transaction } from '@/database/type';
+
+/** Another person's Agent the caller reached through its share and may talk to directly. */
+export interface AddressBookAgentAccess {
+ agentId: string;
+ name: string | null;
+ ownerId: string;
+ shareId: string;
+ title: string | null;
+ workspaceId: string | null;
+}
+
+/**
+ * What Channel and Agent Share ask of a person's address book in one scope: who they can reach
+ * one-on-one, the Agents they reached through a share, and who a share's device grant may name.
+ */
+export interface AddressBook {
+ filterAddressBookPeople: (userIds: string[]) => Promise<string[]>;
+ findAgentAccess: (agentId: string) => Promise<AddressBookAgentAccess | undefined>;
+ findUser: (userId: string) => Promise<ContactUserProfile | undefined>;
+ listAddressBookPeople: () => Promise<ContactUserProfile[]>;
+ listPeople: (options: {
+ limit: number;
+ query?: string;
+ }) => Promise<{ hasMore: boolean; people: ContactUserProfile[] }>;
+ resolveCard: (input: ContactCardInput) => Promise<ContactCard>;
+}
+
+/** Without an address book nobody is a contact: every list is empty and no card can be shared. */
+const emptyAddressBook: AddressBook = {
+ filterAddressBookPeople: async () => [],
+ findAgentAccess: async () => undefined,
+ findUser: async () => undefined,
+ listAddressBookPeople: async () => [],
+ listPeople: async () => ({ hasMore: false, people: [] }),
+ resolveCard: async () => {
+ throw new TRPCError({ code: 'FORBIDDEN', message: 'Contact cards are not available' });
+ },
+};
+
+export const getAddressBook = (
+ _db: LobeChatDatabase,
+ _userId: string,
+ _workspaceId?: string | null,
+): AddressBook => emptyAddressBook;
+
+/** Whether two people are contacts in a scope (`null` is the personal space), both ways. */
+export const areMutualContacts = async (
+ _db: LobeChatDatabase | Transaction,
+ _workspaceId: string | null,
+ _userId: string,
+ _peerUserId: string,
+): Promise<boolean> => false;
+
+/** True for the people `userId` can bring into a personal group; `contactUserId` is a column. */
+export const mutualPersonalContactWhere = (_userId: string, _contactUserId: SQL | string): SQL =>
+ sql`false`;
diff --git a/src/business/server/contact/notifyActivity.ts b/src/business/server/contact/notifyActivity.ts
deleted file mode 100644
index 77ab77666ca..00000000000
--- a/src/business/server/contact/notifyActivity.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-/**
- * A contact request reached a person: `received` is a new request to them, `accepted` means
- * the request they sent was accepted. Fired once per outcome.
- */
-export interface NotifyContactRequestParams {
- /** Who sent the request (`received`) or accepted it (`accepted`). */
- actorUserId: string;
- kind: 'accepted' | 'received';
- recipientUserId: string;
- requestId: string;
-}
-
-export const notifyContactRequest = (_params: NotifyContactRequestParams): Promise<void> =>
- Promise.resolve();
diff --git a/src/features/Channels/ShareRefusalNotice.tsx b/src/features/Channels/ShareRefusalNotice.tsx
index a61ed090301..cc8c2ee07ff 100644
--- a/src/features/Channels/ShareRefusalNotice.tsx
+++ b/src/features/Channels/ShareRefusalNotice.tsx
@@ -1,101 +1,17 @@
import type { ContactUserProfile } from '@lobechat/types';
-import { Button, Flexbox, Icon, Text } from '@lobehub/ui';
-import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import { Flexbox, Icon } from '@lobehub/ui';
import * as stylex from '@stylexjs/stylex';
-import { CircleAlert, UserPlus } from 'lucide-react';
-import { useState } from 'react';
+import { CircleAlert } from 'lucide-react';
import { useTranslation } from 'react-i18next';
-import AsyncError from '@/components/AsyncError';
-import UserAvatar from '@/components/UserAvatar';
-import { contactService } from '@/services/contact';
+import ShareOwnerContactCard from '@/business/client/features/ShareOwnerContactCard';
import { receiptErrorKey } from './MessageReceipts';
-import type { ContactRequestOutcome } from './shareRefusal';
-import { contactRequestOutcome } from './shareRefusal';
import { statusStyles, toneStyles } from './styles';
-const styles = stylex.create({
- // Grows with a long name instead of cutting it short; the conversation width still caps it.
- card: {
- width: 'fit-content',
- minWidth: 280,
- maxWidth: '100%',
- paddingBlock: 10,
- paddingInline: 12,
- borderWidth: 1,
- borderStyle: 'solid',
- borderColor: cssVar.colorBorderSecondary,
- borderRadius: 8,
- backgroundColor: cssVar.colorBgContainer,
- },
- identity: { flex: '1', minWidth: 0 },
- name: { fontWeight: 500 },
-});
-
-const OUTCOME_KEYS = {
- added: 'shareRefusal.added',
- alreadyContact: 'shareRefusal.alreadyContact',
- requestSent: 'shareRefusal.requestSent',
-} as const satisfies Record<ContactRequestOutcome, string>;
-
-/** The shared Agent's creator as a contact card the visitor can add, to ask them for more. */
-function OwnerContactCard({ owner }: { owner: ContactUserProfile }) {
- const { t } = useTranslation('channel');
- const [sending, setSending] = useState(false);
- const [outcome, setOutcome] = useState<ContactRequestOutcome>();
- const [error, setError] = useState<unknown>();
- const name = owner.fullName || owner.username;
-
- const addOwner = async () => {
- setSending(true);
- setError(undefined);
- try {
- setOutcome(contactRequestOutcome({ result: await contactService.sendRequest(owner.id) }));
- } catch (cause) {
- const settled = contactRequestOutcome({ error: cause });
- if (settled) setOutcome(settled);
- else {
- console.error('Failed to ask the shared Agent creator to be a contact', cause);
- setError(cause);
- }
- } finally {
- setSending(false);
- }
- };
-
- return (
- <Flexbox gap={8} {...stylex.props(styles.card)}>
- <Flexbox horizontal align="center" gap={10}>
- <UserAvatar avatar={owner.avatar} name={name} shape="circle" size={36} />
- <Flexbox {...stylex.props(styles.identity)}>
- <Text ellipsis {...stylex.props(styles.name)}>
- {name}
- </Text>
- <Text ellipsis fontSize={12} type="secondary">
- {owner.username
- ? `${t('shareRefusal.ownerCaption')} Β· @${owner.username}`
- : t('shareRefusal.ownerCaption')}
- </Text>
- </Flexbox>
- {outcome ? (
- <Text fontSize={12} type="secondary">
- {t(OUTCOME_KEYS[outcome])}
- </Text>
- ) : (
- <Button icon={UserPlus} loading={sending} size="small" onClick={() => void addOwner()}>
- {t('shareRefusal.addOwner')}
- </Button>
- )}
- </Flexbox>
- {error !== undefined && <AsyncError error={error} variant="inline" />}
- </Flexbox>
- );
-}
-
/**
* Below a visitor's message whose reply a shared Agent's limit refused: why, and the creator's
- * contact card when the limit is theirs to raise. There is no retry; the limit still holds.
+ * card when the limit is theirs to raise. There is no retry; the limit still holds.
*/
export function ShareRefusalNotice({
errorType,
@@ -113,7 +29,7 @@ export function ShareRefusalNotice({
<Icon icon={CircleAlert} size={12} />
{reasonKey ? t(reasonKey) : t('receipt.errorUnavailable')}
</span>
- {owner && <OwnerContactCard owner={owner} />}
+ {owner && <ShareOwnerContactCard owner={owner} />}
</Flexbox>
);
}
diff --git a/src/features/Channels/shareRefusal.test.ts b/src/features/Channels/shareRefusal.test.ts
index 9dcb1ee18b6..e4dcdb8970b 100644
--- a/src/features/Channels/shareRefusal.test.ts
+++ b/src/features/Channels/shareRefusal.test.ts
@@ -1,8 +1,7 @@
import { ChatErrorType } from '@lobechat/types';
-import { TRPCClientError } from '@trpc/client';
import { describe, expect, it } from 'vitest';
-import { contactRequestOutcome, shareRefusalOf, withoutShareRefusals } from './shareRefusal';
+import { shareRefusalOf, withoutShareRefusals } from './shareRefusal';
const owner = { avatar: null, fullName: 'Ada', id: 'owner', username: 'ada' };
@@ -60,24 +59,6 @@ describe('shareRefusalOf', () => {
});
});
-describe('contactRequestOutcome', () => {
- it('reads an accepted or pending request', () => {
- expect(contactRequestOutcome({ result: { status: 'accepted' } })).toBe('added');
- expect(contactRequestOutcome({ result: { status: 'pending' } })).toBe('requestSent');
- });
-
- it('treats a conflict as already reaching the owner, and anything else as an error', () => {
- expect(
- contactRequestOutcome({
- error: new TRPCClientError('Already a contact', {
- result: { error: { data: { code: 'CONFLICT' } } },
- } as any),
- }),
- ).toBe('alreadyContact');
- expect(contactRequestOutcome({ error: new Error('network') })).toBeUndefined();
- });
-});
-
describe('withoutShareRefusals', () => {
const refused = {
errorType: ChatErrorType.ShareMessageLimitExceeded,
diff --git a/src/features/Channels/shareRefusal.ts b/src/features/Channels/shareRefusal.ts
index 77314f271d7..fbe76f55956 100644
--- a/src/features/Channels/shareRefusal.ts
+++ b/src/features/Channels/shareRefusal.ts
@@ -1,6 +1,5 @@
import type { ChannelDetail, ChannelPublicJob, ContactUserProfile } from '@lobechat/types';
import { ChatErrorType } from '@lobechat/types';
-import { TRPCClientError } from '@trpc/client';
/**
* The share refusals a visitor reads beside their message instead of behind a failure mark,
@@ -46,17 +45,3 @@ export const shareRefusalOf = (
...(SHARE_REFUSALS[job.errorType].addOwner && { owner }),
};
};
-
-export type ContactRequestOutcome = 'added' | 'alreadyContact' | 'requestSent';
-
-/**
- * What asking the owner to be a contact settled as. Undefined for a failure the visitor should
- * see as an error; a conflict means they already reach the owner (a contact or a colleague).
- */
-export const contactRequestOutcome = (
- settled: { result: { status: 'accepted' | 'pending' } } | { error: unknown },
-): ContactRequestOutcome | undefined => {
- if ('result' in settled) return settled.result.status === 'accepted' ? 'added' : 'requestSent';
- if (settled.error instanceof TRPCClientError && settled.error.data?.code === 'CONFLICT')
- return 'alreadyContact';
-};
diff --git a/src/services/contact.ts b/src/services/contact.ts
deleted file mode 100644
index 326d3e2a05f..00000000000
--- a/src/services/contact.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { lambdaClient } from '@/libs/trpc/client';
-
-class ContactService {
- /** Asks a person to become a contact; accepts at once when they already asked. */
- sendRequest = (userId: string) => lambdaClient.contact.sendRequest.mutate({ userId });
-}
-
-export const contactService = new ContactService();