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.

✨ feat(contact): share a person or an Agent into a Channel as a card (#23426)

Arvin Xu479ae3060dfe
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.ts
index 5fd3cd85caf..156ec6e17e6 100644
--- a/apps/server/src/routers/lambda/channel.ts
+++ b/apps/server/src/routers/lambda/channel.ts
@@ -446,6 +446,13 @@ export const channelRouter = router({
send: externalChannelProcedure
.input(
z.object({
+ /** Share a contact as a card; the server writes the content and the card snapshot. */
+ card: z
+ .discriminatedUnion('type', [
+ z.object({ type: z.literal('user'), userId: z.string().min(1) }),
+ z.object({ agentId: z.string().min(1), type: z.literal('agent') }),
+ ])
+ .optional(),
channelId,
content: z.string().max(CHANNEL_LIMITS.contentLength),
fileIds: z.array(z.string().min(1)).max(CHANNEL_LIMITS.attachments).optional(),
diff --git a/apps/server/src/routers/lambda/contact.ts b/apps/server/src/routers/lambda/contact.ts
index 2d35837fb77..e2abef18934 100644
--- a/apps/server/src/routers/lambda/contact.ts
+++ b/apps/server/src/routers/lambda/contact.ts
@@ -71,12 +71,16 @@ export const contactRouter = router({
.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);
+ 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({
diff --git a/packages/database/src/models/__tests__/contact.test.ts b/packages/database/src/models/__tests__/contact.test.ts
index aff56d20700..cc4d27d47ad 100644
--- a/packages/database/src/models/__tests__/contact.test.ts
+++ b/packages/database/src/models/__tests__/contact.test.ts
@@ -6,6 +6,9 @@ import { getTestDB } from '../../core/getTestDB';
import {
agents,
agentShares,
+ channelMembers,
+ channelMessages,
+ channels,
userContactRequests,
userContacts,
users,
@@ -617,3 +620,116 @@ describe('removing an external contact who is not one', () => {
);
});
});
+
+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('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('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
index 813a8f6679e..6e3e56fbde1 100644
--- a/packages/database/src/models/contact.ts
+++ b/packages/database/src/models/contact.ts
@@ -1,14 +1,18 @@
import type {
ContactAgentItem,
ContactAgentProfile,
+ ContactCard,
+ ContactCardInput,
ContactItem,
ContactRelation,
ContactRequestItem,
+ ContactRequestSource,
ContactSearchResult,
ContactUserItem,
ContactUserProfile,
ContactWorkspace,
} from '@lobechat/types';
+import { channelMessageDeletedAt, contactCardOf } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import type { SQLWrapper } from 'drizzle-orm';
import { and, desc, eq, exists, inArray, isNotNull, isNull, not, or, sql } from 'drizzle-orm';
@@ -17,6 +21,8 @@ import { alias } from 'drizzle-orm/pg-core';
import {
agents,
agentShares,
+ channelMembers,
+ channelMessages,
userContactRequests,
userContacts,
users,
@@ -37,6 +43,7 @@ const userProfileColumns = {
};
const owners = alias(users, 'contact_agent_owner');
+const referrers = alias(users, 'contact_request_referrer');
/** Who the caller is in the active scope. */
type ScopeRole = 'personal' | 'member' | 'external';
@@ -450,6 +457,7 @@ export class ContactModel {
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' });
@@ -500,12 +508,16 @@ export class ContactModel {
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 });
@@ -543,7 +555,13 @@ export class ContactModel {
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,
@@ -555,6 +573,10 @@ export class ContactModel {
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));
@@ -563,6 +585,20 @@ export class ContactModel {
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 ?? '' }
@@ -776,6 +812,97 @@ export class ContactModel {
);
}
+ /**
+ * 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> => {
+ if (!isUuid(messageId)) return;
+ const [row] = await tx
+ .select({
+ channelId: channelMessages.channelId,
+ 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 ||
+ channelMessageDeletedAt(row.metadata) ||
+ card?.type !== 'user' ||
+ card.userId !== addresseeId
+ )
+ return;
+ return { channelId: row.channelId, messageId, referrerId: row.senderId, type: '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: any Agent whose link share is
+ * on, since anyone signed in can add it anyway; the caller's own Agent with sharing off is
+ * refused so sharing it never publishes it by surprise.
+ */
+ 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,
+ and(eq(agentShares.agentId, agents.id), eq(agentShares.visibility, 'link')),
+ )
+ .leftJoin(owners, eq(owners.id, agents.userId))
+ .where(and(eq(agents.id, input.agentId), notTrashed(agents.isDeleted)))
+ .limit(1);
+ if (!row?.shareId) {
+ if (row?.ownerId === this.userId)
+ 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,
+ name: profile.title,
+ 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). */
diff --git a/packages/database/src/repositories/channel/__tests__/cardMessage.test.ts b/packages/database/src/repositories/channel/__tests__/cardMessage.test.ts
new file mode 100644
index 00000000000..4f019ca5d95
--- /dev/null
+++ b/packages/database/src/repositories/channel/__tests__/cardMessage.test.ts
@@ -0,0 +1,100 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { userContactRequests, users, workspaceMembers } from '../../../schemas';
+import { createChannelFixture } from './testUtils';
+
+const db = await getTestDB();
+const fixture = createChannelFixture(db, 'channel-card');
+beforeEach(async () => {
+ await fixture.setup();
+ // Cards check the address book, which counts fellow workspace members.
+ await db.insert(workspaceMembers).values([
+ { role: 'owner', userId: fixture.ownerId, workspaceId: fixture.workspaceId },
+ { role: 'member', userId: fixture.memberId, workspaceId: fixture.workspaceId },
+ ]);
+});
+afterEach(async () => {
+ await db.delete(userContactRequests);
+ await fixture.cleanup();
+});
+
+describe('a contact card message', () => {
+ it('stores the server snapshot and writes the text fallback itself', async () => {
+ const { asOwner, channel } = await fixture.createTeamChannel();
+ const sent = await asOwner.send(channel.id, {
+ card: { type: 'user', userId: fixture.memberId },
+ content: '',
+ requestKey: 'card',
+ routing: 'fallback',
+ });
+
+ expect(sent.content).toBe('[Contact card] mia');
+ const [seen] = (await asOwner.detail(channel.id)).messages;
+ expect(seen.card).toEqual({
+ avatar: null,
+ name: 'mia',
+ type: 'user',
+ userId: fixture.memberId,
+ username: 'mia',
+ });
+ });
+
+ it('refuses a person the sender may not share, and attachments', async () => {
+ const { asOwner, channel } = await fixture.createTeamChannel();
+ await expect(
+ asOwner.send(channel.id, {
+ card: { type: 'user', userId: 'nobody' },
+ content: '',
+ requestKey: 'stranger',
+ routing: 'fallback',
+ }),
+ ).rejects.toThrow('Share only your contacts');
+ await expect(
+ asOwner.send(channel.id, {
+ card: { type: 'user', userId: fixture.memberId },
+ content: '',
+ fileIds: ['file'],
+ requestKey: 'files',
+ routing: 'fallback',
+ }),
+ ).rejects.toThrow('A card goes without attachments');
+ });
+
+ it('matches a retry by the contact, not its snapshot', async () => {
+ const { asOwner, channel } = await fixture.createTeamChannel();
+ const input = {
+ card: { type: 'user' as const, userId: fixture.memberId },
+ content: '',
+ requestKey: 'retry',
+ routing: 'fallback' as const,
+ };
+ const sent = await asOwner.send(channel.id, input);
+ // A rename since the first attempt does not turn the retry into a conflict.
+ await db.update(users).set({ fullName: 'Mia Renamed' }).where(eq(users.id, fixture.memberId));
+
+ await expect(asOwner.send(channel.id, input)).resolves.toMatchObject({
+ content: '[Contact card] mia',
+ id: sent.id,
+ });
+ await expect(
+ asOwner.send(channel.id, { ...input, card: { type: 'user', userId: fixture.ownerId } }),
+ ).rejects.toMatchObject({ code: 'CONFLICT' });
+ });
+
+ it('drops the card with the message', async () => {
+ const { asMember, asOwner, channel } = await fixture.createTeamChannel();
+ const sent = await asMember.send(channel.id, {
+ card: { type: 'user', userId: fixture.ownerId },
+ content: '',
+ requestKey: 'gone',
+ routing: 'fallback',
+ });
+ await asMember.deleteMessage(channel.id, sent.id);
+
+ const [seen] = (await asOwner.detail(channel.id)).messages;
+ expect(seen.card).toBeNull();
+ });
+});
diff --git a/packages/database/src/repositories/channel/delete.ts b/packages/database/src/repositories/channel/delete.ts
index 1f67aa15991..7443301f280 100644
--- a/packages/database/src/repositories/channel/delete.ts
+++ b/packages/database/src/repositories/channel/delete.ts
@@ -1,3 +1,4 @@
+import type { ChannelMessageMetadata } from '@lobechat/types';
import { channelMessageDeletedAt } from '@lobechat/types';
import { and, eq, inArray, sql } from 'drizzle-orm';
@@ -18,6 +19,11 @@ import { OPEN_JOB_STATUSES } from './writer';
*
* Returns the jobs whose writer is still held: the caller must stop them physically.
*/
+const omitCard = (metadata: ChannelMessageMetadata | null) => {
+ const { card: _card, ...rest } = metadata ?? {};
+ return rest;
+};
+
export const deleteMessage = async (
tx: Transaction,
channelId: string,
@@ -54,7 +60,8 @@ export const deleteMessage = async (
.set({
content: '',
mentions: [],
- metadata: { ...message.metadata, deletedAt: new Date().toISOString() },
+ // A shared card is the message's payload, so it goes with the text.
+ metadata: { ...omitCard(message.metadata), deletedAt: new Date().toISOString() },
// A late decision model answer must not route a deleted message.
...(message.routingStatus === 'pending' && {
routingAttempt: sql`${channelMessages.routingAttempt} + 1`,
diff --git a/packages/database/src/repositories/channel/lastMessage.ts b/packages/database/src/repositories/channel/lastMessage.ts
index d12040dd06f..89da11c6d7f 100644
--- a/packages/database/src/repositories/channel/lastMessage.ts
+++ b/packages/database/src/repositories/channel/lastMessage.ts
@@ -1,4 +1,4 @@
-import type { ChannelLastMessage } from '@lobechat/types';
+import type { ChannelLastMessage, ContactCardType } from '@lobechat/types';
import { and, asc, desc, eq, inArray, isNull, or, sql } from 'drizzle-orm';
import { alias } from 'drizzle-orm/pg-core';
@@ -59,6 +59,8 @@ export const channelLastMessages = async (
agentId: channelMessages.agentId,
agentName: agents.name,
agentTitle: agentTitleSql(),
+ cardName: sql<string | null>`${channelMessages.metadata} -> 'card' ->> 'name'`,
+ cardType: sql<ContactCardType | null>`${channelMessages.metadata} -> 'card' ->> 'type'`,
channelId: channelMessages.channelId,
content: sql<string>`left(${channelMessages.content}, ${LIST_PREVIEW_LENGTH})`,
createdAt: channelMessages.createdAt,
@@ -113,6 +115,7 @@ export const channelLastMessages = async (
name: isAgent ? row.agentName || row.agentTitle : row.userFullName || row.username,
type: isAgent ? ('agent' as const) : ('user' as const),
},
+ card: row.cardType ? { name: row.cardName, type: row.cardType } : null,
content: row.content,
createdAt: row.createdAt,
thread: row.threadId ? { id: row.threadId, title: row.threadTitle } : null,
diff --git a/packages/database/src/repositories/channel/send.ts b/packages/database/src/repositories/channel/send.ts
index 2b07ee52c21..1e334b7b84a 100644
--- a/packages/database/src/repositories/channel/send.ts
+++ b/packages/database/src/repositories/channel/send.ts
@@ -1,10 +1,11 @@
-import type { ChannelMessageMetadata, ChannelRoutingMode } from '@lobechat/types';
-import { CHANNEL_LIMITS } from '@lobechat/types';
+import type { ChannelMessageMetadata, ChannelRoutingMode, ContactCardInput } from '@lobechat/types';
+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 { Transaction } from '../../type';
+import type { LobeChatDatabase, Transaction } from '../../type';
import { isUuid } from '../../utils/uuid';
import { buildWorkspaceWhere } from '../../utils/workspace';
import { sharedAgentOwner } from './agent';
@@ -31,6 +32,11 @@ export interface ChannelSendInput {
* (`channels.agentPairKey`). The caller stays the requester and execution identity.
*/
authorAgentMemberId?: string;
+ /**
+ * Share a contact as a card. The server checks it may be shared, then writes the content (a text
+ * fallback) and `metadata.card` (a snapshot); a retry matches the original by this reference.
+ */
+ card?: ContactCardInput;
content: string;
fileIds?: string[];
/** Member ids. A human quote dispatches only its mentioned Agents. */
@@ -56,6 +62,15 @@ export interface ChannelSendInput {
const sameList = (a: string[], b: string[]) =>
a.length === b.length && a.every((value, index) => value === b[index]);
+/** Whether a stored message shares the same contact, by reference rather than its snapshot. */
+const sameCard = (metadata: ChannelMessageMetadata | null, input: ContactCardInput) => {
+ const card = contactCardOf(metadata);
+ if (!card || card.type !== input.type) return false;
+ return card.type === 'user'
+ ? card.userId === (input as { userId: string }).userId
+ : card.agentId === (input as { agentId: string }).agentId;
+};
+
export const validateSendInput = (input: ChannelSendInput) => {
if (input.replyToId && input.rootMessageId)
throw new ChannelError('BAD_REQUEST', 'Choose a reply or a thread root, not both');
@@ -64,8 +79,10 @@ export const validateSendInput = (input: ChannelSendInput) => {
if (input.silent && (input.replyToId || input.mentions?.length))
throw new ChannelError('BAD_REQUEST', 'A message for the record neither replies nor mentions');
const fileIds = [...new Set(input.fileIds ?? [])];
+ if (input.card && fileIds.length)
+ throw new ChannelError('BAD_REQUEST', 'A card goes without attachments');
if (
- (!input.content.trim() && !fileIds.length) ||
+ (!input.card && !input.content.trim() && !fileIds.length) ||
!input.requestKey ||
input.content.length > CHANNEL_LIMITS.contentLength ||
fileIds.length > CHANNEL_LIMITS.attachments
@@ -99,7 +116,7 @@ export const sendMessage = async (
): Promise<ChannelMessageItem> => {
const { fileIds, mentions } = validateSendInput(input);
const author = await requestAuthor(tx, channel, input.authorAgentMemberId);
- if (author && (mentions.includes(author.id) || fileIds.length))
+ if (author && (mentions.includes(author.id) || fileIds.length || input.card))
throw new ChannelError('BAD_REQUEST', 'An Agent asks the other Agent, without attachments');
const [replyTo] = input.replyToId
? await tx
@@ -161,7 +178,9 @@ export const sendMessage = async (
if (
existing.userId !== (author ? null : member.userId) ||
existing.agentId !== (author?.agentId ?? null) ||
- existing.content !== input.content ||
+ !(input.card
+ ? sameCard(existing.metadata, input.card)
+ : existing.content === input.content) ||
existing.replyToId !== (input.replyToId ?? null) ||
existing.threadId !== threadId ||
!sameList(existingFileIds, fileIds) ||
@@ -314,12 +333,22 @@ export const sendMessage = async (
? candidates
: [];
+ // 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));
+ const metadata = card ? { ...input.metadata, card } : input.metadata;
+
const message = await appendMessage(tx, {
...(author ? { agentId: author.agentId } : { userId: member.userId }),
channelId: channel.id,
- content: input.content,
+ content: card ? contactCardText(card) : input.content,
mentions,
- ...(input.metadata && { metadata: input.metadata }),
+ ...(metadata && { metadata }),
requestKey: input.requestKey,
replyToId: input.replyToId,
routingAttempt: routed.status === 'pending' ? 1 : 0,
diff --git a/packages/database/src/repositories/channel/view.ts b/packages/database/src/repositories/channel/view.ts
index d2ed9905901..8a7ccf918ba 100644
--- a/packages/database/src/repositories/channel/view.ts
+++ b/packages/database/src/repositories/channel/view.ts
@@ -4,6 +4,7 @@ import {
channelMessageEditedAt,
channelMessageReceipt,
channelMessageVia,
+ contactCardOf,
type ChatMessageError,
defaultChannelAgentDirectory,
type LobeAgentAgencyConfig,
@@ -90,6 +91,7 @@ export const publicMessage = (row: MessageRow, fileIds: string[]) => {
name: isAgent ? senderAgentName || senderAgentTitle : senderUserName || senderUsername,
type: isAgent ? ('agent' as const) : ('user' as const),
},
+ card: contactCardOf(message.metadata) ?? null,
deletedAt: channelMessageDeletedAt(message.metadata),
editedAt: channelMessageEditedAt(message.metadata),
// On an Agent's message, the exchange between Agents it reports from.
diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.ts
index 49dd9c72b52..c5714556448 100644
--- a/packages/types/src/channel.ts
+++ b/packages/types/src/channel.ts
@@ -3,6 +3,7 @@ import {
LocalExecutionHeterogeneousAgentTypeSchema,
REMOTE_HETEROGENEOUS_AGENT_CONFIGS,
} from './agent/heterogeneousAgent';
+import type { ContactCard, ContactCardType } from './contact';
import { getWorkingDirEffectivePath } from './device';
import type { BotWakeKind } from './signal';
import type { ExternalWorkSummaryItem } from './work';
@@ -695,6 +696,8 @@ export interface ChannelLastMessage {
attachments: { count: number; fileType: string } | null;
/** Who sent it, so a list can read "Me: …" or "Alice: …"; `id` is null after deletion. */
author: { id: string | null; name: string | null; type: ChannelMemberActorType };
+ /** A shared contact card, so a list can localize "[Contact card] …" instead of the stored text. */
+ card?: { name: string | null; type: ContactCardType } | null;
content: string;
createdAt: Date;
/**
@@ -835,6 +838,8 @@ export interface ChannelPublicMessage {
name: string | null;
type: ChannelMemberActorType;
};
+ /** A person or an Agent shared as a contact card; the content holds its text fallback. */
+ card?: ContactCard | null;
content: string;
createdAt: Date;
/**
diff --git a/packages/types/src/contact.ts b/packages/types/src/contact.ts
index 89244aa48d8..6ec4230ee7e 100644
--- a/packages/types/src/contact.ts
+++ b/packages/types/src/contact.ts
@@ -62,6 +62,8 @@ export interface ContactRequestItem {
direction: 'incoming' | 'outgoing';
id: string;
message: string | null;
+ /** How the requester found the addressee; null for a search or a profile. */
+ source?: ContactRequestSourceItem | null;
/** The other person. */
user: ContactUserProfile;
/** Set when a member invited the addressee to be an external contact of this workspace. */
@@ -91,6 +93,60 @@ export type ContactSearchResult =
/** Owner-side extras of an address book entry; open for later management features. */
export type ContactMetadata = Record<string, unknown>;
+/**
+ * A contact shared into a Channel as a card (`metadata.card` of the message). Only the reference
+ * is authoritative; the name and avatar are the server's snapshot at send time, so a card reads
+ * the same in previews and to Agents after the person or Agent changes. Clients look the person
+ * or the share up again before acting on it.
+ */
+export type ContactCard =
+ | {
+ avatar: string | null;
+ name: string | null;
+ type: 'user';
+ userId: string;
+ username: string | null;
+ }
+ | {
+ agentId: string;
+ avatar: string | null;
+ backgroundColor: string | null;
+ name: string | null;
+ /** Owner's display name, so the card can say whose Agent it is. */
+ ownerName: string | null;
+ /** The link share the recipient adds it through. */
+ shareId: string;
+ type: 'agent';
+ };
+
+export type ContactCardType = ContactCard['type'];
+
+/** What a sender picks to share: the server resolves and snapshots the rest. */
+export type ContactCardInput =
+ { type: 'user'; userId: string } | { agentId: string; type: 'agent' };
+
+/** Reads `metadata.card`, or undefined when a message carries none or a malformed one. */
+export const contactCardOf = (
+ metadata: Record<string, unknown> | null | undefined,
+): ContactCard | undefined => {
+ const card = metadata?.card as Partial<Record<string, unknown>> | undefined;
+ if (card?.type === 'user' && typeof card.userId === 'string') return card as ContactCard;
+ if (
+ card?.type === 'agent' &&
+ typeof card.agentId === 'string' &&
+ typeof card.shareId === 'string'
+ )
+ return card as ContactCard;
+ return undefined;
+};
+
+/**
+ * The stored text of a card message, for every reader that does not render the card: list
+ * previews, notifications, Agents and bots. Clients that render cards localize their own label.
+ */
+export const contactCardText = (card: ContactCard) =>
+ `[${card.type === 'agent' ? 'Agent card' : 'Contact card'}] ${card.name || (card.type === 'user' ? card.username : '') || ''}`.trim();
+
/**
* Stored on a contact request sent from a person's card in a Channel: the card message and who
* shared it. Server-verified at send time, so it never names a referrer who did not share.
@@ -101,3 +157,10 @@ export interface ContactRequestSource {
referrerId: string | null;
type: 'card';
}
+
+/** A request's source as the client shows it: "From X's card". */
+export interface ContactRequestSourceItem {
+ /** Who shared the card; null once their account is gone. */
+ referrer: ContactUserProfile | null;
+ type: 'card';
+}