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(database): split the 1275-line chatGroup model into cohesive modules (#21138)

Arvin Xu9ef1d65699ef
diff --git a/apps/server/src/services/agentGroup/index.ts b/apps/server/src/services/agentGroup/index.ts
index 32bbc5ca029..1085a2b44f6 100644
--- a/apps/server/src/services/agentGroup/index.ts
+++ b/apps/server/src/services/agentGroup/index.ts
@@ -48,7 +48,7 @@ export class AgentGroupService {
* Delete a group and the agents that belonged to it.
*
* The roster read + cleanup used to live here, which cost it two things the
- * model-level version has: it ran OUTSIDE the delete's transaction (an error
+ * repository version has: it ran OUTSIDE the delete's transaction (an error
* between the two steps stranded the agents permanently, invisible because
* they are `virtual`), and it classified members through a visibility-scoped
* read, so a member another workspace user had flipped back to `private` was
@@ -58,7 +58,7 @@ export class AgentGroupService {
* @returns The deleted group and list of deleted group-owned agent IDs
*/
async deleteGroup(groupId: string) {
- const { deletedOwnedAgentIds, group } = await this.chatGroupModel.delete(groupId);
+ const { deletedOwnedAgentIds, group } = await this.agentGroupRepo.deleteGroup(groupId);
return {
deletedVirtualAgentIds: deletedOwnedAgentIds,
diff --git a/apps/server/src/services/resourceTransferRequest/index.ts b/apps/server/src/services/resourceTransferRequest/index.ts
index 469d3480607..95de5ea7e30 100644
--- a/apps/server/src/services/resourceTransferRequest/index.ts
+++ b/apps/server/src/services/resourceTransferRequest/index.ts
@@ -3,9 +3,9 @@ import { TRPCError } from '@trpc/server';
import { and, eq, isNull } from 'drizzle-orm';
import { AgentModel } from '@/database/models/agent';
-import { ChatGroupModel } from '@/database/models/chatGroup';
import { ResourceTransferRequestModel } from '@/database/models/resourceTransferRequest';
import { WorkspaceMemberModel } from '@/database/models/workspaceMember';
+import { AgentGroupRepository } from '@/database/repositories/agentGroup';
import type { ResourceTransferRequestItem } from '@/database/schemas';
import { workspaceMembers } from '@/database/schemas';
import type { LobeChatDatabase, Transaction } from '@/database/type';
@@ -192,8 +192,8 @@ export const executeAcceptedTransfer = async (params: {
switch (request.resourceType) {
case 'agentGroup': {
- const chatGroupModel = new ChatGroupModel(db, recipientId, workspaceId);
- await chatGroupModel.transferGroupOwnership(trx, {
+ const agentGroupRepo = new AgentGroupRepository(db, recipientId, workspaceId);
+ await agentGroupRepo.transferOwnership(trx, {
fromUserId,
groupId: request.resourceId,
toUserId: recipientId,
diff --git a/packages/database/src/models/__tests__/chatGroup.test.ts b/packages/database/src/models/__tests__/chatGroup.test.ts
index 10128402c07..c681638b4bb 100644
--- a/packages/database/src/models/__tests__/chatGroup.test.ts
+++ b/packages/database/src/models/__tests__/chatGroup.test.ts
@@ -1,7 +1,7 @@
// @vitest-environment node
import { DEFAULT_INBOX_AVATAR, INBOX_SESSION_ID } from '@lobechat/const';
import { CHAT_GROUP_SESSION_ID_PREFIX } from '@lobechat/types';
-import { eq, inArray } from 'drizzle-orm';
+import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import type { LobeChatDatabase } from '@/database/type';
@@ -1065,8 +1065,7 @@ describe('ChatGroupModel', () => {
const result = await chatGroupModel.delete('delete-test');
- expect(result.group.id).toBe('delete-test');
- expect(result.deletedOwnedAgentIds).toEqual([]);
+ expect(result.id).toBe('delete-test');
// Verify group was deleted
const groups = await serverDB
@@ -1108,157 +1107,6 @@ describe('ChatGroupModel', () => {
expect(groupAgents).toHaveLength(0);
});
- it('should delete group-owned member agents and keep referenced ones', async () => {
- await serverDB.transaction(async (trx) => {
- await trx
- .insert(chatGroups)
- .values({ id: 'owned-cleanup-group', title: 'Owned Cleanup', userId });
-
- await trx.insert(agentsTable).values([
- // Group-built members: the supervisor plus a virtual member. Neither
- // has any existence outside this group.
- { id: 'owned-supervisor', title: 'Supervisor', userId, virtual: true },
- { id: 'owned-member', title: 'Owned Member', userId, virtual: true },
- // Someone's own agent, merely linked in.
- { id: 'referenced-member', title: 'Referenced Member', userId, virtual: false },
- ]);
-
- await trx.insert(chatGroupsAgents).values([
- {
- agentId: 'owned-supervisor',
- chatGroupId: 'owned-cleanup-group',
- role: 'supervisor',
- userId,
- },
- {
- agentId: 'owned-member',
- chatGroupId: 'owned-cleanup-group',
- userId,
- },
- {
- agentId: 'referenced-member',
- chatGroupId: 'owned-cleanup-group',
- userId,
- },
- ]);
- });
-
- const result = await chatGroupModel.delete('owned-cleanup-group');
-
- expect(result.deletedOwnedAgentIds.sort()).toEqual(['owned-member', 'owned-supervisor']);
-
- const survivors = await serverDB
- .select({ id: agentsTable.id })
- .from(agentsTable)
- .where(inArray(agentsTable.id, ['owned-supervisor', 'owned-member', 'referenced-member']));
- expect(survivors).toEqual([{ id: 'referenced-member' }]);
- });
-
- it('should classify members by agents.virtual', async () => {
- // `agents.virtual` is the whole judgement: it is the only thing keeping
- // this delete from either leaking or over-deleting.
- await serverDB.transaction(async (trx) => {
- await trx
- .insert(chatGroups)
- .values({ id: 'legacy-cleanup-group', title: 'Legacy Cleanup', userId });
-
- await trx.insert(agentsTable).values([
- { id: 'legacy-virtual', title: 'Legacy Virtual', userId, virtual: true },
- { id: 'legacy-real', title: 'Legacy Real', userId, virtual: false },
- ]);
-
- await trx.insert(chatGroupsAgents).values([
- { agentId: 'legacy-virtual', chatGroupId: 'legacy-cleanup-group', userId },
- { agentId: 'legacy-real', chatGroupId: 'legacy-cleanup-group', userId },
- ]);
- });
-
- const result = await chatGroupModel.delete('legacy-cleanup-group');
-
- expect(result.deletedOwnedAgentIds).toEqual(['legacy-virtual']);
-
- const survivors = await serverDB
- .select({ id: agentsTable.id })
- .from(agentsTable)
- .where(inArray(agentsTable.id, ['legacy-virtual', 'legacy-real']));
- expect(survivors).toEqual([{ id: 'legacy-real' }]);
- });
-
- it('should clean up an owned member another workspace user made private', async () => {
- // The previous service-level cleanup read the roster through a
- // visibility-scoped query, so this member was invisible to the deleter
- // and leaked every time.
- const wsModel = new ChatGroupModel(serverDB, userId, workspaceId);
-
- await serverDB.transaction(async (trx) => {
- await trx.insert(chatGroups).values({
- id: 'ws-cleanup-group',
- title: 'Workspace Cleanup',
- userId,
- workspaceId,
- });
-
- await trx.insert(agentsTable).values({
- id: 'ws-private-owned',
- title: 'Private Owned',
- userId: otherUserId,
- virtual: true,
- visibility: 'private',
- workspaceId,
- });
-
- await trx.insert(chatGroupsAgents).values({
- agentId: 'ws-private-owned',
- chatGroupId: 'ws-cleanup-group',
- userId: otherUserId,
- workspaceId,
- });
- });
-
- const result = await wsModel.delete('ws-cleanup-group');
-
- expect(result.deletedOwnedAgentIds).toEqual(['ws-private-owned']);
- const survivors = await serverDB
- .select({ id: agentsTable.id })
- .from(agentsTable)
- .where(eq(agentsTable.id, 'ws-private-owned'));
- expect(survivors).toEqual([]);
- });
-
- it('should never delete a builtin agent that ended up on a roster', async () => {
- // `owned` should be enough on its own; the slug guard is the backstop for
- // a malformed row, and losing someone's Inbox to a group delete is not a
- // failure mode worth leaving to one predicate.
- await serverDB.transaction(async (trx) => {
- await trx
- .insert(chatGroups)
- .values({ id: 'builtin-cleanup-group', title: 'Builtin Cleanup', userId });
-
- await trx.insert(agentsTable).values({
- id: 'builtin-inbox',
- slug: 'inbox',
- title: 'Inbox',
- userId,
- virtual: true,
- });
-
- await trx.insert(chatGroupsAgents).values({
- agentId: 'builtin-inbox',
- chatGroupId: 'builtin-cleanup-group',
- userId,
- });
- });
-
- const result = await chatGroupModel.delete('builtin-cleanup-group');
-
- expect(result.deletedOwnedAgentIds).toEqual([]);
- const survivors = await serverDB
- .select({ id: agentsTable.id })
- .from(agentsTable)
- .where(eq(agentsTable.id, 'builtin-inbox'));
- expect(survivors).toEqual([{ id: 'builtin-inbox' }]);
- });
-
it('should not delete groups belonging to other users', async () => {
// Create group for other user
await serverDB.insert(chatGroups).values({
diff --git a/packages/database/src/models/__tests__/chatGroup.updateAgentInGroup.test.ts b/packages/database/src/models/__tests__/chatGroup.updateAgentInGroup.test.ts
new file mode 100644
index 00000000000..1005a4b814f
--- /dev/null
+++ b/packages/database/src/models/__tests__/chatGroup.updateAgentInGroup.test.ts
@@ -0,0 +1,47 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { agents, chatGroups, chatGroupsAgents, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { ChatGroupModel } from '../chatGroup';
+
+const userId = 'chat-group-supervisor-user';
+const groupId = 'chat-group-supervisor-group';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+const model = new ChatGroupModel(serverDB, userId);
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values({ id: userId });
+ await serverDB.insert(chatGroups).values({ id: groupId, title: 'Group', userId });
+ await serverDB.insert(agents).values([
+ { id: 'standalone-member', title: 'Standalone', userId, virtual: false },
+ { id: 'group-built-member', title: 'Group built', userId, virtual: true },
+ ]);
+ await serverDB.insert(chatGroupsAgents).values([
+ { agentId: 'standalone-member', chatGroupId: groupId, order: 0, role: 'participant', userId },
+ { agentId: 'group-built-member', chatGroupId: groupId, order: 1, role: 'participant', userId },
+ ]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+describe('ChatGroupModel.updateAgentInGroup supervisor promotion', () => {
+ it('refuses to promote a referenced member to supervisor', async () => {
+ await expect(
+ model.updateAgentInGroup(groupId, 'standalone-member', { role: 'supervisor' }),
+ ).rejects.toThrow('Only a group-owned member can act as the group supervisor');
+ });
+
+ it('promotes a group-owned member to supervisor', async () => {
+ const result = await model.updateAgentInGroup(groupId, 'group-built-member', {
+ role: 'supervisor',
+ });
+
+ expect(result).toMatchObject({ agentId: 'group-built-member', role: 'supervisor' });
+ });
+});
diff --git a/packages/database/src/models/chatGroup.ts b/packages/database/src/models/chatGroup.ts
deleted file mode 100644
index a832d4ccd47..00000000000
--- a/packages/database/src/models/chatGroup.ts
+++ /dev/null
@@ -1,1275 +0,0 @@
-import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
-import { TRPCError } from '@trpc/server';
-import { and, asc, desc, eq, inArray, isNull, ne, notInArray, or, sql } from 'drizzle-orm';
-
-import type {
- ChatGroupAgentItem,
- ChatGroupItem,
- NewChatGroup,
- NewChatGroupAgent,
-} from '../schemas';
-import {
- agentBotProviders,
- agentCronJobs,
- agents,
- agentShares,
- chatGroups,
- chatGroupsAgents,
- projectAgents,
- projects,
- sessionGroups,
- tasks,
-} from '../schemas';
-import type { LobeChatDatabase, Transaction } from '../type';
-import { sanitizeAgencyConfigsForWorkspace } from '../utils/agencyConfigDevices';
-import { rehomeAgentConnectorsForRecipient } from '../utils/agentConnectors';
-import { rehomeAgentDocumentsForRecipient } from '../utils/agentDocumentsOwnership';
-import { rehomeAgentExpertiseForRecipient } from '../utils/agentExpertise';
-import {
- detachAgentKnowledgeMountsForRecipient,
- rehomeRetainedAgentKnowledgeMounts,
-} from '../utils/agentKnowledgeMounts';
-import { rehomeAgentLabelsForRecipient } from '../utils/agentLabelsOwnership';
-import { rehomeAgentQuotaBindingsForRecipient } from '../utils/agentQuotaBindings';
-import type { GroupMemberRole } from '../utils/groupMembership';
-import {
- GROUP_SUPERVISOR_ROLE,
- isOwnedMembership,
- resolveGroupMembershipType,
-} from '../utils/groupMembership';
-import { normalizeInboxAgentAvatar } from '../utils/inboxAgent';
-import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
-import { AGENT_SHARED_TRANSFER_BLOCKED } from './agent';
-import { AGENT_COPY_IN_PROGRESS, AgentCopyJobModel } from './agentCopyJob';
-import { AGENT_TRANSFER_IN_PROGRESS, AgentTransferJobModel } from './agentTransferJob';
-
-/** Slugs owned by builtin provisioning; a group delete must never reach one. */
-const RESERVED_BUILTIN_AGENT_SLUGS: string[] = Object.values(BUILTIN_AGENT_SLUGS);
-
-/**
- * The group is no longer where the transfer request said it was: moved scope,
- * changed hands, or was deleted. The request that referenced it can never
- * complete.
- */
-export const CHAT_GROUP_OWNERSHIP_STALE = 'CHAT_GROUP_OWNERSHIP_STALE';
-
-/**
- * Handover refused: the group references a member agent that is private to
- * someone other than the recipient, who would silently lose that participant.
- */
-export const CHAT_GROUP_TRANSFER_HIDDEN_MEMBER = 'CHAT_GROUP_TRANSFER_HIDDEN_MEMBER';
-
-export class ChatGroupModel {
- private userId: string;
- private db: LobeChatDatabase;
- private workspaceId?: string;
-
- constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
- this.userId = userId;
- this.db = db;
- this.workspaceId = workspaceId;
- }
-
- private ownership = () =>
- buildWorkspaceWhere(
- { userId: this.userId, workspaceId: this.workspaceId },
- {
- isDeleted: chatGroups.isDeleted,
- userId: chatGroups.userId,
- workspaceId: chatGroups.workspaceId,
- visibility: chatGroups.visibility,
- },
- );
-
- /**
- * Visibility predicate on the member's `agents` row itself. Group membership
- * (the junction row) does not grant access to the agent: when a member agent
- * is switched back to private by its owner, every roster read must drop it
- * for other members β€” otherwise the join would keep leaking the agent's
- * config/meta through group surfaces.
- */
- private memberAgentVisibility = () =>
- buildWorkspaceWhere(
- { userId: this.userId, workspaceId: this.workspaceId },
- {
- isDeleted: agents.isDeleted,
- userId: agents.userId,
- workspaceId: agents.workspaceId,
- visibility: agents.visibility,
- },
- );
-
- /**
- * Same guard as an EXISTS subquery, for junction queries that don't join
- * `agents`. The subquery is spelled with raw identifiers (not drizzle column
- * refs) because the relational query builder rebinds every referenced column
- * in `where` to the primary table's alias, which would corrupt the subquery.
- * Semantics mirror `buildWorkspaceWhere`.
- */
- private memberAgentVisibleExists = () => {
- if (!this.workspaceId) {
- return sql`EXISTS (SELECT 1 FROM "agents" "ma" WHERE "ma"."id" = ${chatGroupsAgents.agentId} AND "ma"."user_id" = ${this.userId} AND "ma"."workspace_id" IS NULL AND "ma"."is_deleted" IS NOT TRUE)`;
- }
- return sql`EXISTS (SELECT 1 FROM "agents" "ma" WHERE "ma"."id" = ${chatGroupsAgents.agentId} AND "ma"."workspace_id" = ${this.workspaceId} AND ("ma"."visibility" IS NULL OR "ma"."visibility" = 'public' OR ("ma"."visibility" = 'private' AND "ma"."user_id" = ${this.userId})) AND "ma"."is_deleted" IS NOT TRUE)`;
- };
-
- /**
- * Get member avatar metas (avatar + backgroundColor) grouped by chatGroupId,
- * ordered by member order. Inbox members fall back to the default avatar.
- */
- getMemberAvatarsByGroupIds = async (
- groupIds: string[],
- ): Promise<Map<string, Array<{ avatar: string | null; backgroundColor: string | null }>>> => {
- const map = new Map<string, Array<{ avatar: string | null; backgroundColor: string | null }>>();
- if (groupIds.length === 0) return map;
-
- const rows = await this.db
- .select({
- avatar: agents.avatar,
- backgroundColor: agents.backgroundColor,
- chatGroupId: chatGroupsAgents.chatGroupId,
- slug: agents.slug,
- })
- .from(chatGroupsAgents)
- .innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))
- .where(and(inArray(chatGroupsAgents.chatGroupId, groupIds), this.memberAgentVisibility()))
- .orderBy(chatGroupsAgents.order, chatGroupsAgents.createdAt, chatGroupsAgents.agentId);
-
- for (const { avatar, backgroundColor, chatGroupId, slug } of rows) {
- const list = map.get(chatGroupId) ?? [];
- list.push({ avatar: normalizeInboxAgentAvatar(avatar, { slug }), backgroundColor });
- map.set(chatGroupId, list);
- }
-
- return map;
- };
-
- // ******* Query Methods ******* //
-
- /**
- * The supervisor agent a group's conversation answers to, or `null`.
- *
- * Deliberately scoped by workspace rather than by {@link ownership}: callers
- * use this to look up what the group's author decided (its supervisor's
- * permission policies), which must not depend on whether *this* caller can
- * see the group row. A visibility-scoped miss would return `null` and fail
- * open.
- */
- getSupervisorAgentId = async (groupId: string): Promise<string | null> => {
- const [row] = await this.db
- .select({ agentId: chatGroupsAgents.agentId })
- .from(chatGroupsAgents)
- .where(
- and(
- eq(chatGroupsAgents.chatGroupId, groupId),
- eq(chatGroupsAgents.role, GROUP_SUPERVISOR_ROLE),
- this.workspaceId
- ? eq(chatGroupsAgents.workspaceId, this.workspaceId)
- : and(eq(chatGroupsAgents.userId, this.userId), isNull(chatGroupsAgents.workspaceId)),
- ),
- )
- .limit(1);
-
- return row?.agentId ?? null;
- };
-
- async findById(id: string): Promise<ChatGroupItem | undefined> {
- const item = await this.db.query.chatGroups.findFirst({
- where: and(eq(chatGroups.id, id), this.ownership()),
- });
-
- return item;
- }
-
- async query(): Promise<ChatGroupItem[]> {
- return this.db.query.chatGroups.findMany({
- orderBy: [desc(chatGroups.updatedAt)],
- where: this.ownership(),
- });
- }
-
- /**
- * Get a chat group by the forkedFromIdentifier stored in config
- * @param forkedFromIdentifier - The source group's market identifier
- * @returns group id if exists, null otherwise
- */
- async getGroupByForkedFromIdentifier(forkedFromIdentifier: string): Promise<string | null> {
- const result = await this.db.query.chatGroups.findFirst({
- columns: { id: true },
- orderBy: [desc(chatGroups.updatedAt)],
- where: and(
- this.ownership(),
- sql`${chatGroups.config}->>'forkedFromIdentifier' = ${forkedFromIdentifier}`,
- ),
- });
- return result?.id ?? null;
- }
-
- async queryWithMemberDetails(): Promise<any[]> {
- const groups = await this.query();
- if (groups.length === 0) return [];
-
- const groupIds = groups.map((g) => g.id);
-
- const groupAgents = await this.db.query.chatGroupsAgents.findMany({
- where: and(
- inArray(chatGroupsAgents.chatGroupId, groupIds),
- this.agentsOwnership(),
- this.memberAgentVisibleExists(),
- ),
- with: { agent: true },
- });
-
- const groupAgentMap = new Map<string, any[]>();
-
- for (const groupAgent of groupAgents) {
- if (!groupAgent.agent) continue;
-
- const groupList = groupAgentMap.get(groupAgent.chatGroupId) || [];
- groupList.push(groupAgent.agent);
- groupAgentMap.set(groupAgent.chatGroupId, groupList);
- }
-
- return groups.map((group) => ({
- ...group,
- agents: groupAgentMap.get(group.id) || [],
- }));
- }
-
- async findGroupWithAgents(groupId: string): Promise<{
- agents: ChatGroupAgentItem[];
- group: ChatGroupItem;
- } | null> {
- const group = await this.findById(groupId);
- if (!group) return null;
-
- const agents = await this.db.query.chatGroupsAgents.findMany({
- orderBy: [chatGroupsAgents.order, chatGroupsAgents.createdAt, chatGroupsAgents.agentId],
- where: and(
- eq(chatGroupsAgents.chatGroupId, groupId),
- this.agentsOwnership(),
- this.memberAgentVisibleExists(),
- ),
- });
-
- return { agents, group };
- }
-
- // ******* Create Methods ******* //
-
- async create(params: Omit<NewChatGroup, 'userId'>): Promise<ChatGroupItem> {
- const [result] = await this.db
- .insert(chatGroups)
- .values(
- buildWorkspacePayload(
- { userId: this.userId, workspaceId: this.workspaceId },
- { ...params },
- ),
- )
- .returning();
-
- return result;
- }
-
- async createWithAgents(
- groupParams: Omit<NewChatGroup, 'userId'>,
- agentIds: string[],
- ): Promise<{ agents: NewChatGroupAgent[]; group: ChatGroupItem }> {
- const group = await this.create(groupParams);
-
- if (agentIds.length === 0) {
- return { agents: [], group };
- }
-
- const agentParams: NewChatGroupAgent[] = agentIds.map((agentId, index) => ({
- agentId,
- chatGroupId: group.id,
- order: index,
- userId: this.userId,
- workspaceId: this.workspaceId ?? null,
- }));
-
- const agents = await this.db.insert(chatGroupsAgents).values(agentParams).returning();
-
- return { agents, group };
- }
-
- // ******* Update Methods ******* //
-
- /**
- * A move target must be a folder the caller can see, and a workspace-public
- * group may only sit in a public folder. `chat_groups.groupId` is read by
- * every member's sidebar now, and the foreign key only proves the folder
- * exists β€” another workspace's folder, or another member's private one,
- * satisfies it and then renders as Ungrouped for everyone who cannot see it.
- * Mirrors `AgentModel.assertSessionGroupAssignable`.
- */
- private async assertFolderAssignable(id: string, groupId: string) {
- const [folder] = await this.db
- .select({ visibility: sessionGroups.visibility })
- .from(sessionGroups)
- .where(
- and(
- eq(sessionGroups.id, groupId),
- buildWorkspaceWhere(
- { userId: this.userId, workspaceId: this.workspaceId },
- {
- isDeleted: sessionGroups.isDeleted,
- userId: sessionGroups.userId,
- visibility: sessionGroups.visibility,
- workspaceId: sessionGroups.workspaceId,
- },
- ),
- ),
- )
- .limit(1);
-
- if (!folder) throw new Error(`Session group ${groupId} not found in current scope`);
-
- if (!this.workspaceId) return;
-
- const [group] = await this.db
- .select({ visibility: chatGroups.visibility })
- .from(chatGroups)
- .where(and(eq(chatGroups.id, id), this.ownership()))
- .limit(1);
-
- // Same exact-match rule as agents: the render path resolves a private
- // item's folder only against private folders and a public item's only
- // against public ones, so either mismatch lands it in Ungrouped.
- if (group && group.visibility !== folder.visibility)
- throw new Error(
- `A ${group.visibility} chat group cannot be moved into a ${folder.visibility} folder`,
- );
- }
-
- async update(id: string, value: Partial<ChatGroupItem>): Promise<ChatGroupItem> {
- if (value.groupId) await this.assertFolderAssignable(id, value.groupId);
-
- // Scope columns never travel through the generic update. The router hands
- // this a partial insert schema, so without stripping them a member could
- // re-scope another member's group now that the ownership predicate spans
- // every visible workspace row. Ignored rather than rejected so a client
- // that sends an extra field still gets its real edit applied. Publishing
- // has its own path and writes `visibility` directly.
- const { userId: _userId, visibility: _visibility, workspaceId: _workspaceId, ...safe } = value;
-
- const [result] = await this.db
- .update(chatGroups)
- .set(safe)
- .where(and(eq(chatGroups.id, id), this.ownership()))
- .returning();
-
- if (!result) {
- throw new Error('Chat group not found or access denied');
- }
-
- return result;
- }
-
- /**
- * Publish a private chat group into the workspace. One-way: once shared,
- * other members may have started using it, so we never let it slip back to
- * `private`. Restricted to the creator's own still-private group.
- */
- async publishToWorkspace(id: string): Promise<ChatGroupItem> {
- // Rehome exactly as `setVisibility` does. A folder cannot mix
- // visibilities, so publishing out of a private Category has to release the
- // folder too β€” left in place, the group would be public while its folder
- // is not, and the sidebar would show it in Ungrouped rather than where the
- // user published it from.
- const [current] = await this.db
- .select({ folderVisibility: sessionGroups.visibility })
- .from(chatGroups)
- .leftJoin(sessionGroups, eq(chatGroups.groupId, sessionGroups.id))
- .where(and(eq(chatGroups.id, id), this.ownership()))
- .limit(1);
- const clearFolder = current?.folderVisibility != null && current.folderVisibility !== 'public';
-
- const [result] = await this.db
- .update(chatGroups)
- .set({
- updatedAt: new Date(),
- visibility: 'public',
- ...(clearFolder ? { groupId: null } : {}),
- })
- .where(
- and(
- eq(chatGroups.id, id),
- this.ownership(),
- eq(chatGroups.userId, this.userId),
- eq(chatGroups.visibility, 'private'),
- ),
- )
- .returning();
-
- if (!result) {
- throw new Error('Chat group not found, already published, or access denied');
- }
-
- // The synthetic supervisor mirrors the group's visibility at creation
- // (private group β†’ private supervisor). Publish it together with the
- // group, otherwise other members would receive a `supervisorAgentId`
- // whose agent row their roster reads filter out.
- await this.db
- .update(agents)
- .set({ updatedAt: new Date(), visibility: 'public' })
- .where(
- and(
- eq(agents.visibility, 'private'),
- inArray(
- agents.id,
- this.db
- .select({ id: chatGroupsAgents.agentId })
- .from(chatGroupsAgents)
- .where(
- and(eq(chatGroupsAgents.chatGroupId, id), eq(chatGroupsAgents.role, 'supervisor')),
- ),
- ),
- ),
- );
-
- return result;
- }
-
- /**
- * Bidirectional visibility switch for the Permission panel. Router-level
- * guards decide who may call this (creator-only demotion, manager/owner
- * promotion) β€” this method only applies the ownership-scoped write.
- *
- * Mirrors AgentModel.setVisibility: a sidebar folder cannot mix
- * visibilities, so the group is rehomed to the ungrouped section of its new
- * scope when its folder no longer matches.
- */
- async setVisibility(id: string, visibility: 'private' | 'public'): Promise<ChatGroupItem | null> {
- const [current] = await this.db
- .select({ folderVisibility: sessionGroups.visibility })
- .from(chatGroups)
- .leftJoin(sessionGroups, eq(chatGroups.groupId, sessionGroups.id))
- .where(and(eq(chatGroups.id, id), this.ownership()))
- .limit(1);
- const folderVisibility = current?.folderVisibility as 'private' | 'public' | null | undefined;
- const clearFolder = folderVisibility != null && folderVisibility !== visibility;
-
- const [updated] = await this.db
- .update(chatGroups)
- .set({
- updatedAt: new Date(),
- visibility,
- ...(clearFolder ? { groupId: null } : {}),
- })
- .where(and(eq(chatGroups.id, id), this.ownership()))
- .returning();
-
- if (updated) {
- // Keep the synthetic supervisor's visibility in lockstep (mirrors
- // publishToWorkspace): a promoted group must expose its supervisor to
- // members, a demoted group must not leave the supervisor public.
- await this.db
- .update(agents)
- .set({ updatedAt: new Date(), visibility })
- .where(
- and(
- ne(agents.visibility, visibility),
- inArray(
- agents.id,
- this.db
- .select({ id: chatGroupsAgents.agentId })
- .from(chatGroupsAgents)
- .where(
- and(
- eq(chatGroupsAgents.chatGroupId, id),
- eq(chatGroupsAgents.role, 'supervisor'),
- ),
- ),
- ),
- ),
- );
- }
-
- return updated ?? null;
- }
-
- async addAgentToGroup(
- groupId: string,
- agentId: string,
- options?: { order?: number; role?: GroupMemberRole },
- ): Promise<NewChatGroupAgent> {
- const params: NewChatGroupAgent = {
- agentId,
- chatGroupId: groupId,
- order: options?.order || 0,
- role: options?.role || 'assistant',
- userId: this.userId,
- workspaceId: this.workspaceId ?? null,
- };
-
- const [result] = await this.db.insert(chatGroupsAgents).values(params).returning();
- return result;
- }
-
- /**
- * Add multiple agents to a group.
- * Automatically skips agents that are already in the group.
- *
- * @returns Object containing:
- * - `added`: Agents that were newly added to the group
- * - `existing`: Agent IDs that were already in the group (skipped)
- */
- async addAgentsToGroup(
- groupId: string,
- agentIds: string[],
- ): Promise<{ added: NewChatGroupAgent[]; existing: string[] }> {
- const group = await this.findById(groupId);
- if (!group) throw new TRPCError({ code: 'NOT_FOUND', message: 'Group not found' });
-
- // Composite visibility rule for group membership:
- // - A caller-owned private group may admit the caller's own private agents
- // alongside public ones.
- // - Any public group, or any group the caller doesn't own, must contain
- // only public agents β€” even the caller's own private agent can't be
- // added, because that would expose it to the other members.
- // `findById` already scopes by visibility, so reaching here with
- // `group.visibility === 'private'` implies `group.userId === this.userId`.
- const allowPrivateMembers = group.visibility === 'private' && group.userId === this.userId;
-
- if (agentIds.length > 0) {
- // Resolve each requested agent through the workspace + visibility
- // predicate so another user's private agent never enters this set; it
- // simply doesn't match the row filter, and we surface NOT_FOUND below.
- const visibleAgents = await this.db
- .select({
- id: agents.id,
- slug: agents.slug,
- userId: agents.userId,
- virtual: agents.virtual,
- visibility: agents.visibility,
- })
- .from(agents)
- .where(
- and(
- inArray(agents.id, agentIds),
- buildWorkspaceWhere(
- { userId: this.userId, workspaceId: this.workspaceId },
- {
- isDeleted: agents.isDeleted,
- userId: agents.userId,
- workspaceId: agents.workspaceId,
- visibility: agents.visibility,
- },
- ),
- ),
- );
-
- const visibleById = new Map(visibleAgents.map((row) => [row.id, row]));
- for (const agentId of agentIds) {
- const row = visibleById.get(agentId);
- if (!row) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
- }
- if (row.visibility === 'private' && !allowPrivateMembers) {
- // Caller owns this private agent (visibility predicate would have
- // hidden it otherwise) but the group can't hold private members.
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
- }
- }
-
- // `resolveGroupMembershipType` treats a virtual member as OWNED by its
- // group: the delete path takes it down with the group, the transfer path
- // rehomes it. Both are sound only while such an agent belongs to exactly
- // ONE group β€” otherwise deleting either group destroys an agent the
- // other still lists.
- //
- // The invariant is "exactly one", not "never joins one": the group agent
- // builder legitimately creates a `virtual: true` agent and adds it here,
- // and that is its first and only membership. So reject only a virtual
- // agent that is ALREADY on another group's roster β€” which nothing in the
- // product does, since the member picker filters virtual agents
- // (`buildQueryAgentsWhere`), leaving this enforced by a query rather
- // than by the write until now.
- // Builtins (Inbox, the agent builders) are provisioned per user and are
- // `virtual` like a group's own members, so the membership rules would
- // classify one as group-OWNED the moment it joined a roster β€” and
- // `removeAgentsFromGroup` deletes owned members. Letting someone add
- // their Inbox to a group and then leave the group would delete the
- // Inbox. They are nobody's group member; refuse at the door.
- const builtinAgentId = agentIds.find((id) => {
- const slug = visibleById.get(id)?.slug;
- return !!slug && RESERVED_BUILTIN_AGENT_SLUGS.includes(slug);
- });
- if (builtinAgentId) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: 'A builtin agent cannot join a chat group',
- });
- }
-
- const virtualAgentIds = agentIds.filter((id) => visibleById.get(id)?.virtual);
- if (virtualAgentIds.length > 0) {
- const [poached] = await this.db
- .select({ agentId: chatGroupsAgents.agentId })
- .from(chatGroupsAgents)
- .where(
- and(
- inArray(chatGroupsAgents.agentId, virtualAgentIds),
- ne(chatGroupsAgents.chatGroupId, groupId),
- ),
- )
- .limit(1);
-
- if (poached) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: 'A group-owned agent cannot join another group',
- });
- }
- }
- }
-
- const existingAgents = await this.getGroupAgents(groupId);
- const existingAgentIds = new Set(existingAgents.map((a) => a.agentId));
-
- const newAgentIds = agentIds.filter((id) => !existingAgentIds.has(id));
- const existingIds = agentIds.filter((id) => existingAgentIds.has(id));
-
- if (newAgentIds.length === 0) {
- return { added: [], existing: existingIds };
- }
-
- // Append new members after the current highest order so an incremental add
- // never collapses everyone to the default `order = 0` (which would make the
- // roster re-shuffle on every refetch). Supervisor rows sit at `order = -1`,
- // so a group holding only a supervisor yields maxOrder = -1 β†’ the first
- // member gets order 0.
- const maxOrder = existingAgents.reduce((max, agent) => Math.max(max, agent.order ?? 0), -1);
-
- const newAgents: NewChatGroupAgent[] = newAgentIds.map((agentId, index) => ({
- agentId,
- chatGroupId: groupId,
- enabled: true,
- order: maxOrder + 1 + index,
- userId: this.userId,
- workspaceId: this.workspaceId ?? null,
- }));
-
- const added = await this.db.insert(chatGroupsAgents).values(newAgents).returning();
-
- return { added, existing: existingIds };
- }
-
- private agentsOwnership = () =>
- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, chatGroupsAgents);
-
- async removeAgentFromGroup(groupId: string, agentId: string): Promise<void> {
- await this.db
- .delete(chatGroupsAgents)
- .where(
- and(
- eq(chatGroupsAgents.chatGroupId, groupId),
- eq(chatGroupsAgents.agentId, agentId),
- this.agentsOwnership(),
- ),
- );
- }
-
- /**
- * Batch remove multiple agents from a group.
- * More efficient than calling removeAgentFromGroup multiple times.
- */
- async removeAgentsFromGroup(groupId: string, agentIds: string[]): Promise<void> {
- if (agentIds.length === 0) return;
-
- await this.db
- .delete(chatGroupsAgents)
- .where(
- and(
- eq(chatGroupsAgents.chatGroupId, groupId),
- inArray(chatGroupsAgents.agentId, agentIds),
- this.agentsOwnership(),
- ),
- );
- }
-
- async updateAgentInGroup(
- groupId: string,
- agentId: string,
- updates: Partial<Pick<NewChatGroupAgent, 'enabled' | 'order'>> & { role?: GroupMemberRole },
- ): Promise<NewChatGroupAgent> {
- // A supervisor is the group's own synthetic orchestrator: every path that
- // creates one creates a fresh virtual agent for it, and the delete/transfer
- // paths rely on `supervisor ⟹ owned`. Promoting a `referenced` member would
- // break that invariant and put a member's personal agent on the group's
- // lifecycle, so it is refused rather than silently reclassified.
- if (updates.role === GROUP_SUPERVISOR_ROLE) {
- const [row] = await this.db
- .select({ role: chatGroupsAgents.role, slug: agents.slug, virtual: agents.virtual })
- .from(chatGroupsAgents)
- .innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))
- .where(
- and(
- eq(chatGroupsAgents.chatGroupId, groupId),
- eq(chatGroupsAgents.agentId, agentId),
- this.agentsOwnership(),
- ),
- );
-
- if (row && resolveGroupMembershipType(row) !== 'owned') {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: 'Only a group-owned member can act as the group supervisor',
- });
- }
- }
-
- const [result] = await this.db
- .update(chatGroupsAgents)
- .set({ ...updates, updatedAt: new Date() })
- .where(
- and(
- eq(chatGroupsAgents.chatGroupId, groupId),
- eq(chatGroupsAgents.agentId, agentId),
- this.agentsOwnership(),
- ),
- )
- .returning();
-
- return result;
- }
-
- // ******* Delete Methods ******* //
-
- /**
- * Agent ids that die with the given groups.
- *
- * `agents` has NO foreign key to `chat_groups` β€” the cascade only reaches the
- * junction β€” so deleting a group leaves its synthetic supervisor and its
- * group-built members behind forever: `virtual: true` hides them from every
- * list, so nothing will ever surface or reclaim them.
- *
- * Read from the RAW junction rows, with no visibility or ownership predicate
- * on the member agent. Those predicates belong to reads: a member another
- * workspace user flipped back to `private` is still owned by this group, and
- * filtering it out here is precisely how the previous service-level cleanup
- * leaked. The caller has already proven it may delete the group itself.
- */
- private findOwnedMemberAgentIds = async (
- executor: LobeChatDatabase,
- groupIds: string[],
- ): Promise<string[]> => {
- if (groupIds.length === 0) return [];
-
- const rows = await executor
- .select({ agentId: chatGroupsAgents.agentId })
- .from(chatGroupsAgents)
- .innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))
- .where(and(inArray(chatGroupsAgents.chatGroupId, groupIds), isOwnedMembership()));
-
- return [...new Set(rows.map((row) => row.agentId))];
- };
-
- /**
- * Builtin agents (Inbox, the agent builders, …) are provisioned per user and
- * are `virtual` like a group's own members, so `owned` on a malformed
- * junction row would be enough to take one down with a group. Their reserved
- * slugs are the one thing that always tells them apart β€” a cheap belt to the
- * `owned` braces, on a delete whose blast radius is somebody's Inbox.
- */
- private deleteOwnedMemberAgents = async (
- executor: LobeChatDatabase,
- agentIds: string[],
- ): Promise<string[]> => {
- if (agentIds.length === 0) return [];
-
- const deleted = await executor
- .delete(agents)
- .where(
- and(
- inArray(agents.id, agentIds),
- eq(agents.virtual, true),
- // A NULL slug predates slug generation and is not a builtin;
- // `NOT IN` alone would evaluate to NULL and skip those rows.
- or(isNull(agents.slug), notInArray(agents.slug, RESERVED_BUILTIN_AGENT_SLUGS)),
- ),
- )
- .returning({ id: agents.id });
-
- return deleted.map((row) => row.id);
- };
-
- /**
- * Delete a group together with the agents that only existed to serve it.
- *
- * Returns the deleted owned-agent ids so callers can report them; the delete
- * itself needs no follow-up.
- */
- async delete(id: string): Promise<{ deletedOwnedAgentIds: string[]; group: ChatGroupItem }> {
- return this.db.transaction(async (trx) => {
- // Collect BEFORE the delete: the junction rows cascade away with the
- // group, taking the only record of which agents were group-owned.
- const ownedAgentIds = await this.findOwnedMemberAgentIds(trx, [id]);
-
- const [result] = await trx
- .delete(chatGroups)
- .where(and(eq(chatGroups.id, id), this.ownership()))
- .returning();
-
- if (!result) {
- throw new Error('Chat group not found or access denied');
- }
-
- // Same transaction as the group delete: a cleanup that can be interrupted
- // between the two statements is a leak with extra steps.
- const deletedOwnedAgentIds = await this.deleteOwnedMemberAgents(trx, ownedAgentIds);
-
- return { deletedOwnedAgentIds, group: result };
- });
- }
-
- async deleteAll(): Promise<void> {
- await this.db.transaction(async (trx) => {
- const groupIds = await trx
- .select({ id: chatGroups.id })
- .from(chatGroups)
- .where(this.ownership());
-
- const ownedAgentIds = await this.findOwnedMemberAgentIds(
- trx,
- groupIds.map((group) => group.id),
- );
-
- await trx.delete(chatGroups).where(this.ownership());
-
- await this.deleteOwnedMemberAgents(trx, ownedAgentIds);
- });
- }
-
- /**
- * Same-workspace ownership handover: what accepting a member-to-member
- * transfer request executes. Deliberately narrower than the cross-scope
- * `AgentGroupRepository.transferToWorkspace` β€” the group stays where it is,
- * so nothing is cloned and no conversation moves. Only ownership flips: the
- * group row, its junction rows, and the member agents that exist to serve it
- * (supervisor + generated members). Referenced standalone members keep their
- * own owners β€” membership never owned them.
- *
- * Runs inside the caller's transaction: the caller flips the transfer
- * request's status in the same `trx`, so a stale/raced accept rolls both
- * back together.
- */
- transferGroupOwnership = async (
- trx: Transaction,
- params: {
- /** The owner recorded on the transfer request; a mismatch means the request is stale. */
- fromUserId: string;
- groupId: string;
- toUserId: string;
- },
- ): Promise<void> => {
- const { fromUserId, groupId, toUserId } = params;
- if (!this.workspaceId) throw new Error(CHAT_GROUP_OWNERSHIP_STALE);
-
- // FOR UPDATE: serialize against a concurrent cross-scope transfer, delete,
- // or second accept; the loser re-reads and fails the staleness check.
- const [group] = await trx
- .select()
- .from(chatGroups)
- .where(and(eq(chatGroups.id, groupId), eq(chatGroups.workspaceId, this.workspaceId)))
- .for('update');
- if (!group || group.userId !== fromUserId) throw new Error(CHAT_GROUP_OWNERSHIP_STALE);
-
- // Raw roster read (no visibility predicate): the owned/referenced split
- // must see every member, exactly as delete and the cross-scope transfer do.
- const memberRows = await trx
- .select({
- agentId: chatGroupsAgents.agentId,
- role: chatGroupsAgents.role,
- slug: agents.slug,
- virtual: agents.virtual,
- })
- .from(chatGroupsAgents)
- .innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))
- .where(eq(chatGroupsAgents.chatGroupId, groupId));
-
- const agentIds = memberRows.map((row) => row.agentId);
- const ownedAgentIds = memberRows
- .filter((row) => resolveGroupMembershipType(row) === 'owned')
- .map((row) => row.agentId);
-
- // Same lock-then-guard as `transferToWorkspace`: serialize with a
- // concurrent transfer of any member agent BEFORE consulting the pending
- // job tables, so two racing operations cannot both pass the guards.
- if (agentIds.length > 0) {
- await trx
- .select({ id: agents.id })
- .from(agents)
- .where(inArray(agents.id, agentIds))
- .orderBy(asc(agents.id))
- .for('update');
- }
-
- // A share row keeps the agent bound to its current owner and workspace,
- // including when the share is paused. Check only owned members: referenced
- // standalone agents remain with their owner and do not move with the group.
- if (ownedAgentIds.length > 0) {
- const [existingShare] = await trx
- .select({ id: agentShares.id })
- .from(agentShares)
- .where(inArray(agentShares.agentId, ownedAgentIds))
- .limit(1);
- if (existingShare) throw new Error(AGENT_SHARED_TRANSFER_BLOCKED);
- }
-
- // A REFERENCED member that is private to someone other than the recipient
- // would silently vanish from the roster for the group's new owner (every
- // roster read applies member-agent visibility). Refuse instead β€” same
- // policy as the cross-scope transfer; the member's owner can share it and
- // the recipient can retry. Evaluated from a re-read AFTER the agent locks
- // above, so a visibility flip racing this handover cannot slip past the
- // guard on a stale snapshot.
- const referencedIds = memberRows
- .filter((row) => resolveGroupMembershipType(row) === 'referenced')
- .map((row) => row.agentId);
- if (referencedIds.length > 0) {
- const lockedReferenced = await trx
- .select({ userId: agents.userId, visibility: agents.visibility })
- .from(agents)
- .where(inArray(agents.id, referencedIds));
- const hasHiddenReferencedMember = lockedReferenced.some(
- (row) => row.visibility === 'private' && row.userId !== toUserId,
- );
- if (hasHiddenReferencedMember) throw new Error(CHAT_GROUP_TRANSFER_HIDDEN_MEMBER);
- }
-
- // An unfinished backfill still rewrites rows toward the OLD owner's
- // request; hand the group over only once it has drained.
- if (
- (await AgentTransferJobModel.hasPendingJobForAgents(trx, agentIds)) ||
- (await AgentTransferJobModel.hasPendingJobForGroups(trx, [groupId]))
- ) {
- throw new Error(AGENT_TRANSFER_IN_PROGRESS);
- }
- if (
- (await AgentCopyJobModel.hasPendingCopyJobForSourceAgents(trx, agentIds)) ||
- (await AgentCopyJobModel.hasPendingCopyJobForSourceGroups(trx, [groupId]))
- ) {
- throw new Error(AGENT_COPY_IN_PROGRESS);
- }
-
- // An ownership flip does not make the group's content newer, and the
- // scope/visibility/folder/pin all stay: the group is not moving anywhere.
- // `clientId` is cleared β€” unique per (clientId, userId), it belongs to the
- // previous owner's client-side sync and would abort the accept if the
- // recipient already owns a group with the same value.
- await trx
- .update(chatGroups)
- .set({ clientId: null, updatedAt: chatGroups.updatedAt, userId: toUserId })
- .where(eq(chatGroups.id, groupId));
-
- // The junction rows belong to the GROUP, so all of them follow its owner β€”
- // including the rows pointing at referenced members that stay put.
- await trx
- .update(chatGroupsAgents)
- .set({ userId: toUserId })
- .where(eq(chatGroupsAgents.chatGroupId, groupId));
-
- if (ownedAgentIds.length > 0) {
- // Re-home device bindings on the owned agents (supervisor + generated
- // members): a boundDeviceId / fixed device policy pointing at the
- // previous owner's personal or private device would leave the
- // recipient's group runs unroutable. Same sanitation as the member
- // agent handover.
- const ownedRows = await trx
- .select({ agencyConfig: agents.agencyConfig, id: agents.id, visibility: agents.visibility })
- .from(agents)
- .where(inArray(agents.id, ownedAgentIds));
- const cleanedConfigs = await sanitizeAgencyConfigsForWorkspace(
- trx,
- this.workspaceId,
- ownedRows.map((row) => row.agencyConfig),
- { viewerUserId: toUserId },
- );
- for (const [index, row] of ownedRows.entries()) {
- // `clientId` cleared for the same reason as the single-agent handover:
- // it is unique per (clientId, userId) and belongs to the previous
- // owner's client-side sync.
- await trx
- .update(agents)
- .set({
- agencyConfig: cleanedConfigs[index],
- clientId: null,
- updatedAt: agents.updatedAt,
- userId: toUserId,
- })
- .where(eq(agents.id, row.id));
- }
-
- // Owner-attributed runtime rows (cron jobs, bot providers) execute AS
- // their `userId`; the previous owner's rows on the owned agents re-home
- // with them β€” DISABLED, so nothing runs silently under the recipient's
- // identity and budget. Same policy as the single-agent handover.
- await trx
- .update(agentCronJobs)
- .set({ enabled: false, updatedAt: agentCronJobs.updatedAt, userId: toUserId })
- .where(
- and(inArray(agentCronJobs.agentId, ownedAgentIds), eq(agentCronJobs.userId, fromUserId)),
- );
- await trx
- .update(agentBotProviders)
- .set({ enabled: false, updatedAt: agentBotProviders.updatedAt, userId: toUserId })
- .where(
- and(
- inArray(agentBotProviders.agentId, ownedAgentIds),
- eq(agentBotProviders.userId, fromUserId),
- ),
- );
- // Quota account bindings (and exclusively-consumed provider accounts)
- // re-home: both cascade on user deletion. See the util.
- await rehomeAgentQuotaBindingsForRecipient(trx, {
- agentIds: ownedAgentIds,
- fromUserId,
- recipientId: toUserId,
- });
-
- // Label assignments (and exclusively-assigned backing labels) re-home:
- // both cascade on user deletion. See the util.
- await rehomeAgentLabelsForRecipient(trx, {
- agentIds: ownedAgentIds,
- fromUserId,
- recipientId: toUserId,
- });
-
- // Tasks stay with their creators (moving ownership breaks in-flight run
- // identity and splits subtrees). But owned agents that are PRIVATE stop
- // resolving for everyone but the recipient, so detach other users' task
- // assignments to them β€” the schedule goes quiet rather than erroring.
- const privateOwnedIds = ownedRows
- .filter((row) => row.visibility === 'private')
- .map((row) => row.id);
- if (privateOwnedIds.length > 0) {
- await trx
- .update(tasks)
- .set({ assigneeAgentId: null, updatedAt: tasks.updatedAt })
- .where(
- and(
- inArray(tasks.assigneeAgentId, privateOwnedIds),
- ne(tasks.createdByUserId, toUserId),
- ),
- );
-
- // Private owned agents also leave other members' PROJECTS explicitly β€”
- // project agent listings apply member-agent visibility, so those
- // projects would otherwise keep a silent hole. Same policy as the
- // single-agent handover.
- const projectLinks = await trx
- .select({ linkId: projectAgents.id, projectOwnerId: projects.userId })
- .from(projectAgents)
- .innerJoin(projects, eq(projectAgents.projectId, projects.id))
- .where(inArray(projectAgents.agentId, privateOwnedIds));
- const leavingProjectLinkIds = projectLinks
- .filter((link) => link.projectOwnerId !== toUserId)
- .map((link) => link.linkId);
- if (leavingProjectLinkIds.length > 0) {
- await trx.delete(projectAgents).where(inArray(projectAgents.id, leavingProjectLinkIds));
- }
- }
-
- // Knowledge mounts on the owned agents whose KB / file the recipient
- // cannot access would survive as dead links the runtime silently skips.
- // Detach them β€” same policy as the single-agent handover; the manifest
- // surfaces the count to both parties before acceptance.
- await detachAgentKnowledgeMountsForRecipient(trx, {
- agentIds: ownedAgentIds,
- recipientId: toUserId,
- workspaceId: this.workspaceId,
- });
- // The retained mounts the previous owner created re-home with the owned
- // agents β€” the junction `user_id` cascades on user deletion, and the
- // group's knowledge must not die with the previous owner's account.
- await rehomeRetainedAgentKnowledgeMounts(trx, {
- agentIds: ownedAgentIds,
- fromUserId,
- recipientId: toUserId,
- workspaceId: this.workspaceId,
- });
-
- // Connectors: OAuth credentials are personal identity and never travel.
- // Agent-owned rows on the owned members re-home as disconnected shells
- // the recipient must reauthorize; other members' mounted rows unmount.
- await rehomeAgentConnectorsForRecipient(trx, {
- agentIds: ownedAgentIds,
- recipientId: toUserId,
- });
-
- // Expertise + VFS documents: same policies as the single-agent handover
- // (agent-exclusive domains re-home / shared ones unbind; the previous
- // owner's document rows re-home so account deletion cannot strip them).
- await rehomeAgentExpertiseForRecipient(trx, {
- agentIds: ownedAgentIds,
- recipientId: toUserId,
- workspaceId: this.workspaceId,
- });
- await rehomeAgentDocumentsForRecipient(trx, {
- agentIds: ownedAgentIds,
- fromUserId,
- recipientId: toUserId,
- workspaceId: this.workspaceId,
- });
- }
- };
-
- // ******* Agent Query Methods ******* //
-
- async getGroupAgents(groupId: string): Promise<ChatGroupAgentItem[]> {
- return this.db.query.chatGroupsAgents.findMany({
- orderBy: [chatGroupsAgents.order, chatGroupsAgents.createdAt, chatGroupsAgents.agentId],
- where: and(
- eq(chatGroupsAgents.chatGroupId, groupId),
- this.agentsOwnership(),
- this.memberAgentVisibleExists(),
- ),
- });
- }
-
- /**
- * Read-only roster of a group's **enabled** agents joined with their agent meta
- * (title/description) and membership role, ordered by member order.
- *
- * Used to inject the group member list β€” with the real `agt_*` IDs β€” into the
- * supervisor/member runtime context so the orchestration model dispatches
- * members by their actual IDs instead of hallucinating role names (which then
- * fail to resolve to an agent, surfacing as "Agent member(s) failed to start").
- *
- * Disabled members are excluded (matching `getEnabledGroupAgents`): advertising
- * them in `<group_participants>` would let the supervisor invoke a disabled
- * agent, since the group-management runtime accepts whatever id it dispatches.
- */
- async getGroupAgentsWithMeta(groupId: string): Promise<
- Array<{
- agentId: string;
- description: string | null;
- role: string | null;
- title: string | null;
- }>
- > {
- return this.db
- .select({
- agentId: chatGroupsAgents.agentId,
- description: agents.description,
- name: agents.name,
- role: chatGroupsAgents.role,
- title: agents.title,
- })
- .from(chatGroupsAgents)
- .innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))
- .where(
- and(
- eq(chatGroupsAgents.chatGroupId, groupId),
- eq(chatGroupsAgents.enabled, true),
- this.agentsOwnership(),
- this.memberAgentVisibility(),
- ),
- )
- .orderBy(chatGroupsAgents.order, chatGroupsAgents.createdAt, chatGroupsAgents.agentId);
- }
-
- /**
- * Count still-private member agents of a group β€” the publish guard uses
- * this to reject sharing a group whose members would leak on publish.
- */
- async countPrivateGroupAgents(groupId: string): Promise<number> {
- const rows = await this.db
- .select({ agentId: chatGroupsAgents.agentId })
- .from(chatGroupsAgents)
- .innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))
- .where(
- and(
- eq(chatGroupsAgents.chatGroupId, groupId),
- eq(agents.visibility, 'private'),
- // The synthetic supervisor mirrors the group's own visibility, so a
- // private group always owns one private agent. Counting it makes the
- // publish guard unsatisfiable β€” every private group would look like
- // it still holds private members and could never be shared. Only
- // real members can block a publish.
- ne(chatGroupsAgents.role, 'supervisor'),
- this.agentsOwnership(),
- ),
- );
-
- return rows.length;
- }
-
- async getEnabledGroupAgents(groupId: string): Promise<ChatGroupAgentItem[]> {
- return this.db.query.chatGroupsAgents.findMany({
- orderBy: [chatGroupsAgents.order, chatGroupsAgents.createdAt, chatGroupsAgents.agentId],
- where: and(
- eq(chatGroupsAgents.chatGroupId, groupId),
- eq(chatGroupsAgents.enabled, true),
- this.agentsOwnership(),
- this.memberAgentVisibleExists(),
- ),
- });
- }
-
- /**
- * Count workspace groups that would break if the given agent were demoted to
- * private: groups where it is the **supervisor** and the group is visible to
- * someone else (public, or owned by another member). A private supervisor is
- * unresolvable for every other viewer, which makes the whole group unusable β€”
- * so demotion is rejected at the source (mirrors
- * `countTasksBlockingAgentDemotion`). Regular members are deliberately NOT
- * counted: roster reads drop a non-visible member per viewer instead.
- * Deliberately workspace-wide and visibility-blind (NOT `ownership()`):
- * other members' private groups are invisible to the caller but their
- * supervisor would still break.
- */
- async countGroupsBlockingAgentDemotion(
- agentId: string,
- agentOwnerUserId: string,
- ): Promise<number> {
- if (!this.workspaceId) return 0;
- const [row] = await this.db
- .select({ count: sql<number>`count(*)` })
- .from(chatGroupsAgents)
- .innerJoin(chatGroups, eq(chatGroupsAgents.chatGroupId, chatGroups.id))
- .where(
- and(
- eq(chatGroups.workspaceId, this.workspaceId),
- eq(chatGroupsAgents.agentId, agentId),
- eq(chatGroupsAgents.role, 'supervisor'),
- or(eq(chatGroups.visibility, 'public'), ne(chatGroups.userId, agentOwnerUserId)),
- ),
- );
- return Number(row?.count ?? 0);
- }
-
- async getGroupsWithAgents(agentIds?: string[]): Promise<ChatGroupItem[]> {
- if (!agentIds || agentIds.length === 0) {
- return this.query();
- }
-
- // Find groups containing any of the specified agents
- const groupIds = await this.db
- .selectDistinct({ chatGroupId: chatGroupsAgents.chatGroupId })
- .from(chatGroupsAgents)
- .where(
- and(
- this.agentsOwnership(),
- inArray(chatGroupsAgents.agentId, agentIds),
- this.memberAgentVisibleExists(),
- ),
- );
-
- if (groupIds.length === 0) return [];
-
- return this.db.query.chatGroups.findMany({
- orderBy: [desc(chatGroups.updatedAt)],
- where: and(
- inArray(
- chatGroups.id,
- groupIds.map((g) => g.chatGroupId),
- ),
- this.ownership(),
- ),
- });
- }
-}
diff --git a/packages/database/src/models/chatGroup/constants.ts b/packages/database/src/models/chatGroup/constants.ts
new file mode 100644
index 00000000000..168d97749f2
--- /dev/null
+++ b/packages/database/src/models/chatGroup/constants.ts
@@ -0,0 +1,17 @@
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
+
+/** Slugs owned by builtin provisioning; a group delete must never reach one. */
+export const RESERVED_BUILTIN_AGENT_SLUGS: string[] = Object.values(BUILTIN_AGENT_SLUGS);
+
+/**
+ * The group is no longer where the transfer request said it was: moved scope,
+ * changed hands, or was deleted. The request that referenced it can never
+ * complete.
+ */
+export const CHAT_GROUP_OWNERSHIP_STALE = 'CHAT_GROUP_OWNERSHIP_STALE';
+
+/**
+ * Handover refused: the group references a member agent that is private to
+ * someone other than the recipient, who would silently lose that participant.
+ */
+export const CHAT_GROUP_TRANSFER_HIDDEN_MEMBER = 'CHAT_GROUP_TRANSFER_HIDDEN_MEMBER';
diff --git a/packages/database/src/models/chatGroup/deletion.ts b/packages/database/src/models/chatGroup/deletion.ts
new file mode 100644
index 00000000000..d47f6bdc872
--- /dev/null
+++ b/packages/database/src/models/chatGroup/deletion.ts
@@ -0,0 +1,65 @@
+import { and, eq, inArray } from 'drizzle-orm';
+
+import type { ChatGroupItem } from '../../schemas';
+import { agents, chatGroups, chatGroupsAgents } from '../../schemas';
+import { isOwnedMembership } from '../../utils/groupMembership';
+import { type ChatGroupContext, groupOwnership } from './scope';
+
+/**
+ * Agent ids that die with the given groups.
+ *
+ * `agents` has NO foreign key to `chat_groups` β€” the cascade only reaches the
+ * junction β€” so deleting a group leaves its synthetic supervisor and its
+ * group-built members behind forever: `virtual: true` hides them from every
+ * list, so nothing will ever surface or reclaim them.
+ *
+ * Read from the RAW junction rows, with no visibility or ownership predicate
+ * on the member agent. Those predicates belong to reads: a member another
+ * workspace user flipped back to `private` is still owned by this group, and
+ * filtering it out here is precisely how the previous service-level cleanup
+ * leaked. The caller has already proven it may delete the group itself.
+ *
+ * Must be read BEFORE the group delete: the junction rows cascade away with
+ * the group, taking the only record of which agents were group-owned.
+ */
+export const findOwnedMemberAgentIds = async (
+ ctx: ChatGroupContext,
+ groupIds: string[],
+): Promise<string[]> => {
+ if (groupIds.length === 0) return [];
+
+ const rows = await ctx.db
+ .select({ agentId: chatGroupsAgents.agentId })
+ .from(chatGroupsAgents)
+ .innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))
+ .where(and(inArray(chatGroupsAgents.chatGroupId, groupIds), isOwnedMembership()));
+
+ return [...new Set(rows.map((row) => row.agentId))];
+};
+
+export const findGroupIdsInScope = async (ctx: ChatGroupContext): Promise<string[]> => {
+ const rows = await ctx.db
+ .select({ id: chatGroups.id })
+ .from(chatGroups)
+ .where(groupOwnership(ctx));
+
+ return rows.map((row) => row.id);
+};
+
+/** Delete one group row; its junction rows cascade. Throws when not in scope. */
+export const deleteGroup = async (ctx: ChatGroupContext, id: string): Promise<ChatGroupItem> => {
+ const [result] = await ctx.db
+ .delete(chatGroups)
+ .where(and(eq(chatGroups.id, id), groupOwnership(ctx)))
+ .returning();
+
+ if (!result) {
+ throw new Error('Chat group not found or access denied');
+ }
+
+ return result;
+};
+
+export const deleteAllGroups = async (ctx: ChatGroupContext): Promise<void> => {
+ await ctx.db.delete(chatGroups).where(groupOwnership(ctx));
+};
diff --git a/packages/database/src/models/chatGroup/index.ts b/packages/database/src/models/chatGroup/index.ts
new file mode 100644
index 00000000000..ba3615b94c3
--- /dev/null
+++ b/packages/database/src/models/chatGroup/index.ts
@@ -0,0 +1,660 @@
+import { and, desc, eq, inArray, isNull, ne, or, sql } from 'drizzle-orm';
+
+import type {
+ ChatGroupAgentItem,
+ ChatGroupItem,
+ NewChatGroup,
+ NewChatGroupAgent,
+} from '../../schemas';
+import { agents, chatGroups, chatGroupsAgents, sessionGroups } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import type { GroupMemberRole } from '../../utils/groupMembership';
+import { GROUP_SUPERVISOR_ROLE } from '../../utils/groupMembership';
+import { normalizeInboxAgentAvatar } from '../../utils/inboxAgent';
+import { buildWorkspacePayload, buildWorkspaceWhere } from '../../utils/workspace';
+import * as deletion from './deletion';
+import * as membership from './membership';
+import { type ChatGroupContext, groupAgentsOwnership, groupOwnership } from './scope';
+
+export { CHAT_GROUP_OWNERSHIP_STALE, CHAT_GROUP_TRANSFER_HIDDEN_MEMBER } from './constants';
+
+export class ChatGroupModel {
+ private userId: string;
+ private db: LobeChatDatabase;
+ private workspaceId?: string;
+
+ private ctx: ChatGroupContext;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.userId = userId;
+ this.db = db;
+ this.workspaceId = workspaceId;
+ this.ctx = { db, model: this, userId, workspaceId };
+ }
+
+ private ownership = () => groupOwnership(this.ctx);
+
+ private agentsOwnership = () => groupAgentsOwnership(this.ctx);
+
+ /**
+ * Visibility predicate on the member's `agents` row itself. Group membership
+ * (the junction row) does not grant access to the agent: when a member agent
+ * is switched back to private by its owner, every roster read must drop it
+ * for other members β€” otherwise the join would keep leaking the agent's
+ * config/meta through group surfaces.
+ */
+ private memberAgentVisibility = () =>
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ {
+ isDeleted: agents.isDeleted,
+ userId: agents.userId,
+ workspaceId: agents.workspaceId,
+ visibility: agents.visibility,
+ },
+ );
+
+ /**
+ * Same guard as an EXISTS subquery, for junction queries that don't join
+ * `agents`. The subquery is spelled with raw identifiers (not drizzle column
+ * refs) because the relational query builder rebinds every referenced column
+ * in `where` to the primary table's alias, which would corrupt the subquery.
+ * Semantics mirror `buildWorkspaceWhere`.
+ */
+ private memberAgentVisibleExists = () => {
+ if (!this.workspaceId) {
+ return sql`EXISTS (SELECT 1 FROM "agents" "ma" WHERE "ma"."id" = ${chatGroupsAgents.agentId} AND "ma"."user_id" = ${this.userId} AND "ma"."workspace_id" IS NULL AND "ma"."is_deleted" IS NOT TRUE)`;
+ }
+ return sql`EXISTS (SELECT 1 FROM "agents" "ma" WHERE "ma"."id" = ${chatGroupsAgents.agentId} AND "ma"."workspace_id" = ${this.workspaceId} AND ("ma"."visibility" IS NULL OR "ma"."visibility" = 'public' OR ("ma"."visibility" = 'private' AND "ma"."user_id" = ${this.userId})) AND "ma"."is_deleted" IS NOT TRUE)`;
+ };
+
+ /**
+ * Get member avatar metas (avatar + backgroundColor) grouped by chatGroupId,
+ * ordered by member order. Inbox members fall back to the default avatar.
+ */
+ getMemberAvatarsByGroupIds = async (
+ groupIds: string[],
+ ): Promise<Map<string, Array<{ avatar: string | null; backgroundColor: string | null }>>> => {
+ const map = new Map<string, Array<{ avatar: string | null; backgroundColor: string | null }>>();
+ if (groupIds.length === 0) return map;
+
+ const rows = await this.db
+ .select({
+ avatar: agents.avatar,
+ backgroundColor: agents.backgroundColor,
+ chatGroupId: chatGroupsAgents.chatGroupId,
+ slug: agents.slug,
+ })
+ .from(chatGroupsAgents)
+ .innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))
+ .where(and(inArray(chatGroupsAgents.chatGroupId, groupIds), this.memberAgentVisibility()))
+ .orderBy(chatGroupsAgents.order, chatGroupsAgents.createdAt, chatGroupsAgents.agentId);
+
+ for (const { avatar, backgroundColor, chatGroupId, slug } of rows) {
+ const list = map.get(chatGroupId) ?? [];
+ list.push({ avatar: normalizeInboxAgentAvatar(avatar, { slug }), backgroundColor });
+ map.set(chatGroupId, list);
+ }
+
+ return map;
+ };
+
+ // ******* Query Methods ******* //
+
+ /**
+ * The supervisor agent a group's conversation answers to, or `null`.
+ *
+ * Deliberately scoped by workspace rather than by {@link ownership}: callers
+ * use this to look up what the group's author decided (its supervisor's
+ * permission policies), which must not depend on whether *this* caller can
+ * see the group row. A visibility-scoped miss would return `null` and fail
+ * open.
+ */
+ getSupervisorAgentId = async (groupId: string): Promise<string | null> => {
+ const [row] = await this.db
+ .select({ agentId: chatGroupsAgents.agentId })
+ .from(chatGroupsAgents)
+ .where(
+ and(
+ eq(chatGroupsAgents.chatGroupId, groupId),
+ eq(chatGroupsAgents.role, GROUP_SUPERVISOR_ROLE),
+ this.workspaceId
+ ? eq(chatGroupsAgents.workspaceId, this.workspaceId)
+ : and(eq(chatGroupsAgents.userId, this.userId), isNull(chatGroupsAgents.workspaceId)),
+ ),
+ )
+ .limit(1);
+
+ return row?.agentId ?? null;
+ };
+
+ async findById(id: string): Promise<ChatGroupItem | undefined> {
+ const item = await this.db.query.chatGroups.findFirst({
+ where: and(eq(chatGroups.id, id), this.ownership()),
+ });
+
+ return item;
+ }
+
+ async query(): Promise<ChatGroupItem[]> {
+ return this.db.query.chatGroups.findMany({
+ orderBy: [desc(chatGroups.updatedAt)],
+ where: this.ownership(),
+ });
+ }
+
+ /**
+ * Get a chat group by the forkedFromIdentifier stored in config
+ * @param forkedFromIdentifier - The source group's market identifier
+ * @returns group id if exists, null otherwise
+ */
+ async getGroupByForkedFromIdentifier(forkedFromIdentifier: string): Promise<string | null> {
+ const result = await this.db.query.chatGroups.findFirst({
+ columns: { id: true },
+ orderBy: [desc(chatGroups.updatedAt)],
+ where: and(
+ this.ownership(),
+ sql`${chatGroups.config}->>'forkedFromIdentifier' = ${forkedFromIdentifier}`,
+ ),
+ });
+ return result?.id ?? null;
+ }
+
+ async queryWithMemberDetails(): Promise<any[]> {
+ const groups = await this.query();
+ if (groups.length === 0) return [];
+
+ const groupIds = groups.map((g) => g.id);
+
+ const groupAgents = await this.db.query.chatGroupsAgents.findMany({
+ where: and(
+ inArray(chatGroupsAgents.chatGroupId, groupIds),
+ this.agentsOwnership(),
+ this.memberAgentVisibleExists(),
+ ),
+ with: { agent: true },
+ });
+
+ const groupAgentMap = new Map<string, any[]>();
+
+ for (const groupAgent of groupAgents) {
+ if (!groupAgent.agent) continue;
+
+ const groupList = groupAgentMap.get(groupAgent.chatGroupId) || [];
+ groupList.push(groupAgent.agent);
+ groupAgentMap.set(groupAgent.chatGroupId, groupList);
+ }
+
+ return groups.map((group) => ({
+ ...group,
+ agents: groupAgentMap.get(group.id) || [],
+ }));
+ }
+
+ async findGroupWithAgents(groupId: string): Promise<{
+ agents: ChatGroupAgentItem[];
+ group: ChatGroupItem;
+ } | null> {
+ const group = await this.findById(groupId);
+ if (!group) return null;
+
+ const agents = await this.db.query.chatGroupsAgents.findMany({
+ orderBy: [chatGroupsAgents.order, chatGroupsAgents.createdAt, chatGroupsAgents.agentId],
+ where: and(
+ eq(chatGroupsAgents.chatGroupId, groupId),
+ this.agentsOwnership(),
+ this.memberAgentVisibleExists(),
+ ),
+ });
+
+ return { agents, group };
+ }
+
+ // ******* Create Methods ******* //
+
+ async create(params: Omit<NewChatGroup, 'userId'>): Promise<ChatGroupItem> {
+ const [result] = await this.db
+ .insert(chatGroups)
+ .values(
+ buildWorkspacePayload(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ { ...params },
+ ),
+ )
+ .returning();
+
+ return result;
+ }
+
+ async createWithAgents(
+ groupParams: Omit<NewChatGroup, 'userId'>,
+ agentIds: string[],
+ ): Promise<{ agents: NewChatGroupAgent[]; group: ChatGroupItem }> {
+ const group = await this.create(groupParams);
+
+ if (agentIds.length === 0) {
+ return { agents: [], group };
+ }
+
+ const agentParams: NewChatGroupAgent[] = agentIds.map((agentId, index) => ({
+ agentId,
+ chatGroupId: group.id,
+ order: index,
+ userId: this.userId,
+ workspaceId: this.workspaceId ?? null,
+ }));
+
+ const agents = await this.db.insert(chatGroupsAgents).values(agentParams).returning();
+
+ return { agents, group };
+ }
+
+ // ******* Update Methods ******* //
+
+ /**
+ * A move target must be a folder the caller can see, and a workspace-public
+ * group may only sit in a public folder. `chat_groups.groupId` is read by
+ * every member's sidebar now, and the foreign key only proves the folder
+ * exists β€” another workspace's folder, or another member's private one,
+ * satisfies it and then renders as Ungrouped for everyone who cannot see it.
+ * Mirrors `AgentModel.assertSessionGroupAssignable`.
+ */
+ private async assertFolderAssignable(id: string, groupId: string) {
+ const [folder] = await this.db
+ .select({ visibility: sessionGroups.visibility })
+ .from(sessionGroups)
+ .where(
+ and(
+ eq(sessionGroups.id, groupId),
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ {
+ isDeleted: sessionGroups.isDeleted,
+ userId: sessionGroups.userId,
+ visibility: sessionGroups.visibility,
+ workspaceId: sessionGroups.workspaceId,
+ },
+ ),
+ ),
+ )
+ .limit(1);
+
+ if (!folder) throw new Error(`Session group ${groupId} not found in current scope`);
+
+ if (!this.workspaceId) return;
+
+ const [group] = await this.db
+ .select({ visibility: chatGroups.visibility })
+ .from(chatGroups)
+ .where(and(eq(chatGroups.id, id), this.ownership()))
+ .limit(1);
+
+ // Same exact-match rule as agents: the render path resolves a private
+ // item's folder only against private folders and a public item's only
+ // against public ones, so either mismatch lands it in Ungrouped.
+ if (group && group.visibility !== folder.visibility)
+ throw new Error(
+ `A ${group.visibility} chat group cannot be moved into a ${folder.visibility} folder`,
+ );
+ }
+
+ async update(id: string, value: Partial<ChatGroupItem>): Promise<ChatGroupItem> {
+ if (value.groupId) await this.assertFolderAssignable(id, value.groupId);
+
+ // Scope columns never travel through the generic update. The router hands
+ // this a partial insert schema, so without stripping them a member could
+ // re-scope another member's group now that the ownership predicate spans
+ // every visible workspace row. Ignored rather than rejected so a client
+ // that sends an extra field still gets its real edit applied. Publishing
+ // has its own path and writes `visibility` directly.
+ const { userId: _userId, visibility: _visibility, workspaceId: _workspaceId, ...safe } = value;
+
+ const [result] = await this.db
+ .update(chatGroups)
+ .set(safe)
+ .where(and(eq(chatGroups.id, id), this.ownership()))
+ .returning();
+
+ if (!result) {
+ throw new Error('Chat group not found or access denied');
+ }
+
+ return result;
+ }
+
+ /**
+ * Publish a private chat group into the workspace. One-way: once shared,
+ * other members may have started using it, so we never let it slip back to
+ * `private`. Restricted to the creator's own still-private group.
+ */
+ async publishToWorkspace(id: string): Promise<ChatGroupItem> {
+ // Rehome exactly as `setVisibility` does. A folder cannot mix
+ // visibilities, so publishing out of a private Category has to release the
+ // folder too β€” left in place, the group would be public while its folder
+ // is not, and the sidebar would show it in Ungrouped rather than where the
+ // user published it from.
+ const [current] = await this.db
+ .select({ folderVisibility: sessionGroups.visibility })
+ .from(chatGroups)
+ .leftJoin(sessionGroups, eq(chatGroups.groupId, sessionGroups.id))
+ .where(and(eq(chatGroups.id, id), this.ownership()))
+ .limit(1);
+ const clearFolder = current?.folderVisibility != null && current.folderVisibility !== 'public';
+
+ const [result] = await this.db
+ .update(chatGroups)
+ .set({
+ updatedAt: new Date(),
+ visibility: 'public',
+ ...(clearFolder ? { groupId: null } : {}),
+ })
+ .where(
+ and(
+ eq(chatGroups.id, id),
+ this.ownership(),
+ eq(chatGroups.userId, this.userId),
+ eq(chatGroups.visibility, 'private'),
+ ),
+ )
+ .returning();
+
+ if (!result) {
+ throw new Error('Chat group not found, already published, or access denied');
+ }
+
+ // The synthetic supervisor mirrors the group's visibility at creation
+ // (private group β†’ private supervisor). Publish it together with the
+ // group, otherwise other members would receive a `supervisorAgentId`
+ // whose agent row their roster reads filter out.
+ await this.db
+ .update(agents)
+ .set({ updatedAt: new Date(), visibility: 'public' })
+ .where(
+ and(
+ eq(agents.visibility, 'private'),
+ inArray(
+ agents.id,
+ this.db
+ .select({ id: chatGroupsAgents.agentId })
+ .from(chatGroupsAgents)
+ .where(
+ and(eq(chatGroupsAgents.chatGroupId, id), eq(chatGroupsAgents.role, 'supervisor')),
+ ),
+ ),
+ ),
+ );
+
+ return result;
+ }
+
+ /**
+ * Bidirectional visibility switch for the Permission panel. Router-level
+ * guards decide who may call this (creator-only demotion, manager/owner
+ * promotion) β€” this method only applies the ownership-scoped write.
+ *
+ * Mirrors AgentModel.setVisibility: a sidebar folder cannot mix
+ * visibilities, so the group is rehomed to the ungrouped section of its new
+ * scope when its folder no longer matches.
+ */
+ async setVisibility(id: string, visibility: 'private' | 'public'): Promise<ChatGroupItem | null> {
+ const [current] = await this.db
+ .select({ folderVisibility: sessionGroups.visibility })
+ .from(chatGroups)
+ .leftJoin(sessionGroups, eq(chatGroups.groupId, sessionGroups.id))
+ .where(and(eq(chatGroups.id, id), this.ownership()))
+ .limit(1);
+ const folderVisibility = current?.folderVisibility as 'private' | 'public' | null | undefined;
+ const clearFolder = folderVisibility != null && folderVisibility !== visibility;
+
+ const [updated] = await this.db
+ .update(chatGroups)
+ .set({
+ updatedAt: new Date(),
+ visibility,
+ ...(clearFolder ? { groupId: null } : {}),
+ })
+ .where(and(eq(chatGroups.id, id), this.ownership()))
+ .returning();
+
+ if (updated) {
+ // Keep the synthetic supervisor's visibility in lockstep (mirrors
+ // publishToWorkspace): a promoted group must expose its supervisor to
+ // members, a demoted group must not leave the supervisor public.
+ await this.db
+ .update(agents)
+ .set({ updatedAt: new Date(), visibility })
+ .where(
+ and(
+ ne(agents.visibility, visibility),
+ inArray(
+ agents.id,
+ this.db
+ .select({ id: chatGroupsAgents.agentId })
+ .from(chatGroupsAgents)
+ .where(
+ and(
+ eq(chatGroupsAgents.chatGroupId, id),
+ eq(chatGroupsAgents.role, 'supervisor'),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ return updated ?? null;
+ }
+
+ async addAgentToGroup(
+ groupId: string,
+ agentId: string,
+ options?: { order?: number; role?: GroupMemberRole },
+ ): Promise<NewChatGroupAgent> {
+ return membership.addAgentToGroup(this.ctx, groupId, agentId, options);
+ }
+
+ async addAgentsToGroup(
+ groupId: string,
+ agentIds: string[],
+ ): Promise<{ added: NewChatGroupAgent[]; existing: string[] }> {
+ return membership.addAgentsToGroup(this.ctx, groupId, agentIds);
+ }
+
+ async removeAgentFromGroup(groupId: string, agentId: string): Promise<void> {
+ return membership.removeAgentFromGroup(this.ctx, groupId, agentId);
+ }
+
+ async removeAgentsFromGroup(groupId: string, agentIds: string[]): Promise<void> {
+ return membership.removeAgentsFromGroup(this.ctx, groupId, agentIds);
+ }
+
+ async updateAgentInGroup(
+ groupId: string,
+ agentId: string,
+ updates: Partial<Pick<NewChatGroupAgent, 'enabled' | 'order'>> & { role?: GroupMemberRole },
+ ): Promise<NewChatGroupAgent> {
+ return membership.updateAgentInGroup(this.ctx, groupId, agentId, updates);
+ }
+
+ // ******* Delete Methods ******* //
+
+ /**
+ * Delete one group row (its junction rows cascade). Group aggregate only β€”
+ * deleting a group together with the agents it owns goes through
+ * `AgentGroupRepository.deleteGroup`.
+ */
+ async delete(id: string): Promise<ChatGroupItem> {
+ return deletion.deleteGroup(this.ctx, id);
+ }
+
+ /** Delete every group in scope (group aggregate only; see {@link delete}). */
+ async deleteAll(): Promise<void> {
+ return deletion.deleteAllGroups(this.ctx);
+ }
+
+ /** See {@link deletion.findOwnedMemberAgentIds}. */
+ async findOwnedMemberAgentIds(groupIds: string[]): Promise<string[]> {
+ return deletion.findOwnedMemberAgentIds(this.ctx, groupIds);
+ }
+
+ /** Ids of every group in the caller's scope. */
+ async findIdsInScope(): Promise<string[]> {
+ return deletion.findGroupIdsInScope(this.ctx);
+ }
+
+ // ******* Agent Query Methods ******* //
+
+ async getGroupAgents(groupId: string): Promise<ChatGroupAgentItem[]> {
+ return this.db.query.chatGroupsAgents.findMany({
+ orderBy: [chatGroupsAgents.order, chatGroupsAgents.createdAt, chatGroupsAgents.agentId],
+ where: and(
+ eq(chatGroupsAgents.chatGroupId, groupId),
+ this.agentsOwnership(),
+ this.memberAgentVisibleExists(),
+ ),
+ });
+ }
+
+ /**
+ * Read-only roster of a group's **enabled** agents joined with their agent meta
+ * (title/description) and membership role, ordered by member order.
+ *
+ * Used to inject the group member list β€” with the real `agt_*` IDs β€” into the
+ * supervisor/member runtime context so the orchestration model dispatches
+ * members by their actual IDs instead of hallucinating role names (which then
+ * fail to resolve to an agent, surfacing as "Agent member(s) failed to start").
+ *
+ * Disabled members are excluded (matching `getEnabledGroupAgents`): advertising
+ * them in `<group_participants>` would let the supervisor invoke a disabled
+ * agent, since the group-management runtime accepts whatever id it dispatches.
+ */
+ async getGroupAgentsWithMeta(groupId: string): Promise<
+ Array<{
+ agentId: string;
+ description: string | null;
+ role: string | null;
+ title: string | null;
+ }>
+ > {
+ return this.db
+ .select({
+ agentId: chatGroupsAgents.agentId,
+ description: agents.description,
+ name: agents.name,
+ role: chatGroupsAgents.role,
+ title: agents.title,
+ })
+ .from(chatGroupsAgents)
+ .innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))
+ .where(
+ and(
+ eq(chatGroupsAgents.chatGroupId, groupId),
+ eq(chatGroupsAgents.enabled, true),
+ this.agentsOwnership(),
+ this.memberAgentVisibility(),
+ ),
+ )
+ .orderBy(chatGroupsAgents.order, chatGroupsAgents.createdAt, chatGroupsAgents.agentId);
+ }
+
+ /**
+ * Count still-private member agents of a group β€” the publish guard uses
+ * this to reject sharing a group whose members would leak on publish.
+ */
+ async countPrivateGroupAgents(groupId: string): Promise<number> {
+ const rows = await this.db
+ .select({ agentId: chatGroupsAgents.agentId })
+ .from(chatGroupsAgents)
+ .innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))
+ .where(
+ and(
+ eq(chatGroupsAgents.chatGroupId, groupId),
+ eq(agents.visibility, 'private'),
+ // The synthetic supervisor mirrors the group's own visibility, so a
+ // private group always owns one private agent. Counting it makes the
+ // publish guard unsatisfiable β€” every private group would look like
+ // it still holds private members and could never be shared. Only
+ // real members can block a publish.
+ ne(chatGroupsAgents.role, 'supervisor'),
+ this.agentsOwnership(),
+ ),
+ );
+
+ return rows.length;
+ }
+
+ async getEnabledGroupAgents(groupId: string): Promise<ChatGroupAgentItem[]> {
+ return this.db.query.chatGroupsAgents.findMany({
+ orderBy: [chatGroupsAgents.order, chatGroupsAgents.createdAt, chatGroupsAgents.agentId],
+ where: and(
+ eq(chatGroupsAgents.chatGroupId, groupId),
+ eq(chatGroupsAgents.enabled, true),
+ this.agentsOwnership(),
+ this.memberAgentVisibleExists(),
+ ),
+ });
+ }
+
+ /**
+ * Count workspace groups that would break if the given agent were demoted to
+ * private: groups where it is the **supervisor** and the group is visible to
+ * someone else (public, or owned by another member). A private supervisor is
+ * unresolvable for every other viewer, which makes the whole group unusable β€”
+ * so demotion is rejected at the source (mirrors
+ * `countTasksBlockingAgentDemotion`). Regular members are deliberately NOT
+ * counted: roster reads drop a non-visible member per viewer instead.
+ * Deliberately workspace-wide and visibility-blind (NOT `ownership()`):
+ * other members' private groups are invisible to the caller but their
+ * supervisor would still break.
+ */
+ async countGroupsBlockingAgentDemotion(
+ agentId: string,
+ agentOwnerUserId: string,
+ ): Promise<number> {
+ if (!this.workspaceId) return 0;
+ const [row] = await this.db
+ .select({ count: sql<number>`count(*)` })
+ .from(chatGroupsAgents)
+ .innerJoin(chatGroups, eq(chatGroupsAgents.chatGroupId, chatGroups.id))
+ .where(
+ and(
+ eq(chatGroups.workspaceId, this.workspaceId),
+ eq(chatGroupsAgents.agentId, agentId),
+ eq(chatGroupsAgents.role, 'supervisor'),
+ or(eq(chatGroups.visibility, 'public'), ne(chatGroups.userId, agentOwnerUserId)),
+ ),
+ );
+ return Number(row?.count ?? 0);
+ }
+
+ async getGroupsWithAgents(agentIds?: string[]): Promise<ChatGroupItem[]> {
+ if (!agentIds || agentIds.length === 0) {
+ return this.query();
+ }
+
+ // Find groups containing any of the specified agents
+ const groupIds = await this.db
+ .selectDistinct({ chatGroupId: chatGroupsAgents.chatGroupId })
+ .from(chatGroupsAgents)
+ .where(
+ and(
+ this.agentsOwnership(),
+ inArray(chatGroupsAgents.agentId, agentIds),
+ this.memberAgentVisibleExists(),
+ ),
+ );
+
+ if (groupIds.length === 0) return [];
+
+ return this.db.query.chatGroups.findMany({
+ orderBy: [desc(chatGroups.updatedAt)],
+ where: and(
+ inArray(
+ chatGroups.id,
+ groupIds.map((g) => g.chatGroupId),
+ ),
+ this.ownership(),
+ ),
+ });
+ }
+}
diff --git a/packages/database/src/models/chatGroup/membership.ts b/packages/database/src/models/chatGroup/membership.ts
new file mode 100644
index 00000000000..056b8e794e4
--- /dev/null
+++ b/packages/database/src/models/chatGroup/membership.ts
@@ -0,0 +1,264 @@
+import { TRPCError } from '@trpc/server';
+import { and, eq, inArray, ne } from 'drizzle-orm';
+
+import type { NewChatGroupAgent } from '../../schemas';
+import { agents, chatGroupsAgents } from '../../schemas';
+import type { GroupMemberRole } from '../../utils/groupMembership';
+import { GROUP_SUPERVISOR_ROLE, resolveGroupMembershipType } from '../../utils/groupMembership';
+import { buildWorkspaceWhere } from '../../utils/workspace';
+import { RESERVED_BUILTIN_AGENT_SLUGS } from './constants';
+import { type ChatGroupContext, groupAgentsOwnership } from './scope';
+
+export const addAgentToGroup = async (
+ ctx: ChatGroupContext,
+ groupId: string,
+ agentId: string,
+ options?: { order?: number; role?: GroupMemberRole },
+): Promise<NewChatGroupAgent> => {
+ const params: NewChatGroupAgent = {
+ agentId,
+ chatGroupId: groupId,
+ order: options?.order || 0,
+ role: options?.role || 'assistant',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? null,
+ };
+
+ const [result] = await ctx.db.insert(chatGroupsAgents).values(params).returning();
+ return result;
+};
+
+/**
+ * Add multiple agents to a group.
+ * Automatically skips agents that are already in the group.
+ *
+ * @returns Object containing:
+ * - `added`: Agents that were newly added to the group
+ * - `existing`: Agent IDs that were already in the group (skipped)
+ */
+export const addAgentsToGroup = async (
+ ctx: ChatGroupContext,
+ groupId: string,
+ agentIds: string[],
+): Promise<{ added: NewChatGroupAgent[]; existing: string[] }> => {
+ const group = await ctx.model.findById(groupId);
+ if (!group) throw new TRPCError({ code: 'NOT_FOUND', message: 'Group not found' });
+
+ // Composite visibility rule for group membership:
+ // - A caller-owned private group may admit the caller's own private agents
+ // alongside public ones.
+ // - Any public group, or any group the caller doesn't own, must contain
+ // only public agents β€” even the caller's own private agent can't be
+ // added, because that would expose it to the other members.
+ // `findById` already scopes by visibility, so reaching here with
+ // `group.visibility === 'private'` implies `group.userId === ctx.userId`.
+ const allowPrivateMembers = group.visibility === 'private' && group.userId === ctx.userId;
+
+ if (agentIds.length > 0) {
+ // Resolve each requested agent through the workspace + visibility
+ // predicate so another user's private agent never enters this set; it
+ // simply doesn't match the row filter, and we surface NOT_FOUND below.
+ const visibleAgents = await ctx.db
+ .select({
+ id: agents.id,
+ slug: agents.slug,
+ userId: agents.userId,
+ virtual: agents.virtual,
+ visibility: agents.visibility,
+ })
+ .from(agents)
+ .where(
+ and(
+ inArray(agents.id, agentIds),
+ buildWorkspaceWhere(
+ { userId: ctx.userId, workspaceId: ctx.workspaceId },
+ {
+ isDeleted: agents.isDeleted,
+ userId: agents.userId,
+ workspaceId: agents.workspaceId,
+ visibility: agents.visibility,
+ },
+ ),
+ ),
+ );
+
+ const visibleById = new Map(visibleAgents.map((row) => [row.id, row]));
+ for (const agentId of agentIds) {
+ const row = visibleById.get(agentId);
+ if (!row) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
+ }
+ if (row.visibility === 'private' && !allowPrivateMembers) {
+ // Caller owns this private agent (visibility predicate would have
+ // hidden it otherwise) but the group can't hold private members.
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
+ }
+ }
+
+ // `resolveGroupMembershipType` treats a virtual member as OWNED by its
+ // group: the delete path takes it down with the group, the transfer path
+ // rehomes it. Both are sound only while such an agent belongs to exactly
+ // ONE group β€” otherwise deleting either group destroys an agent the
+ // other still lists.
+ //
+ // The invariant is "exactly one", not "never joins one": the group agent
+ // builder legitimately creates a `virtual: true` agent and adds it here,
+ // and that is its first and only membership. So reject only a virtual
+ // agent that is ALREADY on another group's roster β€” which nothing in the
+ // product does, since the member picker filters virtual agents
+ // (`buildQueryAgentsWhere`), leaving this enforced by a query rather
+ // than by the write until now.
+ // Builtins (Inbox, the agent builders) are provisioned per user and are
+ // `virtual` like a group's own members, so the membership rules would
+ // classify one as group-OWNED the moment it joined a roster β€” and
+ // `removeAgentsFromGroup` deletes owned members. Letting someone add
+ // their Inbox to a group and then leave the group would delete the
+ // Inbox. They are nobody's group member; refuse at the door.
+ const builtinAgentId = agentIds.find((id) => {
+ const slug = visibleById.get(id)?.slug;
+ return !!slug && RESERVED_BUILTIN_AGENT_SLUGS.includes(slug);
+ });
+ if (builtinAgentId) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'A builtin agent cannot join a chat group',
+ });
+ }
+
+ const virtualAgentIds = agentIds.filter((id) => visibleById.get(id)?.virtual);
+ if (virtualAgentIds.length > 0) {
+ const [poached] = await ctx.db
+ .select({ agentId: chatGroupsAgents.agentId })
+ .from(chatGroupsAgents)
+ .where(
+ and(
+ inArray(chatGroupsAgents.agentId, virtualAgentIds),
+ ne(chatGroupsAgents.chatGroupId, groupId),
+ ),
+ )
+ .limit(1);
+
+ if (poached) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'A group-owned agent cannot join another group',
+ });
+ }
+ }
+ }
+
+ const existingAgents = await ctx.model.getGroupAgents(groupId);
+ const existingAgentIds = new Set(existingAgents.map((a) => a.agentId));
+
+ const newAgentIds = agentIds.filter((id) => !existingAgentIds.has(id));
+ const existingIds = agentIds.filter((id) => existingAgentIds.has(id));
+
+ if (newAgentIds.length === 0) {
+ return { added: [], existing: existingIds };
+ }
+
+ // Append new members after the current highest order so an incremental add
+ // never collapses everyone to the default `order = 0` (which would make the
+ // roster re-shuffle on every refetch). Supervisor rows sit at `order = -1`,
+ // so a group holding only a supervisor yields maxOrder = -1 β†’ the first
+ // member gets order 0.
+ const maxOrder = existingAgents.reduce((max, agent) => Math.max(max, agent.order ?? 0), -1);
+
+ const newAgents: NewChatGroupAgent[] = newAgentIds.map((agentId, index) => ({
+ agentId,
+ chatGroupId: groupId,
+ enabled: true,
+ order: maxOrder + 1 + index,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? null,
+ }));
+
+ const added = await ctx.db.insert(chatGroupsAgents).values(newAgents).returning();
+
+ return { added, existing: existingIds };
+};
+
+export const removeAgentFromGroup = async (
+ ctx: ChatGroupContext,
+ groupId: string,
+ agentId: string,
+): Promise<void> => {
+ await ctx.db
+ .delete(chatGroupsAgents)
+ .where(
+ and(
+ eq(chatGroupsAgents.chatGroupId, groupId),
+ eq(chatGroupsAgents.agentId, agentId),
+ groupAgentsOwnership(ctx),
+ ),
+ );
+};
+
+/**
+ * Batch remove multiple agents from a group.
+ * More efficient than calling removeAgentFromGroup multiple times.
+ */
+export const removeAgentsFromGroup = async (
+ ctx: ChatGroupContext,
+ groupId: string,
+ agentIds: string[],
+): Promise<void> => {
+ if (agentIds.length === 0) return;
+
+ await ctx.db
+ .delete(chatGroupsAgents)
+ .where(
+ and(
+ eq(chatGroupsAgents.chatGroupId, groupId),
+ inArray(chatGroupsAgents.agentId, agentIds),
+ groupAgentsOwnership(ctx),
+ ),
+ );
+};
+
+export const updateAgentInGroup = async (
+ ctx: ChatGroupContext,
+ groupId: string,
+ agentId: string,
+ updates: Partial<Pick<NewChatGroupAgent, 'enabled' | 'order'>> & { role?: GroupMemberRole },
+): Promise<NewChatGroupAgent> => {
+ // A supervisor is the group's own synthetic orchestrator: every path that
+ // creates one creates a fresh virtual agent for it, and the delete/transfer
+ // paths rely on `supervisor ⟹ owned`. Promoting a `referenced` member would
+ // break that invariant and put a member's personal agent on the group's
+ // lifecycle, so it is refused rather than silently reclassified.
+ if (updates.role === GROUP_SUPERVISOR_ROLE) {
+ const [row] = await ctx.db
+ .select({ role: chatGroupsAgents.role, slug: agents.slug, virtual: agents.virtual })
+ .from(chatGroupsAgents)
+ .innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))
+ .where(
+ and(
+ eq(chatGroupsAgents.chatGroupId, groupId),
+ eq(chatGroupsAgents.agentId, agentId),
+ groupAgentsOwnership(ctx),
+ ),
+ );
+
+ if (row && resolveGroupMembershipType(row) !== 'owned') {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Only a group-owned member can act as the group supervisor',
+ });
+ }
+ }
+
+ const [result] = await ctx.db
+ .update(chatGroupsAgents)
+ .set({ ...updates, updatedAt: new Date() })
+ .where(
+ and(
+ eq(chatGroupsAgents.chatGroupId, groupId),
+ eq(chatGroupsAgents.agentId, agentId),
+ groupAgentsOwnership(ctx),
+ ),
+ )
+ .returning();
+
+ return result;
+};
diff --git a/packages/database/src/models/chatGroup/scope.ts b/packages/database/src/models/chatGroup/scope.ts
new file mode 100644
index 00000000000..ba6f2808a0c
--- /dev/null
+++ b/packages/database/src/models/chatGroup/scope.ts
@@ -0,0 +1,32 @@
+import { chatGroups, chatGroupsAgents } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { buildWorkspaceWhere } from '../../utils/workspace';
+import type { ChatGroupModel } from './index';
+
+/** The caller identity every `ChatGroupModel` query is scoped by. */
+export interface ChatGroupContext {
+ db: LobeChatDatabase;
+ /**
+ * The model instance itself. A module function that builds on a public read calls it through
+ * here, so the call still dispatches through the instance as `this.<method>` did.
+ */
+ model: Pick<ChatGroupModel, 'findById' | 'getGroupAgents'>;
+ userId: string;
+ workspaceId?: string;
+}
+
+/** The chat groups the caller may see: their own, or the workspace's visible ones. */
+export const groupOwnership = (ctx: ChatGroupContext) =>
+ buildWorkspaceWhere(
+ { userId: ctx.userId, workspaceId: ctx.workspaceId },
+ {
+ isDeleted: chatGroups.isDeleted,
+ userId: chatGroups.userId,
+ workspaceId: chatGroups.workspaceId,
+ visibility: chatGroups.visibility,
+ },
+ );
+
+/** The membership rows in the caller's scope. */
+export const groupAgentsOwnership = (ctx: ChatGroupContext) =>
+ buildWorkspaceWhere({ userId: ctx.userId, workspaceId: ctx.workspaceId }, chatGroupsAgents);
diff --git a/packages/database/src/repositories/agentGroup/__tests__/deletion.test.ts b/packages/database/src/repositories/agentGroup/__tests__/deletion.test.ts
new file mode 100644
index 00000000000..b1eb6801e29
--- /dev/null
+++ b/packages/database/src/repositories/agentGroup/__tests__/deletion.test.ts
@@ -0,0 +1,251 @@
+// @vitest-environment node
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import {
+ agents as agentsTable,
+ chatGroups,
+ chatGroupsAgents,
+ users,
+ workspaces,
+} from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { AgentGroupRepository } from '../index';
+
+const userId = 'group-deletion-user';
+const otherUserId = 'group-deletion-other-user';
+const workspaceId = 'group-deletion-workspace';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+const repo = new AgentGroupRepository(serverDB, userId);
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Group Deletion Workspace',
+ primaryOwnerId: userId,
+ slug: workspaceId,
+ });
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+describe('AgentGroupRepository.deleteGroup', () => {
+ it('should delete group-owned member agents and keep referenced ones', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx
+ .insert(chatGroups)
+ .values({ id: 'owned-cleanup-group', title: 'Owned Cleanup', userId });
+
+ await trx.insert(agentsTable).values([
+ // Group-built members: the supervisor plus a virtual member. Neither
+ // has any existence outside this group.
+ { id: 'owned-supervisor', title: 'Supervisor', userId, virtual: true },
+ { id: 'owned-member', title: 'Owned Member', userId, virtual: true },
+ // Someone's own agent, merely linked in.
+ { id: 'referenced-member', title: 'Referenced Member', userId, virtual: false },
+ ]);
+
+ await trx.insert(chatGroupsAgents).values([
+ {
+ agentId: 'owned-supervisor',
+ chatGroupId: 'owned-cleanup-group',
+ role: 'supervisor',
+ userId,
+ },
+ {
+ agentId: 'owned-member',
+ chatGroupId: 'owned-cleanup-group',
+ userId,
+ },
+ {
+ agentId: 'referenced-member',
+ chatGroupId: 'owned-cleanup-group',
+ userId,
+ },
+ ]);
+ });
+
+ const result = await repo.deleteGroup('owned-cleanup-group');
+
+ expect(result.deletedOwnedAgentIds.sort()).toEqual(['owned-member', 'owned-supervisor']);
+
+ const survivors = await serverDB
+ .select({ id: agentsTable.id })
+ .from(agentsTable)
+ .where(inArray(agentsTable.id, ['owned-supervisor', 'owned-member', 'referenced-member']));
+ expect(survivors).toEqual([{ id: 'referenced-member' }]);
+ });
+
+ it('should classify members by agents.virtual', async () => {
+ // `agents.virtual` is the whole judgement: it is the only thing keeping
+ // this delete from either leaking or over-deleting.
+ await serverDB.transaction(async (trx) => {
+ await trx
+ .insert(chatGroups)
+ .values({ id: 'legacy-cleanup-group', title: 'Legacy Cleanup', userId });
+
+ await trx.insert(agentsTable).values([
+ { id: 'legacy-virtual', title: 'Legacy Virtual', userId, virtual: true },
+ { id: 'legacy-real', title: 'Legacy Real', userId, virtual: false },
+ ]);
+
+ await trx.insert(chatGroupsAgents).values([
+ { agentId: 'legacy-virtual', chatGroupId: 'legacy-cleanup-group', userId },
+ { agentId: 'legacy-real', chatGroupId: 'legacy-cleanup-group', userId },
+ ]);
+ });
+
+ const result = await repo.deleteGroup('legacy-cleanup-group');
+
+ expect(result.deletedOwnedAgentIds).toEqual(['legacy-virtual']);
+
+ const survivors = await serverDB
+ .select({ id: agentsTable.id })
+ .from(agentsTable)
+ .where(inArray(agentsTable.id, ['legacy-virtual', 'legacy-real']));
+ expect(survivors).toEqual([{ id: 'legacy-real' }]);
+ });
+
+ it('should clean up an owned member another workspace user made private', async () => {
+ // The previous service-level cleanup read the roster through a
+ // visibility-scoped query, so this member was invisible to the deleter
+ // and leaked every time.
+ const wsRepo = new AgentGroupRepository(serverDB, userId, workspaceId);
+
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(chatGroups).values({
+ id: 'ws-cleanup-group',
+ title: 'Workspace Cleanup',
+ userId,
+ workspaceId,
+ });
+
+ await trx.insert(agentsTable).values({
+ id: 'ws-private-owned',
+ title: 'Private Owned',
+ userId: otherUserId,
+ virtual: true,
+ visibility: 'private',
+ workspaceId,
+ });
+
+ await trx.insert(chatGroupsAgents).values({
+ agentId: 'ws-private-owned',
+ chatGroupId: 'ws-cleanup-group',
+ userId: otherUserId,
+ workspaceId,
+ });
+ });
+
+ const result = await wsRepo.deleteGroup('ws-cleanup-group');
+
+ expect(result.deletedOwnedAgentIds).toEqual(['ws-private-owned']);
+ const survivors = await serverDB
+ .select({ id: agentsTable.id })
+ .from(agentsTable)
+ .where(eq(agentsTable.id, 'ws-private-owned'));
+ expect(survivors).toEqual([]);
+ });
+
+ it('should never delete a builtin agent that ended up on a roster', async () => {
+ // `owned` should be enough on its own; the slug guard is the backstop for
+ // a malformed row, and losing someone's Inbox to a group delete is not a
+ // failure mode worth leaving to one predicate.
+ await serverDB.transaction(async (trx) => {
+ await trx
+ .insert(chatGroups)
+ .values({ id: 'builtin-cleanup-group', title: 'Builtin Cleanup', userId });
+
+ await trx.insert(agentsTable).values({
+ id: 'builtin-inbox',
+ slug: 'inbox',
+ title: 'Inbox',
+ userId,
+ virtual: true,
+ });
+
+ await trx.insert(chatGroupsAgents).values({
+ agentId: 'builtin-inbox',
+ chatGroupId: 'builtin-cleanup-group',
+ userId,
+ });
+ });
+
+ const result = await repo.deleteGroup('builtin-cleanup-group');
+
+ expect(result.deletedOwnedAgentIds).toEqual([]);
+ const survivors = await serverDB
+ .select({ id: agentsTable.id })
+ .from(agentsTable)
+ .where(eq(agentsTable.id, 'builtin-inbox'));
+ expect(survivors).toEqual([{ id: 'builtin-inbox' }]);
+ });
+
+ it('should roll back the owned-agent cleanup when the group is not in scope', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx
+ .insert(chatGroups)
+ .values({ id: 'foreign-cleanup-group', title: 'Foreign', userId: otherUserId });
+ await trx.insert(agentsTable).values({
+ id: 'foreign-owned',
+ title: 'Foreign Owned',
+ userId: otherUserId,
+ virtual: true,
+ });
+ await trx.insert(chatGroupsAgents).values({
+ agentId: 'foreign-owned',
+ chatGroupId: 'foreign-cleanup-group',
+ userId: otherUserId,
+ });
+ });
+
+ await expect(repo.deleteGroup('foreign-cleanup-group')).rejects.toThrow(
+ 'Chat group not found or access denied',
+ );
+
+ const survivors = await serverDB
+ .select({ id: agentsTable.id })
+ .from(agentsTable)
+ .where(eq(agentsTable.id, 'foreign-owned'));
+ expect(survivors).toEqual([{ id: 'foreign-owned' }]);
+ });
+});
+
+describe('AgentGroupRepository.deleteAllGroups', () => {
+ it('should delete every group in scope with its owned agents only', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(chatGroups).values([
+ { id: 'all-group-1', title: 'Group 1', userId },
+ { id: 'all-group-2', title: 'Group 2', userId },
+ { id: 'all-other-group', title: 'Other Group', userId: otherUserId },
+ ]);
+ await trx.insert(agentsTable).values([
+ { id: 'all-owned-1', title: 'Owned 1', userId, virtual: true },
+ { id: 'all-referenced', title: 'Referenced', userId, virtual: false },
+ { id: 'all-other-owned', title: 'Other Owned', userId: otherUserId, virtual: true },
+ ]);
+ await trx.insert(chatGroupsAgents).values([
+ { agentId: 'all-owned-1', chatGroupId: 'all-group-1', userId },
+ { agentId: 'all-referenced', chatGroupId: 'all-group-2', userId },
+ { agentId: 'all-other-owned', chatGroupId: 'all-other-group', userId: otherUserId },
+ ]);
+ });
+
+ await repo.deleteAllGroups();
+
+ const remainingGroups = await serverDB.select({ id: chatGroups.id }).from(chatGroups);
+ expect(remainingGroups).toEqual([{ id: 'all-other-group' }]);
+
+ const survivors = await serverDB
+ .select({ id: agentsTable.id })
+ .from(agentsTable)
+ .where(inArray(agentsTable.id, ['all-owned-1', 'all-referenced', 'all-other-owned']));
+ expect(survivors.map(({ id }) => id).sort()).toEqual(['all-other-owned', 'all-referenced']);
+ });
+});
diff --git a/packages/database/src/models/__tests__/chatGroupTransferOwnership.test.ts b/packages/database/src/repositories/agentGroup/__tests__/transferOwnership.test.ts
similarity index 92%
rename from packages/database/src/models/__tests__/chatGroupTransferOwnership.test.ts
rename to packages/database/src/repositories/agentGroup/__tests__/transferOwnership.test.ts
index 895ed349df7..d1cc3427003 100644
--- a/packages/database/src/models/__tests__/chatGroupTransferOwnership.test.ts
+++ b/packages/database/src/repositories/agentGroup/__tests__/transferOwnership.test.ts
@@ -2,7 +2,17 @@
import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { getTestDB } from '../../core/getTestDB';
+import { getTestDB } from '../../../core/getTestDB';
+import { AGENT_SHARED_TRANSFER_BLOCKED } from '../../../models/agent';
+import {
+ AGENT_TRANSFER_IN_PROGRESS,
+ AgentTransferJobModel,
+} from '../../../models/agentTransferJob';
+import {
+ CHAT_GROUP_OWNERSHIP_STALE,
+ CHAT_GROUP_TRANSFER_HIDDEN_MEMBER,
+ ChatGroupModel,
+} from '../../../models/chatGroup';
import {
agentHistoryJobs,
agents,
@@ -14,15 +24,9 @@ import {
topics,
users,
workspaces,
-} from '../../schemas';
-import type { LobeChatDatabase } from '../../type';
-import { AGENT_SHARED_TRANSFER_BLOCKED } from '../agent';
-import { AGENT_TRANSFER_IN_PROGRESS, AgentTransferJobModel } from '../agentTransferJob';
-import {
- CHAT_GROUP_OWNERSHIP_STALE,
- CHAT_GROUP_TRANSFER_HIDDEN_MEMBER,
- ChatGroupModel,
-} from '../chatGroup';
+} from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { AgentGroupRepository } from '../index';
const serverDB: LobeChatDatabase = await getTestDB();
@@ -32,10 +36,10 @@ const teammateId = 'group-handover-teammate';
const wsId = 'group-handover-ws';
const ownerModel = new ChatGroupModel(serverDB, ownerId, wsId);
-const recipientModel = new ChatGroupModel(serverDB, recipientId, wsId);
+const recipientRepo = new AgentGroupRepository(serverDB, recipientId, wsId);
-const handover = (params: Parameters<ChatGroupModel['transferGroupOwnership']>[1]) =>
- serverDB.transaction(async (trx) => recipientModel.transferGroupOwnership(trx, params));
+const handover = (params: Parameters<AgentGroupRepository['transferOwnership']>[1]) =>
+ serverDB.transaction(async (trx) => recipientRepo.transferOwnership(trx, params));
/** A group with a virtual supervisor (owned) and a standalone teammate agent (referenced). */
const seedGroupWithRoster = async () => {
@@ -86,7 +90,7 @@ afterEach(async () => {
await serverDB.delete(users);
});
-describe('ChatGroupModel.transferGroupOwnership', () => {
+describe('AgentGroupRepository.transferOwnership', () => {
it.each(['link', 'private'] as const)(
'rejects handover when an owned member has a %s share without changing the group',
async (visibility) => {
diff --git a/packages/database/src/repositories/agentGroup/deletion.ts b/packages/database/src/repositories/agentGroup/deletion.ts
new file mode 100644
index 00000000000..9e81f6da2fd
--- /dev/null
+++ b/packages/database/src/repositories/agentGroup/deletion.ts
@@ -0,0 +1,76 @@
+import { and, eq, inArray, isNull, notInArray, or } from 'drizzle-orm';
+
+import { ChatGroupModel } from '../../models/chatGroup';
+import { RESERVED_BUILTIN_AGENT_SLUGS } from '../../models/chatGroup/constants';
+import type { ChatGroupItem } from '../../schemas';
+import { agents } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import type { AgentGroupScope } from './scope';
+
+/**
+ * Builtin agents (Inbox, the agent builders, …) are provisioned per user and
+ * are `virtual` like a group's own members, so `owned` on a malformed
+ * junction row would be enough to take one down with a group. Their reserved
+ * slugs are the one thing that always tells them apart β€” a cheap belt to the
+ * `owned` braces, on a delete whose blast radius is somebody's Inbox.
+ */
+const deleteOwnedMemberAgents = async (
+ executor: LobeChatDatabase,
+ agentIds: string[],
+): Promise<string[]> => {
+ if (agentIds.length === 0) return [];
+
+ const deleted = await executor
+ .delete(agents)
+ .where(
+ and(
+ inArray(agents.id, agentIds),
+ eq(agents.virtual, true),
+ // A NULL slug predates slug generation and is not a builtin;
+ // `NOT IN` alone would evaluate to NULL and skip those rows.
+ or(isNull(agents.slug), notInArray(agents.slug, RESERVED_BUILTIN_AGENT_SLUGS)),
+ ),
+ )
+ .returning({ id: agents.id });
+
+ return deleted.map((row) => row.id);
+};
+
+/**
+ * Delete a group together with the agents that only existed to serve it.
+ * The group (chat-group aggregate) and its owned member agents (agent
+ * aggregate) go in one transaction: a cleanup that can be interrupted between
+ * the two statements is a leak with extra steps.
+ *
+ * Returns the deleted owned-agent ids so callers can report them; the delete
+ * itself needs no follow-up.
+ */
+export const deleteGroupWithOwnedAgents = async (
+ scope: AgentGroupScope,
+ id: string,
+): Promise<{ deletedOwnedAgentIds: string[]; group: ChatGroupItem }> =>
+ scope.db.transaction(async (trx) => {
+ const groupModel = new ChatGroupModel(trx as LobeChatDatabase, scope.userId, scope.workspaceId);
+ // Collect BEFORE the delete: the junction rows cascade away with the
+ // group, taking the only record of which agents were group-owned.
+ const ownedAgentIds = await groupModel.findOwnedMemberAgentIds([id]);
+ const group = await groupModel.delete(id);
+ const deletedOwnedAgentIds = await deleteOwnedMemberAgents(
+ trx as LobeChatDatabase,
+ ownedAgentIds,
+ );
+
+ return { deletedOwnedAgentIds, group };
+ });
+
+/** Delete every group in scope together with the agents they own. */
+export const deleteAllGroupsWithOwnedAgents = async (scope: AgentGroupScope): Promise<void> => {
+ await scope.db.transaction(async (trx) => {
+ const groupModel = new ChatGroupModel(trx as LobeChatDatabase, scope.userId, scope.workspaceId);
+ const groupIds = await groupModel.findIdsInScope();
+ const ownedAgentIds = await groupModel.findOwnedMemberAgentIds(groupIds);
+
+ await groupModel.deleteAll();
+ await deleteOwnedMemberAgents(trx as LobeChatDatabase, ownedAgentIds);
+ });
+};
diff --git a/packages/database/src/repositories/agentGroup/index.ts b/packages/database/src/repositories/agentGroup/index.ts
index 8a67781e6a3..6ebf9864774 100644
--- a/packages/database/src/repositories/agentGroup/index.ts
+++ b/packages/database/src/repositories/agentGroup/index.ts
@@ -7,7 +7,7 @@ import { AGENT_COPY_IN_PROGRESS, AgentCopyJobModel } from '../../models/agentCop
import { AGENT_TRANSFER_IN_PROGRESS, AgentTransferJobModel } from '../../models/agentTransferJob';
import type { AgentItem, ChatGroupItem, NewChatGroup, NewChatGroupAgent } from '../../schemas';
import { agents, chatGroups, chatGroupsAgents, sessionGroups } from '../../schemas';
-import type { LobeChatDatabase } from '../../type';
+import type { LobeChatDatabase, Transaction } from '../../type';
import { GROUP_SUPERVISOR_ROLE, resolveGroupMembershipType } from '../../utils/groupMembership';
import { normalizeInboxAgentMeta } from '../../utils/inboxAgent';
import { buildWorkspaceWhere } from '../../utils/workspace';
@@ -16,8 +16,10 @@ import {
copyGroupToWorkspace,
duplicateGroup,
} from './copy';
+import { deleteAllGroupsWithOwnedAgents, deleteGroupWithOwnedAgents } from './deletion';
import { AgentGroupScope } from './scope';
import { groupTransferHasForeignRows, transferGroupToWorkspace } from './transfer';
+import { transferGroupOwnership } from './transferOwnership';
export { AGENT_GROUP_COPY_SOURCE_MOVED, GROUP_HAS_INACCESSIBLE_MEMBER } from './constants';
@@ -470,7 +472,7 @@ export class AgentGroupRepository {
and(
this.scope.agentOwnership(),
inArray(agents.id, virtualAgentIds),
- // Same backstop as `ChatGroupModel.delete`: builtins (Inbox, the
+ // Same backstop as `deleteGroup`: builtins (Inbox, the
// agent builders) are `virtual` too, so a malformed roster row
// would otherwise classify one as this group's own and take it
// down on removal. `addAgentsToGroup` refuses them at the door;
@@ -619,4 +621,30 @@ export class AgentGroupRepository {
optionsOrNewTitle,
);
}
+
+ /**
+ * Delete a group together with the agents that only existed to serve it,
+ * in one transaction. See {@link deleteGroupWithOwnedAgents}.
+ */
+ async deleteGroup(
+ groupId: string,
+ ): Promise<{ deletedOwnedAgentIds: string[]; group: ChatGroupItem }> {
+ return deleteGroupWithOwnedAgents(this.scope, groupId);
+ }
+
+ /** Delete every group in scope together with the agents they own. */
+ async deleteAllGroups(): Promise<void> {
+ return deleteAllGroupsWithOwnedAgents(this.scope);
+ }
+
+ /**
+ * Same-workspace ownership handover, run inside the caller's transaction.
+ * See {@link transferGroupOwnership}.
+ */
+ async transferOwnership(
+ trx: Transaction,
+ params: Parameters<typeof transferGroupOwnership>[2],
+ ): Promise<void> {
+ return transferGroupOwnership(this.scope, trx, params);
+ }
}
diff --git a/packages/database/src/repositories/agentGroup/transferOwnership.ts b/packages/database/src/repositories/agentGroup/transferOwnership.ts
new file mode 100644
index 00000000000..7b435e9eac5
--- /dev/null
+++ b/packages/database/src/repositories/agentGroup/transferOwnership.ts
@@ -0,0 +1,307 @@
+import { and, asc, eq, inArray, ne } from 'drizzle-orm';
+
+import { AGENT_SHARED_TRANSFER_BLOCKED } from '../../models/agent';
+import { AGENT_COPY_IN_PROGRESS, AgentCopyJobModel } from '../../models/agentCopyJob';
+import { AGENT_TRANSFER_IN_PROGRESS, AgentTransferJobModel } from '../../models/agentTransferJob';
+import {
+ CHAT_GROUP_OWNERSHIP_STALE,
+ CHAT_GROUP_TRANSFER_HIDDEN_MEMBER,
+} from '../../models/chatGroup/constants';
+import {
+ agentBotProviders,
+ agentCronJobs,
+ agents,
+ agentShares,
+ chatGroups,
+ chatGroupsAgents,
+ projectAgents,
+ projects,
+ tasks,
+} from '../../schemas';
+import type { Transaction } from '../../type';
+import { sanitizeAgencyConfigsForWorkspace } from '../../utils/agencyConfigDevices';
+import { rehomeAgentConnectorsForRecipient } from '../../utils/agentConnectors';
+import { rehomeAgentDocumentsForRecipient } from '../../utils/agentDocumentsOwnership';
+import { rehomeAgentExpertiseForRecipient } from '../../utils/agentExpertise';
+import {
+ detachAgentKnowledgeMountsForRecipient,
+ rehomeRetainedAgentKnowledgeMounts,
+} from '../../utils/agentKnowledgeMounts';
+import { rehomeAgentLabelsForRecipient } from '../../utils/agentLabelsOwnership';
+import { rehomeAgentQuotaBindingsForRecipient } from '../../utils/agentQuotaBindings';
+import { resolveGroupMembershipType } from '../../utils/groupMembership';
+import type { AgentGroupScope } from './scope';
+
+/**
+ * Same-workspace ownership handover: what accepting a member-to-member
+ * transfer request executes. Deliberately narrower than the cross-scope
+ * `AgentGroupRepository.transferToWorkspace` β€” the group stays where it is,
+ * so nothing is cloned and no conversation moves. Only ownership flips: the
+ * group row, its junction rows, and the member agents that exist to serve it
+ * (supervisor + generated members). Referenced standalone members keep their
+ * own owners β€” membership never owned them.
+ *
+ * Runs inside the caller's transaction: the caller flips the transfer
+ * request's status in the same `trx`, so a stale/raced accept rolls both
+ * back together. It writes the group, its member agents and their tasks,
+ * project links and runtime rows, so it is a repository unit of work rather
+ * than a `ChatGroupModel` method.
+ */
+export const transferGroupOwnership = async (
+ ctx: Pick<AgentGroupScope, 'workspaceId'>,
+ trx: Transaction,
+ params: {
+ /** The owner recorded on the transfer request; a mismatch means the request is stale. */
+ fromUserId: string;
+ groupId: string;
+ toUserId: string;
+ },
+): Promise<void> => {
+ const { fromUserId, groupId, toUserId } = params;
+ if (!ctx.workspaceId) throw new Error(CHAT_GROUP_OWNERSHIP_STALE);
+
+ // FOR UPDATE: serialize against a concurrent cross-scope transfer, delete,
+ // or second accept; the loser re-reads and fails the staleness check.
+ const [group] = await trx
+ .select()
+ .from(chatGroups)
+ .where(and(eq(chatGroups.id, groupId), eq(chatGroups.workspaceId, ctx.workspaceId)))
+ .for('update');
+ if (!group || group.userId !== fromUserId) throw new Error(CHAT_GROUP_OWNERSHIP_STALE);
+
+ // Raw roster read (no visibility predicate): the owned/referenced split
+ // must see every member, exactly as delete and the cross-scope transfer do.
+ const memberRows = await trx
+ .select({
+ agentId: chatGroupsAgents.agentId,
+ role: chatGroupsAgents.role,
+ slug: agents.slug,
+ virtual: agents.virtual,
+ })
+ .from(chatGroupsAgents)
+ .innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))
+ .where(eq(chatGroupsAgents.chatGroupId, groupId));
+
+ const agentIds = memberRows.map((row) => row.agentId);
+ const ownedAgentIds = memberRows
+ .filter((row) => resolveGroupMembershipType(row) === 'owned')
+ .map((row) => row.agentId);
+
+ // Same lock-then-guard as `transferToWorkspace`: serialize with a
+ // concurrent transfer of any member agent BEFORE consulting the pending
+ // job tables, so two racing operations cannot both pass the guards.
+ if (agentIds.length > 0) {
+ await trx
+ .select({ id: agents.id })
+ .from(agents)
+ .where(inArray(agents.id, agentIds))
+ .orderBy(asc(agents.id))
+ .for('update');
+ }
+
+ // A share row keeps the agent bound to its current owner and workspace,
+ // including when the share is paused. Check only owned members: referenced
+ // standalone agents remain with their owner and do not move with the group.
+ if (ownedAgentIds.length > 0) {
+ const [existingShare] = await trx
+ .select({ id: agentShares.id })
+ .from(agentShares)
+ .where(inArray(agentShares.agentId, ownedAgentIds))
+ .limit(1);
+ if (existingShare) throw new Error(AGENT_SHARED_TRANSFER_BLOCKED);
+ }
+
+ // A REFERENCED member that is private to someone other than the recipient
+ // would silently vanish from the roster for the group's new owner (every
+ // roster read applies member-agent visibility). Refuse instead β€” same
+ // policy as the cross-scope transfer; the member's owner can share it and
+ // the recipient can retry. Evaluated from a re-read AFTER the agent locks
+ // above, so a visibility flip racing this handover cannot slip past the
+ // guard on a stale snapshot.
+ const referencedIds = memberRows
+ .filter((row) => resolveGroupMembershipType(row) === 'referenced')
+ .map((row) => row.agentId);
+ if (referencedIds.length > 0) {
+ const lockedReferenced = await trx
+ .select({ userId: agents.userId, visibility: agents.visibility })
+ .from(agents)
+ .where(inArray(agents.id, referencedIds));
+ const hasHiddenReferencedMember = lockedReferenced.some(
+ (row) => row.visibility === 'private' && row.userId !== toUserId,
+ );
+ if (hasHiddenReferencedMember) throw new Error(CHAT_GROUP_TRANSFER_HIDDEN_MEMBER);
+ }
+
+ // An unfinished backfill still rewrites rows toward the OLD owner's
+ // request; hand the group over only once it has drained.
+ if (
+ (await AgentTransferJobModel.hasPendingJobForAgents(trx, agentIds)) ||
+ (await AgentTransferJobModel.hasPendingJobForGroups(trx, [groupId]))
+ ) {
+ throw new Error(AGENT_TRANSFER_IN_PROGRESS);
+ }
+ if (
+ (await AgentCopyJobModel.hasPendingCopyJobForSourceAgents(trx, agentIds)) ||
+ (await AgentCopyJobModel.hasPendingCopyJobForSourceGroups(trx, [groupId]))
+ ) {
+ throw new Error(AGENT_COPY_IN_PROGRESS);
+ }
+
+ // An ownership flip does not make the group's content newer, and the
+ // scope/visibility/folder/pin all stay: the group is not moving anywhere.
+ // `clientId` is cleared β€” unique per (clientId, userId), it belongs to the
+ // previous owner's client-side sync and would abort the accept if the
+ // recipient already owns a group with the same value.
+ await trx
+ .update(chatGroups)
+ .set({ clientId: null, updatedAt: chatGroups.updatedAt, userId: toUserId })
+ .where(eq(chatGroups.id, groupId));
+
+ // The junction rows belong to the GROUP, so all of them follow its owner β€”
+ // including the rows pointing at referenced members that stay put.
+ await trx
+ .update(chatGroupsAgents)
+ .set({ userId: toUserId })
+ .where(eq(chatGroupsAgents.chatGroupId, groupId));
+
+ if (ownedAgentIds.length > 0) {
+ // Re-home device bindings on the owned agents (supervisor + generated
+ // members): a boundDeviceId / fixed device policy pointing at the
+ // previous owner's personal or private device would leave the
+ // recipient's group runs unroutable. Same sanitation as the member
+ // agent handover.
+ const ownedRows = await trx
+ .select({ agencyConfig: agents.agencyConfig, id: agents.id, visibility: agents.visibility })
+ .from(agents)
+ .where(inArray(agents.id, ownedAgentIds));
+ const cleanedConfigs = await sanitizeAgencyConfigsForWorkspace(
+ trx,
+ ctx.workspaceId,
+ ownedRows.map((row) => row.agencyConfig),
+ { viewerUserId: toUserId },
+ );
+ for (const [index, row] of ownedRows.entries()) {
+ // `clientId` cleared for the same reason as the single-agent handover:
+ // it is unique per (clientId, userId) and belongs to the previous
+ // owner's client-side sync.
+ await trx
+ .update(agents)
+ .set({
+ agencyConfig: cleanedConfigs[index],
+ clientId: null,
+ updatedAt: agents.updatedAt,
+ userId: toUserId,
+ })
+ .where(eq(agents.id, row.id));
+ }
+
+ // Owner-attributed runtime rows (cron jobs, bot providers) execute AS
+ // their `userId`; the previous owner's rows on the owned agents re-home
+ // with them β€” DISABLED, so nothing runs silently under the recipient's
+ // identity and budget. Same policy as the single-agent handover.
+ await trx
+ .update(agentCronJobs)
+ .set({ enabled: false, updatedAt: agentCronJobs.updatedAt, userId: toUserId })
+ .where(
+ and(inArray(agentCronJobs.agentId, ownedAgentIds), eq(agentCronJobs.userId, fromUserId)),
+ );
+ await trx
+ .update(agentBotProviders)
+ .set({ enabled: false, updatedAt: agentBotProviders.updatedAt, userId: toUserId })
+ .where(
+ and(
+ inArray(agentBotProviders.agentId, ownedAgentIds),
+ eq(agentBotProviders.userId, fromUserId),
+ ),
+ );
+ // Quota account bindings (and exclusively-consumed provider accounts)
+ // re-home: both cascade on user deletion. See the util.
+ await rehomeAgentQuotaBindingsForRecipient(trx, {
+ agentIds: ownedAgentIds,
+ fromUserId,
+ recipientId: toUserId,
+ });
+
+ // Label assignments (and exclusively-assigned backing labels) re-home:
+ // both cascade on user deletion. See the util.
+ await rehomeAgentLabelsForRecipient(trx, {
+ agentIds: ownedAgentIds,
+ fromUserId,
+ recipientId: toUserId,
+ });
+
+ // Tasks stay with their creators (moving ownership breaks in-flight run
+ // identity and splits subtrees). But owned agents that are PRIVATE stop
+ // resolving for everyone but the recipient, so detach other users' task
+ // assignments to them β€” the schedule goes quiet rather than erroring.
+ const privateOwnedIds = ownedRows
+ .filter((row) => row.visibility === 'private')
+ .map((row) => row.id);
+ if (privateOwnedIds.length > 0) {
+ await trx
+ .update(tasks)
+ .set({ assigneeAgentId: null, updatedAt: tasks.updatedAt })
+ .where(
+ and(inArray(tasks.assigneeAgentId, privateOwnedIds), ne(tasks.createdByUserId, toUserId)),
+ );
+
+ // Private owned agents also leave other members' PROJECTS explicitly β€”
+ // project agent listings apply member-agent visibility, so those
+ // projects would otherwise keep a silent hole. Same policy as the
+ // single-agent handover.
+ const projectLinks = await trx
+ .select({ linkId: projectAgents.id, projectOwnerId: projects.userId })
+ .from(projectAgents)
+ .innerJoin(projects, eq(projectAgents.projectId, projects.id))
+ .where(inArray(projectAgents.agentId, privateOwnedIds));
+ const leavingProjectLinkIds = projectLinks
+ .filter((link) => link.projectOwnerId !== toUserId)
+ .map((link) => link.linkId);
+ if (leavingProjectLinkIds.length > 0) {
+ await trx.delete(projectAgents).where(inArray(projectAgents.id, leavingProjectLinkIds));
+ }
+ }
+
+ // Knowledge mounts on the owned agents whose KB / file the recipient
+ // cannot access would survive as dead links the runtime silently skips.
+ // Detach them β€” same policy as the single-agent handover; the manifest
+ // surfaces the count to both parties before acceptance.
+ await detachAgentKnowledgeMountsForRecipient(trx, {
+ agentIds: ownedAgentIds,
+ recipientId: toUserId,
+ workspaceId: ctx.workspaceId,
+ });
+ // The retained mounts the previous owner created re-home with the owned
+ // agents β€” the junction `user_id` cascades on user deletion, and the
+ // group's knowledge must not die with the previous owner's account.
+ await rehomeRetainedAgentKnowledgeMounts(trx, {
+ agentIds: ownedAgentIds,
+ fromUserId,
+ recipientId: toUserId,
+ workspaceId: ctx.workspaceId,
+ });
+
+ // Connectors: OAuth credentials are personal identity and never travel.
+ // Agent-owned rows on the owned members re-home as disconnected shells
+ // the recipient must reauthorize; other members' mounted rows unmount.
+ await rehomeAgentConnectorsForRecipient(trx, {
+ agentIds: ownedAgentIds,
+ recipientId: toUserId,
+ });
+
+ // Expertise + VFS documents: same policies as the single-agent handover
+ // (agent-exclusive domains re-home / shared ones unbind; the previous
+ // owner's document rows re-home so account deletion cannot strip them).
+ await rehomeAgentExpertiseForRecipient(trx, {
+ agentIds: ownedAgentIds,
+ recipientId: toUserId,
+ workspaceId: ctx.workspaceId,
+ });
+ await rehomeAgentDocumentsForRecipient(trx, {
+ agentIds: ownedAgentIds,
+ fromUserId,
+ recipientId: toUserId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
+};