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): send every message straight to the only Agent of a one-person group (#21927)

AmAzing-32d7c21abde6
diff --git a/apps/server/src/services/channel/README.md b/apps/server/src/services/channel/README.md
index 6764b9ccabf..ba9e2e79bd4 100644
--- a/apps/server/src/services/channel/README.md
+++ b/apps/server/src/services/channel/README.md
@@ -1,8 +1,10 @@
# Channel responder routing
Unmentioned group messages can use a decision model to choose Agent **members**, not replace
-their configured reply models or runtimes. Explicit mentions and bound direct conversations
-still bypass classification. Agent replies never trigger another classification.
+their configured reply models or runtimes. Explicit mentions, bound direct conversations and
+groups whose only active members are one person and one Agent still bypass classification; in
+the latter, every message from that person, including Thread replies, goes to the Agent. Agent
+replies never trigger another classification.
## Enable
diff --git a/packages/database/src/repositories/channel/README.md b/packages/database/src/repositories/channel/README.md
index 4752b89ddc7..70e752b8a68 100644
--- a/packages/database/src/repositories/channel/README.md
+++ b/packages/database/src/repositories/channel/README.md
@@ -31,7 +31,9 @@ is part of the key because a transferred Agent starts a new conversation in its
Only that human participant can access it, even if another
membership is accidentally granted. It accepts no additional Agent members and routes unmentioned
messages directly to the bound Agent. Group channels leave `agentId` NULL, including groups with
-only one Agent. Deleting a bound Agent cascades its direct conversations and their public history.
+only one Agent. A group whose only active members are one person and one Agent also skips routing:
+every message that mentions no Agent, in the main timeline or any Thread, goes to that Agent,
+which then follows the Thread. Deleting a bound Agent cascades its direct conversations and their public history.
Group history survives deletion of an author or Agent. Message sender references use `SET NULL`;
new writes require exactly one actual sender. Human requests have `userId`, Agent replies have
diff --git a/packages/database/src/repositories/channel/__tests__/pairedSend.test.ts b/packages/database/src/repositories/channel/__tests__/pairedSend.test.ts
new file mode 100644
index 00000000000..f603708fb4b
--- /dev/null
+++ b/packages/database/src/repositories/channel/__tests__/pairedSend.test.ts
@@ -0,0 +1,110 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { channelThreads } 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-paired-send');
+
+beforeEach(fixture.setup);
+afterEach(fixture.cleanup);
+
+/** A workspace group with only its owner as a person. */
+const createPairedChannel = async () => {
+ const asOwner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);
+ const { channel, member: owner } = await asOwner.create({ title: 'Pair' });
+ return { asOwner, channel, owner };
+};
+
+describe('ChannelRepository.send with one person and one Agent', () => {
+ it('sends an unmentioned main-channel message straight to the Agent without a decision', async () => {
+ const { asOwner, channel, owner } = await createPairedChannel();
+ const agent = await fixture.addAgent(channel.id, 'Coder');
+
+ const message = await asOwner.send(channel.id, {
+ content: 'Anyone?',
+ requestKey: 'req-1',
+ routing: 'decision',
+ });
+
+ expect(message).toMatchObject({
+ recipientMemberIds: [agent.id],
+ routingAttempt: 0,
+ routingSource: 'explicit',
+ routingStatus: 'directed',
+ });
+ expect(await jobsOf(db, message.id)).toEqual([
+ expect.objectContaining({ memberId: agent.id, requesterMemberId: owner.id }),
+ ]);
+ });
+
+ it('wakes the Agent even when the message mentions only the person', async () => {
+ const { asOwner, channel, owner } = await createPairedChannel();
+ const agent = await fixture.addAgent(channel.id, 'Coder');
+
+ const message = await asOwner.send(channel.id, {
+ content: 'Note to self',
+ mentions: [owner.id],
+ requestKey: 'req-1',
+ routing: 'decision',
+ });
+
+ expect(message).toMatchObject({ recipientMemberIds: [agent.id], routingStatus: 'directed' });
+ expect(await jobsOf(db, message.id)).toHaveLength(1);
+ });
+
+ it('answers in a Thread the Agent did not follow, and makes it a follower', async () => {
+ const { asOwner, channel } = await createPairedChannel();
+ // Sent before the Agent joined, so the branch starts without any followers.
+ const root = await asOwner.send(channel.id, {
+ content: 'Root',
+ requestKey: 'root',
+ routing: 'decision',
+ });
+ expect(root.routingStatus).toBe('skipped');
+ const agent = await fixture.addAgent(channel.id, 'Coder');
+
+ const reply = await asOwner.send(channel.id, {
+ content: 'Continue here',
+ requestKey: 'thread-1',
+ rootMessageId: root.id,
+ routing: 'decision',
+ });
+
+ expect(reply).toMatchObject({ recipientMemberIds: [agent.id], routingStatus: 'directed' });
+ expect(await jobsOf(db, reply.id)).toEqual([
+ expect.objectContaining({ memberId: agent.id, threadId: reply.threadId }),
+ ]);
+ const [thread] = await db
+ .select()
+ .from(channelThreads)
+ .where(eq(channelThreads.id, reply.threadId!));
+ expect(thread.followerMemberIds).toEqual([agent.id]);
+ });
+
+ it('keeps routing once a second person or Agent joins', async () => {
+ const { asOwner, channel } = await createPairedChannel();
+ await fixture.addAgent(channel.id, 'Coder');
+ await fixture.addAgent(channel.id, 'Reviewer');
+ const twoAgents = await asOwner.send(channel.id, {
+ content: 'Anyone?',
+ requestKey: 'req-1',
+ routing: 'decision',
+ });
+ expect(twoAgents).toMatchObject({ recipientMemberIds: [], routingStatus: 'pending' });
+
+ const team = await fixture.createTeamChannel('Team');
+ await fixture.addAgent(team.channel.id, 'Coder');
+ const twoPeople = await team.asOwner.send(team.channel.id, {
+ content: 'Anyone?',
+ requestKey: 'req-1',
+ routing: 'decision',
+ });
+ expect(twoPeople).toMatchObject({ recipientMemberIds: [], routingStatus: 'pending' });
+ });
+});
diff --git a/packages/database/src/repositories/channel/delivery.ts b/packages/database/src/repositories/channel/delivery.ts
index 8410954c5e7..ad15e591bcd 100644
--- a/packages/database/src/repositories/channel/delivery.ts
+++ b/packages/database/src/repositories/channel/delivery.ts
@@ -94,6 +94,23 @@ export const candidateAgents = async (
return thread ? agents.filter((agent) => thread.followerMemberIds.includes(agent.id)) : agents;
};
+/**
+ * The only Agent of a group with exactly one active person and one active Agent. Such a
+ * group needs no responder decision: every message the person sends goes to this Agent.
+ */
+export const pairedAgent = async (
+ tx: Transaction,
+ channelId: string,
+): Promise<ChannelMemberItem | undefined> => {
+ const members = await tx
+ .select()
+ .from(channelMembers)
+ .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;
+};
+
/**
* Queues one job per Agent. Idempotent through the delivery key. Skips Agents whose
* environment changed after the message, so a late route cannot run an old instruction
diff --git a/packages/database/src/repositories/channel/send.ts b/packages/database/src/repositories/channel/send.ts
index ad369fb23ac..5ad1678bce1 100644
--- a/packages/database/src/repositories/channel/send.ts
+++ b/packages/database/src/repositories/channel/send.ts
@@ -15,6 +15,7 @@ import {
candidateAgents,
deliver,
findThread,
+ pairedAgent,
} from './delivery';
import { ChannelError } from './error';
import { audit } from './transaction';
@@ -64,6 +65,8 @@ export const validateSendInput = (input: ChannelSendInput) => {
* - @mentioning only people wakes no Agent.
* - Without mentions, `decision` leaves the message `pending` for the routing task, and
* `fallback` hands it to every candidate Agent at once.
+ * - A group with one person and one Agent skips routing: any message that mentions no
+ * Agent, in the main channel or a Thread, goes straight to that Agent.
*/
export const sendMessage = async (
tx: Transaction,
@@ -124,19 +127,24 @@ export const sendMessage = async (
const mentioned = await activeMembers(tx, channel.id, mentions);
const mentionedAgents = mentioned.filter((target) => target.actorType === 'agent');
- if (thread && mentioned.length) {
+ const paired =
+ channel.agentId || mentionedAgents.length ? undefined : await pairedAgent(tx, channel.id);
+ // The paired Agent follows the Thread it answers, like a mentioned one.
+ const followers = [...mentions, ...(thread && paired ? [paired.id] : [])];
+ if (thread && followers.some((id) => !thread.followerMemberIds.includes(id))) {
await tx
.update(channelThreads)
- .set({ followerMemberIds: [...new Set([...thread.followerMemberIds, ...mentions])] })
+ .set({ followerMemberIds: [...new Set([...thread.followerMemberIds, ...followers])] })
.where(eq(channelThreads.id, thread.id));
}
- const candidates = mentions.length
- ? []
- : await candidateAgents(tx, channel.id, channel.agentId ? null : thread);
+ const candidates =
+ paired || mentions.length
+ ? []
+ : await candidateAgents(tx, channel.id, channel.agentId ? null : thread);
const direct = !!channel.agentId && candidates.length > 0;
const [pendingRoot] =
- thread && !mentions.length && !direct
+ thread && !paired && !mentions.length && !direct
? await tx
.select({ id: channelMessages.id })
.from(channelMessages)
@@ -147,30 +155,34 @@ export const sendMessage = async (
),
)
: [];
- const routed = mentions.length
- ? ({ reason: 'Mentioned', source: 'explicit', status: 'directed' } as const)
- : pendingRoot
- ? {
- reason: 'Waiting for the root message routing decision',
- source: input.routing === 'fallback' ? ('fallback' as const) : null,
- status: 'pending' as const,
- }
- : !candidates.length
- ? ({ reason: 'No Agent can answer here', source: null, status: 'skipped' } as const)
- : direct
- ? ({ reason: 'Direct conversation', source: 'explicit', status: 'directed' } as const)
- : input.routing === 'decision'
- ? ({ reason: null, source: null, status: 'pending' } as const)
- : ({
- reason: 'No decision model configured',
- source: 'fallback',
- status: 'assigned',
- } as const);
- const recipients = mentions.length
- ? mentionedAgents
- : direct || routed.status === 'assigned'
- ? candidates
- : [];
+ const routed = paired
+ ? ({ reason: 'Only Agent in the Channel', source: 'explicit', status: 'directed' } as const)
+ : mentions.length
+ ? ({ reason: 'Mentioned', source: 'explicit', status: 'directed' } as const)
+ : pendingRoot
+ ? {
+ reason: 'Waiting for the root message routing decision',
+ source: input.routing === 'fallback' ? ('fallback' as const) : null,
+ status: 'pending' as const,
+ }
+ : !candidates.length
+ ? ({ reason: 'No Agent can answer here', source: null, status: 'skipped' } as const)
+ : direct
+ ? ({ reason: 'Direct conversation', source: 'explicit', status: 'directed' } as const)
+ : input.routing === 'decision'
+ ? ({ reason: null, source: null, status: 'pending' } as const)
+ : ({
+ reason: 'No decision model configured',
+ source: 'fallback',
+ status: 'assigned',
+ } as const);
+ const recipients = paired
+ ? [paired]
+ : mentions.length
+ ? mentionedAgents
+ : direct || routed.status === 'assigned'
+ ? candidates
+ : [];
const message = await appendMessage(tx, {
userId: member.userId,