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: contacts message push (#23226)

Arvin Xu605bc00efd59
diff --git a/apps/server/src/routers/lambda/__tests__/contact.notify.test.ts b/apps/server/src/routers/lambda/__tests__/contact.notify.test.ts
index 091b8771216..16e892a2b95 100644
--- a/apps/server/src/routers/lambda/__tests__/contact.notify.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/contact.notify.test.ts
@@ -1,11 +1,20 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from 'vitest';
-const { acceptRequest, notify, sendRequest } = vi.hoisted(() => ({
+const model = vi.hoisted(() => ({
acceptRequest: vi.fn(),
- notify: 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 } = vi.hoisted(() => ({
+ contactsChanged: vi.fn(),
+ notify: vi.fn(),
+}));
vi.mock('@/database/core/db-adaptor', () => ({
getServerDB: vi.fn(function () {
@@ -17,11 +26,12 @@ vi.mock('@/server/services/channel/featureGate', () => ({
}));
vi.mock('@/database/models/contact', () => ({
ContactModel: vi.fn(function () {
- return { acceptRequest, sendRequest };
+ return model;
}),
}));
vi.mock('@/server/services/contact/notify', () => ({
notifyContactRequestAfterResponse: notify,
+ notifyContactsChangedAfterResponse: contactsChanged,
}));
const { contactRouter } = await import('../contact');
@@ -77,4 +87,41 @@ describe('contactRouter notifications', () => {
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/contact.ts b/apps/server/src/routers/lambda/contact.ts
index 23f22729274..7f139720802 100644
--- a/apps/server/src/routers/lambda/contact.ts
+++ b/apps/server/src/routers/lambda/contact.ts
@@ -10,7 +10,10 @@ 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 { notifyContactRequestAfterResponse } from '@/server/services/contact/notify';
+import {
+ notifyContactRequestAfterResponse,
+ notifyContactsChangedAfterResponse,
+} from '@/server/services/contact/notify';
/**
* The address book belongs to the Channel experience: contacts are who you can message there.
@@ -63,6 +66,7 @@ export const contactRouter = router({
recipientUserId: input.userId,
requestId: result.requestId,
});
+ notifyContactsChangedAfterResponse([ctx.userId, input.userId]);
return result;
}),
@@ -76,25 +80,29 @@ export const contactRouter = router({
recipientUserId: result.contactUserId,
requestId: input.requestId,
});
+ notifyContactsChangedAfterResponse([ctx.userId, result.contactUserId]);
return result;
}),
declineRequest: contactProcedure
.input(z.object({ requestId }))
.mutation(async ({ ctx, input }) => {
- await ctx.contactModel.declineRequest(input.requestId);
+ const { requesterId } = await ctx.contactModel.declineRequest(input.requestId);
+ notifyContactsChangedAfterResponse([ctx.userId, requesterId]);
return { success: true };
}),
cancelRequest: contactProcedure
.input(z.object({ requestId }))
.mutation(async ({ ctx, input }) => {
- await ctx.contactModel.cancelRequest(input.requestId);
+ const { addresseeId } = await ctx.contactModel.cancelRequest(input.requestId);
+ notifyContactsChangedAfterResponse([ctx.userId, addresseeId]);
return { success: true };
}),
removeUser: contactProcedure.input(z.object({ userId })).mutation(async ({ ctx, input }) => {
await ctx.contactModel.removeUser(input.userId);
+ notifyContactsChangedAfterResponse([ctx.userId, input.userId]);
return { success: true };
}),
@@ -104,6 +112,7 @@ export const contactRouter = router({
.input(z.object({ userId }))
.mutation(async ({ ctx, input }) => {
await ctx.contactModel.openTo(input.userId);
+ notifyContactsChangedAfterResponse([ctx.userId, input.userId]);
return { success: true };
}),
@@ -113,6 +122,7 @@ export const contactRouter = router({
.input(z.object({ userId }))
.mutation(async ({ ctx, input }) => {
await ctx.contactModel.removeExternal(input.userId);
+ notifyContactsChangedAfterResponse([ctx.userId, input.userId]);
return { success: true };
}),
diff --git a/apps/server/src/services/contact/notify.ts b/apps/server/src/services/contact/notify.ts
index d085c618606..4d5245713f4 100644
--- a/apps/server/src/services/contact/notify.ts
+++ b/apps/server/src/services/contact/notify.ts
@@ -1,5 +1,6 @@
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';
/**
@@ -20,3 +21,12 @@ export const notifyContactRequestAfterResponse = (params: NotifyContactRequestPa
}
});
};
+
+/**
+ * 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/apps/server/src/services/user/notify.test.ts b/apps/server/src/services/user/notify.test.ts
new file mode 100644
index 00000000000..835abbdcdea
--- /dev/null
+++ b/apps/server/src/services/user/notify.test.ts
@@ -0,0 +1,64 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const appEnv = vi.hoisted(() => ({
+ AGENT_GATEWAY_INTERNAL_URL: undefined as string | undefined,
+ AGENT_GATEWAY_SERVICE_TOKEN: 'service-token' as string | undefined,
+ AGENT_GATEWAY_URL: 'https://gateway.test' as string | undefined,
+}));
+vi.mock('@/envs/app', () => ({ appEnv }));
+
+const { notifyUsers } = await import('./notify');
+
+describe('notifyUsers', () => {
+ const fetchMock = vi.fn();
+
+ beforeEach(() => {
+ appEnv.AGENT_GATEWAY_INTERNAL_URL = undefined;
+ appEnv.AGENT_GATEWAY_SERVICE_TOKEN = 'service-token';
+ appEnv.AGENT_GATEWAY_URL = 'https://gateway.test';
+ fetchMock.mockReset().mockResolvedValue(new Response(null, { status: 202 }));
+ vi.stubGlobal('fetch', fetchMock);
+ });
+ afterEach(() => vi.unstubAllGlobals());
+
+ it('posts the topic and each user once to the gateway user feed', async () => {
+ await notifyUsers('contacts', ['a', 'b', 'a', '']);
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(String(url)).toBe('https://gateway.test/api/users/notify');
+ expect(init.headers.Authorization).toBe('Bearer service-token');
+ expect(JSON.parse(init.body)).toEqual({ topic: 'contacts', userIds: ['a', 'b'] });
+ });
+
+ it('prefers the internal gateway URL', async () => {
+ appEnv.AGENT_GATEWAY_INTERNAL_URL = 'http://gateway.internal';
+ await notifyUsers('contacts', ['a']);
+ expect(String(fetchMock.mock.calls[0][0])).toBe('http://gateway.internal/api/users/notify');
+ });
+
+ it('sends more than 500 users in batches', async () => {
+ await notifyUsers(
+ 'contacts',
+ Array.from({ length: 501 }, (_, i) => `u${i}`),
+ );
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body).userIds).toEqual(['u500']);
+ });
+
+ it('does nothing without a gateway, a token or anyone to tell', async () => {
+ appEnv.AGENT_GATEWAY_SERVICE_TOKEN = undefined;
+ await notifyUsers('contacts', ['a']);
+ appEnv.AGENT_GATEWAY_SERVICE_TOKEN = 'service-token';
+ await notifyUsers('contacts', []);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('never throws when the gateway fails or is too old', async () => {
+ fetchMock.mockResolvedValueOnce(new Response('Not found', { status: 404 }));
+ await expect(notifyUsers('contacts', ['a'])).resolves.toBeUndefined();
+ fetchMock.mockRejectedValueOnce(new Error('network down'));
+ await expect(notifyUsers('contacts', ['a'])).resolves.toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/user/notify.ts b/apps/server/src/services/user/notify.ts
new file mode 100644
index 00000000000..2a6f39d4e41
--- /dev/null
+++ b/apps/server/src/services/user/notify.ts
@@ -0,0 +1,39 @@
+import debug from 'debug';
+
+import { appEnv } from '@/envs/app';
+
+const log = debug('lobe-server:user:notify');
+
+/** The gateway's limit per request; larger lists are sent in batches. */
+const MAX_USERS_PER_REQUEST = 500;
+
+/**
+ * Tell each user's open clients that something of theirs changed, named by `topic` (e.g.
+ * `contacts`), through the Agent Gateway's user feed. Best-effort invalidation like
+ * `notifyChannel`: no content is sent, the client re-reads the topic through the API, and it
+ * re-reads after every reconnect, so a lost notice only delays a refresh. Never throws.
+ */
+export const notifyUsers = async (topic: string, userIds: string[]) => {
+ const gateway = appEnv.AGENT_GATEWAY_INTERNAL_URL || appEnv.AGENT_GATEWAY_URL;
+ const token = appEnv.AGENT_GATEWAY_SERVICE_TOKEN;
+ const recipients = [...new Set(userIds.filter(Boolean))];
+ if (!gateway || !token || recipients.length === 0) return;
+ try {
+ for (let offset = 0; offset < recipients.length; offset += MAX_USERS_PER_REQUEST) {
+ const result = await fetch(new URL('/api/users/notify', gateway), {
+ body: JSON.stringify({
+ topic,
+ userIds: recipients.slice(offset, offset + MAX_USERS_PER_REQUEST),
+ }),
+ headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
+ method: 'POST',
+ signal: AbortSignal.timeout(3000),
+ });
+ // An older gateway has no user feed; clients still refresh on reconnect and focus.
+ if (!result.ok) log('Gateway user notification unavailable (%d)', result.status);
+ await result.body?.cancel();
+ }
+ } catch (error) {
+ log('Gateway user notification failed: %O', error);
+ }
+};
diff --git a/packages/agent-gateway-client/src/mux/GatewayMuxClient.channel.test.ts b/packages/agent-gateway-client/src/mux/GatewayMuxClient.channel.test.ts
index 8d2239a5438..faff8c8029a 100644
--- a/packages/agent-gateway-client/src/mux/GatewayMuxClient.channel.test.ts
+++ b/packages/agent-gateway-client/src/mux/GatewayMuxClient.channel.test.ts
@@ -33,7 +33,9 @@ describe('Gateway public Channel notifications', () => {
getToken: async () => 'token',
});
const changed = vi.fn();
+ const userChanged = vi.fn();
const off = mux.on('channel_changed', changed);
+ const offUser = mux.on('user_changed', userChanged);
try {
const connected = mux.connect();
await vi.waitFor(() => expect(sockets[0]).toBeDefined());
@@ -45,9 +47,16 @@ describe('Gateway public Channel notifications', () => {
socket.receive(event);
expect(changed).toHaveBeenCalledExactlyOnceWith(event);
expect(socket.sent.some((message) => JSON.parse(message).type === 'subscribe')).toBe(false);
+ const userEvent = { type: 'user_changed', topic: 'contacts' };
+ socket.receive(userEvent);
+ expect(userChanged).toHaveBeenCalledExactlyOnceWith(userEvent);
+ expect(changed).toHaveBeenCalledTimes(1);
off();
+ offUser();
socket.receive(event);
+ socket.receive(userEvent);
expect(changed).toHaveBeenCalledTimes(1);
+ expect(userChanged).toHaveBeenCalledTimes(1);
} finally {
mux.disconnect();
}
diff --git a/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts b/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts
index ac7fad0dba1..5f04a2a1ade 100644
--- a/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts
+++ b/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts
@@ -722,6 +722,11 @@ export class GatewayMuxClient {
break;
}
+ case 'user_changed': {
+ this.listeners.emit('user_changed', message);
+ break;
+ }
+
case 'op_lifecycle': {
this.listeners.emit('lifecycle', message);
break;
diff --git a/packages/agent-gateway-client/src/mux/types.ts b/packages/agent-gateway-client/src/mux/types.ts
index bf75503bb9f..c5867026d7c 100644
--- a/packages/agent-gateway-client/src/mux/types.ts
+++ b/packages/agent-gateway-client/src/mux/types.ts
@@ -218,6 +218,12 @@ export interface MuxChannelChangedMessage {
type: 'channel_changed';
}
+/** Something of the user's own changed (`topic`, e.g. `contacts`). Re-fetch it through the API. */
+interface MuxUserChangedMessage {
+ topic: string;
+ type: 'user_changed';
+}
+
export interface MuxErrorMessage {
code: string;
message: string;
@@ -238,7 +244,8 @@ export type MuxServerMessage =
| MuxSessionCompleteMessage
| MuxStatusChangeMessage
| MuxSubscribeFailedMessage
- | MuxToolConfirmationRequestMessage;
+ | MuxToolConfirmationRequestMessage
+ | MuxUserChangedMessage;
/** Hub β†’ client messages that are addressed to one operation subscription. */
export type MuxOperationMessage =
@@ -301,6 +308,7 @@ export interface GatewayMuxClientEvents {
* expected to fall back to the v1 per-operation socket.
*/
unavailable: (reason: string) => void;
+ user_changed: (event: MuxUserChangedMessage) => void;
}
// ─── Operation subscription ───
diff --git a/packages/database/src/models/__tests__/contact.test.ts b/packages/database/src/models/__tests__/contact.test.ts
index 45fc17a94c4..564526c84ce 100644
--- a/packages/database/src/models/__tests__/contact.test.ts
+++ b/packages/database/src/models/__tests__/contact.test.ts
@@ -121,7 +121,7 @@ describe('contact requests', () => {
await expect(carolModel.declineRequest(requestId)).rejects.toThrow('Request not found');
await expect(bobModel.cancelRequest(requestId)).rejects.toThrow('Request not found');
- await aliceModel.cancelRequest(requestId);
+ 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');
@@ -430,7 +430,7 @@ describe('contact edge cases', () => {
it('declines a pending request without creating a contact', async () => {
const { requestId } = await aliceModel.sendRequest(bob);
- await bobModel.declineRequest(requestId);
+ await expect(bobModel.declineRequest(requestId)).resolves.toEqual({ requesterId: alice });
expect(await aliceModel.list()).toEqual([]);
expect(await aliceModel.relationTo(bob)).toBe('none');
diff --git a/packages/database/src/models/contact.ts b/packages/database/src/models/contact.ts
index e6dee20222d..d8a1eb9647d 100644
--- a/packages/database/src/models/contact.ts
+++ b/packages/database/src/models/contact.ts
@@ -481,8 +481,9 @@ export class ContactModel {
return { contactUserId: requesterId, workspaceId };
});
- declineRequest = async (requestId: string) => {
- await this.db.transaction(async (tx) => {
+ /** 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
@@ -493,10 +494,11 @@ export class ContactModel {
)
.returning({ id: userContactRequests.id });
if (!declined) throw new TRPCError({ code: 'NOT_FOUND', message: 'Request not found' });
+ return { requesterId: request.requesterId };
});
- };
- cancelRequest = async (requestId: string) => {
+ /** 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
@@ -509,8 +511,9 @@ export class ContactModel {
eq(userContactRequests.status, 'pending'),
),
)
- .returning({ id: userContactRequests.id });
+ .returning({ addresseeId: userContactRequests.addresseeId });
if (!cancelled) throw new TRPCError({ code: 'NOT_FOUND', message: 'Request not found' });
+ return { addresseeId: cancelled.addresseeId };
};
/**