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(channel): shared Agents and one-on-one messages in workspaces (#23145)

Arvin Xu8b8f3bae5e96
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.ts
index 15606d2041d..2b27197cf79 100644
--- a/apps/server/src/routers/lambda/channel.ts
+++ b/apps/server/src/routers/lambda/channel.ts
@@ -236,7 +236,10 @@ export const channelRouter = router({
const access = await ctx.channelService.openShared(input.share);
return { data: access?.channel.id ?? null, success: true };
}),
- /** The personal conversation with a contact; both people must still be contacts. */
+ /**
+ * The one-on-one conversation with another person: a mutual contact in the personal space, a
+ * fellow member in a workspace.
+ */
openPeer: channelProcedure
.input(z.object({ userId: z.string().min(1).max(64) }))
.mutation(async ({ ctx, input }) => {
diff --git a/apps/server/src/routers/lambda/contact.ts b/apps/server/src/routers/lambda/contact.ts
index 3af44e319b5..84a64186c76 100644
--- a/apps/server/src/routers/lambda/contact.ts
+++ b/apps/server/src/routers/lambda/contact.ts
@@ -2,23 +2,31 @@ import { CONTACT_REQUEST_MESSAGE_MAX_LENGTH } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
+import {
+ requireWorkspaceRoleWhenScoped,
+ wsCompatProcedure,
+} from '@/business/server/trpc-middlewares/workspaceAuth';
import { ContactModel } from '@/database/models/contact';
-import { authedProcedure, router } from '@/libs/trpc/lambda';
+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';
/**
* The address book belongs to the Channel experience: contacts are who you can message there.
- * It is personal, so it never takes a workspace scope.
+ * People are personal and listed only in the personal space; a workspace's colleagues are its
+ * members. Shared Agents belong to the active scope: the caller's own in the personal space, the
+ * workspace's β€” seen by every member β€” in a workspace.
*/
-const contactProcedure = authedProcedure.use(serverDatabase).use(async ({ ctx, next }) => {
+const contactProcedure = wsCompatProcedure.use(serverDatabase).use(async ({ ctx, next }) => {
if (!(await isChannelEnabled(ctx.userId)))
throw new TRPCError({
code: 'FORBIDDEN',
message: 'Channels are not enabled for this account',
});
- return next({ ctx: { contactModel: new ContactModel(ctx.serverDB, ctx.userId) } });
+ return next({
+ ctx: { contactModel: new ContactModel(ctx.serverDB, ctx.userId, ctx.workspaceId) },
+ });
});
const userId = z.string().min(1).max(64);
@@ -101,11 +109,14 @@ export const contactRouter = router({
// ── Agents ────────────────────────────────────────────────────────────
+ // 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)),
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);
diff --git a/apps/server/src/services/channel/ChannelService.direct.test.ts b/apps/server/src/services/channel/ChannelService.direct.test.ts
index c3d2cdc6c48..5a960494ed3 100644
--- a/apps/server/src/services/channel/ChannelService.direct.test.ts
+++ b/apps/server/src/services/channel/ChannelService.direct.test.ts
@@ -7,6 +7,7 @@ import { ChannelError } from '@/database/repositories/channel';
import { ChannelService } from './ChannelService';
const {
+ contactScope,
create,
createGroupFromDirect,
findAccess,
@@ -19,6 +20,7 @@ const {
querySystemInfo,
statPath,
} = vi.hoisted(() => ({
+ contactScope: vi.fn(),
create: vi.fn(),
createGroupFromDirect: vi.fn(),
findAccess: vi.fn(),
@@ -44,6 +46,9 @@ vi.mock('@/database/models/project', () => ({ ProjectModel: class {} }));
vi.mock('@/database/models/contact', async (original) => ({
...(await original<object>()),
ContactModel: class {
+ constructor(_db: unknown, userId: string, workspaceId?: string) {
+ contactScope(userId, workspaceId);
+ }
findAgentAccess = findSharedAgent;
},
}));
@@ -152,13 +157,18 @@ describe('the direct Channel of a new Agent', () => {
});
});
- it('never opens a shared Agent in a workspace', async () => {
+ it('opens a shared Agent added in a workspace in that workspace', async () => {
getAgent.mockResolvedValue(null);
findSharedAgent.mockResolvedValue({ name: null, ownerId: 'other', title: 'Shared Helper' });
- await expect(
- new ChannelService({} as never, 'owner', 'ws_1').createDirect('agt_1'),
- ).resolves.toBeUndefined();
- expect(findSharedAgent).not.toHaveBeenCalled();
+ await new ChannelService({} as never, 'owner', 'ws_1').createDirect('agt_1');
+ // The entry is looked up among those added in this workspace.
+ expect(contactScope).toHaveBeenCalledWith('owner', 'ws_1');
+ expect(create).toHaveBeenCalledWith({
+ agentConfig: {},
+ agentId: 'agt_1',
+ sharedAgent: true,
+ title: 'Shared Helper',
+ });
});
});
@@ -269,7 +279,10 @@ describe('opening another person’s Agent from its share', () => {
expect(create).not.toHaveBeenCalled();
});
- it('is personal only', async () => {
- await expect(openShared('shared-helper', 'ws_1')).rejects.toThrow('personal scope');
+ it('opens in a workspace as well', async () => {
+ await expect(openShared('shared-helper', 'ws_1')).resolves.toMatchObject({
+ channel: { id: 'chn_shared' },
+ });
+ expect(create).toHaveBeenCalledWith(expect.objectContaining({ sharedAgent: true }));
});
});
diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.ts
index d143dcb7a92..8eb7c89cf10 100644
--- a/apps/server/src/services/channel/ChannelService.ts
+++ b/apps/server/src/services/channel/ChannelService.ts
@@ -215,12 +215,13 @@ export class ChannelService {
/**
* Another person's Agent the caller added to their contacts through its link share; the entry
- * shows they reached the share. The repository rechecks the live share. Always a personal
- * direct conversation, run in the cloud as the owner.
+ * shows they reached the share. The repository rechecks the live share. A direct conversation
+ * in the scope the Agent was added in, run in the cloud as the owner.
*/
private createSharedDirect = async (agentId: string) => {
- if (this.workspaceId) return;
- const shared = await new ContactModel(this.db, this.userId).findAgentAccess(agentId);
+ const shared = await new ContactModel(this.db, this.userId, this.workspaceId).findAgentAccess(
+ agentId,
+ );
if (!shared) return;
return this.repository.create({
agentConfig: {},
@@ -236,8 +237,6 @@ export class ChannelService {
* signed in. Adding it to contacts stays optional. One's own Agent opens as usual.
*/
openShared = async (share: string) => {
- if (this.workspaceId)
- throw new ChannelError('BAD_REQUEST', 'A shared Agent is messaged from a personal scope');
const key = parseContactHandle(share);
const found = key ? await AgentShareModel.findBySlugOrId(this.db, key) : null;
if (!found || found.visibility !== 'link')
@@ -269,7 +268,8 @@ export class ChannelService {
};
/**
- * The personal conversation with a contact. The stored title is the other person's name for
+ * The one-on-one conversation with a contact (personal space) or a fellow member (workspace).
+ * The stored title is the other person's name for
* whoever opened it; clients title it with whoever the viewer is talking to.
*/
openPeer = async (peerUserId: string) => {
diff --git a/apps/server/src/services/channel/directMessage.test.ts b/apps/server/src/services/channel/directMessage.test.ts
index 0baeb71de68..bc1f407a597 100644
--- a/apps/server/src/services/channel/directMessage.test.ts
+++ b/apps/server/src/services/channel/directMessage.test.ts
@@ -50,13 +50,17 @@ describe('notifyChannelDirectMessages', () => {
);
});
- it('skips workspace Channels without reading the Channel', () => {
+ it('pings a fellow member in a workspace too', async () => {
notifyChannelDirectMessages(
dbReturning([conversation]),
{ userId: 'opener', workspaceId: 'workspace' },
message,
);
- expect(after).not.toHaveBeenCalled();
+ await runScheduled();
+
+ expect(notifyChannelDirectMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ actorUserId: 'opener', recipientUserId: 'peer' }),
+ );
});
it('skips personal Channels that are not between two people', async () => {
diff --git a/apps/server/src/services/channel/directMessage.ts b/apps/server/src/services/channel/directMessage.ts
index 90ae0dcf0a7..9d4f7ec0e9e 100644
--- a/apps/server/src/services/channel/directMessage.ts
+++ b/apps/server/src/services/channel/directMessage.ts
@@ -11,7 +11,7 @@ interface SentMessage {
}
/**
- * Ping the other person of a personal conversation between two contacts about a message the
+ * Ping the other person of a one-on-one conversation between two people about a message the
* sender posted there. Every message counts, @mention or not. Runs after the response and never
* fails the send; a retried send returns the same message, so its notification dedupes. The
* business slot is a no-op outside Cloud.
@@ -21,9 +21,7 @@ export const notifyChannelDirectMessages = (
context: { userId: string; workspaceId?: string },
message: SentMessage,
) => {
- const { userId, workspaceId } = context;
- // Conversations between people are personal.
- if (workspaceId) return;
+ const { userId } = context;
after(async () => {
try {
diff --git a/packages/database/src/models/__tests__/contact.test.ts b/packages/database/src/models/__tests__/contact.test.ts
index 856958c0b7a..1876fe74459 100644
--- a/packages/database/src/models/__tests__/contact.test.ts
+++ b/packages/database/src/models/__tests__/contact.test.ts
@@ -3,7 +3,14 @@ import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
-import { agents, agentShares, userContactRequests, userContacts, users } from '../../schemas';
+import {
+ agents,
+ agentShares,
+ userContactRequests,
+ userContacts,
+ users,
+ workspaces,
+} from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { ContactModel, parseContactHandle } from '../contact';
@@ -18,6 +25,9 @@ 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);
let bobShareId: string;
@@ -28,6 +38,9 @@ beforeEach(async () => {
{ fullName: 'Bob', id: bob, username: 'Bob' },
{ id: carol, username: 'carol' },
]);
+ await serverDB
+ .insert(workspaces)
+ .values({ id: teamId, name: 'Team', primaryOwnerId: alice, slug: teamId });
await serverDB.insert(agents).values([
{ id: bobAgent, title: 'Bob Helper', userId: bob },
{ id: aliceAgent, title: 'Alice Helper', userId: alice },
@@ -50,6 +63,7 @@ afterEach(async () => {
vi.restoreAllMocks();
await serverDB.delete(userContactRequests);
await serverDB.delete(userContacts);
+ await serverDB.delete(workspaces);
await serverDB.delete(users);
});
@@ -221,6 +235,46 @@ describe('shared Agents', () => {
});
});
+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(true);
+ });
+
+ 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('search', () => {
it('finds people by exact username, case-insensitively, with their relation', async () => {
const [result] = await aliceModel.search('@BOB');
diff --git a/packages/database/src/models/contact.ts b/packages/database/src/models/contact.ts
index 3a680755b53..3f6bf71e826 100644
--- a/packages/database/src/models/contact.ts
+++ b/packages/database/src/models/contact.ts
@@ -8,7 +8,7 @@ import type {
ContactUserItem,
} from '@lobechat/types';
import { TRPCError } from '@trpc/server';
-import { and, desc, eq, or, sql } from 'drizzle-orm';
+import { and, desc, eq, isNull, or, sql } from 'drizzle-orm';
import { alias } from 'drizzle-orm/pg-core';
import { agents, agentShares, userContactRequests, userContacts, users } from '../schemas';
@@ -86,32 +86,49 @@ export const parseContactHandle = (query: string): string | undefined => {
/**
* A person's address book and contact requests. Every method acts as `userId`; another
- * person's rows are only touched as the second half of a mutual relation.
+ * person's rows are only touched as the second half of a mutual relation. People are personal: a
+ * workspace lists none, its colleagues being its members. Agents are the scope's: 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) {
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string | null) {
this.db = db;
this.userId = userId;
+ this.workspaceId = workspaceId || null;
+ }
+
+ /** 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 [people, sharedAgents] = await Promise.all([
- this.db
- .select({ createdAt: userContacts.createdAt, user: userProfileColumns })
- .from(userContacts)
- .innerJoin(users, eq(users.id, userContacts.contactUserId))
- .where(and(eq(userContacts.userId, this.userId), eq(userContacts.type, 'user')))
- .orderBy(desc(userContacts.createdAt)),
+ this.workspaceId
+ ? []
+ : this.db
+ .select({ createdAt: userContacts.createdAt, user: userProfileColumns })
+ .from(userContacts)
+ .innerJoin(users, eq(users.id, userContacts.contactUserId))
+ .where(and(eq(userContacts.userId, this.userId), eq(userContacts.type, 'user')))
+ .orderBy(desc(userContacts.createdAt)),
this.db
.select({ 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(and(eq(userContacts.userId, this.userId), eq(userContacts.type, 'agent')))
+ .where(this.agentEntryWhere())
.orderBy(desc(userContacts.createdAt)),
]);
@@ -306,7 +323,7 @@ export class ContactModel {
// ── Agents ────────────────────────────────────────────────────────────
- /** Add another person's Agent through its link share (share id or custom handle). */
+ /** 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' });
@@ -315,7 +332,12 @@ export class ContactModel {
await this.db
.insert(userContacts)
- .values({ agentId: share.agentId, type: 'agent', userId: this.userId })
+ .values({
+ agentId: share.agentId,
+ type: 'agent',
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ })
.onConflictDoNothing();
return toAgentProfile(share);
};
@@ -323,12 +345,13 @@ export class ContactModel {
removeAgent = async (agentId: string) => {
await this.db
.delete(userContacts)
- .where(and(eq(userContacts.userId, this.userId), eq(userContacts.agentId, agentId)));
+ .where(and(this.agentEntryWhere(), eq(userContacts.agentId, agentId)));
};
/**
- * The live share that authorizes me to message another person's Agent: my contact entry for
- * it plus its link share. Returns undefined for my own Agents, which need no share.
+ * 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) => {
const [row] = await this.db
@@ -345,7 +368,7 @@ export class ContactModel {
.innerJoin(agentShares, eq(agentShares.agentId, agents.id))
.where(
and(
- eq(userContacts.userId, this.userId),
+ this.agentEntryWhere(),
eq(userContacts.agentId, agentId),
eq(agentShares.visibility, 'link'),
notTrashed(agents.isDeleted),
diff --git a/packages/database/src/repositories/channel/__tests__/peer.test.ts b/packages/database/src/repositories/channel/__tests__/peer.test.ts
index 2f78ec29c06..9d5d4bacdb2 100644
--- a/packages/database/src/repositories/channel/__tests__/peer.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/peer.test.ts
@@ -1,9 +1,10 @@
// @vitest-environment node
+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, userContacts } from '../../../schemas';
+import { agents, userContacts, workspaceMembers } from '../../../schemas';
import { ChannelRepository } from '..';
import { createChannelFixture, jobsOf } from './testUtils';
@@ -96,11 +97,58 @@ describe('a conversation between two contacts', () => {
// History stays readable.
expect((await asAlice.list()).map((c) => c.id)).toEqual([channel.id]);
});
+});
+
+describe('a conversation between two workspace members', () => {
+ const inTeam = (userId: string) => new ChannelRepository(db, userId, fixture.workspaceId);
+ const join = (...userIds: string[]) =>
+ db
+ .insert(workspaceMembers)
+ .values(
+ userIds.map((userId) => ({ role: 'member', userId, workspaceId: fixture.workspaceId })),
+ )
+ .onConflictDoNothing();
+
+ it('needs both people to be members, not contacts', async () => {
+ await join(alice);
+ await expect(inTeam(alice).openPeer(bob, 'Mia')).rejects.toThrow('Workspace member not found');
+
+ await join(bob);
+ const { channel } = await inTeam(alice).openPeer(bob, 'Mia');
+ expect(channel).toMatchObject({ peerUserId: bob, workspaceId: fixture.workspaceId });
+ expect(await inTeam(bob).list()).toMatchObject([{ id: channel.id, peerUserId: alice }]);
+ });
- it('is never opened in a workspace', async () => {
+ it('is its own conversation, apart from the personal one', async () => {
await befriend();
+ await join(alice, bob);
+ const personal = await asAlice.openPeer(bob, 'Mia');
+ const inWorkspace = await inTeam(bob).openPeer(alice, 'Olivia');
+ expect(inWorkspace.channel.id).not.toBe(personal.channel.id);
+ expect((await inTeam(alice).openPeer(bob, 'Mia')).channel.id).toBe(inWorkspace.channel.id);
+
+ expect((await asAlice.list()).map((c) => c.id)).toEqual([personal.channel.id]);
+ expect((await inTeam(alice).list()).map((c) => c.id)).toEqual([inWorkspace.channel.id]);
+ });
+
+ it('goes silent once either person leaves the workspace', async () => {
+ await join(alice, bob);
+ const { channel } = await inTeam(alice).openPeer(bob, 'Mia');
+ await db
+ .update(workspaceMembers)
+ .set({ deletedAt: new Date() })
+ .where(
+ and(
+ eq(workspaceMembers.workspaceId, fixture.workspaceId),
+ eq(workspaceMembers.userId, bob),
+ ),
+ );
await expect(
- new ChannelRepository(db, alice, fixture.workspaceId).openPeer(bob, 'Mia'),
- ).rejects.toThrow('A conversation between people is personal');
+ inTeam(alice).send(channel.id, {
+ content: 'Still here?',
+ 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 f45e967362c..70912f3008e 100644
--- a/packages/database/src/repositories/channel/__tests__/sharedAgent.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/sharedAgent.test.ts
@@ -261,3 +261,81 @@ 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 open = async () => {
+ const { channel } = await inWorkspace.create({
+ agentId,
+ sharedAgent: true,
+ title: 'Shared Helper',
+ });
+ return channel;
+ };
+
+ it('opens a direct conversation in that workspace through the live share', async () => {
+ const channel = await open();
+ expect(channel).toMatchObject({ agentId, userId: visitorId, workspaceId: fixture.workspaceId });
+
+ const [listed] = await inWorkspace.list();
+ expect(listed).toMatchObject({
+ id: channel.id,
+ sharedAgent: true,
+ sharedAgentHandle: 'shared-helper',
+ });
+ // Personal and workspace conversations stay apart.
+ expect(await visitor.list()).toEqual([]);
+ });
+
+ it('runs as its owner in the owner’s scope, and only the run reads the conversation', async () => {
+ const channel = await open();
+ const message = await inWorkspace.send(channel.id, {
+ content: 'Hello from the team',
+ requestKey: 'ws',
+ routing: 'fallback',
+ });
+ const [job] = await jobsOf(db, message.id);
+
+ const claim = (await execution.claim(channel.id, job.id, lease))!;
+ expect(claim.job.executionConfig).toMatchObject({
+ runtime: 'native',
+ share: { ownerId, shareId, workspaceId: null },
+ });
+ expect(claim.topic).toMatchObject({ senderId: visitorId, userId: ownerId, workspaceId: null });
+
+ const operationId = claim.job.operationId!;
+ await db
+ .update(agentOperations)
+ .set({ status: 'running' })
+ .where(eq(agentOperations.id, operationId));
+ const page = await new ChannelHistoryRepository(db, ownerId).readMessages(operationId);
+ expect(page.messages.map((item) => item.content)).toContain('Hello from the team');
+ await expect(new ChannelHistoryRepository(db, ownerId).currentRun(operationId)).rejects.toThrow(
+ 'A shared Agent can only read its own conversation',
+ );
+ await expect(
+ new ChannelHistoryRepository(db, visitorId, fixture.workspaceId).readMessages(operationId),
+ ).rejects.toThrow('Channel operation not found');
+ });
+
+ it('still cannot join a workspace group', async () => {
+ const { channel } = await inWorkspace.create({ title: 'Group' });
+ await expect(inWorkspace.addAgent(channel.id, { agentId })).rejects.toThrow('Agent not found');
+ });
+
+ it('does not mark a colleague’s workspace Agent as shared', async () => {
+ const teamAgentId = 'agt_channel_shared_team';
+ await db.insert(agents).values({
+ id: teamAgentId,
+ title: 'Team Helper',
+ userId: ownerId,
+ visibility: 'public',
+ workspaceId: fixture.workspaceId,
+ });
+ const { channel } = await inWorkspace.create({ agentId: teamAgentId, title: 'Team Helper' });
+
+ const [listed] = await inWorkspace.list();
+ expect(listed).toMatchObject({ id: channel.id, sharedAgent: false, sharedAgentHandle: null });
+ });
+});
diff --git a/packages/database/src/repositories/channel/agent.ts b/packages/database/src/repositories/channel/agent.ts
index d0652bc779f..e5647ef991e 100644
--- a/packages/database/src/repositories/channel/agent.ts
+++ b/packages/database/src/repositories/channel/agent.ts
@@ -20,6 +20,27 @@ import { normalizeInboxAgentTitle } from '../../utils/inboxAgent';
import { notTrashed } from '../../utils/softDelete';
import { ChannelError } from './error';
+/**
+ * Whether a direct conversation is with an Agent reached through its share: someone else's Agent
+ * this scope does not hold. A workspace colleague's public Agent is the workspace's own.
+ */
+export const isSharedAgentChannel = (
+ channel: Pick<ChannelItem, 'agentId' | 'workspaceId'>,
+ agent: {
+ agentOwnerId: string | null;
+ agentVisibility: string | null;
+ agentWorkspaceId: string | null;
+ },
+ viewerId: string,
+): boolean =>
+ !!channel.agentId &&
+ agent.agentOwnerId !== viewerId &&
+ !(
+ channel.workspaceId &&
+ agent.agentWorkspaceId === channel.workspaceId &&
+ agent.agentVisibility !== 'private'
+ );
+
/** Explicitly select environment fields so legacy or untyped copies cannot override an Agent. */
export const memberEnvironment = (config?: ChannelMemberConfig | null): ChannelMemberConfig =>
cleanObject({
@@ -38,8 +59,9 @@ export interface ChannelAddAgentInput {
/**
* Another person's Agent that `userId` may talk to through its live link share. A link share is
- * open to anyone signed in, so no contact entry is needed; only a personal direct conversation
- * can hold one, because the share admits one person at a time and counts its limits per person.
+ * open to anyone signed in, so no contact entry is needed; only a direct conversation (personal
+ * or in a workspace) can hold one, because the share admits one person at a time and counts its
+ * limits per person.
*/
export const findSharedChannelAgent = async (
tx: Transaction,
@@ -78,11 +100,12 @@ export const findSharedChannelAgent = async (
};
};
-/** Whether a direct conversation may bind another person's Agent through its share. */
-const acceptsSharedAgent = (
- channel: Pick<ChannelItem, 'agentId' | 'workspaceId'>,
- agentId: string,
-) => channel.agentId === agentId && !channel.workspaceId;
+/**
+ * Whether a direct conversation may bind another person's Agent through its share. A direct
+ * conversation has one person in any scope, so a workspace one can hold it as well.
+ */
+const acceptsSharedAgent = (channel: Pick<ChannelItem, 'agentId'>, agentId: string) =>
+ channel.agentId === agentId;
/** Check Agent scope and hold it through creation of the Channel/member reference. */
export const requireChannelAgent = async (
@@ -100,10 +123,9 @@ export const requireChannelAgent = async (
if (agent)
// LobeAI rows are stored without a title; label it the way the rest of the product does.
return { name: agent.name, title: normalizeInboxAgentTitle(agent.title, agent) };
- const shared =
- options.allowShared && !workspaceId
- ? await findSharedChannelAgent(tx, userId, agentId)
- : undefined;
+ const shared = options.allowShared
+ ? await findSharedChannelAgent(tx, userId, agentId)
+ : undefined;
if (!shared) throw new ChannelError('NOT_FOUND', 'Agent not found');
return { name: shared.name, title: shared.title };
};
diff --git a/packages/database/src/repositories/channel/history.ts b/packages/database/src/repositories/channel/history.ts
index f9a2abf484a..5c6e986eed2 100644
--- a/packages/database/src/repositories/channel/history.ts
+++ b/packages/database/src/repositories/channel/history.ts
@@ -83,9 +83,9 @@ export class ChannelHistoryRepository {
.innerJoin(agentOperations, eq(agentOperations.id, channelJobs.operationId))
.where(and(eq(channelJobs.operationId, operationId), eq(channelJobs.channelId, channel.id)))
.limit(1);
- // A shared Agent runs as its owner in its own scope for the person of a personal direct
- // conversation (`executionConfig.share`, frozen at claim): the operation is the owner's,
- // the Channel and its requester are that person's.
+ // A shared Agent runs as its owner in its own scope for the person of a direct
+ // conversation, personal or in that person's workspace (`executionConfig.share`, frozen at
+ // claim): the operation is the owner's, the Channel and its requester are that person's.
const share = row?.job.executionConfig?.share;
const requesterId = share ? channel.userId : this.userId;
if (
@@ -95,7 +95,6 @@ export class ChannelHistoryRepository {
(share
? share.ownerId !== this.userId ||
share.workspaceId !== this.workspaceId ||
- channel.workspaceId !== null ||
channel.agentId !== row.job.manifest?.self.agentId ||
!requesterId
: channel.workspaceId !== this.workspaceId ||
diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.ts
index 878132a47f2..b5ec361ef49 100644
--- a/packages/database/src/repositories/channel/index.ts
+++ b/packages/database/src/repositories/channel/index.ts
@@ -27,6 +27,7 @@ import { normalizeWorkspaceId } from '../../utils/workspace';
import type { ChannelAddAgentInput } from './agent';
import {
addAgentMember,
+ isSharedAgentChannel,
memberEnvironment,
requireAgentMember,
requireChannelAgent,
@@ -36,7 +37,7 @@ import { findThread } from './delivery';
import { editMessage } from './edit';
import { ChannelError } from './error';
import { setMemberMuted } from './mute';
-import { lockPeerPair, peerOf, requireMutualContacts } from './peer';
+import { findPeer, lockPeerPair, peerOf, requirePeerRelation } from './peer';
import {
addChannelUser,
channelUserCandidates,
@@ -602,6 +603,8 @@ export class ChannelRepository {
const rows = await this.db
.select({
agentOwnerId: agents.userId,
+ agentVisibility: agents.visibility,
+ agentWorkspaceId: agents.workspaceId,
channel: channels,
lastReadSequence: channelMembers.lastReadSequence,
memberId: channelMembers.id,
@@ -738,8 +741,8 @@ export class ChannelRepository {
agentIdsOf.set(channelId, ids);
}
- return rows.map(({ agentOwnerId, channel, lastReadSequence, role, shareId, shareSlug }) => {
- const sharedAgent = !!channel.agentId && !channel.workspaceId && agentOwnerId !== this.userId;
+ return rows.map(({ channel, lastReadSequence, role, shareId, shareSlug, ...agent }) => {
+ const sharedAgent = isSharedAgentChannel(channel, agent, this.userId);
return {
...channel,
agentIds: agentIdsOf.get(channel.id) ?? [],
@@ -758,25 +761,30 @@ export class ChannelRepository {
};
/**
- * The caller's personal conversation with a contact, opened by either of them. Requires the
- * mutual contact relation; an existing conversation opens as it is, trashed or not.
+ * The caller's one-on-one conversation with another person in this scope, opened by either of
+ * them: with a mutual contact in the personal space, with a fellow member in a workspace. An
+ * existing conversation opens as it is, trashed or not.
*/
openPeer = (peerUserId: string, title: string): Promise<ChannelAccess> =>
this.db.transaction(async (tx) => {
- if (this.workspaceId)
- throw new ChannelError('BAD_REQUEST', 'A conversation between people is personal');
if (peerUserId === this.userId)
throw new ChannelError('BAD_REQUEST', 'You cannot message yourself');
- await requireMutualContacts(tx, this.userId, peerUserId);
+ 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.userId, peerUserId);
- const existing = await this.findPeer(tx, peerUserId);
+ 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' })
+ .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({
@@ -789,24 +797,6 @@ export class ChannelRepository {
return { channel, member };
});
- private findPeer = async (tx: Transaction, peerUserId: string) => {
- const [row] = await tx
- .select({ channel: channels, member: channelMembers })
- .from(channels)
- .innerJoin(
- channelMembers,
- and(eq(channelMembers.channelId, channels.id), eq(channelMembers.userId, this.userId)),
- )
- .where(
- or(
- and(eq(channels.userId, this.userId), eq(channels.peerUserId, peerUserId)),
- and(eq(channels.userId, peerUserId), eq(channels.peerUserId, this.userId)),
- ),
- )
- .limit(1);
- return row as ChannelAccess | undefined;
- };
-
/**
* The caller's active Channels with their active Agent members, newest first: where the caller
* can address another Agent. Archived and trashed Channels are left out, since nothing posted
diff --git a/packages/database/src/repositories/channel/peer.ts b/packages/database/src/repositories/channel/peer.ts
index 97e896a9635..372bbeca6cc 100644
--- a/packages/database/src/repositories/channel/peer.ts
+++ b/packages/database/src/repositories/channel/peer.ts
@@ -1,9 +1,11 @@
-import { and, eq, or, sql } from 'drizzle-orm';
+import { and, eq, isNull, or, sql } from 'drizzle-orm';
import type { ChannelItem } from '../../schemas';
-import { userContacts } from '../../schemas';
+import { channelMembers, channels, userContacts } from '../../schemas';
import type { Transaction } from '../../type';
import { ChannelError } from './error';
+import { requireWorkspaceMember } from './people';
+import type { ChannelAccess } from './types';
/**
* A personal conversation between two people exists only between contacts. Opening one and
@@ -27,6 +29,22 @@ export const requireMutualContacts = async (
if (rows.length < 2) throw new ChannelError('FORBIDDEN', 'You are not contacts');
};
+/**
+ * What lets two people talk one-on-one in a scope: in the personal space they must be mutual
+ * contacts; in a workspace, both must still be its members. Checked on opening and on every send,
+ * so removing a contact or leaving the workspace silences the conversation and keeps its history.
+ */
+export const requirePeerRelation = async (
+ tx: Transaction,
+ workspaceId: string | null,
+ userId: string,
+ peerUserId: string,
+) => {
+ if (!workspaceId) return requireMutualContacts(tx, userId, peerUserId);
+ await requireWorkspaceMember(tx, workspaceId, userId);
+ await requireWorkspaceMember(tx, workspaceId, peerUserId);
+};
+
/** The other person of a conversation between two people, relative to `viewerId`. */
export const peerOf = (
channel: Pick<ChannelItem, 'peerUserId' | 'userId'>,
@@ -36,8 +54,41 @@ export const peerOf = (
return channel.userId === viewerId ? channel.peerUserId : channel.userId;
};
-/** Transaction-scoped lock on the unordered pair, the same either way round. */
-export const lockPeerPair = async (tx: Transaction, userId: string, peerUserId: string) => {
+/** Transaction-scoped lock on the unordered pair in one scope, the same either way round. */
+export const lockPeerPair = async (
+ tx: Transaction,
+ workspaceId: string | null,
+ userId: string,
+ peerUserId: string,
+) => {
const [a, b] = [userId, peerUserId].sort();
- await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${`channel-peer:${a}:${b}`}))`);
+ const key = `channel-peer:${workspaceId ?? 'personal'}:${a}:${b}`;
+ await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${key}))`);
+};
+
+/** The pair's conversation in one scope, with the caller's membership; one exists per scope. */
+export const findPeer = async (
+ tx: Transaction,
+ workspaceId: string | null,
+ userId: string,
+ peerUserId: string,
+) => {
+ const [row] = await tx
+ .select({ channel: channels, member: channelMembers })
+ .from(channels)
+ .innerJoin(
+ channelMembers,
+ and(eq(channelMembers.channelId, channels.id), eq(channelMembers.userId, userId)),
+ )
+ .where(
+ and(
+ or(
+ and(eq(channels.userId, userId), eq(channels.peerUserId, peerUserId)),
+ and(eq(channels.userId, peerUserId), eq(channels.peerUserId, userId)),
+ ),
+ workspaceId ? eq(channels.workspaceId, workspaceId) : isNull(channels.workspaceId),
+ ),
+ )
+ .limit(1);
+ return row as ChannelAccess | undefined;
};
diff --git a/packages/database/src/repositories/channel/send.ts b/packages/database/src/repositories/channel/send.ts
index dfd120be85a..9b4560558a1 100644
--- a/packages/database/src/repositories/channel/send.ts
+++ b/packages/database/src/repositories/channel/send.ts
@@ -18,7 +18,7 @@ import {
pairedAgent,
} from './delivery';
import { ChannelError } from './error';
-import { peerOf, requireMutualContacts } from './peer';
+import { peerOf, requirePeerRelation } from './peer';
import { audit } from './transaction';
import type { ChannelAccess } from './types';
import { createChannelThread } from './view';
@@ -158,9 +158,15 @@ export const sendMessage = async (
return existing;
}
- // Removing a contact silences the conversation for both people; its history stays.
+ // Removing a contact, or either person leaving the workspace, silences the conversation for
+ // both people; its history stays.
if (channel.peerUserId && member.userId)
- await requireMutualContacts(tx, member.userId, peerOf(channel, member.userId)!);
+ await requirePeerRelation(
+ tx,
+ channel.workspaceId,
+ member.userId,
+ peerOf(channel, member.userId)!,
+ );
if (fileIds.length && channel.agentId) {
// Another person's shared Agent runs as its owner, who cannot read the sender's files.
diff --git a/packages/database/src/schemas/contact.ts b/packages/database/src/schemas/contact.ts
index 8f06585a17f..49374fbe0cc 100644
--- a/packages/database/src/schemas/contact.ts
+++ b/packages/database/src/schemas/contact.ts
@@ -17,8 +17,8 @@ import { users } from './user';
import { workspaces } from './workspace';
/**
- * One entry in an address book. People are personal: their entries pin `user_id` and appear in
- * every scope. An `agent` entry belongs to the scope it was added in: with no `workspace_id` it
+ * One entry in an address book. People are personal: their entries pin `user_id` and are listed
+ * only in the personal space, since a workspace's colleagues are its members. An `agent` entry belongs to the scope it was added in: with no `workspace_id` it
* is its owner's alone; with one it is the workspace's, shown to every member there, and
* `user_id` only records who added it.
*
diff --git a/src/business/server/channel-message/notifyActivity.ts b/src/business/server/channel-message/notifyActivity.ts
index c51dd72df14..40db6bc329f 100644
--- a/src/business/server/channel-message/notifyActivity.ts
+++ b/src/business/server/channel-message/notifyActivity.ts
@@ -1,12 +1,12 @@
/**
- * A person sent a message in a personal conversation between two contacts. Fired once per sent
+ * A person sent a message in a one-on-one conversation between two people. Fired once per sent
* message; the caller has already resolved the recipient as the conversation's other person.
*/
export interface NotifyChannelDirectMessageParams {
actorUserId: string;
channelId: string;
messageId: string;
- /** The other person of the conversation. */
+ /** The other person of the conversation; its Channel says which scope it is in. */
recipientUserId: string;
}