Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(channel): mute an Agent member so it answers only when @mentioned (#23164)

Arvin Xu50d629699bc3
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.ts
index e67fae561a7..15606d2041d 100644
--- a/apps/server/src/routers/lambda/channel.ts
+++ b/apps/server/src/routers/lambda/channel.ts
@@ -267,6 +267,12 @@ export const channelRouter = router({
await ctx.channelService.remove(input.channelId);
return { success: true };
}),
+ setMemberMuted: channelProcedure
+ .input(z.object({ channelId, memberId: z.uuid(), muted: z.boolean() }))
+ .mutation(async ({ ctx, input }) => {
+ await ctx.channelService.setMemberMuted(input.channelId, input.memberId, input.muted);
+ return { success: true };
+ }),
editMessage: channelProcedure
.input(
z.object({
diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.ts
index 1b3ffe4b0fc..d143dcb7a92 100644
--- a/apps/server/src/services/channel/ChannelService.ts
+++ b/apps/server/src/services/channel/ChannelService.ts
@@ -437,6 +437,13 @@ export class ChannelService {
return job;
};
+ /** A muted Agent answers only @mentions; muting also stops what it is answering now. */
+ setMemberMuted = async (channelId: string, memberId: string, muted: boolean) => {
+ const writers = await this.repository.setMemberMuted(channelId, memberId, muted);
+ await new ChannelCoordinator(this.db).stopWriters(writers);
+ await Promise.all([wakeChannel(channelId), this.changed(channelId)]);
+ };
+
stop = async (channelId: string, scope: ChannelStopScope) => {
const writers = await this.repository.stop(channelId, scope);
await new ChannelCoordinator(this.db).stopWriters(writers);
diff --git a/apps/server/src/services/channel/README.md b/apps/server/src/services/channel/README.md
index 17a95797271..8b95dcf4bcd 100644
--- a/apps/server/src/services/channel/README.md
+++ b/apps/server/src/services/channel/README.md
@@ -53,6 +53,10 @@ groups merge field by field), parsed by the shared bot-wake schema.
in the main channel (it still follows up there, and is chosen normally in a Thread it follows):
the decision model never chooses the member either. An unnamed member's generic `Agent` label
is not a name the text can call.
+- **Muted** (`channel_members.config.muted`, `channel.setMemberMuted`, admins only): the member is
+ not a candidate at all. Only an @mention reaches it: not routing, the paired-Agent shortcut, the
+ all-candidate fallback or a reply to its message; it cannot post on its own either. Muting stops
+ its open jobs. The Agent of a direct conversation cannot be muted.
- **Quiet**: the member stayed silent `maxSilentWakes` times since it last answered; routing may still
choose it, but not wake it on a hunch.
diff --git a/packages/database/src/repositories/channel/ChannelRoutingRepository.ts b/packages/database/src/repositories/channel/ChannelRoutingRepository.ts
index 49546e55421..136a4c43dd6 100644
--- a/packages/database/src/repositories/channel/ChannelRoutingRepository.ts
+++ b/packages/database/src/repositories/channel/ChannelRoutingRepository.ts
@@ -17,7 +17,7 @@ import {
import type { LobeChatDatabase } from '../../type';
import { buildWorkspaceWhere } from '../../utils/workspace';
import { fileIdsByMessage } from './attachments';
-import { findThread } from './delivery';
+import { findThread, memberNotMuted } from './delivery';
import { resolveRouting } from './routing';
import { audit, withChannelLock } from './transaction';
@@ -156,6 +156,7 @@ export class ChannelRoutingRepository {
eq(channelMembers.channelId, channelId),
eq(channelMembers.actorType, 'agent'),
eq(channelMembers.status, 'active'),
+ memberNotMuted(),
thread ? inArray(channelMembers.id, thread.followerMemberIds) : undefined,
buildWorkspaceWhere(
{ userId: message.userId, workspaceId: channel.workspaceId ?? undefined },
diff --git a/packages/database/src/repositories/channel/__tests__/mute.test.ts b/packages/database/src/repositories/channel/__tests__/mute.test.ts
new file mode 100644
index 00000000000..e6fbf970f26
--- /dev/null
+++ b/packages/database/src/repositories/channel/__tests__/mute.test.ts
@@ -0,0 +1,139 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { channelJobs } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { ChannelRepository } from '..';
+import { createChannelFixture, jobsOf } from './testUtils';
+
+const db: LobeChatDatabase = await getTestDB();
+const fixture = createChannelFixture(db, 'channel-mute');
+
+beforeEach(fixture.setup);
+afterEach(fixture.cleanup);
+
+const createPair = async () => {
+ const asOwner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);
+ const { channel } = await asOwner.create({ title: 'Pair' });
+ return { asOwner, channel };
+};
+
+describe('ChannelRepository.setMemberMuted', () => {
+ it('leaves a muted paired Agent quiet until it is @mentioned', async () => {
+ const { asOwner, channel } = await createPair();
+ const agent = await fixture.addAgent(channel.id, 'Coder');
+ await asOwner.setMemberMuted(channel.id, agent.id, true);
+
+ const unaddressed = await asOwner.send(channel.id, {
+ content: 'Anyone?',
+ requestKey: 'req-1',
+ routing: 'decision',
+ });
+ expect(unaddressed).toMatchObject({ recipientMemberIds: [], routingStatus: 'skipped' });
+ expect(await jobsOf(db, unaddressed.id)).toEqual([]);
+
+ const mentioned = await asOwner.send(channel.id, {
+ content: '@Coder please',
+ mentions: [agent.id],
+ requestKey: 'req-2',
+ routing: 'decision',
+ });
+ expect(mentioned).toMatchObject({ recipientMemberIds: [agent.id], routingStatus: 'directed' });
+ });
+
+ it('keeps a muted Agent out of the all-candidate fallback', async () => {
+ const { asOwner, channel } = await fixture.createTeamChannel();
+ const muted = await fixture.addAgent(channel.id, 'Muted');
+ const other = await fixture.addAgent(channel.id, 'Other');
+ await asOwner.setMemberMuted(channel.id, muted.id, true);
+
+ const message = await asOwner.send(channel.id, {
+ content: 'Who can help?',
+ requestKey: 'req-1',
+ routing: 'fallback',
+ });
+ expect(message.recipientMemberIds).toEqual([other.id]);
+ });
+
+ it('does not wake a muted Agent for a reply to its message, unless @mentioned', async () => {
+ const { asOwner, channel } = await fixture.createTeamChannel();
+ const agent = await fixture.addAgent(channel.id, 'Secretary');
+ const said = await asOwner.postAgentMessage(channel.id, {
+ agentId: agent.agentId!,
+ content: 'Done.',
+ requestKey: 'post-1',
+ });
+ await asOwner.setMemberMuted(channel.id, agent.id, true);
+
+ const reply = await asOwner.send(channel.id, {
+ content: 'Thanks',
+ replyToId: said.id,
+ requestKey: 'req-1',
+ routing: 'decision',
+ });
+ expect(reply).toMatchObject({ recipientMemberIds: [], routingStatus: 'skipped' });
+
+ const asked = await asOwner.send(channel.id, {
+ content: 'One more thing',
+ mentions: [agent.id],
+ replyToId: said.id,
+ requestKey: 'req-2',
+ routing: 'decision',
+ });
+ expect(asked.recipientMemberIds).toEqual([agent.id]);
+ });
+
+ it('refuses a muted Agent posting on its own', async () => {
+ const { asOwner, channel } = await fixture.createTeamChannel();
+ const agent = await fixture.addAgent(channel.id, 'Secretary');
+ await asOwner.setMemberMuted(channel.id, agent.id, true);
+
+ await expect(
+ asOwner.postAgentMessage(channel.id, {
+ agentId: agent.agentId!,
+ content: 'Hello',
+ requestKey: 'post-1',
+ }),
+ ).rejects.toMatchObject({ code: 'CONFLICT' });
+ });
+
+ it('stops what the Agent is answering, shows it muted and survives an environment change', async () => {
+ const { asOwner, channel } = await createPair();
+ const agent = await fixture.addAgent(channel.id, 'Coder');
+ const message = await asOwner.send(channel.id, {
+ content: 'Long task',
+ requestKey: 'req-1',
+ routing: 'decision',
+ });
+ const [job] = await jobsOf(db, message.id);
+ expect(job.status).toBe('queued');
+
+ await asOwner.setMemberMuted(channel.id, agent.id, true);
+ const [stopped] = await db.select().from(channelJobs).where(eq(channelJobs.id, job.id));
+ expect(stopped.status).toBe('cancelled');
+
+ await asOwner.updateAgentEnvironment(channel.id, agent.id, {});
+ const member = (await asOwner.detail(channel.id)).members.find((m) => m.id === agent.id);
+ expect(member?.muted).toBe(true);
+
+ await asOwner.setMemberMuted(channel.id, agent.id, false);
+ const unmuted = (await asOwner.detail(channel.id)).members.find((m) => m.id === agent.id);
+ expect(unmuted?.muted).toBe(false);
+ });
+
+ it('is for admins, and not for the Agent of a direct conversation', async () => {
+ const { asMember, asOwner, channel } = await fixture.createTeamChannel();
+ const agent = await fixture.addAgent(channel.id, 'Coder');
+ await expect(asMember.setMemberMuted(channel.id, agent.id, true)).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+
+ const { channel: direct } = await asOwner.create({ agentId: agent.agentId!, title: 'DM' });
+ const bound = (await asOwner.detail(direct.id)).members.find((m) => m.actorType === 'agent');
+ await expect(asOwner.setMemberMuted(direct.id, bound!.id, true)).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ });
+ });
+});
diff --git a/packages/database/src/repositories/channel/delivery.ts b/packages/database/src/repositories/channel/delivery.ts
index 24c613e7da4..17bd2022ff8 100644
--- a/packages/database/src/repositories/channel/delivery.ts
+++ b/packages/database/src/repositories/channel/delivery.ts
@@ -21,6 +21,10 @@ import { ChannelError } from './error';
/** Why a deferred `followup` has not started; see {@link deliver} and `claimJob`. */
export const AWAITING_PRIMARY_REASON = 'Waiting for the first responder to finish';
+/** An Agent member that is not muted; a muted one is reached only by an @mention. */
+export const memberNotMuted = () =>
+ sql`coalesce((${channelMembers.config}->>'muted')::boolean, false) = false`;
+
/** The Thread a message belongs to, or null for the main channel. */
export const findThread = async (
tx: Transaction,
@@ -92,6 +96,7 @@ export const candidateAgents = async (
eq(channelMembers.channelId, channelId),
eq(channelMembers.actorType, 'agent'),
eq(channelMembers.status, 'active'),
+ memberNotMuted(),
),
);
@@ -112,7 +117,10 @@ export const pairedAgent = async (
.where(and(eq(channelMembers.channelId, channelId), eq(channelMembers.status, 'active')));
const agents = members.filter((member) => member.actorType === 'agent');
- return agents.length === 1 && members.length === 2 ? agents[0] : undefined;
+ // A muted one waits for an @mention like any other.
+ return agents.length === 1 && members.length === 2 && !agents[0].config?.muted
+ ? agents[0]
+ : undefined;
};
/**
diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.ts
index ea2f3986614..878132a47f2 100644
--- a/packages/database/src/repositories/channel/index.ts
+++ b/packages/database/src/repositories/channel/index.ts
@@ -35,6 +35,7 @@ import { channelAvatarMembers } from './avatars';
import { findThread } from './delivery';
import { editMessage } from './edit';
import { ChannelError } from './error';
+import { setMemberMuted } from './mute';
import { lockPeerPair, peerOf, requireMutualContacts } from './peer';
import {
addChannelUser,
@@ -100,10 +101,12 @@ const WORKSPACE_MANAGER_ROLES = ['owner', 'admin'];
const LIST_PREVIEW_LENGTH = 200;
/** A member config with its reply strategy set, or without one when `wake` is empty. */
+/** An environment plus the member's own settings that live beside it: reply strategy and mute. */
const withMemberWake = (
config: ChannelMemberConfig,
wake: Record<string, unknown> | null | undefined,
-): ChannelMemberConfig => (wake ? { ...config, wake } : config);
+ muted: boolean | undefined,
+): ChannelMemberConfig => ({ ...config, ...(wake && { wake }), ...(muted && { muted }) });
export class ChannelRepository {
private readonly workspaceId: string | null;
@@ -266,7 +269,13 @@ export class ChannelRepository {
const [member] = await tx
.update(channelMembers)
// The environment is replaced; the member's reply strategy is not part of it.
- .set({ config: withMemberWake(memberEnvironment(config), current.config?.wake) })
+ .set({
+ config: withMemberWake(
+ memberEnvironment(config),
+ current.config?.wake,
+ current.config?.muted,
+ ),
+ })
.where(eq(channelMembers.id, memberId))
.returning();
await audit(tx, channelId, 'member_environment_changed', memberId);
@@ -355,7 +364,9 @@ export class ChannelRepository {
const current = await requireAgentMember(tx, channelId, memberId);
const [member] = await tx
.update(channelMembers)
- .set({ config: withMemberWake(memberEnvironment(current.config), wake) })
+ .set({
+ config: withMemberWake(memberEnvironment(current.config), wake, current.config?.muted),
+ })
.where(eq(channelMembers.id, memberId))
.returning();
await audit(tx, channelId, 'member_wake_config_changed', memberId, { reset: !wake });
@@ -1102,6 +1113,11 @@ export class ChannelRepository {
{ minRole: 'admin' },
);
+ /** Mutes or unmutes an Agent member; see `setMemberMuted`. Returns writers to stop. */
+ setMemberMuted = async (channelId: string, memberId: string, muted: boolean) =>
+ this.write(channelId, (tx, { channel }) => setMemberMuted(tx, channel, memberId, muted), {
+ minRole: 'admin',
+ });
/** Rewrites the text of the caller's own message; see `editMessage`. */
editMessage = async (channelId: string, messageId: string, content: string) =>
this.write(channelId, (tx) => editMessage(tx, channelId, this.userId, messageId, content));
diff --git a/packages/database/src/repositories/channel/mute.ts b/packages/database/src/repositories/channel/mute.ts
new file mode 100644
index 00000000000..d1e0575f774
--- /dev/null
+++ b/packages/database/src/repositories/channel/mute.ts
@@ -0,0 +1,52 @@
+import { and, eq, inArray } from 'drizzle-orm';
+
+import type { ChannelJobItem } from '../../schemas';
+import { channelJobs, channelMembers } from '../../schemas';
+import type { Transaction } from '../../type';
+import { requireAgentMember } from './agent';
+import { ChannelError } from './error';
+import { stopScope } from './stop';
+import { audit } from './transaction';
+import { OPEN_JOB_STATUSES } from './writer';
+
+/**
+ * Mutes or unmutes one Agent member. A muted Agent answers only when a person @mentions it:
+ * routing, the paired-Agent shortcut, replies to its messages and its own posts all pass it by.
+ * Muting also stops whatever it is answering now, so it falls quiet at once.
+ *
+ * Returns the stopped jobs whose writer is still held, for the caller to stop physically.
+ */
+export const setMemberMuted = async (
+ tx: Transaction,
+ channel: { agentId: string | null; id: string },
+ memberId: string,
+ muted: boolean,
+): Promise<ChannelJobItem[]> => {
+ // A direct conversation is a chat with this one Agent; muting it would leave nobody to talk to.
+ if (channel.agentId)
+ throw new ChannelError('BAD_REQUEST', 'The Agent of a direct conversation cannot be muted');
+ const member = await requireAgentMember(tx, channel.id, memberId);
+ if (!!member.config?.muted === muted) return [];
+
+ const { muted: _previous, ...rest } = member.config ?? {};
+ await tx
+ .update(channelMembers)
+ .set({ config: muted ? { ...rest, muted: true } : rest })
+ .where(eq(channelMembers.id, memberId));
+ await audit(tx, channel.id, muted ? 'member_muted' : 'member_unmuted', memberId);
+ if (!muted) return [];
+
+ const open = await tx
+ .select({ id: channelJobs.id })
+ .from(channelJobs)
+ .where(
+ and(
+ eq(channelJobs.channelId, channel.id),
+ eq(channelJobs.memberId, memberId),
+ inArray(channelJobs.status, [...OPEN_JOB_STATUSES]),
+ ),
+ );
+ const writers: ChannelJobItem[] = [];
+ for (const { id } of open) writers.push(...(await stopScope(tx, channel.id, { jobId: id })));
+ return writers;
+};
diff --git a/packages/database/src/repositories/channel/post.ts b/packages/database/src/repositories/channel/post.ts
index 5ec2fe47353..4e821bb3392 100644
--- a/packages/database/src/repositories/channel/post.ts
+++ b/packages/database/src/repositories/channel/post.ts
@@ -42,7 +42,7 @@ export const postAgentMessage = async (
if (existing) return existing;
const [member] = await tx
- .select({ id: channelMembers.id })
+ .select({ config: channelMembers.config, id: channelMembers.id })
.from(channelMembers)
.where(
and(
@@ -54,6 +54,8 @@ export const postAgentMessage = async (
)
.limit(1);
if (!member) throw new ChannelError('CONFLICT', 'The Agent is not a member of this Channel');
+ if (member.config?.muted)
+ throw new ChannelError('CONFLICT', 'The Agent is muted in this Channel');
const message = await appendMessage(tx, {
agentId: input.agentId,
diff --git a/packages/database/src/repositories/channel/send.ts b/packages/database/src/repositories/channel/send.ts
index d64b7f83156..dfd120be85a 100644
--- a/packages/database/src/repositories/channel/send.ts
+++ b/packages/database/src/repositories/channel/send.ts
@@ -119,6 +119,8 @@ export const sendMessage = async (
: [];
if (replyTo && !humanQuote && !replyAgent)
throw new ChannelError('BAD_REQUEST', 'The replying Agent is no longer available');
+ // Replying to a muted Agent still opens its Thread, but only an @mention makes it answer.
+ const replyTarget = replyAgent?.config?.muted ? undefined : replyAgent;
// A click is local. Create the Agent's thread atomically with the first sent reply.
const thread = assertThreadOpen(
replyAgent && !sourceThread
@@ -231,7 +233,9 @@ export const sendMessage = async (
const routed = quoteOnly
? ({ reason: 'Quoted human message', source: 'explicit', status: 'skipped' } as const)
: replyAgent
- ? ({ reason: 'Reply to Agent', source: 'explicit', status: 'directed' } as const)
+ ? replyTarget || mentions.length
+ ? ({ reason: 'Reply to Agent', source: 'explicit', status: 'directed' } as const)
+ : ({ reason: 'The Agent is muted', source: 'explicit', status: 'skipped' } as const)
: paired
? ({ reason: 'Only Agent in the Channel', source: 'explicit', status: 'directed' } as const)
: mentions.length
@@ -260,7 +264,14 @@ export const sendMessage = async (
const recipients = quoteOnly
? []
: replyAgent
- ? [...new Map([replyAgent, ...mentionedAgents].map((agent) => [agent.id, agent])).values()]
+ ? [
+ ...new Map(
+ [...(replyTarget ? [replyTarget] : []), ...mentionedAgents].map((agent) => [
+ agent.id,
+ agent,
+ ]),
+ ).values(),
+ ]
: paired
? [paired]
: mentions.length
diff --git a/packages/database/src/repositories/channel/view.ts b/packages/database/src/repositories/channel/view.ts
index cc63f870a55..27ae711edf6 100644
--- a/packages/database/src/repositories/channel/view.ts
+++ b/packages/database/src/repositories/channel/view.ts
@@ -255,6 +255,7 @@ export const readChannelView = async (
string | null
>`coalesce(nullif(${channelMembers.description}, ''), ${agents.description})`,
id: channelMembers.id,
+ muted: sql<boolean>`coalesce((${channelMembers.config}->>'muted')::boolean, false)`,
name: channelMembers.name,
role: channelMembers.role,
status: channelMembers.status,
diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.ts
index 6834c9739de..4998b20e271 100644
--- a/packages/types/src/channel.ts
+++ b/packages/types/src/channel.ts
@@ -105,6 +105,11 @@ export interface ChannelMemberConfig {
* creator, so a workspace channel can use another member's device after its owner approves.
*/
deviceOwnerId?: string;
+ /**
+ * The Agent stays quiet here: nothing reaches it unless a person @mentions it, and it cannot
+ * post on its own. Kept beside the environment and reply strategy, never part of execution.
+ */
+ muted?: boolean;
/**
* This member's own reply strategy, over the channel's `ChannelConfig.wake`. Parsed by the
* shared wake schema; never part of the execution environment.
@@ -530,6 +535,8 @@ export interface ChannelPublicMember {
description: string | null;
id: string;
joinedAt: Date;
+ /** An Agent that answers only when @mentioned; see `ChannelMemberConfig.muted`. */
+ muted?: boolean;
name: string | null;
role: ChannelMemberRole | null;
status: ChannelMemberStatus;